poad 2.41.0 → 2.45.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.
@@ -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,148 @@
1
+ // Catalogue des modèles d'IA (engine 0.31.0+) : par fournisseur, le modèle par défaut et les modèles proposés,
2
+ // avec leur prix (USD par million de jetons) et leur statut. Il vit dans poadio/permalink (poad.json, public),
3
+ // sous la clé « ai » : on y ajoute un modèle sans republier le CLI ni l'engine. Un CLI plus ancien ne lit que
4
+ // la clé « engine » et ignore celle-ci.
5
+ //
6
+ // { "engine": { … },
7
+ // "ai": { "schema": 1, "checked_on": "2026-11-25",
8
+ // "providers": { "anthropic": { "default": "claude-opus-5-5",
9
+ // "models": [{ "id": "claude-opus-5-5", "label": "Claude Opus 5.5",
10
+ // "input": 4, "output": 20, "status": "preview" }] } } } }
11
+ //
12
+ // L'engine ne va jamais sur internet : poad start écrit le catalogue dans poad/data/ai/catalog.json (monté en
13
+ // /data), que le service ai valide à son tour ; sans fichier, la table de l'engine sert. Cache de 6 h dans
14
+ // ~/.poad/ai-catalog.json ; hors ligne, le dernier catalogue connu.
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+
19
+ const PERMALINK_URL = 'https://raw.githubusercontent.com/poadio/permalink/main/poad.json';
20
+ const SCHEMA = 1;
21
+ const CACHE_TTL = 6 * 3600 * 1000;
22
+ const PROVIDERS = ['anthropic', 'openai', 'mistral', 'gemini'];
23
+ const MODEL_ID_RE = /^[A-Za-z0-9._:-]{1,100}$/;
24
+ const STATUSES = ['preview', 'deprecated'];
25
+
26
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
27
+ const priceOk = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0 && n < 100000;
28
+
29
+ /**
30
+ * Catalogue validé tiré de la clé « ai » de poad.json, mêmes règles que l'engine (services/ai/src/catalog.ts) :
31
+ * { catalog, warnings } ; catalog null si le schéma est inconnu ou si aucun fournisseur n'est utilisable.
32
+ */
33
+ const parseCatalog = (raw) => {
34
+ const warnings = [];
35
+ if (!isObj(raw)) return { catalog: null, warnings: ['no "ai" key in poad.json'] };
36
+ if (raw.schema !== SCHEMA) return { catalog: null, warnings: [`AI catalog schema ${JSON.stringify(raw.schema)} is not supported by this CLI (expected ${SCHEMA}): update poad`] };
37
+ if (!isObj(raw.providers)) return { catalog: null, warnings: ['AI catalog: providers must be an object'] };
38
+ const providers = {};
39
+ for (const [p, v] of Object.entries(raw.providers)) {
40
+ if (!PROVIDERS.includes(p)) {
41
+ warnings.push(`unknown provider "${p.slice(0, 40)}" ignored`);
42
+ continue;
43
+ }
44
+ if (!isObj(v) || !Array.isArray(v.models) || typeof v.default !== 'string') {
45
+ warnings.push(`${p}: { default, models } expected, ignored`);
46
+ continue;
47
+ }
48
+ const models = [];
49
+ for (const m of v.models.slice(0, 200)) {
50
+ if (!isObj(m) || typeof m.id !== 'string' || !MODEL_ID_RE.test(m.id) || !priceOk(m.input) || !priceOk(m.output)) {
51
+ warnings.push(`${p}: a model without a valid id, input or output is ignored`);
52
+ continue;
53
+ }
54
+ if (m.status !== undefined && !STATUSES.includes(m.status)) {
55
+ warnings.push(`${p}/${m.id}: status must be preview or deprecated, ignored`);
56
+ continue;
57
+ }
58
+ if (models.some((x) => x.id === m.id)) continue;
59
+ const label = typeof m.label === 'string' && m.label.trim() ? m.label.trim().slice(0, 80) : m.id;
60
+ models.push({ id: m.id, label, input: m.input, output: m.output, ...(m.status ? { status: m.status } : {}) });
61
+ }
62
+ if (!models.some((m) => m.id === v.default)) {
63
+ warnings.push(`${p}: default "${String(v.default).slice(0, 80)}" is not in its models, ignored`);
64
+ continue;
65
+ }
66
+ providers[p] = { default: v.default, models };
67
+ }
68
+ if (!Object.keys(providers).length) return { catalog: null, warnings: [...warnings, 'AI catalog: no usable provider'] };
69
+ const checked = typeof raw.checked_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(raw.checked_on) ? raw.checked_on : null;
70
+ return { catalog: { schema: SCHEMA, checked_on: checked, providers }, warnings };
71
+ };
72
+
73
+ const cacheFile = () => process.env.POAD_AI_CATALOG_CACHE || path.join(os.homedir(), '.poad', 'ai-catalog.json');
74
+
75
+ const readCache = () => {
76
+ try {
77
+ const c = JSON.parse(fs.readFileSync(cacheFile(), 'utf8'));
78
+ return c && typeof c.at === 'number' && c.catalog ? c : null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ };
83
+
84
+ const writeCache = (catalog) => {
85
+ try {
86
+ fs.mkdirSync(path.dirname(cacheFile()), { recursive: true, mode: 0o700 });
87
+ fs.writeFileSync(cacheFile(), JSON.stringify({ at: Date.now(), catalog }));
88
+ } catch {
89
+ // cache facultatif
90
+ }
91
+ };
92
+
93
+ /** Corps de poad.json, ou null (hors ligne, illisible) */
94
+ const fetchPermalink = async (timeout) => {
95
+ try {
96
+ const res = await fetch(PERMALINK_URL, { signal: AbortSignal.timeout(timeout), headers: { 'cache-control': 'no-cache' } });
97
+ return res.ok ? await res.json() : null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ };
102
+
103
+ /**
104
+ * { catalog, source, fetched_at, warnings } ; source : permalink (lu à l'instant), cache, ou none (rien de
105
+ * connu : l'engine prendra sa table). fresh : ignorer le cache récent. fetcher : pour les essais.
106
+ */
107
+ const loadCatalog = async ({ fresh = false, timeout = 2500, fetcher = fetchPermalink } = {}) => {
108
+ const cached = readCache();
109
+ if (!fresh && cached && Date.now() - cached.at < CACHE_TTL) return { catalog: cached.catalog, source: 'cache', fetched_at: new Date(cached.at).toISOString(), warnings: [] };
110
+ const body = await fetcher(timeout);
111
+ if (body) {
112
+ const { catalog, warnings } = parseCatalog(isObj(body) ? body.ai : null);
113
+ if (catalog) {
114
+ writeCache(catalog);
115
+ return { catalog, source: 'permalink', fetched_at: new Date().toISOString(), warnings };
116
+ }
117
+ if (cached) return { catalog: cached.catalog, source: 'cache', fetched_at: new Date(cached.at).toISOString(), warnings };
118
+ return { catalog: null, source: 'none', fetched_at: null, warnings };
119
+ }
120
+ if (cached) return { catalog: cached.catalog, source: 'cache', fetched_at: new Date(cached.at).toISOString(), warnings: [] };
121
+ return { catalog: null, source: 'none', fetched_at: null, warnings: [] };
122
+ };
123
+
124
+ /** poad/data/ai/catalog.json du projet (monté en /data/ai/catalog.json dans l'engine) */
125
+ const engineFile = (root) => path.join(path.dirname(root), 'data', 'ai', 'catalog.json');
126
+
127
+ /**
128
+ * Écrit le catalogue pour l'engine (remplacement atomique), ou retire le fichier s'il n'y a pas de catalogue :
129
+ * l'engine prend alors sa table. Rend le chemin écrit, ou null.
130
+ */
131
+ const writeForEngine = (root, loaded) => {
132
+ const file = engineFile(root);
133
+ if (!loaded || !loaded.catalog) {
134
+ try {
135
+ fs.unlinkSync(file);
136
+ } catch {
137
+ // rien à retirer
138
+ }
139
+ return null;
140
+ }
141
+ fs.mkdirSync(path.dirname(file), { recursive: true });
142
+ const tmp = `${file}.${process.pid}.tmp`;
143
+ fs.writeFileSync(tmp, `${JSON.stringify({ ...loaded.catalog, fetched_at: loaded.fetched_at }, null, 2)}\n`);
144
+ fs.renameSync(tmp, file);
145
+ return file;
146
+ };
147
+
148
+ module.exports = { PERMALINK_URL, SCHEMA, parseCatalog, loadCatalog, writeForEngine, engineFile, cacheFile };
package/utils/ai.js ADDED
@@ -0,0 +1,178 @@
1
+ // Socle IA (engine 0.30.0+, /ai/v1) : clés des fournisseurs et réglages [ai].
2
+ //
3
+ // Clés de la machine : ~/.poad/ai.json (dossier 0700, fichier 0600), écrit seulement par le CLI
4
+ // (poad ai login|logout). Une clé n'est jamais lue sur la ligne de commande (elle finirait dans l'historique du
5
+ // shell), jamais affichée : seulement ses 4 derniers caractères. L'engine ne lit jamais ce fichier : la clé d'un
6
+ // projet est copiée dans ses Credentials (coffre de la base) par poad ai use <fournisseur>.
7
+ //
8
+ // Réglages du projet, poad/config.toml (passés à l'engine par poad start, en variables POAD_AI_*) :
9
+ // [ai]
10
+ // default_provider = "anthropic" anthropic | openai | mistral | gemini
11
+ // default_model = "claude-opus-5-5" modèle du fournisseur par défaut
12
+ // max_tokens = 4096 max_tokens par défaut et plafond par requête
13
+ // monthly_budget_usd = 20 plafond mensuel estimé (dollars US) ; absent : aucun
14
+ // log_content = false true : extrait masqué des messages dans les lignes du puits
15
+ // [ai.models] (engine 0.31.0+) modèle par défaut de chaque fournisseur, pris parmi
16
+ // anthropic = "claude-sonnet-5-5" le catalogue (poad ai models) ; un choix fait dans l'écran IA de la
17
+ // console passe avant (base de l'engine)
18
+ // [ai.prices] prix du projet, en dollars par million de jetons
19
+ // "openai/gpt-5" = { input = 1.25, output = 10 }
20
+ const fs = require('fs');
21
+ const os = require('os');
22
+ const path = require('path');
23
+
24
+ const PROVIDERS = ['anthropic', 'openai', 'mistral', 'gemini'];
25
+ const LABELS = { anthropic: 'Anthropic (Claude)', openai: 'OpenAI (GPT)', mistral: 'Mistral AI', gemini: 'Google Gemini' };
26
+
27
+ /** ~/.poad/ai.json (POAD_AI_KEYS_FILE pour les essais) */
28
+ const keysFile = () => process.env.POAD_AI_KEYS_FILE || path.join(os.homedir(), '.poad', 'ai.json');
29
+
30
+ /** Fin de clé à montrer : …abcd (rien de plus, et rien du tout pour une clé trop courte) */
31
+ const mask = (key) => (key && String(key).length >= 12 ? `…${String(key).slice(-4)}` : key ? '…' : '');
32
+
33
+ const isProvider = (p) => PROVIDERS.includes(p);
34
+
35
+ /**
36
+ * Clés de la machine : { providers: { anthropic: { key, added_at } } }. Un fichier lisible par d'autres est
37
+ * ramené à 0600 (fixed : true). Absent ou illisible : aucune clé (broken : la raison, sans contenu).
38
+ */
39
+ const readKeys = (file = keysFile()) => {
40
+ const out = { providers: {}, fixed: false, broken: null };
41
+ let st;
42
+ try {
43
+ st = fs.statSync(file);
44
+ } catch {
45
+ return out;
46
+ }
47
+ if (process.platform !== 'win32' && (st.mode & 0o077) !== 0) {
48
+ fs.chmodSync(file, 0o600);
49
+ out.fixed = true;
50
+ }
51
+ try {
52
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
53
+ for (const p of PROVIDERS) {
54
+ const e = doc && doc.providers && doc.providers[p];
55
+ if (e && typeof e.key === 'string' && e.key) out.providers[p] = { key: e.key, added_at: typeof e.added_at === 'string' ? e.added_at : null };
56
+ }
57
+ } catch {
58
+ out.broken = `${file} is not valid JSON`;
59
+ }
60
+ return out;
61
+ };
62
+
63
+ /** Écrit les clés : dossier 0700, fichier 0600, remplacement atomique */
64
+ const writeKeys = (providers, file = keysFile()) => {
65
+ const dir = path.dirname(file);
66
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
67
+ // Un dossier déjà là (~/.poad créé par une autre commande, en 0755) est ramené à 0700 ; ses autres fichiers ne changent pas
68
+ if (process.platform !== 'win32' && (fs.statSync(dir).mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
69
+ const tmp = path.join(dir, `.ai.json.${process.pid}.tmp`);
70
+ const doc = { version: 1, note: 'AI provider keys of this machine, written by "poad ai login". Never read by the engine.', providers };
71
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, { mode: 0o600 });
72
+ fs.chmodSync(tmp, 0o600);
73
+ fs.renameSync(tmp, file);
74
+ };
75
+
76
+ /** Forme plausible d'une clé (rien de plus : le fournisseur seul sait si elle vaut) ; null ou la raison */
77
+ const keyProblem = (key) => {
78
+ if (!key) return 'empty key';
79
+ if (/\s/.test(key)) return 'a key has no spaces';
80
+ if (key.length < 8 || key.length > 512) return 'a key has 8 to 512 characters';
81
+ if (!/^[\x21-\x7e]+$/.test(key)) return 'a key is plain ASCII';
82
+ return null;
83
+ };
84
+
85
+ /** Toute l'entrée standard (clé passée par un tube : echo "$KEY" | poad ai login openai) */
86
+ const readStdin = () =>
87
+ new Promise((resolve, reject) => {
88
+ let data = '';
89
+ process.stdin.setEncoding('utf8');
90
+ process.stdin.on('data', (c) => {
91
+ data += c;
92
+ if (data.length > 4096) reject(new Error('too much input on stdin'));
93
+ });
94
+ process.stdin.on('end', () => resolve(data));
95
+ process.stdin.on('error', reject);
96
+ });
97
+
98
+ /** La clé : invite masquée dans un terminal, sinon l'entrée standard. Jamais un argument. */
99
+ const readSecret = async (message) => {
100
+ if (process.stdin.isTTY) {
101
+ const { password } = require('@inquirer/prompts');
102
+ return String(await password({ message, mask: false })).trim();
103
+ }
104
+ return String(await readStdin()).trim();
105
+ };
106
+
107
+ // --- Réglages [ai] de config.toml -------------------------------------------------
108
+
109
+ const MODEL_RE = /^[A-Za-z0-9._:/-]{1,100}$/;
110
+
111
+ /**
112
+ * Variables de l'engine tirées de [ai] ; warnings : ce qui est écarté (affiché par poad start). Une valeur
113
+ * refusée n'est pas transmise (l'engine applique son défaut).
114
+ */
115
+ const engineEnv = (config) => {
116
+ const ai = (config && config.ai) || {};
117
+ const env = [];
118
+ const warnings = [];
119
+ if (ai.default_provider !== undefined) {
120
+ if (isProvider(String(ai.default_provider))) env.push(`POAD_AI_DEFAULT_PROVIDER=${ai.default_provider}`);
121
+ else warnings.push(`[ai] default_provider = "${String(ai.default_provider).slice(0, 32)}" in poad/config.toml: ${PROVIDERS.join(', ')}. Ignored.`);
122
+ }
123
+ if (ai.default_model !== undefined) {
124
+ if (MODEL_RE.test(String(ai.default_model))) env.push(`POAD_AI_DEFAULT_MODEL=${ai.default_model}`);
125
+ else warnings.push('[ai] default_model in poad/config.toml is not a model id. Ignored.');
126
+ }
127
+ if (ai.max_tokens !== undefined) {
128
+ const n = Number(ai.max_tokens);
129
+ if (Number.isInteger(n) && n >= 1 && n <= 200000) env.push(`POAD_AI_MAX_TOKENS=${n}`);
130
+ else warnings.push('[ai] max_tokens in poad/config.toml: an integer from 1 to 200000. Ignored (4096).');
131
+ }
132
+ if (ai.monthly_budget_usd !== undefined) {
133
+ const n = Number(ai.monthly_budget_usd);
134
+ if (Number.isFinite(n) && n >= 0) env.push(`POAD_AI_MONTHLY_BUDGET_USD=${n}`);
135
+ else warnings.push('[ai] monthly_budget_usd in poad/config.toml is not a number of dollars. Ignored: no budget cap.');
136
+ }
137
+ if (ai.log_content !== undefined) env.push(`POAD_AI_LOG_CONTENT=${ai.log_content === true ? 'true' : 'false'}`);
138
+ if (ai.models !== undefined) {
139
+ if (ai.models && typeof ai.models === 'object' && !Array.isArray(ai.models)) {
140
+ const ok = {};
141
+ for (const [p, m] of Object.entries(ai.models)) {
142
+ if (!isProvider(p)) warnings.push(`[ai.models] in poad/config.toml: unknown provider "${String(p).slice(0, 32)}" (${PROVIDERS.join(', ')}). Ignored.`);
143
+ else if (typeof m !== 'string' || !/^[A-Za-z0-9._:-]{1,100}$/.test(m)) warnings.push(`[ai.models] ${p} in poad/config.toml is not a model id. Ignored.`);
144
+ else ok[p] = m;
145
+ }
146
+ if (Object.keys(ok).length) env.push(`POAD_AI_MODELS=${JSON.stringify(ok)}`);
147
+ } else warnings.push('[ai.models] in poad/config.toml must be a table provider = "model". Ignored.');
148
+ }
149
+ if (ai.prices !== undefined) {
150
+ if (ai.prices && typeof ai.prices === 'object' && !Array.isArray(ai.prices)) env.push(`POAD_AI_PRICES=${JSON.stringify(ai.prices)}`);
151
+ else warnings.push('[ai.prices] in poad/config.toml must be a table "provider/model" = { input, output }. Ignored.');
152
+ }
153
+ return { env, warnings };
154
+ };
155
+
156
+ /** Engine 0.30.0 et plus : /ai/v1 et les credentials anthropic, openai, mistral, gemini */
157
+ const supportsAi = (config) => {
158
+ const [major, minor] = String((config && config.engine) || '').split('.').map(Number);
159
+ return major > 0 || (major === 0 && minor >= 30);
160
+ };
161
+
162
+ /**
163
+ * Coût estimé en dollars, 4 décimales, préfixé : « ~$0.0002 », et « < $0.0001 » pour un coût positif plus
164
+ * petit (un appel payé ne s'affiche jamais « 0.0000 »). Sans coût (null) : null.
165
+ */
166
+ const usdText = (n) => {
167
+ if (n === null || n === undefined) return null;
168
+ const v = Number(n) || 0;
169
+ return v > 0 && v < 0.0001 ? '< $0.0001' : `~$${v.toFixed(4)}`;
170
+ };
171
+
172
+ /** Engine 0.31.0 et plus : catalogue des modèles (/data/ai/catalog.json) et [ai.models] */
173
+ const supportsAiModels = (config) => {
174
+ const [major, minor] = String((config && config.engine) || '').split('.').map(Number);
175
+ return major > 0 || (major === 0 && minor >= 31);
176
+ };
177
+
178
+ module.exports = { supportsAiModels, PROVIDERS, LABELS, keysFile, mask, isProvider, readKeys, writeKeys, keyProblem, readSecret, engineEnv, supportsAi, usdText };
@@ -0,0 +1,70 @@
1
+ // Services du projet que la console locale montre (groupe « Services » de son
2
+ // rail, cartes de l'accueil). L'engine ne connaît pas les ports de la machine :
3
+ // le CLI écrit la liste dans poad/data/console/services.json (monté en /data
4
+ // dans l'engine, relu par meta à chaque affichage de la console, engine 0.29.2+).
5
+ //
6
+ // Seuls les services activés dans config.toml y figurent :
7
+ // - db : PostgreSQL de l'engine, toujours (port de la machine) ;
8
+ // - mail : Mailpit, sauf si [smtp] désigne un vrai serveur ;
9
+ // - keycloak : [keycloak] a un port (choisi au premier poad run kc) ou
10
+ // shared = true (port du Keycloak partagé de la machine) ;
11
+ // - valkey : [valkey] a un port.
12
+ // Qu'ils tournent ou non : la console sonde et indique la commande qui les
13
+ // lance. Jamais de secret dans ce fichier : le mot de passe admin de Keycloak
14
+ // reste dans data/keycloak (users.json, ou shared-admin.json pour le partagé),
15
+ // meta ne le lit qu'à la demande de la console locale (bouton copier).
16
+ //
17
+ // Réécrit à poad start, poad run et poad setup ; un échec n'arrête rien.
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ const file = (root) => path.join(path.dirname(root), 'data', 'console', 'services.json');
22
+
23
+ const validPort = (p) => Number.isInteger(Number(p)) && Number(p) > 0 && Number(p) < 65536;
24
+
25
+ /** [{ id, url }] des services activés (config lue de config.toml) */
26
+ const list = (root, config) => {
27
+ const mail = require('./mail');
28
+ const kc = require('./keycloak');
29
+ const shared = require('./keycloak-shared');
30
+ const valkey = require('./valkey');
31
+ const out = [];
32
+ if (config.db && validPort(config.db.port)) out.push({ id: 'db', port: Number(config.db.port) });
33
+ if (mail.usesMailpit(config) && validPort(mail.mailPort(config))) out.push({ id: 'mail', url: `http://localhost:${Number(mail.mailPort(config))}/`, smtp: `${mail.MAIL_ALIAS}:1025` });
34
+ const kcService = require('./services').SERVICES.find((s) => s.id === 'keycloak');
35
+ if (kcService.configured(config)) {
36
+ const port = shared.isShared(config) ? (shared.readState() || {}).port : config.keycloak.port;
37
+ if (validPort(port)) {
38
+ // La console d'administration ouverte sur le realm du projet (le compte
39
+ // admin est celui du realm master : poad info --secrets)
40
+ let realm;
41
+ try {
42
+ const project = kc.loadProject(root, config, { create: false });
43
+ realm = kc.runningRealm(config, project ? project.realm : kc.realmName(config));
44
+ } catch {
45
+ realm = null;
46
+ }
47
+ const base = `http://localhost:${Number(port)}/admin/master/console/`;
48
+ out.push({ id: 'keycloak', url: realm ? `${base}#/${encodeURIComponent(realm)}` : base, ...(realm ? { realm } : {}), shared: shared.isShared(config) });
49
+ }
50
+ }
51
+ if (valkey.enabled(config) && validPort(config.valkey.port)) out.push({ id: 'valkey', port: Number(config.valkey.port), engine_url: valkey.URL });
52
+ return out;
53
+ };
54
+
55
+ /** Écrit la liste (remplacement atomique) ; renvoie la liste, ou null en cas d'échec */
56
+ const write = (root, config = require('./config').loadConfig(root)) => {
57
+ try {
58
+ const services = list(root, config);
59
+ const target = file(root);
60
+ fs.mkdirSync(path.dirname(target), { recursive: true });
61
+ const tmp = `${target}.${process.pid}.tmp`;
62
+ fs.writeFileSync(tmp, JSON.stringify(services, null, 2) + '\n', { mode: 0o644 });
63
+ fs.renameSync(tmp, target);
64
+ return services;
65
+ } catch {
66
+ return null;
67
+ }
68
+ };
69
+
70
+ module.exports = { file, list, write };
package/utils/keycloak.js CHANGED
@@ -332,6 +332,47 @@ const enableUserAttributes = async (port, secrets, realm) => {
332
332
  if (!res.ok) throw new Error(`user profile: ${res.status}`);
333
333
  };
334
334
 
335
+ /**
336
+ * Connexion qui dure à la console d'administration (Keycloak local, développement
337
+ * seulement) : sessions SSO du realm master de 30 jours et case « Se souvenir de
338
+ * moi ». Après une première connexion (case cochée), le lien de la console poad
339
+ * ouvre l'administration déjà connecté, tant que ce Keycloak tourne.
340
+ */
341
+ const LONG_SESSION = 30 * 24 * 3600;
342
+ const MASTER_SESSIONS = {
343
+ rememberMe: true,
344
+ ssoSessionIdleTimeout: LONG_SESSION,
345
+ ssoSessionMaxLifespan: LONG_SESSION,
346
+ ssoSessionIdleTimeoutRememberMe: LONG_SESSION,
347
+ ssoSessionMaxLifespanRememberMe: LONG_SESSION,
348
+ };
349
+ const longAdminSessions = async (port, secrets) => {
350
+ const token = await adminToken(port, secrets);
351
+ const url = `http://localhost:${port}/admin/realms/master`;
352
+ const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
353
+ const realm = await (await fetch(url, { headers })).json();
354
+ if (Object.entries(MASTER_SESSIONS).every(([k, v]) => realm[k] === v)) return false;
355
+ const res = await fetch(url, { method: 'PUT', headers, body: JSON.stringify(MASTER_SESSIONS) });
356
+ if (!res.ok) throw new Error(`master realm sessions: ${res.status}`);
357
+ return true;
358
+ };
359
+
360
+ /**
361
+ * Keycloak partagé : son mot de passe d'administration (rangé pour la machine
362
+ * dans ~/.poad) est recopié dans data/keycloak/shared-admin.json du projet,
363
+ * comme celui d'un Keycloak propre au projet l'est dans data/keycloak/users.json
364
+ * (data/ n'est jamais versionné). meta l'y lit à la demande du bouton « copier »
365
+ * de la console locale. Retiré quand le projet lâche le Keycloak partagé.
366
+ */
367
+ const sharedAdminFile = (root) => path.join(dataDir(root), 'shared-admin.json');
368
+ const writeSharedAdmin = (root, password) => {
369
+ fs.mkdirSync(dataDir(root), { recursive: true });
370
+ const file = sharedAdminFile(root);
371
+ fs.writeFileSync(file, JSON.stringify({ admin_password: password }) + '\n', { mode: 0o600 });
372
+ fs.chmodSync(file, 0o600);
373
+ };
374
+ const removeSharedAdmin = (root) => fs.rmSync(sharedAdminFile(root), { force: true });
375
+
335
376
  /**
336
377
  * Reprise : avant de recréer un Keycloak qui tourne, garde les identifiants de
337
378
  * ses utilisateurs qui n'en ont pas encore dans les secrets (projets antérieurs,
@@ -460,6 +501,11 @@ module.exports = {
460
501
  readRunningRealm,
461
502
  adoptRunningIds,
462
503
  enableUserAttributes,
504
+ longAdminSessions,
505
+ MASTER_SESSIONS,
506
+ sharedAdminFile,
507
+ writeSharedAdmin,
508
+ removeSharedAdmin,
463
509
  exportRealm,
464
510
  assertCanRegister,
465
511
  register,