poad 2.16.1 → 2.18.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/run.js +47 -1
- package/global/start.js +3 -0
- package/global/stop.js +13 -0
- package/package.json +2 -2
- package/project/cli.js +1 -1
- package/project/kc.js +5 -1
- package/project/setup.js +22 -1
- package/utils/engine.js +14 -1
- package/utils/keycloak-shared.js +156 -0
- package/utils/keycloak.js +21 -1
- package/utils/report.js +4 -1
- package/utils/services.js +9 -6
package/global/run.js
CHANGED
|
@@ -77,7 +77,12 @@ module.exports = async (args = {}) => {
|
|
|
77
77
|
for (const service of targets) {
|
|
78
78
|
// --all (ou poad start) complète ce qui manque : un service déjà lancé
|
|
79
79
|
// n'est pas redémarré
|
|
80
|
-
|
|
80
|
+
// Keycloak partagé : il peut tourner pour un autre projet sans être rattaché à celui-ci
|
|
81
|
+
const running =
|
|
82
|
+
service.id === 'keycloak' && require('../utils/keycloak-shared').isShared(config)
|
|
83
|
+
? await require('../utils/keycloak-shared').attached(docker, config)
|
|
84
|
+
: (await containerState(docker, service.container(config))) === 'running';
|
|
85
|
+
if ((all || listed) && running) {
|
|
81
86
|
if (!quiet) console.log(`${chalk.greenBright('✔')} ${service.label} already running.`);
|
|
82
87
|
continue;
|
|
83
88
|
}
|
|
@@ -93,6 +98,8 @@ module.exports = async (args = {}) => {
|
|
|
93
98
|
return console.log(chalk.redBright(`Keycloak not started: ${err.message}`));
|
|
94
99
|
}
|
|
95
100
|
|
|
101
|
+
if (require('../utils/keycloak-shared').isShared(config)) return runSharedKeycloak();
|
|
102
|
+
|
|
96
103
|
// Port gardé d'un lancement à l'autre (l'émetteur des jetons en dépend)
|
|
97
104
|
let port = config.keycloak && Number(config.keycloak.port);
|
|
98
105
|
if (!port) {
|
|
@@ -183,6 +190,45 @@ module.exports = async (args = {}) => {
|
|
|
183
190
|
console.log(' ');
|
|
184
191
|
}
|
|
185
192
|
|
|
193
|
+
/** Keycloak partagé : un realm pour ce projet dans le conteneur commun */
|
|
194
|
+
async function runSharedKeycloak() {
|
|
195
|
+
const shared = require('../utils/keycloak-shared');
|
|
196
|
+
if (!(await pullIfMissing(docker, kc.IMAGE))) return;
|
|
197
|
+
const project = kc.loadProject(root, config);
|
|
198
|
+
const realm = shared.realmFor(config, project.realm);
|
|
199
|
+
const progress = ora('Starting Keycloak (shared)').start();
|
|
200
|
+
let state;
|
|
201
|
+
try {
|
|
202
|
+
state = await shared.ensureRunning(docker, kc.IMAGE);
|
|
203
|
+
await shared.connect(docker, config, kc.ALIAS);
|
|
204
|
+
// Le realm du projet, sous son nom dans le Keycloak partagé
|
|
205
|
+
await shared.importRealm(state, { ...kc.realmOf(config, project), realm });
|
|
206
|
+
kc.register(config, { ...project, realm });
|
|
207
|
+
await kc.enableUserAttributes(state.port, { admin_password: state.admin_password }, realm).catch(() => {});
|
|
208
|
+
progress.succeed(chalk.bold(`Keycloak started (shared, realm "${realm}").`));
|
|
209
|
+
} catch (err) {
|
|
210
|
+
progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (quiet) return;
|
|
214
|
+
console.log(' ');
|
|
215
|
+
const base = `http://localhost:${state.port}`;
|
|
216
|
+
console.log(
|
|
217
|
+
prettyoutput({
|
|
218
|
+
'Keycloak URL': `${base} (shared by the local projects)`,
|
|
219
|
+
Issuer: `${base}/realms/${realm}`,
|
|
220
|
+
'Admin console': `${base}/admin (admin ${state.admin_password})`,
|
|
221
|
+
Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
|
|
222
|
+
'Test users': project.users.map(
|
|
223
|
+
(u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
|
|
224
|
+
),
|
|
225
|
+
'Test set': path.relative(process.cwd(), project.fixturePath),
|
|
226
|
+
})
|
|
227
|
+
);
|
|
228
|
+
console.log(chalk.grey(` The realm is re-imported from ${path.relative(process.cwd(), project.fixturePath)} on each run: "poad kc export" saves changes made in the admin console.`));
|
|
229
|
+
console.log(' ');
|
|
230
|
+
}
|
|
231
|
+
|
|
186
232
|
async function runValkey() {
|
|
187
233
|
const fresh = !valkey.enabled(config);
|
|
188
234
|
if (fresh) {
|
package/global/start.js
CHANGED
|
@@ -70,9 +70,12 @@ module.exports = async (args = {}) => {
|
|
|
70
70
|
Image: image,
|
|
71
71
|
Tty: false,
|
|
72
72
|
Env: [
|
|
73
|
+
// Noms POAD_* depuis l'engine 0.9.0 ; OMNEEDIA_* pour les plus anciens
|
|
74
|
+
'POAD_GATEWAY_URL=http://localhost:' + config.web.port,
|
|
73
75
|
'OMNEEDIA_GATEWAY_URL=http://localhost:' + config.web.port,
|
|
74
76
|
// Projet local : le service auth accepte les redirections vers
|
|
75
77
|
// http://localhost:* (désactivé par défaut, hors du CLI)
|
|
78
|
+
'POAD_AUTH_ALLOW_LOCALHOST_REDIRECTS=true',
|
|
76
79
|
'OMNEEDIA_AUTH_ALLOW_LOCALHOST_REDIRECTS=true',
|
|
77
80
|
'DATA_VOLUME_MOUNTPOINT=/data',
|
|
78
81
|
// Projet local : journaux détaillés (SQL, requêtes lentes dès 100 ms).
|
package/global/stop.js
CHANGED
|
@@ -20,6 +20,19 @@ module.exports = async (args) => {
|
|
|
20
20
|
console.log(' ');
|
|
21
21
|
|
|
22
22
|
const stopKeycloak = async () => {
|
|
23
|
+
const shared = require('../utils/keycloak-shared');
|
|
24
|
+
if (shared.isShared(config)) {
|
|
25
|
+
// Keycloak partagé : on retire le realm du projet et on le détache ; le
|
|
26
|
+
// conteneur s'arrête quand plus aucun projet ne l'utilise
|
|
27
|
+
if (!(await shared.attached(docker, config))) return false;
|
|
28
|
+
const progress = ora('Releasing the shared Keycloak').start();
|
|
29
|
+
kc.unregister(config);
|
|
30
|
+
const project = kc.loadProject(root, config, { create: false });
|
|
31
|
+
await shared.release(docker, config, project && shared.realmFor(config, project.realm));
|
|
32
|
+
const left = await shared.projects(docker);
|
|
33
|
+
progress.succeed(chalk.bold(left.length ? `Keycloak released (still used by ${left.length} other project(s))` : 'Keycloak stopped (no project uses it any more)'));
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
23
36
|
const name = kc.containerName(config);
|
|
24
37
|
if (!(await isDockerExist(name))) return false;
|
|
25
38
|
const progress = ora('Stopping Keycloak').start();
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
module.exports = {
|
|
10
10
|
info: `Information about your project`,
|
|
11
11
|
kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
|
|
12
|
-
setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, --all, --none, --list)',
|
|
12
|
+
setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, kc=shared|own, --all, --none, --list)',
|
|
13
13
|
db: {
|
|
14
14
|
description: 'Local database: db reset (erase, migrate, seed), db seed (apply poad/seed.sql)',
|
|
15
15
|
reset: 'Erase the database and storage files, restart, apply migrations then poad/seed.sql (--yes outside a terminal)',
|
package/project/kc.js
CHANGED
|
@@ -17,7 +17,11 @@ module.exports = async (args = {}) => {
|
|
|
17
17
|
console.log(' ');
|
|
18
18
|
|
|
19
19
|
if (args.export) {
|
|
20
|
-
|
|
20
|
+
const shared = require('../utils/keycloak-shared');
|
|
21
|
+
const up = shared.isShared(config)
|
|
22
|
+
? await shared.attached(new Docker(), config)
|
|
23
|
+
: config.keycloak && config.keycloak.port && (await containerState(new Docker(), kc.containerName(config))) === 'running';
|
|
24
|
+
if (!up) {
|
|
21
25
|
return console.log(chalk.redBright('Keycloak is not running: "poad run kc" first.'));
|
|
22
26
|
}
|
|
23
27
|
try {
|
package/project/setup.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
//
|
|
3
3
|
// poad setup interactif (terminal) : e-mails, services, migrations
|
|
4
4
|
// poad setup kc=on valkey=off non interactif : ne change que ce qui est cité
|
|
5
|
+
// poad setup kc=shared | kc=own Keycloak commun aux projets locaux (un conteneur,
|
|
6
|
+
// un realm par projet), ou propre au projet
|
|
5
7
|
// poad setup --all | --none tous les services optionnels en autostart, ou aucun
|
|
6
8
|
// poad setup mail=smtp smtp.host=smtp.example.com smtp.port=587 smtp.user=apikey smtp.pass=…
|
|
7
9
|
// poad setup mail=mailpit revient à Mailpit (e-mails capturés en local)
|
|
@@ -82,7 +84,11 @@ module.exports = async (args = {}) => {
|
|
|
82
84
|
if (has('none')) for (const s of optional) wish.services[s.id] = false;
|
|
83
85
|
for (const k of keys) {
|
|
84
86
|
const v = args[k];
|
|
85
|
-
if (ALIASES[k]) {
|
|
87
|
+
if (ALIASES[k] === 'keycloak' && ['shared', 'own', 'project'].includes(String(v).toLowerCase())) {
|
|
88
|
+
// kc=shared : un Keycloak commun aux projets locaux ; kc=own : le sien
|
|
89
|
+
wish.services.keycloak = true;
|
|
90
|
+
wish.kcShared = String(v).toLowerCase() === 'shared';
|
|
91
|
+
} else if (ALIASES[k]) {
|
|
86
92
|
const f = flag(v);
|
|
87
93
|
if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
|
|
88
94
|
wish.services[ALIASES[k]] = f;
|
|
@@ -154,6 +160,20 @@ module.exports = async (args = {}) => {
|
|
|
154
160
|
|
|
155
161
|
// ------------------------------------------------------------ écriture
|
|
156
162
|
const changes = [];
|
|
163
|
+
// Mode de Keycloak (partagé ou propre au projet) : s'il tourne, il est
|
|
164
|
+
// arrêté dans l'ancien mode puis relancé dans le nouveau
|
|
165
|
+
const shared = require('../utils/keycloak-shared');
|
|
166
|
+
let restartKc = false;
|
|
167
|
+
if (wish.kcShared !== undefined && wish.kcShared !== shared.isShared(config)) {
|
|
168
|
+
const Docker = require('dockerode');
|
|
169
|
+
const docker = new Docker();
|
|
170
|
+
const { containerState } = require('../utils/services');
|
|
171
|
+
restartKc = shared.isShared(config) ? await shared.attached(docker, config) : (await containerState(docker, require('../utils/keycloak').containerName(config))) === 'running';
|
|
172
|
+
if (restartKc) await require('../global/stop')({ kc: true });
|
|
173
|
+
setKeys(root, 'keycloak', { shared: wish.kcShared });
|
|
174
|
+
changes.push(`Keycloak: ${wish.kcShared ? 'shared by the local projects (one container, one realm per project)' : 'own container for this project'}`);
|
|
175
|
+
config = loadConfig(root);
|
|
176
|
+
}
|
|
157
177
|
for (const [id, on] of Object.entries(wish.services)) {
|
|
158
178
|
const s = optional.find((x) => x.id === id);
|
|
159
179
|
if (on === before.services[id]) continue;
|
|
@@ -207,6 +227,7 @@ module.exports = async (args = {}) => {
|
|
|
207
227
|
}
|
|
208
228
|
for (const c of changes) console.log(`${chalk.greenBright('✔')} ${c}`);
|
|
209
229
|
console.log(' ');
|
|
230
|
+
if (restartKc) await require('../global/run')({ services: ['keycloak'] });
|
|
210
231
|
summary();
|
|
211
232
|
|
|
212
233
|
// ------------------------------------------------------------ projet lancé
|
package/utils/engine.js
CHANGED
|
@@ -29,15 +29,28 @@ const supportsData = (config) => {
|
|
|
29
29
|
return major > 0 || minor >= 8;
|
|
30
30
|
};
|
|
31
31
|
|
|
32
|
+
// Engine 0.10.0 et plus : temps réel (/realtime/v1) et API d'administration (/meta/v1)
|
|
33
|
+
const supportsRealtime = (config) => {
|
|
34
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
35
|
+
return major > 0 || minor >= 10;
|
|
36
|
+
};
|
|
37
|
+
|
|
32
38
|
const dataInfo = (config) =>
|
|
33
39
|
supportsData(config)
|
|
34
40
|
? {
|
|
35
41
|
'REST URL': `http://localhost:${config.web.port}/rest/v1`,
|
|
36
42
|
'API docs': `http://localhost:${config.web.port}/rest/v1/docs#apikey=${config.auth.anon}`,
|
|
43
|
+
...(supportsRealtime(config)
|
|
44
|
+
? {
|
|
45
|
+
'Realtime URL': `ws://localhost:${config.web.port}/realtime/v1/websocket`,
|
|
46
|
+
'Admin API': `http://localhost:${config.web.port}/meta/v1 (service_role key)`,
|
|
47
|
+
'Admin API docs': `http://localhost:${config.web.port}/meta/v1/docs#apikey=${config.auth.service}`,
|
|
48
|
+
}
|
|
49
|
+
: {}),
|
|
37
50
|
}
|
|
38
51
|
: {};
|
|
39
52
|
|
|
40
|
-
module.exports = { usesMinio, storageInfo, supportsData, dataInfo };
|
|
53
|
+
module.exports = { usesMinio, storageInfo, supportsData, supportsRealtime, dataInfo };
|
|
41
54
|
|
|
42
55
|
// Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
|
|
43
56
|
// à jour `engine` dans config.toml. La mise à jour migre poad/data : le projet
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// Keycloak partagé entre les projets locaux (option : [keycloak] shared = true,
|
|
2
|
+
// `poad setup kc=shared`). Un seul conteneur, poad-keycloak-shared, au lieu
|
|
3
|
+
// d'un par projet : Keycloak (Java) pèse 0,5 à 0,7 Go.
|
|
4
|
+
//
|
|
5
|
+
// - port et mot de passe d'administration : ~/.poad/keycloak-shared.json ;
|
|
6
|
+
// - un realm par projet, « <realm du projet>-<6 premiers caractères de son
|
|
7
|
+
// uuid> » (deux projets peuvent avoir le même realm dans keycloak.json),
|
|
8
|
+
// importé par l'API d'administration à chaque `poad run kc` ;
|
|
9
|
+
// - le conteneur est rattaché au réseau de chaque projet qui l'utilise, sous
|
|
10
|
+
// le nom « keycloak » : l'engine le joint comme un Keycloak du projet ;
|
|
11
|
+
// - `poad stop kc` (ou `poad stop`) retire le realm du projet et le détache ;
|
|
12
|
+
// le conteneur s'arrête quand plus aucun projet ne l'utilise.
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const crypto = require('crypto');
|
|
17
|
+
|
|
18
|
+
const NAME = 'poad-keycloak-shared';
|
|
19
|
+
const STATE = path.join(os.homedir(), '.poad', 'keycloak-shared.json');
|
|
20
|
+
const ALNUM = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
|
|
21
|
+
|
|
22
|
+
const isShared = (config) => Boolean(config.keycloak && config.keycloak.shared === true);
|
|
23
|
+
|
|
24
|
+
/** Realm du projet dans le Keycloak partagé */
|
|
25
|
+
const realmFor = (config, projectRealm) => `${projectRealm}-${String(config.project_uuid).slice(0, 6).toLowerCase()}`;
|
|
26
|
+
|
|
27
|
+
const readState = () => {
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(fs.readFileSync(STATE, 'utf-8'));
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Port et mot de passe d'administration, choisis une fois pour la machine */
|
|
36
|
+
async function ensureState() {
|
|
37
|
+
const state = readState();
|
|
38
|
+
if (state && state.port && state.admin_password) return state;
|
|
39
|
+
const { findFreePorts } = require('./ports');
|
|
40
|
+
const [port] = await findFreePorts(1);
|
|
41
|
+
const next = { port, admin_password: Array.from({ length: 16 }, () => ALNUM[crypto.randomInt(ALNUM.length)]).join('') };
|
|
42
|
+
fs.mkdirSync(path.dirname(STATE), { recursive: true });
|
|
43
|
+
fs.writeFileSync(STATE, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
|
|
44
|
+
return next;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const inspect = async (docker) => {
|
|
48
|
+
try {
|
|
49
|
+
return await docker.getContainer(NAME).inspect();
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** Le conteneur partagé tourne-t-il, et ce projet y est-il rattaché ? */
|
|
56
|
+
async function attached(docker, config) {
|
|
57
|
+
const info = await inspect(docker);
|
|
58
|
+
if (!info || !info.State.Running) return false;
|
|
59
|
+
const { networkName } = require('./mail');
|
|
60
|
+
return Object.keys(info.NetworkSettings.Networks || {}).includes(networkName(config));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Démarre le conteneur partagé s'il ne tourne pas ; renvoie l'état (port, mot de passe) */
|
|
64
|
+
async function ensureRunning(docker, image) {
|
|
65
|
+
const state = await ensureState();
|
|
66
|
+
const info = await inspect(docker);
|
|
67
|
+
if (info && info.State.Running) return state;
|
|
68
|
+
if (info) await docker.getContainer(NAME).remove({ force: true }).catch(() => {});
|
|
69
|
+
const container = await docker.createContainer({
|
|
70
|
+
name: NAME,
|
|
71
|
+
Image: image,
|
|
72
|
+
Env: ['KC_BOOTSTRAP_ADMIN_USERNAME=admin', `KC_BOOTSTRAP_ADMIN_PASSWORD=${state.admin_password}`],
|
|
73
|
+
// Émetteur http://localhost:<port> pour le navigateur ; l'engine passe
|
|
74
|
+
// par le réseau du projet (keycloak:8080), d'où le backchannel dynamique
|
|
75
|
+
Cmd: ['start-dev', `--hostname=http://localhost:${state.port}`, '--hostname-backchannel-dynamic=true'],
|
|
76
|
+
ExposedPorts: { '8080/tcp': {} },
|
|
77
|
+
Labels: { 'io.poad.service': 'keycloak-shared' },
|
|
78
|
+
HostConfig: {
|
|
79
|
+
PortBindings: { '8080/tcp': [{ HostPort: String(state.port) }] },
|
|
80
|
+
AutoRemove: true,
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
await container.start();
|
|
84
|
+
for (let i = 0; ; i++) {
|
|
85
|
+
const ok = await fetch(`http://localhost:${state.port}/realms/master`).then(
|
|
86
|
+
(r) => r.ok,
|
|
87
|
+
() => false
|
|
88
|
+
);
|
|
89
|
+
if (ok) break;
|
|
90
|
+
if (i > 120) throw new Error(`shared Keycloak does not answer after 120 s (docker logs ${NAME})`);
|
|
91
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
92
|
+
}
|
|
93
|
+
return state;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Rattache le conteneur au réseau du projet, sous le nom « keycloak » */
|
|
97
|
+
async function connect(docker, config, alias) {
|
|
98
|
+
const { networkName, ensureNetwork } = require('./mail');
|
|
99
|
+
await ensureNetwork(docker, config);
|
|
100
|
+
try {
|
|
101
|
+
await docker.getNetwork(networkName(config)).connect({ Container: NAME, EndpointConfig: { Aliases: [alias] } });
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (!/already exists|is already connected/i.test(String(err.message))) throw err;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const adminToken = async (state) => {
|
|
108
|
+
const body = new URLSearchParams({ grant_type: 'password', client_id: 'admin-cli', username: 'admin', password: state.admin_password });
|
|
109
|
+
const res = await fetch(`http://localhost:${state.port}/realms/master/protocol/openid-connect/token`, { method: 'POST', body });
|
|
110
|
+
if (!res.ok) throw new Error(`shared Keycloak admin login refused (${res.status})`);
|
|
111
|
+
return (await res.json()).access_token;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** (Ré)importe le realm du projet : supprimé s'il existe, puis créé tel que décrit */
|
|
115
|
+
async function importRealm(state, representation) {
|
|
116
|
+
const token = await adminToken(state);
|
|
117
|
+
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
|
|
118
|
+
const url = `http://localhost:${state.port}/admin/realms`;
|
|
119
|
+
const del = await fetch(`${url}/${encodeURIComponent(representation.realm)}`, { method: 'DELETE', headers });
|
|
120
|
+
if (!del.ok && del.status !== 404) throw new Error(`realm ${representation.realm}: delete ${del.status}`);
|
|
121
|
+
const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(representation) });
|
|
122
|
+
if (!res.ok) throw new Error(`realm ${representation.realm}: import ${res.status} ${(await res.text()).slice(0, 200)}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Détache le projet : son realm est supprimé, le conteneur quitte son réseau,
|
|
127
|
+
* et s'arrête s'il ne sert plus aucun projet. Renvoie false s'il n'y était pas.
|
|
128
|
+
*/
|
|
129
|
+
async function release(docker, config, realm) {
|
|
130
|
+
if (!(await attached(docker, config))) return false;
|
|
131
|
+
const state = readState();
|
|
132
|
+
if (state && realm) {
|
|
133
|
+
try {
|
|
134
|
+
const token = await adminToken(state);
|
|
135
|
+
await fetch(`http://localhost:${state.port}/admin/realms/${encodeURIComponent(realm)}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
|
|
136
|
+
} catch {
|
|
137
|
+
/* realm laissé : il sera remplacé au prochain import */
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const { networkName } = require('./mail');
|
|
141
|
+
await docker.getNetwork(networkName(config)).disconnect({ Container: NAME, Force: true }).catch(() => {});
|
|
142
|
+
const info = await inspect(docker);
|
|
143
|
+
// Plus aucun réseau de projet : seul le réseau par défaut reste
|
|
144
|
+
const left = Object.keys((info && info.NetworkSettings.Networks) || {}).filter((n) => n !== 'bridge');
|
|
145
|
+
if (info && !left.length) await docker.getContainer(NAME).remove({ force: true }).catch(() => {});
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Projets rattachés (noms de réseaux), pour l'affichage */
|
|
150
|
+
async function projects(docker) {
|
|
151
|
+
const info = await inspect(docker);
|
|
152
|
+
if (!info || !info.State.Running) return [];
|
|
153
|
+
return Object.keys(info.NetworkSettings.Networks || {}).filter((n) => n !== 'bridge');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = { NAME, STATE, isShared, realmFor, readState, ensureState, attached, ensureRunning, connect, importRealm, release, projects };
|
package/utils/keycloak.js
CHANGED
|
@@ -50,6 +50,20 @@ const slug = (s) =>
|
|
|
50
50
|
.replace(/^-+|-+$/g, '') || 'poad';
|
|
51
51
|
const realmName = (config, fixture) => (fixture && fixture.realm) || slug(config.project_id);
|
|
52
52
|
|
|
53
|
+
/** Realm qui tourne : celui du projet, suffixé dans le Keycloak partagé */
|
|
54
|
+
const runningRealm = (config, realm) => (require('./keycloak-shared').isShared(config) ? require('./keycloak-shared').realmFor(config, realm) : realm);
|
|
55
|
+
|
|
56
|
+
/** Port et mot de passe d'administration du Keycloak qui sert ce projet */
|
|
57
|
+
const adminEndpoint = (config, secrets) => {
|
|
58
|
+
const shared = require('./keycloak-shared');
|
|
59
|
+
if (shared.isShared(config)) {
|
|
60
|
+
const state = shared.readState();
|
|
61
|
+
if (!state) throw new Error('shared Keycloak not set up: "poad run kc" first');
|
|
62
|
+
return { port: state.port, secrets: { ...secrets, admin_password: state.admin_password } };
|
|
63
|
+
}
|
|
64
|
+
return { port: config.keycloak.port, secrets };
|
|
65
|
+
};
|
|
66
|
+
|
|
53
67
|
/**
|
|
54
68
|
* Mot de passe à recopier : lettres et chiffres seulement. Un « - » ou un
|
|
55
69
|
* « _ » coupe la sélection au double-clic dans un terminal, et le mot de
|
|
@@ -326,6 +340,8 @@ const enableUserAttributes = async (port, secrets, realm) => {
|
|
|
326
340
|
*/
|
|
327
341
|
const adoptRunningIds = async (root, config) => {
|
|
328
342
|
const secretsFile = path.join(dataDir(root), 'users.json');
|
|
343
|
+
// Reprise des anciens Keycloak du projet seulement (le partagé est récent)
|
|
344
|
+
if (require('./keycloak-shared').isShared(config)) return 0;
|
|
329
345
|
if (!fs.existsSync(secretsFile) || !(config.keycloak && config.keycloak.port)) return 0;
|
|
330
346
|
const secrets = JSON.parse(fs.readFileSync(secretsFile, 'utf-8'));
|
|
331
347
|
if (!secrets.admin_password) return 0;
|
|
@@ -359,7 +375,8 @@ const adoptRunningIds = async (root, config) => {
|
|
|
359
375
|
*/
|
|
360
376
|
const exportRealm = async (root, config) => {
|
|
361
377
|
const project = loadProject(root, config);
|
|
362
|
-
const
|
|
378
|
+
const { port, secrets } = adminEndpoint(config, project.secrets);
|
|
379
|
+
const running = await readRunningRealm(port, secrets, runningRealm(config, project.realm));
|
|
363
380
|
const known = Object.fromEntries((project.fixture.users || []).map((u) => [u.username, u]));
|
|
364
381
|
const fresh = [];
|
|
365
382
|
const users = running.users.map((u) => {
|
|
@@ -374,6 +391,7 @@ const exportRealm = async (root, config) => {
|
|
|
374
391
|
const { id, ...rest } = u;
|
|
375
392
|
return { ...rest, password };
|
|
376
393
|
});
|
|
394
|
+
// Le fichier garde le nom du realm du projet (sans le suffixe du mode partagé)
|
|
377
395
|
const fixture = { ...project.fixture, realm: project.realm, roles: running.roles, groups: running.groups, users };
|
|
378
396
|
writeJson(project.fixturePath, fixture);
|
|
379
397
|
writeJson(project.secretsFile, project.secrets, 0o600);
|
|
@@ -424,6 +442,8 @@ const unregister = (config) => {
|
|
|
424
442
|
};
|
|
425
443
|
|
|
426
444
|
module.exports = {
|
|
445
|
+
runningRealm,
|
|
446
|
+
adminEndpoint,
|
|
427
447
|
IMAGE,
|
|
428
448
|
PROVIDER,
|
|
429
449
|
NAMES,
|
package/utils/report.js
CHANGED
|
@@ -56,7 +56,10 @@ async function printServices(root, config) {
|
|
|
56
56
|
const configured = s.configured(config);
|
|
57
57
|
if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
|
|
58
58
|
const state = configured ? await containerState(docker, s.container(config)) : null;
|
|
59
|
-
|
|
59
|
+
// Keycloak partagé : il peut tourner pour un autre projet sans servir celui-ci
|
|
60
|
+
const sharedKc = s.id === 'keycloak' && require('./keycloak-shared').isShared(config);
|
|
61
|
+
const running = sharedKc ? await require('./keycloak-shared').attached(docker, config) : state === 'running';
|
|
62
|
+
rows.push({ s, configured, running, auto: configured && s.optional && s.autostart(config) });
|
|
60
63
|
}
|
|
61
64
|
if (!rows.length) return;
|
|
62
65
|
|
package/utils/services.js
CHANGED
|
@@ -30,19 +30,22 @@ const SERVICES = [
|
|
|
30
30
|
names: kc.NAMES,
|
|
31
31
|
cmd: 'kc',
|
|
32
32
|
section: 'keycloak',
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
// Keycloak partagé ([keycloak] shared = true) : un conteneur pour tous les projets
|
|
34
|
+
container: (config) => (require('./keycloak-shared').isShared(config) ? require('./keycloak-shared').NAME : kc.containerName(config)),
|
|
35
|
+
configured: (config) => Boolean(config.keycloak && (config.keycloak.port || config.keycloak.shared === true)),
|
|
35
36
|
autostart: (config) => Boolean(config.keycloak && config.keycloak.autostart === true),
|
|
36
37
|
savePort: (root, port) => kc.savePort(root, port),
|
|
37
38
|
info: (config, root) => {
|
|
38
|
-
const
|
|
39
|
+
const shared = require('./keycloak-shared');
|
|
40
|
+
const state = shared.isShared(config) ? shared.readState() : null;
|
|
41
|
+
const base = `http://localhost:${state ? state.port : config.keycloak.port}`;
|
|
39
42
|
// Lecture seule : rien n'est créé tant que `poad run kc` n'a pas tourné
|
|
40
43
|
const project = root ? kc.loadProject(root, config, { create: false }) : null;
|
|
41
|
-
const realm = project ? project.realm : kc.realmName(config);
|
|
42
|
-
const out = { URL: base, Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
|
|
44
|
+
const realm = kc.runningRealm(config, project ? project.realm : kc.realmName(config));
|
|
45
|
+
const out = { URL: base + (state ? ' (shared by the local projects)' : ''), Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
|
|
43
46
|
if (project) {
|
|
44
47
|
// Deux realms, deux usages : ne pas essayer alice sur la console d'admin
|
|
45
|
-
out['Admin console'] = [`${base}/admin`, `admin ${project.secrets.admin_password}`];
|
|
48
|
+
out['Admin console'] = [`${base}/admin`, `admin ${state ? state.admin_password : project.secrets.admin_password}`];
|
|
46
49
|
out['Test users'] = [
|
|
47
50
|
`realm "${realm}" : "Continuer avec Keycloak" in the app, or ${base}/realms/${realm}/account`,
|
|
48
51
|
...project.users.map(
|