poad 2.12.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.
package/global/start.js CHANGED
@@ -1,5 +1,8 @@
1
- // poad start démarre le projet (engine + Mailpit)
2
- // poad start --all puis tous les services optionnels configurés (Keycloak, Valkey…)
1
+ // poad start démarre le projet (engine + Mailpit), applique les
2
+ // migrations, lance les services en autostart (poad setup),
3
+ // puis affiche l'état complet (comme poad info)
4
+ // poad start --all tous les services configurés, autostart ou non
5
+ // poad start --bare l'engine et Mailpit seulement, cette fois-ci
3
6
  module.exports = async (args = {}) => {
4
7
  const chalk = require('chalk-v2');
5
8
  const Docker = require('dockerode');
@@ -20,12 +23,21 @@ module.exports = async (args = {}) => {
20
23
  const config = require('../utils/config').readConfig(root);
21
24
  const containerName = config.project_uuid;
22
25
  console.log(' ');
23
- const { wantsAll } = require('../utils/services');
26
+ const { wantsAll, SERVICES, autostartServices } = require('../utils/services');
24
27
  const all = wantsAll(args);
28
+ const bare = Boolean(args.bare || args['--bare']);
29
+
30
+ // Services optionnels à lancer, puis l'état complet du projet
31
+ const finish = async () => {
32
+ const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config);
33
+ if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
34
+ console.log(' ');
35
+ await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root));
36
+ };
37
+
25
38
  if (await isDockerExist(containerName)) {
26
39
  console.log(chalk.bold('Container already started'));
27
- if (all) await require('./run')({ all: true });
28
- return;
40
+ return finish();
29
41
  }
30
42
  config.engine = await offerEngineUpgrade(root, config, args);
31
43
  const image = 'poadio/engine:' + config.engine;
@@ -83,23 +95,6 @@ module.exports = async (args = {}) => {
83
95
  return;
84
96
  }
85
97
  progress.succeed(chalk.bold('containers started.'));
86
- if (!all && valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
87
- console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
88
- }
89
- console.log(' ');
90
- console.log(chalk.bold(' 🚀 Container started successfully'));
91
- console.log(' ');
92
- const info = {
93
- 'API URL': `http://localhost:${config.web.port}`,
94
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
95
- ...storageInfo(config),
96
- ...(mailpit ? { 'Mail URL': `http://localhost:${mail.mailPort(config)}` } : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
97
- 'JWT secret': `${config.auth.secret}`,
98
- 'anon key': config.auth.anon,
99
- 'service_role key': config.auth.service,
100
- };
101
- console.log(prettyoutput(info));
102
-
103
98
  // Migrations en attente de poad/migrations ([db] auto_migrate = false pour
104
99
  // les appliquer à la main avec poad migrate)
105
100
  const migrations = require('../utils/migrations');
@@ -116,8 +111,7 @@ module.exports = async (args = {}) => {
116
111
  await require('../utils/migrate-run')(root, config, { quietWhenNone: false });
117
112
  }
118
113
  }
119
- console.log(' ');
120
114
  }
121
115
 
122
- if (all) await require('./run')({ all: true });
116
+ await finish();
123
117
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.12.0",
3
+ "version": "2.13.0",
4
4
  "engine": "0.7.1",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
@@ -8,9 +8,10 @@
8
8
  "poad": "./poad.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "yarn clean && yarn"
11
+ "build": "bun install"
12
12
  },
13
13
  "dependencies": {
14
+ "@inquirer/prompts": "^8.8.0",
14
15
  "axios": "^1.7.7",
15
16
  "boxen": "^5.1.2",
16
17
  "chalk-v2": "^1.0.2",
@@ -26,5 +27,6 @@
26
27
  "pg": "8.16.3",
27
28
  "prettyoutput": "^1.2.0",
28
29
  "toml": "^3.0.0"
29
- }
30
+ },
31
+ "packageManager": "bun@1.4.4"
30
32
  }
package/project/cli.js CHANGED
@@ -9,6 +9,7 @@
9
9
  module.exports = {
10
10
  info: `Information about your project`,
11
11
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
12
+ setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, --all, --none, --list)',
12
13
  migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
13
14
  migration: 'Database migrations: migration new <name>, migration list',
14
15
  /* status: `[AI] Vérification du statut de l'environnement`,
package/project/info.js CHANGED
@@ -1,84 +1,16 @@
1
- // poad info : le projet (URL, base, clés), puis un panneau à part pour les
2
- // services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
1
+ // poad info : le projet (URL, base, clés, migrations), puis un panneau à part
2
+ // pour les services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
3
+ // poad start affiche la même chose à la fin du démarrage.
3
4
  module.exports = async () => {
4
5
  const chalk = require('chalk-v2');
5
- const toml = require('toml');
6
- const fs = require('fs').promises;
7
- const Docker = require('dockerode');
8
- const docker = new Docker();
9
- const prettyoutput = require('prettyoutput');
10
6
  const { findPoadDir } = require('../utils/findpoad');
11
7
  const { isDockerExist } = require('../utils/docker');
12
- const { storageInfo } = require('../utils/engine');
13
- const { SERVICES, containerState } = require('../utils/services');
14
8
  const root = findPoadDir(process.cwd());
15
9
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
16
10
  const config = require('../utils/config').readConfig(root);
17
11
  console.log(' ');
18
12
  if (!(await isDockerExist(config.project_uuid))) {
19
- return console.log(chalk.redBright('Container not found'));
13
+ return console.log(chalk.redBright('The project is not started: "poad start".'));
20
14
  }
21
- console.log(chalk.bold('POAD project info'));
22
- console.log(' ');
23
- const info = {
24
- Engine: config.engine,
25
- 'API URL': `http://localhost:${config.web.port}`,
26
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
27
- ...storageInfo(config),
28
- ...(config.smtp && config.smtp.host ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` } : {}),
29
- 'JWT secret': `${config.auth.secret}`,
30
- 'anon key': config.auth.anon,
31
- 'service_role key': config.auth.service,
32
- };
33
- // Migrations : appliquées / en attente (poad/migrations)
34
- const migrations = require('../utils/migrations');
35
- if (migrations.files(root).list.length) {
36
- let client;
37
- try {
38
- client = await migrations.connect(config);
39
- const st = await migrations.status(root, client);
40
- const done = st.list.length - st.pending.length;
41
- info.Migrations = `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
42
- } catch {
43
- info.Migrations = `${migrations.files(root).list.length} file(s), state unknown`;
44
- } finally {
45
- if (client) await client.end().catch(() => {});
46
- }
47
- }
48
- console.log(prettyoutput(info));
49
-
50
- // Panneau des services : en cours, arrêtés (configurés), ou disponibles
51
- const rows = [];
52
- for (const s of SERVICES) {
53
- const configured = s.configured(config);
54
- if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
55
- const state = configured ? await containerState(docker, s.container(config)) : null;
56
- rows.push({ s, configured, running: state === 'running' });
57
- }
58
- if (!rows.length) return;
59
-
60
- const width = Math.max(...rows.map((r) => r.s.label.length));
61
- const line = chalk.grey('─'.repeat(48));
62
- console.log(chalk.bold('Services'));
63
- console.log(line);
64
- for (const { s, configured, running } of rows) {
65
- const label = chalk.bold(s.label.padEnd(width));
66
- if (running) {
67
- console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}`);
68
- for (const [k, v] of Object.entries(s.info(config, root))) {
69
- // Une liste (comptes de test) : une ligne par entrée, alignées
70
- const lines = Array.isArray(v) ? v : [v];
71
- lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
72
- }
73
- } else if (configured) {
74
- const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
75
- console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')} ${chalk.grey(`(${how})`)}`);
76
- } else {
77
- console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}`)}`);
78
- }
79
- }
80
- console.log(line);
81
- const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
82
- if (stopped) console.log(chalk.grey(` "poad run --all" starts every configured service.`));
83
- console.log(' ');
15
+ await require('../utils/report').printReport(root, config);
84
16
  };
@@ -0,0 +1,241 @@
1
+ // poad setup : ce que "poad start" lance avec le projet
2
+ //
3
+ // poad setup interactif (terminal) : e-mails, services, migrations
4
+ // poad setup kc=on valkey=off non interactif : ne change que ce qui est cité
5
+ // poad setup --all | --none tous les services optionnels en autostart, ou aucun
6
+ // poad setup mail=smtp smtp.host=smtp.example.com smtp.port=587 smtp.user=apikey smtp.pass=…
7
+ // poad setup mail=mailpit revient à Mailpit (e-mails capturés en local)
8
+ // poad setup migrate=off migrations appliquées à la main (poad migrate)
9
+ // poad setup --list affiche les réglages sans rien changer
10
+ //
11
+ // Tout va dans poad/config.toml, sauf le mot de passe SMTP (poad/secrets.toml).
12
+ // Désactiver un service ne retire que son autostart : port, données et jeu de
13
+ // test restent, le réactiver ne coûte rien.
14
+ module.exports = async (args = {}) => {
15
+ const chalk = require('chalk-v2');
16
+ const Docker = require('dockerode');
17
+ const docker = new Docker();
18
+ const { findPoadDir } = require('../utils/findpoad');
19
+ const { isDockerExist } = require('../utils/docker');
20
+ const { findFreePorts } = require('../utils/ports');
21
+ const { setKeys, removeSection } = require('../utils/tomlfile');
22
+ const { loadConfig, readConfig, writeSmtpPass } = require('../utils/config');
23
+ const { SERVICES, containerState } = require('../utils/services');
24
+ const mail = require('../utils/mail');
25
+ const migrations = require('../utils/migrations');
26
+
27
+ const root = findPoadDir(process.cwd());
28
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
29
+ let config = readConfig(root);
30
+ const optional = SERVICES.filter((s) => s.optional);
31
+ console.log(' ');
32
+
33
+ // ------------------------------------------------------------ lecture
34
+ const ALIASES = { kc: 'keycloak', keycloak: 'keycloak', valkey: 'valkey', redis: 'valkey' };
35
+ const ON = new Set(['on', 'true', 'yes', 'oui', '1', 'auto']);
36
+ const OFF = new Set(['off', 'false', 'no', 'non', '0', 'manual']);
37
+ const flag = (v) => {
38
+ const t = String(v).toLowerCase();
39
+ if (ON.has(t)) return true;
40
+ if (OFF.has(t)) return false;
41
+ return null;
42
+ };
43
+ const has = (k) => args[k] || args[`--${k}`];
44
+
45
+ const current = () => ({
46
+ mail: mail.usesMailpit(config) ? 'mailpit' : 'smtp',
47
+ smtp: { ...(config.smtp || {}) },
48
+ services: Object.fromEntries(optional.map((s) => [s.id, s.configured(config) && s.autostart(config)])),
49
+ migrate: migrations.autoMigrate(config),
50
+ });
51
+
52
+ const summary = () => {
53
+ const c = current();
54
+ const pad = (s) => chalk.bold(s.padEnd(11));
55
+ console.log(chalk.bold('Started with "poad start"'));
56
+ console.log(chalk.grey('─'.repeat(48)));
57
+ console.log(` ${pad('E-mails')} ${c.mail === 'mailpit' ? `Mailpit ${chalk.grey(`(local, http://localhost:${mail.mailPort(config)})`)}` : `SMTP ${c.smtp.host}:${c.smtp.port || 587}${c.smtp.user ? chalk.grey(` (${c.smtp.user})`) : ''}`}`);
58
+ for (const s of optional) {
59
+ const state = c.services[s.id]
60
+ ? chalk.greenBright('auto')
61
+ : s.configured(config)
62
+ ? `${chalk.yellowBright('manual')} ${chalk.grey(`(poad run ${s.cmd})`)}`
63
+ : chalk.grey('off');
64
+ console.log(` ${pad(s.label)} ${state}`);
65
+ }
66
+ console.log(` ${pad('Migrations')} ${c.migrate ? chalk.greenBright('applied at start') : `${chalk.yellowBright('manual')} ${chalk.grey('(poad migrate)')}`}`);
67
+ console.log(chalk.grey('─'.repeat(48)));
68
+ };
69
+
70
+ if (has('list')) {
71
+ summary();
72
+ return console.log(' ');
73
+ }
74
+
75
+ // ------------------------------------------------------------ souhaits
76
+ const before = current();
77
+ const wasConfigured = Object.fromEntries(optional.map((s) => [s.id, s.configured(config)]));
78
+ const wish = { services: {} };
79
+ const keys = Object.keys(args).filter((k) => !/^-/.test(k));
80
+
81
+ if (has('all')) for (const s of optional) wish.services[s.id] = true;
82
+ if (has('none')) for (const s of optional) wish.services[s.id] = false;
83
+ for (const k of keys) {
84
+ const v = args[k];
85
+ if (ALIASES[k]) {
86
+ const f = flag(v);
87
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
88
+ wish.services[ALIASES[k]] = f;
89
+ } else if (k === 'mail') {
90
+ if (!['mailpit', 'smtp'].includes(String(v))) return console.log(chalk.redBright('mail=mailpit or mail=smtp.'));
91
+ wish.mail = String(v);
92
+ } else if (k.startsWith('smtp.')) {
93
+ (wish.smtp ??= {})[k.slice(5)] = v;
94
+ } else if (k === 'migrate' || k === 'migrations') {
95
+ const f = flag(v);
96
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
97
+ wish.migrate = f;
98
+ } else if (!['all', 'none', 'list'].includes(k)) {
99
+ return console.log(chalk.redBright(`Unknown setting "${k}". See: poad setup --help`));
100
+ }
101
+ }
102
+ if (wish.smtp && !wish.mail) wish.mail = 'smtp';
103
+
104
+ const interactive = !keys.length && !has('all') && !has('none');
105
+ if (interactive) {
106
+ if (!process.stdin.isTTY) {
107
+ summary();
108
+ console.log(chalk.grey(' Not a terminal: pass settings, e.g. "poad setup kc=on valkey=off", "--all", "--none", "mail=smtp smtp.host=…".'));
109
+ return console.log(' ');
110
+ }
111
+ const { select, checkbox, input, password, confirm } = require('@inquirer/prompts');
112
+ try {
113
+ console.log(chalk.bold('Services started with "poad start"'));
114
+ console.log(' ');
115
+ wish.mail = await select({
116
+ message: 'E-mails (sign up, magic links, password reset)',
117
+ default: before.mail,
118
+ choices: [
119
+ { name: 'Mailpit: captured locally, read them in the browser', value: 'mailpit' },
120
+ { name: 'SMTP server: real delivery', value: 'smtp' },
121
+ ],
122
+ });
123
+ if (wish.mail === 'smtp') {
124
+ const s = before.smtp;
125
+ wish.smtp = {};
126
+ wish.smtp.host = await input({ message: 'SMTP host', default: s.host, required: true });
127
+ wish.smtp.port = Number(await input({ message: 'SMTP port', default: String(s.port || 587), validate: (v) => /^\d+$/.test(v) || 'a port number' }));
128
+ wish.smtp.user = await input({ message: 'SMTP user (empty: none)', default: s.user || '' });
129
+ const pass = await password({ message: s.pass ? 'SMTP password (empty: keep the current one)' : 'SMTP password (empty: none)', mask: '*' });
130
+ if (pass) wish.smtp.pass = pass;
131
+ wish.smtp.sender = await input({ message: 'Sender address', default: s.sender || 'no-reply@poad.local' });
132
+ wish.smtp.secure = await confirm({ message: 'TLS from the start (port 465)?', default: Boolean(s.secure) || wish.smtp.port === 465 });
133
+ }
134
+ const picked = await checkbox({
135
+ message: 'Started with the project (space to toggle, enter to confirm)',
136
+ choices: [
137
+ ...optional.map((s) => ({
138
+ name: s.id === 'keycloak' ? 'Keycloak: OIDC provider with test users (poad/keycloak.json)' : 'Valkey: Redis compatible cache (REDIS_URL of the engine)',
139
+ value: s.id,
140
+ checked: before.services[s.id],
141
+ })),
142
+ { name: 'Migrations: apply poad/migrations at start', value: '_migrate', checked: before.migrate },
143
+ ],
144
+ });
145
+ for (const s of optional) wish.services[s.id] = picked.includes(s.id);
146
+ wish.migrate = picked.includes('_migrate');
147
+ console.log(' ');
148
+ } catch (err) {
149
+ // Ctrl+C dans un prompt
150
+ if (err && err.name === 'ExitPromptError') return console.log(chalk.grey(' Nothing changed.'));
151
+ throw err;
152
+ }
153
+ }
154
+
155
+ // ------------------------------------------------------------ écriture
156
+ const changes = [];
157
+ for (const [id, on] of Object.entries(wish.services)) {
158
+ const s = optional.find((x) => x.id === id);
159
+ if (on === before.services[id]) continue;
160
+ if (on && !s.configured(config)) {
161
+ const [port] = await findFreePorts(1);
162
+ s.savePort(root, port);
163
+ }
164
+ if (on || s.configured(config)) setKeys(root, s.section, { autostart: on });
165
+ changes.push(`${s.label}: ${on ? 'started with the project' : 'manual (poad run ' + s.cmd + ')'}`);
166
+ config = loadConfig(root);
167
+ }
168
+
169
+ let mailChanged = false;
170
+ if (wish.mail === 'smtp') {
171
+ const next = { ...before.smtp, ...(wish.smtp || {}) };
172
+ if (!next.host) return console.log(chalk.redBright('mail=smtp needs smtp.host=…'));
173
+ const { pass, ...visible } = next;
174
+ const fields = {
175
+ host: String(visible.host),
176
+ port: Number(visible.port || 587),
177
+ user: visible.user ? String(visible.user) : null,
178
+ sender: visible.sender ? String(visible.sender) : null,
179
+ secure: visible.secure === true || visible.secure === 'true' ? true : null,
180
+ };
181
+ setKeys(root, 'smtp', fields);
182
+ if (wish.smtp && wish.smtp.pass !== undefined) writeSmtpPass(root, String(wish.smtp.pass));
183
+ const was = before.mail === 'smtp' ? JSON.stringify({ ...before.smtp, pass: undefined }) : '';
184
+ mailChanged = before.mail !== 'smtp' || was !== JSON.stringify({ ...next, pass: undefined }) || (wish.smtp && wish.smtp.pass !== undefined);
185
+ if (mailChanged) changes.push(`E-mails: SMTP ${fields.host}:${fields.port}`);
186
+ } else if (wish.mail === 'mailpit' && before.mail === 'smtp') {
187
+ removeSection(root, 'smtp');
188
+ writeSmtpPass(root, null);
189
+ if (!mail.mailPort(loadConfig(root))) {
190
+ const [port] = await findFreePorts(1);
191
+ setKeys(root, 'mail', { port });
192
+ }
193
+ mailChanged = true;
194
+ changes.push('E-mails: Mailpit');
195
+ }
196
+
197
+ if (wish.migrate !== undefined && wish.migrate !== before.migrate) {
198
+ setKeys(root, 'db', { auto_migrate: wish.migrate ? null : false });
199
+ changes.push(`Migrations: ${wish.migrate ? 'applied at start' : 'manual (poad migrate)'}`);
200
+ }
201
+
202
+ config = loadConfig(root);
203
+ if (!changes.length) {
204
+ summary();
205
+ console.log(chalk.grey(' Nothing changed.'));
206
+ return console.log(' ');
207
+ }
208
+ for (const c of changes) console.log(`${chalk.greenBright('✔')} ${c}`);
209
+ console.log(' ');
210
+ summary();
211
+
212
+ // ------------------------------------------------------------ projet lancé
213
+ if (await isDockerExist(config.project_uuid)) {
214
+ // REDIS_URL n'est donné à l'engine que si Valkey était configuré à son démarrage
215
+ const valkeyNew = wish.services.valkey === true && !wasConfigured.valkey;
216
+ if (mailChanged || valkeyNew) {
217
+ console.log(chalk.yellowBright(' The engine reads its mail and Valkey settings at start: "poad stop" then "poad start" to apply them.'));
218
+ }
219
+ const missing = [];
220
+ for (const s of optional) {
221
+ if (wish.services[s.id] && (await containerState(docker, s.container(config))) !== 'running') missing.push(s);
222
+ }
223
+ if (missing.length) {
224
+ let go = !interactive;
225
+ if (interactive) {
226
+ const { confirm } = require('@inquirer/prompts');
227
+ go = await confirm({ message: `Start ${missing.map((s) => s.label).join(' and ')} now?`, default: true }).catch(() => false);
228
+ }
229
+ if (go) {
230
+ await require('../global/run')({ services: missing.map((s) => s.id), quiet: true });
231
+ console.log(' ');
232
+ await require('../utils/report').printServices(root, loadConfig(root));
233
+ return;
234
+ }
235
+ console.log(chalk.grey(' Applied at the next "poad start" (or "poad run --all").'));
236
+ }
237
+ } else {
238
+ console.log(chalk.grey(' Applied at the next "poad start".'));
239
+ }
240
+ console.log(' ');
241
+ };
package/utils/config.js CHANGED
@@ -34,11 +34,21 @@ function generateSecrets() {
34
34
  };
35
35
  }
36
36
 
37
+ /** Écrit (ou complète) la section [auth] de secrets.toml, en mode 600 */
37
38
  function writeSecrets(root, auth) {
38
- const lines = ['# Secrets du projet poad local : hors git (poad/.gitignore)', '[auth]'];
39
- for (const k of SECRET_KEYS) lines.push(`${k} = ${JSON.stringify(auth[k])}`);
40
- fs.writeFileSync(secretsFile(root), lines.join('\n') + '\n', { mode: 0o600 });
41
- fs.chmodSync(secretsFile(root), 0o600);
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 });
42
52
  }
