poad 2.7.0 → 2.9.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 +2 -1
- package/global/init.js +2 -1
- package/global/run.js +179 -0
- package/global/start.js +53 -40
- package/global/stop.js +58 -11
- package/package.json +2 -2
- package/project/info.js +3 -1
- package/utils/engine.js +64 -0
- package/utils/keycloak.js +188 -0
- package/utils/mail.js +103 -0
- package/utils/pull.js +27 -0
- package/utils/valkey.js +60 -0
package/global/cli.js
CHANGED
|
@@ -10,5 +10,6 @@ module.exports = {
|
|
|
10
10
|
install: `Install poad environment`,
|
|
11
11
|
init: `Init poad project`,
|
|
12
12
|
start: 'Start container for poad local development',
|
|
13
|
-
stop: 'Stop container for poad local development',
|
|
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
15
|
};
|
package/global/init.js
CHANGED
package/global/run.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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
|
+
module.exports = async (args) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const Docker = require('dockerode');
|
|
7
|
+
const docker = new Docker();
|
|
8
|
+
const toml = require('toml');
|
|
9
|
+
const ora = require('ora');
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const prettyoutput = require('prettyoutput');
|
|
13
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
14
|
+
const { isDockerExist } = require('../utils/docker');
|
|
15
|
+
const { findFreePorts } = require('../utils/ports');
|
|
16
|
+
const { pullIfMissing } = require('../utils/pull');
|
|
17
|
+
const kc = require('../utils/keycloak');
|
|
18
|
+
const mail = require('../utils/mail');
|
|
19
|
+
const valkey = require('../utils/valkey');
|
|
20
|
+
|
|
21
|
+
console.log(' ');
|
|
22
|
+
if (!kc.wanted(args) && !valkey.wanted(args)) {
|
|
23
|
+
console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
|
|
24
|
+
console.log(' ');
|
|
25
|
+
console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
|
|
26
|
+
console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
|
|
27
|
+
console.log(' ');
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const root = findPoadDir(process.cwd());
|
|
32
|
+
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'));
|
|
34
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
35
|
+
return console.log(chalk.redBright('The project is not started: run "poad start" first.'));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (valkey.wanted(args)) return runValkey(root, config);
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
kc.assertCanRegister(config);
|
|
42
|
+
} catch (err) {
|
|
43
|
+
return console.log(chalk.redBright(`Keycloak not started: ${err.message}`));
|
|
44
|
+
}
|
|
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'));
|
|
52
|
+
}
|
|
53
|
+
|
|
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 {
|
|
70
|
+
try {
|
|
71
|
+
await docker.getContainer(name).remove({ force: true });
|
|
72
|
+
} catch {
|
|
73
|
+
/* pas de conteneur précédent */
|
|
74
|
+
}
|
|
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
|
+
},
|
|
91
|
+
});
|
|
92
|
+
await container.start();
|
|
93
|
+
|
|
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));
|
|
103
|
+
}
|
|
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
|
+
|
|
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(' ');
|
|
124
|
+
|
|
125
|
+
async function runValkey(root, config) {
|
|
126
|
+
const fresh = !valkey.enabled(config);
|
|
127
|
+
if (fresh) {
|
|
128
|
+
const [port] = await findFreePorts(1);
|
|
129
|
+
valkey.savePort(root, port);
|
|
130
|
+
config = toml.parse(fs.readFileSync(root, 'utf-8'));
|
|
131
|
+
}
|
|
132
|
+
if (!(await pullIfMissing(docker, valkey.IMAGE))) return;
|
|
133
|
+
fs.mkdirSync(valkey.dataDir(root), { recursive: true });
|
|
134
|
+
|
|
135
|
+
const name = valkey.containerName(config);
|
|
136
|
+
const progress = ora('Starting Valkey').start();
|
|
137
|
+
try {
|
|
138
|
+
try {
|
|
139
|
+
await docker.getContainer(name).remove({ force: true });
|
|
140
|
+
} catch {
|
|
141
|
+
/* pas de conteneur précédent */
|
|
142
|
+
}
|
|
143
|
+
await mail.ensureNetwork(docker, config);
|
|
144
|
+
const container = await docker.createContainer(valkey.containerOptions(config, root, mail.onNetwork(config, valkey.ALIAS)));
|
|
145
|
+
await container.start();
|
|
146
|
+
for (let i = 0; ; i++) {
|
|
147
|
+
const exec = await container.exec({ Cmd: ['valkey-cli', 'ping'], AttachStdout: true, AttachStderr: true });
|
|
148
|
+
const out = await new Promise((resolve, reject) =>
|
|
149
|
+
exec.start({}, (err, stream) => {
|
|
150
|
+
if (err) return reject(err);
|
|
151
|
+
let data = '';
|
|
152
|
+
stream.on('data', (c) => (data += c.toString()));
|
|
153
|
+
stream.on('end', () => resolve(data));
|
|
154
|
+
})
|
|
155
|
+
);
|
|
156
|
+
if (out.includes('PONG')) break;
|
|
157
|
+
if (i > 30) throw new Error(`Valkey does not answer after 30 s (docker logs ${name})`);
|
|
158
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
159
|
+
}
|
|
160
|
+
progress.succeed(chalk.bold('Valkey started.'));
|
|
161
|
+
} catch (err) {
|
|
162
|
+
progress.fail(chalk.redBright(`Valkey failed to start: ${err.message}`));
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
console.log(' ');
|
|
167
|
+
console.log(
|
|
168
|
+
prettyoutput({
|
|
169
|
+
'Valkey URL': `redis://127.0.0.1:${config.valkey.port}`,
|
|
170
|
+
'From the engine': valkey.URL,
|
|
171
|
+
Data: path.relative(process.cwd(), valkey.dataDir(root)),
|
|
172
|
+
})
|
|
173
|
+
);
|
|
174
|
+
if (fresh) {
|
|
175
|
+
console.log(chalk.grey(' The engine gets REDIS_URL at its next start: run "poad stop" then "poad start".'));
|
|
176
|
+
console.log(' ');
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
};
|
package/global/start.js
CHANGED
|
@@ -9,20 +9,37 @@ module.exports = async (args) => {
|
|
|
9
9
|
const prettyoutput = require('prettyoutput');
|
|
10
10
|
const { findPoadDir } = require('../utils/findpoad');
|
|
11
11
|
const { isDockerExist } = require('../utils/docker');
|
|
12
|
-
const {
|
|
12
|
+
const { storageInfo, offerEngineUpgrade } = require('../utils/engine');
|
|
13
|
+
const { pullIfMissing } = require('../utils/pull');
|
|
14
|
+
const mail = require('../utils/mail');
|
|
15
|
+
const valkey = require('../utils/valkey');
|
|
13
16
|
const root = findPoadDir(process.cwd());
|
|
14
17
|
const config = toml.parse(await fs.readFile(root, 'utf-8'));
|
|
15
18
|
const containerName = config.project_uuid;
|
|
16
|
-
const minio = usesMinio(config);
|
|
17
19
|
console.log(' ');
|
|
18
20
|
if (await isDockerExist(containerName)) {
|
|
19
21
|
return console.log(chalk.bold('Container already started'));
|
|
20
22
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
config.engine = await offerEngineUpgrade(root, config, args);
|
|
24
|
+
const image = 'poadio/engine:' + config.engine;
|
|
25
|
+
// L'image de la version du projet n'est pas forcément là (poad install tire
|
|
26
|
+
// celle du CLI, et config.toml peut en demander une autre) : on la tire.
|
|
27
|
+
if (!(await pullIfMissing(docker, image))) return;
|
|
28
|
+
const mailpit = mail.usesMailpit(config);
|
|
29
|
+
if (mailpit && !mail.mailPort(config)) {
|
|
30
|
+
return console.log(chalk.redBright(`No [mail] port in ${root}: add a [mail] section with a free port.`));
|
|
31
|
+
}
|
|
32
|
+
if (mailpit && !(await pullIfMissing(docker, mail.MAILPIT_IMAGE))) return;
|
|
33
|
+
|
|
34
|
+
const progress = ora('Starting containers').start();
|
|
35
|
+
try {
|
|
36
|
+
// Réseau du projet : l'engine y joint Mailpit (« mail ») et Keycloak
|
|
37
|
+
await mail.ensureNetwork(docker, config);
|
|
38
|
+
if (mailpit) await mail.startMailpit(docker, config);
|
|
39
|
+
const net = mail.onNetwork(config, 'engine');
|
|
40
|
+
const container = await docker.createContainer({
|
|
24
41
|
name: containerName,
|
|
25
|
-
Image:
|
|
42
|
+
Image: image,
|
|
26
43
|
Tty: false,
|
|
27
44
|
Env: [
|
|
28
45
|
'OMNEEDIA_GATEWAY_URL=http://localhost:' + config.web.port,
|
|
@@ -35,48 +52,44 @@ module.exports = async (args) => {
|
|
|
35
52
|
'JWT_SECRET=' + config.auth.secret,
|
|
36
53
|
'ANON_KEY=' + config.auth.anon,
|
|
37
54
|
'SERVICE_ROLE_KEY=' + config.auth.service,
|
|
38
|
-
...(
|
|
39
|
-
|
|
40
|
-
'S3_ACCESS_KEY=' + config.s3.access_key,
|
|
41
|
-
'S3_SECRET_KEY=' + config.s3.secret_key,
|
|
42
|
-
'S3_REGION=local',
|
|
43
|
-
]
|
|
44
|
-
: []),
|
|
55
|
+
...mail.smtpEnv(config),
|
|
56
|
+
...valkey.engineEnv(config),
|
|
45
57
|
],
|
|
46
58
|
HostConfig: {
|
|
59
|
+
NetworkMode: net.NetworkMode,
|
|
47
60
|
PortBindings: {
|
|
48
61
|
'5432/tcp': [{ HostPort: config.db.port.toString() }],
|
|
49
62
|
'8000/tcp': [{ HostPort: config.web.port.toString() }],
|
|
50
|
-
...(minio
|
|
51
|
-
? { '9500/tcp': [{ HostPort: config.s3.port.toString() }] }
|
|
52
|
-
: {}),
|
|
53
|
-
'9000/tcp': [{ HostPort: config.inbucket.port.toString() }],
|
|
54
63
|
},
|
|
55
64
|
Binds: [path.dirname(root) + '/data:/data'],
|
|
65
|
+
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
66
|
+
// compris sous Linux
|
|
67
|
+
ExtraHosts: ['host.docker.internal:host-gateway'],
|
|
56
68
|
AutoRemove: true,
|
|
57
69
|
},
|
|
58
|
-
|
|
59
|
-
.then((container) => {
|
|
60
|
-
return container.start();
|
|
61
|
-
})
|
|
62
|
-
.then((container) => {
|
|
63
|
-
progress.succeed(chalk.bold('container started.'));
|
|
64
|
-
console.log(' ');
|
|
65
|
-
console.log(chalk.bold(' 🚀 Container started successfully'));
|
|
66
|
-
console.log(' ');
|
|
67
|
-
const info = {
|
|
68
|
-
'API URL': `http://localhost:${config.web.port}`,
|
|
69
|
-
'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
|
|
70
|
-
...storageInfo(config),
|
|
71
|
-
'Inbucket URL': `http://localhost:${config.inbucket.port}`,
|
|
72
|
-
'JWT secret': `${config.auth.secret}`,
|
|
73
|
-
'anon key': config.auth.anon,
|
|
74
|
-
'service_role key': config.auth.service,
|
|
75
|
-
};
|
|
76
|
-
console.log(prettyoutput(info));
|
|
77
|
-
})
|
|
78
|
-
.catch((err) => {
|
|
79
|
-
console.log(err);
|
|
80
|
-
progress.fail(chalk.redBright('Error: Container failed to start'));
|
|
70
|
+
NetworkingConfig: net.endpoint,
|
|
81
71
|
});
|
|
72
|
+
await container.start();
|
|
73
|
+
} catch (err) {
|
|
74
|
+
progress.fail(chalk.redBright(`Error: containers failed to start: ${err.message}`));
|
|
75
|
+
await mail.stopMailpit(docker, config);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
progress.succeed(chalk.bold('containers started.'));
|
|
79
|
+
if (valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
|
|
80
|
+
console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
|
|
81
|
+
}
|
|
82
|
+
console.log(' ');
|
|
83
|
+
console.log(chalk.bold(' 🚀 Container started successfully'));
|
|
84
|
+
console.log(' ');
|
|
85
|
+
const info = {
|
|
86
|
+
'API URL': `http://localhost:${config.web.port}`,
|
|
87
|
+
'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
|
|
88
|
+
...storageInfo(config),
|
|
89
|
+
...(mailpit ? { 'Mail URL': `http://localhost:${mail.mailPort(config)}` } : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
|
|
90
|
+
'JWT secret': `${config.auth.secret}`,
|
|
91
|
+
'anon key': config.auth.anon,
|
|
92
|
+
'service_role key': config.auth.service,
|
|
93
|
+
};
|
|
94
|
+
console.log(prettyoutput(info));
|
|
82
95
|
};
|
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
|
-
|
|
16
|
-
|
|
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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
package/project/info.js
CHANGED
|
@@ -19,7 +19,9 @@ module.exports = async (args) => {
|
|
|
19
19
|
'API URL': `http://localhost:${config.web.port}`,
|
|
20
20
|
'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
|
|
21
21
|
...storageInfo(config),
|
|
22
|
-
|
|
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}` }),
|
|
23
25
|
'JWT secret': `${config.auth.secret}`,
|
|
24
26
|
'anon key': config.auth.anon,
|
|
25
27
|
'service_role key': config.auth.service,
|
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 };
|
package/utils/valkey.js
ADDED
|
@@ -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 };
|