fix(security): whitelist sync data columns and check ownership of references #144
9 changed files with 2201 additions and 149 deletions
10
REVIEW.md
10
REVIEW.md
|
|
@ -27,7 +27,7 @@ Motifs : chemins depuis la racine. `*` ne traverse jamais un `/` ; `**/` vaut z
|
|||
| Motif | Condition | Zone |
|
||||
|---|---|---|
|
||||
| `src/lib/{authToken,logtoConfig,validation}.ts`, `web/src/lib/{auth,logto,api}.ts`, `web/src/middleware.ts`, `web/src/app/api/logto/**`, `web/src/app/auth/**` | toujours | Authentification |
|
||||
| `web/src/app/api/**`, `web/src/lib/{validators,rateLimit,ws}.ts`, `web/server.ts` | toujours | API et isolation des comptes |
|
||||
| `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws}.ts`, `web/server.ts` | toujours | API et isolation des comptes |
|
||||
| `src/services/syncClient.ts`, `src/db/repository/outbox.ts` | toujours | Sync |
|
||||
| `src/db/{schema,client}.ts`, `src/db/migrations/**`, `web/src/db/{schema,client,seed}.ts`, `web/src/db/migrations/**`, `drizzle.config.ts`, `web/drizzle.config.ts`, `sql-transformer.js` | toujours | Migrations et données |
|
||||
| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`) | Migrations et données, Authentification, Sync |
|
||||
|
|
@ -90,7 +90,8 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
|
|||
### API et isolation des comptes
|
||||
|
||||
- Toute lecture et toute écriture filtrent sur `userId = auth.userId` ; une mise à jour ou une suppression vérifie d'abord la propriété (`verifyOwnership`). Une jointure (étiquettes d'une tâche) vérifie la propriété des deux côtés. — `web/src/app/api/sync/route.ts`, `web/src/app/api/tasks/[id]/route.ts`
|
||||
- Le corps est validé par un schéma zod `.strict()`. `data` d'une opération de sync est un `z.record(z.unknown())` : une route ne le recopie jamais tel quel dans un `.set()` ou un `.values()`, elle choisit ses colonnes, sans quoi un client peut écrire `userId` ou `id`. — `web/src/lib/validators.ts`, `web/src/app/api/sync/route.ts`
|
||||
- Le corps est validé par un schéma zod `.strict()`. Exception : `data` d'une opération de sync passe par un schéma par entité et par action (`web/src/lib/syncData.ts`), sans `.strict()` : les clés hors liste sont retirées, pas rejetées, parce que l'app marque son outbox comme synchronisée dès que le push répond 200 et qu'une opération `skipped` serait perdue. Ces schémas ne nomment jamais `id`, `userId`, `createdAt`, `updatedAt` ni `deletedAt`, et `processOperation` n'écrit que leur sortie. Une colonne ajoutée côté app l'est aussi dans le schéma, sinon elle est ignorée en silence. — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts`, #142
|
||||
- Une référence reçue du client (`listId`, `parentId`, `tagId`, l'id d'une liste créée) est vérifiée contre le compte de l'appelant avant l'écriture. `parentId` et l'id d'une création refusent seulement un id pris par un autre compte, sans exiger que la ligne existe : `initialMerge` pousse tout en un lot, une sous-tâche peut arriver avant son parent. — `web/src/app/api/sync/route.ts`, #142
|
||||
- Limites de débit par utilisateur et par catégorie (`sync`, `create`, `read`, `ws-ticket`) ; une route ajoutée en prend une. Le store est en mémoire : il repart à zéro à chaque redémarrage. — `web/src/lib/rateLimit.ts`
|
||||
- WebSocket : ticket à usage unique de 30 s, origines autorisées listées, revalidation toutes les 15 min ; aucun paramètre de requête de `/ws` n'est journalisé. — `web/src/lib/ws.ts`, `web/src/app/api/ws-ticket/route.ts`, `web/server.ts`
|
||||
- Une route de diagnostic (`/api/debug`) ne renvoie que les données de la session qui l'appelle, jamais de secret ni de valeur de cookie. — `web/src/app/api/debug/route.ts`
|
||||
|
|
@ -165,20 +166,21 @@ Companion web, depuis `web/` :
|
|||
|
||||
```bash
|
||||
npm ci
|
||||
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
|
||||
```
|
||||
|
||||
- Comparer deux exports : `(cd <dossier> && find . -type f | sort | xargs sha256sum)` sur l'arbre de base deux fois (déterminisme), puis sur la PR ; même nombre de fichiers et mêmes empreintes, ou une différence expliquée.
|
||||
- Un `npm test` ne compte qu'après une sonde : une vérification volontairement rouge doit le faire sortir en code non nul (`smoke FAIL`, sortie 1).
|
||||
- Un `npm test` ne compte qu'après une sonde : une vérification volontairement rouge doit le faire sortir en code non nul (`smoke FAIL`, sortie 1 ; côté `web/`, une assertion de vitest volontairement fausse, sortie 1).
|
||||
- Ce que ces commandes ne prouvent pas : le comportement sur un appareil (widget, notifications, connexion Logto, sync réelle), qui se teste sur un build de développement ; le site déployé, qui se vérifie après le déploiement manuel.
|
||||
|
||||
## Pièges de revue
|
||||
|
||||
- **Tests verts, build cassé.** Le smoke test ne charge ni Babel ni Metro : seul l'export Expo prouve le bundle (PR #118). — `STATE.md` (2026-09-25)
|
||||
- **Le Bearer ouvre le middleware.** Une route d'API qui oublie `requireAuth()` n'est pas protégée par le middleware dès que la requête porte un `Bearer`, même invalide. Lire le début de chaque route ajoutée. — `web/src/middleware.ts`
|
||||
- **`...data` dans un `.set()`.** Le code de sync recopie aujourd'hui `data` dans les mises à jour de listes, de tâches et d'étiquettes, et le lien tâche-étiquette ne vérifie la propriété ni de la tâche ni de l'étiquette : une PR qui touche `processOperation` ne doit pas étendre ce motif. Correctif suivi dans #142. — `web/src/app/api/sync/route.ts`, #142
|
||||
- **`...data` dans un `.set()`.** Jusqu'à #142, le code de sync recopiait `data` dans les mises à jour, et un client pouvait écrire `userId`. Une PR qui touche `processOperation` passe `data` par un schéma de `syncData.ts` avant tout `.set()` ou `.values()`, et un `...d` n'y est acceptable que sur la sortie d'un de ces schémas. — `web/src/app/api/sync/route.ts`, #142
|
||||
- **Le serveur n'a pas d'`updatedAt` sur les étiquettes.** `createdAt` sert de date de changement au pull : une étiquette renommée n'est pas renvoyée à l'app. — revue de la PR #58, `web/src/app/api/sync/route.ts`
|
||||
- **Polling, pas de requêtes vivantes.** Les écrans relisent SQLite toutes les 500 ms ; un état global de tâches ajouté contourne cette convention. — `CLAUDE.md` « Conventions »
|
||||
- **Widget headless.** `widgetState.ts` reste léger (pas de DB, de drizzle ni de date-fns), le smoke test verrouille son graphe d'import ; un import ajouté rallonge le cold start de chaque tap. — `CLAUDE.md` « Widget Android »
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ HIGH_ALWAYS = [
|
|||
"src/lib/{authToken,logtoConfig,validation}.ts",
|
||||
"web/src/lib/{auth,logto,api}.ts", "web/src/middleware.ts",
|
||||
"web/src/app/api/logto/**", "web/src/app/auth/**",
|
||||
"web/src/app/api/**", "web/src/lib/{validators,rateLimit,ws}.ts", "web/server.ts",
|
||||
"web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws}.ts", "web/server.ts",
|
||||
"src/services/syncClient.ts", "src/db/repository/outbox.ts",
|
||||
"src/db/{schema,client}.ts", "src/db/migrations/**",
|
||||
"web/src/db/{schema,client,seed}.ts", "web/src/db/migrations/**",
|
||||
|
|
|
|||
1573
web/package-lock.json
generated
1573
web/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -6,7 +6,8 @@
|
|||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
"lint": "eslint",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@logto/next": "^4.2.9",
|
||||
|
|
@ -31,9 +32,11 @@
|
|||
"@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",
|
||||
"typescript": "^5"
|
||||
"typescript": "^5",
|
||||
"vitest": "^4.1.12"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
198
web/src/app/api/sync/route.test.ts
Normal file
198
web/src/app/api/sync/route.test.ts
Normal file
|
|
@ -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 <T,>(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<string, unknown>];
|
||||
|
||||
async function push(userId: string, ops: Op[]): Promise<string[]> {
|
||||
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<T = Record<string, unknown>>(sql: string, params: unknown[]): Promise<T | undefined> {
|
||||
return (await h.pg.query<T>(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 });
|
||||
});
|
||||
});
|
||||
|
|
@ -5,6 +5,15 @@ import { eq, and, gte, isNull } from 'drizzle-orm';
|
|||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { rateLimit } from '@/lib/rateLimit';
|
||||
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
|
||||
import {
|
||||
listCreateData,
|
||||
listUpdateData,
|
||||
taskCreateData,
|
||||
taskUpdateData,
|
||||
tagCreateData,
|
||||
tagUpdateData,
|
||||
taskTagData,
|
||||
} from '@/lib/syncData';
|
||||
|
||||
// Idempotency key store (TTL 24h)
|
||||
const idempotencyStore = new Map<string, { result: unknown; expiresAt: number }>();
|
||||
|
|
@ -191,27 +200,28 @@ export async function POST(request: Request) {
|
|||
}
|
||||
|
||||
async function processOperation(op: SyncOperation, userId: string) {
|
||||
const { entityType, entityId, action, data } = op;
|
||||
const { entityType, entityId, action } = op;
|
||||
const data = op.data ?? {};
|
||||
const now = new Date();
|
||||
|
||||
switch (entityType) {
|
||||
case 'list': {
|
||||
if (action === 'create') {
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
const incomingIsInbox = d.isInbox as boolean | undefined;
|
||||
const d = listCreateData.parse(data);
|
||||
await assertIdNotTaken(slLists, entityId, userId);
|
||||
|
||||
const listValues = {
|
||||
id: entityId,
|
||||
userId,
|
||||
name: d.name as string || 'Untitled',
|
||||
color: d.color as string | undefined,
|
||||
icon: d.icon as string | undefined,
|
||||
position: d.position as number | undefined,
|
||||
isInbox: incomingIsInbox,
|
||||
name: d.name || 'Untitled',
|
||||
color: d.color,
|
||||
icon: d.icon,
|
||||
position: d.position,
|
||||
isInbox: d.isInbox,
|
||||
};
|
||||
|
||||
// If the incoming list is an inbox, check for an existing inbox and merge
|
||||
if (incomingIsInbox) {
|
||||
if (d.isInbox) {
|
||||
await db.transaction(async (tx) => {
|
||||
const [existingInbox] = await tx
|
||||
.select()
|
||||
|
|
@ -235,9 +245,10 @@ async function processOperation(op: SyncOperation, userId: string) {
|
|||
await db.insert(slLists).values(listValues).onConflictDoNothing();
|
||||
}
|
||||
} else if (action === 'update') {
|
||||
const d = listUpdateData.parse(data);
|
||||
await verifyOwnership(slLists, entityId, userId);
|
||||
await db.update(slLists)
|
||||
.set({ ...(data as Record<string, unknown>), updatedAt: now })
|
||||
.set({ ...d, updatedAt: now })
|
||||
.where(and(eq(slLists.id, entityId), eq(slLists.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyOwnership(slLists, entityId, userId);
|
||||
|
|
@ -249,32 +260,30 @@ async function processOperation(op: SyncOperation, userId: string) {
|
|||
}
|
||||
case 'task': {
|
||||
if (action === 'create') {
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
const d = taskCreateData.parse(data);
|
||||
await verifyOwnership(slLists, d.listId, userId);
|
||||
// Not verifyOwnership: initialMerge pushes all tasks in one batch, a
|
||||
// subtask may arrive before its parent (parent_id has no FK).
|
||||
if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId);
|
||||
await db.insert(slTasks).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
title: d.title as string || 'Untitled',
|
||||
listId: d.listId as string,
|
||||
notes: d.notes as string | undefined,
|
||||
priority: d.priority as number | undefined,
|
||||
dueDate: d.dueDate ? new Date(d.dueDate as string) : undefined,
|
||||
parentId: d.parentId as string | undefined,
|
||||
recurrence: d.recurrence as string | undefined,
|
||||
position: d.position as number | undefined,
|
||||
title: d.title || 'Untitled',
|
||||
listId: d.listId,
|
||||
notes: d.notes,
|
||||
priority: d.priority,
|
||||
dueDate: d.dueDate,
|
||||
parentId: d.parentId,
|
||||
recurrence: d.recurrence,
|
||||
position: d.position,
|
||||
}).onConflictDoNothing();
|
||||
} else if (action === 'update') {
|
||||
const d = taskUpdateData.parse(data);
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
const raw = { ...(data as Record<string, unknown>), updatedAt: now } as Record<string, unknown>;
|
||||
// Remove id from payload to avoid overwriting primary key
|
||||
delete raw.id;
|
||||
if (raw.dueDate !== undefined) {
|
||||
raw.dueDate = raw.dueDate ? new Date(raw.dueDate as string) : null;
|
||||
}
|
||||
if (raw.completedAt !== undefined) {
|
||||
raw.completedAt = raw.completedAt ? new Date(raw.completedAt as string) : null;
|
||||
}
|
||||
if (d.listId) await verifyOwnership(slLists, d.listId, userId);
|
||||
if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId);
|
||||
await db.update(slTasks)
|
||||
.set(raw)
|
||||
.set({ ...d, updatedAt: now })
|
||||
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
|
|
@ -286,17 +295,20 @@ async function processOperation(op: SyncOperation, userId: string) {
|
|||
}
|
||||
case 'tag': {
|
||||
if (action === 'create') {
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
const d = tagCreateData.parse(data);
|
||||
await db.insert(slTags).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
name: d.name as string || 'Untitled',
|
||||
color: d.color as string | undefined,
|
||||
name: d.name || 'Untitled',
|
||||
color: d.color,
|
||||
}).onConflictDoNothing();
|
||||
} else if (action === 'update') {
|
||||
const d = tagUpdateData.parse(data);
|
||||
await verifyTagOwnership(entityId, userId);
|
||||
// Tags have no updatedAt: skip when nothing is left to write
|
||||
if (d.name === undefined && d.color === undefined) break;
|
||||
await db.update(slTags)
|
||||
.set(data as Record<string, unknown>)
|
||||
.set(d)
|
||||
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyTagOwnership(entityId, userId);
|
||||
|
|
@ -308,8 +320,9 @@ async function processOperation(op: SyncOperation, userId: string) {
|
|||
}
|
||||
case 'taskTag': {
|
||||
// entityId is used as taskId, tagId comes from data
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
const tagId = d.tagId as string;
|
||||
const { tagId } = taskTagData.parse(data);
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
await verifyTagOwnership(tagId, userId);
|
||||
if (action === 'create') {
|
||||
await db.insert(slTaskTags)
|
||||
.values({ taskId: entityId, tagId })
|
||||
|
|
@ -339,3 +352,15 @@ async function verifyTagOwnership(entityId: string, userId: string) {
|
|||
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
|
||||
if (!row) throw new Error('Tag not found or access denied');
|
||||
}
|
||||
|
||||
// Refuse an id that already exists under another account. Unlike
|
||||
// verifyOwnership, a missing row passes: the id may be created later in the
|
||||
// same batch (a subtask pushed before its parent), or by this very insert.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async function assertIdNotTaken(table: any, id: string, userId: string) {
|
||||
const [row] = await db
|
||||
.select({ userId: table.userId })
|
||||
.from(table)
|
||||
.where(eq(table.id, id));
|
||||
if (row && row.userId !== userId) throw new Error('Entity not found or access denied');
|
||||
}
|
||||
|
|
|
|||
188
web/src/lib/syncData.test.ts
Normal file
188
web/src/lib/syncData.test.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
listCreateData,
|
||||
listUpdateData,
|
||||
taskCreateData,
|
||||
taskUpdateData,
|
||||
tagCreateData,
|
||||
tagUpdateData,
|
||||
taskTagData,
|
||||
} from './syncData';
|
||||
|
||||
const ID = '3f1c2b7a-9d4e-4c1a-8b2f-5e6d7c8b9a01';
|
||||
const LIST_ID = '7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d';
|
||||
const PARENT_ID = 'b1c2d3e4-f5a6-4b7c-8d9e-0f1a2b3c4d5e';
|
||||
const TAG_ID = 'c2d3e4f5-a6b7-4c8d-9e0f-1a2b3c4d5e6f';
|
||||
const DATE = '2026-10-19T12:00:00.000Z';
|
||||
|
||||
// Keys a client must never be able to write through `data`.
|
||||
const FORBIDDEN = {
|
||||
id: '00000000-0000-4000-8000-000000000000',
|
||||
userId: 'someone-else',
|
||||
deletedAt: DATE,
|
||||
createdAt: DATE,
|
||||
updatedAt: DATE,
|
||||
};
|
||||
|
||||
function expectNoForbiddenKeys(parsed: object) {
|
||||
for (const key of Object.keys(FORBIDDEN)) {
|
||||
expect(parsed).not.toHaveProperty(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Payloads below are copied from what the mobile app sends today:
|
||||
// src/db/repository/{lists,tasks,tags}.ts and src/services/syncClient.ts (initialMerge).
|
||||
// JSON.parse(JSON.stringify(...)) drops undefined values like the real push does.
|
||||
const wire = <T>(v: T): T => JSON.parse(JSON.stringify(v));
|
||||
|
||||
describe('list data', () => {
|
||||
it('accepts the createList payload with null color and icon', () => {
|
||||
const d = listCreateData.parse(wire({
|
||||
id: LIST_ID, name: 'Courses', color: null, icon: null, position: 3, isInbox: false,
|
||||
}));
|
||||
expect(d).toEqual({ name: 'Courses', color: null, icon: null, position: 3, isInbox: false });
|
||||
});
|
||||
|
||||
it('accepts the initialMerge inbox payload', () => {
|
||||
const d = listCreateData.parse(wire({
|
||||
name: 'Inbox', color: '#4A90A4', icon: 'inbox', position: 0, isInbox: true,
|
||||
}));
|
||||
expect(d.isInbox).toBe(true);
|
||||
expect(d.name).toBe('Inbox');
|
||||
});
|
||||
|
||||
it('accepts the updateList payload and drops id', () => {
|
||||
const d = listUpdateData.parse(wire({ id: LIST_ID, name: 'Maison', color: '#C17767', icon: null }));
|
||||
expect(d).toEqual({ name: 'Maison', color: '#C17767', icon: null });
|
||||
});
|
||||
|
||||
it('strips forbidden keys and isInbox on update', () => {
|
||||
const d = listUpdateData.parse({ ...FORBIDDEN, name: 'x', isInbox: true });
|
||||
expectNoForbiddenKeys(d);
|
||||
expect(d).not.toHaveProperty('isInbox');
|
||||
});
|
||||
|
||||
it('strips forbidden keys on create', () => {
|
||||
expectNoForbiddenKeys(listCreateData.parse({ ...FORBIDDEN, name: 'x' }));
|
||||
});
|
||||
|
||||
it('truncates a long name instead of rejecting it', () => {
|
||||
expect(listUpdateData.parse({ name: 'a'.repeat(201) }).name).toHaveLength(200);
|
||||
});
|
||||
|
||||
it('turns a null name into undefined (NOT NULL column left untouched)', () => {
|
||||
expect(listUpdateData.parse({ name: null }).name).toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts an empty data object', () => {
|
||||
expect(listCreateData.parse({})).toEqual({});
|
||||
});
|
||||
|
||||
it('rejects a wrong type', () => {
|
||||
expect(() => listUpdateData.parse({ position: '3' })).toThrow();
|
||||
expect(() => listCreateData.parse({ isInbox: 'yes' })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('task data', () => {
|
||||
it('accepts the createTask payload with nulls', () => {
|
||||
const d = taskCreateData.parse(wire({
|
||||
id: ID, title: 'Lait', notes: null, completed: false, completedAt: null, priority: 0,
|
||||
dueDate: null, listId: LIST_ID, parentId: null, recurrence: null,
|
||||
}));
|
||||
expect(d).toEqual({
|
||||
title: 'Lait', notes: null, priority: 0, dueDate: null, listId: LIST_ID,
|
||||
parentId: null, recurrence: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the initialMerge task payload (undefined fields dropped on the wire)', () => {
|
||||
const d = taskCreateData.parse(wire({
|
||||
title: 'Sous-tâche', notes: 'n', completed: true, priority: 2,
|
||||
dueDate: DATE, listId: LIST_ID, parentId: PARENT_ID, position: 4, recurrence: 'weekly',
|
||||
}));
|
||||
expect(d).toEqual({
|
||||
title: 'Sous-tâche', notes: 'n', priority: 2, dueDate: new Date(DATE),
|
||||
listId: LIST_ID, parentId: PARENT_ID, position: 4, recurrence: 'weekly',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the updateTask payload', () => {
|
||||
const d = taskUpdateData.parse(wire({
|
||||
id: ID, title: 'Lait', notes: 'bio', completed: true, completedAt: DATE, priority: 3,
|
||||
dueDate: DATE, listId: LIST_ID, parentId: null, recurrence: null,
|
||||
}));
|
||||
expect(d).toEqual({
|
||||
title: 'Lait', notes: 'bio', completed: true, completedAt: new Date(DATE), priority: 3,
|
||||
dueDate: new Date(DATE), listId: LIST_ID, parentId: null, recurrence: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the local inbox id as a reference', () => {
|
||||
const d = taskCreateData.parse({ listId: '00000000-0000-0000-0000-000000000001' });
|
||||
expect(d.listId).toBe('00000000-0000-0000-0000-000000000001');
|
||||
});
|
||||
|
||||
it('strips forbidden keys', () => {
|
||||
expectNoForbiddenKeys(taskUpdateData.parse({ ...FORBIDDEN, title: 'x' }));
|
||||
expectNoForbiddenKeys(taskCreateData.parse({ ...FORBIDDEN, listId: LIST_ID }));
|
||||
});
|
||||
|
||||
it('keeps 10000-char notes and truncates beyond', () => {
|
||||
expect(taskUpdateData.parse({ notes: 'n'.repeat(10000) }).notes).toHaveLength(10000);
|
||||
expect(taskUpdateData.parse({ notes: 'n'.repeat(10001) }).notes).toHaveLength(10000);
|
||||
});
|
||||
|
||||
it('truncates a long title', () => {
|
||||
expect(taskCreateData.parse({ listId: LIST_ID, title: 't'.repeat(501) }).title).toHaveLength(500);
|
||||
});
|
||||
|
||||
it('turns a null listId into undefined on update', () => {
|
||||
expect(taskUpdateData.parse({ listId: null }).listId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('requires listId on create', () => {
|
||||
expect(() => taskCreateData.parse({ title: 'x' })).toThrow();
|
||||
expect(() => taskCreateData.parse({ title: 'x', listId: null })).toThrow();
|
||||
});
|
||||
|
||||
it('rejects invalid dates and wrong types', () => {
|
||||
expect(() => taskUpdateData.parse({ dueDate: 'tomorrow' })).toThrow();
|
||||
expect(() => taskUpdateData.parse({ dueDate: 1760875200000 })).toThrow();
|
||||
expect(() => taskUpdateData.parse({ completedAt: '2026-10-19T12:00:00+02:00' })).toThrow();
|
||||
expect(() => taskUpdateData.parse({ parentId: 'not-a-uuid' })).toThrow();
|
||||
expect(() => taskUpdateData.parse({ priority: 1.5 })).toThrow();
|
||||
expect(() => taskUpdateData.parse({ completed: 'true' })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('tag data', () => {
|
||||
it('accepts the createTag / updateTag payload and drops id', () => {
|
||||
const payload = wire({ id: TAG_ID, name: 'urgent', color: '#E57373' });
|
||||
expect(tagCreateData.parse(payload)).toEqual({ name: 'urgent', color: '#E57373' });
|
||||
expect(tagUpdateData.parse(payload)).toEqual({ name: 'urgent', color: '#E57373' });
|
||||
});
|
||||
|
||||
it('strips forbidden keys', () => {
|
||||
expectNoForbiddenKeys(tagUpdateData.parse({ ...FORBIDDEN, name: 'x' }));
|
||||
});
|
||||
|
||||
it('turns a null color into undefined (NOT NULL column)', () => {
|
||||
expect(tagUpdateData.parse({ color: null }).color).toBeUndefined();
|
||||
});
|
||||
|
||||
it('truncates a long name', () => {
|
||||
expect(tagCreateData.parse({ name: 'a'.repeat(101) }).name).toHaveLength(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe('taskTag data', () => {
|
||||
it('accepts the setTagsForTask payload', () => {
|
||||
expect(taskTagData.parse({ tagId: TAG_ID })).toEqual({ tagId: TAG_ID });
|
||||
});
|
||||
|
||||
it('strips forbidden keys and requires tagId', () => {
|
||||
expectNoForbiddenKeys(taskTagData.parse({ ...FORBIDDEN, tagId: TAG_ID }));
|
||||
expect(() => taskTagData.parse({})).toThrow();
|
||||
});
|
||||
});
|
||||
76
web/src/lib/syncData.ts
Normal file
76
web/src/lib/syncData.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
// Schemas for the `data` field of a sync operation (POST /api/sync).
|
||||
//
|
||||
// Each schema lists the columns a client may write for one entity and action.
|
||||
// Objects are NOT strict: unknown keys (userId, id, deletedAt, createdAt...)
|
||||
// are stripped instead of rejected. The mobile app marks its whole outbox as
|
||||
// synced once the push returns 200, so a rejected operation is lost silently;
|
||||
// stripping keeps older app versions working while never writing those keys.
|
||||
//
|
||||
// Strings are truncated rather than rejected for the same reason. Limits
|
||||
// follow the mobile app (notes go up to 10000 there, unlike the REST schema).
|
||||
|
||||
const text = (max: number) => z.string().transform((s) => s.slice(0, max));
|
||||
|
||||
// NOT NULL column: null means "leave untouched" (or DB default on insert).
|
||||
const notNull = <T extends z.ZodType>(schema: T) =>
|
||||
schema.nullish().transform((v) => v ?? undefined);
|
||||
|
||||
// Nullable column: null clears it, undefined leaves it untouched.
|
||||
const nullable = <T extends z.ZodType>(schema: T) => schema.nullable().optional();
|
||||
|
||||
const isoDate = z.iso.datetime().transform((s) => new Date(s));
|
||||
|
||||
// Format check only; ownership is verified against the database by the route.
|
||||
// z.guid() rather than z.uuid(): the latter rejects non-RFC ids.
|
||||
const ref = z.guid();
|
||||
|
||||
export const listCreateData = z.object({
|
||||
name: notNull(text(200)),
|
||||
color: nullable(text(20)),
|
||||
icon: nullable(text(50)),
|
||||
position: notNull(z.number().int()),
|
||||
isInbox: notNull(z.boolean()),
|
||||
});
|
||||
|
||||
export const listUpdateData = z.object({
|
||||
name: notNull(text(200)),
|
||||
color: nullable(text(20)),
|
||||
icon: nullable(text(50)),
|
||||
position: notNull(z.number().int()),
|
||||
});
|
||||
|
||||
const taskFields = {
|
||||
title: notNull(text(500)),
|
||||
notes: nullable(text(10000)),
|
||||
priority: notNull(z.number().int()),
|
||||
dueDate: nullable(isoDate),
|
||||
parentId: nullable(ref),
|
||||
recurrence: nullable(text(100)),
|
||||
position: notNull(z.number().int()),
|
||||
};
|
||||
|
||||
// completed / completedAt are sent by the app on create but not stored (#142, out of scope).
|
||||
export const taskCreateData = z.object({
|
||||
...taskFields,
|
||||
listId: ref,
|
||||
});
|
||||
|
||||
export const taskUpdateData = z.object({
|
||||
...taskFields,
|
||||
listId: notNull(ref),
|
||||
completed: notNull(z.boolean()),
|
||||
completedAt: nullable(isoDate),
|
||||
});
|
||||
|
||||
export const tagCreateData = z.object({
|
||||
name: notNull(text(100)),
|
||||
color: notNull(text(20)),
|
||||
});
|
||||
|
||||
export const tagUpdateData = tagCreateData;
|
||||
|
||||
export const taskTagData = z.object({
|
||||
tagId: ref,
|
||||
});
|
||||
19
web/vitest.config.mts
Normal file
19
web/vitest.config.mts
Normal file
|
|
@ -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'] } },
|
||||
},
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue