poad 2.7.1 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/global/cli.js CHANGED
@@ -9,6 +9,7 @@
9
9
  module.exports = {
10
10
  install: `Install poad environment`,
11
11
  init: `Init poad project`,
12
- start: 'Start container for poad local development',
13
- stop: 'Stop container for poad local development',
12
+ start: 'Start container for poad local development (start --all: and every configured service)',
13
+ stop: 'Stop container for poad local development (stop kc|valkey: that service only)',
14
+ run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, --all)',
14
15
  };
package/global/init.js CHANGED
@@ -31,7 +31,8 @@ module.exports = async (args) => {
31
31
  config.web = {
32
32
  port: ports[1],
33
33
  };
34
- config.inbucket = {
34
+ // Interface web de Mailpit (e-mails du projet local)
35
+ config.mail = {
35
36
  port: ports[2],
36
37
  };
37
38
  const key = generateSecret();
package/global/run.js ADDED
@@ -0,0 +1,226 @@
1
+ // poad run <service> : démarre un service optionnel à côté du projet.
2
+ // poad run keycloak | kc Keycloak local, déclaré comme fournisseur OIDC
3
+ // poad run valkey | redis Valkey local (REDIS_URL de l'engine)
4
+ // poad run --all | all le projet s'il est arrêté, puis tous les services
5
+ // optionnels configurés dans config.toml
6
+ module.exports = async (args = {}) => {
7
+ const chalk = require('chalk-v2');
8
+ const Docker = require('dockerode');
9
+ const docker = new Docker();
10
+ const toml = require('toml');
11
+ const ora = require('ora');
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const prettyoutput = require('prettyoutput');
15
+ const { findPoadDir } = require('../utils/findpoad');
16
+ const { isDockerExist } = require('../utils/docker');
17
+ const { findFreePorts } = require('../utils/ports');
18
+ const { pullIfMissing } = require('../utils/pull');
19
+ const kc = require('../utils/keycloak');
20
+ const mail = require('../utils/mail');
21
+ const valkey = require('../utils/valkey');
22
+ const { SERVICES, containerState, wantedServices, wantsAll } = require('../utils/services');
23
+
24
+ const all = wantsAll(args);
25
+ const wanted = wantedServices(args);
26
+
27
+ console.log(' ');
28
+ if (!all && !wanted.length) {
29
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
30
+ console.log(' ');
31
+ console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
32
+ console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
33
+ console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
34
+ console.log(' ');
35
+ return;
36
+ }
37
+
38
+ const root = findPoadDir(process.cwd());
39
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
40
+ const readConfig = () => toml.parse(fs.readFileSync(root, 'utf-8'));
41
+ let config = readConfig();
42
+
43
+ if (!(await isDockerExist(config.project_uuid))) {
44
+ if (!all) return console.log(chalk.redBright('The project is not started: run "poad start" first (or "poad run --all").'));
45
+ // --all : le projet d'abord, puis ses services
46
+ await require('./start')({});
47
+ if (!(await isDockerExist(config.project_uuid))) return;
48
+ console.log(' ');
49
+ config = readConfig();
50
+ }
51
+
52
+ // Juste après un démarrage, la base et le service auth ne sont pas encore
53
+ // prêts : Keycloak doit y déclarer son fournisseur, on attend /settings.
54
+ const waitForAuth = async () => {
55
+ const url = `http://localhost:${config.web.port}/auth/v1/settings`;
56
+ for (let i = 0; i < 90; i++) {
57
+ const ok = await fetch(url, { headers: { apikey: config.auth.anon } }).then(
58
+ (r) => r.ok,
59
+ () => false
60
+ );
61
+ if (ok) return true;
62
+ await new Promise((r) => setTimeout(r, 1000));
63
+ }
64
+ return false;
65
+ };
66
+
67
+ const runners = { keycloak: runKeycloak, valkey: runValkey };
68
+ let targets = wanted;
69
+ if (all) {
70
+ targets = SERVICES.filter((s) => s.optional && s.configured(config));
71
+ if (!targets.length) {
72
+ console.log(chalk.grey(' No optional service configured yet: "poad run kc" or "poad run valkey" adds one.'));
73
+ return;
74
+ }
75
+ }
76
+ for (const service of targets) {
77
+ // --all complète ce qui manque : un service déjà lancé n'est pas redémarré
78
+ if (all && (await containerState(docker, service.container(config))) === 'running') {
79
+ console.log(`${chalk.greenBright('✔')} ${service.label} already running.`);
80
+ continue;
81
+ }
82
+ await runners[service.id]();
83
+ config = readConfig();
84
+ }
85
+
86
+ async function runKeycloak() {
87
+ if (!(await waitForAuth())) return console.log(chalk.redBright('Keycloak not started: the auth service does not answer (poad info, docker logs).'));
88
+ try {
89
+ kc.assertCanRegister(config);
90
+ } catch (err) {
91
+ return console.log(chalk.redBright(`Keycloak not started: ${err.message}`));
92
+ }
93
+
94
+ // Port gardé d'un lancement à l'autre (l'émetteur des jetons en dépend)
95
+ let port = config.keycloak && Number(config.keycloak.port);
96
+ if (!port) {
97
+ [port] = await findFreePorts(1);
98
+ kc.savePort(root, port);
99
+ config = readConfig();
100
+ }
101
+
102
+ if (!(await pullIfMissing(docker, kc.IMAGE))) return;
103
+
104
+ const dir = kc.dataDir(root);
105
+ const { file, secrets } = kc.loadSecrets(dir);
106
+ // Dossier à part : Keycloak importe tous les fichiers JSON qu'il y trouve
107
+ const importDir = path.join(dir, 'import');
108
+ fs.mkdirSync(importDir, { recursive: true });
109
+ fs.chmodSync(importDir, 0o755);
110
+ fs.writeFileSync(path.join(importDir, `${kc.REALM}-realm.json`), JSON.stringify(kc.realmOf(config, secrets), null, 2) + '\n', {
111
+ mode: 0o644,
112
+ });
113
+ fs.chmodSync(path.join(importDir, `${kc.REALM}-realm.json`), 0o644);
114
+
115
+ const name = kc.containerName(config);
116
+ const progress = ora('Starting Keycloak').start();
117
+ try {
118
+ try {
119
+ await docker.getContainer(name).remove({ force: true });
120
+ } catch {
121
+ /* pas de conteneur précédent */
122
+ }
123
+ // Sur le réseau du projet : l'engine joint Keycloak sous le nom « keycloak »
124
+ await mail.ensureNetwork(docker, config);
125
+ const net = mail.onNetwork(config, kc.ALIAS);
126
+ const container = await docker.createContainer({
127
+ name,
128
+ Image: kc.IMAGE,
129
+ NetworkingConfig: net.endpoint,
130
+ Env: ['KC_BOOTSTRAP_ADMIN_USERNAME=admin', `KC_BOOTSTRAP_ADMIN_PASSWORD=${secrets.admin_password}`],
131
+ Cmd: ['start-dev', '--import-realm', `--hostname=http://localhost:${port}`, '--hostname-backchannel-dynamic=true'],
132
+ ExposedPorts: { '8080/tcp': {} },
133
+ HostConfig: {
134
+ NetworkMode: net.NetworkMode,
135
+ PortBindings: { '8080/tcp': [{ HostPort: String(port) }] },
136
+ Binds: [`${importDir}:/opt/keycloak/data/import:ro`],
137
+ AutoRemove: true,
138
+ },
139
+ });
140
+ await container.start();
141
+
142
+ const issuer = `http://localhost:${port}/realms/${kc.REALM}`;
143
+ for (let i = 0; ; i++) {
144
+ const ok = await fetch(`${issuer}/.well-known/openid-configuration`).then(
145
+ (r) => r.ok,
146
+ () => false
147
+ );
148
+ if (ok) break;
149
+ if (i > 120) throw new Error(`Keycloak does not answer after 120 s (docker logs ${name})`);
150
+ await new Promise((r) => setTimeout(r, 1000));
151
+ }
152
+ kc.register(config, secrets);
153
+ progress.succeed(chalk.bold('Keycloak started.'));
154
+ } catch (err) {
155
+ progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
156
+ return;
157
+ }
158
+
159
+ console.log(' ');
160
+ const info = {
161
+ 'Keycloak URL': `http://localhost:${port}`,
162
+ Issuer: `http://localhost:${port}/realms/${kc.REALM}`,
163
+ 'Admin console': `http://localhost:${port}/admin (admin / see ${path.relative(process.cwd(), file)})`,
164
+ Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
165
+ 'Test users': secrets.users.map((u) => `${u.username} / ${u.password}${u.emailVerified ? '' : ' (email not verified)'}`),
166
+ };
167
+ console.log(prettyoutput(info));
168
+ console.log(chalk.grey(` The realm is re-imported on each run: changes made in the admin console are not kept.`));
169
+ console.log(' ');
170
+ }
171
+
172
+ async function runValkey() {
173
+ const fresh = !valkey.enabled(config);
174
+ if (fresh) {
175
+ const [port] = await findFreePorts(1);
176
+ valkey.savePort(root, port);
177
+ config = readConfig();
178
+ }
179
+ if (!(await pullIfMissing(docker, valkey.IMAGE))) return;
180
+ fs.mkdirSync(valkey.dataDir(root), { recursive: true });
181
+
182
+ const name = valkey.containerName(config);
183
+ const progress = ora('Starting Valkey').start();
184
+ try {
185
+ try {
186
+ await docker.getContainer(name).remove({ force: true });
187
+ } catch {
188
+ /* pas de conteneur précédent */
189
+ }
190
+ await mail.ensureNetwork(docker, config);
191
+ const container = await docker.createContainer(valkey.containerOptions(config, root, mail.onNetwork(config, valkey.ALIAS)));
192
+ await container.start();
193
+ for (let i = 0; ; i++) {
194
+ const exec = await container.exec({ Cmd: ['valkey-cli', 'ping'], AttachStdout: true, AttachStderr: true });
195
+ const out = await new Promise((resolve, reject) =>
196
+ exec.start({}, (err, stream) => {
197
+ if (err) return reject(err);
198
+ let data = '';
199
+ stream.on('data', (c) => (data += c.toString()));
200
+ stream.on('end', () => resolve(data));
201
+ })
202
+ );
203
+ if (out.includes('PONG')) break;
204
+ if (i > 30) throw new Error(`Valkey does not answer after 30 s (docker logs ${name})`);
205
+ await new Promise((r) => setTimeout(r, 1000));
206
+ }
207
+ progress.succeed(chalk.bold('Valkey started.'));
208
+ } catch (err) {
209
+ progress.fail(chalk.redBright(`Valkey failed to start: ${err.message}`));
210
+ return;
211
+ }
212
+
213
+ console.log(' ');
214
+ console.log(
215
+ prettyoutput({
216
+ 'Valkey URL': `redis://127.0.0.1:${config.valkey.port}`,
217
+ 'From the engine': valkey.URL,
218
+ Data: path.relative(process.cwd(), valkey.dataDir(root)),
219
+ })
220
+ );
221
+ if (fresh) {
222
+ console.log(chalk.grey(' The engine gets REDIS_URL at its next start: run "poad stop" then "poad start".'));
223
+ console.log(' ');
224
+ }
225
+ }
226
+ };
package/global/start.js CHANGED
@@ -1,4 +1,6 @@
1
- module.exports = async (args) => {
1
+ // poad start démarre le projet (engine + Mailpit)
2
+ // poad start --all puis tous les services optionnels configurés (Keycloak, Valkey…)
3
+ module.exports = async (args = {}) => {
2
4
  const chalk = require('chalk-v2');
3
5
  const Docker = require('dockerode');
4
6
  const docker = new Docker();
@@ -9,37 +11,39 @@ module.exports = async (args) => {
9
11
  const prettyoutput = require('prettyoutput');
10
12
  const { findPoadDir } = require('../utils/findpoad');
11
13
  const { isDockerExist } = require('../utils/docker');
12
- const { usesMinio, storageInfo } = require('../utils/engine');
14
+ const { storageInfo, offerEngineUpgrade } = require('../utils/engine');
15
+ const { pullIfMissing } = require('../utils/pull');
16
+ const mail = require('../utils/mail');
17
+ const valkey = require('../utils/valkey');
13
18
  const root = findPoadDir(process.cwd());
14
19
  const config = toml.parse(await fs.readFile(root, 'utf-8'));
15
20
  const containerName = config.project_uuid;
16
- const minio = usesMinio(config);
17
21
  console.log(' ');
22
+ const { wantsAll } = require('../utils/services');
23
+ const all = wantsAll(args);
18
24
  if (await isDockerExist(containerName)) {
19
- return console.log(chalk.bold('Container already started'));
25
+ console.log(chalk.bold('Container already started'));
26
+ if (all) await require('./run')({ all: true });
27
+ return;
20
28
  }
29
+ config.engine = await offerEngineUpgrade(root, config, args);
21
30
  const image = 'poadio/engine:' + config.engine;
22
31
  // L'image de la version du projet n'est pas forcément là (poad install tire
23
32
  // celle du CLI, et config.toml peut en demander une autre) : on la tire.
24
- try {
25
- await docker.getImage(image).inspect();
26
- } catch {
27
- const pulling = ora(`Pulling ${image}`).start();
28
- try {
29
- await new Promise((resolve, reject) =>
30
- docker.pull(image, (err, stream) =>
31
- err ? reject(err) : docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()))
32
- )
33
- );
34
- pulling.succeed(`${image} pulled.`);
35
- } catch (err) {
36
- pulling.fail(chalk.redBright(`Cannot pull ${image}: ${err.message}`));
37
- return;
38
- }
33
+ if (!(await pullIfMissing(docker, image))) return;
34
+ const mailpit = mail.usesMailpit(config);
35
+ if (mailpit && !mail.mailPort(config)) {
36
+ return console.log(chalk.redBright(`No [mail] port in ${root}: add a [mail] section with a free port.`));
39
37
  }
40
- const progress = ora('Starting container').start();
41
- docker
42
- .createContainer({
38
+ if (mailpit && !(await pullIfMissing(docker, mail.MAILPIT_IMAGE))) return;
39
+
40
+ const progress = ora('Starting containers').start();
41
+ try {
42
+ // Réseau du projet : l'engine y joint Mailpit (« mail ») et Keycloak
43
+ await mail.ensureNetwork(docker, config);
44
+ if (mailpit) await mail.startMailpit(docker, config);
45
+ const net = mail.onNetwork(config, 'engine');
46
+ const container = await docker.createContainer({
43
47
  name: containerName,
44
48
  Image: image,
45
49
  Tty: false,
@@ -54,48 +58,45 @@ module.exports = async (args) => {
54
58
  'JWT_SECRET=' + config.auth.secret,
55
59
  'ANON_KEY=' + config.auth.anon,
56
60
  'SERVICE_ROLE_KEY=' + config.auth.service,
57
- ...(minio
58
- ? [
59
- 'S3_ACCESS_KEY=' + config.s3.access_key,
60
- 'S3_SECRET_KEY=' + config.s3.secret_key,
61
- 'S3_REGION=local',
62
- ]
63
- : []),
61
+ ...mail.smtpEnv(config),
62
+ ...valkey.engineEnv(config),
64
63
  ],
65
64
  HostConfig: {
65
+ NetworkMode: net.NetworkMode,
66
66
  PortBindings: {
67
67
  '5432/tcp': [{ HostPort: config.db.port.toString() }],
68
68
  '8000/tcp': [{ HostPort: config.web.port.toString() }],
69
- ...(minio
70
- ? { '9500/tcp': [{ HostPort: config.s3.port.toString() }] }
71
- : {}),
72
- '9000/tcp': [{ HostPort: config.inbucket.port.toString() }],
73
69
  },
74
70
  Binds: [path.dirname(root) + '/data:/data'],
71
+ // Services lancés sur la machine : joignables depuis l'engine, y
72
+ // compris sous Linux
73
+ ExtraHosts: ['host.docker.internal:host-gateway'],
75
74
  AutoRemove: true,
76
75
  },
77
- })
78
- .then((container) => {
79
- return container.start();
80
- })
81
- .then((container) => {
82
- progress.succeed(chalk.bold('container started.'));
83
- console.log(' ');
84
- console.log(chalk.bold(' 🚀 Container started successfully'));
85
- console.log(' ');
86
- const info = {
87
- 'API URL': `http://localhost:${config.web.port}`,
88
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
89
- ...storageInfo(config),
90
- 'Inbucket URL': `http://localhost:${config.inbucket.port}`,
91
- 'JWT secret': `${config.auth.secret}`,
92
- 'anon key': config.auth.anon,
93
- 'service_role key': config.auth.service,
94
- };
95
- console.log(prettyoutput(info));
96
- })
97
- .catch((err) => {
98
- console.log(err);
99
- progress.fail(chalk.redBright('Error: Container failed to start'));
76
+ NetworkingConfig: net.endpoint,
100
77
  });
78
+ await container.start();
79
+ } catch (err) {
80
+ progress.fail(chalk.redBright(`Error: containers failed to start: ${err.message}`));
81
+ await mail.stopMailpit(docker, config);
82
+ return;
83
+ }
84
+ progress.succeed(chalk.bold('containers started.'));
85
+ if (!all && valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
86
+ console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
87
+ }
88
+ console.log(' ');
89
+ console.log(chalk.bold(' 🚀 Container started successfully'));
90
+ console.log(' ');
91
+ const info = {
92
+ 'API URL': `http://localhost:${config.web.port}`,
93
+ 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
94
+ ...storageInfo(config),
95
+ ...(mailpit ? { 'Mail URL': `http://localhost:${mail.mailPort(config)}` } : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
96
+ 'JWT secret': `${config.auth.secret}`,
97
+ 'anon key': config.auth.anon,
98
+ 'service_role key': config.auth.service,
99
+ };
100
+ console.log(prettyoutput(info));
101
+ if (all) await require('./run')({ all: true });
101
102
  };
package/global/stop.js CHANGED
@@ -1,28 +1,75 @@
1
+ // poad stop arrête le projet : engine, Mailpit, Keycloak, réseau
2
+ // poad stop keycloak|kc arrête seulement Keycloak et retire le fournisseur
3
+ // poad stop valkey|redis arrête seulement Valkey
1
4
  module.exports = async (args) => {
2
5
  const Docker = require('dockerode');
3
6
  const docker = new Docker();
4
7
  const toml = require('toml');
5
- const path = require('path');
6
8
  const fs = require('fs').promises;
7
9
  const { findPoadDir } = require('../utils/findpoad');
8
10
  const { isDockerExist } = require('../utils/docker');
11
+ const kc = require('../utils/keycloak');
12
+ const mail = require('../utils/mail');
13
+ const valkey = require('../utils/valkey');
9
14
  const root = findPoadDir(process.cwd());
10
15
  const config = toml.parse(await fs.readFile(root, 'utf-8'));
11
16
  const containerName = config.project_uuid;
12
17
  const ora = require('ora');
13
18
  const chalk = require('chalk-v2');
14
19
  console.log(' ');
15
- if (!(await isDockerExist(containerName))) {
16
- return console.log(chalk.redBright('Container not found'));
20
+
21
+ const stopKeycloak = async () => {
22
+ const name = kc.containerName(config);
23
+ if (!(await isDockerExist(name))) return false;
24
+ const progress = ora('Stopping Keycloak').start();
25
+ kc.unregister(config);
26
+ try {
27
+ await docker.getContainer(name).remove({ force: true });
28
+ progress.succeed(chalk.bold('Keycloak stopped'));
29
+ } catch {
30
+ progress.fail('Error: Failed to stop Keycloak');
31
+ }
32
+ return true;
33
+ };
34
+
35
+ const stopValkey = async () => {
36
+ const name = valkey.containerName(config);
37
+ if (!(await isDockerExist(name))) return false;
38
+ const progress = ora('Stopping Valkey').start();
39
+ try {
40
+ await docker.getContainer(name).stop();
41
+ progress.succeed(chalk.bold('Valkey stopped'));
42
+ } catch {
43
+ progress.fail('Error: Failed to stop Valkey');
44
+ }
45
+ return true;
46
+ };
47
+
48
+ if (kc.wanted(args)) {
49
+ if (!(await stopKeycloak())) console.log(chalk.redBright('Keycloak is not running'));
50
+ return;
17
51
  }
18
- const progress = ora('Stopping container').start();
19
- docker
20
- .getContainer(containerName)
21
- .stop()
22
- .then(() => {
52
+ if (valkey.wanted(args)) {
53
+ if (!(await stopValkey())) console.log(chalk.redBright('Valkey is not running'));
54
+ return;
55
+ }
56
+
57
+ await stopKeycloak();
58
+ await stopValkey();
59
+ const engine = await isDockerExist(containerName);
60
+ if (engine) {
61
+ const progress = ora('Stopping container').start();
62
+ try {
63
+ await docker.getContainer(containerName).stop();
64
+ // AutoRemove : le conteneur disparaît juste après l'arrêt ; le réseau
65
+ // ne peut être supprimé qu'ensuite
66
+ for (let i = 0; i < 20 && (await isDockerExist(containerName)); i++) await new Promise((r) => setTimeout(r, 500));
23
67
  progress.succeed(chalk.bold('Container stopped successfully'));
24
- })
25
- .catch((err) => {
68
+ } catch {
26
69
  progress.fail('Error: Failed to stop container');
27
- });
70
+ }
71
+ }
72
+ const mailpit = await mail.stopMailpit(docker, config);
73
+ await mail.removeNetwork(docker, config);
74
+ if (!engine && !mailpit) console.log(chalk.redBright('Container not found'));
28
75
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.7.1",
4
- "engine": "0.6.3",
3
+ "version": "2.10.0",
4
+ "engine": "0.7.0",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
package/project/info.js CHANGED
@@ -1,12 +1,16 @@
1
- module.exports = async (args) => {
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).
3
+ module.exports = async () => {
2
4
  const chalk = require('chalk-v2');
3
5
  const toml = require('toml');
4
- const path = require('path');
5
6
  const fs = require('fs').promises;
7
+ const Docker = require('dockerode');
8
+ const docker = new Docker();
6
9
  const prettyoutput = require('prettyoutput');
7
10
  const { findPoadDir } = require('../utils/findpoad');
8
11
  const { isDockerExist } = require('../utils/docker');
9
12
  const { storageInfo } = require('../utils/engine');
13
+ const { SERVICES, containerState } = require('../utils/services');
10
14
  const root = findPoadDir(process.cwd());
11
15
  const config = toml.parse(await fs.readFile(root, 'utf-8'));
12
16
  console.log(' ');
@@ -16,13 +20,45 @@ module.exports = async (args) => {
16
20
  console.log(chalk.bold('POAD project info'));
17
21
  console.log(' ');
18
22
  const info = {
23
+ Engine: config.engine,
19
24
  'API URL': `http://localhost:${config.web.port}`,
20
25
  'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
21
26
  ...storageInfo(config),
22
- 'Inbucket URL': `http://localhost:${config.inbucket.port}`,
27
+ ...(config.smtp && config.smtp.host ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` } : {}),
23
28
  'JWT secret': `${config.auth.secret}`,
24
29
  'anon key': config.auth.anon,
25
30
  'service_role key': config.auth.service,
26
31
  };
27
32
  console.log(prettyoutput(info));
33
+
34
+ // Panneau des services : en cours, arrêtés (configurés), ou disponibles
35
+ const rows = [];
36
+ for (const s of SERVICES) {
37
+ const configured = s.configured(config);
38
+ if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
39
+ const state = configured ? await containerState(docker, s.container(config)) : null;
40
+ rows.push({ s, configured, running: state === 'running' });
41
+ }
42
+ if (!rows.length) return;
43
+
44
+ const width = Math.max(...rows.map((r) => r.s.label.length));
45
+ const line = chalk.grey('─'.repeat(48));
46
+ console.log(chalk.bold('Services'));
47
+ console.log(line);
48
+ for (const { s, configured, running } of rows) {
49
+ const label = chalk.bold(s.label.padEnd(width));
50
+ if (running) {
51
+ console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}`);
52
+ for (const [k, v] of Object.entries(s.info(config))) console.log(` ${chalk.grey(k.padEnd(16))} ${v}`);
53
+ } else if (configured) {
54
+ const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
55
+ console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')} ${chalk.grey(`(${how})`)}`);
56
+ } else {
57
+ console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}`)}`);
58
+ }
59
+ }
60
+ console.log(line);
61
+ const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
62
+ if (stopped) console.log(chalk.grey(` "poad run --all" starts every configured service.`));
63
+ console.log(' ');
28
64
  };
package/utils/engine.js CHANGED
@@ -24,3 +24,67 @@ const storageInfo = (config) => {
24
24
  };
25
25
 
26
26
  module.exports = { usesMinio, storageInfo };
27
+
28
+ // Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
29
+ // à jour `engine` dans config.toml (au sein de la même version mineure, où
30
+ // seules des migrations s'appliquent). La mise à jour migre poad/data, sans
31
+ // retour possible : on demande toujours, sauf avec `poad start --upgrade`.
32
+ const parseVersion = (v) => String(v || '').split('.').map(Number);
33
+ const isNewer = (a, b) => {
34
+ const pa = parseVersion(a);
35
+ const pb = parseVersion(b);
36
+ for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0);
37
+ return false;
38
+ };
39
+
40
+ const ask = (question) =>
41
+ new Promise((resolve) => {
42
+ const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
43
+ rl.question(question, (answer) => {
44
+ rl.close();
45
+ resolve(/^(y|yes|o|oui)$/i.test(answer.trim()));
46
+ });
47
+ });
48
+
49
+ /** Version d'engine à démarrer (celle du projet, ou la nouvelle si acceptée) */
50
+ const offerEngineUpgrade = async (root, config, args = {}) => {
51
+ const chalk = require('chalk-v2');
52
+ const fs = require('fs').promises;
53
+ const target = global.package && global.package.engine;
54
+ const current = config.engine;
55
+ if (!target || !isNewer(target, current)) return current;
56
+ const [cMaj, cMin] = parseVersion(current);
57
+ const [tMaj, tMin] = parseVersion(target);
58
+ if (cMaj !== tMaj || cMin !== tMin) {
59
+ console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}).`));
60
+ console.log(chalk.yellow(` Upgrading across minor versions is manual: see the release notes, then edit engine in ${root}.`));
61
+ console.log(' ');
62
+ return current;
63
+ }
64
+ let accepted = Boolean(args.upgrade || args['--upgrade']);
65
+ if (!accepted) {
66
+ if (!process.stdin.isTTY) {
67
+ console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}). Run "poad start --upgrade" to switch.`));
68
+ console.log(' ');
69
+ return current;
70
+ }
71
+ console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}).`));
72
+ console.log(chalk.grey(' Upgrading applies database migrations to poad/data; it cannot be undone.'));
73
+ accepted = await ask(chalk.bold(` Upgrade this project to ${target}? (y/N) `));
74
+ console.log(' ');
75
+ }
76
+ if (!accepted) return current;
77
+ const text = await fs.readFile(root, 'utf-8');
78
+ const updated = text.replace(/^(\s*engine\s*=\s*)["'][^"']*["']/m, `$1"${target}"`);
79
+ if (updated === text) {
80
+ console.log(chalk.redBright(` Cannot find engine in ${root}; edit it by hand.`));
81
+ return current;
82
+ }
83
+ await fs.writeFile(root, updated);
84
+ console.log(chalk.green(` ${root}: engine ${current} → ${target}`));
85
+ console.log(' ');
86
+ return target;
87
+ };
88
+
89
+ module.exports.offerEngineUpgrade = offerEngineUpgrade;
90
+ module.exports.isNewerVersion = isNewer;
@@ -0,0 +1,188 @@
1
+ // Keycloak local, optionnel, pour tester la connexion OIDC sans compte
2
+ // externe : `poad run keycloak` (ou `kc`) / `poad stop keycloak`.
3
+ //
4
+ // - un conteneur par projet : <project_uuid>-keycloak ;
5
+ // - port choisi au premier lancement, gardé dans config.toml ([keycloak]) ;
6
+ // - realm « poad », client « poad », deux utilisateurs de test ; secrets et
7
+ // mots de passe dans poad/data/keycloak/users.json (hors git, comme data) ;
8
+ // - le realm est réimporté à chaque lancement (Keycloak en mode dev, sans
9
+ // persistance) : les changements faits dans la console d'admin se perdent ;
10
+ // - le fournisseur « keycloak » (stratégie oidc) est déclaré au projet.
11
+ //
12
+ // Le navigateur joint Keycloak par http://localhost:<port>, l'engine par le
13
+ // réseau du projet, sous le nom « keycloak » (http://keycloak:8080, option
14
+ // hostname-backchannel-dynamic) : l'émetteur reste http://localhost:<port>
15
+ // pour les deux.
16
+
17
+ const path = require('path');
18
+ const fs = require('fs');
19
+ const crypto = require('crypto');
20
+ const { execFileSync } = require('child_process');
21
+
22
+ const IMAGE = 'quay.io/keycloak/keycloak:26.0.7';
23
+ const REALM = 'poad';
24
+ const CLIENT = 'poad';
25
+ const PROVIDER = 'keycloak';
26
+ const NAMES = ['keycloak', 'kc'];
27
+ const ALIAS = 'keycloak';
28
+
29
+ const containerName = (config) => `${config.project_uuid}-keycloak`;
30
+ const dataDir = (root) => path.join(path.dirname(root), 'data', 'keycloak');
31
+ const random = (n) => crypto.randomBytes(n).toString('base64url');
32
+
33
+ /** Le drapeau désigne-t-il Keycloak ? ({ kc: true }, { keycloak: true }) */
34
+ const wanted = (args = {}) => NAMES.some((n) => args[n]);
35
+
36
+ const psql = (config, sql) =>
37
+ execFileSync(
38
+ 'docker',
39
+ ['exec', '-i', config.project_uuid, 'psql', '-U', 'postgres', '-h', '/var/run/postgresql', '-v', 'ON_ERROR_STOP=1', '-Atq'],
40
+ { input: sql, stdio: ['pipe', 'pipe', 'pipe'] }
41
+ )
42
+ .toString()
43
+ .trim();
44
+
45
+ const quote = (s) => `'${String(s).replace(/'/g, "''")}'`;
46
+
47
+ /** Ajoute ou met à jour la section [keycloak] de config.toml (port) */
48
+ const savePort = (root, port) => {
49
+ const text = fs.readFileSync(root, 'utf-8');
50
+ let updated;
51
+ if (/^\[keycloak\]\s*$/m.test(text)) {
52
+ updated = text.replace(/(^\[keycloak\][^[]*?^port\s*=\s*)\d+/m, `$1${port}`);
53
+ if (updated === text) updated = text.replace(/^\[keycloak\]\s*$/m, `[keycloak]\nport = ${port}`);
54
+ } else {
55
+ updated = `${text.replace(/\s*$/, '')}\n\n[keycloak]\nport = ${port}\n`;
56
+ }
57
+ fs.writeFileSync(root, updated);
58
+ };
59
+
60
+ const rsaKey = () =>
61
+ crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' });
62
+
63
+ /**
64
+ * Comptes de test et clé de signature du realm : créés une fois, puis relus.
65
+ * La clé fixe garde le même JWKS d'un lancement à l'autre : le service auth
66
+ * n'a jamais de clés périmées en cache pour cet émetteur.
67
+ */
68
+ const loadSecrets = (dir) => {
69
+ const file = path.join(dir, 'users.json');
70
+ if (fs.existsSync(file)) {
71
+ const secrets = JSON.parse(fs.readFileSync(file, 'utf-8'));
72
+ if (!secrets.signing_key) {
73
+ secrets.signing_key = rsaKey();
74
+ fs.writeFileSync(file, JSON.stringify(secrets, null, 2) + '\n', { mode: 0o600 });
75
+ }
76
+ return { file, secrets };
77
+ }
78
+ const secrets = {
79
+ signing_key: rsaKey(),
80
+ client_secret: random(24),
81
+ admin_password: random(18),
82
+ users: [
83
+ { username: 'alice', email: 'alice@poad.test', password: random(9), emailVerified: true },
84
+ { username: 'bob', email: 'bob@poad.test', password: random(9), emailVerified: false },
85
+ ],
86
+ };
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ fs.writeFileSync(file, JSON.stringify(secrets, null, 2) + '\n', { mode: 0o600 });
89
+ return { file, secrets };
90
+ };
91
+
92
+ const realmOf = (config, secrets) => ({
93
+ realm: REALM,
94
+ enabled: true,
95
+ registrationAllowed: false,
96
+ components: {
97
+ 'org.keycloak.keys.KeyProvider': [
98
+ {
99
+ name: 'poad-rsa',
100
+ providerId: 'rsa',
101
+ subComponents: {},
102
+ config: { privateKey: [secrets.signing_key], priority: ['200'], algorithm: ['RS256'], active: ['true'], enabled: ['true'] },
103
+ },
104
+ ],
105
+ },
106
+ clients: [
107
+ {
108
+ clientId: CLIENT,
109
+ enabled: true,
110
+ protocol: 'openid-connect',
111
+ publicClient: false,
112
+ secret: secrets.client_secret,
113
+ standardFlowEnabled: true,
114
+ directAccessGrantsEnabled: false,
115
+ redirectUris: [`http://localhost:${config.web.port}/auth/v1/callback`],
116
+ webOrigins: ['+'],
117
+ attributes: { 'pkce.code.challenge.method': 'S256' },
118
+ },
119
+ ],
120
+ users: secrets.users.map((u) => ({
121
+ username: u.username,
122
+ email: u.email,
123
+ emailVerified: u.emailVerified,
124
+ firstName: u.username[0].toUpperCase() + u.username.slice(1),
125
+ lastName: 'Poad',
126
+ enabled: true,
127
+ credentials: [{ type: 'password', value: u.password, temporary: false }],
128
+ })),
129
+ });
130
+
131
+ const isLocalProvider = (params) =>
132
+ /\/\/(keycloak:8080|host\.docker\.internal|localhost|127\.0\.0\.1)[:/]/.test(String(params && params.issuer));
133
+
134
+ /**
135
+ * Déclare le fournisseur au projet. Refuse d'écraser un fournisseur
136
+ * « keycloak » qui ne pointe pas vers un Keycloak local.
137
+ */
138
+ const assertCanRegister = (config) => {
139
+ const existing = psql(config, `select params::text from auth.settings where name = ${quote(PROVIDER)};`);
140
+ if (existing && !isLocalProvider(JSON.parse(existing))) {
141
+ throw new Error(`a "${PROVIDER}" provider already exists in this project and is not a local Keycloak; remove it first`);
142
+ }
143
+ };
144
+
145
+ const register = (config, secrets) => {
146
+ assertCanRegister(config);
147
+ const params = {
148
+ issuer: `http://${ALIAS}:8080/realms/${REALM}`,
149
+ client_id: CLIENT,
150
+ client_secret: secrets.client_secret,
151
+ scopes: 'openid email profile',
152
+ };
153
+ psql(
154
+ config,
155
+ `delete from auth.settings where name = ${quote(PROVIDER)};
156
+ insert into auth.settings (name, strategy, params, instances)
157
+ select ${quote(PROVIDER)}, id, ${quote(JSON.stringify(params))}::jsonb, '00000000-0000-0000-0000-000000000000'
158
+ from auth.providers where strategy = 'oidc';`
159
+ );
160
+ };
161
+
162
+ /** Retire le fournisseur s'il désigne un Keycloak local (projet démarré) */
163
+ const unregister = (config) => {
164
+ try {
165
+ const existing = psql(config, `select params::text from auth.settings where name = ${quote(PROVIDER)};`);
166
+ if (existing && isLocalProvider(JSON.parse(existing))) psql(config, `delete from auth.settings where name = ${quote(PROVIDER)};`);
167
+ } catch {
168
+ /* projet arrêté */
169
+ }
170
+ };
171
+
172
+ module.exports = {
173
+ IMAGE,
174
+ REALM,
175
+ PROVIDER,
176
+ NAMES,
177
+ ALIAS,
178
+ containerName,
179
+ dataDir,
180
+ wanted,
181
+ savePort,
182
+ loadSecrets,
183
+ realmOf,
184
+ assertCanRegister,
185
+ register,
186
+ unregister,
187
+ isLocalProvider,
188
+ };
package/utils/mail.js ADDED
@@ -0,0 +1,103 @@
1
+ // Réseau Docker du projet et attrape-mails local (Mailpit).
2
+ //
3
+ // L'engine ne contient pas d'attrape-mails : en local, `poad start` lance
4
+ // Mailpit dans un conteneur à part (<project_uuid>-mail), sur un réseau propre
5
+ // au projet (poad-<project_uuid>) où l'engine le joint sous le nom « mail ».
6
+ // Si config.toml a une section [smtp], ce serveur est utilisé à la place et
7
+ // Mailpit n'est pas lancé.
8
+
9
+ const MAILPIT_IMAGE = 'axllent/mailpit:v1.27.11';
10
+ const MAIL_ALIAS = 'mail';
11
+
12
+ const networkName = (config) => `poad-${config.project_uuid}`;
13
+ const mailContainerName = (config) => `${config.project_uuid}-mail`;
14
+ /** Port de l'interface web des e-mails ([mail] port) */
15
+ const mailPort = (config) => config.mail && config.mail.port;
16
+
17
+ /** Crée le réseau du projet s'il n'existe pas */
18
+ const ensureNetwork = async (docker, config) => {
19
+ const name = networkName(config);
20
+ const found = await docker.listNetworks({ filters: { name: [name] } });
21
+ if (!found.some((n) => n.Name === name)) await docker.createNetwork({ Name: name, Driver: 'bridge' });
22
+ return name;
23
+ };
24
+
25
+ /** Supprime le réseau (une fois tous les conteneurs du projet arrêtés) */
26
+ const removeNetwork = async (docker, config) => {
27
+ try {
28
+ await docker.getNetwork(networkName(config)).remove();
29
+ } catch {
30
+ /* absent ou encore utilisé */
31
+ }
32
+ };
33
+
34
+ /** Options de création d'un conteneur sur le réseau du projet */
35
+ const onNetwork = (config, alias) => ({
36
+ NetworkMode: networkName(config),
37
+ endpoint: { EndpointsConfig: { [networkName(config)]: { Aliases: [alias] } } },
38
+ });
39
+
40
+ /** Variables SMTP de l'engine : [smtp] de config.toml, sinon Mailpit */
41
+ const smtpEnv = (config) => {
42
+ const s = config.smtp;
43
+ if (s && s.host) {
44
+ return [
45
+ `SMTP_HOST=${s.host}`,
46
+ `SMTP_PORT=${s.port || 587}`,
47
+ `SMTP_SECURE=${s.secure ? 'true' : 'false'}`,
48
+ ...(s.user ? [`SMTP_USER=${s.user}`] : []),
49
+ ...(s.pass ? [`SMTP_PASS=${s.pass}`] : []),
50
+ `SMTP_SENDER=${s.sender || 'no-reply@poad.local'}`,
51
+ ];
52
+ }
53
+ return [`SMTP_HOST=${MAIL_ALIAS}`, 'SMTP_PORT=1025', 'SMTP_SECURE=false', 'SMTP_SENDER=no-reply@poad.local'];
54
+ };
55
+
56
+ const usesMailpit = (config) => !(config.smtp && config.smtp.host);
57
+
58
+ /** Lance Mailpit (le remplace s'il tourne déjà) */
59
+ const startMailpit = async (docker, config) => {
60
+ const name = mailContainerName(config);
61
+ try {
62
+ await docker.getContainer(name).remove({ force: true });
63
+ } catch {
64
+ /* pas de conteneur précédent */
65
+ }
66
+ const net = onNetwork(config, MAIL_ALIAS);
67
+ const container = await docker.createContainer({
68
+ name,
69
+ Image: MAILPIT_IMAGE,
70
+ Env: ['MP_SMTP_AUTH_ACCEPT_ANY=true', 'MP_SMTP_AUTH_ALLOW_INSECURE=true', 'MP_MAX_MESSAGES=1000'],
71
+ ExposedPorts: { '8025/tcp': {} },
72
+ HostConfig: {
73
+ NetworkMode: net.NetworkMode,
74
+ PortBindings: { '8025/tcp': [{ HostPort: String(mailPort(config)) }] },
75
+ AutoRemove: true,
76
+ },
77
+ NetworkingConfig: net.endpoint,
78
+ });
79
+ await container.start();
80
+ };
81
+
82
+ const stopMailpit = async (docker, config) => {
83
+ try {
84
+ await docker.getContainer(mailContainerName(config)).remove({ force: true });
85
+ return true;
86
+ } catch {
87
+ return false;
88
+ }
89
+ };
90
+
91
+ module.exports = {
92
+ MAILPIT_IMAGE,
93
+ networkName,
94
+ mailContainerName,
95
+ mailPort,
96
+ ensureNetwork,
97
+ removeNetwork,
98
+ onNetwork,
99
+ smtpEnv,
100
+ usesMailpit,
101
+ startMailpit,
102
+ stopMailpit,
103
+ };
package/utils/pull.js ADDED
@@ -0,0 +1,27 @@
1
+ // Tire une image Docker si elle n'est pas déjà là. Renvoie false en cas
2
+ // d'échec (message déjà affiché).
3
+ const pullIfMissing = async (docker, image) => {
4
+ const ora = require('ora');
5
+ const chalk = require('chalk-v2');
6
+ try {
7
+ await docker.getImage(image).inspect();
8
+ return true;
9
+ } catch {
10
+ /* absente : on la tire */
11
+ }
12
+ const pulling = ora(`Pulling ${image}`).start();
13
+ try {
14
+ await new Promise((resolve, reject) =>
15
+ docker.pull(image, (err, stream) =>
16
+ err ? reject(err) : docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()))
17
+ )
18
+ );
19
+ pulling.succeed(`${image} pulled.`);
20
+ return true;
21
+ } catch (err) {
22
+ pulling.fail(chalk.redBright(`Cannot pull ${image}: ${err.message}`));
23
+ return false;
24
+ }
25
+ };
26
+
27
+ module.exports = { pullIfMissing };
@@ -0,0 +1,63 @@
1
+ // Services qui tournent à côté de l'engine, chacun dans son conteneur :
2
+ // - Mailpit : lancé par `poad start` (sauf si [smtp] désigne un vrai serveur) ;
3
+ // - Keycloak : optionnel, `poad run kc` ;
4
+ // - Valkey : optionnel, `poad run valkey`.
5
+ // Un service optionnel est « configuré » quand config.toml a sa section (port
6
+ // choisi au premier lancement) : `poad run --all` relance ceux-là.
7
+
8
+ const kc = require('./keycloak');
9
+ const valkey = require('./valkey');
10
+ const mail = require('./mail');
11
+
12
+ const SERVICES = [
13
+ {
14
+ id: 'mail',
15
+ label: 'Mailpit',
16
+ optional: false,
17
+ container: (config) => mail.mailContainerName(config),
18
+ configured: (config) => mail.usesMailpit(config),
19
+ info: (config) => ({ URL: `http://localhost:${mail.mailPort(config)}`, SMTP: 'mail:1025 (depuis l’engine)' }),
20
+ },
21
+ {
22
+ id: 'keycloak',
23
+ label: 'Keycloak',
24
+ optional: true,
25
+ names: kc.NAMES,
26
+ cmd: 'kc',
27
+ container: (config) => kc.containerName(config),
28
+ configured: (config) => Boolean(config.keycloak && config.keycloak.port),
29
+ info: (config) => ({
30
+ URL: `http://localhost:${config.keycloak.port}`,
31
+ Issuer: `http://localhost:${config.keycloak.port}/realms/${kc.REALM}`,
32
+ Provider: `"${kc.PROVIDER}"`,
33
+ }),
34
+ },
35
+ {
36
+ id: 'valkey',
37
+ label: 'Valkey',
38
+ optional: true,
39
+ names: valkey.NAMES,
40
+ cmd: 'valkey',
41
+ container: (config) => valkey.containerName(config),
42
+ configured: (config) => valkey.enabled(config),
43
+ info: (config) => ({ URL: `redis://127.0.0.1:${config.valkey.port}`, 'From the engine': valkey.URL }),
44
+ },
45
+ ];
46
+
47
+ /** État d'un conteneur : 'running', 'stopped' (existe mais arrêté) ou null (absent) */
48
+ const containerState = async (docker, name) => {
49
+ try {
50
+ const data = await docker.getContainer(name).inspect();
51
+ return data.State && data.State.Running ? 'running' : 'stopped';
52
+ } catch {
53
+ return null;
54
+ }
55
+ };
56
+
57
+ /** Services optionnels désignés par les arguments ({ kc: true }, { valkey: true }…) */
58
+ const wantedServices = (args = {}) => SERVICES.filter((s) => s.optional && s.names.some((n) => args[n]));
59
+
60
+ /** --all, all : tous les services optionnels configurés */
61
+ const wantsAll = (args = {}) => Boolean(args.all || args['--all'] || args['-a']);
62
+
63
+ module.exports = { SERVICES, containerState, wantedServices, wantsAll };
@@ -0,0 +1,60 @@
1
+ // Valkey local, optionnel (fork libre de Redis, licence BSD) :
2
+ // `poad run valkey` (ou `redis`) / `poad stop valkey`.
3
+ //
4
+ // - un conteneur par projet : <project_uuid>-valkey ;
5
+ // - port choisi au premier lancement, gardé dans config.toml ([valkey]) ;
6
+ // - données persistées dans poad/data/valkey (AOF) ;
7
+ // - l'engine le joint par le réseau du projet sous le nom « valkey »
8
+ // (REDIS_URL=redis://valkey:6379, passé par `poad start` quand la section
9
+ // [valkey] existe) ; la machine par 127.0.0.1:<port> seulement.
10
+
11
+ const path = require('path');
12
+ const fs = require('fs');
13
+
14
+ const IMAGE = 'valkey/valkey:8.1.4-alpine';
15
+ const NAMES = ['valkey', 'redis'];
16
+ const ALIAS = 'valkey';
17
+ const URL = `redis://${ALIAS}:6379`;
18
+
19
+ const containerName = (config) => `${config.project_uuid}-valkey`;
20
+ const dataDir = (root) => path.join(path.dirname(root), 'data', 'valkey');
21
+
22
+ /** Le drapeau désigne-t-il Valkey ? ({ valkey: true }, { redis: true }) */
23
+ const wanted = (args = {}) => NAMES.some((n) => args[n]);
24
+
25
+ /** Le projet utilise-t-il Valkey ? (section [valkey] de config.toml) */
26
+ const enabled = (config) => Boolean(config.valkey && config.valkey.port);
27
+
28
+ /** Variables de l'engine : REDIS_URL quand le projet utilise Valkey */
29
+ const engineEnv = (config) => (enabled(config) ? [`REDIS_URL=${URL}`] : []);
30
+
31
+ /** Ajoute ou met à jour la section [valkey] de config.toml (port) */
32
+ const savePort = (root, port) => {
33
+ const text = fs.readFileSync(root, 'utf-8');
34
+ let updated;
35
+ if (/^\[valkey\]\s*$/m.test(text)) {
36
+ updated = text.replace(/(^\[valkey\][^[]*?^port\s*=\s*)\d+/m, `$1${port}`);
37
+ if (updated === text) updated = text.replace(/^\[valkey\]\s*$/m, `[valkey]\nport = ${port}`);
38
+ } else {
39
+ updated = `${text.replace(/\s*$/, '')}\n\n[valkey]\nport = ${port}\n`;
40
+ }
41
+ fs.writeFileSync(root, updated);
42
+ };
43
+
44
+ /** Options de création du conteneur */
45
+ const containerOptions = (config, root, net) => ({
46
+ name: containerName(config),
47
+ Image: IMAGE,
48
+ Cmd: ['valkey-server', '--appendonly', 'yes', '--dir', '/data'],
49
+ ExposedPorts: { '6379/tcp': {} },
50
+ NetworkingConfig: net.endpoint,
51
+ HostConfig: {
52
+ NetworkMode: net.NetworkMode,
53
+ // Sans mot de passe : joignable depuis la machine seulement
54
+ PortBindings: { '6379/tcp': [{ HostIp: '127.0.0.1', HostPort: String(config.valkey.port) }] },
55
+ Binds: [`${dataDir(root)}:/data`],
56
+ AutoRemove: true,
57
+ },
58
+ });
59
+
60
+ module.exports = { IMAGE, NAMES, ALIAS, URL, containerName, dataDir, wanted, enabled, engineEnv, savePort, containerOptions };