Skip to content

Commit 15f26c5

Browse files
Add TOTP two-factor, recovery codes, and session management
Two-factor (Google Authenticator-compatible): - Hand-rolled RFC 6238 TOTP (SHA-1, 30s, 6 digits) on node:crypto, verified against the RFC test vectors (9 unit tests). No third-party auth dependency. - Setup flow stores a pending secret, returns an otpauth URI + QR data URL, and only enables 2FA after the user proves a valid code. - Ten one-time recovery codes (SHA-256 hashed) issued on enable; regenerate and disable both require the password. Login accepts a TOTP code or a recovery code. Sessions: - Sessions now record login IP, user-agent and a throttled rolling last-seen. - GET /auth/sessions lists active sessions (current one flagged); DELETE one or all-others to revoke. Surfaced on a new Account page. Web: - Login gains a second step for the 2FA code; Account page for 2FA setup (QR + recovery codes) and session review/revocation. De-emojified prominent headers. Tests: 2 integration tests (2FA required + recovery-code consumption; session list + revoke). Suite now 27 API tests. Checklist updated.
1 parent 0c75f31 commit 15f26c5

20 files changed

Lines changed: 1015 additions & 16 deletions

File tree

‎TEST-CHECKLIST.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,23 @@ then copies the link. Manage them under the **Shares** tab.
6161
- [ ] **Revoke**: revoking in the Shares tab makes the link 404 immediately.
6262
- [ ] **ZK guard**: a vault file/folder cannot be shared (the Share action errors).
6363

64+
## Two-factor auth, recovery codes & sessions (lot 2)
65+
66+
Account security lives under your email (top-right) → **Account**.
67+
68+
- [ ] **Enable 2FA**: Account → Enable two-factor → scan the QR with Google Authenticator
69+
(or enter the secret manually) → enter the 6-digit code → 10 recovery codes are shown
70+
once. Save them.
71+
- [ ] **Login with 2FA**: sign out, sign in → after the password you are asked for the
72+
6-digit code; a wrong code is refused, the right one logs you in.
73+
- [ ] **Recovery code**: at the 2FA prompt, enter one of the saved recovery codes instead;
74+
it works once and is then consumed (reusing it fails).
75+
- [ ] **Regenerate recovery codes**: Account → Regenerate (password required) issues a new
76+
set and invalidates the old.
77+
- [ ] **Disable 2FA**: Account → Disable (password required); login no longer asks for a code.
78+
- [ ] **Sessions**: Account → Active sessions lists each session with IP, device and last-seen,
79+
marking the current one. Sign in from another browser → it appears in the list.
80+
- [ ] **Revoke session**: revoke another session → it is signed out (its next request fails).
81+
- [ ] **Sign out others**: "Sign out other sessions" keeps only the current device.
82+
6483
<!-- New features are appended below as they are built. -->

‎apps/api/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,12 @@
3131
"fastify": "^5.2.0",
3232
"fastify-plugin": "^5.0.1",
3333
"pino": "^9.5.0",
34+
"qrcode": "^1.5.4",
3435
"zod": "^3.24.1"
3536
},
3637
"devDependencies": {
3738
"@types/node": "^22.10.2",
39+
"@types/qrcode": "^1.5.5",
3840
"form-data": "^4.0.1",
3941
"pino-pretty": "^13.0.0",
4042
"prisma": "^6.1.0",
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-- AlterTable
2+
ALTER TABLE "Session" ADD COLUMN "ip" TEXT,
3+
ADD COLUMN "lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
4+
ADD COLUMN "userAgent" TEXT;
5+
6+
-- AlterTable
7+
ALTER TABLE "User" ADD COLUMN "totpEnabled" BOOLEAN NOT NULL DEFAULT false,
8+
ADD COLUMN "totpSecret" TEXT;
9+
10+
-- CreateTable
11+
CREATE TABLE "RecoveryCode" (
12+
"id" TEXT NOT NULL,
13+
"userId" TEXT NOT NULL,
14+
"codeHash" TEXT NOT NULL,
15+
"usedAt" TIMESTAMP(3),
16+
17+
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
18+
);
19+
20+
-- CreateIndex
21+
CREATE INDEX "RecoveryCode_userId_idx" ON "RecoveryCode"("userId");
22+
23+
-- AddForeignKey
24+
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

‎apps/api/prisma/schema.prisma‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ model User {
5555
// denormalised running total of bytes the user stores, kept in sync on upload/delete
5656
usedBytes BigInt @default(0)
5757
disabled Boolean @default(false)
58+
// Two-factor (TOTP). `totpSecret` is also used as the pending secret during setup.
59+
totpSecret String?
60+
totpEnabled Boolean @default(false)
5861
createdAt DateTime @default(now())
5962
updatedAt DateTime @updatedAt
6063
@@ -65,16 +68,32 @@ model User {
6568
remoteJobs RemoteUploadJob[]
6669
auditLogs AuditLog[]
6770
shares ShareLink[]
71+
recoveryCodes RecoveryCode[]
6872
6973
@@index([email])
7074
}
7175

76+
// One-time 2FA recovery codes, stored as SHA-256 hashes.
77+
model RecoveryCode {
78+
id String @id @default(cuid())
79+
userId String
80+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
81+
codeHash String
82+
usedAt DateTime?
83+
84+
@@index([userId])
85+
}
86+
7287
model Session {
7388
id String @id @default(cuid())
7489
userId String
7590
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
7691
// per-session secret used to derive the double-submit CSRF token
7792
csrfSecret String
93+
// captured at login so the user can review where they are signed in
94+
ip String?
95+
userAgent String?
96+
lastSeenAt DateTime @default(now())
7897
expiresAt DateTime
7998
createdAt DateTime @default(now())
8099

‎apps/api/src/plugins/auth.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify';
1010
import fp from 'fastify-plugin';
1111
import { CSRF_HEADER, SESSION_COOKIE, safeEqual } from '@opencoperlock/shared';
12-
import { getSession } from '../services/session.js';
12+
import { getSession, touchSession } from '../services/session.js';
1313

1414
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
1515

@@ -27,6 +27,8 @@ const authPlugin: FastifyPluginAsync = async (app) => {
2727
if (!session) return;
2828
req.user = session.user;
2929
req.sessionData = { id: session.id, csrfSecret: session.csrfSecret };
30+
// Rolling "last seen" for the session-management view (throttled internally).
31+
void touchSession(session.id, session.lastSeenAt);
3032
});
3133

3234
function enforceCsrf(req: FastifyRequest, reply: FastifyReply): boolean {

‎apps/api/src/routes/auth.ts‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { parseOr400 } from '../lib/validate.js';
55
import { verifyPassword } from '../services/password.js';
66
import { createSession, destroySession } from '../services/session.js';
77
import { checkLock, clearFailures, recordFailure } from '../services/throttle.js';
8+
import { verifyTotp } from '../services/totp.js';
9+
import { consumeRecoveryCode } from '../services/recovery.js';
810
import { setSessionCookie, clearSessionCookie } from '../lib/cookies.js';
911
import { toPublicUser } from '../lib/serialize.js';
1012
import { audit } from '../services/audit.js';
@@ -41,8 +43,26 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
4143
return reply.code(401).send({ error: 'Invalid credentials' });
4244
}
4345

46+
// Second factor, when enabled: accept a 6-digit TOTP or a one-time recovery code.
47+
if (user.totpEnabled) {
48+
if (!body.totp) {
49+
return reply.code(401).send({ error: 'Two-factor code required', code: 'TOTP_REQUIRED' });
50+
}
51+
const totpOk = user.totpSecret ? verifyTotp(user.totpSecret, body.totp) : false;
52+
const recoveryOk = totpOk ? false : await consumeRecoveryCode(user.id, body.totp);
53+
if (!totpOk && !recoveryOk) {
54+
const after = await recordFailure('login', body.email, LOGIN_THROTTLE);
55+
await audit(req, 'auth.login.2fa_failed', { actorId: user.id });
56+
if (after.locked) reply.header('Retry-After', String(after.retryAfterSec));
57+
return reply.code(401).send({ error: 'Invalid two-factor code', code: 'TOTP_INVALID' });
58+
}
59+
}
60+
4461
await clearFailures('login', body.email);
45-
const session = await createSession(user.id);
62+
const session = await createSession(user.id, {
63+
ip: req.ip,
64+
userAgent: req.headers['user-agent'] ?? null,
65+
});
4666
setSessionCookie(reply, session.id, session.expiresAt, secureCookies);
4767
await audit(req, 'auth.login', { actorId: user.id });
4868
return { user: toPublicUser(user), csrfToken: session.csrfSecret };
@@ -60,6 +80,47 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
6080
if (!req.user || !req.sessionData) return reply.code(401).send({ error: 'Not authenticated' });
6181
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
6282
if (!user) return reply.code(401).send({ error: 'Not authenticated' });
63-
return { user: toPublicUser(user), csrfToken: req.sessionData.csrfSecret };
83+
return {
84+
user: toPublicUser(user),
85+
csrfToken: req.sessionData.csrfSecret,
86+
totpEnabled: user.totpEnabled,
87+
};
88+
});
89+
90+
// GET /auth/sessions — the user's active sessions, so they can spot unfamiliar ones.
91+
app.get('/sessions', { preHandler: app.requireAuth }, async (req) => {
92+
const sessions = await prisma.session.findMany({
93+
where: { userId: req.user!.id },
94+
orderBy: { lastSeenAt: 'desc' },
95+
select: { id: true, ip: true, userAgent: true, lastSeenAt: true, createdAt: true },
96+
});
97+
return {
98+
sessions: sessions.map((s) => ({
99+
id: s.id,
100+
ip: s.ip,
101+
userAgent: s.userAgent,
102+
lastSeenAt: s.lastSeenAt.toISOString(),
103+
createdAt: s.createdAt.toISOString(),
104+
current: s.id === req.sessionData!.id,
105+
})),
106+
};
107+
});
108+
109+
// DELETE /auth/sessions/:id — revoke one session (e.g. a suspicious one).
110+
app.delete('/sessions/:id', { preHandler: app.requireAuth }, async (req, reply) => {
111+
const { id } = req.params as { id: string };
112+
const res = await prisma.session.deleteMany({ where: { id, userId: req.user!.id } });
113+
if (res.count === 0) return reply.code(404).send({ error: 'Session not found' });
114+
await audit(req, 'auth.session.revoke', { target: id });
115+
return { ok: true };
116+
});
117+
118+
// DELETE /auth/sessions — revoke every other session (keep the current one).
119+
app.delete('/sessions', { preHandler: app.requireAuth }, async (req) => {
120+
const res = await prisma.session.deleteMany({
121+
where: { userId: req.user!.id, id: { not: req.sessionData!.id } },
122+
});
123+
await audit(req, 'auth.session.revoke_others');
124+
return { ok: true, revoked: res.count };
64125
});
65126
};

