poad 2.40.0 → 2.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/global/cli.js CHANGED
@@ -10,7 +10,7 @@ module.exports = {
10
10
  install: `Install poad environment`,
11
11
  init: `Init poad project`,
12
12
  create: 'Create a poad project and its front-ends. Outside a project: create <project> --template angular|next|nuxt|vanilla [--app web] makes poad/ (backend) and apps/<app> (first front-end), a workspace package.json (bun start: poad, then every front-end), dependencies, first git commit. Inside a project: create <app> --template t adds apps/<app> on its own port. --flat: the former layout (poad/ inside the app). Template from npm, integrity checked (create --help)',
13
- start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state, secrets hidden: poad info --secrets (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one',
13
+ start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state, secrets hidden: poad info --secrets (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one. Request bodies are limited by the gateway to [gateway] max_body of poad/config.toml (default "10m", storage uploads excepted)',
14
14
  stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
15
15
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
16
16
  clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey/flows runner, networks, unused engine images (--dry-run to list, --yes without question)',
package/global/start.js CHANGED
@@ -25,6 +25,7 @@ module.exports = async (args = {}) => {
25
25
  const mail = require('../utils/mail');
26
26
  const valkey = require('../utils/valkey');
27
27
  const runner = require('../utils/runner');
28
+ const gateway = require('../utils/gateway');
28
29
  const root = findPoadDir(process.cwd());
29
30
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
30
31
  const config = require('../utils/config').readConfig(root);
@@ -50,6 +51,8 @@ module.exports = async (args = {}) => {
50
51
  return finish();
51
52
  }
52
53
  config.engine = await offerEngineUpgrade(root, config, args);
54
+ const gatewayWarning = gateway.maxBody(config).warning;
55
+ if (gatewayWarning) console.log(chalk.yellowBright(gatewayWarning));
53
56
  const image = 'poadio/engine:' + config.engine;
54
57
  // L'image de la version du projet n'est pas forcément là (poad install tire
55
58
  // celle du CLI, et config.toml peut en demander une autre) : on la tire.
@@ -120,6 +123,8 @@ module.exports = async (args = {}) => {
120
123
  ...valkey.engineEnv(config),
121
124
  // FLOWS_* : engine 0.18.0+ et Valkey configuré ; sinon le service flows reste arrêté
122
125
  ...runner.engineEnv(config),
126
+ // Taille maximale d'un corps de requête : [gateway] max_body (engine 0.28.2+)
127
+ ...gateway.engineEnv(config),
123
128
  ],
124
129
  ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
125
130
  HostConfig: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.40.0",
3
+ "version": "2.42.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -22,7 +22,7 @@ module.exports = {
22
22
  diff: 'Structure changes made outside the migrations (console SQL, psql…): diff to list them, diff <name> to write them as a migration, diff --discard to forget them',
23
23
  },
24
24
  upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade channel=beta (or channel = "beta" in poad/config.toml, or POAD_CHANNEL=beta), upgrade --rollback, upgrade --list (--yes outside a terminal)',
25
- logs: 'Unified logs of the project: logs [service…] level=warn since=15m request=<id> grep=<text> flow=<name> run=<id or its first 8 characters> step=<name> function=<name> limit=100 -f --json',
25
+ logs: 'Unified logs of the project: logs [service…] level=warn since=15m request=<id> grep=<text> flow=<name> run=<id or its first 8 characters> step=<name> function=<name> token=<MCP token name, id or prefix> tool=<MCP tool> outcome=<ok, refused, error…> limit=100 -f --json',
26
26
  gen: {
27
27
  description: 'Generators: gen types (TypeScript types of the database), gen env (types of the public variables)',
28
28
  types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
package/project/logs.js CHANGED
@@ -12,6 +12,12 @@
12
12
  // 8 caractères au moins)
13
13
  // poad logs step=appel une étape (avec flow= ou run= le plus souvent)
14
14
  // poad logs function=demo-stats une fonction : ses appels et ses console.log
15
+ // poad logs token="Claude Code" un jeton du serveur MCP (engine 0.29+) : par son
16
+ // nom, son id (ou son début) ou son préfixe ; ses
17
+ // appels (mcp) et les changements de ses droits (meta)
18
+ // poad logs tool=select_rows un outil du serveur MCP
19
+ // poad logs outcome=refused un résultat d'appel MCP (ok, error, refused,
20
+ // invalid, not_found, unauthorized, rate_limited)
15
21
  // poad logs limit=500 nombre de lignes (100 par défaut)
16
22
  // poad logs -f | --follow suivi en direct
17
23
  // poad logs --json une ligne JSON par entrée (pour jq)
@@ -21,14 +27,14 @@
21
27
  // dit pas. Le CLI lit _logs.entries dans la base du projet : ces filtres
22
28
  // portent sur la colonne attrs et valent pour tout engine qui a le collecteur
23
29
  // (les index qui les accélèrent arrivent avec l'engine 0.18.1).
24
- module.exports = async (args = {}) => {
30
+ module.exports = async (args = {}, raw = []) => {
25
31
  const chalk = require('chalk-v2');
26
32
  const { findPoadDir } = require('../utils/findpoad');
27
33
  const { isDockerExist } = require('../utils/docker');
28
34
  const { readConfig } = require('../utils/config');
29
35
  const { supportsLogs } = require('../utils/logs');
30
36
  const { connect } = require('../utils/migrations');
31
- const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine } = require('../utils/logline');
37
+ const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition } = require('../utils/logline');
32
38
 
33
39
  const root = findPoadDir(process.cwd());
34
40
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
@@ -42,7 +48,7 @@ module.exports = async (args = {}) => {
42
48
  return console.log(chalk.redBright('The project is not started: run "poad start".'));
43
49
  }
44
50
 
45
- const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', 'run', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
51
+ const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
46
52
  const flag = (...names) => names.some((n) => args[n] === true);
47
53
  const follow = flag('-f', '--follow', 'follow');
48
54
  const asJson = flag('--json', 'json');
@@ -74,25 +80,38 @@ module.exports = async (args = {}) => {
74
80
  process.exitCode = 1;
75
81
  return console.log(chalk.redBright(attrs.error));
76
82
  }
83
+ // token= : la valeur telle que tapée (parseArgs ferait d'un préfixe tout en chiffres un nombre)
84
+ const typed = raw.find((w) => typeof w === 'string' && w.startsWith('token='));
85
+ const token = parseToken(typed !== undefined ? typed.slice('token='.length) : args.token);
86
+ if (token && token.error) {
87
+ process.exitCode = 1;
88
+ return console.log(chalk.redBright(token.error));
89
+ }
77
90
  const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
78
91
 
79
92
  // Conditions communes à la première lecture et au suivi
80
93
  const where = [];
81
94
  const values = [];
82
- const add = (sql, v) => {
83
- values.push(v);
84
- where.push(sql.replace('?', `$${values.length}`));
95
+ const add = (sql, ...vs) => {
96
+ where.push(
97
+ sql.replace(/\?/g, () => {
98
+ values.push(vs.shift());
99
+ return `$${values.length}`;
100
+ }),
101
+ );
85
102
  };
86
103
  if (services.length) add('service = any(?)', services);
87
104
  if (level) add('level = any(?)', LEVELS.slice(LEVELS.indexOf(level)));
88
105
  if (since) add("ts >= now() - ?::interval", since);
89
106
  if (args.request) add('request_id like ?', `${String(args.request).replace(/[%_]/g, '')}%`);
90
107
  if (args.grep) add('msg ilike ?', `%${String(args.grep).replace(/[%_\\]/g, (c) => `\\${c}`)}%`);
91
- for (const [sql, v] of attrs.conditions) add(sql, v);
108
+ for (const [sql, ...v] of attrs.conditions) add(sql, ...v);
92
109
 
93
110
  const print = (r) => console.log(asJson ? JSON.stringify(r) : formatLine(r, chalk));
94
111
 
95
112
  const client = await connect(config);
113
+ // Le jeton par son nom actuel, son préfixe ou le début de son id : ses lignes, même sous un ancien nom
114
+ if (token) add(...tokenCondition(token, await resolveTokenIds(client, token)));
96
115
  const from = (extra) => fromClause([...where, ...(extra ? [extra] : [])].join(' and ') || 'true', attrs.prefix);
97
116
  let lastId = 0;
98
117
  try {
@@ -0,0 +1,24 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const { maxBody, engineEnv } = require('../utils/gateway');
4
+
5
+ test('gateway : max_body par défaut 10m', () => {
6
+ assert.deepStrictEqual(maxBody({}), { value: '10m' });
7
+ assert.deepStrictEqual(maxBody({ gateway: {} }), { value: '10m' });
8
+ assert.deepStrictEqual(engineEnv({}), ['POAD_GATEWAY_MAX_BODY=10m']);
9
+ });
10
+
11
+ test('gateway : max_body de config.toml, normalisé', () => {
12
+ assert.deepStrictEqual(engineEnv({ gateway: { max_body: '50m' } }), ['POAD_GATEWAY_MAX_BODY=50m']);
13
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: ' 512K ' } }), { value: '512k' });
14
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: 1048576 } }), { value: '1048576' });
15
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: '0' } }), { value: '0' });
16
+ });
17
+
18
+ test('gateway : une valeur qui n’est pas une taille donne 10m et un avertissement', () => {
19
+ for (const bad of ['10 MB', '10mb', '-1', '1.5m', 'big', '10m; return 200']) {
20
+ const r = maxBody({ gateway: { max_body: bad } });
21
+ assert.strictEqual(r.value, '10m', bad);
22
+ assert.match(r.warning, /is not a size/);
23
+ }
24
+ });
@@ -0,0 +1,192 @@
1
+ // poad logs : filtres du serveur MCP (token=, tool=, outcome=) et rendu de ses lignes.
2
+ // Sans réseau ni Docker : la base du projet est un faux client qui note les requêtes.
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const path = require('path');
6
+ const { attrConditions, parseToken, tokenCondition, resolveTokenIds, formatLine } = require('../utils/logline');
7
+
8
+ // chalk sans couleur : chaque style rend le texte tel quel, chaînable (chalk.bgRed.white)
9
+ const plain = new Proxy(function () {}, { get: () => plain, apply: (t, self, [s]) => String(s) });
10
+ // chalk qui marque le style : chalk.green('ok') → <green>ok</green>
11
+ const marked = (name = '') => new Proxy(function () {}, { get: (t, k) => marked(k), apply: (t, self, [s]) => `<${name}>${s}</${name}>` });
12
+
13
+ const TOKEN_ID = '3f2a9c1e-5b7d-4e8f-9a0b-1c2d3e4f5a6b';
14
+ const SECRET_LIKE = `poad_mcp_ab12cd34_${'Z'.repeat(40)}`;
15
+
16
+ test('logs : tool= et outcome= portent sur les attributs du même nom', () => {
17
+ const r = attrConditions({ tool: 'select_rows', outcome: 'refused' });
18
+ assert.deepStrictEqual(r.conditions, [
19
+ ["attrs->>'tool' = ?", 'select_rows'],
20
+ ["attrs->>'outcome' = ?", 'refused'],
21
+ ]);
22
+ assert.match(attrConditions({ tool: true }).error, /tool=<name>: a value is expected, such as tool=select_rows/);
23
+ assert.match(attrConditions({ outcome: '' }).error, /outcome=<outcome>/);
24
+ });
25
+
26
+ test('logs : token= par le nom, le préfixe, l’id entier ou son début', () => {
27
+ assert.deepStrictEqual(parseToken('Claude Code de Marie'), { name: 'Claude Code de Marie', prefix: null, id: null, idStart: null });
28
+ assert.deepStrictEqual(parseToken('ab12cd34'), { name: 'ab12cd34', prefix: 'ab12cd34', id: null, idStart: 'ab12cd34' });
29
+ assert.deepStrictEqual(parseToken('poad_mcp_ab12cd34'), { name: 'poad_mcp_ab12cd34', prefix: 'ab12cd34', id: null, idStart: null });
30
+ assert.deepStrictEqual(parseToken(TOKEN_ID.toUpperCase()), { name: TOKEN_ID.toUpperCase(), prefix: null, id: TOKEN_ID, idStart: null });
31
+ assert.strictEqual(parseToken('3f2a9c1e-5b7d').idStart, '3f2a9c1e-5b7d');
32
+ assert.strictEqual(parseToken(undefined), null);
33
+ assert.match(parseToken(true).error, /a value is expected/);
34
+ });
35
+
36
+ test('logs : token= refuse un jeton entier sans le répéter', () => {
37
+ const r = parseToken(SECRET_LIKE);
38
+ assert.match(r.error, /MCP token itself/);
39
+ assert.ok(!r.error.includes('ZZZZZZZZ'), 'le secret ne doit pas apparaître');
40
+ assert.ok(!r.error.includes('ab12cd34'));
41
+ });
42
+
43
+ test('logs : condition de token= (nom, ids résolus, préfixe des refus, début d’id)', () => {
44
+ const [sql, ...values] = tokenCondition(parseToken('ab12cd34'), [TOKEN_ID]);
45
+ assert.strictEqual(sql, "(attrs->>'token_name' = ? or attrs->>'name_before' = ? or attrs->>'token_id' = any(?) or attrs->>'token_prefix' = ? or attrs->>'token_id' like ?)");
46
+ assert.deepStrictEqual(values, ['ab12cd34', 'ab12cd34', [TOKEN_ID], 'ab12cd34', 'ab12cd34%']);
47
+ // Un id entier compte même absent de la table (jeton supprimé) ; pas de doublon
48
+ const [sql2, ...v2] = tokenCondition(parseToken(TOKEN_ID), [TOKEN_ID]);
49
+ assert.strictEqual(sql2, "(attrs->>'token_name' = ? or attrs->>'name_before' = ? or attrs->>'token_id' = any(?))");
50
+ assert.deepStrictEqual(v2, [TOKEN_ID, TOKEN_ID, [TOKEN_ID]]);
51
+ assert.strictEqual(sql2.split('?').length - 1, v2.length, 'autant de ? que de valeurs');
52
+ });
53
+
54
+ test('logs : resolveTokenIds lit _poad.mcp_tokens, et rien sans la table', async () => {
55
+ const seen = [];
56
+ const client = {
57
+ query: async (text, values) => {
58
+ seen.push({ text, values });
59
+ if (/to_regclass/.test(text)) return { rows: [{ ok: true, changes: true }] };
60
+ return { rows: [{ id: TOKEN_ID }, { id: TOKEN_ID }] };
61
+ },
62
+ };
63
+ assert.deepStrictEqual(await resolveTokenIds(client, parseToken('Claude Code')), [TOKEN_ID]);
64
+ assert.deepStrictEqual(seen[1].values, ['Claude Code', '', '']);
65
+ assert.ok(!/hash/.test(seen[1].text), 'jamais l’empreinte');
66
+ // Un ancien nom : l'historique des droits (engine 0.29.1+), seulement s'il existe
67
+ assert.match(seen[1].text, /union select token_id::text from _poad\.mcp_token_changes where name_before = \$1 or name_after = \$1/);
68
+ const older = [];
69
+ await resolveTokenIds({ query: async (text) => (older.push(text), /to_regclass/.test(text) ? { rows: [{ ok: true, changes: false }] } : { rows: [] }) }, parseToken('x'));
70
+ assert.ok(!/mcp_token_changes/.test(older[1]));
71
+ const none = { query: async () => ({ rows: [{ ok: false }] }) };
72
+ assert.deepStrictEqual(await resolveTokenIds(none, parseToken('x')), []);
73
+ const broken = { query: async () => { throw new Error('permission denied'); } };
74
+ assert.deepStrictEqual(await resolveTokenIds(broken, parseToken('x')), []);
75
+ });
76
+
77
+ test('logs : rendu d’une ligne mcp (jeton, outil, résultat en couleur, une seule durée)', () => {
78
+ const r = {
79
+ ts: '2026-11-24T10:00:00.000Z', level: 'info', service: 'mcp', request_id: 'abcdef1234567890',
80
+ msg: 'tools/call select_rows ok (12.4 ms)',
81
+ attrs: { token_id: TOKEN_ID, token_name: 'Claude Code', role: 'anon', rpc_method: 'tools/call', tool: 'select_rows', outcome: 'ok', tool_ms: 12.4, duration_ms: 12.6, arg_keys: ['table', 'where'] },
82
+ };
83
+ const text = formatLine(r, plain);
84
+ assert.match(text, /\[Claude Code\] tools\/call select_rows ok \(12\.4 ms\) anon/);
85
+ assert.ok(!text.includes('12.6 ms'), 'duration_ms en double');
86
+ assert.match(text, /args: table,where/);
87
+ assert.ok(!text.includes(TOKEN_ID));
88
+ assert.match(formatLine(r, marked()), /<green>ok<\/green>/);
89
+
90
+ // Message sans l'outil ni le résultat : ils sont ajoutés
91
+ const bare = formatLine({ ...r, msg: 'tools/call', attrs: { ...r.attrs, outcome: 'refused' } }, marked());
92
+ assert.match(bare, /<cyan>select_rows<\/cyan> <yellow>refused<\/yellow> 12\.4 ms/);
93
+
94
+ // Appel refusé avant tout message : le préfixe, la raison
95
+ const denied = formatLine({ ...r, level: 'warn', msg: 'unauthorized', attrs: { outcome: 'unauthorized', reason: 'revoked', token_prefix: 'ab12cd34', duration_ms: 1.1 } }, plain);
96
+ assert.match(denied, /\[poad_mcp_ab12cd34…\] unauthorized revoked 1\.1 ms/);
97
+ });
98
+
99
+ test('logs : rendu des lignes mcp telles que les écrit l’engine 0.29.0 (nom dans le message, pas de durée)', () => {
100
+ const base = { ts: '2026-11-24T20:51:37.119Z', service: 'mcp', request_id: 'dd7cc423-7374' };
101
+ const ok = formatLine({ ...base, level: 'info', msg: 'tools/call list_tables ok [Live check CLI]', attrs: { role: 'anon', tool: 'list_tables', outcome: 'ok', tool_ms: 8.8, arg_keys: ['schema'], token_name: 'Live check CLI', duration_ms: 9.1 } }, plain);
102
+ assert.match(ok, /info tools\/call list_tables ok \[Live check CLI\] 8\.8 ms anon args: schema ·dd7cc423$/);
103
+ const refused = formatLine({ ...base, level: 'warn', msg: 'tools/call execute_sql refused [Live check CLI]', attrs: { role: 'anon', tool: 'execute_sql', error: 'missing scope sql', outcome: 'refused', arg_keys: ['query'], token_name: 'Live check CLI', duration_ms: 0 } }, marked());
104
+ assert.match(refused, /execute_sql <yellow>refused<\/yellow> \[Live check CLI\]/);
105
+ const denied = formatLine({ ...base, level: 'warn', msg: 'POST /mcp/v1 401 unknown', attrs: { reason: 'unknown', status: 401, outcome: 'unauthorized', duration_ms: 0.6, token_prefix: '1kh8k2m3' } }, plain);
106
+ assert.match(denied, /\[poad_mcp_1kh8k2m3…\] POST \/mcp\/v1 401 unknown unauthorized 0\.6 ms ·dd7cc423$/);
107
+ });
108
+
109
+ test('logs : rendu d’un changement de droits d’un jeton (meta)', () => {
110
+ const text = formatLine({
111
+ ts: '2026-11-24T10:00:00.000Z', level: 'warn', service: 'meta', request_id: null,
112
+ msg: 'jeton MCP « Claude Code » modifié par cli : droits élargis',
113
+ attrs: { event: 'mcp_token_updated', token_id: TOKEN_ID, token_name: 'Claude Code', actor: 'cli', scopes_added: ['data:write'], scopes_removed: ['sql'] },
114
+ }, plain);
115
+ assert.match(text, /droits élargis \+data:write -sql$/);
116
+ // Renommage et échéance, tels que les écrit l'engine 0.29.1
117
+ const renamed = formatLine({
118
+ ts: '2026-11-24T21:01:45.387Z', level: 'info', service: 'meta', request_id: '5f26fd1c-83f5',
119
+ msg: 'jeton MCP « Live check renamed » modifié par cli',
120
+ attrs: { actor: 'cli', event: 'mcp_token_updated', expiry: 'unchanged', token_id: TOKEN_ID, token_name: 'Live check renamed', name_before: 'Live check CLI', scopes_added: [], scopes_removed: [] },
121
+ }, plain);
122
+ assert.match(renamed, /modifié par cli renamed from « Live check CLI » ·5f26fd1c$/);
123
+ const shortened = formatLine({
124
+ ts: '2026-11-24T21:01:45.387Z', level: 'info', service: 'meta', request_id: null, msg: 'jeton MCP « x » modifié par cli',
125
+ attrs: { event: 'mcp_token_updated', token_name: 'x', name_before: 'x', expiry: 'shortened', expires_at_after: '2026-12-01T00:00:00.000Z' },
126
+ }, plain);
127
+ assert.match(shortened, /modifié par cli expiry shortened 2026-12-01$/);
128
+ });
129
+
130
+ // poad logs de bout en bout, modules du projet remplacés
131
+ const run = async (args, raw, rows = []) => {
132
+ const queries = [];
133
+ const client = {
134
+ query: async (text, values) => {
135
+ queries.push({ text, values });
136
+ if (/to_regclass/.test(text)) return { rows: [{ ok: true }] };
137
+ if (/_poad\.mcp_tokens/.test(text)) return { rows: [{ id: TOKEN_ID }] };
138
+ if (/max\(id\)/.test(text)) return { rows: [{ id: 0 }] };
139
+ if (/id > /.test(text)) {
140
+ setImmediate(() => process.emit('SIGINT'));
141
+ return { rows: [] };
142
+ }
143
+ return { rows };
144
+ },
145
+ end: async () => {},
146
+ };
147
+ const stub = (rel, exports) => {
148
+ const file = require.resolve(path.join('..', rel));
149
+ require.cache[file] = { id: file, filename: file, loaded: true, exports };
150
+ };
151
+ stub('utils/findpoad', { findPoadDir: () => '/tmp/projet' });
152
+ stub('utils/config', { readConfig: () => ({ engine: '0.29.1', project_uuid: 'test' }) });
153
+ stub('utils/docker', { isDockerExist: async () => true });
154
+ stub('utils/migrations', { connect: async () => client });
155
+ delete require.cache[require.resolve('../project/logs')];
156
+ const out = [];
157
+ const log = console.log;
158
+ console.log = (...a) => out.push(a.join(' '));
159
+ try {
160
+ await require('../project/logs')(args, raw);
161
+ } finally {
162
+ console.log = log;
163
+ }
164
+ return { queries, out };
165
+ };
166
+
167
+ test('poad logs mcp token=<nom> tool= outcome= : une requête paramétrée, --json inchangé', async () => {
168
+ const row = { id: 7, ts: '2026-11-24T10:00:00.000Z', level: 'info', service: 'mcp', msg: 'tools/call select_rows ok (1 ms)', request_id: 'r1', attrs: { token_name: 'Claude Code', tool: 'select_rows', outcome: 'ok' } };
169
+ const raw = ['mcp', 'token=Claude Code', 'tool=select_rows', 'outcome=ok', '--json'];
170
+ const { queries, out } = await run({ mcp: true, token: 'Claude Code', tool: 'select_rows', outcome: 'ok', '--json': true }, raw, [row]);
171
+ const read = queries.find((q) => /from _logs\.entries/.test(q.text));
172
+ assert.match(read.text, /service = any\(\$1\) and attrs->>'tool' = \$2 and attrs->>'outcome' = \$3 and \(attrs->>'token_name' = \$4 or attrs->>'name_before' = \$5 or attrs->>'token_id' = any\(\$6\)\)/);
173
+ assert.deepStrictEqual(read.values, [['mcp'], 'select_rows', 'ok', 'Claude Code', 'Claude Code', [TOKEN_ID]]);
174
+ assert.ok(!read.text.includes('Claude Code'), 'les valeurs passent en paramètre');
175
+ assert.deepStrictEqual(out.map((l) => JSON.parse(l)), [row]);
176
+ });
177
+
178
+ test('poad logs token=<préfixe tout en chiffres> -f : la valeur telle que tapée, et le suivi garde le filtre', async () => {
179
+ const { queries } = await run({ token: 1234567, '-f': true }, ['token=01234567', '-f']);
180
+ const follow = queries.find((q) => /id > /.test(q.text));
181
+ assert.ok(follow, 'requête de suivi');
182
+ assert.match(follow.text, /attrs->>'token_prefix' = \$4/);
183
+ assert.deepStrictEqual(follow.values, ['01234567', '01234567', [TOKEN_ID], '01234567', '01234567%']);
184
+ });
185
+
186
+ test('poad logs token=<jeton entier> : refusé, aucune requête, le jeton n’est pas répété', async () => {
187
+ const { queries, out } = await run({ token: SECRET_LIKE }, [`token=${SECRET_LIKE}`]);
188
+ assert.strictEqual(queries.length, 0);
189
+ assert.ok(!out.join('\n').includes('ZZZZZZZZ'));
190
+ assert.strictEqual(process.exitCode, 1);
191
+ process.exitCode = 0;
192
+ });
@@ -0,0 +1,31 @@
1
+ // Passerelle de l'engine : réglages de poad/config.toml qu'elle lit au
2
+ // démarrage, passés en variables d'environnement par `poad start`.
3
+ //
4
+ // [gateway]
5
+ // max_body = "10m" taille maximale d'un corps de requête (k, m ou g ;
6
+ // "0" = aucune limite). Au-delà : 413. Les envois du
7
+ // storage y échappent (le service a sa propre limite).
8
+ //
9
+ // Engine 0.28.2 et plus (POAD_GATEWAY_MAX_BODY) ; un engine plus ancien ignore
10
+ // la variable et n'a pas de limite. L'engine vérifie aussi la valeur et revient
11
+ // à 10m si elle n'est pas une taille.
12
+
13
+ const DEFAULT_MAX_BODY = '10m';
14
+ const SIZE = /^[0-9]+[kmg]?$/;
15
+
16
+ /** Taille maximale d'un corps, normalisée ; { value, warning } si la valeur de config.toml est refusée */
17
+ const maxBody = (config) => {
18
+ const raw = config && config.gateway ? config.gateway.max_body : undefined;
19
+ if (raw === undefined || raw === null || raw === '') return { value: DEFAULT_MAX_BODY };
20
+ const value = String(raw).trim().toLowerCase();
21
+ if (SIZE.test(value)) return { value };
22
+ return {
23
+ value: DEFAULT_MAX_BODY,
24
+ warning: `[gateway] max_body = "${String(raw).slice(0, 32)}" in poad/config.toml is not a size (examples: "10m", "512k", "1g"): ${DEFAULT_MAX_BODY} is used.`,
25
+ };
26
+ };
27
+
28
+ /** Variables de l'engine */
29
+ const engineEnv = (config) => [`POAD_GATEWAY_MAX_BODY=${maxBody(config).value}`];
30
+
31
+ module.exports = { DEFAULT_MAX_BODY, maxBody, engineEnv };
package/utils/logline.js CHANGED
@@ -5,7 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
5
5
 
6
6
  // Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
7
7
  // que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
8
- const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function' };
8
+ const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome' };
9
+ const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused' };
9
10
  // Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
10
11
  const RUN_RE = /^[0-9a-f-]{8,36}$/;
11
12
 
@@ -22,7 +23,7 @@ const attrConditions = (args = {}) => {
22
23
  for (const [option, attr] of Object.entries(ATTR_OPTIONS)) {
23
24
  const value = args[option];
24
25
  if (value === undefined) continue;
25
- if (value === true || value === '') return { error: `${option}=<name>: a value is expected, such as ${option}=${option === 'function' ? 'demo-stats' : option === 'step' ? 'appel' : 'demo-flux'}` };
26
+ if (value === true || value === '') return { error: `${option}=<${option === 'outcome' ? 'outcome' : 'name'}>: a value is expected, such as ${option}=${EXAMPLES[option]}` };
26
27
  conditions.push([`attrs->>'${attr}' = ?`, String(value)]);
27
28
  }
28
29
  if (args.run !== undefined) {
@@ -44,6 +45,79 @@ const attrConditions = (args = {}) => {
44
45
  */
45
46
  const fromClause = (cond, prefix) => (prefix ? `(select * from _logs.entries where ${cond} offset 0) e` : `_logs.entries where ${cond}`);
46
47
 
48
+ // Jeton du serveur MCP (engine 0.29+) : poad_mcp_<préfixe de 8>_<secret>.
49
+ // Le préfixe et l'id se montrent (console, lignes du puits), jamais le secret.
50
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
51
+ const ID_START_RE = /^[0-9a-f][0-9a-f-]{7,34}$/;
52
+ const PREFIX_RE = /^[a-z0-9]{8}$/;
53
+
54
+ /**
55
+ * Ce que désigne token=<valeur> : un nom, un id (entier ou son début, 8
56
+ * caractères au moins) ou le préfixe du jeton (8 caractères, ou poad_mcp_<préfixe>).
57
+ * Un jeton entier est refusé, sans le répéter : il n'a rien à faire sur une
58
+ * ligne de commande ni dans l'historique du shell.
59
+ */
60
+ const parseToken = (value) => {
61
+ if (value === undefined) return null;
62
+ if (value === true || String(value).trim() === '') return { error: 'token=<name>: a value is expected, the name, id or prefix of an MCP token, such as token="Claude Code"' };
63
+ const v = String(value).trim();
64
+ if (/^poad_mcp_[a-z0-9]{8}_/i.test(v)) return { error: 'token=: this is an MCP token itself. Give its name, its id or its prefix (poad_mcp_<prefix>), never the token: revoke it if it was shared.' };
65
+ const m = /^poad_mcp_([a-z0-9]{8})$/.exec(v);
66
+ const lower = v.toLowerCase();
67
+ return {
68
+ name: v,
69
+ prefix: m ? m[1] : PREFIX_RE.test(v) ? v : null,
70
+ id: UUID_RE.test(lower) ? lower : null,
71
+ idStart: !UUID_RE.test(lower) && ID_START_RE.test(lower) ? lower : null,
72
+ };
73
+ };
74
+
75
+ /**
76
+ * Ids des jetons de _poad.mcp_tokens que désigne token= : par le nom actuel,
77
+ * le préfixe ou le début de l'id. Couvre les lignes écrites sous un ancien nom.
78
+ * Sans la table (engine avant 0.29) ou sans droit de la lire : aucun.
79
+ */
80
+ const resolveTokenIds = async (client, t) => {
81
+ if (!t || t.error) return [];
82
+ try {
83
+ const exists = await client.query(
84
+ "select to_regclass('_poad.mcp_tokens') is not null as ok, to_regclass('_poad.mcp_token_changes') is not null as changes",
85
+ );
86
+ if (!exists.rows[0] || !exists.rows[0].ok) return [];
87
+ // Un ancien nom (renommage, engine 0.29.1+) : l'historique des droits le garde
88
+ const former = exists.rows[0].changes ? ' union select token_id::text from _poad.mcp_token_changes where name_before = $1 or name_after = $1' : '';
89
+ const r = await client.query(
90
+ `select id::text as id from _poad.mcp_tokens where name = $1 or prefix = $2 or id::text like $3${former}`,
91
+ [t.name, t.prefix || '', t.id || (t.idStart ? `${t.idStart}%` : '')],
92
+ );
93
+ return [...new Set(r.rows.map((row) => row.id))];
94
+ } catch {
95
+ return [];
96
+ }
97
+ };
98
+
99
+ /**
100
+ * Condition de token= sur les lignes de mcp (token_id, token_name, et
101
+ * token_prefix d'un appel refusé) et de meta (mcp_token_updated, mcp_token_revoked).
102
+ * Renvoie [sql avec des ?, ...valeurs].
103
+ */
104
+ const tokenCondition = (t, ids = []) => {
105
+ const all = [...new Set([...ids, ...(t.id ? [t.id] : [])])];
106
+ // name_before : la ligne de meta d'un renommage, sous l'ancien nom
107
+ const parts = ["attrs->>'token_name' = ?", "attrs->>'name_before' = ?", "attrs->>'token_id' = any(?)"];
108
+ const values = [t.name, t.name, all];
109
+ if (t.prefix) {
110
+ parts.push("attrs->>'token_prefix' = ?");
111
+ values.push(t.prefix);
112
+ }
113
+ if (t.idStart) {
114
+ // Ni % ni _ possibles (ID_START_RE) : rien à échapper
115
+ parts.push("attrs->>'token_id' like ?");
116
+ values.push(`${t.idStart}%`);
117
+ }
118
+ return [`(${parts.join(' or ')})`, ...values];
119
+ };
120
+
47
121
  const COLORS = ['cyanBright', 'magentaBright', 'blueBright', 'greenBright', 'yellow', 'cyan', 'magenta', 'blue'];
48
122
  const colorOf = (s) => COLORS[[...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % COLORS.length];
49
123
  const WIDTH = 8;
@@ -60,9 +134,55 @@ const origin = (r, chalk) => {
60
134
  return a.stream === 'stderr' ? chalk.yellow(`[${a.step}!]`) : chalk.cyan(`[${a.step}]`);
61
135
  }
62
136
  if (a.function && !String(r.msg).includes(String(a.function))) return chalk.cyan(`[${a.function}]`);
137
+ // Appel au serveur MCP : le jeton, par son nom, quand le message ne le dit pas
138
+ // (engine 0.29.0 : « tools/call list_tables ok [nom] » ; meta le dit aussi)
139
+ if (r.service === 'mcp') {
140
+ if (a.token_name) return String(r.msg).includes(String(a.token_name)) ? '' : chalk.cyan(`[${a.token_name}]`);
141
+ if (a.token_prefix) return chalk.yellow(`[poad_mcp_${a.token_prefix}…]`);
142
+ }
63
143
  return '';
64
144
  };
65
145
 
146
+ // Résultat d'un appel MCP : ok en vert, refus en jaune, échec en rouge
147
+ const OUTCOME_STYLE = { ok: 'green', refused: 'yellow', invalid: 'yellow', not_found: 'yellow', rate_limited: 'yellow', unauthorized: 'redBright', error: 'redBright' };
148
+ const styleOutcome = (o, chalk) => chalk[OUTCOME_STYLE[o] || 'white'](o);
149
+
150
+ /**
151
+ * Message d'une ligne du service mcp : outil, résultat (en couleur) et durée de
152
+ * l'outil, que le message les dise déjà (« tools/call select_rows ok (12.4 ms) »)
153
+ * ou non. Renvoie { msg, extra, ms } ; ms : la durée est dite, pas de duration_ms en plus.
154
+ */
155
+ const mcpParts = (r, chalk) => {
156
+ const a = r.attrs || {};
157
+ let msg = String(r.msg);
158
+ const extra = [];
159
+ if (a.tool && !msg.includes(String(a.tool))) extra.push(chalk.cyan(String(a.tool)));
160
+ if (a.outcome) {
161
+ const o = String(a.outcome);
162
+ const re = /^[a-z_]+$/i.test(o) ? new RegExp(`(^|\\s)${o}(?=\\s|$|\\))`) : null;
163
+ if (re && re.test(msg)) msg = msg.replace(re, (all, sp) => `${sp}${styleOutcome(o, chalk)}`);
164
+ else extra.push(styleOutcome(o, chalk));
165
+ }
166
+ const hasMs = /\d ms\)?$/.test(msg) || /\(\d+(\.\d+)? ms\)/.test(msg);
167
+ if (a.tool_ms !== undefined && !hasMs) extra.push(`${a.tool_ms} ms`);
168
+ // La raison d'un refus, sauf si le message la dit (« POST /mcp/v1 401 revoked »)
169
+ const reason = a.reason ? String(a.reason) : '';
170
+ if (reason && !(/^[a-z_]+$/i.test(reason) && new RegExp(`(^|\\s)${reason}(\\s|$)`).test(msg))) extra.push(chalk.yellow(reason));
171
+ // Les noms des arguments (jamais leur valeur), en dernier
172
+ const tail = Array.isArray(a.arg_keys) && a.arg_keys.length ? [chalk.grey(`args: ${a.arg_keys.join(',')}`)] : [];
173
+ return { msg, extra, tail, ms: hasMs || a.tool_ms !== undefined };
174
+ };
175
+
176
+ // Droits d'un jeton MCP modifiés (service meta) : les scopes gagnés et perdus
177
+ const tokenChange = (a, chalk) => {
178
+ const out = [];
179
+ if (a.name_before && a.token_name && a.name_before !== a.token_name) out.push(chalk.grey(`renamed from « ${a.name_before} »`));
180
+ if (Array.isArray(a.scopes_added) && a.scopes_added.length) out.push(chalk.yellow(a.scopes_added.map((s) => `+${s}`).join(' ')));
181
+ if (Array.isArray(a.scopes_removed) && a.scopes_removed.length) out.push(chalk.grey(a.scopes_removed.map((s) => `-${s}`).join(' ')));
182
+ if (a.expiry && a.expiry !== 'unchanged') out.push(`expiry ${a.expiry}${a.expires_at_after ? ` ${String(a.expires_at_after).slice(0, 10)}` : ''}`);
183
+ return out;
184
+ };
185
+
66
186
  /** Texte d'une entrée de _logs.entries (une ligne, plus la pile d'une erreur) */
67
187
  const formatLine = (r, chalk) => {
68
188
  const a = r.attrs || {};
@@ -70,19 +190,23 @@ const formatLine = (r, chalk) => {
70
190
  const time = new Date(r.ts).toISOString().slice(11, 23);
71
191
  const svc = chalk[colorOf(r.service)](r.service.padEnd(WIDTH).slice(0, WIDTH));
72
192
  const lvl = (levelStyle[r.level] || chalk.white)(r.level.padEnd(5));
73
- const extra = [];
74
- // La durée d'une requête lente de Postgres est déjà dans son message
75
- if (a.duration_ms !== undefined && r.service !== 'postgres') extra.push(`${a.duration_ms} ms`);
193
+ const mcp = r.service === 'mcp' ? mcpParts(r, chalk) : null;
194
+ const msg = mcp ? mcp.msg : r.msg;
195
+ const extra = mcp ? [...mcp.extra] : [];
196
+ // La durée d'une requête lente de Postgres est déjà dans son message, celle d'un appel MCP aussi
197
+ if (a.duration_ms !== undefined && r.service !== 'postgres' && !(mcp && mcp.ms)) extra.push(`${a.duration_ms} ms`);
76
198
  if (a.role) extra.push(a.role);
199
+ if (r.service === 'meta' && /^mcp_token_/.test(a.event || '')) extra.push(...tokenChange(a, chalk));
77
200
  if (a.error_code || a.error) extra.push(chalk.yellow([a.error_code, a.error].filter(Boolean).join(': ')));
78
201
  if (a.err && a.err.message) extra.push(chalk.redBright(a.err.message));
79
202
  if (a.sql) extra.push(chalk.grey(String(a.sql).replace(/\s+/g, ' ').slice(0, 160)));
80
203
  if (a.statement && r.service === 'postgres') extra.push(chalk.grey(String(a.statement).replace(/\s+/g, ' ').slice(0, 160)));
204
+ if (mcp) extra.push(...mcp.tail);
81
205
  const req = r.request_id ? chalk.grey(` ·${r.request_id.slice(0, 8)}`) : '';
82
206
  const from = origin(r, chalk);
83
- let text = `${chalk.grey(time)} ${svc} ${lvl} ${from ? `${from} ` : ''}${r.msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`;
207
+ let text = `${chalk.grey(time)} ${svc} ${lvl} ${from ? `${from} ` : ''}${msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`;
84
208
  if (a.err && a.err.stack && r.level !== 'debug') text += '\n' + chalk.grey(String(a.err.stack).split('\n').slice(1, 6).join('\n'));
85
209
  return text;
86
210
  };
87
211
 
88
- module.exports = { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine };
212
+ module.exports = { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition };