poad 2.9.0 → 2.10.1

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,7 +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',
12
+ start: 'Start container for poad local development (start --all: and every configured service)',
13
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)',
14
+ run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, --all)',
15
15
  };
package/global/run.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // poad run <service> : démarre un service optionnel à côté du projet.
2
2
  // poad run keycloak | kc Keycloak local, déclaré comme fournisseur OIDC
3
3
  // poad run valkey | redis Valkey local (REDIS_URL de l'engine)
4
- module.exports = async (args) => {
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 = {}) => {
5
7
  const chalk = require('chalk-v2');
6
8
  const Docker = require('dockerode');
7
9
  const docker = new Docker();
@@ -17,117 +19,162 @@ module.exports = async (args) => {
17
19
  const kc = require('../utils/keycloak');
18
20
  const mail = require('../utils/mail');
19
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);
20
26
 
21
27
  console.log(' ');
22
- if (!kc.wanted(args) && !valkey.wanted(args)) {
28
+ if (!all && !wanted.length) {
23
29
  console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
24
30
  console.log(' ');
25
- console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
31
+ console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
26
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`);
27
34
  console.log(' ');
28
35
  return;
29
36
  }
30
37
 
31
38
  const root = findPoadDir(process.cwd());
32
39
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
33
- let config = toml.parse(fs.readFileSync(root, 'utf-8'));
40
+ const readConfig = () => toml.parse(fs.readFileSync(root, 'utf-8'));
41
+ let config = readConfig();
42
+
34
43
  if (!(await isDockerExist(config.project_uuid))) {
35
- return console.log(chalk.redBright('The project is not started: run "poad start" first.'));
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();
36
50
  }
37
51
 
38
- if (valkey.wanted(args)) return runValkey(root, config);
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
+ };
39
66
 
40
- try {
41
- kc.assertCanRegister(config);
42
- } catch (err) {
43
- return console.log(chalk.redBright(`Keycloak not started: ${err.message}`));
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
+ }
44
75
  }
45
-
46
- // Port gardé d'un lancement à l'autre (l'émetteur des jetons en dépend)
47
- let port = config.keycloak && Number(config.keycloak.port);
48
- if (!port) {
49
- [port] = await findFreePorts(1);
50
- kc.savePort(root, port);
51
- config = toml.parse(fs.readFileSync(root, 'utf-8'));
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();
52
84
  }
53
85
 
54
- if (!(await pullIfMissing(docker, kc.IMAGE))) return;
55
-
56
- const dir = kc.dataDir(root);
57
- const { file, secrets } = kc.loadSecrets(dir);
58
- // Dossier à part : Keycloak importe tous les fichiers JSON qu'il y trouve
59
- const importDir = path.join(dir, 'import');
60
- fs.mkdirSync(importDir, { recursive: true });
61
- fs.chmodSync(importDir, 0o755);
62
- fs.writeFileSync(path.join(importDir, `${kc.REALM}-realm.json`), JSON.stringify(kc.realmOf(config, secrets), null, 2) + '\n', {
63
- mode: 0o644,
64
- });
65
- fs.chmodSync(path.join(importDir, `${kc.REALM}-realm.json`), 0o644);
66
-
67
- const name = kc.containerName(config);
68
- const progress = ora('Starting Keycloak').start();
69
- try {
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).'));
70
88
  try {
71
- await docker.getContainer(name).remove({ force: true });
72
- } catch {
73
- /* pas de conteneur précédent */
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();
74
100
  }
75
- // Sur le réseau du projet : l'engine joint Keycloak sous le nom « keycloak »
76
- await mail.ensureNetwork(docker, config);
77
- const net = mail.onNetwork(config, kc.ALIAS);
78
- const container = await docker.createContainer({
79
- name,
80
- Image: kc.IMAGE,
81
- NetworkingConfig: net.endpoint,
82
- Env: ['KC_BOOTSTRAP_ADMIN_USERNAME=admin', `KC_BOOTSTRAP_ADMIN_PASSWORD=${secrets.admin_password}`],
83
- Cmd: ['start-dev', '--import-realm', `--hostname=http://localhost:${port}`, '--hostname-backchannel-dynamic=true'],
84
- ExposedPorts: { '8080/tcp': {} },
85
- HostConfig: {
86
- NetworkMode: net.NetworkMode,
87
- PortBindings: { '8080/tcp': [{ HostPort: String(port) }] },
88
- Binds: [`${importDir}:/opt/keycloak/data/import:ro`],
89
- AutoRemove: true,
90
- },
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,
91
112
  });
92
- await container.start();
113
+ fs.chmodSync(path.join(importDir, `${kc.REALM}-realm.json`), 0o644);
93
114
 
94
- const issuer = `http://localhost:${port}/realms/${kc.REALM}`;
95
- for (let i = 0; ; i++) {
96
- const ok = await fetch(`${issuer}/.well-known/openid-configuration`).then(
97
- (r) => r.ok,
98
- () => false
99
- );
100
- if (ok) break;
101
- if (i > 120) throw new Error(`Keycloak does not answer after 120 s (docker logs ${name})`);
102
- await new Promise((r) => setTimeout(r, 1000));
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;
103
157
  }
104
- kc.register(config, secrets);
105
- progress.succeed(chalk.bold('Keycloak started.'));
106
- } catch (err) {
107
- progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
108
- return;
109
- }
110
158
 