‎apps/api/src/routes/twofa.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/**
2+
* Two-factor (TOTP) management. The setup flow stores a *pending* secret, requires the
3+
* user to prove possession by entering a code, and only then enables 2FA and issues
4+
* one-time recovery codes. Disabling and regenerating recovery codes require the password.
5+
*/
6+
import type { FastifyPluginAsync } from 'fastify';
7+
import QRCode from 'qrcode';
8+
import { passwordConfirmSchema, totpTokenSchema } from '@opencoperlock/shared';
9+
import { prisma } from '../db.js';
10+
import { parseOr400 } from '../lib/validate.js';
11+
import { verifyPassword } from '../services/password.js';
12+
import { generateTotpSecret, totpUri, verifyTotp } from '../services/totp.js';
13+
import {
14+
clearRecoveryCodes,
15+
regenerateRecoveryCodes,
16+
remainingRecoveryCodes,
17+
} from '../services/recovery.js';
18+
import { audit } from '../services/audit.js';
19+
20+
export const twoFactorRoutes: FastifyPluginAsync = async (app) => {
21+
app.addHook('preHandler', app.requireAuth);
22+
23+
// GET /2fa/status — whether 2FA is on and how many recovery codes remain.
24+
app.get('/status', async (req) => {
25+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
26+
return {
27+
enabled: user.totpEnabled,
28+
recoveryCodesRemaining: user.totpEnabled ? await remainingRecoveryCodes(user.id) : 0,
29+
};
30+
});
31+
32+
// POST /2fa/setup — generate a pending secret + QR. Does not enable 2FA yet.
33+
app.post('/setup', async (req, reply) => {
34+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
35+
if (user.totpEnabled) {
36+
return reply.code(400).send({ error: 'Two-factor is already enabled' });
37+
}
38+
const secret = generateTotpSecret();
39+
await prisma.user.update({ where: { id: user.id }, data: { totpSecret: secret } });
40+
const uri = totpUri(secret, user.email);
41+
return { secret, otpauthUri: uri, qrDataUrl: await QRCode.toDataURL(uri) };
42+
});
43+
44+
// POST /2fa/enable — verify a code against the pending secret, then turn 2FA on and
45+
// return the one-time recovery codes (shown once).
46+
app.post('/enable', async (req, reply) => {
47+
const body = parseOr400(reply, totpTokenSchema, req.body);
48+
if (!body) return;
49+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
50+
if (user.totpEnabled) return reply.code(400).send({ error: 'Two-factor is already enabled' });
51+
if (!user.totpSecret) return reply.code(400).send({ error: 'Start setup first' });
52+
if (!verifyTotp(user.totpSecret, body.token)) {
53+
return reply.code(400).send({ error: 'Incorrect code' });
54+
}
55+
await prisma.user.update({ where: { id: user.id }, data: { totpEnabled: true } });
56+
const recoveryCodes = await regenerateRecoveryCodes(user.id);
57+
await audit(req, 'auth.2fa.enable');
58+
return { enabled: true, recoveryCodes };
59+
});
60+
61+
// POST /2fa/disable — turn 2FA off (password required), clearing secret + recovery codes.
62+
app.post('/disable', async (req, reply) => {
63+
const body = parseOr400(reply, passwordConfirmSchema, req.body);
64+
if (!body) return;
65+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
66+
if (!(await verifyPassword(user.passwordHash, body.password))) {
67+
return reply.code(401).send({ error: 'Incorrect password' });
68+
}
69+
await prisma.user.update({
70+
where: { id: user.id },
71+
data: { totpEnabled: false, totpSecret: null },
72+
});
73+
await clearRecoveryCodes(user.id);
74+
await audit(req, 'auth.2fa.disable');
75+
return { enabled: false };
76+
});
77+
78+
// POST /2fa/recovery/regenerate — issue a fresh set of recovery codes (password required).
79+
app.post('/recovery/regenerate', async (req, reply) => {
80+
const body = parseOr400(reply, passwordConfirmSchema, req.body);
81+
if (!body) return;
82+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
83+
if (!user.totpEnabled) return reply.code(400).send({ error: 'Two-factor is not enabled' });
84+
if (!(await verifyPassword(user.passwordHash, body.password))) {
85+
return reply.code(401).send({ error: 'Incorrect password' });
86+
}
87+
const recoveryCodes = await regenerateRecoveryCodes(user.id);
88+
await audit(req, 'auth.2fa.recovery_regenerate');
89+
return { recoveryCodes };
90+
});
91+
};

