mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
refactor(auth, files): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -188,7 +188,7 @@ describe('AdminController read-only getters', () => {
|
||||
expect(adminCtl(svc({ getPermissions: vi.fn().mockReturnValue({ a: 1 }) } as Partial<AdminService>)).permissions()).toEqual({ a: 1 });
|
||||
expect(adminCtl(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
|
||||
await expect(adminCtl(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
|
||||
expect(adminCtl(svc(), undefined, undefined, {}, { listInvites: vi.fn().mockReturnValue([{ id: 1 }]) }).listInvites()).toEqual({ invites: [{ id: 1 }] });
|
||||
expect(await adminCtl(svc(), undefined, undefined, {}, { listInvites: vi.fn().mockReturnValue([{ id: 1 }]) }).listInvites()).toEqual({ invites: [{ id: 1 }] });
|
||||
expect(adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
|
||||
expect(adminCtl(svc(), undefined, undefined, { listAllMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) }).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
|
||||
expect(await adminCtl(svc(), undefined, undefined, {}, {}, { listAllOAuthSessions: vi.fn().mockResolvedValue([{ id: 1 }]) }).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
|
||||
|
||||
@@ -106,7 +106,7 @@ beforeAll(async () => {
|
||||
svc = new AdminService(
|
||||
dbs,
|
||||
new AddonsService(dbs),
|
||||
new PasskeyService(dbs, auth, webauthn),
|
||||
new PasskeyService(dbs, auth, webauthn, await createTestUnitOfWork(dbs.connection)),
|
||||
auth,
|
||||
permissions,
|
||||
await makeNotificationsService(dbs, realtime),
|
||||
|
||||
@@ -84,7 +84,7 @@ beforeAll(async () => {
|
||||
svc = new AdminService(
|
||||
dbs,
|
||||
new AddonsService(dbs),
|
||||
new PasskeyService(dbs, auth, webauthn),
|
||||
new PasskeyService(dbs, auth, webauthn, await createTestUnitOfWork(dbs.connection)),
|
||||
auth,
|
||||
permissions,
|
||||
await makeNotificationsService(dbs, realtime),
|
||||
|
||||
@@ -66,28 +66,28 @@ beforeEach(() => vi.clearAllMocks());
|
||||
describe('JwtAuthGuard', () => {
|
||||
const guard = new JwtAuthGuard();
|
||||
|
||||
it('rejects with the legacy 401 { error, code } when no token is present', () => {
|
||||
it('rejects with the legacy 401 { error, code } when no token is present', async () => {
|
||||
vi.mocked(extractToken).mockReturnValue(null);
|
||||
expect(thrown(() => guard.canActivate(context({ headers: {}, cookies: {} })))).toEqual({
|
||||
expect(await thrownAsync(() => guard.canActivate(context({ headers: {}, cookies: {} })))).toEqual({
|
||||
status: 401,
|
||||
body: { error: 'Access token required', code: 'AUTH_REQUIRED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an invalid/expired token (verify returns null)', () => {
|
||||
it('rejects an invalid/expired token (verify returns null)', async () => {
|
||||
vi.mocked(extractToken).mockReturnValue('tok');
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(null);
|
||||
expect(thrown(() => guard.canActivate(context({ headers: {} })))).toEqual({
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);
|
||||
expect(await thrownAsync(() => guard.canActivate(context({ headers: {} })))).toEqual({
|
||||
status: 401,
|
||||
body: { error: 'Invalid or expired token', code: 'AUTH_REQUIRED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('attaches the loaded user and allows a valid token through', () => {
|
||||
it('attaches the loaded user and allows a valid token through', async () => {
|
||||
const req: Record<string, unknown> = { headers: {} };
|
||||
vi.mocked(extractToken).mockReturnValue('tok');
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(user);
|
||||
expect(guard.canActivate(context(req))).toBe(true);
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(user);
|
||||
expect(await guard.canActivate(context(req))).toBe(true);
|
||||
expect(req.user).toBe(user);
|
||||
});
|
||||
});
|
||||
@@ -95,30 +95,30 @@ describe('JwtAuthGuard', () => {
|
||||
describe('CookieAuthGuard', () => {
|
||||
const guard = new CookieAuthGuard();
|
||||
|
||||
it('401s when the trek_session cookie is missing', () => {
|
||||
expect(thrown(() => guard.canActivate(context({ cookies: {} })))).toEqual({
|
||||
it('401s when the trek_session cookie is missing', async () => {
|
||||
expect(await thrownAsync(() => guard.canActivate(context({ cookies: {} })))).toEqual({
|
||||
status: 401,
|
||||
body: { error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' },
|
||||
});
|
||||
// and when there is no cookies object at all
|
||||
expect(thrown(() => guard.canActivate(context({})))).toEqual({
|
||||
expect(await thrownAsync(() => guard.canActivate(context({})))).toEqual({
|
||||
status: 401,
|
||||
body: { error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('401s when the cookie token fails verification', () => {
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(null);
|
||||
expect(thrown(() => guard.canActivate(context({ cookies: { trek_session: 'tok' } })))).toEqual({
|
||||
it('401s when the cookie token fails verification', async () => {
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);
|
||||
expect(await thrownAsync(() => guard.canActivate(context({ cookies: { trek_session: 'tok' } })))).toEqual({
|
||||
status: 401,
|
||||
body: { error: 'Invalid or expired session', code: 'AUTH_REQUIRED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('attaches the user and allows a valid cookie session through', () => {
|
||||
it('attaches the user and allows a valid cookie session through', async () => {
|
||||
const req: Record<string, unknown> = { cookies: { trek_session: 'tok' } };
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(user);
|
||||
expect(guard.canActivate(context(req))).toBe(true);
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(user);
|
||||
expect(await guard.canActivate(context(req))).toBe(true);
|
||||
expect(req.user).toBe(user);
|
||||
});
|
||||
});
|
||||
@@ -126,27 +126,27 @@ describe('CookieAuthGuard', () => {
|
||||
describe('OptionalJwtGuard', () => {
|
||||
const guard = new OptionalJwtGuard();
|
||||
|
||||
it('always allows; sets req.user to null when no token', () => {
|
||||
it('always allows; sets req.user to null when no token', async () => {
|
||||
const req: Record<string, unknown> = { headers: {} };
|
||||
vi.mocked(extractToken).mockReturnValue(null);
|
||||
expect(guard.canActivate(context(req))).toBe(true);
|
||||
expect(await guard.canActivate(context(req))).toBe(true);
|
||||
expect(req.user).toBeNull();
|
||||
expect(verifyJwtAndLoadUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sets req.user to null when a token verifies to nothing', () => {
|
||||
it('sets req.user to null when a token verifies to nothing', async () => {
|
||||
const req: Record<string, unknown> = { headers: {} };
|
||||
vi.mocked(extractToken).mockReturnValue('tok');
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(null);
|
||||
expect(guard.canActivate(context(req))).toBe(true);
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);
|
||||
expect(await guard.canActivate(context(req))).toBe(true);
|
||||
expect(req.user).toBeNull();
|
||||
});
|
||||
|
||||
it('populates req.user from a valid token', () => {
|
||||
it('populates req.user from a valid token', async () => {
|
||||
const req: Record<string, unknown> = { headers: {} };
|
||||
vi.mocked(extractToken).mockReturnValue('tok');
|
||||
vi.mocked(verifyJwtAndLoadUser).mockReturnValue(user);
|
||||
expect(guard.canActivate(context(req))).toBe(true);
|
||||
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(user);
|
||||
expect(await guard.canActivate(context(req))).toBe(true);
|
||||
expect(req.user).toBe(user);
|
||||
});
|
||||
});
|
||||
@@ -170,14 +170,14 @@ describe('PasskeyEnabledGuard', () => {
|
||||
const resolveAuthToggles = vi.fn();
|
||||
const guard = new PasskeyEnabledGuard({ resolveAuthToggles } as unknown as AuthService);
|
||||
|
||||
it('404s when passkey_login is off', () => {
|
||||
resolveAuthToggles.mockReturnValue({ passkey_login: false });
|
||||
expect(thrown(() => guard.canActivate())).toEqual({ status: 404, body: { error: 'Passkey login is not enabled' } });
|
||||
it('404s when passkey_login is off', async () => {
|
||||
resolveAuthToggles.mockResolvedValue({ passkey_login: false });
|
||||
expect(await thrownAsync(() => guard.canActivate())).toEqual({ status: 404, body: { error: 'Passkey login is not enabled' } });
|
||||
});
|
||||
|
||||
it('allows when passkey_login is on', () => {
|
||||
resolveAuthToggles.mockReturnValue({ passkey_login: true });
|
||||
expect(guard.canActivate()).toBe(true);
|
||||
it('allows when passkey_login is on', async () => {
|
||||
resolveAuthToggles.mockResolvedValue({ passkey_login: true });
|
||||
expect(await guard.canActivate()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -241,17 +241,17 @@ describe('PasskeyController', () => {
|
||||
}, 10000);
|
||||
|
||||
it('credentials: list, rename (error + success), delete (error + success)', async () => {
|
||||
passkey.listPasskeys.mockReturnValue([{ id: 'a' }]);
|
||||
expect(pc(rl()).list(user)).toEqual({ credentials: [{ id: 'a' }] });
|
||||
passkey.listPasskeys.mockResolvedValue([{ id: 'a' }]);
|
||||
expect(await pc(rl()).list(user)).toEqual({ credentials: [{ id: 'a' }] });
|
||||
|
||||
passkey.renamePasskey.mockReturnValue({ error: 'Not found', status: 404 });
|
||||
expect(thrown(() => pc(rl()).rename(user, 'cid', { name: 'x' }))).toEqual({ status: 404, body: { error: 'Not found' } });
|
||||
passkey.renamePasskey.mockReturnValue({ success: true });
|
||||
expect(pc(rl()).rename(user, 'cid', { name: 'x' })).toEqual({ success: true });
|
||||
passkey.renamePasskey.mockResolvedValue({ error: 'Not found', status: 404 });
|
||||
expect(await thrownAsync(() => pc(rl()).rename(user, 'cid', { name: 'x' }))).toEqual({ status: 404, body: { error: 'Not found' } });
|
||||
passkey.renamePasskey.mockResolvedValue({ success: true });
|
||||
expect(await pc(rl()).rename(user, 'cid', { name: 'x' })).toEqual({ success: true });
|
||||
|
||||
passkey.deletePasskey.mockReturnValue({ error: 'Incorrect password', status: 401 });
|
||||
passkey.deletePasskey.mockResolvedValue({ error: 'Incorrect password', status: 401 });
|
||||
expect(await thrownAsync(() => pc(rl()).remove(user, 'cid', { password: 'x' }, req))).toEqual({ status: 401, body: { error: 'Incorrect password' } });
|
||||
passkey.deletePasskey.mockReturnValue({ success: true });
|
||||
passkey.deletePasskey.mockResolvedValue({ success: true });
|
||||
expect(await pc(rl()).remove(user, 'cid', { password: 'p' }, req)).toEqual({ success: true });
|
||||
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.passkey_delete' }));
|
||||
});
|
||||
|
||||
@@ -83,11 +83,11 @@ describe('RateLimitService', () => {
|
||||
});
|
||||
|
||||
describe('AuthPublicController', () => {
|
||||
it('demo-login maps error, else sets the cookie + returns token/user', () => {
|
||||
expect(thrown(() => apc(asvc({ demoLogin: vi.fn().mockReturnValue({ error: 'Demo disabled', status: 403 }) } as Partial<AuthService>), rl()).demoLogin(req, res))).toEqual({ status: 403, body: { error: 'Demo disabled' } });
|
||||
it('demo-login maps error, else sets the cookie + returns token/user', async () => {
|
||||
expect(await thrownAsync(() => apc(asvc({ demoLogin: vi.fn().mockReturnValue({ error: 'Demo disabled', status: 403 }) } as Partial<AuthService>), rl()).demoLogin(req, res))).toEqual({ status: 403, body: { error: 'Demo disabled' } });
|
||||
const setAuthCookie = vi.fn();
|
||||
const c = apc(asvc({ demoLogin: vi.fn().mockReturnValue({ token: 'tk', user }), setAuthCookie } as Partial<AuthService>), rl());
|
||||
expect(c.demoLogin(req, res)).toEqual({ token: 'tk', user });
|
||||
expect(await c.demoLogin(req, res)).toEqual({ token: 'tk', user });
|
||||
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk', req);
|
||||
});
|
||||
|
||||
@@ -100,11 +100,11 @@ describe('AuthPublicController', () => {
|
||||
expect(setAuthCookie).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('invite 429 when rate-limited', () => {
|
||||
it('invite 429 when rate-limited', async () => {
|
||||
const s = rl();
|
||||
s.check('login', '9.9.9.9', 10, 15 * 60 * 1000, Date.now()); // not exhausted yet
|
||||
const c = apc(asvc({ validateInviteToken: vi.fn().mockReturnValue({ valid: true, max_uses: 1, used_count: 0, expires_at: null }) } as Partial<AuthService>), s);
|
||||
expect(c.invite('tok', req)).toEqual({ valid: true, max_uses: 1, used_count: 0, expires_at: null });
|
||||
expect(await c.invite('tok', req)).toEqual({ valid: true, max_uses: 1, used_count: 0, expires_at: null });
|
||||
});
|
||||
|
||||
it('login: mfa branch, success cookie, error mapping', async () => {
|
||||
@@ -142,9 +142,9 @@ describe('AuthPublicController', () => {
|
||||
expect(getAppConfig).toHaveBeenLastCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('invite maps a service error', () => {
|
||||
it('invite maps a service error', async () => {
|
||||
const c = apc(asvc({ validateInviteToken: vi.fn().mockReturnValue({ error: 'Expired', status: 410 }) } as Partial<AuthService>), rl());
|
||||
expect(thrown(() => c.invite('tok', req))).toEqual({ status: 410, body: { error: 'Expired' } });
|
||||
expect(await thrownAsync(() => c.invite('tok', req))).toEqual({ status: 410, body: { error: 'Expired' } });
|
||||
});
|
||||
|
||||
it('login takes the mfa-required branch and never sets a cookie', async () => {
|
||||
@@ -195,7 +195,7 @@ describe('AuthPublicController', () => {
|
||||
for (let i = 0; i < 10; i++) s.check('login', '9.9.9.9', 10, 15 * 60 * 1000, now);
|
||||
const c = apc(asvc({ registerUser: vi.fn(), validateInviteToken: vi.fn() } as Partial<AuthService>), s);
|
||||
expect(await thrownAsync(() => c.register(anyBody(), req, res))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
expect(thrown(() => c.invite('t', req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
expect(await thrownAsync(() => c.invite('t', req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
});
|
||||
|
||||
it('mfa/verify-login sets cookie + audits; logout clears cookie', async () => {
|
||||
@@ -210,9 +210,9 @@ describe('AuthPublicController', () => {
|
||||
});
|
||||
|
||||
describe('AuthController (authenticated)', () => {
|
||||
it('GET /me 404 when missing, else returns the loaded user', () => {
|
||||
expect(thrown(() => ac(asvc({ getCurrentUser: vi.fn().mockReturnValue(undefined) } as Partial<AuthService>), rl()).me(user))).toEqual({ status: 404, body: { error: 'User not found' } });
|
||||
expect(ac(asvc({ getCurrentUser: vi.fn().mockReturnValue({ id: 1 }) } as Partial<AuthService>), rl()).me(user)).toEqual({ user: { id: 1 } });
|
||||
it('GET /me 404 when missing, else returns the loaded user', async () => {
|
||||
expect(await thrownAsync(() => ac(asvc({ getCurrentUser: vi.fn().mockReturnValue(undefined) } as Partial<AuthService>), rl()).me(user))).toEqual({ status: 404, body: { error: 'User not found' } });
|
||||
expect(await ac(asvc({ getCurrentUser: vi.fn().mockReturnValue({ id: 1 }) } as Partial<AuthService>), rl()).me(user)).toEqual({ user: { id: 1 } });
|
||||
});
|
||||
|
||||
it('change-password maps error, else audits', async () => {
|
||||
@@ -377,7 +377,7 @@ describe('AuthController (authenticated)', () => {
|
||||
const deleteAvatar = vi.fn().mockResolvedValue({ removed: true });
|
||||
expect(await ac(asvc({}), rl(), {}, { deleteAvatar }).deleteAvatar(user)).toEqual({ removed: true });
|
||||
const listUsers = vi.fn().mockReturnValue([{ id: 1 }]);
|
||||
expect(ac(asvc({}), rl(), {}, { listUsers }).users(user)).toEqual({ users: [{ id: 1 }] });
|
||||
expect(await ac(asvc({}), rl(), {}, { listUsers }).users(user)).toEqual({ users: [{ id: 1 }] });
|
||||
expect(listUsers).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
@@ -388,8 +388,8 @@ describe('AuthController (authenticated)', () => {
|
||||
});
|
||||
|
||||
it('app-settings get maps error, else returns data; put maps error, else audits', async () => {
|
||||
expect(thrown(() => ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ error: 'denied', status: 403 }) } as Partial<AuthService>), rl()).getAppSettings(user))).toEqual({ status: 403, body: { error: 'denied' } });
|
||||
expect(ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ data: { x: 1 } }) } as Partial<AuthService>), rl()).getAppSettings(user)).toEqual({ x: 1 });
|
||||
expect(await thrownAsync(() => ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ error: 'denied', status: 403 }) } as Partial<AuthService>), rl()).getAppSettings(user))).toEqual({ status: 403, body: { error: 'denied' } });
|
||||
expect(await ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ data: { x: 1 } }) } as Partial<AuthService>), rl()).getAppSettings(user)).toEqual({ x: 1 });
|
||||
expect(await thrownAsync(() => ac(asvc({ updateAppSettings: vi.fn().mockReturnValue({ error: 'bad', status: 400 }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req))).toEqual({ status: 400, body: { error: 'bad' } });
|
||||
expect(await ac(asvc({ updateAppSettings: vi.fn().mockReturnValue({ auditSummary: 's', auditDebugDetails: 'd' }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req)).toEqual({ success: true });
|
||||
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.app_update' }));
|
||||
|
||||
@@ -131,14 +131,14 @@ afterAll(() => testDb.close());
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('requestPasswordReset — OIDC/SSO accounts', () => {
|
||||
it('AUTH-DB-PR1: refuses a reset for an OIDC-linked account that has a (random) password hash', () => {
|
||||
it('AUTH-DB-PR1: refuses a reset for an OIDC-linked account that has a (random) password hash', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// OIDC users are created with a random bcrypt hash, so password_hash is set —
|
||||
// the old guard keyed off a missing hash and therefore let the reset through.
|
||||
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?')
|
||||
.run('sub-1129', 'https://idp.example', user.id);
|
||||
|
||||
const result = svc.requestPasswordReset(user.email, null);
|
||||
const result = await svc.requestPasswordReset(user.email, null);
|
||||
|
||||
expect(result.reason).toBe('oidc_only');
|
||||
expect(result.tokenForDelivery).toBeNull();
|
||||
@@ -147,9 +147,9 @@ describe('requestPasswordReset — OIDC/SSO accounts', () => {
|
||||
expect(n).toBe(0);
|
||||
});
|
||||
|
||||
it('AUTH-DB-PR2: still issues a reset for a normal local (non-SSO) account', () => {
|
||||
it('AUTH-DB-PR2: still issues a reset for a normal local (non-SSO) account', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = svc.requestPasswordReset(user.email, null);
|
||||
const result = await svc.requestPasswordReset(user.email, null);
|
||||
expect(result.reason).toBe('issued');
|
||||
expect(result.tokenForDelivery).toBeTruthy();
|
||||
});
|
||||
@@ -160,19 +160,19 @@ describe('requestPasswordReset — OIDC/SSO accounts', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('getAppSettings', () => {
|
||||
it('AUTH-DB-013: returns 403 for non-admin', () => {
|
||||
it('AUTH-DB-013: returns 403 for non-admin', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = svc.getAppSettings(user.id);
|
||||
const result = await svc.getAppSettings(user.id);
|
||||
expect(result.status).toBe(403);
|
||||
expect(result.error).toMatch(/admin/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-014: returns settings object for admin with known key allow_registration', () => {
|
||||
it('AUTH-DB-014: returns settings object for admin with known key allow_registration', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
testDb
|
||||
.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'true')")
|
||||
.run();
|
||||
const result = svc.getAppSettings(user.id);
|
||||
const result = await svc.getAppSettings(user.id);
|
||||
expect(result.status).toBeUndefined();
|
||||
expect(result.data).toBeDefined();
|
||||
expect(result.data).toHaveProperty('allow_registration', 'true');
|
||||
@@ -184,25 +184,25 @@ describe('getAppSettings', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('isOidcOnlyMode', () => {
|
||||
it('AUTH-DB-019: returns false when OIDC_ONLY env var is not set', () => {
|
||||
it('AUTH-DB-019: returns false when OIDC_ONLY env var is not set', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
expect(svc.isOidcOnlyMode()).toBe(false);
|
||||
expect(await svc.isOidcOnlyMode()).toBe(false);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-020: returns false when OIDC_ONLY=true but no OIDC_ISSUER configured', () => {
|
||||
it('AUTH-DB-020: returns false when OIDC_ONLY=true but no OIDC_ISSUER configured', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', 'true');
|
||||
vi.stubEnv('OIDC_ISSUER', '');
|
||||
vi.stubEnv('OIDC_CLIENT_ID', '');
|
||||
expect(svc.isOidcOnlyMode()).toBe(false);
|
||||
expect(await svc.isOidcOnlyMode()).toBe(false);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-021: returns true when OIDC_ONLY=true AND OIDC_ISSUER AND OIDC_CLIENT_ID are set', () => {
|
||||
it('AUTH-DB-021: returns true when OIDC_ONLY=true AND OIDC_ISSUER AND OIDC_CLIENT_ID are set', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', 'true');
|
||||
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');
|
||||
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
|
||||
expect(svc.isOidcOnlyMode()).toBe(true);
|
||||
expect(await svc.isOidcOnlyMode()).toBe(true);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -217,63 +217,63 @@ describe('resolveAuthToggles', () => {
|
||||
testDb.prepare("DELETE FROM app_settings WHERE key IN ('password_login','password_registration','oidc_login','oidc_registration','oidc_only','allow_registration')").run();
|
||||
});
|
||||
|
||||
it('AUTH-DB-022a: returns all true by default (no DB keys, no env override)', () => {
|
||||
it('AUTH-DB-022a: returns all true by default (no DB keys, no env override)', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
expect(t.password_login).toBe(true);
|
||||
expect(t.password_registration).toBe(true);
|
||||
expect(t.oidc_login).toBe(true);
|
||||
expect(t.oidc_registration).toBe(true);
|
||||
});
|
||||
|
||||
it('AUTH-DB-022b: legacy — OIDC_ONLY=true with OIDC configured disables password_login and password_registration', () => {
|
||||
it('AUTH-DB-022b: legacy — OIDC_ONLY=true with OIDC configured disables password_login and password_registration', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', 'true');
|
||||
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');
|
||||
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
expect(t.password_login).toBe(false);
|
||||
expect(t.password_registration).toBe(false);
|
||||
expect(t.oidc_login).toBe(true);
|
||||
expect(t.oidc_registration).toBe(true);
|
||||
});
|
||||
|
||||
it('AUTH-DB-022c: legacy — allow_registration=false disables both password and oidc registration', () => {
|
||||
it('AUTH-DB-022c: legacy — allow_registration=false disables both password and oidc registration', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
expect(t.password_login).toBe(true);
|
||||
expect(t.password_registration).toBe(false);
|
||||
expect(t.oidc_login).toBe(true);
|
||||
expect(t.oidc_registration).toBe(false);
|
||||
});
|
||||
|
||||
it('AUTH-DB-022d: new granular keys take precedence over legacy keys', () => {
|
||||
it('AUTH-DB-022d: new granular keys take precedence over legacy keys', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'true')").run();
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
// New key present → use new keys, allow_registration ignored
|
||||
expect(t.password_registration).toBe(true);
|
||||
expect(t.oidc_registration).toBe(true); // defaults to true when key not set
|
||||
});
|
||||
|
||||
it('AUTH-DB-022e: OIDC_ONLY env var overrides new granular keys for password toggles', () => {
|
||||
it('AUTH-DB-022e: OIDC_ONLY env var overrides new granular keys for password toggles', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', 'true');
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_login', 'true')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'true')").run();
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
// OIDC_ONLY forces password toggles off even when DB says true
|
||||
expect(t.password_login).toBe(false);
|
||||
expect(t.password_registration).toBe(false);
|
||||
});
|
||||
|
||||
it('AUTH-DB-022f: individual granular keys can be set independently', () => {
|
||||
it('AUTH-DB-022f: individual granular keys can be set independently', async () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_login', 'true')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'false')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_login', 'true')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_registration', 'false')").run();
|
||||
const t = svc.resolveAuthToggles();
|
||||
const t = await svc.resolveAuthToggles();
|
||||
expect(t.password_login).toBe(true);
|
||||
expect(t.password_registration).toBe(false);
|
||||
expect(t.oidc_login).toBe(true);
|
||||
@@ -286,26 +286,26 @@ describe('resolveAuthToggles', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('setupMfa', () => {
|
||||
it('AUTH-DB-022: returns 403 in demo mode for demo@nomad.app', () => {
|
||||
it('AUTH-DB-022: returns 403 in demo mode for demo@nomad.app', async () => {
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
const result = svc.setupMfa(user.id, 'demo@nomad.app');
|
||||
const result = await svc.setupMfa(user.id, 'demo@nomad.app');
|
||||
expect(result.status).toBe(403);
|
||||
expect(result.error).toMatch(/demo mode/i);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-023: returns 400 when MFA is already enabled', () => {
|
||||
it('AUTH-DB-023: returns 400 when MFA is already enabled', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1 WHERE id = ?').run(user.id);
|
||||
const result = svc.setupMfa(user.id, user.email);
|
||||
const result = await svc.setupMfa(user.id, user.email);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/already enabled/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-024: returns secret and otpauth_url when MFA setup starts successfully', () => {
|
||||
it('AUTH-DB-024: returns secret and otpauth_url when MFA setup starts successfully', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = svc.setupMfa(user.id, user.email);
|
||||
const result = await svc.setupMfa(user.id, user.email);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(typeof result.secret).toBe('string');
|
||||
expect(result.secret!.length).toBeGreaterThan(0);
|
||||
@@ -320,17 +320,17 @@ describe('setupMfa', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('enableMfa', () => {
|
||||
it('AUTH-DB-025: returns 400 when no verification code is provided', () => {
|
||||
it('AUTH-DB-025: returns 400 when no verification code is provided', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = svc.enableMfa(user.id, undefined);
|
||||
const result = await svc.enableMfa(user.id, undefined);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/code is required/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-026: returns 400 when there is no pending MFA setup', () => {
|
||||
it('AUTH-DB-026: returns 400 when there is no pending MFA setup', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// No setupMfa called first, so no pending entry exists
|
||||
const result = svc.enableMfa(user.id, '123456');
|
||||
const result = await svc.enableMfa(user.id, '123456');
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/no mfa setup in progress/i);
|
||||
});
|
||||
@@ -341,10 +341,10 @@ describe('enableMfa', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('disableMfa', () => {
|
||||
it('AUTH-DB-027: returns 403 in demo mode for demo@nomad.app', () => {
|
||||
it('AUTH-DB-027: returns 403 in demo mode for demo@nomad.app', async () => {
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
const result = svc.disableMfa(user.id, 'demo@nomad.app', {
|
||||
const result = await svc.disableMfa(user.id, 'demo@nomad.app', {
|
||||
password: 'password123',
|
||||
code: '000000',
|
||||
});
|
||||
@@ -353,22 +353,22 @@ describe('disableMfa', () => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-028: returns 400 when password or code is missing', () => {
|
||||
it('AUTH-DB-028: returns 400 when password or code is missing', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
const missingCode = svc.disableMfa(user.id, user.email, { password: 'pass', code: undefined });
|
||||
const missingCode = await svc.disableMfa(user.id, user.email, { password: 'pass', code: undefined });
|
||||
expect(missingCode.status).toBe(400);
|
||||
expect(missingCode.error).toMatch(/password and authenticator code/i);
|
||||
|
||||
const missingPassword = svc.disableMfa(user.id, user.email, { password: undefined, code: '123456' });
|
||||
const missingPassword = await svc.disableMfa(user.id, user.email, { password: undefined, code: '123456' });
|
||||
expect(missingPassword.status).toBe(400);
|
||||
expect(missingPassword.error).toMatch(/password and authenticator code/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-029: returns 400 when MFA is not enabled on the account', () => {
|
||||
it('AUTH-DB-029: returns 400 when MFA is not enabled on the account', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// mfa_enabled defaults to 0 / not set
|
||||
const result = svc.disableMfa(user.id, user.email, { password: 'password123', code: '000000' });
|
||||
const result = await svc.disableMfa(user.id, user.email, { password: 'password123', code: '000000' });
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/not enabled/i);
|
||||
});
|
||||
@@ -379,23 +379,23 @@ describe('disableMfa', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('validateInviteToken', () => {
|
||||
it('AUTH-DB-030: returns 404 for unknown token', () => {
|
||||
const result = svc.validateInviteToken('no-such-token');
|
||||
it('AUTH-DB-030: returns 404 for unknown token', async () => {
|
||||
const result = await svc.validateInviteToken('no-such-token');
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
|
||||
it('AUTH-DB-031: returns 410 when max_uses exceeded', () => {
|
||||
it('AUTH-DB-031: returns 410 when max_uses exceeded', async () => {
|
||||
// createInviteToken with used_count already at max
|
||||
const invite = createInviteToken(testDb, { max_uses: 1 });
|
||||
// manually set used_count = 1 to simulate exhaustion
|
||||
testDb.prepare('UPDATE invite_tokens SET used_count = 1 WHERE id = ?').run(invite.id);
|
||||
const result = svc.validateInviteToken(invite.token);
|
||||
const result = await svc.validateInviteToken(invite.token);
|
||||
expect(result.status).toBe(410);
|
||||
});
|
||||
|
||||
it('AUTH-DB-032: returns 410 when expired', () => {
|
||||
it('AUTH-DB-032: returns 410 when expired', async () => {
|
||||
const invite = createInviteToken(testDb, { expires_at: '2000-01-01T00:00:00.000Z' });
|
||||
const result = svc.validateInviteToken(invite.token);
|
||||
const result = await svc.validateInviteToken(invite.token);
|
||||
expect(result.status).toBe(410);
|
||||
});
|
||||
});
|
||||
@@ -430,13 +430,13 @@ describe('registerUser — OIDC-only / registration-disabled', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('loginUser — OIDC-only mode', () => {
|
||||
it('AUTH-DB-035: returns 403 when oidc_only=true', () => {
|
||||
it('AUTH-DB-035: returns 403 when oidc_only=true', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_only', 'true')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_issuer', 'https://x')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_client_id', 'id')").run();
|
||||
|
||||
const result = svc.loginUser({ email: user.email, password });
|
||||
const result = await svc.loginUser({ email: user.email, password });
|
||||
expect(result.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -446,13 +446,13 @@ describe('loginUser — OIDC-only mode', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('changePassword — OIDC-only mode', () => {
|
||||
it('AUTH-DB-036: returns 403 when oidc_only=true', () => {
|
||||
it('AUTH-DB-036: returns 403 when oidc_only=true', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_only', 'true')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_issuer', 'https://x')").run();
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_client_id', 'id')").run();
|
||||
|
||||
const result = svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
const result = await svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
expect(result.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -463,14 +463,14 @@ describe('changePassword — session invalidation', () => {
|
||||
const mcpCount = (id: number) =>
|
||||
(testDb.prepare('SELECT COUNT(*) c FROM mcp_tokens WHERE user_id = ?').get(id) as { c: number }).c;
|
||||
|
||||
it('AUTH-DB-036b: bumps password_version, prunes MCP tokens, and re-issues a session', () => {
|
||||
it('AUTH-DB-036b: bumps password_version, prunes MCP tokens, and re-issues a session', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
tokens.createMcpToken(user.id, 'cli');
|
||||
|
||||
expect(pvOf(user.id)).toBe(0);
|
||||
expect(mcpCount(user.id)).toBe(1);
|
||||
|
||||
const result = svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
const result = await svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(typeof result.token).toBe('string'); // fresh session for the current device
|
||||
@@ -478,23 +478,23 @@ describe('changePassword — session invalidation', () => {
|
||||
expect(mcpCount(user.id)).toBe(0); // static MCP tokens revoked
|
||||
});
|
||||
|
||||
it('AUTH-DB-036c: a token minted before the change no longer validates afterwards', () => {
|
||||
it('AUTH-DB-036c: a token minted before the change no longer validates afterwards', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const stolen = svc.generateToken({ id: user.id }); // pv=0 at mint time
|
||||
const stolen = await svc.generateToken({ id: user.id }); // pv=0 at mint time
|
||||
|
||||
expect(verifyJwtAndLoadUser(stolen)).not.toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(stolen)).not.toBeNull();
|
||||
|
||||
svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
await svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(stolen)).toBeNull(); // invalidated by the pv bump
|
||||
expect(await verifyJwtAndLoadUser(stolen)).toBeNull(); // invalidated by the pv bump
|
||||
});
|
||||
|
||||
it('AUTH-DB-036d: preserves the remember choice in the re-issued session (#1927)', () => {
|
||||
it('AUTH-DB-036d: preserves the remember choice in the re-issued session (#1927)', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { user, password } = createUser(testDb);
|
||||
|
||||
const result = svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' }, true);
|
||||
const result = await svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' }, true);
|
||||
expect(result.success).toBe(true);
|
||||
const decoded = jwt.decode(result.token!) as { remember?: boolean; iat: number; exp: number };
|
||||
expect(decoded.remember).toBe(true);
|
||||
@@ -507,11 +507,11 @@ describe('changePassword — session invalidation', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('disableMfa — require_mfa policy', () => {
|
||||
it('AUTH-DB-037: returns 403 when require_mfa=true is set globally', () => {
|
||||
it('AUTH-DB-037: returns 403 when require_mfa=true is set globally', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('require_mfa', 'true')").run();
|
||||
|
||||
const result = svc.disableMfa(user.id, user.email, { password: 'pass', code: '123456' });
|
||||
const result = await svc.disableMfa(user.id, user.email, { password: 'pass', code: '123456' });
|
||||
expect(result.status).toBe(403);
|
||||
expect(result.error).toMatch(/cannot be disabled/i);
|
||||
});
|
||||
@@ -522,25 +522,25 @@ describe('disableMfa — require_mfa policy', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('verifyMfaLogin — validation', () => {
|
||||
it('AUTH-DB-038: returns 400 when mfa_token or code is missing', () => {
|
||||
const result = svc.verifyMfaLogin({ mfa_token: undefined, code: undefined });
|
||||
it('AUTH-DB-038: returns 400 when mfa_token or code is missing', async () => {
|
||||
const result = await svc.verifyMfaLogin({ mfa_token: undefined, code: undefined });
|
||||
expect(result.status).toBe(400);
|
||||
});
|
||||
|
||||
it('AUTH-DB-039: returns 401 when mfa_token has wrong purpose', () => {
|
||||
it('AUTH-DB-039: returns 401 when mfa_token has wrong purpose', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const jwt = require('jsonwebtoken');
|
||||
const tok = jwt.sign({ id: 1, purpose: 'wrong' }, 'test-secret', { expiresIn: '5m', algorithm: 'HS256' });
|
||||
const result = svc.verifyMfaLogin({ mfa_token: tok, code: '123456' });
|
||||
const result = await svc.verifyMfaLogin({ mfa_token: tok, code: '123456' });
|
||||
expect(result.status).toBe(401);
|
||||
expect(result.error).toMatch(/invalid/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-040: returns 401 when user not found for valid mfa_token', () => {
|
||||
it('AUTH-DB-040: returns 401 when user not found for valid mfa_token', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const jwt = require('jsonwebtoken');
|
||||
const tok = jwt.sign({ id: 99999, purpose: 'mfa_login' }, 'test-secret', { expiresIn: '5m', algorithm: 'HS256' });
|
||||
const result = svc.verifyMfaLogin({ mfa_token: tok, code: '123456' });
|
||||
const result = await svc.verifyMfaLogin({ mfa_token: tok, code: '123456' });
|
||||
expect(result.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -670,18 +670,18 @@ describe('getAppConfig', () => {
|
||||
});
|
||||
|
||||
describe('demoLogin', () => {
|
||||
it('AUTH-DB-053: 404 outside demo mode', () => {
|
||||
it('AUTH-DB-053: 404 outside demo mode', async () => {
|
||||
vi.stubEnv('DEMO_MODE', '');
|
||||
expect(svc.demoLogin()).toEqual({ error: 'Not found', status: 404 });
|
||||
expect(await svc.demoLogin()).toEqual({ error: 'Not found', status: 404 });
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-054: 500 when the demo user row is missing; token + safe user when present', () => {
|
||||
it('AUTH-DB-054: 500 when the demo user row is missing; token + safe user when present', async () => {
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
expect(svc.demoLogin()).toEqual({ error: 'Demo user not found', status: 500 });
|
||||
expect(await svc.demoLogin()).toEqual({ error: 'Demo user not found', status: 500 });
|
||||
// demoLogin looks up DEMO_EMAIL_PRIMARY specifically (not any demo alias).
|
||||
createUser(testDb, { email: 'demo@trek.app' });
|
||||
const result = svc.demoLogin();
|
||||
const result = await svc.demoLogin();
|
||||
expect(typeof result.token).toBe('string');
|
||||
expect(result.user).not.toHaveProperty('password_hash');
|
||||
vi.unstubAllEnvs();
|
||||
@@ -689,9 +689,9 @@ describe('demoLogin', () => {
|
||||
});
|
||||
|
||||
describe('validateInviteToken — valid path', () => {
|
||||
it('AUTH-DB-055: returns valid with usage metadata', () => {
|
||||
it('AUTH-DB-055: returns valid with usage metadata', async () => {
|
||||
const invite = createInviteToken(testDb, { max_uses: 5 });
|
||||
const result = svc.validateInviteToken(invite.token);
|
||||
const result = await svc.validateInviteToken(invite.token);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.max_uses).toBe(5);
|
||||
expect(result.used_count).toBe(0);
|
||||
@@ -730,26 +730,26 @@ describe('registerUser — success paths', () => {
|
||||
});
|
||||
|
||||
describe('loginUser — credential branches', () => {
|
||||
it('AUTH-DB-059: unknown email answers the generic 401', () => {
|
||||
const result = svc.loginUser({ email: 'nobody@x.com', password: 'pw' });
|
||||
it('AUTH-DB-059: unknown email answers the generic 401', async () => {
|
||||
const result = await svc.loginUser({ email: 'nobody@x.com', password: 'pw' });
|
||||
expect(result).toMatchObject({ error: 'Invalid email or password', status: 401, auditUserId: null });
|
||||
expect(result.auditDetails).toMatchObject({ reason: 'unknown_email' });
|
||||
});
|
||||
|
||||
it('AUTH-DB-060: missing fields answer the bespoke 400', () => {
|
||||
expect(svc.loginUser({ email: '', password: '' })).toEqual({ error: 'Email and password are required', status: 400 });
|
||||
it('AUTH-DB-060: missing fields answer the bespoke 400', async () => {
|
||||
expect(await svc.loginUser({ email: '', password: '' })).toEqual({ error: 'Email and password are required', status: 400 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-061: wrong password answers the generic 401 with the wrong_password audit reason', () => {
|
||||
it('AUTH-DB-061: wrong password answers the generic 401 with the wrong_password audit reason', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = svc.loginUser({ email: user.email, password: 'nope' });
|
||||
const result = await svc.loginUser({ email: user.email, password: 'nope' });
|
||||
expect(result.status).toBe(401);
|
||||
expect(result.auditDetails).toMatchObject({ reason: 'wrong_password' });
|
||||
});
|
||||
|
||||
it('AUTH-DB-062: success returns token + stripped user and bumps last_login/login_count', () => {
|
||||
it('AUTH-DB-062: success returns token + stripped user and bumps last_login/login_count', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const result = svc.loginUser({ email: user.email, password });
|
||||
const result = await svc.loginUser({ email: user.email, password });
|
||||
expect(typeof result.token).toBe('string');
|
||||
expect(result.user).not.toHaveProperty('password_hash');
|
||||
expect(result.auditAction).toBe('user.login');
|
||||
@@ -758,24 +758,24 @@ describe('loginUser — credential branches', () => {
|
||||
expect(row.last_login).not.toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-DB-063: an MFA-enabled account gets the interstitial mfa_token instead of a session', () => {
|
||||
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);
|
||||
const { password } = { password: undefined };
|
||||
void password;
|
||||
const result = svc.loginUser({ email: user.email, password: 'TestPass' });
|
||||
const result = await svc.loginUser({ email: user.email, password: 'TestPass' });
|
||||
// wrong password still 401s before the MFA branch
|
||||
expect(result.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentUser', () => {
|
||||
it('AUTH-DB-064: returns the stripped row with avatar_url; null for a missing id', () => {
|
||||
it('AUTH-DB-064: returns the stripped row with avatar_url; null for a missing id', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const loaded = svc.getCurrentUser(user.id);
|
||||
const loaded = await svc.getCurrentUser(user.id);
|
||||
expect(loaded?.id).toBe(user.id);
|
||||
expect(loaded).not.toHaveProperty('password_hash');
|
||||
expect(svc.getCurrentUser(999999)).toBeNull();
|
||||
expect(await svc.getCurrentUser(999999)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -801,39 +801,39 @@ describe('deleteAccount', () => {
|
||||
});
|
||||
|
||||
describe('updateAppSettings', () => {
|
||||
it('AUTH-DB-071: 403 for non-admin', () => {
|
||||
it('AUTH-DB-071: 403 for non-admin', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(svc.updateAppSettings(user.id, {}).status).toBe(403);
|
||||
expect((await svc.updateAppSettings(user.id, {})).status).toBe(403);
|
||||
});
|
||||
|
||||
it('AUTH-DB-072: require_mfa=true refuses when the admin has neither MFA nor a passkey', () => {
|
||||
it('AUTH-DB-072: require_mfa=true refuses when the admin has neither MFA nor a passkey', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const result = svc.updateAppSettings(user.id, { require_mfa: true });
|
||||
const result = await svc.updateAppSettings(user.id, { require_mfa: true });
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/secure your own account/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-073: require_mfa=true is allowed once the admin has MFA enabled', () => {
|
||||
it('AUTH-DB-073: require_mfa=true is allowed once the admin has MFA enabled', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1 WHERE id = ?').run(user.id);
|
||||
const result = svc.updateAppSettings(user.id, { require_mfa: true });
|
||||
const result = await svc.updateAppSettings(user.id, { require_mfa: true });
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.auditSummary).toMatchObject({ require_mfa: true });
|
||||
testDb.prepare("DELETE FROM app_settings WHERE key = 'require_mfa'").run();
|
||||
});
|
||||
|
||||
it('AUTH-DB-074: lockout prevention refuses disabling every login method', () => {
|
||||
it('AUTH-DB-074: lockout prevention refuses disabling every login method', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const result = svc.updateAppSettings(user.id, { password_login: 'false', oidc_login: 'false' });
|
||||
const result = await svc.updateAppSettings(user.id, { password_login: 'false', oidc_login: 'false' });
|
||||
expect(result).toEqual({ error: 'Cannot disable all login methods. At least one must remain enabled.', status: 400 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-075: the smtp_pass masking sentinel is skipped on a notification-settings change', () => {
|
||||
it('AUTH-DB-075: the smtp_pass masking sentinel is skipped on a notification-settings change', async () => {
|
||||
// The reminder crons read their gates per tick now, so a settings change no
|
||||
// longer flags (or needs) a scheduler restart.
|
||||
const { user } = createAdmin(testDb);
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('smtp_pass', 'stored')").run();
|
||||
const result = svc.updateAppSettings(user.id, { smtp_pass: '••••••••', notification_channels: 'email' });
|
||||
const result = await svc.updateAppSettings(user.id, { smtp_pass: '••••••••', notification_channels: 'email' });
|
||||
expect(result.success).toBe(true);
|
||||
const { value } = testDb.prepare("SELECT value FROM app_settings WHERE key = 'smtp_pass'").get() as { value: string };
|
||||
expect(value).toBe('stored'); // sentinel never overwrites the secret
|
||||
@@ -843,11 +843,11 @@ describe('updateAppSettings', () => {
|
||||
});
|
||||
|
||||
describe('MFA success flows', () => {
|
||||
it('AUTH-DB-076: setup → enable with a valid TOTP code returns backup codes and persists the encrypted secret', () => {
|
||||
it('AUTH-DB-076: setup → enable with a valid TOTP code returns backup codes and persists the encrypted secret', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const setup = svc.setupMfa(user.id, user.email);
|
||||
const setup = await svc.setupMfa(user.id, user.email);
|
||||
const code = authenticator.generate(setup.secret!);
|
||||
const result = svc.enableMfa(user.id, code);
|
||||
const result = await svc.enableMfa(user.id, code);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.backup_codes).toHaveLength(10);
|
||||
const row = testDb.prepare('SELECT mfa_enabled, mfa_secret FROM users WHERE id = ?').get(user.id) as { mfa_enabled: number; mfa_secret: string };
|
||||
@@ -855,129 +855,129 @@ describe('MFA success flows', () => {
|
||||
expect(row.mfa_secret).toBe('enc:' + setup.secret);
|
||||
});
|
||||
|
||||
it('AUTH-DB-077: enable with a wrong code answers 401 and keeps the pending secret', () => {
|
||||
it('AUTH-DB-077: enable with a wrong code answers 401 and keeps the pending secret', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
svc.setupMfa(user.id, user.email);
|
||||
expect(svc.enableMfa(user.id, '000000')).toEqual({ error: 'Invalid verification code', status: 401 });
|
||||
await svc.setupMfa(user.id, user.email);
|
||||
expect(await svc.enableMfa(user.id, '000000')).toEqual({ error: 'Invalid verification code', status: 401 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-078: disableMfa succeeds with the right password + TOTP code', () => {
|
||||
it('AUTH-DB-078: disableMfa succeeds with the right password + TOTP code', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const secret = authenticator.generateSecret();
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ? WHERE id = ?').run('enc:' + secret, user.id);
|
||||
const result = svc.disableMfa(user.id, user.email, { password, code: authenticator.generate(secret) });
|
||||
const result = await svc.disableMfa(user.id, user.email, { password, code: authenticator.generate(secret) });
|
||||
expect(result).toEqual({ success: true, mfa_enabled: false });
|
||||
const row = testDb.prepare('SELECT mfa_enabled, mfa_secret FROM users WHERE id = ?').get(user.id) as { mfa_enabled: number; mfa_secret: string | null };
|
||||
expect(row.mfa_enabled).toBe(0);
|
||||
expect(row.mfa_secret).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-DB-079: disableMfa answers 401 on a wrong password', () => {
|
||||
it('AUTH-DB-079: disableMfa answers 401 on a wrong password', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const secret = authenticator.generateSecret();
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ? WHERE id = ?').run('enc:' + secret, user.id);
|
||||
expect(svc.disableMfa(user.id, user.email, { password: 'wrong', code: authenticator.generate(secret) }))
|
||||
expect(await svc.disableMfa(user.id, user.email, { password: 'wrong', code: authenticator.generate(secret) }))
|
||||
.toEqual({ error: 'Incorrect password', status: 401 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-080: verifyMfaLogin succeeds with a TOTP code from the interstitial token', () => {
|
||||
it('AUTH-DB-080: verifyMfaLogin succeeds with a TOTP code from the interstitial token', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const secret = authenticator.generateSecret();
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ? WHERE id = ?').run('enc:' + secret, user.id);
|
||||
const interstitial = svc.loginUser({ email: user.email, password });
|
||||
const interstitial = await svc.loginUser({ email: user.email, password });
|
||||
expect(interstitial.mfa_required).toBe(true);
|
||||
const result = svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: authenticator.generate(secret) });
|
||||
const result = await svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: authenticator.generate(secret) });
|
||||
expect(typeof result.token).toBe('string');
|
||||
expect(result.auditUserId).toBe(user.id);
|
||||
});
|
||||
|
||||
it('AUTH-DB-081: verifyMfaLogin consumes a backup code when the TOTP fails', () => {
|
||||
it('AUTH-DB-081: verifyMfaLogin consumes a backup code when the TOTP fails', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
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);
|
||||
const interstitial = svc.loginUser({ email: user.email, password });
|
||||
const result = svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: 'AAAA-1111' });
|
||||
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 };
|
||||
expect(JSON.parse(row.mfa_backup_codes)).toHaveLength(1); // used code spliced out
|
||||
// the spent code no longer verifies
|
||||
const again = svc.loginUser({ email: user.email, password });
|
||||
expect(svc.verifyMfaLogin({ mfa_token: again.mfa_token, code: 'AAAA-1111' }).status).toBe(401);
|
||||
const again = await svc.loginUser({ email: user.email, password });
|
||||
expect((await svc.verifyMfaLogin({ mfa_token: again.mfa_token, code: 'AAAA-1111' })).status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resetPassword', () => {
|
||||
it('AUTH-DB-082: consumes an issued token, bumps password_version and burns sibling tokens', () => {
|
||||
it('AUTH-DB-082: consumes an issued token, bumps password_version and burns sibling tokens', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const issued = svc.requestPasswordReset(user.email, '1.2.3.4');
|
||||
const issued = await svc.requestPasswordReset(user.email, '1.2.3.4');
|
||||
expect(issued.reason).toBe('issued');
|
||||
const result = svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' });
|
||||
const result = await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' });
|
||||
expect(result).toEqual({ success: true, userId: user.id });
|
||||
const row = testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(user.id) as { password_version: number };
|
||||
expect(row.password_version).toBe(1);
|
||||
// token is burned — a second use answers the bespoke 400
|
||||
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh456!' }))
|
||||
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh456!' }))
|
||||
.toEqual({ error: 'This reset link has already been used', status: 400 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-083: bespoke 400s for missing/unknown/expired tokens', () => {
|
||||
expect(svc.resetPassword({ new_password: 'Fresh123!' })).toEqual({ error: 'Reset token is required', status: 400 });
|
||||
expect(svc.resetPassword({ token: 't' })).toEqual({ error: 'New password is required', status: 400 });
|
||||
expect(svc.resetPassword({ token: 'unknown-token', new_password: 'Fresh123!' }))
|
||||
it('AUTH-DB-083: bespoke 400s for missing/unknown/expired tokens', async () => {
|
||||
expect(await svc.resetPassword({ new_password: 'Fresh123!' })).toEqual({ error: 'Reset token is required', status: 400 });
|
||||
expect(await svc.resetPassword({ token: 't' })).toEqual({ error: 'New password is required', status: 400 });
|
||||
expect(await svc.resetPassword({ token: 'unknown-token', new_password: 'Fresh123!' }))
|
||||
.toEqual({ error: 'Invalid or expired reset link', status: 400 });
|
||||
|
||||
const { user } = createUser(testDb);
|
||||
const issued = svc.requestPasswordReset(user.email, null);
|
||||
const issued = await svc.requestPasswordReset(user.email, null);
|
||||
testDb.prepare("UPDATE password_reset_tokens SET expires_at = '2000-01-01T00:00:00.000Z' WHERE user_id = ?").run(user.id);
|
||||
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
|
||||
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
|
||||
.toEqual({ error: 'Reset link has expired. Please request a new one.', status: 400 });
|
||||
});
|
||||
|
||||
it('AUTH-DB-084: an MFA-enabled account demands a code, then consumes a backup code', () => {
|
||||
it('AUTH-DB-084: an MFA-enabled account demands a code, then consumes a backup code', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const secret = authenticator.generateSecret();
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ?, mfa_backup_codes = ? WHERE id = ?')
|
||||
.run('enc:' + secret, JSON.stringify([hashBackupCode('CCCC-3333')]), user.id);
|
||||
const issued = svc.requestPasswordReset(user.email, null);
|
||||
const issued = await svc.requestPasswordReset(user.email, null);
|
||||
// no code → mfa_required interstitial, token NOT burned
|
||||
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
|
||||
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
|
||||
.toEqual({ mfa_required: true, status: 200 });
|
||||
// wrong code → 401
|
||||
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: '000000' }))
|
||||
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(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: 'CCCC-3333' }))
|
||||
expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!', mfa_code: 'CCCC-3333' }))
|
||||
.toEqual({ success: true, userId: user.id });
|
||||
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-085: password-login-disabled and per-email throttle short-circuit the request', () => {
|
||||
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');
|
||||
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
|
||||
expect(svc.requestPasswordReset('whoever@x.com', null).reason).toBe('password_login_disabled');
|
||||
expect((await svc.requestPasswordReset('whoever@x.com', null)).reason).toBe('password_login_disabled');
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
const { user } = createUser(testDb);
|
||||
svc.requestPasswordReset(user.email, null);
|
||||
svc.requestPasswordReset(user.email, null);
|
||||
svc.requestPasswordReset(user.email, null);
|
||||
expect(svc.requestPasswordReset(user.email, null).reason).toBe('throttled_per_email');
|
||||
await svc.requestPasswordReset(user.email, null);
|
||||
await svc.requestPasswordReset(user.email, null);
|
||||
await svc.requestPasswordReset(user.email, null);
|
||||
expect((await svc.requestPasswordReset(user.email, null)).reason).toBe('throttled_per_email');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ephemeral + demo helpers', () => {
|
||||
it('AUTH-DB-088: isDemoUser is true only for the demo email in demo mode', () => {
|
||||
it('AUTH-DB-088: isDemoUser is true only for the demo email in demo mode', async () => {
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
const { user: other } = createUser(testDb);
|
||||
expect(svc.isDemoUser(user.id)).toBe(false); // demo mode off
|
||||
expect(await svc.isDemoUser(user.id)).toBe(false); // demo mode off
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
expect(svc.isDemoUser(user.id)).toBe(true);
|
||||
expect(svc.isDemoUser(other.id)).toBe(false);
|
||||
expect(await svc.isDemoUser(user.id)).toBe(true);
|
||||
expect(await svc.isDemoUser(other.id)).toBe(false);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -1004,14 +1004,14 @@ describe('auth quirk fixes', () => {
|
||||
expect(used_count).toBe(0);
|
||||
});
|
||||
|
||||
it('AUTH-DB-091: a backup-code login burns the code and records the login as one atomic pair', () => {
|
||||
it('AUTH-DB-091: a backup-code login burns the code and records the login as one atomic pair', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const secret = authenticator.generateSecret();
|
||||
testDb.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ?, mfa_backup_codes = ? WHERE id = ?')
|
||||
.run('enc:' + secret, JSON.stringify([hashBackupCode('DDDD-4444')]), user.id);
|
||||
const interstitial = svc.loginUser({ email: user.email, password });
|
||||
const interstitial = await svc.loginUser({ email: user.email, password });
|
||||
|
||||
const result = svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: 'DDDD-4444' });
|
||||
const result = await svc.verifyMfaLogin({ mfa_token: interstitial.mfa_token, code: 'DDDD-4444' });
|
||||
|
||||
expect(typeof result.token).toBe('string');
|
||||
const row = testDb.prepare('SELECT mfa_backup_codes, login_count, last_login FROM users WHERE id = ?').get(user.id) as { mfa_backup_codes: string; login_count: number; last_login: string | null };
|
||||
@@ -1037,31 +1037,31 @@ describe('MCP token verification round-trips', () => {
|
||||
expect(tokens.verifyMcpToken('trek_no_such_token')).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-BR-003: verifyJwtToken round-trips a service-minted token through the pv gate', () => {
|
||||
it('AUTH-BR-003: verifyJwtToken round-trips a service-minted token through the pv gate', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const token = svc.generateToken({ id: user.id });
|
||||
expect(svc.verifyJwtToken(token)?.id).toBe(user.id);
|
||||
expect(svc.verifyJwtToken('not-a-jwt')).toBeNull();
|
||||
const token = await svc.generateToken({ id: user.id });
|
||||
expect((await svc.verifyJwtToken(token))?.id).toBe(user.id);
|
||||
expect(await svc.verifyJwtToken('not-a-jwt')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateToken remember claim (#1927)', () => {
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
it('AUTH-TOKEN-001: embeds remember and picks the matching lifetime when the caller chose', () => {
|
||||
it('AUTH-TOKEN-001: embeds remember and picks the matching lifetime when the caller chose', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const long = jwt.decode(svc.generateToken({ id: user.id }, true)) as { remember?: boolean; iat: number; exp: number };
|
||||
const long = jwt.decode(await svc.generateToken({ id: user.id }, true)) as { remember?: boolean; iat: number; exp: number };
|
||||
expect(long.remember).toBe(true);
|
||||
expect(long.exp - long.iat).toBe(2592000);
|
||||
|
||||
const short = jwt.decode(svc.generateToken({ id: user.id }, false)) as { remember?: boolean; iat: number; exp: number };
|
||||
const short = jwt.decode(await svc.generateToken({ id: user.id }, false)) as { remember?: boolean; iat: number; exp: number };
|
||||
expect(short.remember).toBe(false);
|
||||
expect(short.exp - short.iat).toBe(86400);
|
||||
});
|
||||
|
||||
it('AUTH-TOKEN-002: omits the claim entirely when the caller did not choose (legacy payload)', () => {
|
||||
it('AUTH-TOKEN-002: omits the claim entirely when the caller did not choose (legacy payload)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const decoded = jwt.decode(svc.generateToken({ id: user.id })) as { remember?: boolean; iat: number; exp: number };
|
||||
const decoded = jwt.decode(await svc.generateToken({ id: user.id })) as { remember?: boolean; iat: number; exp: number };
|
||||
expect('remember' in decoded).toBe(false);
|
||||
expect(decoded.exp - decoded.iat).toBe(86400);
|
||||
});
|
||||
|
||||
@@ -71,65 +71,65 @@ describe('extractToken', () => {
|
||||
});
|
||||
|
||||
describe('verifyJwtAndLoadUser', () => {
|
||||
it('AUTH-JWT-001: returns the user for a valid token, without password_version', () => {
|
||||
it('AUTH-JWT-001: returns the user for a valid token, without password_version', async () => {
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 });
|
||||
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(token)).toEqual({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user' });
|
||||
expect(await verifyJwtAndLoadUser(token)).toEqual({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user' });
|
||||
});
|
||||
|
||||
it('AUTH-JWT-002: returns null for a malformed token', () => {
|
||||
expect(verifyJwtAndLoadUser('invalid.jwt.token')).toBeNull();
|
||||
it('AUTH-JWT-002: returns null for a malformed token', async () => {
|
||||
expect(await verifyJwtAndLoadUser('invalid.jwt.token')).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-003: returns null when the user no longer exists', () => {
|
||||
it('AUTH-JWT-003: returns null when the user no longer exists', async () => {
|
||||
userRow(undefined);
|
||||
expect(verifyJwtAndLoadUser(jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' }))).toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-004: returns null for an expired token', () => {
|
||||
it('AUTH-JWT-004: returns null for an expired token', async () => {
|
||||
const expired = jwt.sign({ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 }, 'test-secret', { algorithm: 'HS256' });
|
||||
expect(verifyJwtAndLoadUser(expired)).toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(expired)).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-005: returns null for a token signed with the wrong secret', () => {
|
||||
expect(verifyJwtAndLoadUser(jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' }))).toBeNull();
|
||||
it('AUTH-JWT-005: returns null for a token signed with the wrong secret', async () => {
|
||||
expect(await verifyJwtAndLoadUser(jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-006: rejects a purpose-scoped mfa_login token even when the user is valid', () => {
|
||||
it('AUTH-JWT-006: rejects a purpose-scoped mfa_login token even when the user is valid', async () => {
|
||||
// Issued after the password check but before TOTP, signed with the same
|
||||
// secret. It must never authenticate an ordinary request.
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 });
|
||||
const mfaToken = jwt.sign({ id: 1, purpose: 'mfa_login' }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(mfaToken)).toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(mfaToken)).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-007: rejects a token whose password_version predates the user row', () => {
|
||||
it('AUTH-JWT-007: rejects a token whose password_version predates the user row', async () => {
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 2 });
|
||||
const stale = jwt.sign({ id: 1, pv: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(stale)).toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(stale)).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-008: accepts a token whose password_version matches', () => {
|
||||
it('AUTH-JWT-008: accepts a token whose password_version matches', async () => {
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 2 });
|
||||
const current = jwt.sign({ id: 1, pv: 2 }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(current)).not.toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(current)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-009: a pre-pv token still works against a never-reset user (both read as 0)', () => {
|
||||
it('AUTH-JWT-009: a pre-pv token still works against a never-reset user (both read as 0)', async () => {
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: null });
|
||||
const legacy = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(legacy)).not.toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(legacy)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-JWT-010: but a pre-pv token stops working once the user has reset', () => {
|
||||
it('AUTH-JWT-010: but a pre-pv token stops working once the user has reset', async () => {
|
||||
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 1 });
|
||||
const legacy = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
|
||||
expect(verifyJwtAndLoadUser(legacy)).toBeNull();
|
||||
expect(await verifyJwtAndLoadUser(legacy)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ interface Mocks {
|
||||
|
||||
/** The demo gate is off unless a case turns it on; every write tool asks it. */
|
||||
function makeMcp(m: Mocks = {}) {
|
||||
const auth: Partial<AuthService> = m.auth ?? { isDemoUser: () => false };
|
||||
const auth: Partial<AuthService> = m.auth ?? { isDemoUser: async () => false };
|
||||
return new DawarichMcp(
|
||||
(m.suggestions ?? {}) as DawarichSuggestionsService,
|
||||
(m.tracks ?? {}) as DawarichTracksService,
|
||||
@@ -221,7 +221,7 @@ describe('DawarichMcp surface', () => {
|
||||
// draws: reading is not a write. The gate is wired to answer "yes, demo"
|
||||
// here, so a check added to a read would turn both of these into refusals
|
||||
// and payload() would fail on the isError flag.
|
||||
const isDemoUser = vi.fn().mockReturnValue(true);
|
||||
const isDemoUser = vi.fn().mockResolvedValue(true);
|
||||
const listFn = vi.fn().mockReturnValue(list(1));
|
||||
const forTrip = vi.fn().mockResolvedValue({
|
||||
days: [], source: 'tracks', fetchedAt: '2026-05-02T09:00:00.000Z', pointCount: 0, truncated: false,
|
||||
@@ -431,30 +431,30 @@ describe('DawarichMcp list_dawarich_suggestions', () => {
|
||||
describe('DawarichMcp accept tools', () => {
|
||||
it.each(['acceptAsPlace', 'acceptAsJournalEntry', 'markBucketVisited', 'dismiss'])(
|
||||
'DAWARICH-MCP-040: %s refuses the demo account before the service is reached',
|
||||
(method) => {
|
||||
async (method) => {
|
||||
// One argument object for all four: the demo check runs before anything
|
||||
// reads the body, so the extra keys are exactly as irrelevant here as the
|
||||
// refusal makes them.
|
||||
const args = { suggestionId: 9, tripId: 2, journalId: 2 };
|
||||
const accept = vi.fn();
|
||||
const setState = vi.fn();
|
||||
const isDemoUser = vi.fn().mockReturnValue(true);
|
||||
const isDemoUser = vi.fn().mockResolvedValue(true);
|
||||
const mcp = makeMcp({ suggestions: { accept, setState }, auth: { isDemoUser } });
|
||||
|
||||
const call = (mcp as unknown as Record<string, (a: unknown, c: McpContext) => McpTextResult>)[method];
|
||||
expect(refusal(call.call(mcp, args, ctx))).toBe('Write operations are disabled in demo mode.');
|
||||
const call = (mcp as unknown as Record<string, (a: unknown, c: McpContext) => Promise<McpTextResult>>)[method];
|
||||
expect(refusal(await call.call(mcp, args, ctx))).toBe('Write operations are disabled in demo mode.');
|
||||
expect(isDemoUser).toHaveBeenCalledWith(7);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
expect(setState).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('DAWARICH-MCP-041: accepting as a place forwards every correction under target "place", with the id kept out of the body', () => {
|
||||
it('DAWARICH-MCP-041: accepting as a place forwards every correction under target "place", with the id kept out of the body', async () => {
|
||||
// suggestionId is the second argument, not a body field. Leaving it in the
|
||||
// body would put a key into DawarichAccept that nothing reads, and the next
|
||||
// reader would reasonably assume it was the one being accepted.
|
||||
const accept = vi.fn().mockReturnValue({ createdPlaceId: 5, createdJournalEntryId: null, bucketListItemId: null });
|
||||
const out = payload(makeMcp({ suggestions: { accept } }).acceptAsPlace(
|
||||
const out = payload(await makeMcp({ suggestions: { accept } }).acceptAsPlace(
|
||||
{ suggestionId: 9, tripId: 2, dayId: 4, name: 'Hafen', notes: 'windy', lat: 53.5, lng: 9.9 },
|
||||
ctx,
|
||||
));
|
||||
@@ -472,15 +472,15 @@ describe('DawarichMcp accept tools', () => {
|
||||
expect(out).toMatchObject({ createdPlaceId: 5 });
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-042: a bare accept sends only the target, so the service keeps its own defaults for the trip and the coordinates', () => {
|
||||
it('DAWARICH-MCP-042: a bare accept sends only the target, so the service keeps its own defaults for the trip and the coordinates', async () => {
|
||||
const accept = vi.fn().mockReturnValue({ createdPlaceId: 1 });
|
||||
makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx);
|
||||
await makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx);
|
||||
expect(accept).toHaveBeenCalledWith(7, 9, { target: 'place' });
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-043: accepting as a journal entry forwards target "journal" with the journey, the story and the corrected stamp', () => {
|
||||
it('DAWARICH-MCP-043: accepting as a journal entry forwards target "journal" with the journey, the story and the corrected stamp', async () => {
|
||||
const accept = vi.fn().mockReturnValue({ createdJournalEntryId: 11 });
|
||||
const out = payload(makeMcp({ suggestions: { accept } }).acceptAsJournalEntry(
|
||||
const out = payload(await makeMcp({ suggestions: { accept } }).acceptAsJournalEntry(
|
||||
{ suggestionId: 9, journalId: 3, name: 'The harbour', notes: 'It rained.', date: '2026-05-01', time: '09:30' },
|
||||
ctx,
|
||||
));
|
||||
@@ -496,15 +496,15 @@ describe('DawarichMcp accept tools', () => {
|
||||
expect(out).toMatchObject({ createdJournalEntryId: 11 });
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-044: ticking off a wish names it explicitly when the caller did', () => {
|
||||
it('DAWARICH-MCP-044: ticking off a wish names it explicitly when the caller did', async () => {
|
||||
const accept = vi.fn().mockReturnValue({ bucketListItemId: 8 });
|
||||
makeMcp({ suggestions: { accept } }).markBucketVisited({ suggestionId: 9, bucketListItemId: 8 }, ctx);
|
||||
await makeMcp({ suggestions: { accept } }).markBucketVisited({ suggestionId: 9, bucketListItemId: 8 }, ctx);
|
||||
expect(accept).toHaveBeenCalledWith(7, 9, { target: 'bucket_list', bucketListItemId: 8 });
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-045: an omitted wish stays undefined rather than being guessed here, and the service falls back to the matched one', () => {
|
||||
it('DAWARICH-MCP-045: an omitted wish stays undefined rather than being guessed here, and the service falls back to the matched one', async () => {
|
||||
const accept = vi.fn().mockReturnValue({ bucketListItemId: 2 });
|
||||
makeMcp({ suggestions: { accept } }).markBucketVisited({ suggestionId: 9 }, ctx);
|
||||
await makeMcp({ suggestions: { accept } }).markBucketVisited({ suggestionId: 9 }, ctx);
|
||||
expect(accept).toHaveBeenCalledWith(7, 9, { target: 'bucket_list', bucketListItemId: undefined });
|
||||
});
|
||||
|
||||
@@ -515,9 +515,9 @@ describe('DawarichMcp accept tools', () => {
|
||||
['trip_required', 'A trip is required to create a place', 400],
|
||||
])(
|
||||
'DAWARICH-MCP-046: the AcceptError %s comes back as a refusal an assistant can read (%s), not as an exception and not as the HTTP %i the REST half answers',
|
||||
(code, message, status) => {
|
||||
async (code, message, status) => {
|
||||
const accept = vi.fn(() => { throw new AcceptError(code, message, status); });
|
||||
const result = makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx);
|
||||
const result = await makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx);
|
||||
|
||||
expect(refusal(result)).toBe(message);
|
||||
// The status code is the REST half's vocabulary. MCP has isError and a
|
||||
@@ -527,46 +527,46 @@ describe('DawarichMcp accept tools', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('DAWARICH-MCP-047: the same shaping covers the journal and bucket-list tools, because run() is shared and a second copy would drift', () => {
|
||||
it('DAWARICH-MCP-047: the same shaping covers the journal and bucket-list tools, because run() is shared and a second copy would drift', async () => {
|
||||
const accept = vi.fn(() => { throw new AcceptError('not_found', 'Bucket-list entry not found', 404); });
|
||||
const mcp = makeMcp({ suggestions: { accept } });
|
||||
|
||||
expect(refusal(mcp.acceptAsJournalEntry({ suggestionId: 9, journalId: 1 }, ctx))).toBe('Bucket-list entry not found');
|
||||
expect(refusal(mcp.markBucketVisited({ suggestionId: 9 }, ctx))).toBe('Bucket-list entry not found');
|
||||
expect(refusal(await mcp.acceptAsJournalEntry({ suggestionId: 9, journalId: 1 }, ctx))).toBe('Bucket-list entry not found');
|
||||
expect(refusal(await mcp.markBucketVisited({ suggestionId: 9 }, ctx))).toBe('Bucket-list entry not found');
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-048: anything that is not an AcceptError propagates, because a failed write must never be reported as a success', () => {
|
||||
it('DAWARICH-MCP-048: anything that is not an AcceptError propagates, because a failed write must never be reported as a success', async () => {
|
||||
// A locked database, or a permission lookup that blew up, is not a refusal
|
||||
// the caller can act on. Flattening it into a text result would hand the
|
||||
// assistant a message with no isError flag on it to notice.
|
||||
const accept = vi.fn(() => { throw new Error('SQLITE_BUSY: database is locked'); });
|
||||
expect(() => makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx))
|
||||
.toThrow('SQLITE_BUSY: database is locked');
|
||||
await expect(makeMcp({ suggestions: { accept } }).acceptAsPlace({ suggestionId: 9 }, ctx))
|
||||
.rejects.toThrow('SQLITE_BUSY: database is locked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DawarichMcp dismiss_dawarich_suggestion', () => {
|
||||
it('DAWARICH-MCP-050: dismissed is the default, because that is what the tool is for', () => {
|
||||
it('DAWARICH-MCP-050: dismissed is the default, because that is what the tool is for', async () => {
|
||||
const updated = { id: 4, state: 'dismissed' };
|
||||
const setState = vi.fn().mockReturnValue(updated);
|
||||
const out = payload(makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 4 }, ctx));
|
||||
const out = payload(await makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 4 }, ctx));
|
||||
|
||||
expect(setState).toHaveBeenCalledWith(7, 4, 'dismissed');
|
||||
expect(out).toEqual({ suggestion: updated });
|
||||
});
|
||||
|
||||
it('DAWARICH-MCP-051: "new" puts a dismissed stay back into the review list', () => {
|
||||
it('DAWARICH-MCP-051: "new" puts a dismissed stay back into the review list', async () => {
|
||||
const setState = vi.fn().mockReturnValue({ id: 4, state: 'new' });
|
||||
makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 4, state: 'new' }, ctx);
|
||||
await makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 4, state: 'new' }, ctx);
|
||||
expect(setState).toHaveBeenCalledWith(7, 4, 'new');
|
||||
});
|
||||
|
||||
it("DAWARICH-MCP-052: somebody else's suggestion gets the answer a missing one gets: the service says null, the tool says not found", () => {
|
||||
it("DAWARICH-MCP-052: somebody else's suggestion gets the answer a missing one gets: the service says null, the tool says not found", async () => {
|
||||
// The service scopes its lookup by user_id, so null covers both cases and
|
||||
// the tool must not separate them. A different message for "exists but is
|
||||
// not yours" would let a caller enumerate other people's suggestion ids.
|
||||
const setState = vi.fn().mockReturnValue(null);
|
||||
expect(refusal(makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 999 }, ctx)))
|
||||
expect(refusal(await makeMcp({ suggestions: { setState } }).dismiss({ suggestionId: 999 }, ctx)))
|
||||
.toBe('Suggestion not found');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,6 +42,7 @@ import type { RealtimeService } from '../../../../src/nest/realtime/realtime.ser
|
||||
import { createTables } from '../../../../src/db/schema';
|
||||
import { runMigrations } from '../../../../src/db/migrations';
|
||||
import { createTrip, createUser } from '../../../helpers/factories';
|
||||
import { createTestUnitOfWork } from '../../../helpers/test-uow';
|
||||
|
||||
const link = (id: number): LinkRow => ({ id, provider_id: 'paperless' } as LinkRow);
|
||||
|
||||
@@ -421,12 +422,9 @@ describe('DocSyncJob and a provider switched off in the admin panel', () => {
|
||||
const addons = { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService;
|
||||
const registry = new DocumentProviderRegistry([paperless, nextcloud] as unknown as DocumentProvider[]);
|
||||
const config = new DocSyncConfigService(dbs, registry);
|
||||
const service = new DocSyncService(
|
||||
dbs, config, registry,
|
||||
{} as StorageService, {} as FilesService, new AllowedFileTypesService(dbs),
|
||||
{ broadcast: vi.fn() } as unknown as RealtimeService,
|
||||
addons,
|
||||
);
|
||||
// Built in beforeAll: DocSyncService now takes a UnitOfWork, and
|
||||
// createTestUnitOfWork is async — module-scope construction cannot await it.
|
||||
let service: DocSyncService;
|
||||
const registrar = { isEnabled: () => false } as unknown as CronRegistrarService;
|
||||
/** A job of its own per pass, so the interval never decides whether a tick runs. */
|
||||
const tick = () => new DocSyncJob(dbs, service, config, addons, registrar).tick();
|
||||
@@ -435,7 +433,14 @@ describe('DocSyncJob and a provider switched off in the admin panel', () => {
|
||||
testDb.prepare('UPDATE document_providers SET enabled = ? WHERE id = ?').run(on ? 1 : 0, id);
|
||||
const linkRow = (id: number) => testDb.prepare('SELECT * FROM trip_document_links WHERE id = ?').get(id);
|
||||
|
||||
beforeAll(() => {
|
||||
beforeAll(async () => {
|
||||
service = new DocSyncService(
|
||||
dbs, config, registry,
|
||||
{} as StorageService, {} as FilesService, new AllowedFileTypesService(dbs),
|
||||
{ broadcast: vi.fn() } as unknown as RealtimeService,
|
||||
addons,
|
||||
await createTestUnitOfWork(testDb),
|
||||
);
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
const ownerId = createUser(testDb, { username: 'owner', email: 'owner@docsync-job.test' }).user.id;
|
||||
|
||||
@@ -166,7 +166,7 @@ describe('DocSyncMcp access', () => {
|
||||
it('does not reach the sync service at all for a trip the user cannot see', async () => {
|
||||
const { mcp, sync, config } = makeMcp({ access: false, links: [link(1)] });
|
||||
await mcp.syncNow({ tripId: 3 }, ctx);
|
||||
mcp.listIssues({ tripId: 3 }, ctx);
|
||||
await mcp.listIssues({ tripId: 3 }, ctx);
|
||||
await mcp.getTripDocumentSync({ tripId: 3 }, ctx);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
expect(sync.status).not.toHaveBeenCalled();
|
||||
@@ -185,24 +185,24 @@ describe('get_trip_document_sync', () => {
|
||||
});
|
||||
|
||||
describe('list_trip_document_sync_issues', () => {
|
||||
it('says the trip is not configured rather than answering with an empty list', () => {
|
||||
it('says the trip is not configured rather than answering with an empty list', async () => {
|
||||
// An empty list and no connection at all read identically to an assistant,
|
||||
// and "everything is in step" is the wrong answer to give about documents
|
||||
// that were never being synced.
|
||||
const { mcp, sync } = makeMcp({ links: [] });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: false, issues: [] });
|
||||
expect(payload(await mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: false, issues: [] });
|
||||
expect(sync.issues).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports an empty list for a configured trip with nothing to decide', () => {
|
||||
it('reports an empty list for a configured trip with nothing to decide', async () => {
|
||||
const { mcp } = makeMcp({ links: [link(1)], issues: [] });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues: [] });
|
||||
expect(payload(await mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues: [] });
|
||||
});
|
||||
|
||||
it('passes the open issues through for a configured trip', () => {
|
||||
it('passes the open issues through for a configured trip', async () => {
|
||||
const issues = [{ id: 9, state: 'conflict', remote_name: 'boarding.pdf' }];
|
||||
const { mcp, sync } = makeMcp({ links: [link(1)], issues });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues });
|
||||
expect(payload(await mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues });
|
||||
expect(sync.issues).toHaveBeenCalledWith(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,6 +70,7 @@ import type { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import type { FilesService } from '../../../../src/nest/files/files.service';
|
||||
import type { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import type { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
|
||||
import { createTestUnitOfWork } from '../../../helpers/test-uow';
|
||||
|
||||
// ── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -303,7 +304,7 @@ const switchProvider = (id: string, on: boolean) =>
|
||||
// ── Suite ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('DocSyncService', () => {
|
||||
beforeAll(() => {
|
||||
beforeAll(async () => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
spoolDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-docsync-'));
|
||||
@@ -330,6 +331,7 @@ describe('DocSyncService', () => {
|
||||
new AllowedFileTypesService(dbs),
|
||||
realtime,
|
||||
addons as unknown as AddonsService,
|
||||
await createTestUnitOfWork(testDb),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -59,9 +59,9 @@ const trip = { id: 5, user_id: 42 } as never;
|
||||
|
||||
// The 404 "Trip not found" cases moved to trip-access.guard.test.ts with the check.
|
||||
describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => {
|
||||
it('GET / lists with the trash flag', () => {
|
||||
it('GET / lists with the trash flag', async () => {
|
||||
const listFiles = vi.fn().mockReturnValue([{ id: 1 }]);
|
||||
expect(fc(fsvc({ listFiles } as Partial<FilesService>)).list(user, trip, '5', 'true')).toEqual({ files: [{ id: 1 }] });
|
||||
expect(await fc(fsvc({ listFiles } as Partial<FilesService>)).list(user, trip, '5', 'true')).toEqual({ files: [{ id: 1 }] });
|
||||
expect(listFiles).toHaveBeenCalledWith('5', true);
|
||||
});
|
||||
|
||||
@@ -218,7 +218,7 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
|
||||
expect(await fc(fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), deleteFileLink } as Partial<FilesService>)).unlink(user, trip, '5', '9', '3')).toEqual({ success: true });
|
||||
expect(deleteFileLink).toHaveBeenCalledWith('3', '9');
|
||||
const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), getFileLinks: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<FilesService>);
|
||||
expect(fc(s).links(user, trip, '5', '9')).toEqual({ links: [{ id: 1 }] });
|
||||
expect(await fc(s).links(user, trip, '5', '9')).toEqual({ links: [{ id: 1 }] });
|
||||
});
|
||||
|
||||
it('the link routes resolve the file against :tripId, so a foreign file is 404', async () => {
|
||||
@@ -227,8 +227,7 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
|
||||
expect(await rejected(fc(unlinkSvc).unlink(user, trip, '5', '9', '3'))).toEqual({ status: 404, body: { error: 'File not found' } });
|
||||
expect(unlinkSvc.deleteFileLink).not.toHaveBeenCalled();
|
||||
const listSvc = foreign();
|
||||
// `links` is still a synchronous handler, so it throws rather than rejecting.
|
||||
expect(thrown(() => fc(listSvc).links(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
|
||||
expect(await rejected(fc(listSvc).links(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
|
||||
expect(listSvc.getFileLinks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
afterAll(async () => {
|
||||
testDb.close();
|
||||
bareDb.close();
|
||||
});
|
||||
@@ -104,8 +104,8 @@ function seedTrip() {
|
||||
return { user, trip };
|
||||
}
|
||||
|
||||
function makeFile(tripId: number, userId: number, overrides: Partial<{ filename: string; originalname: string; size: number; mimetype: string }> = {}, opts: Parameters<FilesService['createFile']>[3] = {}) {
|
||||
return svc.createFile(
|
||||
async function makeFile(tripId: number, userId: number, overrides: Partial<{ filename: string; originalname: string; size: number; mimetype: string }> = {}, opts: Parameters<FilesService['createFile']>[3] = {}) {
|
||||
return await svc.createFile(
|
||||
tripId,
|
||||
{ filename: 'stored-name.pdf', originalname: 'visa.pdf', size: 1234, mimetype: 'application/pdf', ...overrides },
|
||||
userId,
|
||||
@@ -166,55 +166,55 @@ describe('files.constants', () => {
|
||||
// against the single remaining query owner.
|
||||
|
||||
describe('AllowedFileTypesService.get', () => {
|
||||
it('FILE-SVC-006: returns the app_settings value when set', () => {
|
||||
it('FILE-SVC-006: returns the app_settings value when set', async () => {
|
||||
setAppSetting(testDb, 'allowed_file_types', 'pdf,txt');
|
||||
expect(new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe('pdf,txt');
|
||||
expect(await new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe('pdf,txt');
|
||||
});
|
||||
|
||||
it('FILE-SVC-007: returns the default when the row is absent', () => {
|
||||
expect(new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
it('FILE-SVC-007: returns the default when the row is absent', async () => {
|
||||
expect(await new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
|
||||
it('FILE-SVC-008: returns the default for an empty value (|| coercion, not ??)', () => {
|
||||
it('FILE-SVC-008: returns the default for an empty value (|| coercion, not ??)', async () => {
|
||||
setAppSetting(testDb, 'allowed_file_types', '');
|
||||
expect(new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
expect(await new AllowedFileTypesService(new DatabaseService(testDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
|
||||
it('FILE-SVC-009: returns the default when the query throws (no app_settings table)', () => {
|
||||
expect(new AllowedFileTypesService(new DatabaseService(bareDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
it('FILE-SVC-009: returns the default when the query throws (no app_settings table)', async () => {
|
||||
expect(await new AllowedFileTypesService(new DatabaseService(bareDb)).get()).toBe(DEFAULT_ALLOWED_EXTENSIONS);
|
||||
});
|
||||
});
|
||||
|
||||
// ── trip-scoped reads ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('getFileById / getDeletedFile', () => {
|
||||
it('FILE-SVC-010: getFileById is trip-scoped', () => {
|
||||
it('FILE-SVC-010: getFileById is trip-scoped', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const other = createTrip(testDb, user.id);
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(svc.getFileById(file.id, trip.id)?.id).toBe(file.id);
|
||||
expect(svc.getFileById(file.id, other.id)).toBeUndefined();
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
expect((await svc.getFileById(file.id, trip.id))?.id).toBe(file.id);
|
||||
expect(await svc.getFileById(file.id, other.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-011: getDeletedFile returns only soft-deleted rows', () => {
|
||||
it('FILE-SVC-011: getDeletedFile returns only soft-deleted rows', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(svc.getDeletedFile(file.id, trip.id)).toBeUndefined();
|
||||
svc.softDeleteFile(file.id);
|
||||
expect(svc.getDeletedFile(file.id, trip.id)?.id).toBe(file.id);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
expect(await svc.getDeletedFile(file.id, trip.id)).toBeUndefined();
|
||||
await svc.softDeleteFile(file.id);
|
||||
expect((await svc.getDeletedFile(file.id, trip.id))?.id).toBe(file.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listFiles', () => {
|
||||
it('FILE-SVC-012: active list excludes trash, is starred-first and carries the formatted shape', () => {
|
||||
it('FILE-SVC-012: active list excludes trash, is starred-first and carries the formatted shape', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
makeFile(trip.id, user.id, { originalname: 'plain.pdf' });
|
||||
const starred = makeFile(trip.id, user.id, { originalname: 'starred.pdf' });
|
||||
const trashed = makeFile(trip.id, user.id, { originalname: 'gone.pdf' });
|
||||
svc.toggleStarred(starred.id, 0);
|
||||
svc.softDeleteFile(trashed.id);
|
||||
await makeFile(trip.id, user.id, { originalname: 'plain.pdf' });
|
||||
const starred = await makeFile(trip.id, user.id, { originalname: 'starred.pdf' });
|
||||
const trashed = await makeFile(trip.id, user.id, { originalname: 'gone.pdf' });
|
||||
await svc.toggleStarred(starred.id, 0);
|
||||
await svc.softDeleteFile(trashed.id);
|
||||
|
||||
const files = svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
const files = await svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
expect(files.map((f) => f.id)).toHaveLength(2);
|
||||
expect(files[0].id).toBe(starred.id); // ORDER BY f.starred DESC first
|
||||
expect(files.map((f) => f.id)).not.toContain(trashed.id);
|
||||
@@ -223,27 +223,27 @@ describe('listFiles', () => {
|
||||
expect(files[0]).toHaveProperty('uploaded_by_avatar');
|
||||
});
|
||||
|
||||
it('FILE-SVC-013: trash list returns only soft-deleted files', () => {
|
||||
it('FILE-SVC-013: trash list returns only soft-deleted files', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const kept = makeFile(trip.id, user.id);
|
||||
const trashed = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(trashed.id);
|
||||
const kept = await makeFile(trip.id, user.id);
|
||||
const trashed = await makeFile(trip.id, user.id);
|
||||
await svc.softDeleteFile(trashed.id);
|
||||
|
||||
const trash = svc.listFiles(trip.id, true) as Record<string, unknown>[];
|
||||
const trash = await svc.listFiles(trip.id, true) as Record<string, unknown>[];
|
||||
expect(trash.map((f) => f.id)).toEqual([trashed.id]);
|
||||
expect(trash.map((f) => f.id)).not.toContain(kept.id);
|
||||
});
|
||||
|
||||
it('FILE-SVC-014: batches file_links and filters null targets by truthiness', () => {
|
||||
it('FILE-SVC-014: batches file_links and filters null targets by truthiness', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const linked = makeFile(trip.id, user.id);
|
||||
const bare = makeFile(trip.id, user.id);
|
||||
svc.createFileLink(linked.id, { reservation_id: reservation.id });
|
||||
svc.createFileLink(linked.id, { place_id: place.id });
|
||||
const linked = await makeFile(trip.id, user.id);
|
||||
const bare = await makeFile(trip.id, user.id);
|
||||
await svc.createFileLink(linked.id, { reservation_id: reservation.id });
|
||||
await svc.createFileLink(linked.id, { place_id: place.id });
|
||||
|
||||
const files = svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
const files = await svc.listFiles(trip.id, false) as Record<string, unknown>[];
|
||||
const linkedRow = files.find((f) => f.id === linked.id);
|
||||
const bareRow = files.find((f) => f.id === bare.id);
|
||||
expect(linkedRow.linked_reservation_ids).toEqual([reservation.id]);
|
||||
@@ -252,14 +252,14 @@ describe('listFiles', () => {
|
||||
expect(bareRow.linked_place_ids).toEqual([]);
|
||||
|
||||
const item = Number(testDb.prepare('INSERT INTO budget_items (trip_id, name) VALUES (?, ?)').run(trip.id, 'Dinner').lastInsertRowid);
|
||||
svc.createFileLink(linked.id, { budget_item_id: item });
|
||||
const withReceipt = (svc.listFiles(trip.id, false) as Record<string, unknown>[]).find((f) => f.id === linked.id);
|
||||
await svc.createFileLink(linked.id, { budget_item_id: item });
|
||||
const withReceipt = (await svc.listFiles(trip.id, false) as Record<string, unknown>[]).find((f) => f.id === linked.id);
|
||||
expect(withReceipt.linked_budget_item_ids).toEqual([item]);
|
||||
expect((svc.listFiles(trip.id, false) as Record<string, unknown>[]).find((f) => f.id === bare.id).linked_budget_item_ids).toEqual([]);
|
||||
expect((await svc.listFiles(trip.id, false) as Record<string, unknown>[]).find((f) => f.id === bare.id).linked_budget_item_ids).toEqual([]);
|
||||
|
||||
// The empty-trip guard skips the IN () batch entirely.
|
||||
const empty = createTrip(testDb, user.id);
|
||||
expect(svc.listFiles(empty.id, false)).toEqual([]);
|
||||
expect(await svc.listFiles(empty.id, false)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -270,41 +270,41 @@ describe('budget receipts', () => {
|
||||
return Number(testDb.prepare('INSERT INTO budget_items (trip_id, name) VALUES (?, ?)').run(tripId, 'Dinner').lastInsertRowid);
|
||||
}
|
||||
|
||||
it('FILE-SVC-040: an upload naming an expense gets its link row straight away', () => {
|
||||
it('FILE-SVC-040: an upload naming an expense gets its link row straight away', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const item = seedItem(trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { budget_item_id: item });
|
||||
const file = await makeFile(trip.id, user.id, {}, { budget_item_id: item });
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ? AND budget_item_id = ?').get(file.id, item)).toEqual({ c: 1 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-041: an upload without one writes no link at all', () => {
|
||||
it('FILE-SVC-041: an upload without one writes no link at all', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ?').get(file.id)).toEqual({ c: 0 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-042: updateFile attaches to an expense and detaches on a falsy id', () => {
|
||||
it('FILE-SVC-042: updateFile attaches to an expense and detaches on a falsy id', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const item = seedItem(trip.id);
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
|
||||
svc.updateFile(file.id, file, { budget_item_id: item });
|
||||
await svc.updateFile(file.id, file, { budget_item_id: item });
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ? AND budget_item_id = ?').get(file.id, item)).toEqual({ c: 1 });
|
||||
|
||||
// Sending it twice must not double the row.
|
||||
svc.updateFile(file.id, file, { budget_item_id: item });
|
||||
await svc.updateFile(file.id, file, { budget_item_id: item });
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ?').get(file.id)).toEqual({ c: 1 });
|
||||
|
||||
svc.updateFile(file.id, file, { budget_item_id: null });
|
||||
await svc.updateFile(file.id, file, { budget_item_id: null });
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ? AND budget_item_id IS NOT NULL').get(file.id)).toEqual({ c: 0 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-043: leaving budget_item_id out touches no link', () => {
|
||||
it('FILE-SVC-043: leaving budget_item_id out touches no link', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const item = seedItem(trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { budget_item_id: item });
|
||||
const file = await makeFile(trip.id, user.id, {}, { budget_item_id: item });
|
||||
|
||||
svc.updateFile(file.id, file, { description: 'renamed' });
|
||||
await svc.updateFile(file.id, file, { description: 'renamed' });
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM file_links WHERE file_id = ? AND budget_item_id = ?').get(file.id, item)).toEqual({ c: 1 });
|
||||
});
|
||||
});
|
||||
@@ -312,9 +312,9 @@ describe('budget receipts', () => {
|
||||
// ── createFile / updateFile / toggleStarred ───────────────────────────────────
|
||||
|
||||
describe('createFile', () => {
|
||||
it('FILE-SVC-015: coerces falsy opts to NULL (|| null) and re-selects the formatted row', () => {
|
||||
it('FILE-SVC-015: coerces falsy opts to NULL (|| null) and re-selects the formatted row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, {}, { place_id: '', reservation_id: undefined, description: '' });
|
||||
const file = await makeFile(trip.id, user.id, {}, { place_id: '', reservation_id: undefined, description: '' });
|
||||
const row = testDb.prepare('SELECT * FROM trip_files WHERE id = ?').get(file.id) as Record<string, unknown>;
|
||||
expect(row.place_id).toBeNull();
|
||||
expect(row.reservation_id).toBeNull();
|
||||
@@ -323,10 +323,10 @@ describe('createFile', () => {
|
||||
expect((file as unknown as Record<string, unknown>).uploaded_by_name).toBe(user.username);
|
||||
});
|
||||
|
||||
it('FILE-SVC-016: stores the provided metadata and links the reservation title through FILE_SELECT', () => {
|
||||
it('FILE-SVC-016: stores the provided metadata and links the reservation title through FILE_SELECT', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id, { title: 'Night train' });
|
||||
const file = makeFile(trip.id, user.id, { originalname: 'ticket.pdf', size: 99, mimetype: 'application/pdf' }, {
|
||||
const file = await makeFile(trip.id, user.id, { originalname: 'ticket.pdf', size: 99, mimetype: 'application/pdf' }, {
|
||||
reservation_id: String(reservation.id),
|
||||
description: 'the booking',
|
||||
});
|
||||
@@ -339,23 +339,23 @@ describe('createFile', () => {
|
||||
});
|
||||
|
||||
describe('updateFile', () => {
|
||||
it('FILE-SVC-017: undefined fields keep the current values', () => {
|
||||
it('FILE-SVC-017: undefined fields keep the current values', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { description: 'keep me', place_id: String(place.id) });
|
||||
const current = svc.getFileById(file.id, trip.id)!;
|
||||
const updated = svc.updateFile(file.id, current, {}) as Record<string, unknown>;
|
||||
const file = await makeFile(trip.id, user.id, {}, { description: 'keep me', place_id: String(place.id) });
|
||||
const current = await svc.getFileById(file.id, trip.id)!;
|
||||
const updated = await svc.updateFile(file.id, current, {}) as Record<string, unknown>;
|
||||
expect(updated.description).toBe('keep me');
|
||||
expect(updated.place_id).toBe(place.id);
|
||||
});
|
||||
|
||||
it("FILE-SVC-018: '' clears every field (|| null) — description matches createFile's coercion", () => {
|
||||
it("FILE-SVC-018: '' clears every field (|| null) — description matches createFile's coercion", async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id, {}, { description: 'old', place_id: String(place.id), reservation_id: String(reservation.id) });
|
||||
const current = svc.getFileById(file.id, trip.id)!;
|
||||
const updated = svc.updateFile(file.id, current, { description: '', place_id: '', reservation_id: null }) as Record<string, unknown>;
|
||||
const file = await makeFile(trip.id, user.id, {}, { description: 'old', place_id: String(place.id), reservation_id: String(reservation.id) });
|
||||
const current = await svc.getFileById(file.id, trip.id)!;
|
||||
const updated = await svc.updateFile(file.id, current, { description: '', place_id: '', reservation_id: null }) as Record<string, unknown>;
|
||||
expect(updated.description).toBeNull(); // '' → NULL on update too (post-migration fix: symmetric with createFile)
|
||||
expect(updated.place_id).toBeNull();
|
||||
expect(updated.reservation_id).toBeNull();
|
||||
@@ -363,28 +363,28 @@ describe('updateFile', () => {
|
||||
});
|
||||
|
||||
describe('toggleStarred / softDeleteFile / restoreFile', () => {
|
||||
it('FILE-SVC-019: toggleStarred flips 0→1 and 1→0', () => {
|
||||
it('FILE-SVC-019: toggleStarred flips 0→1 and 1→0', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const on = svc.toggleStarred(file.id, 0);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
const on = await svc.toggleStarred(file.id, 0);
|
||||
expect(on.starred).toBe(1);
|
||||
const off = svc.toggleStarred(file.id, on.starred);
|
||||
const off = await svc.toggleStarred(file.id, on.starred);
|
||||
expect(off.starred).toBe(0);
|
||||
});
|
||||
|
||||
it('FILE-SVC-020: softDeleteFile stamps deleted_at', () => {
|
||||
it('FILE-SVC-020: softDeleteFile stamps deleted_at', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(file.id);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
await svc.softDeleteFile(file.id);
|
||||
const row = testDb.prepare('SELECT deleted_at FROM trip_files WHERE id = ?').get(file.id) as Record<string, unknown>;
|
||||
expect(row.deleted_at).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FILE-SVC-021: restoreFile clears deleted_at and returns the formatted row', () => {
|
||||
it('FILE-SVC-021: restoreFile clears deleted_at and returns the formatted row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
svc.softDeleteFile(file.id);
|
||||
const restored = svc.restoreFile(file.id) as Record<string, unknown>;
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
await svc.softDeleteFile(file.id);
|
||||
const restored = await svc.restoreFile(file.id) as Record<string, unknown>;
|
||||
expect(restored.deleted_at).toBeNull();
|
||||
expect(restored.url).toBe(`/api/trips/${trip.id}/files/${file.id}/download`);
|
||||
});
|
||||
@@ -395,46 +395,46 @@ describe('toggleStarred / softDeleteFile / restoreFile', () => {
|
||||
describe('permanentDeleteFile', () => {
|
||||
it('FILE-SVC-022: deletes the storage object (idempotent on missing), then the DB row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, { filename: 'on-disk.pdf' });
|
||||
const file = await makeFile(trip.id, user.id, { filename: 'on-disk.pdf' });
|
||||
storageDelete.mockResolvedValue(undefined);
|
||||
await svc.permanentDeleteFile(svc.getFileById(file.id, trip.id) as TripFile);
|
||||
await svc.permanentDeleteFile(await svc.getFileById(file.id, trip.id) as TripFile);
|
||||
expect(storageDelete).toHaveBeenCalledWith('files', 'on-disk.pdf');
|
||||
expect(svc.getFileById(file.id, trip.id)).toBeUndefined();
|
||||
expect(await svc.getFileById(file.id, trip.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-023: a delete failure logs [files], rethrows and keeps the DB row', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id, { filename: 'stuck.pdf' });
|
||||
const file = await makeFile(trip.id, user.id, { filename: 'stuck.pdf' });
|
||||
const boom = new Error('EACCES');
|
||||
storageDelete.mockRejectedValue(boom);
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
await expect(svc.permanentDeleteFile(svc.getFileById(file.id, trip.id) as TripFile)).rejects.toThrow('EACCES');
|
||||
await expect(svc.permanentDeleteFile(await svc.getFileById(file.id, trip.id) as TripFile)).rejects.toThrow('EACCES');
|
||||
expect(err).toHaveBeenCalledWith('[files] unlink failed for stuck.pdf, keeping DB row:', boom);
|
||||
expect(svc.getFileById(file.id, trip.id)).toBeDefined();
|
||||
expect(await svc.getFileById(file.id, trip.id)).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('emptyTrash', () => {
|
||||
it('FILE-SVC-024: unlinks every trashed file and deletes their rows, returning the count', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const a = makeFile(trip.id, user.id, { filename: 'a.pdf' });
|
||||
const b = makeFile(trip.id, user.id, { filename: 'b.pdf' });
|
||||
const kept = makeFile(trip.id, user.id, { filename: 'kept.pdf' });
|
||||
svc.softDeleteFile(a.id);
|
||||
svc.softDeleteFile(b.id);
|
||||
const a = await makeFile(trip.id, user.id, { filename: 'a.pdf' });
|
||||
const b = await makeFile(trip.id, user.id, { filename: 'b.pdf' });
|
||||
const kept = await makeFile(trip.id, user.id, { filename: 'kept.pdf' });
|
||||
await svc.softDeleteFile(a.id);
|
||||
await svc.softDeleteFile(b.id);
|
||||
storageDelete.mockResolvedValue(undefined);
|
||||
|
||||
await expect(svc.emptyTrash(trip.id)).resolves.toBe(2);
|
||||
expect(svc.listFiles(trip.id, true)).toEqual([]);
|
||||
expect(svc.getFileById(kept.id, trip.id)).toBeDefined();
|
||||
expect(await svc.listFiles(trip.id, true)).toEqual([]);
|
||||
expect(await svc.getFileById(kept.id, trip.id)).toBeDefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-025: a partial unlink failure keeps the failed row, swallows the error and counts only successes', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const good = makeFile(trip.id, user.id, { filename: 'good.pdf' });
|
||||
const bad = makeFile(trip.id, user.id, { filename: 'bad.pdf' });
|
||||
svc.softDeleteFile(good.id);
|
||||
svc.softDeleteFile(bad.id);
|
||||
const good = await makeFile(trip.id, user.id, { filename: 'good.pdf' });
|
||||
const bad = await makeFile(trip.id, user.id, { filename: 'bad.pdf' });
|
||||
await svc.softDeleteFile(good.id);
|
||||
await svc.softDeleteFile(bad.id);
|
||||
const boom = new Error('EBUSY');
|
||||
storageDelete.mockImplementation((_category: string, name: string) =>
|
||||
name.includes('bad.pdf') ? Promise.reject(boom) : Promise.resolve()
|
||||
@@ -443,8 +443,8 @@ describe('emptyTrash', () => {
|
||||
|
||||
await expect(svc.emptyTrash(trip.id)).resolves.toBe(1);
|
||||
expect(err).toHaveBeenCalledWith('[files] unlink failed for bad.pdf, keeping DB row:', boom);
|
||||
expect(svc.getFileById(good.id, trip.id)).toBeUndefined();
|
||||
expect(svc.getDeletedFile(bad.id, trip.id)).toBeDefined();
|
||||
expect(await svc.getFileById(good.id, trip.id)).toBeUndefined();
|
||||
expect(await svc.getDeletedFile(bad.id, trip.id)).toBeDefined();
|
||||
});
|
||||
|
||||
it('FILE-SVC-026: an empty trash resolves to 0 without touching storage', async () => {
|
||||
@@ -464,7 +464,7 @@ describe('findForeignLinkTarget', () => {
|
||||
return { user, mine, foreign };
|
||||
}
|
||||
|
||||
it('FILE-SVC-027: flags each foreign target kind and passes same-trip ids', () => {
|
||||
it('FILE-SVC-027: flags each foreign target kind and passes same-trip ids', async () => {
|
||||
const { mine, foreign } = twoTrips();
|
||||
const foreignRes = createReservation(testDb, foreign.id);
|
||||
const foreignPlace = createPlace(testDb, foreign.id);
|
||||
@@ -472,27 +472,27 @@ describe('findForeignLinkTarget', () => {
|
||||
const foreignAssignment = createDayAssignment(testDb, foreignDay.id, createPlace(testDb, foreign.id).id);
|
||||
const myRes = createReservation(testDb, mine.id);
|
||||
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id })).toBe('reservation_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { place_id: foreignPlace.id })).toBe('place_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { assignment_id: foreignAssignment.id })).toBe('assignment_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: myRes.id })).toBeNull();
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id })).toBe('reservation_id');
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { place_id: foreignPlace.id })).toBe('place_id');
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { assignment_id: foreignAssignment.id })).toBe('assignment_id');
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: myRes.id })).toBeNull();
|
||||
|
||||
// A receipt may only point at an expense on the same trip.
|
||||
const foreignItem = Number(testDb.prepare('INSERT INTO budget_items (trip_id, name) VALUES (?, ?)').run(foreign.id, 'Foreign').lastInsertRowid);
|
||||
const myItem = Number(testDb.prepare('INSERT INTO budget_items (trip_id, name) VALUES (?, ?)').run(mine.id, 'Mine').lastInsertRowid);
|
||||
expect(svc.findForeignLinkTarget(mine.id, { budget_item_id: foreignItem })).toBe('budget_item_id');
|
||||
expect(svc.findForeignLinkTarget(mine.id, { budget_item_id: myItem })).toBeNull();
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { budget_item_id: foreignItem })).toBe('budget_item_id');
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { budget_item_id: myItem })).toBeNull();
|
||||
});
|
||||
|
||||
it('FILE-SVC-028: falsy ids are skipped (they clear the link) and reservation is checked first', () => {
|
||||
it('FILE-SVC-028: falsy ids are skipped (they clear the link) and reservation is checked first', async () => {
|
||||
const { mine, foreign } = twoTrips();
|
||||
const foreignRes = createReservation(testDb, foreign.id);
|
||||
const foreignPlace = createPlace(testDb, foreign.id);
|
||||
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: 0, place_id: null, assignment_id: undefined })).toBeNull();
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: '' })).toBeNull();
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: 0, place_id: null, assignment_id: undefined })).toBeNull();
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: '' })).toBeNull();
|
||||
// Both foreign — the reservation check runs before the place check.
|
||||
expect(svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id, place_id: foreignPlace.id })).toBe('reservation_id');
|
||||
expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id, place_id: foreignPlace.id })).toBe('reservation_id');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -511,89 +511,89 @@ type FileLinkRow = {
|
||||
};
|
||||
|
||||
describe('createFileLink / deleteFileLink / getFileLinks', () => {
|
||||
it('FILE-SVC-029: inserts with || null coercion, dedupes via INSERT OR IGNORE and returns the re-select', () => {
|
||||
it('FILE-SVC-029: inserts with || null coercion, dedupes via INSERT OR IGNORE and returns the re-select', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id, { title: 'Ferry' });
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
|
||||
const links = svc.createFileLink(file.id, { reservation_id: reservation.id, place_id: '' }) as FileLinkRow[];
|
||||
const links = await svc.createFileLink(file.id, { reservation_id: reservation.id, place_id: '' }) as FileLinkRow[];
|
||||
expect(links).toHaveLength(1);
|
||||
expect(links[0].reservation_id).toBe(reservation.id);
|
||||
expect(links[0].place_id).toBeNull();
|
||||
|
||||
const again = svc.createFileLink(file.id, { reservation_id: reservation.id }) as FileLinkRow[];
|
||||
const again = await svc.createFileLink(file.id, { reservation_id: reservation.id }) as FileLinkRow[];
|
||||
expect(again).toHaveLength(1); // UNIQUE(file_id, reservation_id) + OR IGNORE
|
||||
|
||||
const hydrated = svc.getFileLinks(file.id) as FileLinkRow[];
|
||||
const hydrated = await svc.getFileLinks(file.id) as FileLinkRow[];
|
||||
expect(hydrated[0].reservation_title).toBe('Ferry');
|
||||
});
|
||||
|
||||
it('FILE-SVC-030: an insert error propagates (post-migration fix: no silent swallow)', () => {
|
||||
it('FILE-SVC-030: an insert error propagates (post-migration fix: no silent swallow)', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const file = makeFile(trip.id, user.id);
|
||||
expect(() => svc.createFileLink(file.id, { reservation_id: { bad: true } as never })).toThrow();
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
await expect(svc.createFileLink(file.id, { reservation_id: { bad: true } as never })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('FILE-SVC-031: deleteFileLink is scoped to (id AND file_id)', () => {
|
||||
it('FILE-SVC-031: deleteFileLink is scoped to (id AND file_id)', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const file = makeFile(trip.id, user.id);
|
||||
const other = makeFile(trip.id, user.id);
|
||||
const [link] = svc.createFileLink(file.id, { reservation_id: reservation.id }) as FileLinkRow[];
|
||||
const file = await makeFile(trip.id, user.id);
|
||||
const other = await makeFile(trip.id, user.id);
|
||||
const [link] = await svc.createFileLink(file.id, { reservation_id: reservation.id }) as FileLinkRow[];
|
||||
|
||||
svc.deleteFileLink(link.id, other.id); // wrong file — no-op
|
||||
expect(svc.getFileLinks(file.id)).toHaveLength(1);
|
||||
svc.deleteFileLink(link.id, file.id);
|
||||
expect(svc.getFileLinks(file.id)).toHaveLength(0);
|
||||
await svc.deleteFileLink(link.id, other.id); // wrong file — no-op
|
||||
expect(await svc.getFileLinks(file.id)).toHaveLength(1);
|
||||
await svc.deleteFileLink(link.id, file.id);
|
||||
expect(await svc.getFileLinks(file.id)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── download auth & glue ──────────────────────────────────────────────────────
|
||||
|
||||
describe('authenticateDownload', () => {
|
||||
it('FILE-SVC-032: a valid session cookie wins over a bearer token', () => {
|
||||
it('FILE-SVC-032: a valid session cookie wins over a bearer token', async () => {
|
||||
verifyJwtAndLoadUser.mockReturnValue({ id: 42 });
|
||||
const result = svc.authenticateDownload(req({ cookie: 'cookie-jwt', bearer: 'bearer-jwt' }));
|
||||
const result = await svc.authenticateDownload(req({ cookie: 'cookie-jwt', bearer: 'bearer-jwt' }));
|
||||
expect(result).toEqual({ userId: 42 });
|
||||
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('cookie-jwt');
|
||||
});
|
||||
|
||||
it('FILE-SVC-033: a bearer token is used when no cookie is present; invalid JWTs 401', () => {
|
||||
it('FILE-SVC-033: a bearer token is used when no cookie is present; invalid JWTs 401', async () => {
|
||||
verifyJwtAndLoadUser.mockReturnValue({ id: 7 });
|
||||
expect(svc.authenticateDownload(req({ bearer: 'bearer-jwt' }))).toEqual({ userId: 7 });
|
||||
expect(await svc.authenticateDownload(req({ bearer: 'bearer-jwt' }))).toEqual({ userId: 7 });
|
||||
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('bearer-jwt');
|
||||
|
||||
verifyJwtAndLoadUser.mockReturnValue(null);
|
||||
expect(svc.authenticateDownload(req({ bearer: 'stale' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
expect(await svc.authenticateDownload(req({ bearer: 'stale' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-034: a ?token= ephemeral token is consumed with the download purpose', () => {
|
||||
it('FILE-SVC-034: a ?token= ephemeral token is consumed with the download purpose', async () => {
|
||||
consumeEphemeralToken.mockReturnValue(9);
|
||||
expect(svc.authenticateDownload(req({ token: 'eph' }))).toEqual({ userId: 9 });
|
||||
expect(await svc.authenticateDownload(req({ token: 'eph' }))).toEqual({ userId: 9 });
|
||||
expect(consumeEphemeralToken).toHaveBeenCalledWith('eph', 'download');
|
||||
|
||||
consumeEphemeralToken.mockReturnValue(null);
|
||||
expect(svc.authenticateDownload(req({ token: 'spent' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
expect(await svc.authenticateDownload(req({ token: 'spent' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
|
||||
});
|
||||
|
||||
it('FILE-SVC-035: no credentials at all is a 401 Authentication required', () => {
|
||||
expect(svc.authenticateDownload(req({}))).toEqual({ error: 'Authentication required', status: 401 });
|
||||
it('FILE-SVC-035: no credentials at all is a 401 Authentication required', async () => {
|
||||
expect(await svc.authenticateDownload(req({}))).toEqual({ error: 'Authentication required', status: 401 });
|
||||
expect(verifyJwtAndLoadUser).not.toHaveBeenCalled();
|
||||
expect(consumeEphemeralToken).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyTripAccess / can / files.bridge', () => {
|
||||
it('FILE-SVC-036: verifyTripAccess resolves owner and member, refuses strangers', () => {
|
||||
it('FILE-SVC-036: verifyTripAccess resolves owner and member, refuses strangers', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, member.id);
|
||||
|
||||
expect(svc.verifyTripAccess(trip.id, owner.id)?.id).toBe(trip.id);
|
||||
expect(svc.verifyTripAccess(trip.id, member.id)).toBeDefined();
|
||||
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
|
||||
expect((await svc.verifyTripAccess(trip.id, owner.id))?.id).toBe(trip.id);
|
||||
expect(await svc.verifyTripAccess(trip.id, member.id)).toBeDefined();
|
||||
expect(await svc.verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
|
||||
});
|
||||
|
||||
it('FILE-SVC-037: can() forwards to checkPermission with the shared-trip flag', async () => {
|
||||
@@ -611,13 +611,13 @@ describe('verifyTripAccess / can / files.bridge', () => {
|
||||
expect(checkPermission).toHaveBeenLastCalledWith('file_upload', 'user', user.id, user.id, false);
|
||||
});
|
||||
|
||||
it('FILE-SVC-038: the allowed-extension list is a live read, not a boot snapshot', () => {
|
||||
it('FILE-SVC-038: the allowed-extension list is a live read, not a boot snapshot', async () => {
|
||||
// Was asserted against files.bridge, which built its own FilesService. The
|
||||
// list moved to a leaf service the multer factories inject, and the property
|
||||
// that matters is unchanged: an admin editing the list in settings applies
|
||||
// to the next upload, with no invalidation wiring.
|
||||
const allowed = new AllowedFileTypesService(new DatabaseService(testDb));
|
||||
setAppSetting(testDb, 'allowed_file_types', 'md,markdown');
|
||||
expect(allowed.get()).toBe('md,markdown');
|
||||
expect(await allowed.get()).toBe('md,markdown');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -54,9 +54,9 @@ function ctx(request: Record<string, unknown>) {
|
||||
} as never;
|
||||
}
|
||||
|
||||
const thrown = (run: () => unknown) => {
|
||||
const thrown = async (run: () => unknown) => {
|
||||
try {
|
||||
run();
|
||||
await run();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(HttpException);
|
||||
const e = err as HttpException;
|
||||
@@ -68,9 +68,9 @@ const thrown = (run: () => unknown) => {
|
||||
const ENFORCED: Rows = { requireMfa: 'true', mfaEnabled: 0 };
|
||||
|
||||
describe('MfaPolicyGuard', () => {
|
||||
it('MFA-001: refuses a user without MFA while the policy is on, with the legacy body', () => {
|
||||
it('MFA-001: refuses a user without MFA while the policy is on, with the legacy body', async () => {
|
||||
const { guard } = makeGuard(ENFORCED);
|
||||
expect(thrown(() => guard.canActivate(ctx({ user })))).toEqual({
|
||||
expect(await thrown(() => guard.canActivate(ctx({ user })))).toEqual({
|
||||
status: 403,
|
||||
body: {
|
||||
error: 'Two-factor authentication is required. Complete setup in Settings.',
|
||||
@@ -79,68 +79,68 @@ describe('MfaPolicyGuard', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('MFA-002: lets a user with TOTP through', () => {
|
||||
it('MFA-002: lets a user with TOTP through', async () => {
|
||||
const { guard } = makeGuard({ requireMfa: 'true', mfaEnabled: 1 });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-003: a user-verified passkey satisfies the policy like TOTP does', () => {
|
||||
it('MFA-003: a user-verified passkey satisfies the policy like TOTP does', async () => {
|
||||
const { guard } = makeGuard({ requireMfa: 'true', mfaEnabled: 0, hasPasskey: true });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-004: does nothing when the policy is off, and never reads the users row', () => {
|
||||
it('MFA-004: does nothing when the policy is off, and never reads the users row', async () => {
|
||||
const { guard, get } = makeGuard({ requireMfa: 'false', mfaEnabled: 0 });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(get.mock.calls.some((c) => String(c[0]).includes('FROM users'))).toBe(false);
|
||||
});
|
||||
|
||||
it('MFA-005: does nothing when the setting row is absent at all', () => {
|
||||
it('MFA-005: does nothing when the setting row is absent at all', async () => {
|
||||
const { guard } = makeGuard({ mfaEnabled: 0 });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-006: an anonymous request is not the policy business', () => {
|
||||
it('MFA-006: an anonymous request is not the policy business', async () => {
|
||||
const { guard, get } = makeGuard(ENFORCED);
|
||||
expect(guard.canActivate(ctx({}))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({}))).toBe(true);
|
||||
expect(get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MFA-007: the demo account is exempt while demo mode is on', () => {
|
||||
it('MFA-007: the demo account is exempt while demo mode is on', async () => {
|
||||
const demoUser = { id: 1, email: DEMO_EMAIL_PRIMARY, role: 'user' } as User;
|
||||
expect(makeGuard(ENFORCED, {}, true).guard.canActivate(ctx({ user: demoUser }))).toBe(true);
|
||||
expect(await makeGuard(ENFORCED, {}, true).guard.canActivate(ctx({ user: demoUser }))).toBe(true);
|
||||
// …and not otherwise.
|
||||
expect(thrown(() => makeGuard(ENFORCED, {}, false).guard.canActivate(ctx({ user: demoUser })))).toEqual({
|
||||
expect(await thrown(() => makeGuard(ENFORCED, {}, false).guard.canActivate(ctx({ user: demoUser })))).toEqual({
|
||||
status: 403,
|
||||
body: expect.objectContaining({ code: 'MFA_REQUIRED' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('MFA-008: a user row that vanished mid-request is let through, not 403d', () => {
|
||||
it('MFA-008: a user row that vanished mid-request is let through, not 403d', async () => {
|
||||
const { guard } = makeGuard({ requireMfa: 'true', userMissing: true });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-009: @MfaExempt is the way out — setup would be unreachable otherwise', () => {
|
||||
it('MFA-009: @MfaExempt is the way out — setup would be unreachable otherwise', async () => {
|
||||
const { guard } = makeGuard(ENFORCED, { exempt: true });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-010: it reads req.user rather than verifying the token again', () => {
|
||||
it('MFA-010: it reads req.user rather than verifying the token again', async () => {
|
||||
// The middleware this replaces called jwt.verify and SELECTed the users row a
|
||||
// second time on every /api request, then discarded the result.
|
||||
const { guard, get } = makeGuard({ requireMfa: 'true', mfaEnabled: 1 });
|
||||
guard.canActivate(ctx({ user, headers: { authorization: 'Bearer nonsense' } }));
|
||||
await guard.canActivate(ctx({ user, headers: { authorization: 'Bearer nonsense' } }));
|
||||
expect(get.mock.calls.map((c) => c[0]).every((sql) => !String(sql).includes('password_version'))).toBe(true);
|
||||
});
|
||||
|
||||
it('MFA-011: a @Public route no longer 403s a logged-in user without MFA', () => {
|
||||
it('MFA-011: a @Public route no longer 403s a logged-in user without MFA', async () => {
|
||||
// The correction. /api/config, /api/help/*, the public journey and share
|
||||
// routes and /api/health/features all answered a stranger fine and answered
|
||||
// this user with a 403, because they were added after the middleware path
|
||||
// lists were written and nobody noticed.
|
||||
const { guard, get } = makeGuard(ENFORCED, { public: true });
|
||||
expect(guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(await guard.canActivate(ctx({ user }))).toBe(true);
|
||||
expect(get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -1178,12 +1178,12 @@ describe('verifyIdToken', () => {
|
||||
// ── wrapper methods (carried over from the delegation-shim suite) ────────────
|
||||
|
||||
describe('wrapper methods', () => {
|
||||
it('OIDC-SVC-046: oidcLoginEnabled reads the resolved auth toggle', () => {
|
||||
it('OIDC-SVC-046: oidcLoginEnabled reads the resolved auth toggle', async () => {
|
||||
const spy = vi.spyOn(auth, 'resolveAuthToggles');
|
||||
spy.mockReturnValue({ oidc_login: true } as ReturnType<AuthService['resolveAuthToggles']>);
|
||||
expect(svc.oidcLoginEnabled()).toBe(true);
|
||||
spy.mockReturnValue({ oidc_login: false } as ReturnType<AuthService['resolveAuthToggles']>);
|
||||
expect(svc.oidcLoginEnabled()).toBe(false);
|
||||
spy.mockResolvedValue({ oidc_login: true } as Awaited<ReturnType<AuthService['resolveAuthToggles']>>);
|
||||
expect(await svc.oidcLoginEnabled()).toBe(true);
|
||||
spy.mockResolvedValue({ oidc_login: false } as Awaited<ReturnType<AuthService['resolveAuthToggles']>>);
|
||||
expect(await svc.oidcLoginEnabled()).toBe(false);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
@@ -1222,22 +1222,22 @@ describe('OIDC settings', () => {
|
||||
expect(result.discovery_url).toBe('');
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', () => {
|
||||
svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
|
||||
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', async () => {
|
||||
await svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
|
||||
const result = svc.getOidcSettings() as any;
|
||||
expect(result.issuer).toBe('https://auth.example.com');
|
||||
expect(result.client_id).toBe('my-client');
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
|
||||
svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
|
||||
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', async () => {
|
||||
await svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
|
||||
const result = svc.getOidcSettings() as any;
|
||||
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
|
||||
expect(result.oidc_only).toBe(false);
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', () => {
|
||||
const result = svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any;
|
||||
it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', async () => {
|
||||
const result = await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any;
|
||||
expect(result.success).toBe(true);
|
||||
const settings = svc.getOidcSettings();
|
||||
expect(settings).toMatchObject({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' });
|
||||
@@ -1245,31 +1245,31 @@ describe('OIDC settings', () => {
|
||||
});
|
||||
|
||||
describe('OIDC settings — the lockout guard', () => {
|
||||
it('OIDC-SETTINGS-050 refuses to clear the config while password login is off', () => {
|
||||
it('OIDC-SETTINGS-050 refuses to clear the config while password login is off', async () => {
|
||||
// Clearing the issuer with password login disabled locks every user out of the
|
||||
// instance: no SSO to log in through, and no password form either.
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: false } as never);
|
||||
expect(svc.updateOidcSettings({ issuer: '', client_id: 'x' })).toMatchObject({ status: 400 });
|
||||
expect(svc.updateOidcSettings({ issuer: 'x', client_id: '' })).toMatchObject({ status: 400 });
|
||||
expect((svc.updateOidcSettings({ issuer: '', client_id: '' }) as { error?: string }).error).toMatch(/password login/i);
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockResolvedValue({ password_login: false } as never);
|
||||
expect(await svc.updateOidcSettings({ issuer: '', client_id: 'x' })).toMatchObject({ status: 400 });
|
||||
expect(await svc.updateOidcSettings({ issuer: 'x', client_id: '' })).toMatchObject({ status: 400 });
|
||||
expect(((await svc.updateOidcSettings({ issuer: '', client_id: '' })) as { error?: string }).error).toMatch(/password login/i);
|
||||
toggles.mockRestore();
|
||||
});
|
||||
|
||||
it('OIDC-SETTINGS-051 allows the same clear once password login is back on', () => {
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: true } as never);
|
||||
expect(svc.updateOidcSettings({ issuer: '', client_id: '' })).toEqual({ success: true });
|
||||
it('OIDC-SETTINGS-051 allows the same clear once password login is back on', async () => {
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockResolvedValue({ password_login: true } as never);
|
||||
expect(await svc.updateOidcSettings({ issuer: '', client_id: '' })).toEqual({ success: true });
|
||||
toggles.mockRestore();
|
||||
});
|
||||
|
||||
it('OIDC-SETTINGS-052 an omitted client_secret keeps the stored one, an empty string clears it', () => {
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: true } as never);
|
||||
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: 'shh' });
|
||||
it('OIDC-SETTINGS-052 an omitted client_secret keeps the stored one, an empty string clears it', async () => {
|
||||
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockResolvedValue({ password_login: true } as never);
|
||||
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: 'shh' });
|
||||
expect(svc.getOidcSettings().client_secret_set).toBe(true);
|
||||
// Omitted: the write skips the column entirely rather than blanking it, which is
|
||||
// what lets the admin panel save the form without re-typing the secret.
|
||||
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c' });
|
||||
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c' });
|
||||
expect(svc.getOidcSettings().client_secret_set).toBe(true);
|
||||
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: '' });
|
||||
await svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: '' });
|
||||
expect(svc.getOidcSettings().client_secret_set).toBe(false);
|
||||
toggles.mockRestore();
|
||||
});
|
||||
|
||||
@@ -125,7 +125,7 @@ beforeAll(async () => {
|
||||
new EphemeralTokenService(),
|
||||
new AllowedFileTypesService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb),
|
||||
);
|
||||
svc = new PasskeyService(new DatabaseService(testDb), auth, webauthn);
|
||||
svc = new PasskeyService(new DatabaseService(testDb), auth, webauthn, await createTestUnitOfWork(testDb));
|
||||
});
|
||||
|
||||
const CFG = { rpID: 'trek.example.com', rpName: 'TREK', origins: ['https://trek.example.com'], explicitOrigins: false };
|
||||
@@ -660,7 +660,7 @@ describe('passkeyLoginVerify', () => {
|
||||
// ── listPasskeys ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('listPasskeys', () => {
|
||||
it('PASSKEY-SVC-025: lists newest-first with backed_up remapped to a boolean', () => {
|
||||
it('PASSKEY-SVC-025: lists newest-first with backed_up remapped to a boolean', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
testDb.prepare(
|
||||
@@ -669,7 +669,7 @@ describe('listPasskeys', () => {
|
||||
).run(user.id, user.id);
|
||||
insertCredential(other.id);
|
||||
|
||||
const list = svc.listPasskeys(user.id);
|
||||
const list = await svc.listPasskeys(user.id);
|
||||
expect(list.map((c) => c.name)).toEqual(['New', 'Old']);
|
||||
expect(list[0]).toEqual({
|
||||
id: expect.any(Number),
|
||||
@@ -686,47 +686,47 @@ describe('listPasskeys', () => {
|
||||
// ── renamePasskey ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('renamePasskey', () => {
|
||||
it('PASSKEY-SVC-026: rejects a missing, non-string or whitespace-only name', () => {
|
||||
it('PASSKEY-SVC-026: rejects a missing, non-string or whitespace-only name', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cred = insertCredential(user.id);
|
||||
expect(svc.renamePasskey(user.id, String(cred.id), undefined)).toEqual({ error: 'Name is required', status: 400 });
|
||||
expect(svc.renamePasskey(user.id, String(cred.id), 42)).toEqual({ error: 'Name is required', status: 400 });
|
||||
expect(svc.renamePasskey(user.id, String(cred.id), ' ')).toEqual({ error: 'Name is required', status: 400 });
|
||||
expect(await svc.renamePasskey(user.id, String(cred.id), undefined)).toEqual({ error: 'Name is required', status: 400 });
|
||||
expect(await svc.renamePasskey(user.id, String(cred.id), 42)).toEqual({ error: 'Name is required', status: 400 });
|
||||
expect(await svc.renamePasskey(user.id, String(cred.id), ' ')).toEqual({ error: 'Name is required', status: 400 });
|
||||
});
|
||||
|
||||
it('PASSKEY-SVC-027: renames (trimmed, capped at 60) and 404s on foreign or unknown ids', () => {
|
||||
it('PASSKEY-SVC-027: renames (trimmed, capped at 60) and 404s on foreign or unknown ids', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const cred = insertCredential(user.id);
|
||||
|
||||
expect(svc.renamePasskey(user.id, String(cred.id), ` ${'n'.repeat(80)} `)).toEqual({ success: true });
|
||||
expect(await svc.renamePasskey(user.id, String(cred.id), ` ${'n'.repeat(80)} `)).toEqual({ success: true });
|
||||
const row = testDb.prepare('SELECT name FROM webauthn_credentials WHERE id = ?').get(cred.id) as { name: string };
|
||||
expect(row.name).toBe('n'.repeat(60));
|
||||
|
||||
expect(svc.renamePasskey(other.id, String(cred.id), 'Steal')).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
expect(svc.renamePasskey(user.id, '999999', 'Ghost')).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
expect(await svc.renamePasskey(other.id, String(cred.id), 'Steal')).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
expect(await svc.renamePasskey(user.id, '999999', 'Ghost')).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── deletePasskey ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('deletePasskey', () => {
|
||||
it('PASSKEY-SVC-028: requires the current password (missing, wrong, or no hash all 401)', () => {
|
||||
it('PASSKEY-SVC-028: requires the current password (missing, wrong, or no hash all 401)', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const cred = insertCredential(user.id);
|
||||
expect(svc.deletePasskey(user.id, String(cred.id), undefined)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
expect(svc.deletePasskey(user.id, String(cred.id), `${password}x`)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
expect(await svc.deletePasskey(user.id, String(cred.id), undefined)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
expect(await svc.deletePasskey(user.id, String(cred.id), `${password}x`)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
testDb.prepare("UPDATE users SET password_hash = '' WHERE id = ?").run(user.id);
|
||||
expect(svc.deletePasskey(user.id, String(cred.id), password)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
expect(await svc.deletePasskey(user.id, String(cred.id), password)).toEqual({ error: 'Incorrect password', status: 401 });
|
||||
});
|
||||
|
||||
it('PASSKEY-SVC-029: deletes own credentials only — foreign ids 404 without leaking', () => {
|
||||
it('PASSKEY-SVC-029: deletes own credentials only — foreign ids 404 without leaking', async () => {
|
||||
const { user, password } = createUser(testDb);
|
||||
const { user: other, password: otherPassword } = createUser(testDb);
|
||||
const cred = insertCredential(user.id);
|
||||
|
||||
expect(svc.deletePasskey(other.id, String(cred.id), otherPassword)).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
expect(svc.deletePasskey(user.id, String(cred.id), password)).toEqual({ success: true });
|
||||
expect(await svc.deletePasskey(other.id, String(cred.id), otherPassword)).toEqual({ error: 'Passkey not found', status: 404 });
|
||||
expect(await svc.deletePasskey(user.id, String(cred.id), password)).toEqual({ success: true });
|
||||
expect(testDb.prepare('SELECT COUNT(*) AS n FROM webauthn_credentials').get()).toEqual({ n: 0 });
|
||||
});
|
||||
});
|
||||
@@ -734,8 +734,8 @@ describe('deletePasskey', () => {
|
||||
// ── adminResetPasskeys ────────────────────────────────────────────────────────
|
||||
|
||||
describe('adminResetPasskeys', () => {
|
||||
it('PASSKEY-SVC-030: 404s on an unknown user, else clears all credentials and reports the count', () => {
|
||||
expect(svc.adminResetPasskeys(999_999)).toEqual({ error: 'User not found', status: 404 });
|
||||
it('PASSKEY-SVC-030: 404s on an unknown user, else clears all credentials and reports the count', async () => {
|
||||
expect(await svc.adminResetPasskeys(999_999)).toEqual({ error: 'User not found', status: 404 });
|
||||
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
@@ -743,8 +743,8 @@ describe('adminResetPasskeys', () => {
|
||||
insertCredential(user.id);
|
||||
const kept = insertCredential(other.id);
|
||||
|
||||
expect(svc.adminResetPasskeys(user.id)).toEqual({ success: true, deleted: 2, email: user.email });
|
||||
expect(svc.adminResetPasskeys(user.id)).toEqual({ success: true, deleted: 0, email: user.email });
|
||||
expect(await svc.adminResetPasskeys(user.id)).toEqual({ success: true, deleted: 2, email: user.email });
|
||||
expect(await svc.adminResetPasskeys(user.id)).toEqual({ success: true, deleted: 0, email: user.email });
|
||||
expect(testDb.prepare('SELECT id FROM webauthn_credentials').all()).toEqual([{ id: kept.id }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,48 +36,48 @@ afterAll(() => { testDb.close(); });
|
||||
// ── Invites ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Invites', () => {
|
||||
it('ADMIN-SVC-024 — createInvite returns invite with token', () => {
|
||||
it('ADMIN-SVC-024 — createInvite returns invite with token', async () => {
|
||||
const { user: admin } = createAdmin(testDb);
|
||||
const result = svc.createInvite(admin.id, { max_uses: 5 }) as any;
|
||||
const result = await svc.createInvite(admin.id, { max_uses: 5 }) as any;
|
||||
expect(result.invite.token).toBeDefined();
|
||||
expect(result.invite.max_uses).toBe(5);
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-025 — createInvite defaults to 1 use', () => {
|
||||
it('ADMIN-SVC-025 — createInvite defaults to 1 use', async () => {
|
||||
const { user: admin } = createAdmin(testDb);
|
||||
const result = svc.createInvite(admin.id, {}) as any;
|
||||
const result = await svc.createInvite(admin.id, {}) as any;
|
||||
expect(result.uses).toBe(1);
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-026 — listInvites returns array', () => {
|
||||
it('ADMIN-SVC-026 — listInvites returns array', async () => {
|
||||
const { user: admin } = createAdmin(testDb);
|
||||
svc.createInvite(admin.id, {});
|
||||
const invites = svc.listInvites() as any[];
|
||||
await svc.createInvite(admin.id, {});
|
||||
const invites = await svc.listInvites() as any[];
|
||||
expect(invites.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-027 — deleteInvite removes invite', () => {
|
||||
it('ADMIN-SVC-027 — deleteInvite removes invite', async () => {
|
||||
const { user: admin } = createAdmin(testDb);
|
||||
const invite = createInviteToken(testDb, { created_by: admin.id }) as any;
|
||||
const result = svc.deleteInvite(String(invite.id)) as any;
|
||||
const result = await svc.deleteInvite(String(invite.id)) as any;
|
||||
expect(result.error).toBeUndefined();
|
||||
const check = testDb.prepare('SELECT id FROM invite_tokens WHERE id = ?').get(invite.id);
|
||||
expect(check).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-028 — deleteInvite returns 404 for non-existent invite', () => {
|
||||
const result = svc.deleteInvite('99999') as any;
|
||||
it('ADMIN-SVC-028 — deleteInvite returns 404 for non-existent invite', async () => {
|
||||
const result = await svc.deleteInvite('99999') as any;
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Invites — trip binding', () => {
|
||||
it('ADMIN-SVC-073 — createInvite 404s on a trip_id that does not resolve', () => {
|
||||
it('ADMIN-SVC-073 — createInvite 404s on a trip_id that does not resolve', async () => {
|
||||
const { user: admin } = createAdmin(testDb);
|
||||
expect(svc.createInvite(admin.id, { trip_id: 99999 }) as any).toMatchObject({ status: 404, error: 'Trip not found' });
|
||||
expect(svc.createInvite(admin.id, { trip_id: 'not-a-number' }) as any).toMatchObject({ status: 404 });
|
||||
expect(await svc.createInvite(admin.id, { trip_id: 99999 }) as any).toMatchObject({ status: 404, error: 'Trip not found' });
|
||||
expect(await svc.createInvite(admin.id, { trip_id: 'not-a-number' }) as any).toMatchObject({ status: 404 });
|
||||
expect(testDb.prepare('SELECT COUNT(*) as c FROM invite_tokens').get()).toEqual({ c: 0 });
|
||||
// An absent/blank binding is still a plain registration invite.
|
||||
expect((svc.createInvite(admin.id, {}) as any).tripId).toBeNull();
|
||||
expect((await svc.createInvite(admin.id, {}) as any).tripId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,12 +23,12 @@ describe('roadtrip read tools', () => {
|
||||
});
|
||||
it('passes reviewed Google stops and the authenticated user to the importer', async () => {
|
||||
const routes = { preview: vi.fn(async () => ({ stops: [] })), import: vi.fn(() => ({ imported: 2 })) };
|
||||
const auth = { isDemoUser: vi.fn(() => false) };
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
const tool = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
await tool.preview({ url: 'https://www.google.com/maps/dir/A/B' });
|
||||
expect(routes.preview).toHaveBeenCalledWith('https://www.google.com/maps/dir/A/B');
|
||||
const input = { tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] };
|
||||
expect(JSON.stringify(tool.import(input, ctx))).toContain('2');
|
||||
expect(JSON.stringify(await tool.import(input, ctx))).toContain('2');
|
||||
expect(routes.import).toHaveBeenCalledWith(10, 5, input);
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ describe('roadtrip read tools', () => {
|
||||
// The one non-admin write tool that had no gate: a demo session could write
|
||||
// thirty places and their assignments onto the shared demo trip.
|
||||
const routes = { preview: vi.fn(), import: vi.fn() };
|
||||
const auth = { isDemoUser: vi.fn(() => true) };
|
||||
const auth = { isDemoUser: vi.fn(async () => true) };
|
||||
const tool = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
|
||||
const res = await tool.import({ tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] } as never, ctx);
|
||||
@@ -55,7 +55,7 @@ describe('roadtrip read tools', () => {
|
||||
const charging = new ChargingMcp({ read: refuse('Place not found', 404) } as never, db as never, {} as never);
|
||||
expect(text(await charging.read({ tripId: 10, placeId: 2 }, ctx))).toEqual([true, 'Place not found']);
|
||||
|
||||
const auth = { isDemoUser: vi.fn(() => false) };
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
const routes = { preview: refuse('Use a Google Maps directions link.', 400), import: refuse('Permission denied', 403) };
|
||||
const google = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
expect(text(await google.preview({ url: 'https://www.google.com/maps/place/A' }))).toEqual([true, 'Use a Google Maps directions link.']);
|
||||
|
||||
@@ -52,14 +52,14 @@ function handler(): CallHandler & { handle: ReturnType<typeof vi.fn> } {
|
||||
}
|
||||
|
||||
function makeInterceptor() {
|
||||
const generateToken = vi.fn().mockReturnValue('renewed.jwt');
|
||||
const generateToken = vi.fn().mockResolvedValue('renewed.jwt');
|
||||
const interceptor = new SessionRenewalInterceptor({ generateToken } as unknown as AuthService);
|
||||
return { interceptor, generateToken };
|
||||
}
|
||||
|
||||
async function run(interceptor: SessionRenewalInterceptor, req: ReqShape, res: ReturnType<typeof makeRes>, type = 'http') {
|
||||
const h = handler();
|
||||
const out = await lastValueFrom(interceptor.intercept(ctx(req, res, type), h));
|
||||
const out = await lastValueFrom(await interceptor.intercept(ctx(req, res, type), h));
|
||||
expect(out).toBe('ok');
|
||||
expect(h.handle).toHaveBeenCalled();
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ afterAll(() => {
|
||||
});
|
||||
|
||||
describe('erasePluginUserData', () => {
|
||||
it('USER-CLEANUP-001: deletes the host-side per-user plugin rows', () => {
|
||||
it('USER-CLEANUP-001: deletes the host-side per-user plugin rows', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb, { username: 'other' });
|
||||
installPlugin('demo', []);
|
||||
@@ -103,34 +103,34 @@ describe('erasePluginUserData', () => {
|
||||
testDb.prepare('INSERT INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)')
|
||||
.run('demo', other.id, '{"token":"keep-me"}');
|
||||
|
||||
svc.erasePluginUserData(user.id);
|
||||
await svc.erasePluginUserData(user.id);
|
||||
|
||||
const rows = testDb.prepare('SELECT user_id FROM plugin_user_config').all() as Array<{ user_id: number }>;
|
||||
expect(rows.map(r => r.user_id)).toEqual([other.id]);
|
||||
});
|
||||
|
||||
it('USER-CLEANUP-002: enqueues an erasure only for plugins holding hook:user-data', () => {
|
||||
it('USER-CLEANUP-002: enqueues an erasure only for plugins holding hook:user-data', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
installPlugin('with-hook', ['hook:user-data', 'trips:read']);
|
||||
installPlugin('without-hook', ['trips:read']);
|
||||
installPlugin('no-permissions', null);
|
||||
|
||||
svc.erasePluginUserData(user.id);
|
||||
await svc.erasePluginUserData(user.id);
|
||||
|
||||
expect(queuedFor(user.id)).toEqual(['with-hook']);
|
||||
});
|
||||
|
||||
it('USER-CLEANUP-003: treats an unparseable permissions column as no permissions', () => {
|
||||
it('USER-CLEANUP-003: treats an unparseable permissions column as no permissions', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
testDb.prepare('INSERT INTO plugins (id, name, version, permissions) VALUES (?, ?, ?, ?)')
|
||||
.run('broken', 'broken', '1.0.0', '{not json');
|
||||
|
||||
svc.erasePluginUserData(user.id);
|
||||
await svc.erasePluginUserData(user.id);
|
||||
|
||||
expect(queuedFor(user.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('USER-CLEANUP-004: enqueues every orphan data dir — an uninstall keeps no permissions row', () => {
|
||||
it('USER-CLEANUP-004: enqueues every orphan data dir — an uninstall keeps no permissions row', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-plugins-data-'));
|
||||
dataRootRef.value = root;
|
||||
@@ -140,7 +140,7 @@ describe('erasePluginUserData', () => {
|
||||
fs.mkdirSync(path.join(root, 'installed'));
|
||||
|
||||
try {
|
||||
svc.erasePluginUserData(user.id);
|
||||
await svc.erasePluginUserData(user.id);
|
||||
// 'installed' comes from the permissions scan, not the orphan scan, and the
|
||||
// INSERT OR IGNORE keeps it single.
|
||||
expect(queuedFor(user.id)).toEqual(['installed', 'uninstalled-but-retained']);
|
||||
@@ -155,7 +155,7 @@ describe('erasePluginUserData', () => {
|
||||
slim.prepare('INSERT INTO users (id) VALUES (1)').run();
|
||||
const slimSvc = new UserCleanupService(new DatabaseService(slim), budget, await createTestUnitOfWork(testDb));
|
||||
|
||||
expect(() => slimSvc.erasePluginUserData(1)).not.toThrow();
|
||||
await expect(slimSvc.erasePluginUserData(1)).resolves.toBeUndefined();
|
||||
|
||||
slim.close();
|
||||
});
|
||||
@@ -216,6 +216,10 @@ describe('deleteUserCompletely', () => {
|
||||
|
||||
// Fail on the final statement only, after the reference cleanup has written.
|
||||
const failing = new DatabaseService(testDb);
|
||||
// `.bind` is load-bearing here and must NOT become an arrow forwarder: it captures
|
||||
// the ORIGINAL run before vi.spyOn replaces the property, whereas `(...a) => failing.run(...a)`
|
||||
// would re-enter the spy and recurse. `run` stays synchronous (recipe R0), so the
|
||||
// `any`-typed alias hides nothing.
|
||||
const realRun = failing.run.bind(failing);
|
||||
vi.spyOn(failing, 'run').mockImplementation((sql: string, ...params: unknown[]) => {
|
||||
if (sql.startsWith('DELETE FROM users')) throw new Error('boom');
|
||||
|
||||
@@ -170,21 +170,21 @@ describe('getSettings', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('listUsers', () => {
|
||||
it('AUTH-DB-011: returns all users except self, sorted by username', () => {
|
||||
it('AUTH-DB-011: returns all users except self, sorted by username', async () => {
|
||||
const { user: self } = createUser(testDb, { username: 'zzself' });
|
||||
createUser(testDb, { username: 'alice' });
|
||||
createUser(testDb, { username: 'charlie' });
|
||||
createUser(testDb, { username: 'bob' });
|
||||
const result = profile.listUsers(self.id);
|
||||
const result = await profile.listUsers(self.id);
|
||||
expect(result).toHaveLength(3);
|
||||
const names = result.map((u) => u.username);
|
||||
expect(names).toEqual([...names].sort());
|
||||
expect(names).not.toContain('zzself');
|
||||
});
|
||||
|
||||
it('AUTH-DB-012: returns empty array when only one user exists', () => {
|
||||
it('AUTH-DB-012: returns empty array when only one user exists', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = profile.listUsers(user.id);
|
||||
const result = await profile.listUsers(user.id);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,87 +49,87 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('WebauthnConfigService.resolve', () => {
|
||||
it('WAC-001: derives the RP ID and single origin from a real APP_URL domain', () => {
|
||||
it('WAC-001: derives the RP ID and single origin from a real APP_URL domain', async () => {
|
||||
appUrlRef.value = 'https://trek.example.org';
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg).not.toBeNull();
|
||||
expect(cfg!.rpID).toBe('trek.example.org');
|
||||
expect(cfg!.origins).toEqual(['https://trek.example.org']);
|
||||
expect(cfg!.explicitOrigins).toBe(false); // derived, not operator-supplied
|
||||
expect(svc.isConfigured()).toBe(true);
|
||||
expect(await svc.isConfigured()).toBe(true);
|
||||
});
|
||||
|
||||
it('WAC-002: returns null for a bare-IP host (IPs are not valid RP IDs)', () => {
|
||||
it('WAC-002: returns null for a bare-IP host (IPs are not valid RP IDs)', async () => {
|
||||
appUrlRef.value = 'http://192.168.1.50:3001';
|
||||
expect(svc.resolve()).toBeNull();
|
||||
expect(svc.isConfigured()).toBe(false);
|
||||
expect(await svc.resolve()).toBeNull();
|
||||
expect(await svc.isConfigured()).toBe(false);
|
||||
});
|
||||
|
||||
it('WAC-003: nothing configured resolves to the localhost dev fallback (#2147)', () => {
|
||||
it('WAC-003: nothing configured resolves to the localhost dev fallback (#2147)', async () => {
|
||||
// getAppUrl() never yields '' — an unconfigured instance lands on
|
||||
// http://localhost:{PORT}, so resolve() returns the localhost dev config.
|
||||
// The remote-origin guard for that phantom config lives in PasskeyService.
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.rpID).toBe('localhost');
|
||||
expect(cfg!.explicitOrigins).toBe(false);
|
||||
expect(svc.isConfigured()).toBe(true);
|
||||
expect(await svc.isConfigured()).toBe(true);
|
||||
});
|
||||
|
||||
it('WAC-004: localhost dev uses the browser (Vite :5173) origin, not just the API port', () => {
|
||||
it('WAC-004: localhost dev uses the browser (Vite :5173) origin, not just the API port', async () => {
|
||||
appUrlRef.value = 'http://localhost:3001';
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.rpID).toBe('localhost');
|
||||
expect(cfg!.origins).toContain('http://localhost:5173');
|
||||
expect(cfg!.origins).toContain('http://localhost:3001');
|
||||
});
|
||||
|
||||
it('WAC-005: an explicit webauthn_rp_id app-setting overrides APP_URL', () => {
|
||||
it('WAC-005: an explicit webauthn_rp_id app-setting overrides APP_URL', async () => {
|
||||
appUrlRef.value = 'https://internal.example.org';
|
||||
settingsStore.set('webauthn_rp_id', 'public.example.org');
|
||||
settingsStore.set('webauthn_origins', 'https://public.example.org');
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.rpID).toBe('public.example.org');
|
||||
expect(cfg!.origins).toEqual(['https://public.example.org']);
|
||||
expect(cfg!.explicitOrigins).toBe(true);
|
||||
});
|
||||
|
||||
it('WAC-006: webauthn_origins is parsed as a comma-separated, trimmed list', () => {
|
||||
it('WAC-006: webauthn_origins is parsed as a comma-separated, trimmed list', async () => {
|
||||
settingsStore.set('webauthn_rp_id', 'example.org');
|
||||
settingsStore.set('webauthn_origins', 'https://a.example.org , https://b.example.org/');
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.origins).toEqual(['https://a.example.org', 'https://b.example.org']);
|
||||
});
|
||||
|
||||
it('WAC-007: the WEBAUTHN_RP_ID env var takes priority', () => {
|
||||
it('WAC-007: the WEBAUTHN_RP_ID env var takes priority', async () => {
|
||||
vi.stubEnv('WEBAUTHN_RP_ID', 'env.example.org');
|
||||
vi.stubEnv('WEBAUTHN_ORIGINS', 'https://env.example.org');
|
||||
appUrlRef.value = 'https://ignored.example.org';
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.rpID).toBe('env.example.org');
|
||||
expect(cfg!.origins).toEqual(['https://env.example.org']);
|
||||
});
|
||||
|
||||
it('WAC-008: a configured RP ID with no origins falls back to the APP_URL origin', () => {
|
||||
it('WAC-008: a configured RP ID with no origins falls back to the APP_URL origin', async () => {
|
||||
appUrlRef.value = 'https://trek.example.org';
|
||||
settingsStore.set('webauthn_rp_id', 'trek.example.org');
|
||||
const cfg = svc.resolve();
|
||||
const cfg = await svc.resolve();
|
||||
expect(cfg!.origins).toEqual(['https://trek.example.org']);
|
||||
expect(cfg!.explicitOrigins).toBe(false); // the origin list itself is still derived
|
||||
});
|
||||
|
||||
it('WAC-009: an operator flipping the RP ID at runtime takes effect on the next resolve', () => {
|
||||
it('WAC-009: an operator flipping the RP ID at runtime takes effect on the next resolve', async () => {
|
||||
appUrlRef.value = 'https://trek.example.org';
|
||||
expect(svc.resolve()!.rpID).toBe('trek.example.org');
|
||||
expect((await svc.resolve())!.rpID).toBe('trek.example.org');
|
||||
|
||||
settingsStore.set('webauthn_rp_id', 'moved.example.org');
|
||||
|
||||
expect(svc.resolve()!.rpID).toBe('moved.example.org');
|
||||
expect((await svc.resolve())!.rpID).toBe('moved.example.org');
|
||||
});
|
||||
|
||||
it('WAC-010: the WEBAUTHN_ORIGINS env var also marks the origin list explicit', () => {
|
||||
it('WAC-010: the WEBAUTHN_ORIGINS env var also marks the origin list explicit', async () => {
|
||||
vi.stubEnv('WEBAUTHN_RP_ID', 'env.example.org');
|
||||
vi.stubEnv('WEBAUTHN_ORIGINS', 'https://env.example.org');
|
||||
expect(svc.resolve()!.explicitOrigins).toBe(true);
|
||||
expect((await svc.resolve())!.explicitOrigins).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user