revert: drop the strict parent check and batch ordering (e8abcfc)

Decision from Max (2026-10-21, after review comment 26317): forget the
parent existence check altogether. The review found that
orderSyncOperations was quadratic and synchronous, so one authenticated
request of a few MB could freeze the companion for every account, and
that the strict check on updates would silently refuse every edit of a
subtask already stored without its parent.

The tree is back to fdd4c95 (approved in comment 26259): a parentId held
by another account is still refused (assertIdNotTaken), a missing
parent is accepted as before.

This reverts commit e8abcfc217.

Refs #142

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-21 19:47:17 -04:00
commit c923485fd7
5 changed files with 8 additions and 117 deletions

View file

@ -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. `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
- 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`

View file

@ -157,17 +157,6 @@ 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 }],

View file

@ -6,7 +6,6 @@ import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
import {
orderSyncOperations,
listCreateData,
listUpdateData,
taskCreateData,
@ -171,7 +170,7 @@ export async function POST(request: Request) {
const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = [];
for (const op of orderSyncOperations(body.data.operations)) {
for (const op of body.data.operations) {
const storeKey = `${auth.userId}:${op.idempotencyKey}`;
// Check idempotency
@ -263,9 +262,9 @@ async function processOperation(op: SyncOperation, userId: string) {
if (action === 'create') {
const d = taskCreateData.parse(data);
await verifyOwnership(slLists, d.listId, 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);
// 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,
@ -282,7 +281,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 verifyOwnership(slTasks, d.parentId, userId);
if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId);
await db.update(slTasks)
.set({ ...d, updatedAt: now })
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
@ -355,7 +354,8 @@ async function verifyTagOwnership(entityId: string, userId: string) {
}
// Refuse an id that already exists under another account. Unlike
// verifyOwnership, a missing row passes: the insert that follows creates it.
// 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

View file

@ -7,7 +7,6 @@ import {
tagCreateData,
tagUpdateData,
taskTagData,
orderSyncOperations,
} from './syncData';
const ID = '3f1c2b7a-9d4e-4c1a-8b2f-5e6d7c8b9a01';
@ -187,48 +186,3 @@ describe('taskTag data', () => {
expect(() => taskTagData.parse({})).toThrow();
});
});
describe('orderSyncOperations', () => {
const op = (entityType: string, action: string, entityId: string, data?: Record<string, unknown>) =>
({ 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']);
});
});

View file

@ -74,55 +74,3 @@ export const tagUpdateData = tagCreateData;
export const taskTagData = z.object({
tagId: ref,
});
type OrderableOp = {
entityType: string;
action: string;
entityId: string;
data?: Record<string, unknown>;
};
/**
* 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<T extends OrderableOp>(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<string>();
const waiting = new Map<string, T[]>();
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;
}