fix(auth): invite validation keeps expires_at null on the wire; password transaction scopes and reset-token burn pinned

This commit is contained in:
jubnl
2026-09-23 00:00:32 +02:00
parent 8610a67bb9
commit 8b815891f5
5 changed files with 164 additions and 32 deletions
+7 -2
View File
@@ -425,12 +425,17 @@ export class AuthService {
return { token, user: { ...safe, avatar_url: avatarUrl(user) } };
}
async validateInviteToken(token: string): Promise<{ error?: string; status?: number; valid?: boolean; max_uses?: number; used_count?: number; expires_at?: string }> {
async validateInviteToken(token: string): Promise<{ error?: string; status?: number; valid?: boolean; max_uses?: number; used_count?: number; expires_at?: string | null }> {
const invite = await this.inviteTokens.findByToken(token);
if (!invite) return { error: 'Invalid invite link', status: 404 };
if (invite.max_uses > 0 && invite.used_count >= invite.max_uses) return { error: 'Invite link has been fully used', status: 410 };
if (invite.expires_at && new Date(invite.expires_at) < new Date()) return { error: 'Invite link has expired', status: 410 };
return { valid: true, max_uses: invite.max_uses, used_count: invite.used_count, expires_at: invite.expires_at ?? undefined };
// Rule 16 (nullable columns stay null on the wire, docs/superpowers/plans/
// 2026-09-21-orm-migration-program.md:45; task-5-review-security.md F1 /
// task-5-review-template.md T1): pass the repository's `string | null`
// through unchanged — `?? undefined` made JSON.stringify drop the key
// entirely for a never-expiring invite instead of emitting `null`.
return { valid: true, max_uses: invite.max_uses, used_count: invite.used_count, expires_at: invite.expires_at };
}
async registerUser(rawBody: unknown): Promise<{ error?: string; status?: number; token?: string; user?: Record<string, unknown>; auditUserId?: number; auditDetails?: Record<string, unknown> }> {
+10 -9
View File
@@ -43,21 +43,22 @@ export class UserCleanupService {
* Best-effort per table so a slimmed-down schema (some tests) can't fail the user
* deletion itself.
*
* UC1–UC3 (`plugin_user_config`/`plugin_oauth_tokens`/`plugin_oauth_state`/
* `plugins`/`plugin_user_erasure_queue`) stay raw `DatabaseService` calls —
* every one of these tables is owned by `nest/plugins`, which lands in
* Plan 3j, not this plan (Plan 3b Task 5 ruling; inventory §6 "the single
* largest 'stays raw' carve-out in Plan 3b"). Only `DELETE FROM users`
* below (UC11) is this domain's own and converts.
* UC1 (`plugin_user_config`/`plugin_oauth_tokens`/`plugin_oauth_state`),
* UC2 (`plugins`) and UC3 (`plugin_user_erasure_queue`) stay raw
* `DatabaseService` calls — every one of these tables is owned by
* `nest/plugins`, which lands in Plan 3j, not this plan (Plan 3b Task 5
* ruling; inventory §6 "the single largest 'stays raw' carve-out in Plan
* 3b"). Only `DELETE FROM users` below (UC11) is this domain's own and
* converts.
*/
async erasePluginUserData(userId: number): Promise<void> {
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
try { this.db.run(`DELETE FROM ${table} WHERE user_id = ?`, userId); } catch { /* table absent (slim schema) */ }
try { this.db.run(`DELETE FROM ${table} WHERE user_id = ?`, userId); } catch { /* table absent (slim schema) */ } // UC1 — Plan 3j
}
try {
const rows = this.db.all<{ id: string; permissions: string | null }>('SELECT id, permissions FROM plugins');
const rows = this.db.all<{ id: string; permissions: string | null }>('SELECT id, permissions FROM plugins'); // UC2 — Plan 3j
const installed = new Set(rows.map((r) => r.id));
const insert = this.db.prepare('INSERT OR IGNORE INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES (?, ?)');
const insert = this.db.prepare('INSERT OR IGNORE INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES (?, ?)'); // UC3 — Plan 3j
for (const r of rows) {
let perms: unknown;
try { perms = JSON.parse(r.permissions ?? '[]'); } catch { perms = []; }
+12
View File
@@ -195,6 +195,18 @@ describe('Registration', () => {
expect(res.status).toBe(410);
expect(res.body.error).toMatch(/fully used/i);
});
it('AUTH-013 — GET /api/auth/invite/:token for a never-expiring invite keeps expires_at present and null on the wire (rule 16, task-5-review F1/T1)', async () => {
const { user: admin } = createAdmin(testDb);
const invite = createInviteToken(testDb, { max_uses: 3, created_by: admin.id });
testDb.prepare('UPDATE invite_tokens SET used_count = 1 WHERE id = ?').run(invite.id);
const res = await request(app).get(`/api/auth/invite/${invite.token}`);
expect(res.status).toBe(200);
// toEqual cannot see a dropped key (undefined and missing compare equal),
// so this asserts on the raw response text, byte for byte.
expect(res.text).toBe(JSON.stringify({ valid: true, max_uses: 3, used_count: 1, expires_at: null }));
});
});
// ─────────────────────────────────────────────────────────────────────────────
@@ -150,21 +150,27 @@ describe('PasswordResetTokensRepository', () => {
// default). This repository has only ONE entity-hydrating read method
// (`findByTokenHash`) — unlike `McpTokensRepository`/`Users.repository.ts`,
// which each have two differently-projected NAMED read methods to
// combine. PWDRESETREPO-010/011 are the structural + behavioural proof
// that the real call shape (`findByTokenHash` then `markConsumed`/
// `consumeAllLiveForUser` inside the same `uow.transactional`) is safe.
// combine. PWDRESETREPO-010 is the structural proof (no managed entity
// left behind); PWDRESETREPO-011 pins the REAL call shape (`findByTokenHash`
// then `markConsumed` inside the same `uow.transactional`) as safe under
// the shipped default, but — by construction — it CANNOT fail: a single
// managed read re-snapshots every field it names, so nothing is dirty at
// the closing flush regardless of whether the mechanism exists on this
// table. It is not, on its own, proof the B1 stale-write-back mechanism
// (`task-1-review.md` B1) is absent here.
//
// An attempted third test forcing `disableIdentityMap: false` on two raw
// `find`/`findOne` calls with disjoint field sets (mirroring
// `McpTokensRepository`'s `MCPTOKREPO-023` reproduction) was tried here
// and did NOT reproduce the stale write-back on this table — the
// `nativeUpdate` survived the closing flush both times, the same "safe"
// outcome as the class-default path. Per `task-1-rereview.md` F-R5, this
// mechanism is sensitive to exactly which methods/entities exercise it;
// not reproducing it for a single-read-method repository is an honest
// finding (same precedent as Task 2's report: "the implementer could not
// reproduce the write-back within nativeUpdate-only shapes"), not a gap
// in these two tests' coverage of the real code path.
// Task 5's original report tried a THIRD test — two raw `find`/`findOne`
// calls with disjoint field sets, `disableIdentityMap: false` — and did
// not reproduce it. `task-5-review-template.md` T2 found that attempt used
// the ordering `task-4-review.md` F1 already showed is non-load-bearing
// (narrower projection first). The mechanism DOES reproduce on this table
// once the WIDER projection — the one carrying the written column,
// `consumed_at` — runs FIRST: PWDRESETREPO-012 pairs this repository's own
// read (projection A, wide) with a narrower **managed** `em.findOne`
// (projection B) and is mutation-proved (green here, red once
// `findByTokenHash` is forced to `disableIdentityMap: false, refresh:
// true` — see the fix report). PWDRESETREPO-013 repeats the shape for
// `consumeAllLiveForUser`, the repository's other write method.
// ---------------------------------------------------------------------
describe('identity-map isolation', () => {
@@ -177,7 +183,7 @@ describe('PasswordResetTokensRepository', () => {
expect(t.em.getUnitOfWork().getById(PasswordResetTokens, id)).toBeUndefined();
});
it('PWDRESETREPO-011: findByTokenHash then markConsumed inside uow.transactional survives the closing flush', async () => {
it('PWDRESETREPO-011: findByTokenHash then markConsumed inside uow.transactional survives the closing flush (cannot fail by construction — see PWDRESETREPO-012 for the mutation-proved guard)', async () => {
const { user } = createUser(testDb);
const id = seedToken(user.id, hash('survives'));
const uow = new UnitOfWork(t.em);
@@ -190,5 +196,33 @@ describe('PasswordResetTokensRepository', () => {
expect(rawRow(id).consumed_at).not.toBeNull();
});
it('PWDRESETREPO-012: findByTokenHash is the FIRST, wider read (it carries consumed_at); a narrower managed read follows; markConsumed still lands', async () => {
const { user } = createUser(testDb);
const id = seedToken(user.id, hash('dshape'));
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
await tokens.findByTokenHash(hash('dshape')); // projection A — WIDE (carries consumed_at)
await t.em.findOne(PasswordResetTokens, { id }, { fields: ['id', 'token_hash'], refresh: true, disableIdentityMap: false }); // projection B — NARROW, managed
await tokens.markConsumed(id);
});
expect(rawRow(id).consumed_at).not.toBeNull();
});
it('PWDRESETREPO-013: same D-shape guard for consumeAllLiveForUser', async () => {
const { user } = createUser(testDb);
const id = seedToken(user.id, hash('dshape-consume-all'));
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
await tokens.findByTokenHash(hash('dshape-consume-all')); // projection A — WIDE (carries consumed_at)
await t.em.findOne(PasswordResetTokens, { id }, { fields: ['id', 'token_hash'], refresh: true, disableIdentityMap: false }); // projection B — NARROW, managed
await tokens.consumeAllLiveForUser(user.id);
});
expect(rawRow(id).consumed_at).not.toBeNull();
});
});
});
+86 -6
View File
@@ -164,6 +164,15 @@ describe('requestPasswordReset — OIDC/SSO accounts', () => {
expect(result.reason).toBe('issued');
expect(result.tokenForDelivery).toBeTruthy();
});
it('AUTH-DB-PR3: a second request burns the prior live token — exactly one stays live (AU37, F3 task-5-review-security.md)', async () => {
const { user } = createUser(testDb);
await svc.requestPasswordReset(user.email, null);
await svc.requestPasswordReset(user.email, null);
const { n } = testDb.prepare('SELECT COUNT(*) AS n FROM password_reset_tokens WHERE user_id = ? AND consumed_at IS NULL')
.get(user.id) as { n: number };
expect(n).toBe(1);
});
});
// ---------------------------------------------------------------------------
@@ -511,6 +520,24 @@ describe('changePassword — session invalidation', () => {
expect(decoded.remember).toBe(true);
expect(decoded.exp - decoded.iat).toBe(2592000); // remember window survives the change
});
it('AUTH-DB-036e: the block is atomic — a failing mcp_tokens prune rolls the whole password change back (F2, task-5-review-security.md, USER-CLEANUP-009 pattern)', async () => {
const { user, password } = createUser(testDb);
await tokens.createMcpToken(user.id, 'cli');
const hashBefore = (testDb.prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as { password_hash: string }).password_hash;
const mcpTokensRepo = await createTestMcpTokensRepo(testDb);
const deleteAllForUserSpy = vi.spyOn(mcpTokensRepo, 'deleteAllForUser').mockRejectedValueOnce(new Error('boom'));
try {
await expect(svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' })).rejects.toThrow('boom');
expect(pvOf(user.id)).toBe(0); // password_version unchanged
expect((testDb.prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as { password_hash: string }).password_hash).toBe(hashBefore); // old hash unchanged
expect(mcpCount(user.id)).toBe(1); // the mcp_tokens row survives — the DELETE never committed
} finally {
deleteAllForUserSpy.mockRestore();
}
});
});
// ---------------------------------------------------------------------------
@@ -769,6 +796,17 @@ describe('loginUser — credential branches', () => {
expect(row.last_login).not.toBeNull();
});
it('AUTH-DB-062b: forwards the caller\'s remember choice into the minted token (T4, task-5-review-template.md; unit-level pin, not only the e2e)', async () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const { user, password } = createUser(testDb);
const result = await svc.loginUser({ email: user.email, password, remember_me: true });
expect(typeof result.token).toBe('string');
const decoded = jwt.decode(result.token!) as { remember?: boolean; iat: number; exp: number };
expect(decoded.remember).toBe(true);
expect(decoded.exp - decoded.iat).toBe(2592000);
});
it('AUTH-DB-063: an MFA-enabled account gets the interstitial mfa_token instead of a session', async () => {
const { user } = createUser(testDb);
testDb.prepare("UPDATE users SET mfa_enabled = 1, mfa_secret = 'enc:JBSWY3DPEHPK3PXP' WHERE id = ?").run(user.id);
@@ -907,13 +945,16 @@ describe('MFA success flows', () => {
const secret = authenticator.generateSecret();
const codes = ['AAAA-1111', 'BBBB-2222'];
// hashBackupCode (legacy SHA-256) hashes still verify via matchBackupCode.
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ?, mfa_backup_codes = ? WHERE id = ?')
.run('enc:' + secret, JSON.stringify(codes.map(hashBackupCode)), user.id);
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ?, mfa_backup_codes = ?, updated_at = ? WHERE id = ?')
.run('enc:' + secret, JSON.stringify(codes.map(hashBackupCode)), '2000-01-01T00:00:00.000Z', user.id);
const interstitial = await svc.loginUser({ email: user.email, password });
const result = await svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: 'AAAA-1111' });
expect(typeof result.token).toBe('string');
const row = testDb.prepare('SELECT mfa_backup_codes FROM users WHERE id = ?').get(user.id) as { mfa_backup_codes: string };
const row = testDb.prepare('SELECT mfa_backup_codes, updated_at FROM users WHERE id = ?').get(user.id) as { mfa_backup_codes: string; updated_at: string };
expect(JSON.parse(row.mfa_backup_codes)).toHaveLength(1); // used code spliced out
// AU33 (setBackupCodesAndTouch, F3 task-5-review-security.md): the backup-code
// login branch DOES stamp updated_at, unlike resetPassword's AU44 below.
expect(row.updated_at).not.toBe('2000-01-01T00:00:00.000Z');
// the spent code no longer verifies
const again = await svc.loginUser({ email: user.email, password });
expect((await svc.verifyMfaLogin({ mfa_token: again.mfa_token, code: 'AAAA-1111' })).status).toBe(401);
@@ -959,13 +1000,52 @@ describe('resetPassword', () => {
// wrong code → 401
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: '000000' }))
.toEqual({ error: 'Invalid MFA code', status: 401 });
// backup code → success + code consumed
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: 'CCCC-3333' }))
.toEqual({ success: true, userId: user.id });
// AU44 vs AU33 (F3, task-5-review-security.md): resetPassword's backup-code
// splice must call the untouched setBackupCodes (AU44), never
// setBackupCodesAndTouch (AU33, verifyMfaLogin's own branch, AUTH-DB-081) —
// the same transaction's own setPassword call (AU43) already stamps
// updated_at, so a raw before/after read on the row can't isolate AU44's
// no-touch behaviour here (that's USERSREPO-034, at the repository level);
// the call site is what's unlocked, so this pins the call site directly.
const usersRepo = await createTestUsersRepo(testDb);
const setBackupCodesSpy = vi.spyOn(usersRepo, 'setBackupCodes');
const setBackupCodesAndTouchSpy = vi.spyOn(usersRepo, 'setBackupCodesAndTouch');
try {
// backup code → success + code consumed
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: 'CCCC-3333' }))
.toEqual({ success: true, userId: user.id });
expect(setBackupCodesSpy).toHaveBeenCalledTimes(1);
expect(setBackupCodesAndTouchSpy).not.toHaveBeenCalled();
} finally {
setBackupCodesSpy.mockRestore();
setBackupCodesAndTouchSpy.mockRestore();
}
const row = testDb.prepare('SELECT mfa_backup_codes FROM users WHERE id = ?').get(user.id) as { mfa_backup_codes: string };
expect(JSON.parse(row.mfa_backup_codes)).toHaveLength(0);
});
it('AUTH-DB-084b: the block is atomic — a failing mcp_tokens prune rolls the whole reset-password block back (F2, task-5-review-security.md, USER-CLEANUP-009 pattern)', async () => {
const { user } = createUser(testDb);
const issued = await svc.requestPasswordReset(user.email, null);
const hashBefore = (testDb.prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as { password_hash: string }).password_hash;
const mcpTokensRepo = await createTestMcpTokensRepo(testDb);
const deleteAllForUserSpy = vi.spyOn(mcpTokensRepo, 'deleteAllForUser').mockRejectedValueOnce(new Error('boom'));
try {
await expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' })).rejects.toThrow('boom');
const row = testDb.prepare('SELECT password_hash, password_version FROM users WHERE id = ?').get(user.id) as { password_hash: string; password_version: number };
expect(row.password_hash).toBe(hashBefore); // old hash unchanged
expect(row.password_version).toBe(0);
const tokenRow = testDb.prepare('SELECT consumed_at FROM password_reset_tokens WHERE user_id = ?').get(user.id) as { consumed_at: string | null };
expect(tokenRow.consumed_at).toBeNull(); // the reset token was never committed as consumed
} finally {
deleteAllForUserSpy.mockRestore();
}
});
it('AUTH-DB-085: password-login-disabled and per-email throttle short-circuit the request', async () => {
vi.stubEnv('OIDC_ONLY', 'true');
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');