43
53
 
44
54
  /** poad/.gitignore : data/ et secrets.toml (complète un fichier existant) */
@@ -57,9 +67,10 @@ function stripSecrets(text) {
57
67
  const kept = lines.filter((line) => {
58
68
  const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
59
69
  if (head) section = head[1].trim();
60
- if (section !== 'auth') return true;
61
70
  const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
62
- return !(key && SECRET_KEYS.includes(key[1]));
71
+ if (section === 'auth') return !(key && SECRET_KEYS.includes(key[1]));
72
+ if (section === 'smtp') return !(key && key[1] === 'pass');
73
+ return true;
63
74
  });
64
75
  return kept.join('\n');
65
76
  }
@@ -75,8 +86,21 @@ function loadConfig(root, notices = []) {
75
86
  const inline = SECRET_KEYS.filter((k) => auth[k] !== undefined);
76
87
  let secrets = null;
77
88
 
89
+ let stored = {};
78
90
  if (fs.existsSync(secretsFile(root))) {
79
- secrets = (toml.parse(fs.readFileSync(secretsFile(root), 'utf-8')).auth || {});
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
+ }
80
104
  }
81
105
  if (inline.length) {
82
106
  // Ancien format : les secrets de config.toml priment (ce sont ceux que
@@ -94,6 +118,7 @@ function loadConfig(root, notices = []) {
94
118
  }
95
119
 
96
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);
97
122
  return config;
98
123
  }
99
124
 
@@ -108,4 +133,4 @@ function readConfig(root) {
108
133
  return config;
109
134
  }
110
135
 
111
- module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
136
+ module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, writeSmtpPass, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
@@ -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 };