fix(sync): bound what one POST /api/sync can cost the companion

- validators: at most 200 operations per sync batch (SYNC_MAX_OPERATIONS),
  length checked before the elements (z.array(z.unknown()).max(n).pipe),
  idempotency keys must be UUIDs; same pre-check on reorder ids (1000) and
  task tag ids (100).
- parseBody: a 400 carries only the first zod issue, at most 200 characters.
- idempotency: per-account store in insertion order, 5000 keys per account
  (oldest evicted), cleanup drops expired keys and empty accounts; the sync
  route uses it instead of its unbounded Map.
- middleware.test.ts: every matcher covers /api/sync, the condition for
  Next's 10 MB body cut.
- REVIEW.md: idempotency.ts joins the high-level API row, new zone rules;
  scripts/review-levels.py follows.

Refs #147

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-24 14:13:40 -04:00
commit d2289806a4
11 changed files with 408 additions and 44 deletions

View file

@ -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,syncData,rateLimit,ws}.ts`, `web/server.ts` | toujours | API et isolation des comptes |
| `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.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 |
@ -92,6 +92,11 @@ 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
- Un lot de sync compte au plus 200 opérations (`SYNC_MAX_OPERATIONS`) et l'app en envoie 50 (`batchSize`) : une montée de `batchSize` se juge contre cette borne et contre la limite `sync` (10 requêtes par minute, GET et POST confondus), et le companion se déploie avant l'app. — `web/src/lib/validators.ts`, `src/services/syncClient.ts`, #147
- Tout tableau d'un schéma de requête a sa longueur contrôlée avant ses éléments (`z.array(z.unknown()).max(n).pipe(…)`) : zod valide chaque élément avant la longueur, et un tableau hostile produit un issue par élément. — `web/src/lib/validators.ts`, #147
- `parseBody` ne renvoie que le premier issue d'une erreur zod, et au plus 200 caractères. — `web/src/lib/api.ts`, #147
- Les clés d'idempotence sont des UUID, 5 000 au plus par compte, la plus ancienne évincée au-delà (`idempotency.ts`) : une clé évincée rejouée réapplique son opération. — `web/src/lib/idempotency.ts`, `web/src/app/api/sync/route.ts`, #147
- Aucune borne de taille du corps n'est posée par le companion : Next ne coupe le corps à 10 Mo (`experimental.proxyClientMaxBodySize`) que si `middleware.ts` couvre la route, ce que vérifie `middleware.test.ts`. Un `config.matcher` qui exclut une route d'API lui retire cette coupure. — `web/src/middleware.ts`, `web/src/middleware.test.ts`, #147
- 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

@ -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,syncData,rateLimit,ws}.ts", "web/server.ts",
"web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.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/**",

View file

