fix(security): whitelist sync data columns and check ownership of references
POST /api/sync copied the client's `data` into `.set()` for list, task and tag updates, so an authenticated client could rewrite `userId` (moving its rows into another account), `id`, `createdAt` or `deletedAt`. Task-tag links, task `listId`/`parentId` and list creation did not check that the referenced rows belong to the caller. - web/src/lib/syncData.ts: one zod schema per entity and action. Unknown keys are stripped rather than rejected, because the app marks its outbox as synced on HTTP 200 and a skipped operation would be lost. Strings are truncated to the mobile limits (notes 10000). Null maps to undefined for NOT NULL columns. - processOperation writes only the parsed output; taskTag create and delete verify the task and the tag; task create/update verify listId; parentId and list create ids are refused when taken by another account (a missing parent passes, since initialMerge can push a subtask before its parent). - vitest 4.1 (vitest 5 requires @types/node >= 22, web is on 20) with tests built from the payloads the app sends today. - REVIEW.md: rules and pitfall updated, npm test added, syncData.ts in the Haut table (review-levels.py --check passes). Refs #142 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
547a180d4b
commit
97f5a6bad6
7 changed files with 1974 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 données de sync (web/src/lib/syncData.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/**",
|
||||
|
|
|
|||
1564
web/package-lock.json
generated
1564
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",
|
||||
|
|
@ -34,6 +35,7 @@
|
|||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.2",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
"typescript": "^5",
|
||||
"vitest": "^4.1.12"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue