From 6fddded0eab8a1d391fccd869d40a8c23e32da19 Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 23:31:11 -0500 Subject: [PATCH 1/2] feat(web): schema for agent tokens and the agent action journal (#199) Add the two tables behind the MCP server of the companion: sl_agent_tokens (personal tokens, only the SHA-256 hash is stored, unique; scope limited to read or write by a CHECK constraint) and sl_agent_actions (journal of what each token wrote; the token link falls to null when the token is deleted, the token name stays). No existing column changes. - schema.ts: the two tables, as specified by the issue. - 0005_agent_tokens.sql, meta/0005_snapshot.json and the journal entry are the untouched output of `drizzle-kit generate --name agent_tokens`. - probe.sql: controls 11 (journal_plus_de_90_jours, journal lines older than 91 days) and 12 (journal_autre_compte, lines whose token or touched row belongs to another account, critical). The read-only contract is unchanged. - probe.test.ts: twelve controls, a journal in the healthy base, one test per new anomaly. - agentSchema.test.ts (new): constraints of the two tables through the drizzle schema, and the migrations through the drizzle migrator, on an empty database and on a populated database at migration 0004. Resolves #199 Co-Authored-By: Claude Fable 5.2 --- web/scripts/probe.sql | 47 +- web/src/db/migrations/0005_agent_tokens.sql | 28 + web/src/db/migrations/meta/0005_snapshot.json | 621 ++++++++++++++++++ web/src/db/migrations/meta/_journal.json | 7 + web/src/db/schema.ts | 36 +- web/src/test/agentSchema.test.ts | 241 +++++++ web/src/test/probe.test.ts | 84 ++- 7 files changed, 1053 insertions(+), 11 deletions(-) create mode 100644 web/src/db/migrations/0005_agent_tokens.sql create mode 100644 web/src/db/migrations/meta/0005_snapshot.json create mode 100644 web/src/test/agentSchema.test.ts diff --git a/web/scripts/probe.sql b/web/scripts/probe.sql index be6371d..33a84b2 100644 --- a/web/scripts/probe.sql +++ b/web/scripts/probe.sql @@ -1,8 +1,8 @@ -- Read-only production probe of the companion database (#176). -- --- Run after each companion deploy (see REVIEW.md, "Déploiement web"). Each --- control returns one row `controle|nombre`: a control name and a count, never --- an account id, a title, a name or any content. "Active" means +-- Run after each companion deploy (see REVIEW.md, "Déploiement web"). Each of +-- the twelve controls returns one row `controle|nombre`: a control name and a +-- count, never an account id, a title, a name or any content. "Active" means -- `deleted_at IS NULL` (lists, tasks and tags are soft-deleted). -- -- The whole script runs in a READ ONLY transaction and ends with ROLLBACK. @@ -30,8 +30,22 @@ -- different user_id values. CRITICAL -- 10. compte_sans_inbox accounts with active tasks and no active Inbox. anomaly -- +-- Journal of the AI assistants (sl_agent_actions, #199): +-- 11. journal_plus_de_90_jours journal lines older than 91 days. anomaly +-- The journal is kept 90 days, purged every day by the server (#203): a +-- line past 91 days means the purge did not run. +-- 12. journal_autre_compte journal lines whose token (token_id) or +-- touched row (entity_id in sl_tasks, sl_lists +-- or sl_tags, by entity_type) belongs to +-- another user_id. CRITICAL +-- A line counts once, even when both its token and its row belong to +-- another account. A line without a token (token_id is null once the token +-- is revoked) or whose row matches nothing does not count; a soft-deleted +-- row of another account counts, as in controls 7 to 9. +-- -- Foreign keys with ON DELETE CASCADE make a link to a missing list, task or --- tag impossible; only parent_id can point to a missing row. +-- tag impossible; only parent_id and the journal's entity_id, which have no +-- foreign key, can point to a missing row. BEGIN TRANSACTION READ ONLY; @@ -104,6 +118,31 @@ SELECT controle, nombre FROM ( SELECT 1 FROM sl_lists l WHERE l.user_id = t.user_id AND l.is_inbox AND l.deleted_at IS NULL ) + + UNION ALL + SELECT 11, 'journal_plus_de_90_jours', count(*)::int + FROM sl_agent_actions a + WHERE a.created_at < now() - interval '91 days' + + UNION ALL + SELECT 12, 'journal_autre_compte', count(*)::int + FROM sl_agent_actions a + WHERE EXISTS ( + SELECT 1 FROM sl_agent_tokens k + WHERE k.id = a.token_id AND k.user_id <> a.user_id + ) + OR (a.entity_type = 'task' AND EXISTS ( + SELECT 1 FROM sl_tasks t + WHERE t.id = a.entity_id AND t.user_id <> a.user_id + )) + OR (a.entity_type = 'list' AND EXISTS ( + SELECT 1 FROM sl_lists l + WHERE l.id = a.entity_id AND l.user_id <> a.user_id + )) + OR (a.entity_type = 'tag' AND EXISTS ( + SELECT 1 FROM sl_tags g + WHERE g.id = a.entity_id AND g.user_id <> a.user_id + )) ) controles ORDER BY rang; diff --git a/web/src/db/migrations/0005_agent_tokens.sql b/web/src/db/migrations/0005_agent_tokens.sql new file mode 100644 index 0000000..341c0da --- /dev/null +++ b/web/src/db/migrations/0005_agent_tokens.sql @@ -0,0 +1,28 @@ +CREATE TABLE "sl_agent_actions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" text NOT NULL, + "token_id" uuid, + "token_name" text NOT NULL, + "tool" text NOT NULL, + "entity_type" text NOT NULL, + "entity_id" uuid NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "sl_agent_tokens" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" text NOT NULL, + "name" text NOT NULL, + "token_hash" text NOT NULL, + "hint" text NOT NULL, + "scope" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "last_used_at" timestamp with time zone, + "expires_at" timestamp with time zone, + CONSTRAINT "sl_agent_tokens_scope_check" CHECK ("sl_agent_tokens"."scope" in ('read', 'write')) +); +--> statement-breakpoint +ALTER TABLE "sl_agent_actions" ADD CONSTRAINT "sl_agent_actions_token_id_sl_agent_tokens_id_fk" FOREIGN KEY ("token_id") REFERENCES "public"."sl_agent_tokens"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "idx_sl_agent_actions_user_created" ON "sl_agent_actions" USING btree ("user_id","created_at");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_sl_agent_tokens_hash" ON "sl_agent_tokens" USING btree ("token_hash");--> statement-breakpoint +CREATE INDEX "idx_sl_agent_tokens_user" ON "sl_agent_tokens" USING btree ("user_id"); \ No newline at end of file diff --git a/web/src/db/migrations/meta/0005_snapshot.json b/web/src/db/migrations/meta/0005_snapshot.json new file mode 100644 index 0000000..28a549f --- /dev/null +++ b/web/src/db/migrations/meta/0005_snapshot.json @@ -0,0 +1,621 @@ +{ + "id": "7827a2c0-f907-46ac-9100-f19ba46d45a1", + "prevId": "f15d185b-4478-4cdf-91b9-e281f16fdb3f", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.sl_agent_actions": { + "name": "sl_agent_actions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_id": { + "name": "token_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "token_name": { + "name": "token_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_sl_agent_actions_user_created": { + "name": "idx_sl_agent_actions_user_created", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sl_agent_actions_token_id_sl_agent_tokens_id_fk": { + "name": "sl_agent_actions_token_id_sl_agent_tokens_id_fk", + "tableFrom": "sl_agent_actions", + "tableTo": "sl_agent_tokens", + "columnsFrom": [ + "token_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_agent_tokens": { + "name": "sl_agent_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hint": { + "name": "hint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_agent_tokens_hash": { + "name": "idx_sl_agent_tokens_hash", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_agent_tokens_user": { + "name": "idx_sl_agent_tokens_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "sl_agent_tokens_scope_check": { + "name": "sl_agent_tokens_scope_check", + "value": "\"sl_agent_tokens\".\"scope\" in ('read', 'write')" + } + }, + "isRLSEnabled": false + }, + "public.sl_lists": { + "name": "sl_lists", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_inbox": { + "name": "is_inbox", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_lists_user": { + "name": "idx_sl_lists_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tags": { + "name": "sl_tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#4A90A4'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tags_user": { + "name": "idx_sl_tags_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_task_tags": { + "name": "sl_task_tags", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag_id": { + "name": "tag_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sl_task_tags_task_id_sl_tasks_id_fk": { + "name": "sl_task_tags_task_id_sl_tasks_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sl_task_tags_tag_id_sl_tags_id_fk": { + "name": "sl_task_tags_tag_id_sl_tags_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sl_task_tags_task_id_tag_id_pk": { + "name": "sl_task_tags_task_id_tag_id_pk", + "columns": [ + "task_id", + "tag_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tasks": { + "name": "sl_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed": { + "name": "completed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "due_date": { + "name": "due_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "list_id": { + "name": "list_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "recurrence": { + "name": "recurrence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tasks_user": { + "name": "idx_sl_tasks_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_list": { + "name": "idx_sl_tasks_list", + "columns": [ + { + "expression": "list_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_parent": { + "name": "idx_sl_tasks_parent", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sl_tasks_list_id_sl_lists_id_fk": { + "name": "sl_tasks_list_id_sl_lists_id_fk", + "tableFrom": "sl_tasks", + "tableTo": "sl_lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/web/src/db/migrations/meta/_journal.json b/web/src/db/migrations/meta/_journal.json index 60cf58a..b37aca1 100644 --- a/web/src/db/migrations/meta/_journal.json +++ b/web/src/db/migrations/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1794153811697, "tag": "0004_cleanup_deleted_task_links", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1794716346885, + "tag": "0005_agent_tokens", + "breakpoints": true } ] } \ No newline at end of file diff --git a/web/src/db/schema.ts b/web/src/db/schema.ts index 7eec89e..525ee23 100644 --- a/web/src/db/schema.ts +++ b/web/src/db/schema.ts @@ -1,4 +1,5 @@ -import { pgTable, uuid, text, integer, boolean, timestamp, primaryKey, index } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; +import { pgTable, uuid, text, integer, boolean, timestamp, primaryKey, index, uniqueIndex, check } from 'drizzle-orm/pg-core'; export const slLists = pgTable('sl_lists', { id: uuid('id').primaryKey().defaultRandom(), @@ -55,3 +56,36 @@ export const slTaskTags = pgTable('sl_task_tags', { }, (table) => [ primaryKey({ columns: [table.taskId, table.tagId] }), ]); + +// Personal tokens that link an AI assistant (MCP) to an account (#199). +// Only the hash of a token is stored; revoking a token deletes its row. +export const slAgentTokens = pgTable('sl_agent_tokens', { + id: uuid('id').primaryKey().defaultRandom(), + userId: text('user_id').notNull(), + name: text('name').notNull(), + tokenHash: text('token_hash').notNull(), // SHA-256 of the token, hex + hint: text('hint').notNull(), // last 4 characters of the token + scope: text('scope').notNull(), // 'read' | 'write' + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + lastUsedAt: timestamp('last_used_at', { withTimezone: true }), + expiresAt: timestamp('expires_at', { withTimezone: true }), // null: never +}, (t) => [ + uniqueIndex('idx_sl_agent_tokens_hash').on(t.tokenHash), + index('idx_sl_agent_tokens_user').on(t.userId), + check('sl_agent_tokens_scope_check', sql`${t.scope} in ('read', 'write')`), +]); + +// Journal of what each token wrote (#199): the type and the id of the touched +// row, never its title. A revoked token leaves its lines, with token_id null. +export const slAgentActions = pgTable('sl_agent_actions', { + id: uuid('id').primaryKey().defaultRandom(), + userId: text('user_id').notNull(), + tokenId: uuid('token_id').references(() => slAgentTokens.id, { onDelete: 'set null' }), + tokenName: text('token_name').notNull(), // name at the time of the call + tool: text('tool').notNull(), + entityType: text('entity_type').notNull(), // 'task' | 'list' | 'tag' + entityId: uuid('entity_id').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), +}, (t) => [ + index('idx_sl_agent_actions_user_created').on(t.userId, t.createdAt), +]); diff --git a/web/src/test/agentSchema.test.ts b/web/src/test/agentSchema.test.ts new file mode 100644 index 0000000..5355d02 --- /dev/null +++ b/web/src/test/agentSchema.test.ts @@ -0,0 +1,241 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash, randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll } from 'vitest'; +import { PGlite } from 'electric-sql-pglite'; +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/pglite'; +import { migrate } from 'drizzle-orm/pglite/migrator'; +import * as schema from '@/db/schema'; + +// Agent tokens and the agent action journal (#199): the two tables of +// migration 0005, on an in-memory Postgres (PGlite). The migrations run +// through the drizzle migrator, as in web/server.ts (journal order, one +// transaction), and the rows are written through the drizzle schema +// (web/src/db/schema.ts): a column that the schema and the migration name +// differently fails here. + +const MIGRATIONS = path.join(__dirname, '../db/migrations'); +const { slAgentTokens, slAgentActions } = schema; + +const pg = new PGlite(); +const db = drizzle(pg, { schema }); + +beforeAll(async () => { + await migrate(db, { migrationsFolder: MIGRATIONS }); +}); + +type TokenFields = Partial; +type ActionFields = Partial; + +// Each test creates its own accounts (#148): no test reads or writes the rows +// of another, so the file passes in any order (vitest runs it shuffled). +const newUser = () => `user-${u()}`; + +// What the companion keeps of a token: the SHA-256 of the secret, in hex. +const hashOf = (secret: string) => createHash('sha256').update(secret).digest('hex'); + +async function newToken(userId: string, fields: TokenFields = {}) { + const [row] = await db.insert(slAgentTokens) + .values({ userId, name: 'Assistant', tokenHash: hashOf(u()), hint: 'abcd', scope: 'write', ...fields }) + .returning(); + return row; +} + +// A journal line written with `token`, on a row id that matches nothing +// unless `fields.entityId` names one. +async function newAction(userId: string, token: { id: string; name: string }, fields: ActionFields = {}) { + const [row] = await db.insert(slAgentActions) + .values({ userId, tokenId: token.id, tokenName: token.name, tool: 'update_task', entityType: 'task', entityId: u(), ...fields }) + .returning(); + return row; +} + +// Why Postgres refused a query: its error code and the constraint it names. +// drizzle wraps the driver error and keeps it as `cause`. +async function refusal(query: PromiseLike): Promise<{ code?: string; constraint?: string }> { + try { + await query; + } catch (e) { + const error = ((e as { cause?: unknown }).cause ?? e) as { code?: string; constraint?: string }; + return { code: error.code, constraint: error.constraint }; + } + throw new Error('the query was accepted'); +} + +describe('sl_agent_tokens', () => { + it('stores a token: id and creation date by default, never used, no expiry', async () => { + const userId = newUser(); + const tokenHash = hashOf(u()); + const row = await newToken(userId, { name: 'Hermes', tokenHash, scope: 'read' }); + expect(row).toMatchObject({ userId, name: 'Hermes', tokenHash, hint: 'abcd', scope: 'read', lastUsedAt: null, expiresAt: null }); + expect(row.id).toMatch(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/); + expect(Math.abs(Date.now() - row.createdAt.getTime())).toBeLessThan(60_000); + }); + + it('refuses a second token with the same hash, in the same account and in another', async () => { + const [A, B] = [newUser(), newUser()]; + const tokenHash = hashOf(u()); + await newToken(A, { tokenHash }); + const duplicate = { code: '23505', constraint: 'idx_sl_agent_tokens_hash' }; + expect(await refusal(newToken(A, { tokenHash }))).toEqual(duplicate); + expect(await refusal(newToken(B, { tokenHash }))).toEqual(duplicate); + const rows = await db.select().from(slAgentTokens).where(eq(slAgentTokens.tokenHash, tokenHash)); + expect(rows.map((r) => r.userId)).toEqual([A]); + }); + + it('accepts the scopes read and write, refuses any other', async () => { + const userId = newUser(); + const outside = { code: '23514', constraint: 'sl_agent_tokens_scope_check' }; + for (const scope of ['admin', '', 'Read', 'read,write']) { + expect(await refusal(newToken(userId, { scope }))).toEqual(outside); + } + const read = await newToken(userId, { scope: 'read' }); + await newToken(userId, { scope: 'write' }); + // The constraint holds on an update too. + expect(await refusal(db.update(slAgentTokens).set({ scope: 'admin' }).where(eq(slAgentTokens.id, read.id)))).toEqual(outside); + const rows = await db.select().from(slAgentTokens).where(eq(slAgentTokens.userId, userId)); + expect(rows.map((r) => r.scope).sort()).toEqual(['read', 'write']); + }); +}); + +describe('sl_agent_actions', () => { + it('keeps the lines of a deleted token: token_id falls to null, token_name stays', async () => { + const userId = newUser(); + const revoked = await newToken(userId, { name: 'Hermes' }); + const kept = await newToken(userId, { name: 'Claude' }); + const first = await newAction(userId, revoked); + const second = await newAction(userId, revoked, { tool: 'create_list', entityType: 'list' }); + const other = await newAction(userId, kept); + expect(first).toMatchObject({ userId, tokenId: revoked.id, tokenName: 'Hermes', tool: 'update_task', entityType: 'task' }); + + await db.delete(slAgentTokens).where(eq(slAgentTokens.id, revoked.id)); + + const lines = await db.select().from(slAgentActions).where(eq(slAgentActions.userId, userId)); + const line = (id: string) => lines.find((l) => l.id === id); + expect(lines).toHaveLength(3); + // Everything but token_id is as written: name, tool, row, date. + expect(line(first.id)).toEqual({ ...first, tokenId: null }); + expect(line(second.id)).toEqual({ ...second, tokenId: null }); + expect(line(first.id)?.tokenName).toBe('Hermes'); + // The line of the token that still exists keeps its link. + expect(line(other.id)).toEqual(other); + }); + + it('refuses a line whose token_id matches no token', async () => { + const userId = newUser(); + expect(await refusal(newAction(userId, { id: u(), name: 'Ghost' }))).toEqual({ + code: '23503', + constraint: 'sl_agent_actions_token_id_sl_agent_tokens_id_fk', + }); + }); +}); + +describe('migrations 0000 to 0005', () => { + type Journal = { entries: { idx: number; tag: string; when: number }[] }; + const journal = JSON.parse(fs.readFileSync(path.join(MIGRATIONS, 'meta/_journal.json'), 'utf8')) as Journal; + const EXISTING = ['sl_lists', 'sl_tasks', 'sl_tags', 'sl_task_tags']; + const OLD = '2026-01-01T00:00:00.000Z'; + + async function count(base: PGlite, table: string): Promise { + return (await base.query<{ n: number }>(`select count(*)::int n from ${table}`)).rows[0].n; + } + + async function tables(base: PGlite): Promise { + const { rows } = await base.query<{ table_name: string }>( + "select table_name from information_schema.tables where table_schema = 'public' order by table_name", + ); + return rows.map((r) => r.table_name); + } + + // Every row and every column definition of the tables that existed before 0005. + async function snapshot(base: PGlite) { + const rows: Record = {}; + for (const table of EXISTING) rows[table] = (await base.query(`select * from ${table} order by 1, 2`)).rows; + const columns = (await base.query( + `select table_name, column_name, data_type, is_nullable, column_default + from information_schema.columns + where table_schema = 'public' and table_name in (${EXISTING.map((t) => `'${t}'`).join(', ')}) + order by table_name, ordinal_position`, + )).rows; + return { rows, columns }; + } + + // Two accounts with lists, tasks (a subtask, a deleted one), tags and links. + async function seedOld(base: PGlite) { + for (const userId of ['user-a', 'user-b']) { + const [inbox, list, gone, task, sub, dead, tag, deadTag] = Array.from({ length: 8 }, () => u()); + await base.query('insert into sl_lists (id, user_id, name, is_inbox) values ($1, $2, $3, true)', [inbox, userId, 'Inbox']); + await base.query('insert into sl_lists (id, user_id, name, color, icon, position) values ($1, $2, $3, $4, $5, 1)', [list, userId, 'Courses', '#4A90A4', 'cart']); + await base.query('insert into sl_lists (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [gone, userId, 'Gone', OLD]); + await base.query( + 'insert into sl_tasks (id, user_id, title, notes, priority, due_date, list_id, recurrence) values ($1, $2, $3, $4, 2, $5, $6, $7)', + [task, userId, 'Task', 'notes', OLD, list, 'weekly'], + ); + await base.query('insert into sl_tasks (id, user_id, title, list_id, parent_id) values ($1, $2, $3, $4, $5)', [sub, userId, 'Subtask', inbox, task]); + await base.query( + 'insert into sl_tasks (id, user_id, title, completed, completed_at, list_id, deleted_at) values ($1, $2, $3, true, $4, $5, $4)', + [dead, userId, 'Dead', OLD, gone], + ); + await base.query('insert into sl_tags (id, user_id, name, color) values ($1, $2, $3, $4)', [tag, userId, 'Urgent', '#E57373']); + await base.query('insert into sl_tags (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [deadTag, userId, 'Old', OLD]); + await base.query('insert into sl_task_tags (task_id, tag_id) values ($1, $3), ($2, $3), ($1, $4)', [task, sub, tag, deadTag]); + } + } + + it('the journal names every migration file once, in file order, with increasing dates', () => { + const files = fs.readdirSync(MIGRATIONS).filter((f) => f.endsWith('.sql')).sort(); + expect(journal.entries.map((e) => `${e.tag}.sql`)).toEqual(files); + expect(journal.entries.map((e) => e.idx)).toEqual(files.map((_, i) => i)); + expect(journal.entries[5].tag).toBe('0005_agent_tokens'); + // The migrator skips an entry that is not more recent than the last one applied. + journal.entries.forEach((e, i) => { + if (i > 0) expect(e.when).toBeGreaterThan(journal.entries[i - 1].when); + }); + }); + + it('0005 names no table that existed before it', () => { + const sql = fs.readFileSync(path.join(MIGRATIONS, '0005_agent_tokens.sql'), 'utf8'); + for (const table of EXISTING) expect(sql).not.toContain(table); + }); + + it('replay on an empty database through the drizzle migrator', async () => { + // beforeAll ran the migrator on the empty database of this file. + expect(await count(pg, 'drizzle.__drizzle_migrations')).toBe(journal.entries.length); + expect(await tables(pg)).toEqual(expect.arrayContaining([...EXISTING, 'sl_agent_tokens', 'sl_agent_actions'])); + }); + + it('0005 applies to a 0004 database that already holds lists, tasks and tags, without changing them', async () => { + // A copy of the migrations whose journal stops at `last`: what an image + // built at that migration applies at start-up. + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-migrations-')); + fs.cpSync(MIGRATIONS, dir, { recursive: true }); + const journalUpTo = (last: number) => fs.writeFileSync( + path.join(dir, 'meta/_journal.json'), + JSON.stringify({ ...journal, entries: journal.entries.filter((e) => e.idx <= last) }), + ); + const old = new PGlite(); + const oldDb = drizzle(old); + try { + journalUpTo(4); + await migrate(oldDb, { migrationsFolder: dir }); + expect(await count(old, 'drizzle.__drizzle_migrations')).toBe(5); + expect(await tables(old)).toEqual([...EXISTING].sort()); + await seedOld(old); + const before = await snapshot(old); + expect(EXISTING.map((t) => before.rows[t].length)).toEqual([6, 6, 4, 6]); + + journalUpTo(5); + await migrate(oldDb, { migrationsFolder: dir }); + expect(await count(old, 'drizzle.__drizzle_migrations')).toBe(6); + expect(await snapshot(old)).toEqual(before); + expect(await tables(old)).toEqual([...EXISTING, 'sl_agent_tokens', 'sl_agent_actions'].sort()); + expect(await count(old, 'sl_agent_tokens')).toBe(0); + expect(await count(old, 'sl_agent_actions')).toBe(0); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + await old.close(); + } + }, 30_000); // a second PGlite instance boots in seconds, over the 5 s default +}); diff --git a/web/src/test/probe.test.ts b/web/src/test/probe.test.ts index 3c14172..1fcc029 100644 --- a/web/src/test/probe.test.ts +++ b/web/src/test/probe.test.ts @@ -23,6 +23,8 @@ const CONTROLS = [ 'sous_tache_parent_autre_compte', 'lien_etiquette_autre_compte', 'compte_sans_inbox', + 'journal_plus_de_90_jours', + 'journal_autre_compte', ] as const; type Control = (typeof CONTROLS)[number]; @@ -30,6 +32,7 @@ type Counts = Record; const pg = new PGlite(); const DELETED = '2026-11-01T12:00:00.000Z'; +const DAY_MS = 24 * 60 * 60 * 1000; beforeAll(async () => { const dir = path.join(__dirname, '../db/migrations'); @@ -41,7 +44,7 @@ beforeAll(async () => { }, 30_000); // PGlite boots in seconds, slower while other files boot theirs (#196) beforeEach(async () => { - await pg.exec('TRUNCATE sl_task_tags, sl_tasks, sl_tags, sl_lists'); + await pg.exec('TRUNCATE sl_agent_actions, sl_agent_tokens, sl_task_tags, sl_tasks, sl_tags, sl_lists'); }); function expected(overrides: Partial = {}): Counts { @@ -93,12 +96,39 @@ async function link(taskId: string, tagId: string) { await pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [taskId, tagId]); } -type Account = { userId: string; inbox: string; list: string; task: string; tag: string }; +// A personal token of an AI assistant (#199); only its account matters here. +async function token(userId: string) { + const id = u(); + await pg.query( + 'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope) values ($1, $2, $3, $4, $5, $6)', + [id, userId, 'token', `hash-${id}`, 'abcd', 'write'], + ); + return id; +} + +// A journal line of `userId`, written with `tokenId` (null: the token was +// revoked since) on the row `entityId`; `ageDays` backdates it by that many +// 24-hour days. +async function action( + userId: string, + tokenId: string | null, + entityId: string, + opts: { type?: 'task' | 'list' | 'tag'; ageDays?: number } = {}, +) { + await pg.query( + 'insert into sl_agent_actions (user_id, token_id, token_name, tool, entity_type, entity_id, created_at) values ($1, $2, $3, $4, $5, $6, $7)', + [userId, tokenId, 'token', 'tool', opts.type ?? 'task', entityId, new Date(Date.now() - (opts.ageDays ?? 0) * DAY_MS).toISOString()], + ); +} + +type Account = { userId: string; inbox: string; list: string; task: string; tag: string; token: string }; // A healthy account, with the soft-deleted rows that must not count: // a deleted Inbox next to the active one, a deleted list holding a deleted // task, a deleted subtask of a deleted parent, a deleted subtask whose parent -// is missing, and a deleted tag without links. +// is missing, and a deleted tag without links. Its journal (#199) holds lines +// that must not count either: on its own task, list and tag with its own +// token, one whose token was revoked and one whose row matches nothing. async function healthyAccount(): Promise { const userId = `user-${u()}`; const inbox = await list(userId, { inbox: true }); @@ -113,7 +143,13 @@ async function healthyAccount(): Promise { await task(userId, l, { parentId: goneTask, deleted: true }); await task(userId, l, { parentId: u(), deleted: true }); await tag(userId, { deleted: true }); - return { userId, inbox, list: l, task: t, tag: g }; + const k = await token(userId); + await action(userId, k, t); + await action(userId, k, l, { type: 'list' }); + await action(userId, k, g, { type: 'tag' }); + await action(userId, null, t); + await action(userId, k, u()); + return { userId, inbox, list: l, task: t, tag: g, token: k }; } async function healthyBase() { @@ -257,10 +293,40 @@ describe('web/scripts/probe.sql: each control detects its seeded anomaly', () => await task(C, cList); expect(await counts()).toEqual(expected({ compte_sans_inbox: 1 })); }); + + it('journal_plus_de_90_jours: a journal line of 92 days', async () => { + const { A } = await healthyBase(); + await action(A.userId, A.token, A.task, { ageDays: 92 }); + expect(await counts()).toEqual(expected({ journal_plus_de_90_jours: 1 })); + }); + + it('journal_plus_de_90_jours does not count a journal line of 90 days', async () => { + const { A } = await healthyBase(); + await action(A.userId, A.token, A.task, { ageDays: 90 }); + expect(await counts()).toEqual(expected()); + }); + + it('journal_autre_compte: a line of A written with a token of B', async () => { + const { A, B } = await healthyBase(); + await action(A.userId, B.token, A.task); + expect(await counts()).toEqual(expected({ journal_autre_compte: 1 })); + }); + + it.each(['task', 'list', 'tag'] as const)('journal_autre_compte: a line of A on a %s of B', async (type) => { + const { A, B } = await healthyBase(); + await action(A.userId, A.token, B[type], { type }); + expect(await counts()).toEqual(expected({ journal_autre_compte: 1 })); + }); + + it('journal_autre_compte counts a line once when both its token and its row belong to B', async () => { + const { A, B } = await healthyBase(); + await action(A.userId, B.token, B.task); + expect(await counts()).toEqual(expected({ journal_autre_compte: 1 })); + }); }); -// Controls 7 to 9 are isolation checks: a cross-account row is a leak even -// once soft-deleted, so they count deleted rows too. +// Controls 7 to 9 and 12 are isolation checks: a cross-account row is a leak +// even once soft-deleted, so they count deleted rows too. describe('web/scripts/probe.sql: isolation controls count deleted rows', () => { it('tache_liste_autre_compte: a deleted task of B in a list of A', async () => { const { A, B } = await healthyBase(); @@ -279,4 +345,10 @@ describe('web/scripts/probe.sql: isolation controls count deleted rows', () => { await link(A.task, await tag(B.userId, { deleted: true })); expect(await counts()).toEqual(expected({ lien_etiquette_autre_compte: 1, lien_etiquette_supprimee: 1 })); }); + + it('journal_autre_compte: a line of A on a deleted task of B', async () => { + const { A, B } = await healthyBase(); + await action(A.userId, A.token, await task(B.userId, B.list, { deleted: true })); + expect(await counts()).toEqual(expected({ journal_autre_compte: 1 })); + }); }); -- 2.52.0 From f23b7aceab29fcabfc61a8b3467e4bd7544e1861 Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 23:31:19 -0500 Subject: [PATCH 2/2] docs(review): the production probe returns twelve lines (#199) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Déploiement web": the probe now also reads the journal of the AI assistants. Twelve lines instead of ten at both places, with the two new controls and their severity: journal_plus_de_90_jours (anomaly) and journal_autre_compte (critical). Co-Authored-By: Claude Fable 5.2 --- REVIEW.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index bd562c6..7eb02d5 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -163,7 +163,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Le site se déploie à la main (rsync des sources puis `docker compose up --build` sur le VPS) : le merge ne déploie pas, et la PR qui exige un déploiement le dit, avec ses étapes. — `STATE.md` (« Companion web ») - Les secrets (`LOGTO_APP_SECRET`, `LOGTO_COOKIE_SECRET`, `DATABASE_URL`) vivent dans l'environnement du conteneur, jamais dans le dépôt ; `web/.env.template` ne porte que des noms et des valeurs publiques. — `web/.env.template`, `CLAUDE.md` global « Securite » - L'image tourne sous l'utilisateur `nextjs` (uid 1001) et embarque `src/db/migrations`, lues au démarrage. — `web/Dockerfile`, `web/server.ts` -- Chaque déploiement du companion est suivi de la sonde `web/scripts/probe.sql`, en lecture seule sur la base de prod : elle compte les dérives que les versions passées ont laissées dans les données (Inbox en double, liens vers une ligne supprimée, sous-tâches orphelines, lignes rattachées à un autre compte). Le nom du conteneur PostgreSQL, l'utilisateur et la base se lisent dans `/data/simpl-liste-web/docker-compose.yml` sur le VPS, sans jamais être affichés ni copiés dans une issue ou une PR. La connexion passe par le socket local du conteneur : ni `DATABASE_URL` ni mot de passe en argument. — #176 +- Chaque déploiement du companion est suivi de la sonde `web/scripts/probe.sql`, en lecture seule sur la base de prod : elle compte les dérives que les versions passées ont laissées dans les données (Inbox en double, liens vers une ligne supprimée, sous-tâches orphelines, lignes rattachées à un autre compte) et, depuis #199, celles du journal des assistants IA (`sl_agent_actions`). Le nom du conteneur PostgreSQL, l'utilisateur et la base se lisent dans `/data/simpl-liste-web/docker-compose.yml` sur le VPS, sans jamais être affichés ni copiés dans une issue ou une PR. La connexion passe par le socket local du conteneur : ni `DATABASE_URL` ni mot de passe en argument. — #176 ```bash ssh ubuntu@vps-b0826277.tail3c811f.ts.net \ @@ -171,7 +171,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm < web/scripts/probe.sql ``` -- Lecture du résultat : une ligne `controle|nombre` par contrôle, dix lignes, des noms et des nombres seulement ; les lignes `BEGIN` et `ROLLBACK` que psql affiche autour ne sont pas des contrôles. L'en-tête de `probe.sql` décrit chaque contrôle et sa gravité : `tache_liste_autre_compte`, `sous_tache_parent_autre_compte` et `lien_etiquette_autre_compte` sont critiques (fuite possible entre comptes), les autres sont des anomalies. `lien_tache_supprimee` n'est pas nul en temps normal : la suppression d'une tâche garde ses liens, il se lit par rapport à la base de départ postée en commentaire de #176. Une erreur, ou moins de dix lignes, veut dire que la sonde n'a pas tourné, pas que la base est saine. +- Lecture du résultat : une ligne `controle|nombre` par contrôle, douze lignes, des noms et des nombres seulement ; les lignes `BEGIN` et `ROLLBACK` que psql affiche autour ne sont pas des contrôles. L'en-tête de `probe.sql` décrit chaque contrôle et sa gravité : `tache_liste_autre_compte`, `sous_tache_parent_autre_compte`, `lien_etiquette_autre_compte` et `journal_autre_compte` sont critiques (fuite possible entre comptes), les autres sont des anomalies. Les deux derniers contrôles lisent le journal des assistants IA (`sl_agent_actions`, #199) : `journal_plus_de_90_jours` compte les lignes de plus de 91 jours (anomalie : le journal se garde 90 jours, une ligne plus vieille veut dire que la purge quotidienne, livrée par #203, n'a pas tourné), et `journal_autre_compte` compte les lignes dont le jeton ou l'élément touché (tâche, liste ou étiquette, supprimé ou non) appartient à un autre compte (critique) ; une ligne dont le jeton a été révoqué ou dont l'élément n'a plus de ligne en base ne compte pas. `lien_tache_supprimee` n'est pas nul en temps normal : la suppression d'une tâche garde ses liens, il se lit par rapport à la base de départ postée en commentaire de #176. Une erreur, ou moins de douze lignes, veut dire que la sonde n'a pas tourné, pas que la base est saine. - Suite d'une anomalie : la session explique à Max chaque compteur non nul (ce qu'il mesure, la cause probable, la gravité), puis un échange de questions et réponses décide s'il faut ouvrir une issue. Pas d'issue automatique, pas de retour arrière du déploiement. - Une PR qui modifie `probe.sql` garde le contrat que vérifie `web/src/test/probe.test.ts` : une transaction `READ ONLY` ouverte en premier, `ROLLBACK` en dernière instruction, aucune méta-commande psql, aucun `COMMIT`, `END` ni `READ WRITE`, et une sortie limitée à `controle` et `nombre`. -- 2.52.0