@ -19,15 +19,11 @@ vi.mock('@/db/client', async () => {
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/api', () => ({
// The real parseBody runs: its bounded 400 is under test (#147).
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
vi.mock('@/lib/api', async (importOriginal) => ({
...(await importOriginal<typeof import('@/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 }));
@ -436,3 +432,59 @@ describe('POST /api/sync: completion on task create (#146)', () => {
expect(await createTask({})).toEqual({ completed: false, completed_at: null });
});
});
describe('POST /api/sync: bounded batches (#147)', () => {
async function post(userId: string, body: unknown): Promise<Response> {
h.userId = userId;
return POST(new Request('http://localhost/api/sync', { method: 'POST', body: JSON.stringify(body) }));
}
function listOps(n: number) {
return Array.from({ length: n }, (_, i) => ({
idempotencyKey: u(), entityType: 'list', action: 'create', entityId: u(),
data: { name: `L${i}`, position: i, isInbox: false },
}));
}
it('(a) refuses 201 valid operations and writes nothing for the account', async () => {
const userId = `user-${u()}`;
const res = await post(userId, { operations: listOps(201) });
expect(res.status).toBe(400);
expect(await row('select count(*)::int c from sl_lists where user_id=$1', [userId])).toEqual({ c: 0 });
});
it('(b) answers 100000 empty objects with a 400 under 1 KB', async () => {
const res = await post(`user-${u()}`, { operations: Array.from({ length: 100_000 }, () => ({})) });
expect(res.status).toBe(400);
expect((await res.text()).length).toBeLessThan(1024);
});
it('(c) applies 200 operations', async () => {
const userId = `user-${u()}`;
const list = u();
const ops: Op[] = [
['list', 'create', list, { name: 'L', position: 0, isInbox: false }],
...Array.from({ length: 199 }, (_, i): Op => ['task', 'create', u(), { title: `T${i}`, listId: list, position: i }]),
];
expect(await push(userId, ops)).toEqual(Array(200).fill('applied'));
expect(await row('select count(*)::int c from sl_tasks where user_id=$1', [userId])).toEqual({ c: 199 });
});
it('(d) refuses an idempotencyKey that is not a UUID', async () => {
const [op] = listOps(1);
const res = await post(`user-${u()}`, { operations: [{ ...op, idempotencyKey: 'outbox-1' }] });
expect(res.status).toBe(400);
});
it('skips a replayed key without an error, for its account only', async () => {
const userId = `user-${u()}`;
const [op] = listOps(1);
const results = async (uid: string) =>
((await (await post(uid, { operations: [op] })).json()) as { results: Result[] }).results
.map(({ status, error }) => ({ status, error }));
expect(await results(userId)).toEqual([{ status: 'applied', error: undefined }]);
expect(await results(userId)).toEqual([{ status: 'skipped', error: undefined }]);
// Same key from another account: not skipped by the store (the id is taken).
expect(await results(`user-${u()}`)).toEqual([{ status: 'skipped', error: 'Entity not found or access denied' }]);
});
});

View file

@ -5,6 +5,7 @@ import { eq, and, gte, isNull, ne, inArray, desc } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
import { createIdempotencyStore } from '@/lib/idempotency';
import {
listCreateData,
listUpdateData,
@ -15,20 +16,8 @@ import {
taskTagData,
} from '@/lib/syncData';
// Idempotency key store (TTL 24h)
const idempotencyStore = new Map<string, { result: unknown; expiresAt: number }>();
// Cleanup expired keys periodically
function cleanupIdempotencyKeys() {
const now = Date.now();
for (const [key, entry] of idempotencyStore) {
if (entry.expiresAt < now) {
idempotencyStore.delete(key);
}
}
}
const TTL_24H = 24 * 60 * 60 * 1000;
// Idempotency keys, 24 h and at most 5000 per account (#147).
const idempotency = createIdempotencyStore({ ttlMs: 24 * 60 * 60 * 1000, maxPerAccount: 5000 });
export async function GET(request: NextRequest) {
const auth = await requireAuth();
@ -165,27 +154,21 @@ export async function POST(request: Request) {
const body = await parseBody(request, (d) => syncPushSchema.parse(d));
if (body.error) return body.error;
cleanupIdempotencyKeys();
idempotency.cleanup(Date.now());
const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = [];
const ctx: RequestContext = { inboxCreated: false };
for (const op of body.data.operations) {
const storeKey = `${auth.userId}:${op.idempotencyKey}`;
// Check idempotency
const existing = idempotencyStore.get(storeKey);
if (existing && existing.expiresAt > Date.now()) {
if (idempotency.seen(auth.userId, op.idempotencyKey, Date.now())) {
results.push({ idempotencyKey: op.idempotencyKey, status: 'skipped' });
continue;
}
try {
await processOperation(op, auth.userId, ctx);
idempotencyStore.set(storeKey, {
result: true,
expiresAt: Date.now() + TTL_24H,
});
idempotency.remember(auth.userId, op.idempotencyKey, Date.now());
results.push({ idempotencyKey: op.idempotencyKey, status: 'applied' });
} catch (e) {
results.push({

51
web/src/lib/api.test.ts Normal file
View file

@ -0,0 +1,51 @@
import { describe, it, expect, vi } from 'vitest';
import { z } from 'zod';
// parseBody returns a bounded 400 (#147). The Logto session helper is not
// under test.
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
const { parseBody } = await import('./api');
function request(body: string) {
return new Request('http://localhost/api/x', { method: 'POST', body });
}
async function errorOf(body: string, parse: (d: unknown) => unknown) {
const r = await parseBody(request(body), parse);
expect(r.error).toBeDefined();
expect(r.error!.status).toBe(400);
const text = await r.error!.text();
return { text, error: (JSON.parse(text) as { error: string }).error };
}
describe('parseBody', () => {
it('returns only the first issue of a zod error', async () => {
const schema = z.object({ a: z.string(), b: z.number(), c: z.boolean() });
expect(schema.safeParse({}).error!.issues.length).toBe(3);
const { error } = await errorOf('{}', (d) => schema.parse(d));
expect(error).toMatch(/^a: /);
expect(error).not.toMatch(/\bb\b|\bc\b/);
});
it('bounds a zod message that lists every unknown key', async () => {
const schema = z.object({}).strict();
const keys = Object.fromEntries(Array.from({ length: 10_000 }, (_, i) => [`key${i}`, 1]));
const { text } = await errorOf(JSON.stringify(keys), (d) => schema.parse(d));
expect(text.length).toBeLessThan(1024);
});
it('truncates another error message to 200 characters', async () => {
const { error } = await errorOf('{}', () => { throw new Error('x'.repeat(5000)); });
expect(error).toBe('x'.repeat(200));
});
it('returns 400 on invalid JSON', async () => {
const { error } = await errorOf('{not json', (d) => d);
expect(error.length).toBeGreaterThan(0);
});
it('returns the parsed data', async () => {
expect(await parseBody(request('{"a":1}'), (d) => d)).toEqual({ data: { a: 1 } });
});
});

View file

@ -1,6 +1,10 @@
import { getAuthenticatedUser } from '@/lib/auth';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { ZodError } from 'zod';
// Longest error message a 400 from parseBody carries (#147).
const MAX_ERROR_LENGTH = 200;
/**
* Verify a JWT access token from Logto (for mobile clients).
@ -52,6 +56,24 @@ export async function requireAuth(): Promise<
return { userId: user.userId };
}
/**
* Error text of a rejected body, bounded whatever the client sent: only the
* first zod issue (a hostile batch can produce one issue per element), and at
* most MAX_ERROR_LENGTH characters (an unrecognized_keys message lists every
* extra key the client sent).
*/
function errorMessage(e: unknown): string {
let message: string;
if (e instanceof ZodError) {
const issue = e.issues[0];
const where = issue?.path.map(String).join('.') ?? '';
message = issue ? (where ? `${where}: ${issue.message}` : issue.message) : 'Invalid request body';
} else {
message = e instanceof Error ? e.message : 'Invalid request body';
}
return message.slice(0, MAX_ERROR_LENGTH);
}
/**
* Wrap a handler with JSON parse error handling.
*/
@ -64,7 +86,6 @@ export async function parseBody<T>(request: Request, parse: (data: unknown) => T
const data = parse(raw);
return { data };
} catch (e) {
const message = e instanceof Error ? e.message : 'Invalid request body';
return { error: NextResponse.json({ error: message }, { status: 400 }) };
return { error: NextResponse.json({ error: errorMessage(e) }, { status: 400 }) };
}
}

View file

@ -0,0 +1,67 @@
import { describe, it, expect } from 'vitest';
import { createIdempotencyStore } from './idempotency';
const TTL = 24 * 60 * 60 * 1000;
const T0 = 1_700_000_000_000;
function store() {
return createIdempotencyStore({ ttlMs: TTL, maxPerAccount: 5000 });
}
describe('createIdempotencyStore', () => {
it('sees a key after remember, not before', () => {
const s = store();
expect(s.seen('a', 'k', T0)).toBe(false);
s.remember('a', 'k', T0);
expect(s.seen('a', 'k', T0 + 1)).toBe(true);
});
it('forgets a key after the TTL', () => {
const s = store();
s.remember('a', 'k', T0);
expect(s.seen('a', 'k', T0 + TTL - 1)).toBe(true);
expect(s.seen('a', 'k', T0 + TTL)).toBe(false);
});
it('keeps accounts isolated', () => {
const s = store();
s.remember('a', 'k', T0);
expect(s.seen('b', 'k', T0)).toBe(false);
s.remember('b', 'other', T0);
expect(s.seen('a', 'other', T0)).toBe(false);
});
it('evicts the oldest key of an account at the 5001st', () => {
const s = store();
for (let i = 0; i < 5000; i++) s.remember('a', `k${i}`, T0 + i);
s.remember('b', 'k0', T0);
expect(s.seen('a', 'k0', T0 + 5000)).toBe(true);
s.remember('a', 'k5000', T0 + 5000);
expect(s.seen('a', 'k0', T0 + 5001)).toBe(false);
expect(s.seen('a', 'k1', T0 + 5001)).toBe(true);
expect(s.seen('a', 'k5000', T0 + 5001)).toBe(true);
// Another account's keys are not evicted by this one.
expect(s.seen('b', 'k0', T0 + 5001)).toBe(true);
});
it('cleanup removes expired keys and empty accounts', () => {
const s = store();
s.remember('a', 'old', T0);
s.remember('a', 'new', T0 + 10);
s.remember('b', 'old', T0);
expect(s.stats()).toEqual({ accounts: 2, keys: 3 });
s.cleanup(T0 + TTL);
expect(s.stats()).toEqual({ accounts: 1, keys: 1 });
expect(s.seen('a', 'new', T0 + TTL)).toBe(true);
// Removed, not just expired: even an earlier clock no longer sees it.
expect(s.seen('a', 'old', T0 + 1)).toBe(false);
s.cleanup(T0 + TTL + 10);
expect(s.stats()).toEqual({ accounts: 0, keys: 0 });
});
it('holds at most 5000 keys per account', () => {
const s = store();
for (let i = 0; i < 6000; i++) s.remember('a', `k${i}`, T0);
expect(s.stats()).toEqual({ accounts: 1, keys: 5000 });
});
});

View file

@ -0,0 +1,63 @@
// In-memory idempotency store for POST /api/sync (#147), bounded per account.
//
// One Map per account, in insertion order: past `maxPerAccount` keys the oldest
// is evicted, so one account cannot grow the store without limit. An evicted
// key replayed later re-applies its operation; with 5000 keys per account and
// batches of at most 200 operations, that takes more than 25 full batches
// between the first send and the replay. Like the rate limiter, the store
// starts empty on every restart.
export type IdempotencyStore = {
seen(userId: string, key: string, now: number): boolean;
remember(userId: string, key: string, now: number): void;
cleanup(now: number): void;
// Accounts and keys held, for tests.
stats(): { accounts: number; keys: number };
};
export function createIdempotencyStore(
{ ttlMs, maxPerAccount }: { ttlMs: number; maxPerAccount: number },
): IdempotencyStore {
// userId -> (key -> expiresAt), each inner Map in insertion order.
const accounts = new Map<string, Map<string, number>>();
return {
seen(userId, key, now) {
const expiresAt = accounts.get(userId)?.get(key);
return expiresAt !== undefined && expiresAt > now;
},
remember(userId, key, now) {
let keys = accounts.get(userId);
if (!keys) {
keys = new Map();
accounts.set(userId, keys);
}
// Re-insert so a refreshed key moves to the newest end.
keys.delete(key);
keys.set(key, now + ttlMs);
while (keys.size > maxPerAccount) {
const oldest = keys.keys().next().value as string;
keys.delete(oldest);
}
},
cleanup(now) {
for (const [userId, keys] of accounts) {
// Keys are in insertion order with the same TTL, so expiry dates only
// grow: stop at the first live key.
for (const [key, expiresAt] of keys) {
if (expiresAt > now) break;
keys.delete(key);
}
if (keys.size === 0) accounts.delete(userId);
}
},
stats() {
let keys = 0;
for (const k of accounts.values()) keys += k.size;
return { accounts: accounts.size, keys };
},
};
}

View file

@ -0,0 +1,83 @@
import { randomUUID as u } from 'node:crypto';
import { describe, it, expect } from 'vitest';
import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS } from './validators';
// Length bounds checked before the elements (#147).
function op() {
return { idempotencyKey: u(), entityType: 'task', entityId: u(), action: 'delete' };
}
function ops(n: number) {
return Array.from({ length: n }, op);
}
describe('syncPushSchema', () => {
it('bounds a batch at 200 operations', () => {
expect(SYNC_MAX_OPERATIONS).toBe(200);
});
it('reports a single issue for 100000 empty objects', () => {
const r = syncPushSchema.safeParse({ operations: Array.from({ length: 100_000 }, () => ({})) });
expect(r.success).toBe(false);
expect(r.error!.issues).toHaveLength(1);
expect(r.error!.issues[0].code).toBe('too_big');
});
it('refuses 201 valid operations', () => {
const r = syncPushSchema.safeParse({ operations: ops(201) });
expect(r.success).toBe(false);
expect(r.error!.issues).toHaveLength(1);
expect(r.error!.issues[0].code).toBe('too_big');
});
it('accepts 200 valid operations', () => {
const r = syncPushSchema.safeParse({ operations: ops(200) });
expect(r.success).toBe(true);
expect(r.data!.operations).toHaveLength(200);
});
it('still validates each operation under the bound', () => {
expect(syncPushSchema.safeParse({ operations: [{}] }).success).toBe(false);
});
it('refuses an idempotencyKey that is not a UUID', () => {
const r = syncPushSchema.safeParse({ operations: [{ ...op(), idempotencyKey: 'outbox-1' }] });
expect(r.success).toBe(false);
expect(r.error!.issues[0].path).toEqual(['operations', 0, 'idempotencyKey']);
});
});
describe('reorderSchema', () => {
it('refuses 1001 ids', () => {
const r = reorderSchema.safeParse({ ids: Array.from({ length: 1001 }, () => u()) });
expect(r.success).toBe(false);
expect(r.error!.issues[0].code).toBe('too_big');
});
it('accepts 1000 ids', () => {
expect(reorderSchema.safeParse({ ids: Array.from({ length: 1000 }, () => u()) }).success).toBe(true);
});
it('reports a single issue for 100000 invalid values', () => {
const r = reorderSchema.safeParse({ ids: Array.from({ length: 100_000 }, () => 'x') });
expect(r.success).toBe(false);
expect(r.error!.issues).toHaveLength(1);
});
it('still refuses an empty list', () => {
expect(reorderSchema.safeParse({ ids: [] }).success).toBe(false);
});
});
describe('assignTagsSchema', () => {
it('refuses 101 ids', () => {
const r = assignTagsSchema.safeParse({ tagIds: Array.from({ length: 101 }, () => u()) });
expect(r.success).toBe(false);
expect(r.error!.issues[0].code).toBe('too_big');
});
it('accepts 100 ids', () => {
expect(assignTagsSchema.safeParse({ tagIds: Array.from({ length: 100 }, () => u()) }).success).toBe(true);
});
});

View file

@ -15,8 +15,11 @@ export const updateListSchema = z.object({
isInbox: z.boolean().optional(),
}).strict();
// Array lengths are checked before the elements (z.array(z.unknown()).max(n)
// then .pipe): zod validates every element of an array before its length, so a
// long array of invalid items would otherwise produce one issue per item.
export const reorderSchema = z.object({
ids: z.array(z.string().uuid()).min(1),
ids: z.array(z.unknown()).min(1).max(1000).pipe(z.array(z.string().uuid())),
}).strict();
// Tasks
@ -54,18 +57,30 @@ export const updateTagSchema = z.object({
}).strict();
export const assignTagsSchema = z.object({
tagIds: z.array(z.string().uuid()).min(1),
tagIds: z.array(z.unknown()).min(1).max(100).pipe(z.array(z.string().uuid())),
}).strict();
// Sync
// Maximum operations in one POST /api/sync. The app sends batches of 50
// (`batchSize` in src/services/syncClient.ts): raising `batchSize` above this
// bound requires deploying the companion first. The request body itself is
// only cut at 10 MB by Next when web/src/middleware.ts covers the route
// (see middleware.test.ts).
export const SYNC_MAX_OPERATIONS = 200;
const syncOperationSchema = z.object({
// The app always uses randomUUID (outbox entry id, or initialMerge).
idempotencyKey: z.guid(),
entityType: z.enum(['list', 'task', 'tag', 'taskTag']),
entityId: z.string().uuid(),
action: z.enum(['create', 'update', 'delete']),
data: z.record(z.string(), z.unknown()).optional(),
}).strict();
export const syncPushSchema = z.object({
operations: z.array(z.object({
idempotencyKey: z.string().min(1).max(200),
entityType: z.enum(['list', 'task', 'tag', 'taskTag']),
entityId: z.string().uuid(),
action: z.enum(['create', 'update', 'delete']),
data: z.record(z.string(), z.unknown()).optional(),
}).strict()),
// Length first: one issue for an oversized batch, whatever its items.
operations: z.array(z.unknown()).max(SYNC_MAX_OPERATIONS).pipe(z.array(syncOperationSchema)),
}).strict();
export type SyncOperation = z.infer<typeof syncPushSchema>['operations'][number];

View file

@ -0,0 +1,24 @@
import { describe, it, expect } from 'vitest';
import { config } from './middleware';
// Next only cuts a request body at 10 MB (experimental.proxyClientMaxBodySize,
// next/dist/server/body-streams.js) when the middleware covers the route
// (#147): POST /api/sync relies on that cut, so every matcher must cover it.
// Each pattern is read as an anchored RegExp, which is exact for the
// regex-only patterns this file uses.
const patterns = config.matcher.map((p) => new RegExp(`^${p}$`));
describe('middleware config.matcher', () => {
it('has at least one pattern', () => {
expect(patterns.length).toBeGreaterThan(0);
});
it.each(config.matcher.map((p, i) => [p, patterns[i]] as const))('%s covers /api/sync', (_, re) => {
expect(re.test('/api/sync')).toBe(true);
});
it('reads the patterns as written (they still exclude /api/health)', () => {
expect(patterns.some((re) => re.test('/api/health'))).toBe(false);
});
});