mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-22 06:41:46 +00:00
Merge branch 'dev' into search-auto-complete
This commit is contained in:
@@ -471,14 +471,11 @@ describe('OIDC Settings', () => {
|
||||
expect(result.client_id).toBe('my-client');
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-049 — updateOidcSettings sets oidc_only flag correctly', () => {
|
||||
updateOidcSettings({ oidc_only: true });
|
||||
const enabled = getOidcSettings() as any;
|
||||
expect(enabled.oidc_only).toBe(true);
|
||||
|
||||
updateOidcSettings({ oidc_only: false });
|
||||
const disabled = getOidcSettings() as any;
|
||||
expect(disabled.oidc_only).toBe(false);
|
||||
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
|
||||
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
|
||||
const result = getOidcSettings() as any;
|
||||
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
|
||||
expect(result.oidc_only).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ import {
|
||||
getAppSettings,
|
||||
validateKeys,
|
||||
isOidcOnlyMode,
|
||||
resolveAuthToggles,
|
||||
setupMfa,
|
||||
enableMfa,
|
||||
disableMfa,
|
||||
@@ -322,6 +323,80 @@ describe('isOidcOnlyMode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// resolveAuthToggles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('resolveAuthToggles', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
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)', () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
const t = 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', () => {
|
||||
vi.stubEnv('OIDC_ONLY', 'true');
|
||||
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');
|
||||
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
|
||||
const t = 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', () => {
|
||||
vi.stubEnv('OIDC_ONLY', '');
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
|
||||
const t = 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', () => {
|
||||
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 = 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', () => {
|
||||
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 = 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', () => {
|
||||
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 = 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);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// setupMfa
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -454,7 +529,7 @@ describe('registerUser — OIDC-only / registration-disabled', () => {
|
||||
|
||||
const result = registerUser({ username: 'u', email: 'new@x.com', password: 'Secure123!' });
|
||||
expect(result.status).toBe(403);
|
||||
expect(result.error).toMatch(/SSO/i);
|
||||
expect(result.error).toMatch(/password registration is disabled/i);
|
||||
});
|
||||
|
||||
it('AUTH-DB-034: returns 403 when registration is disabled and no invite', () => {
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
/**
|
||||
* Unit tests for collabService — COLLAB-SVC-001 to COLLAB-SVC-030.
|
||||
* Covers votePoll edge cases, listMessages pagination, deleteMessage ownership,
|
||||
* updateNote partial fields, fetchLinkPreview, avatarUrl, createMessage reply validation.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
|
||||
// ── DB setup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: any, userId: number) =>
|
||||
db.prepare(`
|
||||
SELECT t.id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: any, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
|
||||
// Stub checkSsrf so fetchLinkPreview tests can control SSRF behaviour
|
||||
const { mockCheckSsrf, mockCreatePinnedDispatcher } = vi.hoisted(() => ({
|
||||
mockCheckSsrf: vi.fn(async () => ({ allowed: true, resolvedIp: '93.184.216.34' })),
|
||||
mockCreatePinnedDispatcher: vi.fn(() => ({})),
|
||||
}));
|
||||
vi.mock('../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf: mockCheckSsrf,
|
||||
createPinnedDispatcher: mockCreatePinnedDispatcher,
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip } from '../../helpers/factories';
|
||||
import {
|
||||
avatarUrl,
|
||||
votePoll,
|
||||
listMessages,
|
||||
createMessage,
|
||||
deleteMessage,
|
||||
updateNote,
|
||||
createNote,
|
||||
createPoll,
|
||||
closePoll,
|
||||
fetchLinkPreview,
|
||||
} from '../../../src/services/collabService';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: true, resolvedIp: '93.184.216.34' });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
mockCheckSsrf.mockReset();
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: true, resolvedIp: '93.184.216.34' });
|
||||
});
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function setup() {
|
||||
const { user: user1 } = createUser(testDb);
|
||||
const { user: user2 } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user1.id);
|
||||
return { user1, user2, trip };
|
||||
}
|
||||
|
||||
// ── avatarUrl ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('avatarUrl', () => {
|
||||
it('COLLAB-SVC-001: returns null when avatar is null', () => {
|
||||
expect(avatarUrl({ avatar: null })).toBeNull();
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-002: returns upload path when avatar is set', () => {
|
||||
expect(avatarUrl({ avatar: 'abc.jpg' })).toBe('/uploads/avatars/abc.jpg');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-003: returns null when avatar is empty string', () => {
|
||||
expect(avatarUrl({ avatar: '' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── votePoll ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('votePoll', () => {
|
||||
it('COLLAB-SVC-004: returns error "closed" when poll is closed', () => {
|
||||
const { user1, trip } = setup();
|
||||
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
|
||||
closePoll(trip.id, poll!.id);
|
||||
|
||||
const result = votePoll(trip.id, poll!.id, user1.id, 0);
|
||||
expect(result.error).toBe('closed');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-005: returns error "invalid_index" for negative index', () => {
|
||||
const { user1, trip } = setup();
|
||||
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
|
||||
|
||||
const result = votePoll(trip.id, poll!.id, user1.id, -1);
|
||||
expect(result.error).toBe('invalid_index');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-006: returns error "invalid_index" for out-of-range index', () => {
|
||||
const { user1, trip } = setup();
|
||||
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
|
||||
|
||||
const result = votePoll(trip.id, poll!.id, user1.id, 5);
|
||||
expect(result.error).toBe('invalid_index');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-007: returns error "not_found" for nonexistent poll', () => {
|
||||
const { user1, trip } = setup();
|
||||
const result = votePoll(trip.id, 9999, user1.id, 0);
|
||||
expect(result.error).toBe('not_found');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-008: successfully votes and returns poll with voters', () => {
|
||||
const { user1, trip } = setup();
|
||||
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['Yes', 'No'] });
|
||||
|
||||
const result = votePoll(trip.id, poll!.id, user1.id, 0);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.poll).toBeDefined();
|
||||
expect(result.poll!.options[0].voters).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-009: toggles vote off when voted again on same option', () => {
|
||||
const { user1, trip } = setup();
|
||||
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['Yes', 'No'] });
|
||||
|
||||
votePoll(trip.id, poll!.id, user1.id, 0);
|
||||
const result = votePoll(trip.id, poll!.id, user1.id, 0);
|
||||
expect(result.poll!.options[0].voters).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── listMessages with before cursor ──────────────────────────────────────────
|
||||
|
||||
describe('listMessages', () => {
|
||||
it('COLLAB-SVC-010: returns all messages when no before cursor', () => {
|
||||
const { user1, trip } = setup();
|
||||
createMessage(trip.id, user1.id, 'Hello');
|
||||
createMessage(trip.id, user1.id, 'World');
|
||||
|
||||
const msgs = listMessages(trip.id);
|
||||
expect(msgs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-011: paginates using before cursor (returns messages with id < before)', () => {
|
||||
const { user1, trip } = setup();
|
||||
const r1 = createMessage(trip.id, user1.id, 'First');
|
||||
const r2 = createMessage(trip.id, user1.id, 'Second');
|
||||
const r3 = createMessage(trip.id, user1.id, 'Third');
|
||||
|
||||
const id3 = r3.message!.id;
|
||||
const msgs = listMessages(trip.id, id3);
|
||||
expect(msgs.length).toBe(2);
|
||||
const texts = msgs.map(m => m.text);
|
||||
expect(texts).toContain('First');
|
||||
expect(texts).toContain('Second');
|
||||
expect(texts).not.toContain('Third');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-012: returns messages in ascending order (reversed after DESC query)', () => {
|
||||
const { user1, trip } = setup();
|
||||
createMessage(trip.id, user1.id, 'A');
|
||||
createMessage(trip.id, user1.id, 'B');
|
||||
createMessage(trip.id, user1.id, 'C');
|
||||
|
||||
const msgs = listMessages(trip.id);
|
||||
expect(msgs[0].text).toBe('A');
|
||||
expect(msgs[2].text).toBe('C');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-013: includes reactions grouped by emoji', () => {
|
||||
const { user1, trip } = setup();
|
||||
const r = createMessage(trip.id, user1.id, 'React me');
|
||||
const msgId = r.message!.id;
|
||||
testDb.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(msgId, user1.id, '👍');
|
||||
|
||||
const msgs = listMessages(trip.id);
|
||||
expect(msgs[0].reactions).toBeDefined();
|
||||
expect(msgs[0].reactions).toHaveLength(1);
|
||||
expect(msgs[0].reactions[0].emoji).toBe('👍');
|
||||
});
|
||||
});
|
||||
|
||||
// ── createMessage with invalid replyTo ───────────────────────────────────────
|
||||
|
||||
describe('createMessage', () => {
|
||||
it('COLLAB-SVC-014: returns error when replyTo message does not exist', () => {
|
||||
const { user1, trip } = setup();
|
||||
const result = createMessage(trip.id, user1.id, 'Reply to nothing', 9999);
|
||||
expect(result.error).toBe('reply_not_found');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-015: creates message with valid replyTo', () => {
|
||||
const { user1, trip } = setup();
|
||||
const r1 = createMessage(trip.id, user1.id, 'Original');
|
||||
const r2 = createMessage(trip.id, user1.id, 'Reply', r1.message!.id);
|
||||
expect(r2.error).toBeUndefined();
|
||||
expect(r2.message!.reply_to).toBe(r1.message!.id);
|
||||
});
|
||||
});
|
||||
|
||||
// ── deleteMessage ownership check ─────────────────────────────────────────────
|
||||
|
||||
describe('deleteMessage', () => {
|
||||
it('COLLAB-SVC-016: returns error "not_owner" when user does not own message', () => {
|
||||
const { user1, user2, trip } = setup();
|
||||
const r = createMessage(trip.id, user1.id, 'My message');
|
||||
|
||||
const result = deleteMessage(trip.id, r.message!.id, user2.id);
|
||||
expect(result.error).toBe('not_owner');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-017: returns error "not_found" for nonexistent message', () => {
|
||||
const { user1, trip } = setup();
|
||||
const result = deleteMessage(trip.id, 9999, user1.id);
|
||||
expect(result.error).toBe('not_found');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-018: marks message as deleted when owner deletes it', () => {
|
||||
const { user1, trip } = setup();
|
||||
const r = createMessage(trip.id, user1.id, 'Delete me');
|
||||
|
||||
const result = deleteMessage(trip.id, r.message!.id, user1.id);
|
||||
expect(result.error).toBeUndefined();
|
||||
|
||||
const row = testDb.prepare('SELECT deleted FROM collab_messages WHERE id = ?').get(r.message!.id) as any;
|
||||
expect(row.deleted).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── updateNote partial fields ─────────────────────────────────────────────────
|
||||
|
||||
describe('updateNote', () => {
|
||||
it('COLLAB-SVC-019: updates only title when other fields are undefined', () => {
|
||||
const { user1, trip } = setup();
|
||||
const note = createNote(trip.id, user1.id, { title: 'Original', content: 'Some content', website: 'https://example.com' });
|
||||
|
||||
updateNote(trip.id, note.id, { title: 'Updated' });
|
||||
|
||||
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
|
||||
expect(updated.title).toBe('Updated');
|
||||
expect(updated.content).toBe('Some content'); // unchanged
|
||||
expect(updated.website).toBe('https://example.com'); // unchanged
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-020: clears content when content is explicitly set to empty string', () => {
|
||||
const { user1, trip } = setup();
|
||||
const note = createNote(trip.id, user1.id, { title: 'T', content: 'Old content' });
|
||||
|
||||
updateNote(trip.id, note.id, { content: '' });
|
||||
|
||||
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
|
||||
expect(updated.content).toBe('');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-021: updates website when website is defined', () => {
|
||||
const { user1, trip } = setup();
|
||||
const note = createNote(trip.id, user1.id, { title: 'T' });
|
||||
|
||||
updateNote(trip.id, note.id, { website: 'https://new.example.com' });
|
||||
|
||||
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
|
||||
expect(updated.website).toBe('https://new.example.com');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-022: clears website when website is explicitly set to empty string', () => {
|
||||
const { user1, trip } = setup();
|
||||
const note = createNote(trip.id, user1.id, { title: 'T', website: 'https://old.com' });
|
||||
|
||||
updateNote(trip.id, note.id, { website: '' });
|
||||
|
||||
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
|
||||
expect(updated.website).toBe('');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-023: returns null when note does not exist', () => {
|
||||
const { trip } = setup();
|
||||
const result = updateNote(trip.id, 9999, { title: 'Ghost' });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-024: updates pinned flag', () => {
|
||||
const { user1, trip } = setup();
|
||||
const note = createNote(trip.id, user1.id, { title: 'T', pinned: false });
|
||||
|
||||
updateNote(trip.id, note.id, { pinned: true });
|
||||
|
||||
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
|
||||
expect(updated.pinned).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── fetchLinkPreview ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('fetchLinkPreview', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-025: returns OG title and description from HTML', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
text: async () => `
|
||||
<html>
|
||||
<head>
|
||||
<meta property="og:title" content="Test Title" />
|
||||
<meta property="og:description" content="Test Description" />
|
||||
<meta property="og:image" content="https://example.com/image.jpg" />
|
||||
<meta property="og:site_name" content="Example" />
|
||||
</head>
|
||||
</html>
|
||||
`,
|
||||
}));
|
||||
|
||||
const result = await fetchLinkPreview('https://example.com/page');
|
||||
expect(result.title).toBe('Test Title');
|
||||
expect(result.description).toBe('Test Description');
|
||||
expect(result.image).toBe('https://example.com/image.jpg');
|
||||
expect(result.url).toBe('https://example.com/page');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-026: falls back to <title> tag when no og:title', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
text: async () => `<html><head><title>Page Title</title></head></html>`,
|
||||
}));
|
||||
|
||||
const result = await fetchLinkPreview('https://example.com/');
|
||||
expect(result.title).toBe('Page Title');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-027: returns fallback when fetch response is not ok', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
text: async () => '',
|
||||
}));
|
||||
|
||||
const result = await fetchLinkPreview('https://example.com/bad');
|
||||
expect(result.title).toBeNull();
|
||||
expect(result.description).toBeNull();
|
||||
expect(result.url).toBe('https://example.com/bad');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-028: returns fallback when SSRF check blocks the URL', async () => {
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: false, error: 'SSRF blocked' });
|
||||
|
||||
const result = await fetchLinkPreview('https://169.254.169.254/');
|
||||
expect(result.title).toBeNull();
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-029: returns fallback when fetch throws (network error)', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
|
||||
|
||||
const result = await fetchLinkPreview('https://example.com/net-error');
|
||||
expect(result.title).toBeNull();
|
||||
expect(result.url).toBe('https://example.com/net-error');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-030: falls back to meta description tag when no og:description', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
text: async () => `
|
||||
<html><head>
|
||||
<meta name="description" content="Meta description here" />
|
||||
</head></html>
|
||||
`,
|
||||
}));
|
||||
|
||||
const result = await fetchLinkPreview('https://example.com/meta');
|
||||
expect(result.description).toBe('Meta description here');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,368 @@
|
||||
/**
|
||||
* Unit tests for journeyShareService — JOURNEY-SHARE-001 through JOURNEY-SHARE-018.
|
||||
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
// -- DB setup -----------------------------------------------------------------
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => null,
|
||||
isOwner: () => false,
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-secret',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createJourney, createJourneyEntry } from '../../helpers/factories';
|
||||
import {
|
||||
createOrUpdateJourneyShareLink,
|
||||
getJourneyShareLink,
|
||||
deleteJourneyShareLink,
|
||||
validateShareTokenForPhoto,
|
||||
validateShareTokenForAsset,
|
||||
getPublicJourney,
|
||||
} from '../../../src/services/journeyShareService';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
// -- Helpers ------------------------------------------------------------------
|
||||
|
||||
/** Insert a journey_photos row and return its id. */
|
||||
function insertJourneyPhoto(
|
||||
entryId: number,
|
||||
opts: { filePath?: string; assetId?: string; ownerId?: number } = {}
|
||||
): number {
|
||||
const result = testDb.prepare(`
|
||||
INSERT INTO journey_photos (entry_id, file_path, caption, sort_order, created_at, asset_id, owner_id)
|
||||
VALUES (?, ?, NULL, 0, ?, ?, ?)
|
||||
`).run(entryId, opts.filePath ?? '/photos/test.jpg', Date.now(), opts.assetId ?? null, opts.ownerId ?? null);
|
||||
return result.lastInsertRowid as number;
|
||||
}
|
||||
|
||||
// -- Tests --------------------------------------------------------------------
|
||||
|
||||
describe('createOrUpdateJourneyShareLink', () => {
|
||||
it('JOURNEY-SHARE-001: creates a new share link with default permissions', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
const result = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
expect(result.created).toBe(true);
|
||||
expect(result.token).toBeTruthy();
|
||||
expect(result.token.length).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-002: creates a share link with custom permissions', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
createOrUpdateJourneyShareLink(journey.id, user.id, {
|
||||
share_timeline: true,
|
||||
share_gallery: false,
|
||||
share_map: false,
|
||||
});
|
||||
|
||||
const link = getJourneyShareLink(journey.id);
|
||||
expect(link).not.toBeNull();
|
||||
expect(link!.share_timeline).toBe(true);
|
||||
expect(link!.share_gallery).toBe(false);
|
||||
expect(link!.share_map).toBe(false);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-003: updates permissions on existing link without regenerating token', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
const first = createOrUpdateJourneyShareLink(journey.id, user.id, {
|
||||
share_timeline: true,
|
||||
share_gallery: true,
|
||||
share_map: true,
|
||||
});
|
||||
const second = createOrUpdateJourneyShareLink(journey.id, user.id, {
|
||||
share_timeline: true,
|
||||
share_gallery: false,
|
||||
share_map: false,
|
||||
});
|
||||
|
||||
expect(second.created).toBe(false);
|
||||
expect(second.token).toBe(first.token);
|
||||
|
||||
const link = getJourneyShareLink(journey.id);
|
||||
expect(link!.share_gallery).toBe(false);
|
||||
expect(link!.share_map).toBe(false);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-004: different journeys get different tokens', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const j1 = createJourney(testDb, user.id);
|
||||
const j2 = createJourney(testDb, user.id);
|
||||
|
||||
const r1 = createOrUpdateJourneyShareLink(j1.id, user.id, {});
|
||||
const r2 = createOrUpdateJourneyShareLink(j2.id, user.id, {});
|
||||
|
||||
expect(r1.token).not.toBe(r2.token);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getJourneyShareLink', () => {
|
||||
it('JOURNEY-SHARE-005: returns null when no share link exists', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
const result = getJourneyShareLink(journey.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-006: returns share link info when it exists', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
createOrUpdateJourneyShareLink(journey.id, user.id, {
|
||||
share_timeline: true,
|
||||
share_gallery: false,
|
||||
share_map: true,
|
||||
});
|
||||
|
||||
const result = getJourneyShareLink(journey.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.token).toBeTruthy();
|
||||
expect(result!.share_timeline).toBe(true);
|
||||
expect(result!.share_gallery).toBe(false);
|
||||
expect(result!.share_map).toBe(true);
|
||||
expect(result!.created_at).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteJourneyShareLink', () => {
|
||||
it('JOURNEY-SHARE-007: removes an existing share link', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
deleteJourneyShareLink(journey.id);
|
||||
|
||||
expect(getJourneyShareLink(journey.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-008: does not throw when deleting non-existent link', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
expect(() => deleteJourneyShareLink(journey.id)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateShareTokenForPhoto', () => {
|
||||
it('JOURNEY-SHARE-009: returns journeyId and ownerId for valid token + photo', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id });
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = validateShareTokenForPhoto(token, photoId);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.journeyId).toBe(journey.id);
|
||||
expect(result!.ownerId).toBe(user.id);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-010: returns null for invalid token', () => {
|
||||
const result = validateShareTokenForPhoto('nonexistent-token', 1);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-011: returns null when photo does not belong to shared journey', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey1 = createJourney(testDb, user.id);
|
||||
const journey2 = createJourney(testDb, user.id);
|
||||
const entry2 = createJourneyEntry(testDb, journey2.id, user.id);
|
||||
const photoId = insertJourneyPhoto(entry2.id);
|
||||
const { token } = createOrUpdateJourneyShareLink(journey1.id, user.id, {});
|
||||
|
||||
const result = validateShareTokenForPhoto(token, photoId);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-012: falls back to journey owner_id when photo has no owner_id', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
const photoId = insertJourneyPhoto(entry.id, { ownerId: undefined });
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = validateShareTokenForPhoto(token, photoId);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.ownerId).toBe(user.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateShareTokenForAsset', () => {
|
||||
it('JOURNEY-SHARE-013: returns ownerId when asset belongs to shared journey', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-123', ownerId: user.id });
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = validateShareTokenForAsset(token, 'immich-asset-123');
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.ownerId).toBe(user.id);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-014: returns null for invalid token', () => {
|
||||
const result = validateShareTokenForAsset('bad-token', 'some-asset');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-015: falls back to journey owner when asset not found in photos', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = validateShareTokenForAsset(token, 'nonexistent-asset');
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.ownerId).toBe(user.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPublicJourney', () => {
|
||||
it('JOURNEY-SHARE-016: returns null for invalid token', () => {
|
||||
const result = getPublicJourney('invalid-token');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-017: returns journey data with entries, stats, and permissions', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id, {
|
||||
title: 'Japan 2026',
|
||||
subtitle: 'Cherry blossom season',
|
||||
});
|
||||
const entry1 = createJourneyEntry(testDb, journey.id, user.id, {
|
||||
type: 'entry',
|
||||
title: 'Arrived in Tokyo',
|
||||
entry_date: '2026-03-20',
|
||||
location_name: 'Tokyo',
|
||||
});
|
||||
createJourneyEntry(testDb, journey.id, user.id, {
|
||||
type: 'entry',
|
||||
title: 'Kyoto Day Trip',
|
||||
entry_date: '2026-03-22',
|
||||
location_name: 'Kyoto',
|
||||
});
|
||||
insertJourneyPhoto(entry1.id);
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
|
||||
share_timeline: true,
|
||||
share_gallery: true,
|
||||
share_map: false,
|
||||
});
|
||||
|
||||
const result = getPublicJourney(token);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.journey.title).toBe('Japan 2026');
|
||||
expect(result!.journey.subtitle).toBe('Cherry blossom season');
|
||||
expect(result!.entries).toHaveLength(2);
|
||||
expect(result!.stats.entries).toBe(2);
|
||||
expect(result!.stats.photos).toBe(1);
|
||||
expect(result!.stats.cities).toBe(2);
|
||||
expect(result!.permissions.share_timeline).toBe(true);
|
||||
expect(result!.permissions.share_gallery).toBe(true);
|
||||
expect(result!.permissions.share_map).toBe(false);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-018: excludes skeleton entries from public view', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
createJourneyEntry(testDb, journey.id, user.id, {
|
||||
type: 'entry',
|
||||
title: 'Visible Entry',
|
||||
entry_date: '2026-01-10',
|
||||
});
|
||||
createJourneyEntry(testDb, journey.id, user.id, {
|
||||
type: 'skeleton',
|
||||
title: 'Skeleton Entry',
|
||||
entry_date: '2026-01-11',
|
||||
});
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = getPublicJourney(token);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.entries).toHaveLength(1);
|
||||
expect(result!.entries[0].title).toBe('Visible Entry');
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-019: enriches entries with parsed tags and photos', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id, {
|
||||
type: 'entry',
|
||||
entry_date: '2026-04-01',
|
||||
});
|
||||
// Set tags on the entry directly
|
||||
testDb.prepare('UPDATE journey_entries SET tags = ? WHERE id = ?')
|
||||
.run(JSON.stringify(['food', 'culture']), entry.id);
|
||||
insertJourneyPhoto(entry.id, { filePath: '/photos/a.jpg' });
|
||||
insertJourneyPhoto(entry.id, { filePath: '/photos/b.jpg' });
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = getPublicJourney(token);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
const enriched = result!.entries[0];
|
||||
expect(enriched.tags).toEqual(['food', 'culture']);
|
||||
expect(enriched.photos).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-020: returns empty entries array for journey with no entries', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id, { title: 'Empty Journey' });
|
||||
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
|
||||
|
||||
const result = getPublicJourney(token);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.entries).toEqual([]);
|
||||
expect(result!.stats.entries).toBe(0);
|
||||
expect(result!.stats.photos).toBe(0);
|
||||
expect(result!.stats.cities).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -384,7 +384,12 @@ describe('searchNominatim (fetch stubbed)', () => {
|
||||
});
|
||||
|
||||
it('MAPS-030b: throws when nominatim response is not ok', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
text: async () => '',
|
||||
}));
|
||||
const { searchNominatim } = await import('../../../src/services/mapsService');
|
||||
await expect(searchNominatim('fail')).rejects.toThrow('Nominatim API error');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Unit tests for memories/helpersService — MEM-HELPERS-001 to MEM-HELPERS-020.
|
||||
* Covers mapDbError, getAlbumIdFromLink, pipeAsset error paths.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
// ── DB setup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: any, userId: number) =>
|
||||
db.prepare(`
|
||||
SELECT t.id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: any, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-secret',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
|
||||
const { mockSafeFetch } = vi.hoisted(() => ({
|
||||
mockSafeFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/utils/ssrfGuard', () => {
|
||||
class SsrfBlockedError extends Error {
|
||||
constructor(msg: string) { super(msg); this.name = 'SsrfBlockedError'; }
|
||||
}
|
||||
return {
|
||||
safeFetch: mockSafeFetch,
|
||||
SsrfBlockedError,
|
||||
checkSsrf: vi.fn(async () => ({ allowed: true, resolvedIp: '1.2.3.4' })),
|
||||
};
|
||||
});
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip } from '../../helpers/factories';
|
||||
import { mapDbError, getAlbumIdFromLink, pipeAsset } from '../../../src/services/memories/helpersService';
|
||||
import { SsrfBlockedError } from '../../../src/utils/ssrfGuard';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
mockSafeFetch.mockReset();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
// ── mapDbError ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('mapDbError', () => {
|
||||
it('MEM-HELPERS-001: returns 409 for unique constraint error', () => {
|
||||
const err = new Error('UNIQUE constraint failed: users.email');
|
||||
const result = mapDbError(err, 'fallback');
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error.status).toBe(409);
|
||||
expect(result.error.message).toBe('Resource already exists');
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-002: returns 409 for generic constraint error', () => {
|
||||
const err = new Error('constraint violation');
|
||||
const result = mapDbError(err, 'fallback');
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error.status).toBe(409);
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-003: returns 500 with original message for non-constraint error', () => {
|
||||
const err = new Error('Something went wrong');
|
||||
const result = mapDbError(err, 'fallback');
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error.status).toBe(500);
|
||||
expect(result.error.message).toBe('Something went wrong');
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-004: returns 500 for generic DB error', () => {
|
||||
const err = new Error('disk I/O error');
|
||||
const result = mapDbError(err, 'fallback');
|
||||
expect(result.error.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getAlbumIdFromLink ────────────────────────────────────────────────────────
|
||||
|
||||
describe('getAlbumIdFromLink', () => {
|
||||
it('MEM-HELPERS-005: returns 404 when trip access is denied', () => {
|
||||
const result = getAlbumIdFromLink('9999', 'link-1', 1);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-006: returns 404 when album link is not found', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
const result = getAlbumIdFromLink(String(trip.id), 'nonexistent-link', user.id);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error.status).toBe(404);
|
||||
expect(result.error.message).toBe('Album link not found');
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-007: returns album_id when link exists', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
// Insert with auto-increment id (INTEGER PRIMARY KEY)
|
||||
const ins = testDb.prepare(
|
||||
'INSERT INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(trip.id, user.id, 'immich', 'album-123', 'My Album');
|
||||
const linkId = ins.lastInsertRowid;
|
||||
|
||||
const result = getAlbumIdFromLink(String(trip.id), String(linkId), user.id);
|
||||
expect(result.success).toBe(true);
|
||||
expect((result as any).data).toBe('album-123');
|
||||
});
|
||||
});
|
||||
|
||||
// ── pipeAsset ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('pipeAsset', () => {
|
||||
function mockResponse(overrides: Record<string, any> = {}) {
|
||||
return {
|
||||
status: vi.fn().mockReturnThis(),
|
||||
set: vi.fn().mockReturnThis(),
|
||||
end: vi.fn(),
|
||||
json: vi.fn(),
|
||||
headersSent: false,
|
||||
...overrides,
|
||||
} as any;
|
||||
}
|
||||
|
||||
it('MEM-HELPERS-009: calls response.end() when resp.body is null', async () => {
|
||||
mockSafeFetch.mockResolvedValue({
|
||||
status: 200,
|
||||
headers: { get: vi.fn(() => null) },
|
||||
body: null,
|
||||
});
|
||||
const res = mockResponse();
|
||||
|
||||
await pipeAsset('https://example.com/asset', res);
|
||||
|
||||
expect(res.end).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-010: returns 400 when SsrfBlockedError is thrown', async () => {
|
||||
mockSafeFetch.mockRejectedValue(new SsrfBlockedError('SSRF blocked'));
|
||||
const res = mockResponse({ headersSent: false });
|
||||
|
||||
await pipeAsset('https://internal.example.com/asset', res);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-011: returns 500 for generic fetch error', async () => {
|
||||
mockSafeFetch.mockRejectedValue(new Error('Network error'));
|
||||
const res = mockResponse({ headersSent: false });
|
||||
|
||||
await pipeAsset('https://example.com/asset', res);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(500);
|
||||
expect(res.json).toHaveBeenCalledWith({ error: 'Failed to fetch asset' });
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-012: calls response.end() when headersSent is true on error', async () => {
|
||||
mockSafeFetch.mockRejectedValue(new Error('fail'));
|
||||
const res = mockResponse({ headersSent: true });
|
||||
|
||||
await pipeAsset('https://example.com/asset', res);
|
||||
|
||||
expect(res.end).toHaveBeenCalled();
|
||||
expect(res.json).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MEM-HELPERS-013: sets content-type header when present in response', async () => {
|
||||
mockSafeFetch.mockResolvedValue({
|
||||
status: 200,
|
||||
headers: {
|
||||
get: (h: string) => {
|
||||
if (h === 'content-type') return 'image/jpeg';
|
||||
return null;
|
||||
},
|
||||
},
|
||||
body: null,
|
||||
});
|
||||
const res = mockResponse();
|
||||
|
||||
await pipeAsset('https://example.com/img.jpg', res);
|
||||
|
||||
expect(res.set).toHaveBeenCalledWith('Content-Type', 'image/jpeg');
|
||||
expect(res.end).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Unit tests for memories/unifiedService — MEM-UNIFIED-001 to MEM-UNIFIED-010.
|
||||
* Covers error paths: access denied, disabled provider, no providers enabled.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
// ── DB setup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: any, userId: number) =>
|
||||
db.prepare(`
|
||||
SELECT t.id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: any, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-secret',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../../src/services/notificationService', () => ({
|
||||
send: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip } from '../../helpers/factories';
|
||||
import {
|
||||
listTripPhotos,
|
||||
listTripAlbumLinks,
|
||||
addTripPhotos,
|
||||
setTripPhotoSharing,
|
||||
removeTripPhoto,
|
||||
createTripAlbumLink,
|
||||
removeAlbumLink,
|
||||
} from '../../../src/services/memories/unifiedService';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
// Ensure default providers are enabled (resetTestDb seeds them but doesn't reset enabled flag)
|
||||
testDb.prepare('UPDATE photo_providers SET enabled = 1').run();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
// ── listTripPhotos ────────────────────────────────────────────────────────────
|
||||
|
||||
describe('listTripPhotos', () => {
|
||||
it('MEM-UNIFIED-001: returns 404 when user cannot access trip', () => {
|
||||
const result = listTripPhotos('9999', 1);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-002: returns 400 when no photo providers are enabled', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
// Disable all providers
|
||||
testDb.prepare('UPDATE photo_providers SET enabled = 0').run();
|
||||
|
||||
const result = listTripPhotos(String(trip.id), user.id);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(400);
|
||||
expect((result as any).error.message).toMatch(/no photo providers enabled/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ── listTripAlbumLinks ────────────────────────────────────────────────────────
|
||||
|
||||
describe('listTripAlbumLinks', () => {
|
||||
it('MEM-UNIFIED-003: returns 404 when user cannot access trip', () => {
|
||||
const result = listTripAlbumLinks('9999', 1);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-004: returns 400 when no photo providers are enabled', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
testDb.prepare('UPDATE photo_providers SET enabled = 0').run();
|
||||
|
||||
const result = listTripAlbumLinks(String(trip.id), user.id);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ── addTripPhotos ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('addTripPhotos', () => {
|
||||
it('MEM-UNIFIED-005: returns 404 when user cannot access trip', async () => {
|
||||
const result = await addTripPhotos('9999', 1, false, [{ provider: 'immich', asset_ids: ['a1'] }], 'sid');
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-006: returns 400 when provider is found but disabled (covers line 25)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
// Insert a disabled provider
|
||||
testDb.prepare(
|
||||
'INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run('disabled-prov', 'Disabled', 'Disabled provider', 'Image', 0, 99);
|
||||
|
||||
const result = await addTripPhotos(
|
||||
String(trip.id),
|
||||
user.id,
|
||||
false,
|
||||
[{ provider: 'disabled-prov', asset_ids: ['asset-x'] }],
|
||||
'sid',
|
||||
);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(400);
|
||||
expect((result as any).error.message).toMatch(/not enabled/i);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-007: returns 400 when provider is not found', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
const result = await addTripPhotos(
|
||||
String(trip.id),
|
||||
user.id,
|
||||
false,
|
||||
[{ provider: 'nonexistent-provider', asset_ids: ['asset-x'] }],
|
||||
'sid',
|
||||
);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(400);
|
||||
expect((result as any).error.message).toMatch(/not supported/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ── setTripPhotoSharing ───────────────────────────────────────────────────────
|
||||
|
||||
describe('setTripPhotoSharing', () => {
|
||||
it('MEM-UNIFIED-008: returns 404 when user cannot access trip', async () => {
|
||||
const result = await setTripPhotoSharing('9999', 1, 'immich', 'asset-1', true);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ── removeTripPhoto ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('removeTripPhoto', () => {
|
||||
it('MEM-UNIFIED-009: returns 404 when user cannot access trip', () => {
|
||||
const result = removeTripPhoto('9999', 1, 'immich', 'asset-1');
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ── createTripAlbumLink ───────────────────────────────────────────────────────
|
||||
|
||||
describe('createTripAlbumLink', () => {
|
||||
it('MEM-UNIFIED-010: returns 404 when user cannot access trip', () => {
|
||||
const result = createTripAlbumLink('9999', 1, 'immich', 'album-1', 'My Album');
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-011: returns 400 when provider is disabled', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
testDb.prepare(
|
||||
'INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run('disabled-prov2', 'Disabled2', 'desc', 'Image', 0, 100);
|
||||
|
||||
const result = createTripAlbumLink(String(trip.id), user.id, 'disabled-prov2', 'album-1', 'My Album');
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ── removeAlbumLink ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('removeAlbumLink', () => {
|
||||
it('MEM-UNIFIED-012: returns 404 when user cannot access trip', () => {
|
||||
const result = removeAlbumLink('9999', '1', 1);
|
||||
expect(result.success).toBe(false);
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -94,14 +94,14 @@ describe('getPreferencesMatrix', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { event_types } = getPreferencesMatrix(user.id, 'user');
|
||||
expect(event_types).not.toContain('version_available');
|
||||
expect(event_types.length).toBe(7);
|
||||
expect(event_types.length).toBe(8);
|
||||
});
|
||||
|
||||
it('NPREF-005 — user scope excludes version_available for everyone including admins', () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const { event_types } = getPreferencesMatrix(user.id, 'admin', 'user');
|
||||
expect(event_types).not.toContain('version_available');
|
||||
expect(event_types.length).toBe(7);
|
||||
expect(event_types.length).toBe(8);
|
||||
});
|
||||
|
||||
it('NPREF-005b — admin scope returns only version_available', () => {
|
||||
|
||||
@@ -0,0 +1,939 @@
|
||||
/**
|
||||
* Unit tests for server/src/services/oauthService.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: any, userId: number) =>
|
||||
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: any, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
vi.mock('../../../src/services/apiKeyCrypto', () => ({
|
||||
encrypt_api_key: (v: string) => v,
|
||||
decrypt_api_key: (v: string) => v,
|
||||
maybe_encrypt_api_key: (v: string) => v,
|
||||
}));
|
||||
vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn(), sessions: new Map() }));
|
||||
vi.mock('../../../src/demo/demo-reset', () => ({ saveBaseline: vi.fn() }));
|
||||
vi.mock('../../../src/services/adminService', () => ({
|
||||
isAddonEnabled: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
// PKCE helper — generates a valid code_verifier + code_challenge pair (RFC 7636)
|
||||
function makePkce() {
|
||||
const verifier = crypto.randomBytes(32).toString('base64url'); // 43 chars
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); // 43 chars
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
import {
|
||||
createOAuthClient,
|
||||
listOAuthClients,
|
||||
deleteOAuthClient,
|
||||
rotateOAuthClientSecret,
|
||||
createAuthCode,
|
||||
consumeAuthCode,
|
||||
issueTokens,
|
||||
getUserByAccessToken,
|
||||
refreshTokens,
|
||||
revokeToken,
|
||||
listOAuthSessions,
|
||||
revokeSession,
|
||||
validateAuthorizeRequest,
|
||||
verifyPKCE,
|
||||
authenticateClient,
|
||||
saveConsent,
|
||||
getConsent,
|
||||
isConsentSufficient,
|
||||
} from '../../../src/services/oauthService';
|
||||
import { isAddonEnabled } from '../../../src/services/adminService';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
// Clear oauth tables manually since they're not in the standard reset list
|
||||
testDb.exec('DELETE FROM oauth_tokens');
|
||||
testDb.exec('DELETE FROM oauth_consents');
|
||||
testDb.exec('DELETE FROM oauth_clients');
|
||||
vi.mocked(isAddonEnabled).mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeClient(
|
||||
userId: number,
|
||||
overrides: Partial<{ name: string; redirectUris: string[]; scopes: string[] }> = {}
|
||||
) {
|
||||
return createOAuthClient(
|
||||
userId,
|
||||
overrides.name ?? 'Test Client',
|
||||
overrides.redirectUris ?? ['https://example.com/callback'],
|
||||
overrides.scopes ?? ['trips:read'],
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// createOAuthClient
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('createOAuthClient', () => {
|
||||
it('creates a client successfully and returns client_secret only on creation', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = makeClient(user.id);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.client).toBeDefined();
|
||||
expect(typeof result.client!.client_secret).toBe('string');
|
||||
expect((result.client!.client_secret as string).startsWith('trekcs_')).toBe(true);
|
||||
});
|
||||
|
||||
it('client_id is a UUID', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = makeClient(user.id);
|
||||
expect(result.client!.client_id).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
);
|
||||
});
|
||||
|
||||
it('returns 400 error if name is empty', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, '', ['https://example.com/cb'], ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('Name');
|
||||
});
|
||||
|
||||
it('returns 400 error if name exceeds 100 characters', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const longName = 'A'.repeat(101);
|
||||
const result = createOAuthClient(user.id, longName, ['https://example.com/cb'], ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('100');
|
||||
});
|
||||
|
||||
it('returns 400 error if no redirect URIs provided', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', [], ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('redirect URI');
|
||||
});
|
||||
|
||||
it('returns 400 error if more than 10 redirect URIs provided', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const uris = Array.from({ length: 11 }, (_, i) => `https://example${i}.com/cb`);
|
||||
const result = createOAuthClient(user.id, 'Test', uris, ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('10');
|
||||
});
|
||||
|
||||
it('returns 400 error for invalid URI format', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['not-a-url'], ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('Invalid redirect URI');
|
||||
});
|
||||
|
||||
it('returns 400 error for non-https URI (not localhost)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['http://example.com/cb'], ['trips:read']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('HTTPS');
|
||||
});
|
||||
|
||||
it('allows http://localhost redirect URI', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['http://localhost:3000/callback'], ['trips:read']);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.client).toBeDefined();
|
||||
});
|
||||
|
||||
it('allows http://127.0.0.1 redirect URI', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['http://127.0.0.1:5000/callback'], ['trips:read']);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.client).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns 400 error if no scopes provided', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['https://example.com/cb'], []);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('scope');
|
||||
});
|
||||
|
||||
it('returns 400 error for invalid scopes', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = createOAuthClient(user.id, 'Test', ['https://example.com/cb'], ['invalid:scope']);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain('Invalid scopes');
|
||||
});
|
||||
|
||||
it('enforces max 10 clients per user', () => {
|
||||
const { user } = createUser(testDb);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const r = makeClient(user.id, { name: `Client ${i}` });
|
||||
expect(r.error).toBeUndefined();
|
||||
}
|
||||
const eleventh = makeClient(user.id, { name: 'Eleventh' });
|
||||
expect(eleventh.status).toBe(400);
|
||||
expect(eleventh.error).toContain('10');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listOAuthClients
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('listOAuthClients', () => {
|
||||
it('returns empty array for user with no clients', () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(listOAuthClients(user.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns created clients with redirect_uris and allowed_scopes as arrays', () => {
|
||||
const { user } = createUser(testDb);
|
||||
makeClient(user.id, { name: 'Client A', redirectUris: ['https://a.com/cb'], scopes: ['trips:read', 'budget:read'] });
|
||||
const clients = listOAuthClients(user.id);
|
||||
expect(clients).toHaveLength(1);
|
||||
expect(clients[0].name).toBe('Client A');
|
||||
expect(Array.isArray(clients[0].redirect_uris)).toBe(true);
|
||||
expect(Array.isArray(clients[0].allowed_scopes)).toBe(true);
|
||||
expect(clients[0].allowed_scopes).toContain('trips:read');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// deleteOAuthClient
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('deleteOAuthClient', () => {
|
||||
it('deletes own client successfully', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientRowId = created.client!.id as string;
|
||||
const result = deleteOAuthClient(user.id, clientRowId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(listOAuthClients(user.id)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns 404 for non-existent client', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = deleteOAuthClient(user.id, 'non-existent-id');
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 404 for another user's client", () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const created = makeClient(owner.id);
|
||||
const result = deleteOAuthClient(other.id, created.client!.id as string);
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// rotateOAuthClientSecret
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('rotateOAuthClientSecret', () => {
|
||||
it('rotates secret and returns new client_secret starting with trekcs_', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const oldSecret = created.client!.client_secret as string;
|
||||
const result = rotateOAuthClientSecret(user.id, created.client!.id as string);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.client_secret).toBeDefined();
|
||||
expect((result.client_secret as string).startsWith('trekcs_')).toBe(true);
|
||||
expect(result.client_secret).not.toBe(oldSecret);
|
||||
});
|
||||
|
||||
it('returns 404 for non-existent client', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = rotateOAuthClientSecret(user.id, 'non-existent-id');
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
|
||||
it('revokes old tokens after rotation', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
expect(getUserByAccessToken(access_token)).not.toBeNull();
|
||||
|
||||
rotateOAuthClientSecret(user.id, created.client!.id as string);
|
||||
|
||||
expect(getUserByAccessToken(access_token)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// createAuthCode + consumeAuthCode
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('createAuthCode + consumeAuthCode', () => {
|
||||
it('create code and consume it once returns the pending entry', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const code = createAuthCode({
|
||||
clientId,
|
||||
userId: user.id,
|
||||
redirectUri: 'https://example.com/callback',
|
||||
scopes: ['trips:read'],
|
||||
codeChallenge: 'abc123',
|
||||
codeChallengeMethod: 'S256',
|
||||
});
|
||||
|
||||
const entry = consumeAuthCode(code);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry!.userId).toBe(user.id);
|
||||
expect(entry!.clientId).toBe(clientId);
|
||||
});
|
||||
|
||||
it('returns null for non-existent code', () => {
|
||||
expect(consumeAuthCode('does-not-exist')).toBeNull();
|
||||
});
|
||||
|
||||
it('consuming same code twice returns null (one-time use)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const code = createAuthCode({
|
||||
clientId,
|
||||
userId: user.id,
|
||||
redirectUri: 'https://example.com/callback',
|
||||
scopes: ['trips:read'],
|
||||
codeChallenge: 'abc123',
|
||||
codeChallengeMethod: 'S256',
|
||||
});
|
||||
|
||||
consumeAuthCode(code);
|
||||
expect(consumeAuthCode(code)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// issueTokens + getUserByAccessToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('issueTokens + getUserByAccessToken', () => {
|
||||
it('issues tokens with correct prefixes', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const tokens = issueTokens(clientId, user.id, ['trips:read']);
|
||||
expect(tokens.access_token.startsWith('trekoa_')).toBe(true);
|
||||
expect(tokens.refresh_token.startsWith('trekrf_')).toBe(true);
|
||||
expect(tokens.token_type).toBe('Bearer');
|
||||
expect(typeof tokens.expires_in).toBe('number');
|
||||
});
|
||||
|
||||
it('getUserByAccessToken returns user and scopes for a valid token', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read', 'budget:write']);
|
||||
const info = getUserByAccessToken(access_token);
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.user.email).toBe(user.email);
|
||||
expect(info!.scopes).toContain('trips:read');
|
||||
expect(info!.scopes).toContain('budget:write');
|
||||
});
|
||||
|
||||
it('getUserByAccessToken returns null for unknown token', () => {
|
||||
expect(getUserByAccessToken('trekoa_unknown')).toBeNull();
|
||||
});
|
||||
|
||||
it('getUserByAccessToken returns null for revoked token', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
revokeToken(access_token, clientId);
|
||||
expect(getUserByAccessToken(access_token)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// refreshTokens
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('refreshTokens', () => {
|
||||
it('exchanges a refresh token for a new token pair', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const { refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
const result = refreshTokens(refresh_token, clientId, rawSecret);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.tokens).toBeDefined();
|
||||
expect(result.tokens!.access_token.startsWith('trekoa_')).toBe(true);
|
||||
});
|
||||
|
||||
it('old tokens are revoked after refresh (rotation)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const { access_token, refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
refreshTokens(refresh_token, clientId, rawSecret);
|
||||
expect(getUserByAccessToken(access_token)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns invalid_grant for unknown refresh token', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const result = refreshTokens('trekrf_unknown', clientId, rawSecret);
|
||||
expect(result.error).toBe('invalid_grant');
|
||||
expect(result.status).toBe(400);
|
||||
});
|
||||
|
||||
it('returns invalid_grant for revoked token', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const { access_token, refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
revokeToken(access_token, clientId);
|
||||
const result = refreshTokens(refresh_token, clientId, rawSecret);
|
||||
expect(result.error).toBe('invalid_grant');
|
||||
});
|
||||
|
||||
it('returns invalid_client for wrong client_secret', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
const result = refreshTokens(refresh_token, clientId, 'wrong-secret');
|
||||
expect(result.error).toBe('invalid_client');
|
||||
expect(result.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// revokeToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('revokeToken', () => {
|
||||
it('after revoking access token, getUserByAccessToken returns null', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
expect(getUserByAccessToken(access_token)).not.toBeNull();
|
||||
|
||||
revokeToken(access_token, clientId);
|
||||
expect(getUserByAccessToken(access_token)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listOAuthSessions + revokeSession
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('listOAuthSessions + revokeSession', () => {
|
||||
it('lists active sessions', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
issueTokens(clientId, user.id, ['trips:read']);
|
||||
const sessions = listOAuthSessions(user.id);
|
||||
expect(sessions).toHaveLength(1);
|
||||
expect(sessions[0].client_id).toBe(clientId);
|
||||
});
|
||||
|
||||
it('revoked session is not listed', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
revokeToken(access_token, clientId);
|
||||
const sessions = listOAuthSessions(user.id);
|
||||
expect(sessions).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('revokeSession returns 404 for unknown session', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = revokeSession(user.id, 99999);
|
||||
expect(result.status).toBe(404);
|
||||
});
|
||||
|
||||
it('revokeSession by session id removes session from list', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
issueTokens(clientId, user.id, ['trips:read']);
|
||||
const sessions = listOAuthSessions(user.id);
|
||||
const sessionId = sessions[0].id as number;
|
||||
|
||||
const result = revokeSession(user.id, sessionId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(listOAuthSessions(user.id)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// validateAuthorizeRequest
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('validateAuthorizeRequest', () => {
|
||||
// Use a proper 43-char S256 code_challenge to pass H1 format validation
|
||||
const { challenge: VALID_CHALLENGE } = makePkce();
|
||||
|
||||
function makeParams(overrides: Partial<{
|
||||
response_type: string;
|
||||
client_id: string;
|
||||
redirect_uri: string;
|
||||
scope: string;
|
||||
code_challenge: string;
|
||||
code_challenge_method: string;
|
||||
}> = {}) {
|
||||
return {
|
||||
response_type: 'code',
|
||||
client_id: '',
|
||||
redirect_uri: 'https://example.com/callback',
|
||||
scope: 'trips:read',
|
||||
code_challenge: VALID_CHALLENGE,
|
||||
code_challenge_method: 'S256',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it('returns mcp_disabled when isAddonEnabled returns false', () => {
|
||||
vi.mocked(isAddonEnabled).mockReturnValue(false);
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: 'x' }), null);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('mcp_disabled');
|
||||
});
|
||||
|
||||
it('requires response_type=code', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = validateAuthorizeRequest(makeParams({ response_type: 'token', client_id: 'x' }), user.id);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('unsupported_response_type');
|
||||
});
|
||||
|
||||
it('requires PKCE with S256', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: 'x', code_challenge_method: 'plain' }), user.id);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('requires valid client_id', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: 'nonexistent' }), user.id);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_client');
|
||||
});
|
||||
|
||||
it('validates redirect_uri against registered URIs', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id, { redirectUris: ['https://example.com/callback'] });
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const result = validateAuthorizeRequest(
|
||||
makeParams({ client_id: clientId, redirect_uri: 'https://evil.com/callback' }),
|
||||
user.id
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_redirect_uri');
|
||||
});
|
||||
|
||||
it('validates scope against client allowed_scopes', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id, { scopes: ['trips:read'] });
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const result = validateAuthorizeRequest(
|
||||
makeParams({ client_id: clientId, scope: 'budget:write' }),
|
||||
user.id
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_scope');
|
||||
});
|
||||
|
||||
it('returns loginRequired when userId is null', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), null);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.loginRequired).toBe(true);
|
||||
});
|
||||
|
||||
it('returns consentRequired=true when consent not yet saved', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), user.id);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.consentRequired).toBe(true);
|
||||
});
|
||||
|
||||
it('returns consentRequired=false when consent already saved and sufficient', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
saveConsent(clientId, user.id, ['trips:read']);
|
||||
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), user.id);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.consentRequired).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// verifyPKCE
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('verifyPKCE', () => {
|
||||
it('returns true for valid code_verifier / code_challenge pair (SHA256 base64url)', () => {
|
||||
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
||||
expect(verifyPKCE(verifier, challenge)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for wrong verifier', () => {
|
||||
const verifier = 'correct-verifier';
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
||||
expect(verifyPKCE('wrong-verifier', challenge)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// authenticateClient
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('authenticateClient', () => {
|
||||
it('returns client row for correct credentials', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const client = authenticateClient(clientId, rawSecret);
|
||||
expect(client).not.toBeNull();
|
||||
expect(client!.client_id).toBe(clientId);
|
||||
});
|
||||
|
||||
it('returns null for wrong secret', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
expect(authenticateClient(clientId, 'wrong-secret')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for unknown client_id', () => {
|
||||
expect(authenticateClient('unknown-client-id', 'any-secret')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// saveConsent + getConsent + isConsentSufficient
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('saveConsent + getConsent + isConsentSufficient', () => {
|
||||
it('saves and retrieves consent', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
saveConsent(clientId, user.id, ['trips:read', 'budget:write']);
|
||||
const consent = getConsent(clientId, user.id);
|
||||
expect(consent).not.toBeNull();
|
||||
expect(consent).toContain('trips:read');
|
||||
expect(consent).toContain('budget:write');
|
||||
});
|
||||
|
||||
it('isConsentSufficient returns true when all requested scopes are in existing', () => {
|
||||
expect(isConsentSufficient(['trips:read', 'budget:write'], ['trips:read'])).toBe(true);
|
||||
expect(isConsentSufficient(['trips:read', 'budget:write'], ['trips:read', 'budget:write'])).toBe(true);
|
||||
});
|
||||
|
||||
it('isConsentSufficient returns false when some scopes are missing', () => {
|
||||
expect(isConsentSufficient(['trips:read'], ['trips:read', 'budget:write'])).toBe(false);
|
||||
expect(isConsentSufficient([], ['trips:read'])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M5 — saveConsent unions instead of replacing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('saveConsent — scope union (M5)', () => {
|
||||
it('unioning scopes: approving B after A leaves both in consent', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id, { scopes: ['trips:read', 'budget:write'] });
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
saveConsent(clientId, user.id, ['trips:read']);
|
||||
saveConsent(clientId, user.id, ['budget:write']);
|
||||
|
||||
const consent = getConsent(clientId, user.id);
|
||||
expect(consent).toContain('trips:read');
|
||||
expect(consent).toContain('budget:write');
|
||||
});
|
||||
|
||||
it('re-approving a superset scope still preserves previously-consented scopes', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id, { scopes: ['trips:read', 'trips:write'] });
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
saveConsent(clientId, user.id, ['trips:read', 'trips:write']);
|
||||
// approve only trips:read on a later request
|
||||
saveConsent(clientId, user.id, ['trips:read']);
|
||||
|
||||
const consent = getConsent(clientId, user.id);
|
||||
// trips:write should NOT be removed (union semantics)
|
||||
expect(consent).toContain('trips:read');
|
||||
expect(consent).toContain('trips:write');
|
||||
});
|
||||
|
||||
it('consent is sufficient after sequential approvals — no re-prompt needed', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id, { scopes: ['trips:read', 'budget:write'] });
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
saveConsent(clientId, user.id, ['trips:read']);
|
||||
saveConsent(clientId, user.id, ['budget:write']);
|
||||
|
||||
// Should not require consent again for either scope
|
||||
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['trips:read'])).toBe(true);
|
||||
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['budget:write'])).toBe(true);
|
||||
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['trips:read', 'budget:write'])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C2 — getUserByAccessToken returns clientId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('getUserByAccessToken — includes clientId (C2)', () => {
|
||||
it('returns clientId matching the issuing OAuth client', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
const info = getUserByAccessToken(access_token);
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.clientId).toBe(clientId);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C3 — Refresh token replay detection and chain revocation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('refreshTokens — replay detection (C3)', () => {
|
||||
it('replaying a revoked refresh token returns invalid_grant', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
// Issue tokens, then rotate once (old token becomes revoked)
|
||||
const { refresh_token: firstRefresh } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
const rotateResult = refreshTokens(firstRefresh, clientId, rawSecret);
|
||||
expect(rotateResult.error).toBeUndefined();
|
||||
const { refresh_token: secondRefresh } = rotateResult.tokens!;
|
||||
|
||||
// Replay the FIRST (now revoked) refresh token
|
||||
const replayResult = refreshTokens(firstRefresh, clientId, rawSecret);
|
||||
expect(replayResult.error).toBe('invalid_grant');
|
||||
expect(replayResult.status).toBe(400);
|
||||
});
|
||||
|
||||
it('replaying a revoked token also revokes the entire rotation chain', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
// Issue → rotate once
|
||||
const { refresh_token: first } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
const r1 = refreshTokens(first, clientId, rawSecret);
|
||||
const { access_token: access2, refresh_token: second } = r1.tokens!;
|
||||
|
||||
// Replay first (revoked) refresh token → chain revoke
|
||||
refreshTokens(first, clientId, rawSecret);
|
||||
|
||||
// The rotated access token should also be dead now
|
||||
expect(getUserByAccessToken(access2)).toBeNull();
|
||||
|
||||
// The second refresh token should also be revoked
|
||||
const r2 = refreshTokens(second, clientId, rawSecret);
|
||||
expect(r2.error).toBe('invalid_grant');
|
||||
});
|
||||
|
||||
it('new rotation chain after replay is independent', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const rawSecret = created.client!.client_secret as string;
|
||||
|
||||
const { refresh_token: first } = issueTokens(clientId, user.id, ['trips:read']);
|
||||
// Rotate once
|
||||
const r1 = refreshTokens(first, clientId, rawSecret);
|
||||
const { refresh_token: second } = r1.tokens!;
|
||||
// Rotate again on the second token
|
||||
const r2 = refreshTokens(second, clientId, rawSecret);
|
||||
expect(r2.error).toBeUndefined();
|
||||
const { refresh_token: third } = r2.tokens!;
|
||||
|
||||
// Replay the first revoked token → revokes chain containing first+second+third
|
||||
refreshTokens(first, clientId, rawSecret);
|
||||
|
||||
// third should now be revoked too (it's in the same chain)
|
||||
const r3 = refreshTokens(third, clientId, rawSecret);
|
||||
expect(r3.error).toBe('invalid_grant');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// H1 — PKCE code_challenge / code_verifier format validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('verifyPKCE — format validation (H1)', () => {
|
||||
it('returns false for a code_verifier that is too short (< 43 chars)', () => {
|
||||
const { challenge } = makePkce();
|
||||
expect(verifyPKCE('short', challenge)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for a code_verifier that is too long (> 128 chars)', () => {
|
||||
const { challenge } = makePkce();
|
||||
const longVerifier = 'a'.repeat(129);
|
||||
expect(verifyPKCE(longVerifier, challenge)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for a code_verifier with invalid characters', () => {
|
||||
const { challenge } = makePkce();
|
||||
const badVerifier = 'A'.repeat(42) + ' '; // space is not allowed
|
||||
expect(verifyPKCE(badVerifier, challenge)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for a valid 43-char verifier matching its challenge', () => {
|
||||
const { verifier, challenge } = makePkce();
|
||||
expect(verifyPKCE(verifier, challenge)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateAuthorizeRequest — PKCE format (H1)', () => {
|
||||
it('returns invalid_request when code_challenge is shorter than 43 chars', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
const result = validateAuthorizeRequest({
|
||||
response_type: 'code',
|
||||
client_id: clientId,
|
||||
redirect_uri: 'https://example.com/callback',
|
||||
scope: 'trips:read',
|
||||
code_challenge: 'tooshort',
|
||||
code_challenge_method: 'S256',
|
||||
}, user.id);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('returns invalid_request when code_challenge contains invalid characters', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
|
||||
// 43 chars but includes '=' which is not base64url
|
||||
const badChallenge = '='.repeat(43);
|
||||
const result = validateAuthorizeRequest({
|
||||
response_type: 'code',
|
||||
client_id: clientId,
|
||||
redirect_uri: 'https://example.com/callback',
|
||||
scope: 'trips:read',
|
||||
code_challenge: badChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
}, user.id);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toBe('invalid_request');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// H3 — validateAuthorizeRequest: loginRequired response strips client info
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('validateAuthorizeRequest — unauthenticated strips client info (H3)', () => {
|
||||
it('loginRequired response does not include client.name or allowed_scopes', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = created.client!.client_id as string;
|
||||
const { challenge } = makePkce();
|
||||
|
||||
const result = validateAuthorizeRequest({
|
||||
response_type: 'code',
|
||||
client_id: clientId,
|
||||
redirect_uri: 'https://example.com/callback',
|
||||
scope: 'trips:read',
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: 'S256',
|
||||
}, null /* unauthenticated */);
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.loginRequired).toBe(true);
|
||||
// Must NOT expose client metadata to unauthenticated callers
|
||||
expect(result.client).toBeUndefined();
|
||||
expect(result.scopes).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -389,3 +389,74 @@ describe('findOrCreateUser', () => {
|
||||
expect(token.used_count).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── exchangeCodeForToken ──────────────────────────────────────────────────────
|
||||
|
||||
describe('exchangeCodeForToken', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('OIDC-SVC-030: sends correct POST body and returns token data', async () => {
|
||||
const { exchangeCodeForToken } = await import('../../../src/services/oidcService');
|
||||
|
||||
const mockTokenData = { access_token: 'tok', token_type: 'Bearer' };
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => mockTokenData,
|
||||
}));
|
||||
|
||||
const doc = { token_endpoint: 'https://oidc.example.com/token' } as any;
|
||||
const result = await exchangeCodeForToken(doc, 'auth-code-123', 'https://app/callback', 'client-id', 'client-secret');
|
||||
|
||||
expect(result.access_token).toBe('tok');
|
||||
expect(result._ok).toBe(true);
|
||||
expect(result._status).toBe(200);
|
||||
|
||||
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(fetchCall[0]).toBe('https://oidc.example.com/token');
|
||||
expect(fetchCall[1].method).toBe('POST');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-031: reflects _ok=false when provider returns error status', async () => {
|
||||
const { exchangeCodeForToken } = await import('../../../src/services/oidcService');
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 400,
|
||||
json: async () => ({ error: 'invalid_grant' }),
|
||||
}));
|
||||
|
||||
const doc = { token_endpoint: 'https://oidc.example.com/token' } as any;
|
||||
const result = await exchangeCodeForToken(doc, 'bad-code', 'https://app/callback', 'c', 's');
|
||||
|
||||
expect(result._ok).toBe(false);
|
||||
expect(result._status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getUserInfo ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('getUserInfo', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('OIDC-SVC-032: fetches userinfo with Bearer token and returns parsed JSON', async () => {
|
||||
const { getUserInfo } = await import('../../../src/services/oidcService');
|
||||
|
||||
const userInfoData = { sub: 'user-sub', email: 'user@example.com', name: 'User Name' };
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
json: async () => userInfoData,
|
||||
}));
|
||||
|
||||
const result = await getUserInfo('https://oidc.example.com/userinfo', 'access-token-123');
|
||||
|
||||
expect(result.sub).toBe('user-sub');
|
||||
expect(result.email).toBe('user@example.com');
|
||||
|
||||
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(fetchCall[1].headers.Authorization).toBe('Bearer access-token-123');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createAdmin } from '../../helpers/factories';
|
||||
import { checkAndNotifyVersion } from '../../../src/services/adminService';
|
||||
import { checkAndNotifyVersion, __clearVersionCacheForTests } from '../../../src/services/adminService';
|
||||
|
||||
// Helper: mock the GitHub releases/latest endpoint
|
||||
function mockGitHubLatest(tagName: string, ok = true): void {
|
||||
@@ -63,6 +63,7 @@ beforeAll(() => {
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
__clearVersionCacheForTests();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user