111
- console.log(' ');
112
- const info = {
113
- 'Keycloak URL': `http://localhost:${port}`,
114
- Issuer: `http://localhost:${port}/realms/${kc.REALM}`,
115
- 'Admin console': `http://localhost:${port}/admin (admin / see ${path.relative(process.cwd(), file)})`,
116
- Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
117
- 'Test users': secrets.users.map(
118
- (u) => `${u.username} / ${u.password}${u.emailVerified ? '' : ' (email not verified)'}`
119
- ),
120
- };
121
- console.log(prettyoutput(info));
122
- console.log(chalk.grey(` The realm is re-imported on each run: changes made in the admin console are not kept.`));
123
- console.log(' ');
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
+ }
124
171
 
125
- async function runValkey(root, config) {
172
+ async function runValkey() {
126
173
  const fresh = !valkey.enabled(config);
127
174
  if (fresh) {
128
175
  const [port] = await findFreePorts(1);
129
176
  valkey.savePort(root, port);
130
- config = toml.parse(fs.readFileSync(root, 'utf-8'));
177
+ config = readConfig();
131
178
  }
132
179
  if (!(await pullIfMissing(docker, valkey.IMAGE))) return;
133
180
  fs.mkdirSync(valkey.dataDir(root), { recursive: true });
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();
@@ -17,8 +19,12 @@ module.exports = async (args) => {
17
19
  const config = toml.parse(await fs.readFile(root, 'utf-8'));
18
20
  const containerName = config.project_uuid;
19
21
  console.log(' ');
22
+ const { wantsAll } = require('../utils/services');
23
+ const all = wantsAll(args);
20
24
  if (await isDockerExist(containerName)) {
21
- 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;
22
28
  }
23
29
  config.engine = await offerEngineUpgrade(root, config, args);
24
30
  const image = 'poadio/engine:' + config.engine;
@@ -76,7 +82,7 @@ module.exports = async (args) => {
76
82
  return;
77
83
  }
78
84
  progress.succeed(chalk.bold('containers started.'));
79
- if (valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
85
+ if (!all && valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
80
86
  console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
81
87
  }
82
88
  console.log(' ');
@@ -92,4 +98,5 @@ module.exports = async (args) => {
92
98
  'service_role key': config.auth.service,
93
99
  };
94
100
  console.log(prettyoutput(info));
101
+ if (all) await require('./run')({ all: true });
95
102
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.9.0",
3
+ "version": "2.10.1",
4
4
  "engine": "0.7.0",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
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,15 +20,49 @@ 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
- ...(config.smtp && config.smtp.host
23
- ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }
24
- : { 'Mail URL': `http://localhost:${config.mail && config.mail.port}` }),
27
+ ...(config.smtp && config.smtp.host ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` } : {}),
25
28
  'JWT secret': `${config.auth.secret}`,
26
29
  'anon key': config.auth.anon,
27
30
  'service_role key': config.auth.service,
28
31
  };
29
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, root))) {
53
+ // Une liste (comptes de test) : une ligne par entrée, alignées
54
+ const lines = Array.isArray(v) ? v : [v];
55
+ lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
56
+ }
57
+ } else if (configured) {
58
+ const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
59
+ console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')} ${chalk.grey(`(${how})`)}`);
60
+ } else {
61
+ console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}`)}`);
62
+ }
63
+ }
64
+ console.log(line);
65
+ const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
66
+ if (stopped) console.log(chalk.grey(` "poad run --all" starts every configured service.`));
67
+ console.log(' ');
30
68
  };