‎apps/api/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { quickRoutes } from './routes/quick.js';
1515
import { remoteRoutes } from './routes/remote.js';
1616
import { shareRoutes } from './routes/shares.js';
1717
import { sharePublicRoutes } from './routes/share-public.js';
18+
import { twoFactorRoutes } from './routes/twofa.js';
1819
import { adminRoutes } from './routes/admin.js';
1920

2021
export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
@@ -73,6 +74,7 @@ export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
7374
await app.register(remoteRoutes, { prefix: '/remote' });
7475
await app.register(shareRoutes, { prefix: '/shares' });
7576
await app.register(sharePublicRoutes, { prefix: '/s' });
77+
await app.register(twoFactorRoutes, { prefix: '/2fa' });
7678
await app.register(adminRoutes, { prefix: '/admin' });
7779

7880
app.setErrorHandler((err: { statusCode?: number; message?: string }, req, reply) => {

‎apps/api/src/services/recovery.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* One-time recovery codes — a fallback when an authenticator device is lost. Codes are
3+
* shown to the user exactly once and stored only as SHA-256 hashes. They are
4+
* high-entropy and single-use, and login is rate-limited/locked out, so a fast hash is
5+
* appropriate (argon2 over ten candidates per attempt would be needlessly slow).
6+
*/
7+
import { randomInt } from 'node:crypto';
8+
import { sha256Hex } from '@opencoperlock/shared';
9+
import { prisma } from '../db.js';
10+
11+
const CODE_COUNT = 10;
12+
13+
/** A 10-digit code formatted as `XXXXX-XXXXX` for readability. */
14+
function makeCode(): string {
15+
let digits = '';
16+
for (let i = 0; i < 10; i += 1) digits += randomInt(0, 10).toString();
17+
return `${digits.slice(0, 5)}-${digits.slice(5)}`;
18+
}
19+
20+
/** Normalize user input (strip spaces/dashes) before hashing/comparison. */
21+
function normalize(code: string): string {
22+
return code.replace(/[\s-]/g, '');
23+
}
24+
25+
function hash(code: string): string {
26+
return sha256Hex(normalize(code));
27+
}
28+
29+
/**
30+
* Replace a user's recovery codes with a fresh set. Returns the plaintext codes to show
31+
* once; only their hashes are persisted.
32+
*/
33+
export async function regenerateRecoveryCodes(userId: string): Promise<string[]> {
34+
const codes = Array.from({ length: CODE_COUNT }, makeCode);
35+
await prisma.$transaction([
36+
prisma.recoveryCode.deleteMany({ where: { userId } }),
37+
prisma.recoveryCode.createMany({
38+
data: codes.map((c) => ({ userId, codeHash: hash(c) })),
39+
}),
40+
]);
41+
return codes;
42+
}
43+
44+
/** Consume a recovery code if it matches an unused one. Returns true on success. */
45+
export async function consumeRecoveryCode(userId: string, code: string): Promise<boolean> {
46+
const match = await prisma.recoveryCode.findFirst({
47+
where: { userId, codeHash: hash(code), usedAt: null },
48+
});
49+
if (!match) return false;
50+
await prisma.recoveryCode.update({ where: { id: match.id }, data: { usedAt: new Date() } });
51+
return true;
52+
}
53+
54+
export async function remainingRecoveryCodes(userId: string): Promise<number> {
55+
return prisma.recoveryCode.count({ where: { userId, usedAt: null } });
56+
}
57+
58+
export async function clearRecoveryCodes(userId: string): Promise<void> {
59+
await prisma.recoveryCode.deleteMany({ where: { userId } });
60+
}

0 commit comments

Comments
 (0)