From e8abcfc21798c3ba51e5e83ce2c8c8fc4389d24f Mon Sep 17 00:00:00 2001 From: le king fu Date: Wed, 21 Oct 2026 19:36:35 -0400 Subject: [PATCH] fix(sync): require an existing parent and order each pushed batch Decision from Max (2026-10-21, /pr-brief of PR #144): a subtask whose parent does not exist on the server is refused, instead of accepted when no other account holds the id. initialMerge pushes every local task in one batch, in SQLite order, so a subtask could come before its parent. orderSyncOperations moves a subtask create right after the create of its parent when both are in the batch (nested subtasks and cycles handled); every other operation keeps its relative order. A parent sent in a later batch is not found and the subtask is skipped, which Max accepted. Refs #142 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 2 +- web/src/app/api/sync/route.test.ts | 11 +++++++ web/src/app/api/sync/route.ts | 14 ++++---- web/src/lib/syncData.test.ts | 46 ++++++++++++++++++++++++++ web/src/lib/syncData.ts | 52 ++++++++++++++++++++++++++++++ 5 files changed, 117 insertions(+), 8 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 578dad8..05dcc3e 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -91,7 +91,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - 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()`. 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 +- 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. `listId` et `parentId` doivent exister et appartenir à l'appelant (décision de Max du 2026-10-21, `/pr-brief` de la PR #144) : `initialMerge` pousse tout en un lot, donc le serveur range chaque lot pour qu'un parent créé dans le même lot passe avant ses sous-tâches (`orderSyncOperations`). L'id d'une liste créée refuse seulement un id pris par un autre compte. — `web/src/app/api/sync/route.ts`, `web/src/lib/syncData.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` diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 7878d36..b9d24de 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -157,6 +157,17 @@ describe('POST /api/sync: task references', () => { expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); }); + it('refuses a subtask whose parent does not exist', async () => { + const id = u(); + expect(await push('userB', [['task', 'create', id, { title: 'orphan', listId: B.list, parentId: u() }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); + }); + + it('refuses moving a task under a parent that does not exist', async () => { + expect(await push('userB', [['task', 'update', B.task, { parentId: u() }]])).toEqual(['skipped']); + expect(await row('select parent_id from sl_tasks where id=$1', [B.task])).toEqual({ parent_id: null }); + }); + 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 }], diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index cb14996..69062f5 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -6,6 +6,7 @@ import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { syncPushSchema, type SyncOperation } from '@/lib/validators'; import { + orderSyncOperations, listCreateData, listUpdateData, taskCreateData, @@ -170,7 +171,7 @@ export async function POST(request: Request) { const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = []; - for (const op of body.data.operations) { + for (const op of orderSyncOperations(body.data.operations)) { const storeKey = `${auth.userId}:${op.idempotencyKey}`; // Check idempotency @@ -262,9 +263,9 @@ async function processOperation(op: SyncOperation, userId: string) { if (action === 'create') { 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); + // The parent must already exist: POST orders each batch so that a + // parent created in the same batch comes first (orderSyncOperations). + if (d.parentId) await verifyOwnership(slTasks, d.parentId, userId); await db.insert(slTasks).values({ id: entityId, userId, @@ -281,7 +282,7 @@ async function processOperation(op: SyncOperation, userId: string) { const d = taskUpdateData.parse(data); await verifyOwnership(slTasks, entityId, userId); if (d.listId) await verifyOwnership(slLists, d.listId, userId); - if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId); + if (d.parentId) await verifyOwnership(slTasks, d.parentId, userId); await db.update(slTasks) .set({ ...d, updatedAt: now }) .where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId))); @@ -354,8 +355,7 @@ async function verifyTagOwnership(entityId: string, userId: string) { } // 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. +// verifyOwnership, a missing row passes: the insert that follows creates it. // eslint-disable-next-line @typescript-eslint/no-explicit-any async function assertIdNotTaken(table: any, id: string, userId: string) { const [row] = await db diff --git a/web/src/lib/syncData.test.ts b/web/src/lib/syncData.test.ts index 3d54154..a23f0c1 100644 --- a/web/src/lib/syncData.test.ts +++ b/web/src/lib/syncData.test.ts @@ -7,6 +7,7 @@ import { tagCreateData, tagUpdateData, taskTagData, + orderSyncOperations, } from './syncData'; const ID = '3f1c2b7a-9d4e-4c1a-8b2f-5e6d7c8b9a01'; @@ -186,3 +187,48 @@ describe('taskTag data', () => { expect(() => taskTagData.parse({})).toThrow(); }); }); + +describe('orderSyncOperations', () => { + const op = (entityType: string, action: string, entityId: string, data?: Record) => + ({ entityType, action, entityId, data }); + const ids = (ops: { entityId: string; action: string }[]) => ops.map((o) => `${o.action}:${o.entityId}`); + + it('moves a subtask create right after the create of its parent', () => { + const ops = [ + op('list', 'create', 'L'), + op('task', 'create', 'sub', { parentId: 'P' }), + op('task', 'create', 'other'), + op('task', 'create', 'P'), + op('taskTag', 'create', 'sub', { tagId: 'T' }), + ]; + expect(ids(orderSyncOperations(ops))).toEqual(['create:L', 'create:other', 'create:P', 'create:sub', 'create:sub']); + }); + + it('handles nested subtasks in reverse order', () => { + const ops = [ + op('task', 'create', 'c', { parentId: 'b' }), + op('task', 'create', 'b', { parentId: 'a' }), + op('task', 'create', 'a'), + ]; + expect(ids(orderSyncOperations(ops))).toEqual(['create:a', 'create:b', 'create:c']); + }); + + it('keeps the order when the parent is not created in the batch, or already came first', () => { + const ops = [ + op('task', 'create', 'P'), + op('task', 'create', 'sub', { parentId: 'P' }), + op('task', 'create', 'orphan', { parentId: 'elsewhere' }), + op('task', 'update', 'x', { parentId: 'P' }), + ]; + expect(orderSyncOperations(ops)).toEqual(ops); + }); + + it('keeps every operation of a parent cycle', () => { + const ops = [ + op('task', 'create', 'a', { parentId: 'b' }), + op('task', 'create', 'b', { parentId: 'a' }), + op('tag', 'create', 't'), + ]; + expect(ids(orderSyncOperations(ops)).sort()).toEqual(['create:a', 'create:b', 'create:t']); + }); +}); diff --git a/web/src/lib/syncData.ts b/web/src/lib/syncData.ts index e1e8907..045d990 100644 --- a/web/src/lib/syncData.ts +++ b/web/src/lib/syncData.ts @@ -74,3 +74,55 @@ export const tagUpdateData = tagCreateData; export const taskTagData = z.object({ tagId: ref, }); + +type OrderableOp = { + entityType: string; + action: string; + entityId: string; + data?: Record; +}; + +/** + * Order a pushed batch so that a subtask create comes right after the create + * of its parent when both are in the batch. initialMerge sends every local + * task in one go, in SQLite order, and the route requires an existing parent + * owned by the caller (#142). Other operations keep their relative order. + * A subtask whose parent is not created in the batch keeps its place. + */ +export function orderSyncOperations(ops: T[]): T[] { + const parentOf = (op: T): string | undefined => + op.entityType === 'task' && op.action === 'create' && typeof op.data?.parentId === 'string' + ? op.data.parentId + : undefined; + + const createdTasks = new Set( + ops.filter((op) => op.entityType === 'task' && op.action === 'create').map((op) => op.entityId), + ); + const done = new Set(); + const waiting = new Map(); + const ordered: T[] = []; + + const emit = (op: T) => { + ordered.push(op); + if (op.entityType !== 'task' || op.action !== 'create') return; + done.add(op.entityId); + const children = waiting.get(op.entityId) ?? []; + waiting.delete(op.entityId); + children.forEach(emit); + }; + + for (const op of ops) { + const parent = parentOf(op); + if (parent && parent !== op.entityId && createdTasks.has(parent) && !done.has(parent)) { + waiting.set(parent, [...(waiting.get(parent) ?? []), op]); + } else { + emit(op); + } + } + // Cycles (a task listed as the parent of its own parent): keep them, in order. + const emitted = new Set(ordered); + for (const op of ops) { + if (!emitted.has(op)) ordered.push(op); + } + return ordered; +}