poad 2.11.0 → 2.13.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,136 @@
1
+ // Configuration d'un projet poad, en deux fichiers :
2
+ // poad/config.toml versionné : ports, engine, services… aucun secret
3
+ // poad/secrets.toml propre à la machine, hors git : secret JWT et clés
4
+ // (anon, service_role, admin) signées avec lui
5
+ //
6
+ // loadConfig() fusionne les deux : le reste du CLI lit config.auth.secret,
7
+ // config.auth.anon… comme avant. Un ancien config.toml qui contient encore
8
+ // les secrets est migré à la première lecture ; un projet cloné sans
9
+ // secrets.toml en reçoit de nouveaux.
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const toml = require('toml');
13
+
14
+ const SECRET_KEYS = ['secret', 'anon', 'service', 'admin'];
15
+
16
+ const GITIGNORE = `# Généré par poad : propre à chaque machine, jamais versionné
17
+ data/
18
+ secrets.toml
19
+ `;
20
+
21
+ const poadDir = (root) => path.dirname(root);
22
+ const secretsFile = (root) => path.join(poadDir(root), 'secrets.toml');
23
+
24
+ /** Nouveau secret JWT et clés signées avec lui */
25
+ function generateSecrets() {
26
+ const jwt = require('jsonwebtoken');
27
+ const { generateSecret } = require('./jwtkey');
28
+ const secret = generateSecret();
29
+ return {
30
+ secret,
31
+ anon: jwt.sign({ role: 'anon', iss: 'poad' }, secret),
32
+ service: jwt.sign({ role: 'service_role', iss: 'poad' }, secret),
33
+ admin: jwt.sign({ role: 'admin', iss: 'poad' }, secret),
34
+ };
35
+ }
36
+
37
+ /** Écrit (ou complète) la section [auth] de secrets.toml, en mode 600 */
38
+ function writeSecrets(root, auth) {
39
+ const { setKeys } = require('./tomlfile');
40
+ const file = secretsFile(root);
41
+ if (!fs.existsSync(file)) fs.writeFileSync(file, '# Secrets du projet poad local : hors git (poad/.gitignore)\n', { mode: 0o600 });
42
+ setKeys(file, 'auth', Object.fromEntries(SECRET_KEYS.map((k) => [k, auth[k]])), { mode: 0o600 });
43
+ }
44
+
45
+ /** Mot de passe SMTP : dans secrets.toml ([smtp] pass), null le retire */
46
+ function writeSmtpPass(root, pass) {
47
+ const { setKeys, removeSection } = require('./tomlfile');
48
+ const file = secretsFile(root);
49
+ if (pass === null || pass === undefined) return removeSection(file, 'smtp');
50
+ if (!fs.existsSync(file)) fs.writeFileSync(file, '# Secrets du projet poad local : hors git (poad/.gitignore)\n', { mode: 0o600 });
51
+ setKeys(file, 'smtp', { pass }, { mode: 0o600 });
52
+ }
53
+
54
+ /** poad/.gitignore : data/ et secrets.toml (complète un fichier existant) */
55
+ function ensureGitignore(root) {
56
+ const file = path.join(poadDir(root), '.gitignore');
57
+ if (!fs.existsSync(file)) return fs.writeFileSync(file, GITIGNORE);
58
+ const text = fs.readFileSync(file, 'utf-8');
59
+ const missing = ['data/', 'secrets.toml'].filter((l) => !text.split(/\r?\n/).includes(l));
60
+ if (missing.length) fs.writeFileSync(file, `${text.replace(/\s*$/, '')}\n${missing.join('\n')}\n`);
61
+ }
62
+
63
+ /** Retire les lignes secrètes de la section [auth] du texte de config.toml */
64
+ function stripSecrets(text) {
65
+ const lines = text.split(/\r?\n/);
66
+ let section = '';
67
+ const kept = lines.filter((line) => {
68
+ const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
69
+ if (head) section = head[1].trim();
70
+ const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
71
+ if (section === 'auth') return !(key && SECRET_KEYS.includes(key[1]));
72
+ if (section === 'smtp') return !(key && key[1] === 'pass');
73
+ return true;
74
+ });
75
+ return kept.join('\n');
76
+ }
77
+
78
+ /**
79
+ * Lit config.toml et secrets.toml, migre ou crée les secrets si besoin.
80
+ * Renvoie la configuration fusionnée ; notices : ce qui a été fait (à afficher).
81
+ */
82
+ function loadConfig(root, notices = []) {
83
+ const text = fs.readFileSync(root, 'utf-8');
84
+ const config = toml.parse(text);
85
+ const auth = config.auth || {};
86
+ const inline = SECRET_KEYS.filter((k) => auth[k] !== undefined);
87
+ let secrets = null;
88
+
89
+ let stored = {};
90
+ if (fs.existsSync(secretsFile(root))) {
91
+ stored = toml.parse(fs.readFileSync(secretsFile(root), 'utf-8'));
92
+ secrets = stored.auth || {};
93
+ }
94
+ // Mot de passe SMTP écrit dans config.toml : il rejoint secrets.toml
95
+ const inlinePass = config.smtp && config.smtp.pass !== undefined ? String(config.smtp.pass) : null;
96
+ if (inlinePass !== null) {
97
+ writeSmtpPass(root, inlinePass);
98
+ stored.smtp = { ...(stored.smtp || {}), pass: inlinePass };
99
+ if (!inline.length) {
100
+ fs.writeFileSync(root, stripSecrets(text));
101
+ ensureGitignore(root);
102
+ notices.push(`SMTP password moved from config.toml to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
103
+ }
104
+ }
105
+ if (inline.length) {
106
+ // Ancien format : les secrets de config.toml priment (ce sont ceux que
107
+ // l'engine et les fronts utilisent déjà), puis on les sort du fichier.
108
+ secrets = { ...(secrets || {}), ...Object.fromEntries(inline.map((k) => [k, auth[k]])) };
109
+ writeSecrets(root, secrets);
110
+ fs.writeFileSync(root, stripSecrets(text));
111
+ ensureGitignore(root);
112
+ notices.push(`Secrets moved from config.toml to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
113
+ } else if (!secrets || SECRET_KEYS.some((k) => !secrets[k])) {
114
+ secrets = generateSecrets();
115
+ writeSecrets(root, secrets);
116
+ ensureGitignore(root);
117
+ notices.push(`New project secrets written to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
118
+ }
119
+
120
+ config.auth = { ...auth, ...Object.fromEntries(SECRET_KEYS.map((k) => [k, secrets[k]])) };
121
+ if (config.smtp && stored.smtp && stored.smtp.pass !== undefined) config.smtp.pass = String(stored.smtp.pass);
122
+ return config;
123
+ }
124
+
125
+ /** loadConfig + affichage des notices */
126
+ function readConfig(root) {
127
+ const notices = [];
128
+ const config = loadConfig(root, notices);
129
+ if (notices.length) {
130
+ const chalk = require('chalk-v2');
131
+ for (const n of notices) console.log(chalk.grey(` ${n}`));
132
+ }
133
+ return config;
134
+ }
135
+
136
+ module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, writeSmtpPass, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
@@ -0,0 +1,40 @@
1
+ // Application des migrations avec affichage, partagée par poad migrate et poad start
2
+ const path = require('path');
3
+
4
+ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
5
+ const chalk = require('chalk-v2');
6
+ const migrations = require('./migrations');
7
+ const rel = (p) => path.relative(process.cwd(), p);
8
+
9
+ let result;
10
+ try {
11
+ result = await migrations.migrate(root, config, {
12
+ onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
13
+ });
14
+ } catch (err) {
15
+ console.log(chalk.redBright(`Migrations not applied: ${err.message}`));
16
+ return false;
17
+ }
18
+ const { applied, failed, state } = result;
19
+
20
+ for (const m of state.changed) {
21
+ console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
22
+ }
23
+ for (const r of state.missing) {
24
+ console.log(chalk.yellowBright(` ${r.version}_${r.name}.sql was applied but is no longer in ${rel(migrations.dir(root))}.`));
25
+ }
26
+ for (const f of state.ignored) {
27
+ console.log(chalk.grey(` ${f} ignored: migration files are named <YYYYMMDDHHMMSS>_<name>.sql`));
28
+ }
29
+ if (failed) {
30
+ console.log(`${chalk.redBright('✖')} ${chalk.bold(failed.migration.file)}`);
31
+ console.log(chalk.redBright(` ${failed.message}`));
32
+ console.log(chalk.grey(' Rolled back: fix the file, then "poad migrate".'));
33
+ const left = state.pending.length - applied.length - 1;
34
+ if (left > 0) console.log(chalk.grey(` ${left} later migration(s) not attempted.`));
35
+ return false;
36
+ }
37
+ if (applied.length) console.log(chalk.bold(` ${applied.length} migration(s) applied.`));
38
+ else if (!quietWhenNone) console.log(chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
39
+ return true;
40
+ };
@@ -0,0 +1,189 @@
1
+ // Migrations du schéma de la base : poad/migrations/<AAAAMMJJHHMMSS>_<nom>.sql
2
+ //
3
+ // - appliquées dans l'ordre des noms, chacune dans sa transaction, avec son
4
+ // inscription dans poad_migrations.history (version, nom, empreinte) ;
5
+ // - une migration déjà appliquée n'est jamais rejouée : si son fichier a
6
+ // changé depuis, on le signale (écrivez plutôt une nouvelle migration) ;
7
+ // - un verrou consultatif évite deux applications simultanées.
8
+ //
9
+ // Le CLI se connecte à la base du projet local (port [db] de config.toml).
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const crypto = require('crypto');
13
+
14
+ const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]+)\.sql$/;
15
+ const LOCK_ID = 7_340_201; // pg_advisory_lock : propre aux migrations poad
16
+
17
+ const dir = (root) => path.join(path.dirname(root), 'migrations');
18
+
19
+ const checksum = (sql) => crypto.createHash('sha256').update(sql).digest('hex');
20
+
21
+ /** Fichiers de migration du projet, triés ; les autres fichiers sont ignorés */
22
+ function files(root) {
23
+ const d = dir(root);
24
+ if (!fs.existsSync(d)) return { list: [], ignored: [] };
25
+ const names = fs.readdirSync(d).filter((f) => !f.startsWith('.')).sort();
26
+ const list = [];
27
+ const ignored = [];
28
+ for (const file of names) {
29
+ const m = FILE_RE.exec(file);
30
+ if (!m) {
31
+ ignored.push(file);
32
+ continue;
33
+ }
34
+ const sql = fs.readFileSync(path.join(d, file), 'utf-8');
35
+ list.push({ version: m[1], name: m[2], file, path: path.join(d, file), sql, checksum: checksum(sql) });
36
+ }
37
+ return { list, ignored };
38
+ }
39
+
40
+ /** Horodatage UTC AAAAMMJJHHMMSS */
41
+ function timestamp(date = new Date()) {
42
+ return date.toISOString().replace(/[-:T]/g, '').slice(0, 14);
43
+ }
44
+
45
+ /** Crée poad/migrations/<horodatage>_<nom>.sql ; renvoie son chemin */
46
+ function create(root, name) {
47
+ const slug = String(name || '')
48
+ .normalize('NFD')
49
+ .replace(/[̀-ͯ]/g, '')
50
+ .replace(/[^A-Za-z0-9_-]+/g, '_')
51
+ .replace(/^_+|_+$/g, '')
52
+ .toLowerCase();
53
+ if (!slug) throw new Error('a migration needs a name: poad migration new <name>');
54
+ fs.mkdirSync(dir(root), { recursive: true });
55
+ let version = timestamp();
56
+ // Deux migrations créées dans la même seconde : la seconde passe après
57
+ while (files(root).list.some((m) => m.version === version)) version = String(Number(version) + 1);
58
+ const file = path.join(dir(root), `${version}_${slug}.sql`);
59
+ fs.writeFileSync(
60
+ file,
61
+ `-- ${slug}\n-- Appliquée une seule fois, dans une transaction, par "poad migrate" (ou poad start).\n-- Une fois appliquée, ne la modifiez plus : écrivez une nouvelle migration.\n\n`
62
+ );
63
+ return file;
64
+ }
65
+
66
+ async function connect(config) {
67
+ const { Client } = require('pg');
68
+ const client = new Client({
69
+ host: '127.0.0.1',
70
+ port: Number(config.db.port),
71
+ user: 'postgres',
72
+ password: 'postgres',
73
+ database: 'postgres',
74
+ connectionTimeoutMillis: 5000,
75
+ application_name: 'poad-cli',
76
+ });
77
+ await client.connect();
78
+ client.on('error', () => {}); // fermeture de la connexion par le serveur
79
+ return client;
80
+ }
81
+
82
+ async function ensureHistory(client) {
83
+ await client.query(`
84
+ create schema if not exists poad_migrations;
85
+ create table if not exists poad_migrations.history (
86
+ version text primary key,
87
+ name text not null,
88
+ checksum text not null,
89
+ applied_at timestamptz not null default now()
90
+ );
91
+ revoke all on schema poad_migrations from public;
92
+ `);
93
+ }
94
+
95
+ /** État : appliquées, en attente, modifiées après application, absentes du dossier */
96
+ async function status(root, client) {
97
+ const { list, ignored } = files(root);
98
+ await ensureHistory(client);
99
+ const { rows } = await client.query('select version, name, checksum, applied_at from poad_migrations.history order by version');
100
+ const applied = new Map(rows.map((r) => [r.version, r]));
101
+ const local = new Set(list.map((m) => m.version));
102
+ return {
103
+ list: list.map((m) => {
104
+ const row = applied.get(m.version);
105
+ return { ...m, applied: row ? row.applied_at : null, changed: Boolean(row && row.checksum !== m.checksum) };
106
+ }),
107
+ pending: list.filter((m) => !applied.has(m.version)),
108
+ changed: list.filter((m) => applied.has(m.version) && applied.get(m.version).checksum !== m.checksum),
109
+ missing: rows.filter((r) => !local.has(r.version)),
110
+ ignored,
111
+ };
112
+ }
113
+
114
+ /** Ligne et colonne d'une position (1-based) dans le texte */
115
+ function lineOf(sql, position) {
116
+ const before = sql.slice(0, Math.max(0, Number(position) - 1));
117
+ const line = before.split('\n').length;
118
+ return line;
119
+ }
120
+
121
+ /**
122
+ * Applique les migrations en attente. S'arrête à la première erreur (sa
123
+ * transaction est annulée, les suivantes ne sont pas tentées).
124
+ * Renvoie { applied: [...], failed: { migration, message } | null, state }.
125
+ */
126
+ async function migrate(root, config, { onApply } = {}) {
127
+ const client = await connect(config);
128
+ const applied = [];
129
+ try {
130
+ await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
131
+ const state = await status(root, client);
132
+ for (const m of state.pending) {
133
+ try {
134
+ await client.query('begin');
135
+ await client.query(m.sql);
136
+ await client.query('insert into poad_migrations.history (version, name, checksum) values ($1, $2, $3)', [m.version, m.name, m.checksum]);
137
+ await client.query('commit');
138
+ applied.push(m);
139
+ if (onApply) onApply(m);
140
+ } catch (err) {
141
+ await client.query('rollback').catch(() => {});
142
+ const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
143
+ return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
144
+ }
145
+ }
146
+ return { applied, failed: null, state };
147
+ } finally {
148
+ await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
149
+ await client.end().catch(() => {});
150
+ }
151
+ }
152
+
153
+ /** Attend que la base accepte les connexions (démarrage de l'engine) */
154
+ async function waitForDb(config, seconds = 90) {
155
+ for (let i = 0; i < seconds; i++) {
156
+ try {
157
+ const client = await connect(config);
158
+ await client.query('select 1');
159
+ await client.end();
160
+ return true;
161
+ } catch {
162
+ await new Promise((r) => setTimeout(r, 1000));
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+
168
+ /**
169
+ * Attend que les services de l'engine aient créé leurs schémas (auth,
170
+ * storage) : une migration peut y écrire (buckets, politiques).
171
+ */
172
+ async function waitForServices(config, seconds = 90) {
173
+ const base = `http://localhost:${config.web.port}`;
174
+ const ok = (url, headers) => fetch(url, { headers }).then((r) => r.ok, () => false);
175
+ for (let i = 0; i < seconds; i++) {
176
+ const [auth, storage] = await Promise.all([
177
+ ok(`${base}/auth/v1/settings`, { apikey: config.auth.anon }),
178
+ ok(`${base}/storage/v1/status`, { apikey: config.auth.anon }),
179
+ ]);
180
+ if (auth && storage) return true;
181
+ await new Promise((r) => setTimeout(r, 1000));
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /** Les migrations s'appliquent-elles à poad start ? ([db] auto_migrate, vrai par défaut) */
187
+ const autoMigrate = (config) => !(config.db && config.db.auto_migrate === false);
188
+
189
+ module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, FILE_RE };
@@ -0,0 +1,95 @@
1
+ // Affichage de l'état du projet, commun à poad info et poad start : le projet
2
+ // (URL, base, clés, migrations), puis le panneau des services (Mailpit,
3
+ // Keycloak, Valkey) avec leur état et leurs accès.
4
+ const path = require('path');
5
+
6
+ async function migrationsLine(root, config) {
7
+ const migrations = require('./migrations');
8
+ const count = migrations.files(root).list.length;
9
+ if (!count) return null;
10
+ let client;
11
+ try {
12
+ client = await migrations.connect(config);
13
+ const st = await migrations.status(root, client);
14
+ const done = st.list.length - st.pending.length;
15
+ return `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
16
+ } catch {
17
+ return `${count} file(s), state unknown`;
18
+ } finally {
19
+ if (client) await client.end().catch(() => {});
20
+ }
21
+ }
22
+
23
+ async function printProject(root, config) {
24
+ const chalk = require('chalk-v2');
25
+ const prettyoutput = require('prettyoutput');
26
+ const { storageInfo } = require('./engine');
27
+ const mail = require('./mail');
28
+ console.log(chalk.bold('POAD project'));
29
+ console.log(' ');
30
+ const info = {
31
+ Engine: config.engine,
32
+ 'API URL': `http://localhost:${config.web.port}`,
33
+ 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
34
+ ...storageInfo(config),
35
+ ...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
36
+ 'JWT secret': `${config.auth.secret}`,
37
+ 'anon key': config.auth.anon,
38
+ 'service_role key': config.auth.service,
39
+ Config: `${path.relative(process.cwd(), root)} (secrets: ${path.relative(process.cwd(), require('./config').secretsFile(root))})`,
40
+ };
41
+ const line = await migrationsLine(root, config);
42
+ if (line) info.Migrations = line;
43
+ console.log(prettyoutput(info));
44
+ }
45
+
46
+ async function printServices(root, config) {
47
+ const chalk = require('chalk-v2');
48
+ const Docker = require('dockerode');
49
+ const docker = new Docker();
50
+ const { SERVICES, containerState } = require('./services');
51
+
52
+ // En cours, arrêtés (configurés), ou disponibles
53
+ const rows = [];
54
+ for (const s of SERVICES) {
55
+ const configured = s.configured(config);
56
+ if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
57
+ const state = configured ? await containerState(docker, s.container(config)) : null;
58
+ rows.push({ s, configured, running: state === 'running', auto: configured && s.optional && s.autostart(config) });
59
+ }
60
+ if (!rows.length) return;
61
+
62
+ const width = Math.max(...rows.map((r) => r.s.label.length));
63
+ const rule = chalk.grey('─'.repeat(48));
64
+ console.log(chalk.bold('Services'));
65
+ console.log(rule);
66
+ for (const { s, configured, running, auto } of rows) {
67
+ const label = chalk.bold(s.label.padEnd(width));
68
+ const tag = auto ? chalk.cyan(' auto') : '';
69
+ if (running) {
70
+ console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}${tag}`);
71
+ for (const [k, v] of Object.entries(s.info(config, root))) {
72
+ // Une liste (comptes de test) : une ligne par entrée, alignées
73
+ const lines = Array.isArray(v) ? v : [v];
74
+ lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
75
+ }
76
+ } else if (configured) {
77
+ const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
78
+ console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')}${tag} ${chalk.grey(`(${how})`)}`);
79
+ } else {
80
+ console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}, or poad setup`)}`);
81
+ }
82
+ }
83
+ console.log(rule);
84
+ const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
85
+ if (stopped) console.log(chalk.grey(' "poad run --all" starts every configured service; "poad setup" chooses those started with the project.'));
86
+ console.log(' ');
87
+ }
88
+
89
+ /** Projet puis services */
90
+ async function printReport(root, config) {
91
+ await printProject(root, config);
92
+ await printServices(root, config);
93
+ }
94
+
95
+ module.exports = { printReport, printProject, printServices, migrationsLine };
package/utils/services.js CHANGED
@@ -4,6 +4,8 @@
4
4
  // - Valkey : optionnel, `poad run valkey`.
5
5
  // Un service optionnel est « configuré » quand config.toml a sa section (port
6
6
  // choisi au premier lancement) : `poad run --all` relance ceux-là.
7
+ // Avec autostart = true dans sa section, `poad start` le lance aussi
8
+ // (`poad setup` règle ces options).
7
9
 
8
10
  const kc = require('./keycloak');
9
11
  const valkey = require('./valkey');
@@ -18,6 +20,7 @@ const SERVICES = [
18
20
  optional: false,
19
21
  container: (config) => mail.mailContainerName(config),
20
22
  configured: (config) => mail.usesMailpit(config),
23
+ autostart: (config) => mail.usesMailpit(config),
21
24
  info: (config) => ({ URL: `http://localhost:${mail.mailPort(config)}`, SMTP: 'mail:1025 (depuis l’engine)' }),
22
25
  },
23
26
  {
@@ -26,8 +29,11 @@ const SERVICES = [
26
29
  optional: true,
27
30
  names: kc.NAMES,
28
31
  cmd: 'kc',
32
+ section: 'keycloak',
29
33
  container: (config) => kc.containerName(config),
30
34
  configured: (config) => Boolean(config.keycloak && config.keycloak.port),
35
+ autostart: (config) => Boolean(config.keycloak && config.keycloak.autostart === true),
36
+ savePort: (root, port) => kc.savePort(root, port),
31
37
  info: (config, root) => {
32
38
  const base = `http://localhost:${config.keycloak.port}`;
33
39
  // Lecture seule : rien n'est créé tant que `poad run kc` n'a pas tourné
@@ -55,8 +61,11 @@ const SERVICES = [
55
61
  optional: true,
56
62
  names: valkey.NAMES,
57
63
  cmd: 'valkey',
64
+ section: 'valkey',
58
65
  container: (config) => valkey.containerName(config),
59
66
  configured: (config) => valkey.enabled(config),
67
+ autostart: (config) => Boolean(config.valkey && config.valkey.autostart === true),
68
+ savePort: (root, port) => valkey.savePort(root, port),
60
69
  info: (config) => ({ URL: `redis://127.0.0.1:${config.valkey.port}`, 'From the engine': valkey.URL }),
61
70
  },
62
71
  ];
@@ -77,4 +86,7 @@ const wantedServices = (args = {}) => SERVICES.filter((s) => s.optional && s.nam
77
86
  /** --all, all : tous les services optionnels configurés */
78
87
  const wantsAll = (args = {}) => Boolean(args.all || args['--all'] || args['-a']);
79
88
 
80
- module.exports = { SERVICES, containerState, wantedServices, wantsAll };
89
+ /** Services optionnels que poad start lance (autostart = true) */
90
+ const autostartServices = (config) => SERVICES.filter((s) => s.optional && s.configured(config) && s.autostart(config));
91
+
92
+ module.exports = { SERVICES, containerState, wantedServices, wantsAll, autostartServices };
@@ -0,0 +1,72 @@
1
+ // Modifications ciblées d'un fichier TOML simple (config.toml, secrets.toml) :
2
+ // le texte est modifié ligne à ligne, les commentaires et l'ordre restent.
3
+ // Valeurs : chaîne, nombre, booléen ; null retire la clé.
4
+ const fs = require('fs');
5
+
6
+ const format = (v) => (typeof v === 'string' ? JSON.stringify(v) : String(v));
7
+
8
+ /** Bornes [début, fin) des lignes de la section (début = ligne d'en-tête), ou null */
9
+ function sectionRange(lines, section) {
10
+ const head = lines.findIndex((l) => new RegExp(`^\\s*\\[${section.replace(/\./g, '\\.')}\\]\\s*$`).test(l));
11
+ if (head < 0) return null;
12
+ let end = head + 1;
13
+ while (end < lines.length && !/^\s*\[[^\]]+\]\s*$/.test(lines[end])) end++;
14
+ return [head, end];
15
+ }
16
+
17
+ /** Applique { clé: valeur | null } à la section (créée au besoin) d'un texte TOML */
18
+ function setInText(text, section, values) {
19
+ const lines = text.replace(/\s*$/, '').split(/\r?\n/);
20
+ let range = sectionRange(lines, section);
21
+ const entries = Object.entries(values);
22
+ if (!range) {
23
+ const add = entries.filter(([, v]) => v !== null && v !== undefined);
24
+ if (!add.length) return text;
25
+ if (lines.length && lines[lines.length - 1].trim()) lines.push('');
26
+ lines.push(`[${section}]`, ...add.map(([k, v]) => `${k} = ${format(v)}`));
27
+ return lines.join('\n') + '\n';
28
+ }
29
+ for (const [key, value] of entries) {
30
+ range = sectionRange(lines, section);
31
+ const at = lines.slice(range[0] + 1, range[1]).findIndex((l) => new RegExp(`^\\s*${key}\\s*=`).test(l));
32
+ const index = at < 0 ? -1 : range[0] + 1 + at;
33
+ if (value === null || value === undefined) {
34
+ if (index >= 0) lines.splice(index, 1);
35
+ } else if (index >= 0) {
36
+ lines[index] = `${key} = ${format(value)}`;
37
+ } else {
38
+ // Après la dernière ligne non vide de la section
39
+ let insert = range[1];
40
+ while (insert > range[0] + 1 && !lines[insert - 1].trim()) insert--;
41
+ lines.splice(insert, 0, `${key} = ${format(value)}`);
42
+ }
43
+ }
44
+ return lines.join('\n') + '\n';
45
+ }
46
+
47
+ /** Retire une section entière */
48
+ function removeSectionInText(text, section) {
49
+ const lines = text.split(/\r?\n/);
50
+ const range = sectionRange(lines, section);
51
+ if (!range) return text;
52
+ lines.splice(range[0], range[1] - range[0]);
53
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\s*$/, '') + '\n';
54
+ }
55
+
56
+ function setKeys(file, section, values, { mode } = {}) {
57
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : '';
58
+ const updated = setInText(text, section, values);
59
+ if (updated !== text) fs.writeFileSync(file, updated, mode ? { mode } : undefined);
60
+ if (mode) fs.chmodSync(file, mode);
61
+ return updated !== text;
62
+ }
63
+
64
+ function removeSection(file, section) {
65
+ if (!fs.existsSync(file)) return false;
66
+ const text = fs.readFileSync(file, 'utf-8');
67
+ const updated = removeSectionInText(text, section);
68
+ if (updated !== text) fs.writeFileSync(file, updated);
69
+ return updated !== text;
70
+ }
71
+
72
+ module.exports = { setKeys, removeSection, setInText, removeSectionInText };