diff --git a/REVIEW.md b/REVIEW.md index 183d7ac..578dad8 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -166,7 +166,7 @@ Companion web, depuis `web/` : ```bash npm ci -npm test # vitest : schémas de données de sync (web/src/lib/syncData.test.ts) +npm test # vitest : schémas de sync (syncData.test.ts) et isolation des comptes sur la vraie route, PGlite en mémoire (api/sync/route.test.ts) npx tsc --noEmit npm run lint npm run build diff --git a/web/package-lock.json b/web/package-lock.json index afa7702..658ceed 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -30,6 +30,7 @@ "@types/react-dom": "^19", "@types/ws": "^8.18.1", "drizzle-kit": "^0.31.10", + "electric-sql-pglite": "npm:@electric-sql/pglite@^0.5.10", "eslint": "^9", "eslint-config-next": "16.2.2", "tailwindcss": "^4", @@ -4421,6 +4422,14 @@ "node": ">= 0.4" } }, + "node_modules/electric-sql-pglite": { + "name": "@electric-sql/pglite", + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.10.tgz", + "integrity": "sha512-tXc/25U3ulOkiRQuTFdwIv+JhBqtMdAF7Gvo6CfZZWtSB4+hgC4Wr2vwK5ngvvN5PJfAAEGIsfyCVy1JhCOBYw==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/electron-to-chromium": { "version": "1.5.331", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.331.tgz", diff --git a/web/package.json b/web/package.json index 261006b..1fb952e 100644 --- a/web/package.json +++ b/web/package.json @@ -32,6 +32,7 @@ "@types/react-dom": "^19", "@types/ws": "^8.18.1", "drizzle-kit": "^0.31.10", + "electric-sql-pglite": "npm:@electric-sql/pglite@^0.5.10", "eslint": "^9", "eslint-config-next": "16.2.2", "tailwindcss": "^4", diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts new file mode 100644 index 0000000..7878d36 --- /dev/null +++ b/web/src/app/api/sync/route.test.ts @@ -0,0 +1,198 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import type { PGlite } from 'electric-sql-pglite'; + +// Account-isolation tests for POST /api/sync (#142): the real route handler +// runs against an in-memory Postgres (PGlite) with the companion migrations, +// and two accounts. Auth and rate limiting are stubbed; they are not under test. + +const h = await vi.hoisted(async () => { + const { PGlite } = await import('electric-sql-pglite'); + return { pg: new PGlite() as PGlite, userId: '' }; +}); + +vi.mock('@/db/client', async () => { + const { drizzle } = await import('drizzle-orm/pglite'); + const schema = await import('@/db/schema'); + return { db: drizzle(h.pg, { schema }) }; +}); + +vi.mock('@/lib/api', () => ({ + requireAuth: async () => ({ userId: h.userId }), + parseBody: async (request: Request, parse: (d: unknown) => T) => { + try { + return { data: parse(await request.json()) }; + } catch (e) { + return { error: new Response(String(e), { status: 400 }) }; + } + }, +})); + +vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); + +const { POST } = await import('./route'); + +type Op = [entityType: string, action: string, entityId: string, data?: Record]; + +async function push(userId: string, ops: Op[]): Promise { + h.userId = userId; + const operations = ops.map(([entityType, action, entityId, data]) => ({ + idempotencyKey: u(), entityType, action, entityId, ...(data ? { data } : {}), + })); + const res = await POST(new Request('http://localhost/api/sync', { + method: 'POST', + body: JSON.stringify({ operations }), + })); + expect(res.status).toBe(200); + const body = await res.json() as { results: { status: string }[] }; + return body.results.map((r) => r.status); +} + +async function row>(sql: string, params: unknown[]): Promise { + return (await h.pg.query(sql, params)).rows[0]; +} + +const D = '2026-10-19T12:00:00.000Z'; +const A = { inbox: u(), list: u(), task: u(), tag: u() }; +const B = { inbox: u(), list: u(), task: u(), tag: u(), sub: u(), parent: u() }; + +beforeAll(async () => { + const dir = path.join(__dirname, '../../../db/migrations'); + for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await h.pg.exec(stmt); + } + } + + // Payload shapes copied from src/db/repository/* and initialMerge (src/services/syncClient.ts) + expect(await push('userA', [ + ['list', 'create', A.inbox, { name: 'Inbox', color: '#4A90A4', icon: 'inbox', position: 0, isInbox: true }], + ['list', 'create', A.list, { id: A.list, name: 'A list', color: null, icon: null, position: 1, isInbox: false }], + ['task', 'create', A.task, { id: A.task, title: 'A task', notes: null, completed: false, completedAt: null, priority: 0, dueDate: null, listId: A.list, parentId: null, recurrence: null }], + ['tag', 'create', A.tag, { id: A.tag, name: 'a-tag', color: '#E57373' }], + ['taskTag', 'create', A.task, { tagId: A.tag }], + ])).toEqual(Array(5).fill('applied')); +}); + +describe('POST /api/sync: payloads the app sends today', () => { + it('applies an initialMerge batch (nulls, 10000-char notes, subtask before its parent)', async () => { + const results = await push('userB', [ + ['list', 'create', B.inbox, { name: 'Inbox', color: null, icon: null, position: 0, isInbox: true }], + ['list', 'create', B.list, { id: B.list, name: 'B list', color: null, icon: null, position: 1, isInbox: false }], + ['list', 'update', B.list, { id: B.list, name: 'B list 2', color: '#C17767', icon: null }], + ['task', 'create', B.task, { id: B.task, title: 'B task', notes: null, completed: false, completedAt: null, priority: 1, dueDate: D, listId: B.inbox, parentId: null, recurrence: null }], + ['task', 'create', B.sub, { title: 'B sub', completed: false, priority: 0, listId: B.list, parentId: B.parent, position: 0 }], + ['task', 'create', B.parent, { title: 'B parent', completed: false, priority: 0, listId: B.list, position: 1 }], + ['task', 'update', B.task, { id: B.task, title: 'B task', notes: 'n'.repeat(10000), completed: true, completedAt: D, priority: 3, dueDate: null, listId: B.inbox, parentId: null, recurrence: 'weekly' }], + ['tag', 'create', B.tag, { id: B.tag, name: 'b-tag', color: '#8BA889' }], + ['tag', 'update', B.tag, { id: B.tag, name: 'b-tag-2', color: '#7B68EE' }], + ['taskTag', 'create', B.task, { tagId: B.tag }], + ]); + expect(results).toEqual(Array(10).fill('applied')); + expect(await row('select length(notes) n, completed from sl_tasks where id=$1', [B.task])) + .toEqual({ n: 10000, completed: true }); + expect(await row('select parent_id from sl_tasks where id=$1', [B.sub])).toEqual({ parent_id: B.parent }); + }); +}); + +describe('POST /api/sync: mass assignment', () => { + it('does not move a list to another account through data.userId', async () => { + expect(await push('userB', [['list', 'update', B.list, { userId: 'userA', name: 'moved?' }]])).toEqual(['applied']); + expect(await row('select user_id, name from sl_lists where id=$1', [B.list])) + .toEqual({ user_id: 'userB', name: 'moved?' }); + }); + + it('ignores userId, id, createdAt, deletedAt and isInbox on list, task and tag updates', async () => { + const evil = { userId: 'userA', id: u(), createdAt: '2000-01-01T00:00:00.000Z', deletedAt: D, isInbox: true }; + expect(await push('userB', [ + ['list', 'update', B.list, { ...evil, name: 'renamed' }], + ['task', 'update', B.task, { ...evil, title: 'renamed' }], + ['tag', 'update', B.tag, { ...evil, name: 'renamed' }], + ])).toEqual(['applied', 'applied', 'applied']); + for (const [table, id] of [['sl_lists', B.list], ['sl_tasks', B.task], ['sl_tags', B.tag]]) { + const r = await row<{ user_id: string; deleted_at: Date | null; created_at: Date }>( + `select user_id, deleted_at, created_at from ${table} where id=$1`, [id]); + expect(r?.user_id).toBe('userB'); + expect(r?.deleted_at).toBeNull(); + expect(r?.created_at.getFullYear()).toBeGreaterThan(2000); + } + expect(await row('select is_inbox from sl_lists where id=$1', [B.list])).toEqual({ is_inbox: false }); + }); + + it('applies a tag update carrying only forbidden keys without writing anything', async () => { + expect(await push('userB', [['tag', 'update', B.tag, { userId: 'userA' }]])).toEqual(['applied']); + expect(await row('select user_id, name from sl_tags where id=$1', [B.tag])).toEqual({ user_id: 'userB', name: 'renamed' }); + }); +}); + +describe('POST /api/sync: task-tag links', () => { + it('refuses a link to another account\'s task', async () => { + expect(await push('userB', [['taskTag', 'create', A.task, { tagId: B.tag }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_task_tags where task_id=$1 and tag_id=$2', [A.task, B.tag])).toEqual({ c: 0 }); + }); + + it('refuses a link to another account\'s tag', async () => { + expect(await push('userB', [['taskTag', 'create', B.task, { tagId: A.tag }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_task_tags where task_id=$1 and tag_id=$2', [B.task, A.tag])).toEqual({ c: 0 }); + }); + + it('refuses to delete another account\'s link', async () => { + expect(await push('userB', [['taskTag', 'delete', A.task, { tagId: A.tag }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_task_tags where task_id=$1 and tag_id=$2', [A.task, A.tag])).toEqual({ c: 1 }); + }); +}); + +describe('POST /api/sync: task references', () => { + it('refuses a task created in another account\'s list', async () => { + const id = u(); + expect(await push('userB', [['task', 'create', id, { title: 'x', listId: A.list }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); + }); + + it('refuses a task created under another account\'s task', async () => { + const id = u(); + expect(await push('userB', [['task', 'create', id, { title: 'x', listId: B.list, parentId: A.task }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); + }); + + it('refuses moving a task into another account\'s list or under its task', async () => { + expect(await push('userB', [ + ['task', 'update', B.task, { listId: A.list }], + ['task', 'update', B.task, { parentId: A.task }], + ])).toEqual(['skipped', 'skipped']); + expect(await row('select list_id, parent_id from sl_tasks where id=$1', [B.task])) + .toEqual({ list_id: B.inbox, parent_id: null }); + }); + + it('still lets the owner move a task between its own lists', async () => { + expect(await push('userB', [['task', 'update', B.sub, { listId: B.inbox }]])).toEqual(['applied']); + expect(await row('select list_id from sl_tasks where id=$1', [B.sub])).toEqual({ list_id: B.inbox }); + }); +}); + +describe('POST /api/sync: list creation with an id taken by another account', () => { + it('refuses an inbox create before moving tasks or archiving the caller\'s inbox', async () => { + expect(await push('userB', [['list', 'create', A.list, { name: 'hijack', isInbox: true }]])).toEqual(['skipped']); + expect(await row('select deleted_at from sl_lists where id=$1', [B.inbox])).toEqual({ deleted_at: null }); + expect(await row('select list_id from sl_tasks where id=$1', [B.task])).toEqual({ list_id: B.inbox }); + expect(await row('select user_id, name from sl_lists where id=$1', [A.list])).toEqual({ user_id: 'userA', name: 'A list' }); + }); + + it('refuses a regular list create', async () => { + expect(await push('userB', [['list', 'create', A.inbox, { name: 'hijack' }]])).toEqual(['skipped']); + expect(await row('select user_id, name from sl_lists where id=$1', [A.inbox])).toEqual({ user_id: 'userA', name: 'Inbox' }); + }); +}); + +describe('POST /api/sync: owner deletes', () => { + it('applies deletes of the caller\'s own rows and links', async () => { + expect(await push('userB', [ + ['taskTag', 'delete', B.task, { tagId: B.tag }], + ['task', 'delete', B.sub, { id: B.sub }], + ['tag', 'delete', B.tag, { id: B.tag }], + ])).toEqual(['applied', 'applied', 'applied']); + expect(await row('select count(*)::int c from sl_task_tags where task_id=$1', [B.task])).toEqual({ c: 0 }); + }); +}); diff --git a/web/vitest.config.mts b/web/vitest.config.mts new file mode 100644 index 0000000..30a25e0 --- /dev/null +++ b/web/vitest.config.mts @@ -0,0 +1,19 @@ +import { fileURLToPath } from 'node:url'; +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + resolve: { + alias: [ + // Mirrors the `@/*` path of tsconfig.json so tests can import route handlers. + { find: /^@\//, replacement: fileURLToPath(new URL('./src/', import.meta.url)) }, + // PGlite is installed under an npm alias (devDependency `electric-sql-pglite`): + // under its real name it would satisfy drizzle-orm's optional peer and land + // in the production image (`npm ci --omit=dev`), 35 MB for a test database. + { find: /^@electric-sql\/pglite$/, replacement: 'electric-sql-pglite' }, + ], + }, + test: { + // drizzle-orm/pglite imports `@electric-sql/pglite`: inline it so the alias applies. + server: { deps: { inline: ['drizzle-orm'] } }, + }, +});