poad 2.10.2 → 2.12.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/init.js +32 -47
- package/global/run.js +26 -16
- package/global/start.js +22 -1
- package/global/stop.js +2 -1
- package/package.json +3 -2
- package/project/cli.js +3 -0
- package/project/info.js +17 -1
- package/project/kc.js +47 -0
- package/project/migrate.js +16 -0
- package/project/migration.js +62 -0
- package/utils/config.js +111 -0
- package/utils/keycloak.js +317 -80
- package/utils/migrate-run.js +40 -0
- package/utils/migrations.js +189 -0
- package/utils/services.js +13 -21
package/global/init.js
CHANGED
|
@@ -1,56 +1,41 @@
|
|
|
1
|
-
|
|
1
|
+
// poad init : crée le dossier poad/ du projet
|
|
2
|
+
// poad/config.toml ports, engine, services : versionné
|
|
3
|
+
// poad/secrets.toml secret JWT et clés : propre à la machine, hors git
|
|
4
|
+
// poad/migrations/ schéma de la base, appliqué par poad start / poad migrate
|
|
5
|
+
// poad/.gitignore data/ et secrets.toml
|
|
6
|
+
// poad/data/ base et fichiers du projet local, hors git
|
|
7
|
+
module.exports = async () => {
|
|
2
8
|
const path = require('path');
|
|
3
|
-
const
|
|
9
|
+
const fs = require('fs');
|
|
4
10
|
const { findFreePorts } = require('../utils/ports');
|
|
5
|
-
const { generateSecret } = require('../utils/jwtkey');
|
|
6
11
|
const json2toml = require('json2toml');
|
|
7
|
-
const fs = require('fs').promises;
|
|
8
12
|
const generateUniqueId = require('generate-unique-id');
|
|
9
13
|
const chalk = require('chalk-v2');
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
};
|
|
18
|
-
const admin = {
|
|
19
|
-
role: 'admin',
|
|
20
|
-
iss: 'poad',
|
|
21
|
-
};
|
|
22
|
-
let config = {};
|
|
23
|
-
config.project_id = path.basename(process.cwd());
|
|
24
|
-
config.project_uuid = generateUniqueId();
|
|
25
|
-
await fs.mkdir(path.join(process.cwd(), 'poad', 'data'), { recursive: true });
|
|
14
|
+
const { generateSecrets, writeSecrets, ensureGitignore } = require('../utils/config');
|
|
15
|
+
const migrations = require('../utils/migrations');
|
|
16
|
+
|
|
17
|
+
const dir = path.join(process.cwd(), 'poad');
|
|
18
|
+
const root = path.join(dir, 'config.toml');
|
|
19
|
+
if (fs.existsSync(root)) return console.log(chalk.bold('\n ✅ Your project has already been initialized'));
|
|
20
|
+
|
|
21
|
+
fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
|
|
26
22
|
const ports = await findFreePorts(3);
|
|
27
|
-
config
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
port: ports[1],
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
port: ports[2],
|
|
37
|
-
};
|
|
38
|
-
const key = generateSecret();
|
|
39
|
-
config.auth = {
|
|
40
|
-
jwt_expiry: 3600,
|
|
41
|
-
secret: key,
|
|
42
|
-
anon: jwt.sign(anon, key),
|
|
43
|
-
service: jwt.sign(service, key),
|
|
44
|
-
admin: jwt.sign(admin, key),
|
|
23
|
+
const config = {
|
|
24
|
+
project_id: path.basename(process.cwd()),
|
|
25
|
+
project_uuid: generateUniqueId(),
|
|
26
|
+
engine: global.package.engine,
|
|
27
|
+
db: { port: ports[0] },
|
|
28
|
+
web: { port: ports[1] },
|
|
29
|
+
// Interface web de Mailpit (e-mails du projet local)
|
|
30
|
+
mail: { port: ports[2] },
|
|
31
|
+
auth: { jwt_expiry: 3600 },
|
|
45
32
|
};
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
chalk.bold('\n ✅ Your project has already been initialized')
|
|
53
|
-
);
|
|
54
|
-
await fs.writeFile(path.join(process.cwd(), 'poad', 'config.toml'), toml);
|
|
33
|
+
fs.writeFileSync(root, json2toml(config));
|
|
34
|
+
writeSecrets(root, generateSecrets());
|
|
35
|
+
ensureGitignore(root);
|
|
36
|
+
fs.mkdirSync(migrations.dir(root), { recursive: true });
|
|
37
|
+
fs.writeFileSync(path.join(migrations.dir(root), '.gitkeep'), '');
|
|
38
|
+
|
|
55
39
|
console.log(chalk.bold('\n ✅ Your project has been initialized'));
|
|
40
|
+
console.log(chalk.grey(' poad/config.toml and poad/migrations/ are versioned; poad/secrets.toml and poad/data/ stay on this machine.'));
|
|
56
41
|
};
|
package/global/run.js
CHANGED
|
@@ -37,8 +37,8 @@ module.exports = async (args = {}) => {
|
|
|
37
37
|
|
|
38
38
|
const root = findPoadDir(process.cwd());
|
|
39
39
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
40
|
-
const readConfig = () =>
|
|
41
|
-
let config = readConfig();
|
|
40
|
+
const readConfig = () => require('../utils/config').loadConfig(root);
|
|
41
|
+
let config = require('../utils/config').readConfig(root);
|
|
42
42
|
|
|
43
43
|
if (!(await isDockerExist(config.project_uuid))) {
|
|
44
44
|
if (!all) return console.log(chalk.redBright('The project is not started: run "poad start" first (or "poad run --all").'));
|
|
@@ -101,16 +101,19 @@ module.exports = async (args = {}) => {
|
|
|
101
101
|
|
|
102
102
|
if (!(await pullIfMissing(docker, kc.IMAGE))) return;
|
|
103
103
|
|
|
104
|
-
|
|
105
|
-
|
|
104
|
+
// Identifiants des utilisateurs du Keycloak qui tourne (projets antérieurs),
|
|
105
|
+
// puis jeu de test du projet (poad/keycloak.json) et secrets (data/keycloak)
|
|
106
|
+
await kc.adoptRunningIds(root, config);
|
|
107
|
+
const project = kc.loadProject(root, config);
|
|
108
|
+
const { secrets } = project;
|
|
106
109
|
// Dossier à part : Keycloak importe tous les fichiers JSON qu'il y trouve
|
|
107
|
-
const importDir = path.join(
|
|
110
|
+
const importDir = path.join(kc.dataDir(root), 'import');
|
|
108
111
|
fs.mkdirSync(importDir, { recursive: true });
|
|
109
112
|
fs.chmodSync(importDir, 0o755);
|
|
110
|
-
fs.
|
|
111
|
-
|
|
112
|
-
});
|
|
113
|
-
fs.chmodSync(
|
|
113
|
+
for (const old of fs.readdirSync(importDir)) fs.rmSync(path.join(importDir, old));
|
|
114
|
+
const realmFile = path.join(importDir, `${project.realm}-realm.json`);
|
|
115
|
+
fs.writeFileSync(realmFile, JSON.stringify(kc.realmOf(config, project), null, 2) + '\n', { mode: 0o644 });
|
|
116
|
+
fs.chmodSync(realmFile, 0o644);
|
|
114
117
|
|
|
115
118
|
const name = kc.containerName(config);
|
|
116
119
|
const progress = ora('Starting Keycloak').start();
|
|
@@ -139,7 +142,7 @@ module.exports = async (args = {}) => {
|
|
|
139
142
|
});
|
|
140
143
|
await container.start();
|
|
141
144
|
|
|
142
|
-
const issuer = `http://localhost:${port}/realms/${
|
|
145
|
+
const issuer = `http://localhost:${port}/realms/${project.realm}`;
|
|
143
146
|
for (let i = 0; ; i++) {
|
|
144
147
|
const ok = await fetch(`${issuer}/.well-known/openid-configuration`).then(
|
|
145
148
|
(r) => r.ok,
|
|
@@ -149,7 +152,10 @@ module.exports = async (args = {}) => {
|
|
|
149
152
|
if (i > 120) throw new Error(`Keycloak does not answer after 120 s (docker logs ${name})`);
|
|
150
153
|
await new Promise((r) => setTimeout(r, 1000));
|
|
151
154
|
}
|
|
152
|
-
kc.register(config,
|
|
155
|
+
kc.register(config, project);
|
|
156
|
+
await kc.enableUserAttributes(port, secrets, project.realm).catch(() => {
|
|
157
|
+
/* sans effet sur la connexion : seuls les attributs ajoutés dans la console seraient perdus */
|
|
158
|
+
});
|
|
153
159
|
progress.succeed(chalk.bold('Keycloak started.'));
|
|
154
160
|
} catch (err) {
|
|
155
161
|
progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
|
|
@@ -157,15 +163,19 @@ module.exports = async (args = {}) => {
|
|
|
157
163
|
}
|
|
158
164
|
|
|
159
165
|
console.log(' ');
|
|
166
|
+
const base = `http://localhost:${port}`;
|
|
160
167
|
const info = {
|
|
161
|
-
'Keycloak URL':
|
|
162
|
-
Issuer:
|
|
163
|
-
'Admin console':
|
|
168
|
+
'Keycloak URL': base,
|
|
169
|
+
Issuer: `${base}/realms/${project.realm}`,
|
|
170
|
+
'Admin console': `${base}/admin (admin ${secrets.admin_password})`,
|
|
164
171
|
Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
|
|
165
|
-
'Test users':
|
|
172
|
+
'Test users': project.users.map(
|
|
173
|
+
(u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
|
|
174
|
+
),
|
|
175
|
+
'Test set': path.relative(process.cwd(), project.fixturePath),
|
|
166
176
|
};
|
|
167
177
|
console.log(prettyoutput(info));
|
|
168
|
-
console.log(chalk.grey(` The realm is re-imported on each run: changes made in the admin console
|
|
178
|
+
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.`));
|
|
169
179
|
console.log(' ');
|
|
170
180
|
}
|
|
171
181
|
|
package/global/start.js
CHANGED
|
@@ -16,7 +16,8 @@ module.exports = async (args = {}) => {
|
|
|
16
16
|
const mail = require('../utils/mail');
|
|
17
17
|
const valkey = require('../utils/valkey');
|
|
18
18
|
const root = findPoadDir(process.cwd());
|
|
19
|
-
|
|
19
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
20
|
+
const config = require('../utils/config').readConfig(root);
|
|
20
21
|
const containerName = config.project_uuid;
|
|
21
22
|
console.log(' ');
|
|
22
23
|
const { wantsAll } = require('../utils/services');
|
|
@@ -98,5 +99,25 @@ module.exports = async (args = {}) => {
|
|
|
98
99
|
'service_role key': config.auth.service,
|
|
99
100
|
};
|
|
100
101
|
console.log(prettyoutput(info));
|
|
102
|
+
|
|
103
|
+
// Migrations en attente de poad/migrations ([db] auto_migrate = false pour
|
|
104
|
+
// les appliquer à la main avec poad migrate)
|
|
105
|
+
const migrations = require('../utils/migrations');
|
|
106
|
+
if (migrations.files(root).list.length) {
|
|
107
|
+
if (!migrations.autoMigrate(config)) {
|
|
108
|
+
console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
|
|
109
|
+
} else {
|
|
110
|
+
const waiting = ora('Waiting for the database to apply migrations').start();
|
|
111
|
+
const ready = (await migrations.waitForDb(config)) && (await migrations.waitForServices(config));
|
|
112
|
+
if (!ready) {
|
|
113
|
+
waiting.fail(chalk.redBright('Migrations not applied: the engine does not answer (poad migrate later).'));
|
|
114
|
+
} else {
|
|
115
|
+
waiting.stop();
|
|
116
|
+
await require('../utils/migrate-run')(root, config, { quietWhenNone: false });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
console.log(' ');
|
|
120
|
+
}
|
|
121
|
+
|
|
101
122
|
if (all) await require('./run')({ all: true });
|
|
102
123
|
};
|
package/global/stop.js
CHANGED
|
@@ -12,7 +12,8 @@ module.exports = async (args) => {
|
|
|
12
12
|
const mail = require('../utils/mail');
|
|
13
13
|
const valkey = require('../utils/valkey');
|
|
14
14
|
const root = findPoadDir(process.cwd());
|
|
15
|
-
|
|
15
|
+
if (!root) return console.log(require('chalk-v2').redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
16
17
|
const containerName = config.project_uuid;
|
|
17
18
|
const ora = require('ora');
|
|
18
19
|
const chalk = require('chalk-v2');
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "poad",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"engine": "0.7.
|
|
3
|
+
"version": "2.12.0",
|
|
4
|
+
"engine": "0.7.1",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"bin": {
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"listr": "^0.14.3",
|
|
24
24
|
"log-beautify": "^1.2.0",
|
|
25
25
|
"ora": "^5.4.1",
|
|
26
|
+
"pg": "8.16.3",
|
|
26
27
|
"prettyoutput": "^1.2.0",
|
|
27
28
|
"toml": "^3.0.0"
|
|
28
29
|
}
|
package/project/cli.js
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
*/
|
|
9
9
|
module.exports = {
|
|
10
10
|
info: `Information about your project`,
|
|
11
|
+
kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
|
|
12
|
+
migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
|
|
13
|
+
migration: 'Database migrations: migration new <name>, migration list',
|
|
11
14
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
12
15
|
gen: {
|
|
13
16
|
description: 'Génération automatique des éléments clés pour votre projet',
|
package/project/info.js
CHANGED
|
@@ -12,7 +12,8 @@ module.exports = async () => {
|
|
|
12
12
|
const { storageInfo } = require('../utils/engine');
|
|
13
13
|
const { SERVICES, containerState } = require('../utils/services');
|
|
14
14
|
const root = findPoadDir(process.cwd());
|
|
15
|
-
|
|
15
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
16
17
|
console.log(' ');
|
|
17
18
|
if (!(await isDockerExist(config.project_uuid))) {
|
|
18
19
|
return console.log(chalk.redBright('Container not found'));
|
|
@@ -29,6 +30,21 @@ module.exports = async () => {
|
|
|
29
30
|
'anon key': config.auth.anon,
|
|
30
31
|
'service_role key': config.auth.service,
|
|
31
32
|
};
|
|
33
|
+
// Migrations : appliquées / en attente (poad/migrations)
|
|
34
|
+
const migrations = require('../utils/migrations');
|
|
35
|
+
if (migrations.files(root).list.length) {
|
|
36
|
+
let client;
|
|
37
|
+
try {
|
|
38
|
+
client = await migrations.connect(config);
|
|
39
|
+
const st = await migrations.status(root, client);
|
|
40
|
+
const done = st.list.length - st.pending.length;
|
|
41
|
+
info.Migrations = `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
|
|
42
|
+
} catch {
|
|
43
|
+
info.Migrations = `${migrations.files(root).list.length} file(s), state unknown`;
|
|
44
|
+
} finally {
|
|
45
|
+
if (client) await client.end().catch(() => {});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
32
48
|
console.log(prettyoutput(info));
|
|
33
49
|
|
|
34
50
|
// Panneau des services : en cours, arrêtés (configurés), ou disponibles
|
package/project/kc.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// poad kc export réécrit poad/keycloak.json depuis le Keycloak qui tourne
|
|
2
|
+
// (rôles, groupes, utilisateurs créés ou modifiés dans la console)
|
|
3
|
+
// poad kc affiche le jeu de test du projet
|
|
4
|
+
module.exports = async (args = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const toml = require('toml');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const Docker = require('dockerode');
|
|
10
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
11
|
+
const kc = require('../utils/keycloak');
|
|
12
|
+
const { containerState } = require('../utils/services');
|
|
13
|
+
|
|
14
|
+
const root = findPoadDir(process.cwd());
|
|
15
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
17
|
+
console.log(' ');
|
|
18
|
+
|
|
19
|
+
if (args.export) {
|
|
20
|
+
if (!(config.keycloak && config.keycloak.port) || (await containerState(new Docker(), kc.containerName(config))) !== 'running') {
|
|
21
|
+
return console.log(chalk.redBright('Keycloak is not running: "poad run kc" first.'));
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const { file, users, fresh } = await kc.exportRealm(root, config);
|
|
25
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} : ${users} user(s) exported`);
|
|
26
|
+
if (fresh.length) {
|
|
27
|
+
console.log(chalk.yellowBright(` New password for ${fresh.join(', ')} (unknown to the file): applied at the next "poad run kc".`));
|
|
28
|
+
}
|
|
29
|
+
} catch (err) {
|
|
30
|
+
console.log(chalk.redBright(`Export failed: ${err.message}`));
|
|
31
|
+
}
|
|
32
|
+
console.log(' ');
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const project = kc.loadProject(root, config, { create: false });
|
|
37
|
+
if (!project) return console.log(chalk.grey(' No Keycloak test set yet: "poad run kc" creates poad/keycloak.json.'));
|
|
38
|
+
console.log(`${chalk.bold('Keycloak test set')} ${chalk.grey(path.relative(process.cwd(), project.fixturePath))} realm ${chalk.bold(project.realm)}`);
|
|
39
|
+
console.log(' ');
|
|
40
|
+
for (const u of project.users) {
|
|
41
|
+
const flags = [u.roles.length ? `[${u.roles.join(', ')}]` : '', u.emailVerified ? '' : '(email not verified)'].filter(Boolean).join(' ');
|
|
42
|
+
console.log(` ${chalk.bold(u.username.padEnd(10))} ${u.password} ${u.email || ''} ${chalk.grey(flags)}`);
|
|
43
|
+
}
|
|
44
|
+
console.log(' ');
|
|
45
|
+
console.log(chalk.grey(' Edit the file then "poad run kc" to apply it; "poad kc export" saves changes made in the admin console.'));
|
|
46
|
+
console.log(' ');
|
|
47
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// poad migrate : applique les migrations en attente de poad/migrations
|
|
2
|
+
module.exports = async () => {
|
|
3
|
+
const chalk = require('chalk-v2');
|
|
4
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
5
|
+
const { isDockerExist } = require('../utils/docker');
|
|
6
|
+
const { readConfig } = require('../utils/config');
|
|
7
|
+
|
|
8
|
+
const root = findPoadDir(process.cwd());
|
|
9
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
10
|
+
const config = readConfig(root);
|
|
11
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
12
|
+
return console.log(chalk.redBright('The project is not started: run "poad start" (it applies pending migrations too).'));
|
|
13
|
+
}
|
|
14
|
+
const ok = await require('../utils/migrate-run')(root, config);
|
|
15
|
+
if (!ok) process.exitCode = 1;
|
|
16
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// poad migration new <nom> crée poad/migrations/<horodatage>_<nom>.sql
|
|
2
|
+
// poad migration list migrations appliquées et en attente
|
|
3
|
+
// (poad migrate applique celles en attente)
|
|
4
|
+
module.exports = async (args = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
8
|
+
const { isDockerExist } = require('../utils/docker');
|
|
9
|
+
const { readConfig } = require('../utils/config');
|
|
10
|
+
const migrations = require('../utils/migrations');
|
|
11
|
+
|
|
12
|
+
const root = findPoadDir(process.cwd());
|
|
13
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
14
|
+
const words = Object.keys(args);
|
|
15
|
+
const rel = (p) => path.relative(process.cwd(), p);
|
|
16
|
+
|
|
17
|
+
if (words[0] === 'new') {
|
|
18
|
+
try {
|
|
19
|
+
const file = migrations.create(root, words.slice(1).join('_'));
|
|
20
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel(file))}`);
|
|
21
|
+
console.log(chalk.grey(' Write your SQL in it, then "poad migrate".'));
|
|
22
|
+
} catch (err) {
|
|
23
|
+
console.log(chalk.redBright(err.message));
|
|
24
|
+
}
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (words[0] === 'list' || !words.length) {
|
|
29
|
+
const config = readConfig(root);
|
|
30
|
+
const { list, ignored } = migrations.files(root);
|
|
31
|
+
console.log(`${chalk.bold('Migrations')} ${chalk.grey(rel(migrations.dir(root)))}`);
|
|
32
|
+
console.log(' ');
|
|
33
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
34
|
+
for (const m of list) console.log(` ${chalk.grey('?')} ${m.file}`);
|
|
35
|
+
if (!list.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
|
|
36
|
+
console.log(' ');
|
|
37
|
+
return console.log(chalk.grey(' The project is not started: applied state unknown.'));
|
|
38
|
+
}
|
|
39
|
+
let client;
|
|
40
|
+
try {
|
|
41
|
+
client = await migrations.connect(config);
|
|
42
|
+
const state = await migrations.status(root, client);
|
|
43
|
+
for (const m of state.list) {
|
|
44
|
+
const mark = m.changed ? chalk.yellowBright('!') : m.applied ? chalk.greenBright('✔') : chalk.cyanBright('○');
|
|
45
|
+
const note = m.changed ? chalk.yellowBright(' changed after it was applied') : m.applied ? chalk.grey(` ${new Date(m.applied).toISOString().slice(0, 16).replace('T', ' ')}`) : chalk.cyanBright(' pending');
|
|
46
|
+
console.log(` ${mark} ${m.file}${note}`);
|
|
47
|
+
}
|
|
48
|
+
for (const r of state.missing) console.log(` ${chalk.yellowBright('!')} ${r.version}_${r.name}.sql${chalk.yellowBright(' applied, file missing')}`);
|
|
49
|
+
if (!state.list.length && !state.missing.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
|
|
50
|
+
for (const f of ignored) console.log(chalk.grey(` ${f} ignored (expected <YYYYMMDDHHMMSS>_<name>.sql)`));
|
|
51
|
+
console.log(' ');
|
|
52
|
+
if (state.pending.length) console.log(chalk.cyanBright(` ${state.pending.length} pending: "poad migrate".`));
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.log(chalk.redBright(`Cannot read the migration state: ${err.message}`));
|
|
55
|
+
} finally {
|
|
56
|
+
if (client) await client.end().catch(() => {});
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list')} | ${chalk.cyanBright('poad migrate')}`);
|
|
62
|
+
};
|
package/utils/config.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Configuration d'un projet poad, en deux fichiers :
|
|
2
|
+
// poad/config.toml versionné : ports, engine, services… aucun secret
|
|
3
|
+
// poad/secrets.toml propre à la machine, hors git : secret JWT et clés
|
|
4
|
+
// (anon, service_role, admin) signées avec lui
|
|
5
|
+
//
|
|
6
|
+
// loadConfig() fusionne les deux : le reste du CLI lit config.auth.secret,
|
|
7
|
+
// config.auth.anon… comme avant. Un ancien config.toml qui contient encore
|
|
8
|
+
// les secrets est migré à la première lecture ; un projet cloné sans
|
|
9
|
+
// secrets.toml en reçoit de nouveaux.
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const toml = require('toml');
|
|
13
|
+
|
|
14
|
+
const SECRET_KEYS = ['secret', 'anon', 'service', 'admin'];
|
|
15
|
+
|
|
16
|
+
const GITIGNORE = `# Généré par poad : propre à chaque machine, jamais versionné
|
|
17
|
+
data/
|
|
18
|
+
secrets.toml
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const poadDir = (root) => path.dirname(root);
|
|
22
|
+
const secretsFile = (root) => path.join(poadDir(root), 'secrets.toml');
|
|
23
|
+
|
|
24
|
+
/** Nouveau secret JWT et clés signées avec lui */
|
|
25
|
+
function generateSecrets() {
|
|
26
|
+
const jwt = require('jsonwebtoken');
|
|
27
|
+
const { generateSecret } = require('./jwtkey');
|
|
28
|
+
const secret = generateSecret();
|
|
29
|
+
return {
|
|
30
|
+
secret,
|
|
31
|
+
anon: jwt.sign({ role: 'anon', iss: 'poad' }, secret),
|
|
32
|
+
service: jwt.sign({ role: 'service_role', iss: 'poad' }, secret),
|
|
33
|
+
admin: jwt.sign({ role: 'admin', iss: 'poad' }, secret),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function writeSecrets(root, auth) {
|
|
38
|
+
const lines = ['# Secrets du projet poad local : hors git (poad/.gitignore)', '[auth]'];
|
|
39
|
+
for (const k of SECRET_KEYS) lines.push(`${k} = ${JSON.stringify(auth[k])}`);
|
|
40
|
+
fs.writeFileSync(secretsFile(root), lines.join('\n') + '\n', { mode: 0o600 });
|
|
41
|
+
fs.chmodSync(secretsFile(root), 0o600);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** poad/.gitignore : data/ et secrets.toml (complète un fichier existant) */
|
|
45
|
+
function ensureGitignore(root) {
|
|
46
|
+
const file = path.join(poadDir(root), '.gitignore');
|
|
47
|
+
if (!fs.existsSync(file)) return fs.writeFileSync(file, GITIGNORE);
|
|
48
|
+
const text = fs.readFileSync(file, 'utf-8');
|
|
49
|
+
const missing = ['data/', 'secrets.toml'].filter((l) => !text.split(/\r?\n/).includes(l));
|
|
50
|
+
if (missing.length) fs.writeFileSync(file, `${text.replace(/\s*$/, '')}\n${missing.join('\n')}\n`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Retire les lignes secrètes de la section [auth] du texte de config.toml */
|
|
54
|
+
function stripSecrets(text) {
|
|
55
|
+
const lines = text.split(/\r?\n/);
|
|
56
|
+
let section = '';
|
|
57
|
+
const kept = lines.filter((line) => {
|
|
58
|
+
const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
|
|
59
|
+
if (head) section = head[1].trim();
|
|
60
|
+
if (section !== 'auth') return true;
|
|
61
|
+
const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
|
|
62
|
+
return !(key && SECRET_KEYS.includes(key[1]));
|
|
63
|
+
});
|
|
64
|
+
return kept.join('\n');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Lit config.toml et secrets.toml, migre ou crée les secrets si besoin.
|
|
69
|
+
* Renvoie la configuration fusionnée ; notices : ce qui a été fait (à afficher).
|
|
70
|
+
*/
|
|
71
|
+
function loadConfig(root, notices = []) {
|
|
72
|
+
const text = fs.readFileSync(root, 'utf-8');
|
|
73
|
+
const config = toml.parse(text);
|
|
74
|
+
const auth = config.auth || {};
|
|
75
|
+
const inline = SECRET_KEYS.filter((k) => auth[k] !== undefined);
|
|
76
|
+
let secrets = null;
|
|
77
|
+
|
|
78
|
+
if (fs.existsSync(secretsFile(root))) {
|
|
79
|
+
secrets = (toml.parse(fs.readFileSync(secretsFile(root), 'utf-8')).auth || {});
|
|
80
|
+
}
|
|
81
|
+
if (inline.length) {
|
|
82
|
+
// Ancien format : les secrets de config.toml priment (ce sont ceux que
|
|
83
|
+
// l'engine et les fronts utilisent déjà), puis on les sort du fichier.
|
|
84
|
+
secrets = { ...(secrets || {}), ...Object.fromEntries(inline.map((k) => [k, auth[k]])) };
|
|
85
|
+
writeSecrets(root, secrets);
|
|
86
|
+
fs.writeFileSync(root, stripSecrets(text));
|
|
87
|
+
ensureGitignore(root);
|
|
88
|
+
notices.push(`Secrets moved from config.toml to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
|
|
89
|
+
} else if (!secrets || SECRET_KEYS.some((k) => !secrets[k])) {
|
|
90
|
+
secrets = generateSecrets();
|
|
91
|
+
writeSecrets(root, secrets);
|
|
92
|
+
ensureGitignore(root);
|
|
93
|
+
notices.push(`New project secrets written to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
config.auth = { ...auth, ...Object.fromEntries(SECRET_KEYS.map((k) => [k, secrets[k]])) };
|
|
97
|
+
return config;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** loadConfig + affichage des notices */
|
|
101
|
+
function readConfig(root) {
|
|
102
|
+
const notices = [];
|
|
103
|
+
const config = loadConfig(root, notices);
|
|
104
|
+
if (notices.length) {
|
|
105
|
+
const chalk = require('chalk-v2');
|
|
106
|
+
for (const n of notices) console.log(chalk.grey(` ${n}`));
|
|
107
|
+
}
|
|
108
|
+
return config;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
package/utils/keycloak.js
CHANGED
|
@@ -3,11 +3,19 @@
|
|
|
3
3
|
//
|
|
4
4
|
// - un conteneur par projet : <project_uuid>-keycloak ;
|
|
5
5
|
// - port choisi au premier lancement, gardé dans config.toml ([keycloak]) ;
|
|
6
|
-
// - realm
|
|
7
|
-
//
|
|
6
|
+
// - un realm au nom du projet (project_id), client « poad » ;
|
|
7
|
+
// - LE JEU DE TEST DU PROJET est dans poad/keycloak.json, VERSIONNÉ : rôles,
|
|
8
|
+
// groupes, utilisateurs (mots de passe en clair : comptes de test). Toute
|
|
9
|
+
// l'équipe a les mêmes comptes ; `poad kc export` y réécrit l'état du
|
|
10
|
+
// Keycloak qui tourne (comptes créés dans la console d'admin) ;
|
|
11
|
+
// - les secrets du realm restent hors git, dans poad/data/keycloak/users.json :
|
|
12
|
+
// clé de signature, secret du client, mot de passe admin, identifiants
|
|
13
|
+
// Keycloak des utilisateurs (stables : sans eux, chaque réimport change le
|
|
14
|
+
// « sub » et poad ne reconnaît plus les identités déjà liées) ;
|
|
8
15
|
// - le realm est réimporté à chaque lancement (Keycloak en mode dev, sans
|
|
9
|
-
// persistance)
|
|
10
|
-
// -
|
|
16
|
+
// persistance) ;
|
|
17
|
+
// - les rôles du realm arrivent dans la claim « roles » des jetons ; le
|
|
18
|
+
// fournisseur « keycloak » est déclaré au projet avec roles_claim: "roles".
|
|
11
19
|
//
|
|
12
20
|
// Le navigateur joint Keycloak par http://localhost:<port>, l'engine par le
|
|
13
21
|
// réseau du projet, sous le nom « keycloak » (http://keycloak:8080, option
|
|
@@ -20,16 +28,28 @@ const crypto = require('crypto');
|
|
|
20
28
|
const { execFileSync } = require('child_process');
|
|
21
29
|
|
|
22
30
|
const IMAGE = 'quay.io/keycloak/keycloak:26.0.7';
|
|
23
|
-
const REALM = 'poad';
|
|
24
31
|
const CLIENT = 'poad';
|
|
25
32
|
const PROVIDER = 'keycloak';
|
|
26
33
|
const NAMES = ['keycloak', 'kc'];
|
|
27
34
|
const ALIAS = 'keycloak';
|
|
35
|
+
const ROLES_CLAIM = 'roles';
|
|
28
36
|
|
|
29
37
|
const containerName = (config) => `${config.project_uuid}-keycloak`;
|
|
30
38
|
const dataDir = (root) => path.join(path.dirname(root), 'data', 'keycloak');
|
|
39
|
+
/** Jeu de test versionné du projet : poad/keycloak.json */
|
|
40
|
+
const fixtureFile = (root) => path.join(path.dirname(root), 'keycloak.json');
|
|
31
41
|
const random = (n) => crypto.randomBytes(n).toString('base64url');
|
|
32
42
|
|
|
43
|
+
/** Realm du projet : celui de keycloak.json, sinon le nom du projet */
|
|
44
|
+
const slug = (s) =>
|
|
45
|
+
String(s || 'poad')
|
|
46
|
+
.normalize('NFD')
|
|
47
|
+
.replace(/[̀-ͯ]/g, '')
|
|
48
|
+
.toLowerCase()
|
|
49
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
50
|
+
.replace(/^-+|-+$/g, '') || 'poad';
|
|
51
|
+
const realmName = (config, fixture) => (fixture && fixture.realm) || slug(config.project_id);
|
|
52
|
+
|
|
33
53
|
/**
|
|
34
54
|
* Mot de passe à recopier : lettres et chiffres seulement. Un « - » ou un
|
|
35
55
|
* « _ » coupe la sélection au double-clic dans un terminal, et le mot de
|
|
@@ -69,87 +89,296 @@ const savePort = (root, port) => {
|
|
|
69
89
|
const rsaKey = () =>
|
|
70
90
|
crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' });
|
|
71
91
|
|
|
92
|
+
const writeJson = (file, data, mode) => {
|
|
93
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
94
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', mode ? { mode } : undefined);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
|
|
98
|
+
|
|
99
|
+
/** Jeu de test par défaut : deux rôles, alice administratrice, bob utilisateur non vérifié */
|
|
100
|
+
const defaultFixture = (realm, old = []) => {
|
|
101
|
+
const pass = (name) => {
|
|
102
|
+
const p = (old.find((u) => u.username === name) || {}).password;
|
|
103
|
+
return isTypeable(p) ? p : typeable(12);
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
$comment:
|
|
107
|
+
'Comptes de test Keycloak du projet (poad run kc). Fichier versionné : mots de passe en clair, pour le test seulement. `poad kc export` réécrit ce fichier depuis le Keycloak qui tourne.',
|
|
108
|
+
realm,
|
|
109
|
+
roles: ['admin', 'user'],
|
|
110
|
+
groups: [],
|
|
111
|
+
users: [
|
|
112
|
+
{ username: 'alice', email: 'alice@poad.test', firstName: 'Alice', lastName: 'Poad', password: pass('alice'), emailVerified: true, roles: ['admin', 'user'], groups: [], attributes: {} },
|
|
113
|
+
{ username: 'bob', email: 'bob@poad.test', firstName: 'Bob', lastName: 'Poad', password: pass('bob'), emailVerified: false, roles: ['user'], groups: [], attributes: {} },
|
|
114
|
+
],
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
|
|
72
118
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
119
|
+
* Charge le jeu de test (poad/keycloak.json) et les secrets (data/keycloak/users.json),
|
|
120
|
+
* crée ce qui manque, et renvoie les utilisateurs complets (id stable, mot de passe).
|
|
121
|
+
*
|
|
122
|
+
* Reprise des projets antérieurs : les utilisateurs de l'ancien users.json
|
|
123
|
+
* passent dans keycloak.json avec leurs mots de passe ; users.json ne garde
|
|
124
|
+
* plus que les secrets. Appelé par `poad run kc` (Keycloak est recréé juste
|
|
125
|
+
* après) et, en lecture seule (create: false), par `poad info`.
|
|
76
126
|
*/
|
|
77
|
-
const
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
127
|
+
const loadProject = (root, config, { create = true } = {}) => {
|
|
128
|
+
const secretsFile = path.join(dataDir(root), 'users.json');
|
|
129
|
+
const fixturePath = fixtureFile(root);
|
|
130
|
+
let secrets = fs.existsSync(secretsFile) ? JSON.parse(fs.readFileSync(secretsFile, 'utf-8')) : null;
|
|
131
|
+
let fixture = fs.existsSync(fixturePath) ? JSON.parse(fs.readFileSync(fixturePath, 'utf-8')) : null;
|
|
132
|
+
if (!create) {
|
|
133
|
+
if (!secrets || !fixture) return null;
|
|
134
|
+
}
|
|
135
|
+
let secretsChanged = false;
|
|
136
|
+
if (!secrets) {
|
|
137
|
+
secrets = {};
|
|
138
|
+
secretsChanged = true;
|
|
139
|
+
}
|
|
140
|
+
if (!secrets.signing_key) {
|
|
141
|
+
secrets.signing_key = rsaKey();
|
|
142
|
+
secretsChanged = true;
|
|
143
|
+
}
|
|
144
|
+
if (!secrets.client_secret) {
|
|
145
|
+
secrets.client_secret = random(24);
|
|
146
|
+
secretsChanged = true;
|
|
147
|
+
}
|
|
148
|
+
if (!isTypeable(secrets.admin_password)) {
|
|
149
|
+
secrets.admin_password = typeable(16);
|
|
150
|
+
secretsChanged = true;
|
|
151
|
+
}
|
|
152
|
+
if (!fixture) {
|
|
153
|
+
fixture = defaultFixture(realmName(config), secrets.users || []);
|
|
154
|
+
if (create) writeJson(fixturePath, fixture);
|
|
155
|
+
}
|
|
156
|
+
if (secrets.users) {
|
|
157
|
+
// Ancien format : les comptes vivent maintenant dans keycloak.json
|
|
158
|
+
delete secrets.users;
|
|
159
|
+
secretsChanged = true;
|
|
160
|
+
}
|
|
161
|
+
secrets.ids = secrets.ids || {};
|
|
162
|
+
secrets.passwords = secrets.passwords || {};
|
|
163
|
+
|
|
164
|
+
const users = (fixture.users || []).map((u) => {
|
|
165
|
+
if (!secrets.ids[u.username]) {
|
|
166
|
+
secrets.ids[u.username] = crypto.randomUUID();
|
|
167
|
+
secretsChanged = true;
|
|
91
168
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
169
|
+
let password = u.password;
|
|
170
|
+
if (!password) {
|
|
171
|
+
// Pas de mot de passe dans le fichier : généré, gardé hors git
|
|
172
|
+
if (!secrets.passwords[u.username]) {
|
|
173
|
+
secrets.passwords[u.username] = typeable(12);
|
|
174
|
+
secretsChanged = true;
|
|
96
175
|
}
|
|
176
|
+
password = secrets.passwords[u.username];
|
|
97
177
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
};
|
|
110
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
111
|
-
fs.writeFileSync(file, JSON.stringify(secrets, null, 2) + '\n', { mode: 0o600 });
|
|
112
|
-
return { file, secrets };
|
|
178
|
+
return {
|
|
179
|
+
...u,
|
|
180
|
+
id: secrets.ids[u.username],
|
|
181
|
+
password,
|
|
182
|
+
emailVerified: u.emailVerified !== false,
|
|
183
|
+
roles: u.roles || [],
|
|
184
|
+
groups: u.groups || [],
|
|
185
|
+
attributes: u.attributes || {},
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
if (secretsChanged && create) writeJson(secretsFile, secrets, 0o600);
|
|
189
|
+
return { secretsFile, fixturePath, secrets, fixture, users, realm: realmName(config, fixture) };
|
|
113
190
|
};
|
|
114
191
|
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
192
|
+
const asList = (v) => (Array.isArray(v) ? v : [v]);
|
|
193
|
+
|
|
194
|
+
/** Représentation Keycloak du realm, importée au démarrage */
|
|
195
|
+
const realmOf = (config, project) => {
|
|
196
|
+
const { secrets, fixture, users, realm } = project;
|
|
197
|
+
const roles = [...new Set([...(fixture.roles || []), ...users.flatMap((u) => u.roles)])];
|
|
198
|
+
const groups = [...new Set([...(fixture.groups || []), ...users.flatMap((u) => u.groups)])];
|
|
199
|
+
return {
|
|
200
|
+
realm,
|
|
201
|
+
enabled: true,
|
|
202
|
+
registrationAllowed: false,
|
|
203
|
+
components: {
|
|
204
|
+
'org.keycloak.keys.KeyProvider': [
|
|
205
|
+
{
|
|
206
|
+
name: 'poad-rsa',
|
|
207
|
+
providerId: 'rsa',
|
|
208
|
+
subComponents: {},
|
|
209
|
+
config: { privateKey: [secrets.signing_key], priority: ['200'], algorithm: ['RS256'], active: ['true'], enabled: ['true'] },
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
},
|
|
213
|
+
roles: { realm: roles.map((name) => ({ name })) },
|
|
214
|
+
groups: groups.map((name) => ({ name, path: `/${name}` })),
|
|
215
|
+
clients: [
|
|
121
216
|
{
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
217
|
+
clientId: CLIENT,
|
|
218
|
+
enabled: true,
|
|
219
|
+
protocol: 'openid-connect',
|
|
220
|
+
publicClient: false,
|
|
221
|
+
secret: secrets.client_secret,
|
|
222
|
+
standardFlowEnabled: true,
|
|
223
|
+
directAccessGrantsEnabled: false,
|
|
224
|
+
redirectUris: [`http://localhost:${config.web.port}/auth/v1/callback`],
|
|
225
|
+
webOrigins: ['+'],
|
|
226
|
+
attributes: { 'pkce.code.challenge.method': 'S256' },
|
|
227
|
+
// Rôles du realm, à plat, dans la claim « roles » (jeton d'identité,
|
|
228
|
+
// jeton d'accès, userinfo) : poad les recopie dans app_metadata.roles
|
|
229
|
+
protocolMappers: [
|
|
230
|
+
{
|
|
231
|
+
name: 'realm roles',
|
|
232
|
+
protocol: 'openid-connect',
|
|
233
|
+
protocolMapper: 'oidc-usermodel-realm-role-mapper',
|
|
234
|
+
config: {
|
|
235
|
+
'claim.name': ROLES_CLAIM,
|
|
236
|
+
multivalued: 'true',
|
|
237
|
+
'jsonType.label': 'String',
|
|
238
|
+
'id.token.claim': 'true',
|
|
239
|
+
'access.token.claim': 'true',
|
|
240
|
+
'userinfo.token.claim': 'true',
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
],
|
|
126
244
|
},
|
|
127
245
|
],
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
246
|
+
users: users.map((u) => ({
|
|
247
|
+
id: u.id,
|
|
248
|
+
username: u.username,
|
|
249
|
+
email: u.email,
|
|
250
|
+
emailVerified: u.emailVerified,
|
|
251
|
+
firstName: u.firstName || capitalize(u.username),
|
|
252
|
+
lastName: u.lastName || '',
|
|
132
253
|
enabled: true,
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
254
|
+
attributes: Object.fromEntries(Object.entries(u.attributes).map(([k, v]) => [k, asList(v).map(String)])),
|
|
255
|
+
credentials: [{ type: 'password', value: u.password, temporary: false }],
|
|
256
|
+
realmRoles: u.roles,
|
|
257
|
+
groups: u.groups.map((g) => `/${g}`),
|
|
258
|
+
})),
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/** Jeton d'administration du Keycloak qui tourne (realm master) */
|
|
263
|
+
const adminToken = async (port, secrets) => {
|
|
264
|
+
const body = new URLSearchParams({ grant_type: 'password', client_id: 'admin-cli', username: 'admin', password: secrets.admin_password });
|
|
265
|
+
const res = await fetch(`http://localhost:${port}/realms/master/protocol/openid-connect/token`, { method: 'POST', body });
|
|
266
|
+
if (!res.ok) throw new Error(`Keycloak admin login refused (${res.status})`);
|
|
267
|
+
return (await res.json()).access_token;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* État du realm qui tourne : rôles, groupes, utilisateurs (avec leurs rôles et
|
|
272
|
+
* groupes). Les mots de passe ne se relisent pas : ceux du fichier sont gardés.
|
|
273
|
+
*/
|
|
274
|
+
const readRunningRealm = async (port, secrets, realm) => {
|
|
275
|
+
const token = await adminToken(port, secrets);
|
|
276
|
+
const get = async (p) => {
|
|
277
|
+
const res = await fetch(`http://localhost:${port}/admin/realms/${encodeURIComponent(realm)}${p}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
278
|
+
if (!res.ok) throw new Error(`Keycloak admin API ${p}: ${res.status}`);
|
|
279
|
+
return res.json();
|
|
280
|
+
};
|
|
281
|
+
// Rôles techniques créés par Keycloak dans chaque realm
|
|
282
|
+
const builtin = (n) => n === 'offline_access' || n === 'uma_authorization' || n.startsWith('default-roles-');
|
|
283
|
+
const roles = (await get('/roles')).map((r) => r.name).filter((n) => !builtin(n)).sort();
|
|
284
|
+
const flatten = (gs) => gs.flatMap((g) => [g.name, ...flatten(g.subGroups || [])]);
|
|
285
|
+
const groups = flatten(await get('/groups?briefRepresentation=true')).sort();
|
|
286
|
+
const users = [];
|
|
287
|
+
for (const u of await get('/users?max=1000&briefRepresentation=false')) {
|
|
288
|
+
const userRoles = (await get(`/users/${u.id}/role-mappings/realm`)).map((r) => r.name).filter((n) => !builtin(n)).sort();
|
|
289
|
+
const userGroups = (await get(`/users/${u.id}/groups`)).map((g) => g.name).sort();
|
|
290
|
+
users.push({
|
|
291
|
+
id: u.id,
|
|
292
|
+
username: u.username,
|
|
293
|
+
email: u.email,
|
|
294
|
+
firstName: u.firstName,
|
|
295
|
+
lastName: u.lastName,
|
|
296
|
+
emailVerified: Boolean(u.emailVerified),
|
|
297
|
+
roles: userRoles,
|
|
298
|
+
groups: userGroups,
|
|
299
|
+
attributes: Object.fromEntries(Object.entries(u.attributes || {}).map(([k, v]) => [k, v.length === 1 ? v[0] : v])),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
users.sort((a, b) => a.username.localeCompare(b.username));
|
|
303
|
+
return { roles, groups, users };
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Autorise les attributs libres sur les utilisateurs du realm (Keycloak 24+ les
|
|
308
|
+
* ignore sinon quand on les ajoute par la console d'admin) : sans ça, un
|
|
309
|
+
* attribut saisi dans la console disparaîtrait avant `poad kc export`.
|
|
310
|
+
*/
|
|
311
|
+
const enableUserAttributes = async (port, secrets, realm) => {
|
|
312
|
+
const token = await adminToken(port, secrets);
|
|
313
|
+
const url = `http://localhost:${port}/admin/realms/${encodeURIComponent(realm)}/users/profile`;
|
|
314
|
+
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
|
|
315
|
+
const profile = await (await fetch(url, { headers })).json();
|
|
316
|
+
if (profile.unmanagedAttributePolicy === 'ENABLED') return;
|
|
317
|
+
const res = await fetch(url, { method: 'PUT', headers, body: JSON.stringify({ ...profile, unmanagedAttributePolicy: 'ENABLED' }) });
|
|
318
|
+
if (!res.ok) throw new Error(`user profile: ${res.status}`);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Reprise : avant de recréer un Keycloak qui tourne, garde les identifiants de
|
|
323
|
+
* ses utilisateurs qui n'en ont pas encore dans les secrets (projets antérieurs,
|
|
324
|
+
* où chaque réimport en tirait de nouveaux). Ainsi le « sub » ne change plus et
|
|
325
|
+
* les identités déjà liées dans poad restent valables. Sans effet si rien ne tourne.
|
|
326
|
+
*/
|
|
327
|
+
const adoptRunningIds = async (root, config) => {
|
|
328
|
+
const secretsFile = path.join(dataDir(root), 'users.json');
|
|
329
|
+
if (!fs.existsSync(secretsFile) || !(config.keycloak && config.keycloak.port)) return 0;
|
|
330
|
+
const secrets = JSON.parse(fs.readFileSync(secretsFile, 'utf-8'));
|
|
331
|
+
if (!secrets.admin_password) return 0;
|
|
332
|
+
const fixture = fs.existsSync(fixtureFile(root)) ? JSON.parse(fs.readFileSync(fixtureFile(root), 'utf-8')) : null;
|
|
333
|
+
secrets.ids = secrets.ids || {};
|
|
334
|
+
let adopted = 0;
|
|
335
|
+
// Realm du projet, ou « poad », nom unique des versions antérieures
|
|
336
|
+
for (const realm of [...new Set([realmName(config, fixture), 'poad'])]) {
|
|
337
|
+
let running;
|
|
338
|
+
try {
|
|
339
|
+
running = await readRunningRealm(config.keycloak.port, secrets, realm);
|
|
340
|
+
} catch {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
for (const u of running.users) {
|
|
344
|
+
if (!secrets.ids[u.username]) {
|
|
345
|
+
secrets.ids[u.username] = u.id;
|
|
346
|
+
adopted++;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
if (adopted) writeJson(secretsFile, secrets, 0o600);
|
|
352
|
+
return adopted;
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* `poad kc export` : réécrit keycloak.json depuis le Keycloak qui tourne.
|
|
357
|
+
* Mots de passe : ceux du fichier pour les comptes connus ; un compte créé
|
|
358
|
+
* dans la console reçoit un nouveau mot de passe, appliqué au prochain `poad run kc`.
|
|
359
|
+
*/
|
|
360
|
+
const exportRealm = async (root, config) => {
|
|
361
|
+
const project = loadProject(root, config);
|
|
362
|
+
const running = await readRunningRealm(config.keycloak.port, project.secrets, project.realm);
|
|
363
|
+
const known = Object.fromEntries((project.fixture.users || []).map((u) => [u.username, u]));
|
|
364
|
+
const fresh = [];
|
|
365
|
+
const users = running.users.map((u) => {
|
|
366
|
+
const before = known[u.username] || {};
|
|
367
|
+
let password = before.password || project.secrets.passwords[u.username];
|
|
368
|
+
if (!password) {
|
|
369
|
+
password = typeable(12);
|
|
370
|
+
fresh.push(u.username);
|
|
371
|
+
}
|
|
372
|
+
// Garde l'identifiant Keycloak : le « sub » reste le même au prochain lancement
|
|
373
|
+
project.secrets.ids[u.username] = u.id;
|
|
374
|
+
const { id, ...rest } = u;
|
|
375
|
+
return { ...rest, password };
|
|
376
|
+
});
|
|
377
|
+
const fixture = { ...project.fixture, realm: project.realm, roles: running.roles, groups: running.groups, users };
|
|
378
|
+
writeJson(project.fixturePath, fixture);
|
|
379
|
+
writeJson(project.secretsFile, project.secrets, 0o600);
|
|
380
|
+
return { file: project.fixturePath, users: users.length, fresh };
|
|
381
|
+
};
|
|
153
382
|
|
|
154
383
|
const isLocalProvider = (params) =>
|
|
155
384
|
/\/\/(keycloak:8080|host\.docker\.internal|localhost|127\.0\.0\.1)[:/]/.test(String(params && params.issuer));
|
|
@@ -165,13 +394,15 @@ const assertCanRegister = (config) => {
|
|
|
165
394
|
}
|
|
166
395
|
};
|
|
167
396
|
|
|
168
|
-
const register = (config,
|
|
397
|
+
const register = (config, project) => {
|
|
169
398
|
assertCanRegister(config);
|
|
170
399
|
const params = {
|
|
171
|
-
issuer: `http://${ALIAS}:8080/realms/${
|
|
400
|
+
issuer: `http://${ALIAS}:8080/realms/${project.realm}`,
|
|
172
401
|
client_id: CLIENT,
|
|
173
|
-
client_secret: secrets.client_secret,
|
|
402
|
+
client_secret: project.secrets.client_secret,
|
|
174
403
|
scopes: 'openid email profile',
|
|
404
|
+
// Rôles du realm recopiés dans app_metadata.roles à chaque connexion
|
|
405
|
+
roles_claim: ROLES_CLAIM,
|
|
175
406
|
};
|
|
176
407
|
psql(
|
|
177
408
|
config,
|
|
@@ -194,16 +425,22 @@ const unregister = (config) => {
|
|
|
194
425
|
|
|
195
426
|
module.exports = {
|
|
196
427
|
IMAGE,
|
|
197
|
-
REALM,
|
|
198
428
|
PROVIDER,
|
|
199
429
|
NAMES,
|
|
200
430
|
ALIAS,
|
|
431
|
+
ROLES_CLAIM,
|
|
201
432
|
containerName,
|
|
202
433
|
dataDir,
|
|
434
|
+
fixtureFile,
|
|
435
|
+
realmName,
|
|
203
436
|
wanted,
|
|
204
437
|
savePort,
|
|
205
|
-
|
|
438
|
+
loadProject,
|
|
206
439
|
realmOf,
|
|
440
|
+
readRunningRealm,
|
|
441
|
+
adoptRunningIds,
|
|
442
|
+
enableUserAttributes,
|
|
443
|
+
exportRealm,
|
|
207
444
|
assertCanRegister,
|
|
208
445
|
register,
|
|
209
446
|
unregister,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Application des migrations avec affichage, partagée par poad migrate et poad start
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const migrations = require('./migrations');
|
|
7
|
+
const rel = (p) => path.relative(process.cwd(), p);
|
|
8
|
+
|
|
9
|
+
let result;
|
|
10
|
+
try {
|
|
11
|
+
result = await migrations.migrate(root, config, {
|
|
12
|
+
onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
|
|
13
|
+
});
|
|
14
|
+
} catch (err) {
|
|
15
|
+
console.log(chalk.redBright(`Migrations not applied: ${err.message}`));
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const { applied, failed, state } = result;
|
|
19
|
+
|
|
20
|
+
for (const m of state.changed) {
|
|
21
|
+
console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
|
|
22
|
+
}
|
|
23
|
+
for (const r of state.missing) {
|
|
24
|
+
console.log(chalk.yellowBright(` ${r.version}_${r.name}.sql was applied but is no longer in ${rel(migrations.dir(root))}.`));
|
|
25
|
+
}
|
|
26
|
+
for (const f of state.ignored) {
|
|
27
|
+
console.log(chalk.grey(` ${f} ignored: migration files are named <YYYYMMDDHHMMSS>_<name>.sql`));
|
|
28
|
+
}
|
|
29
|
+
if (failed) {
|
|
30
|
+
console.log(`${chalk.redBright('✖')} ${chalk.bold(failed.migration.file)}`);
|
|
31
|
+
console.log(chalk.redBright(` ${failed.message}`));
|
|
32
|
+
console.log(chalk.grey(' Rolled back: fix the file, then "poad migrate".'));
|
|
33
|
+
const left = state.pending.length - applied.length - 1;
|
|
34
|
+
if (left > 0) console.log(chalk.grey(` ${left} later migration(s) not attempted.`));
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (applied.length) console.log(chalk.bold(` ${applied.length} migration(s) applied.`));
|
|
38
|
+
else if (!quietWhenNone) console.log(chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
|
|
39
|
+
return true;
|
|
40
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Migrations du schéma de la base : poad/migrations/<AAAAMMJJHHMMSS>_<nom>.sql
|
|
2
|
+
//
|
|
3
|
+
// - appliquées dans l'ordre des noms, chacune dans sa transaction, avec son
|
|
4
|
+
// inscription dans poad_migrations.history (version, nom, empreinte) ;
|
|
5
|
+
// - une migration déjà appliquée n'est jamais rejouée : si son fichier a
|
|
6
|
+
// changé depuis, on le signale (écrivez plutôt une nouvelle migration) ;
|
|
7
|
+
// - un verrou consultatif évite deux applications simultanées.
|
|
8
|
+
//
|
|
9
|
+
// Le CLI se connecte à la base du projet local (port [db] de config.toml).
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
|
|
14
|
+
const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]+)\.sql$/;
|
|
15
|
+
const LOCK_ID = 7_340_201; // pg_advisory_lock : propre aux migrations poad
|
|
16
|
+
|
|
17
|
+
const dir = (root) => path.join(path.dirname(root), 'migrations');
|
|
18
|
+
|
|
19
|
+
const checksum = (sql) => crypto.createHash('sha256').update(sql).digest('hex');
|
|
20
|
+
|
|
21
|
+
/** Fichiers de migration du projet, triés ; les autres fichiers sont ignorés */
|
|
22
|
+
function files(root) {
|
|
23
|
+
const d = dir(root);
|
|
24
|
+
if (!fs.existsSync(d)) return { list: [], ignored: [] };
|
|
25
|
+
const names = fs.readdirSync(d).filter((f) => !f.startsWith('.')).sort();
|
|
26
|
+
const list = [];
|
|
27
|
+
const ignored = [];
|
|
28
|
+
for (const file of names) {
|
|
29
|
+
const m = FILE_RE.exec(file);
|
|
30
|
+
if (!m) {
|
|
31
|
+
ignored.push(file);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const sql = fs.readFileSync(path.join(d, file), 'utf-8');
|
|
35
|
+
list.push({ version: m[1], name: m[2], file, path: path.join(d, file), sql, checksum: checksum(sql) });
|
|
36
|
+
}
|
|
37
|
+
return { list, ignored };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Horodatage UTC AAAAMMJJHHMMSS */
|
|
41
|
+
function timestamp(date = new Date()) {
|
|
42
|
+
return date.toISOString().replace(/[-:T]/g, '').slice(0, 14);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Crée poad/migrations/<horodatage>_<nom>.sql ; renvoie son chemin */
|
|
46
|
+
function create(root, name) {
|
|
47
|
+
const slug = String(name || '')
|
|
48
|
+
.normalize('NFD')
|
|
49
|
+
.replace(/[̀-ͯ]/g, '')
|
|
50
|
+
.replace(/[^A-Za-z0-9_-]+/g, '_')
|
|
51
|
+
.replace(/^_+|_+$/g, '')
|
|
52
|
+
.toLowerCase();
|
|
53
|
+
if (!slug) throw new Error('a migration needs a name: poad migration new <name>');
|
|
54
|
+
fs.mkdirSync(dir(root), { recursive: true });
|
|
55
|
+
let version = timestamp();
|
|
56
|
+
// Deux migrations créées dans la même seconde : la seconde passe après
|
|
57
|
+
while (files(root).list.some((m) => m.version === version)) version = String(Number(version) + 1);
|
|
58
|
+
const file = path.join(dir(root), `${version}_${slug}.sql`);
|
|
59
|
+
fs.writeFileSync(
|
|
60
|
+
file,
|
|
61
|
+
`-- ${slug}\n-- Appliquée une seule fois, dans une transaction, par "poad migrate" (ou poad start).\n-- Une fois appliquée, ne la modifiez plus : écrivez une nouvelle migration.\n\n`
|
|
62
|
+
);
|
|
63
|
+
return file;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function connect(config) {
|
|
67
|
+
const { Client } = require('pg');
|
|
68
|
+
const client = new Client({
|
|
69
|
+
host: '127.0.0.1',
|
|
70
|
+
port: Number(config.db.port),
|
|
71
|
+
user: 'postgres',
|
|
72
|
+
password: 'postgres',
|
|
73
|
+
database: 'postgres',
|
|
74
|
+
connectionTimeoutMillis: 5000,
|
|
75
|
+
application_name: 'poad-cli',
|
|
76
|
+
});
|
|
77
|
+
await client.connect();
|
|
78
|
+
client.on('error', () => {}); // fermeture de la connexion par le serveur
|
|
79
|
+
return client;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function ensureHistory(client) {
|
|
83
|
+
await client.query(`
|
|
84
|
+
create schema if not exists poad_migrations;
|
|
85
|
+
create table if not exists poad_migrations.history (
|
|
86
|
+
version text primary key,
|
|
87
|
+
name text not null,
|
|
88
|
+
checksum text not null,
|
|
89
|
+
applied_at timestamptz not null default now()
|
|
90
|
+
);
|
|
91
|
+
revoke all on schema poad_migrations from public;
|
|
92
|
+
`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** État : appliquées, en attente, modifiées après application, absentes du dossier */
|
|
96
|
+
async function status(root, client) {
|
|
97
|
+
const { list, ignored } = files(root);
|
|
98
|
+
await ensureHistory(client);
|
|
99
|
+
const { rows } = await client.query('select version, name, checksum, applied_at from poad_migrations.history order by version');
|
|
100
|
+
const applied = new Map(rows.map((r) => [r.version, r]));
|
|
101
|
+
const local = new Set(list.map((m) => m.version));
|
|
102
|
+
return {
|
|
103
|
+
list: list.map((m) => {
|
|
104
|
+
const row = applied.get(m.version);
|
|
105
|
+
return { ...m, applied: row ? row.applied_at : null, changed: Boolean(row && row.checksum !== m.checksum) };
|
|
106
|
+
}),
|
|
107
|
+
pending: list.filter((m) => !applied.has(m.version)),
|
|
108
|
+
changed: list.filter((m) => applied.has(m.version) && applied.get(m.version).checksum !== m.checksum),
|
|
109
|
+
missing: rows.filter((r) => !local.has(r.version)),
|
|
110
|
+
ignored,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Ligne et colonne d'une position (1-based) dans le texte */
|
|
115
|
+
function lineOf(sql, position) {
|
|
116
|
+
const before = sql.slice(0, Math.max(0, Number(position) - 1));
|
|
117
|
+
const line = before.split('\n').length;
|
|
118
|
+
return line;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Applique les migrations en attente. S'arrête à la première erreur (sa
|
|
123
|
+
* transaction est annulée, les suivantes ne sont pas tentées).
|
|
124
|
+
* Renvoie { applied: [...], failed: { migration, message } | null, state }.
|
|
125
|
+
*/
|
|
126
|
+
async function migrate(root, config, { onApply } = {}) {
|
|
127
|
+
const client = await connect(config);
|
|
128
|
+
const applied = [];
|
|
129
|
+
try {
|
|
130
|
+
await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
|
|
131
|
+
const state = await status(root, client);
|
|
132
|
+
for (const m of state.pending) {
|
|
133
|
+
try {
|
|
134
|
+
await client.query('begin');
|
|
135
|
+
await client.query(m.sql);
|
|
136
|
+
await client.query('insert into poad_migrations.history (version, name, checksum) values ($1, $2, $3)', [m.version, m.name, m.checksum]);
|
|
137
|
+
await client.query('commit');
|
|
138
|
+
applied.push(m);
|
|
139
|
+
if (onApply) onApply(m);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
await client.query('rollback').catch(() => {});
|
|
142
|
+
const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
|
|
143
|
+
return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return { applied, failed: null, state };
|
|
147
|
+
} finally {
|
|
148
|
+
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
149
|
+
await client.end().catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Attend que la base accepte les connexions (démarrage de l'engine) */
|
|
154
|
+
async function waitForDb(config, seconds = 90) {
|
|
155
|
+
for (let i = 0; i < seconds; i++) {
|
|
156
|
+
try {
|
|
157
|
+
const client = await connect(config);
|
|
158
|
+
await client.query('select 1');
|
|
159
|
+
await client.end();
|
|
160
|
+
return true;
|
|
161
|
+
} catch {
|
|
162
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Attend que les services de l'engine aient créé leurs schémas (auth,
|
|
170
|
+
* storage) : une migration peut y écrire (buckets, politiques).
|
|
171
|
+
*/
|
|
172
|
+
async function waitForServices(config, seconds = 90) {
|
|
173
|
+
const base = `http://localhost:${config.web.port}`;
|
|
174
|
+
const ok = (url, headers) => fetch(url, { headers }).then((r) => r.ok, () => false);
|
|
175
|
+
for (let i = 0; i < seconds; i++) {
|
|
176
|
+
const [auth, storage] = await Promise.all([
|
|
177
|
+
ok(`${base}/auth/v1/settings`, { apikey: config.auth.anon }),
|
|
178
|
+
ok(`${base}/storage/v1/status`, { apikey: config.auth.anon }),
|
|
179
|
+
]);
|
|
180
|
+
if (auth && storage) return true;
|
|
181
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
182
|
+
}
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Les migrations s'appliquent-elles à poad start ? ([db] auto_migrate, vrai par défaut) */
|
|
187
|
+
const autoMigrate = (config) => !(config.db && config.db.auto_migrate === false);
|
|
188
|
+
|
|
189
|
+
module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, FILE_RE };
|
package/utils/services.js
CHANGED
|
@@ -8,17 +8,8 @@
|
|
|
8
8
|
const kc = require('./keycloak');
|
|
9
9
|
const valkey = require('./valkey');
|
|
10
10
|
const mail = require('./mail');
|
|
11
|
-
const fs = require('fs');
|
|
12
11
|
const path = require('path');
|
|
13
12
|
|
|
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
13
|
|
|
23
14
|
const SERVICES = [
|
|
24
15
|
{
|
|
@@ -38,21 +29,22 @@ const SERVICES = [
|
|
|
38
29
|
container: (config) => kc.containerName(config),
|
|
39
30
|
configured: (config) => Boolean(config.keycloak && config.keycloak.port),
|
|
40
31
|
info: (config, root) => {
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
const users = readKeycloakUsers(root);
|
|
48
|
-
if (users) {
|
|
49
|
-
const base = `http://localhost:${config.keycloak.port}`;
|
|
32
|
+
const base = `http://localhost:${config.keycloak.port}`;
|
|
33
|
+
// Lecture seule : rien n'est créé tant que `poad run kc` n'a pas tourné
|
|
34
|
+
const project = root ? kc.loadProject(root, config, { create: false }) : null;
|
|
35
|
+
const realm = project ? project.realm : kc.realmName(config);
|
|
36
|
+
const out = { URL: base, Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
|
|
37
|
+
if (project) {
|
|
50
38
|
// Deux realms, deux usages : ne pas essayer alice sur la console d'admin
|
|
51
|
-
out['Admin console'] = [`${base}/admin`, `admin ${
|
|
39
|
+
out['Admin console'] = [`${base}/admin`, `admin ${project.secrets.admin_password}`];
|
|
52
40
|
out['Test users'] = [
|
|
53
|
-
`realm "${
|
|
54
|
-
...
|
|
41
|
+
`realm "${realm}" : "Continuer avec Keycloak" in the app, or ${base}/realms/${realm}/account`,
|
|
42
|
+
...project.users.map(
|
|
43
|
+
(u) =>
|
|
44
|
+
`${u.username.padEnd(6)} ${u.password} ${u.email || ''}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
|
|
45
|
+
),
|
|
55
46
|
];
|
|
47
|
+
out['Test set'] = `${path.relative(process.cwd(), project.fixturePath)} (poad kc export saves the running realm)`;
|
|
56
48
|
}
|
|
57
49
|
return out;
|
|
58
50
|
},
|