@@ -0,0 +1,83 @@
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
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ const readKeycloakUsers = (root) => {
15
+ if (!root) return null;
16
+ try {
17
+ return JSON.parse(fs.readFileSync(path.join(kc.dataDir(root), 'users.json'), 'utf-8'));
18
+ } catch {
19
+ return null;
20
+ }
21
+ };
22
+
23
+ const SERVICES = [
24
+ {
25
+ id: 'mail',
26
+ label: 'Mailpit',
27
+ optional: false,
28
+ container: (config) => mail.mailContainerName(config),
29
+ configured: (config) => mail.usesMailpit(config),
30
+ info: (config) => ({ URL: `http://localhost:${mail.mailPort(config)}`, SMTP: 'mail:1025 (depuis l’engine)' }),
31
+ },
32
+ {
33
+ id: 'keycloak',
34
+ label: 'Keycloak',
35
+ optional: true,
36
+ names: kc.NAMES,
37
+ cmd: 'kc',
38
+ container: (config) => kc.containerName(config),
39
+ configured: (config) => Boolean(config.keycloak && config.keycloak.port),
40
+ info: (config, root) => {
41
+ const out = {
42
+ URL: `http://localhost:${config.keycloak.port}`,
43
+ Issuer: `http://localhost:${config.keycloak.port}/realms/${kc.REALM}`,
44
+ Provider: `"${kc.PROVIDER}"`,
45
+ };
46
+ // Comptes de test du realm (poad/data/keycloak/users.json) : locaux, faits pour être affichés
47
+ const users = readKeycloakUsers(root);
48
+ if (users) {
49
+ out['Admin console'] = `http://localhost:${config.keycloak.port}/admin (admin / ${users.admin_password})`;
50
+ out['Test users'] = users.users.map((u) => `${u.username} / ${u.password} ${u.email}${u.emailVerified ? '' : ' (email not verified)'}`);
51
+ }
52
+ return out;
53
+ },
54
+ },
55
+ {
56
+ id: 'valkey',
57
+ label: 'Valkey',
58
+ optional: true,
59
+ names: valkey.NAMES,
60
+ cmd: 'valkey',
61
+ container: (config) => valkey.containerName(config),
62
+ configured: (config) => valkey.enabled(config),
63
+ info: (config) => ({ URL: `redis://127.0.0.1:${config.valkey.port}`, 'From the engine': valkey.URL }),
64
+ },
65
+ ];
66
+
67
+ /** État d'un conteneur : 'running', 'stopped' (existe mais arrêté) ou null (absent) */
68
+ const containerState = async (docker, name) => {
69
+ try {
70
+ const data = await docker.getContainer(name).inspect();
71
+ return data.State && data.State.Running ? 'running' : 'stopped';
72
+ } catch {
73
+ return null;
74
+ }
75
+ };
76
+
77
+ /** Services optionnels désignés par les arguments ({ kc: true }, { valkey: true }…) */
78
+ const wantedServices = (args = {}) => SERVICES.filter((s) => s.optional && s.names.some((n) => args[n]));
79
+
80
+ /** --all, all : tous les services optionnels configurés */
81
+ const wantsAll = (args = {}) => Boolean(args.all || args['--all'] || args['-a']);
82
+
83
+ module.exports = { SERVICES, containerState, wantedServices, wantsAll };