poad 2.38.0 → 2.39.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.
@@ -0,0 +1,122 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { rewritePackageJson, packageName, prepareStarter, adaptToPackageManager, templateByValue } = require('../utils/starter');
6
+ const { tmpdir } = require('./helpers');
7
+
8
+ const published = {
9
+ name: '@poadio/starter-angular',
10
+ title: 'Mon application',
11
+ description: 'Template description (npm)',
12
+ version: '0.4.0',
13
+ license: 'MIT',
14
+ repository: { type: 'git', url: 'https://github.com/poadio/starter-angular.git' },
15
+ publishConfig: { access: 'public' },
16
+ files: ['src'],
17
+ bugs: 'https://x',
18
+ homepage: 'https://x',
19
+ keywords: ['poad'],
20
+ scripts: { start: 'node scripts/dev.mjs' },
21
+ dependencies: { '@poadio/client-js': '^0.3.1' },
22
+ poad: { routing: 'classic', template: { framework: 'angular', description: 'Application Angular branchée sur poad', gitignore: ['/dist'] } },
23
+ packageManager: 'bun@1.4.4',
24
+ };
25
+
26
+ test('package.json rewrite: name, version, private, publication fields dropped', () => {
27
+ const pkg = rewritePackageJson(published, { name: 'my-app', title: 'my-app', from: '@poadio/starter-angular@0.4.0' });
28
+ assert.strictEqual(pkg.name, 'my-app');
29
+ assert.strictEqual(pkg.version, '0.1.0');
30
+ assert.strictEqual(pkg.private, true);
31
+ assert.strictEqual(pkg.title, 'my-app');
32
+ assert.strictEqual(pkg.description, 'Application Angular branchée sur poad');
33
+ for (const k of ['files', 'publishConfig', 'repository', 'bugs', 'homepage', 'keywords', 'license']) assert.ok(!(k in pkg), `${k} dropped`);
34
+ assert.deepStrictEqual(pkg.poad, { routing: 'classic', from: '@poadio/starter-angular@0.4.0' });
35
+ // le reste est gardé
36
+ assert.deepStrictEqual(pkg.scripts, published.scripts);
37
+ assert.deepStrictEqual(pkg.dependencies, published.dependencies);
38
+ assert.strictEqual(pkg.packageManager, 'bun@1.4.4');
39
+ assert.deepStrictEqual(Object.keys(pkg).slice(0, 5), ['name', 'title', 'description', 'version', 'private']);
40
+ // l'objet d'origine n'est pas modifié
41
+ assert.strictEqual(published.name, '@poadio/starter-angular');
42
+ });
43
+
44
+ test('package name from a folder name', () => {
45
+ assert.strictEqual(packageName('My App!'), 'my-app');
46
+ assert.strictEqual(packageName('..'), 'app');
47
+ assert.strictEqual(packageName('_x_'), 'x');
48
+ });
49
+
50
+ test('prepareStarter: .gitignore restored from gitignore, template lines added, publication files stripped', (t) => {
51
+ const dir = tmpdir(t);
52
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(published));
53
+ fs.writeFileSync(path.join(dir, 'gitignore'), '/node_modules\n');
54
+ fs.writeFileSync(path.join(dir, '.npmignore'), 'test/\n');
55
+ fs.mkdirSync(path.join(dir, 'poad'));
56
+ fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "template"\n');
57
+ const r = prepareStarter(dir);
58
+ const gi = fs.readFileSync(path.join(dir, '.gitignore'), 'utf8');
59
+ assert.match(gi, /^\/node_modules$/m);
60
+ assert.match(gi, /^\/dist$/m);
61
+ assert.strictEqual(fs.existsSync(path.join(dir, 'gitignore')), false);
62
+ assert.strictEqual(fs.existsSync(path.join(dir, '.npmignore')), false);
63
+ assert.strictEqual(fs.existsSync(path.join(dir, 'poad', 'config.toml')), false);
64
+ assert.strictEqual(r.gitignore, 'restored');
65
+ });
66
+
67
+ test('prepareStarter: legacy npm renamed .gitignore to .npmignore', (t) => {
68
+ const dir = tmpdir(t);
69
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
70
+ fs.writeFileSync(path.join(dir, '.npmignore'), 'dist/\n');
71
+ prepareStarter(dir);
72
+ assert.strictEqual(fs.readFileSync(path.join(dir, '.gitignore'), 'utf8'), 'dist/\n');
73
+ });
74
+
75
+ test('adaptToPackageManager: foreign lockfiles and packageManager removed', (t) => {
76
+ const dir = tmpdir(t);
77
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'a', packageManager: 'bun@1.4.4' }));
78
+ fs.writeFileSync(path.join(dir, 'bun.lock'), '');
79
+ assert.deepStrictEqual(adaptToPackageManager(dir, 'bun'), []);
80
+ assert.deepStrictEqual(adaptToPackageManager(dir, 'pnpm'), ['bun.lock', 'packageManager (package.json)']);
81
+ assert.ok(!('packageManager' in JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))));
82
+ });
83
+
84
+ test('templates table', () => {
85
+ assert.strictEqual(templateByValue('Next').package, '@poadio/starter-next');
86
+ assert.strictEqual(templateByValue('svelte'), null);
87
+ });
88
+
89
+ // Port et URL du front selon le framework : poad.port (starter-next, gardé
90
+ // après la réécriture), sinon poad.template.port, sinon le défaut de l'outil
91
+ test('devServer: Next.js reads poad.port, nothing written', async (t) => {
92
+ const { devServer } = require('../utils/starter');
93
+ const dir = tmpdir(t);
94
+ const next = { name: '@poadio/starter-next', dependencies: { next: '16.4.6' }, poad: { port: 3300, template: { framework: 'next', port: 3300 } } };
95
+ assert.deepStrictEqual(await devServer(dir, next), { framework: 'next', label: 'Next.js', port: 3300, url: 'http://localhost:3300' });
96
+ assert.deepStrictEqual(fs.readdirSync(dir), []);
97
+ // poad.port l'emporte sur poad.template.port ; sans framework déclaré, les dépendances
98
+ assert.strictEqual((await devServer(dir, { dependencies: { next: '1' }, poad: { port: 3400, template: { port: 3300 } } })).port, 3400);
99
+ assert.strictEqual((await devServer(dir, { dependencies: { next: '1' }, poad: { template: { port: 3500 } } })).port, 3500);
100
+ // rien de déclaré : le port de next dev
101
+ assert.deepStrictEqual(await devServer(dir, { dependencies: { next: '1' } }), { framework: 'next', label: 'Next.js', port: 3000, url: 'http://localhost:3000' });
102
+ assert.strictEqual((await devServer(dir, { dependencies: { nuxt: '4' } })).label, 'Nuxt');
103
+ });
104
+
105
+ test('devServer: Angular gets a free port from poad.template.port, written to angular.json', async (t) => {
106
+ const { devServer } = require('../utils/starter');
107
+ const dir = tmpdir(t);
108
+ fs.writeFileSync(path.join(dir, 'angular.json'), JSON.stringify({ projects: { app: { architect: { serve: { options: {} } } } } }));
109
+ const dev = await devServer(dir, published);
110
+ assert.strictEqual(dev.label, 'Angular');
111
+ assert.ok(dev.port >= 4300 && dev.port < 4400, String(dev.port));
112
+ assert.strictEqual(dev.url, `http://localhost:${dev.port}`);
113
+ const ng = JSON.parse(fs.readFileSync(path.join(dir, 'angular.json'), 'utf8'));
114
+ assert.strictEqual(ng.projects.app.architect.serve.options.port, dev.port);
115
+ });
116
+
117
+ test('devServer: unknown framework, no port declared: no URL', async (t) => {
118
+ const { devServer } = require('../utils/starter');
119
+ assert.deepStrictEqual(await devServer(tmpdir(t), { name: 'x' }), { framework: null, label: null, port: null, url: null });
120
+ const vanilla = await devServer(tmpdir(t), { poad: { port: 5180, template: { framework: 'vanilla' } } });
121
+ assert.deepStrictEqual(vanilla, { framework: 'vanilla', label: 'Vanilla', port: 5180, url: 'http://localhost:5180' });
122
+ });
@@ -0,0 +1,101 @@
1
+ // node --test test/
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const zlib = require('zlib');
7
+ const { extractTgz, TarError } = require('../utils/tar');
8
+ const { tgz, paxRecord, tmpdir } = require('./helpers');
9
+
10
+ const refuses = (t, entries, pattern) => {
11
+ const root = tmpdir(t);
12
+ const target = path.join(root, 'app');
13
+ assert.throws(() => extractTgz(tgz(entries), target), (err) => err instanceof TarError && pattern.test(err.message));
14
+ // Rien n'a été écrit : ni dans la cible, ni à côté
15
+ assert.deepStrictEqual(fs.existsSync(target) ? fs.readdirSync(target) : [], []);
16
+ assert.deepStrictEqual(fs.readdirSync(root).filter((n) => n !== 'app'), []);
17
+ };
18
+
19
+ test('extracts a regular npm package, without its first folder', (t) => {
20
+ const target = path.join(tmpdir(t), 'app');
21
+ const n = extractTgz(
22
+ tgz([
23
+ { name: 'package/package.json', data: '{"name":"x"}' },
24
+ { name: 'package/src/', type: '5' },
25
+ { name: 'package/src/main.ts', data: 'console.log(1)' },
26
+ { name: 'package/scripts/dev.mjs', data: '#!/usr/bin/env node', mode: 0o4755 },
27
+ ]),
28
+ target
29
+ );
30
+ assert.strictEqual(n, 3);
31
+ assert.strictEqual(fs.readFileSync(path.join(target, 'src/main.ts'), 'utf8'), 'console.log(1)');
32
+ // exécutable gardé, setuid retiré
33
+ assert.strictEqual(fs.statSync(path.join(target, 'scripts/dev.mjs')).mode & 0o7777, 0o755);
34
+ assert.strictEqual(fs.statSync(path.join(target, 'package.json')).mode & 0o7777, 0o644);
35
+ });
36
+
37
+ test('long names through pax headers', (t) => {
38
+ const target = path.join(tmpdir(t), 'app');
39
+ const long = `package/${'d'.repeat(120)}/file.txt`;
40
+ extractTgz(tgz([{ name: 'PaxHeader', type: 'x', data: paxRecord('path', long) }, { name: 'short', data: 'ok' }]), target);
41
+ assert.strictEqual(fs.readFileSync(path.join(target, 'd'.repeat(120), 'file.txt'), 'utf8'), 'ok');
42
+ });
43
+
44
+ test('refuses ../ (path traversal), even after valid entries', (t) => {
45
+ refuses(t, [{ name: 'package/ok.txt', data: 'fine' }, { name: 'package/../../x', data: 'evil' }], /"\.\."/);
46
+ });
47
+
48
+ test('refuses ../ hidden in a pax path', (t) => {
49
+ refuses(t, [{ name: 'PaxHeader', type: 'x', data: paxRecord('path', 'package/a/../../../x') }, { name: 'package/innocent', data: 'evil' }], /"\.\."/);
50
+ });
51
+
52
+ test('refuses absolute paths', (t) => {
53
+ refuses(t, [{ name: '/tmp/poad-evil', data: 'evil' }], /absolute/);
54
+ refuses(t, [{ name: 'C:/evil', data: 'evil' }], /absolute/);
55
+ });
56
+
57
+ test('refuses backslashes', (t) => {
58
+ refuses(t, [{ name: 'package\\..\\..\\x', data: 'evil' }], /backslash/);
59
+ });
60
+
61
+ test('refuses symbolic links, inside or outside the target', (t) => {
62
+ refuses(t, [{ name: 'package/link', type: '2', linkname: '/etc/passwd' }], /symbolic link/);
63
+ refuses(t, [{ name: 'package/link', type: '2', linkname: 'src' }], /symbolic link/);
64
+ });
65
+
66
+ test('refuses hard links', (t) => {
67
+ refuses(t, [{ name: 'package/hl', type: '1', linkname: '../../etc/passwd' }], /hard link/);
68
+ });
69
+
70
+ test('refuses devices and fifos', (t) => {
71
+ refuses(t, [{ name: 'package/dev', type: '3' }], /unsupported type/);
72
+ refuses(t, [{ name: 'package/fifo', type: '6' }], /unsupported type/);
73
+ });
74
+
75
+ test('refuses duplicates and a file used as a folder', (t) => {
76
+ refuses(t, [{ name: 'package/a', data: '1' }, { name: 'package/a', data: '2' }], /duplicate/);
77
+ refuses(t, [{ name: 'package/a', data: '1' }, { name: 'package/a/b', data: '2' }], /parent is a file/);
78
+ });
79
+
80
+ test('refuses a corrupt header and a non-gzip file', (t) => {
81
+ const buf = zlib.gunzipSync(tgz([{ name: 'package/a', data: '1' }]));
82
+ buf[0] ^= 0xff;
83
+ const target = path.join(tmpdir(t), 'app');
84
+ assert.throws(() => extractTgz(zlib.gzipSync(buf), target), /checksum/);
85
+ assert.throws(() => extractTgz(Buffer.from('not gzip'), target), /not a gzip archive/);
86
+ });
87
+
88
+ test('refuses an archive too large once decompressed (zip bomb)', (t) => {
89
+ const target = path.join(tmpdir(t), 'app');
90
+ const bomb = tgz([{ name: 'package/zeros', data: Buffer.alloc(2 * 1024 * 1024) }]);
91
+ assert.throws(() => extractTgz(bomb, target, { maxBytes: 1024 * 1024 }), /larger than/);
92
+ });
93
+
94
+ test('never writes through an existing file or link', (t) => {
95
+ const root = tmpdir(t);
96
+ const target = path.join(root, 'app');
97
+ fs.mkdirSync(target);
98
+ fs.symlinkSync(path.join(root, 'outside.txt'), path.join(target, 'a.txt'));
99
+ assert.throws(() => extractTgz(tgz([{ name: 'package/a.txt', data: 'evil' }]), target), /EEXIST/);
100
+ assert.strictEqual(fs.existsSync(path.join(root, 'outside.txt')), false);
101
+ });
package/utils/engine.js CHANGED
@@ -8,13 +8,14 @@ const usesMinio = (config) => {
8
8
  return Boolean(config.s3) && major === 0 && minor < 6;
9
9
  };
10
10
 
11
- // Storage lines shown by `poad start` and `poad info`.
12
- const storageInfo = (config) => {
11
+ // Storage lines shown by `poad start` and `poad info`. The S3 secret key is
12
+ // shown only with opts.secrets (poad info --secrets).
13
+ const storageInfo = (config, opts = {}) => {
13
14
  if (usesMinio(config)) {
14
15
  return {
15
16
  'S3 URL': `http://localhost:${config.s3.port}/`,
16
17
  'S3 ACCESS KEY': config.s3.access_key,
17
- 'S3 SECRET KEY': config.s3.secret_key,
18
+ 'S3 SECRET KEY': require('./report').secretValue(config.s3.secret_key, opts),
18
19
  'S3 REGION': 'local',
19
20
  };
20
21
  }
@@ -49,7 +50,9 @@ const supportsFlows = (config) => {
49
50
 
50
51
  const consoleUrl = (config) => `http://localhost:${config.web.port}/console`;
51
52
 
52
- const dataInfo = (config) =>
53
+ // La documentation de l'API d'administration s'ouvre avec la clé service_role
54
+ // dans l'URL : seulement avec opts.secrets (poad info --secrets).
55
+ const dataInfo = (config, opts = {}) =>
53
56
  supportsData(config)
54
57
  ? {
55
58
  'REST URL': `http://localhost:${config.web.port}/rest/v1`,
@@ -58,7 +61,9 @@ const dataInfo = (config) =>
58
61
  ? {
59
62
  'Realtime URL': `ws://localhost:${config.web.port}/realtime/v1/websocket`,
60
63
  'Admin API': `http://localhost:${config.web.port}/meta/v1 (service_role key)`,
61
- 'Admin API docs': `http://localhost:${config.web.port}/meta/v1/docs#apikey=${config.auth.service}`,
64
+ 'Admin API docs': opts.secrets
65
+ ? `http://localhost:${config.web.port}/meta/v1/docs#apikey=${config.auth.service}`
66
+ : `http://localhost:${config.web.port}/meta/v1/docs ${require('chalk-v2').grey('(service_role key: poad info --secrets)')}`,
62
67
  }
63
68
  : {}),
64
69
  }
package/utils/git.js CHANGED
@@ -77,7 +77,7 @@ function ensureLines(dir, title, lines) {
77
77
  const have = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
78
78
  const missing = lines.filter((l) => !have.has(l));
79
79
  if (!missing.length) return 0;
80
- fs.writeFileSync(file, (existing ? existing.replace(/\s*$/, '\n') : '') + `\n# ${title}\n${missing.join('\n')}\n`);
80
+ fs.writeFileSync(file, (existing ? existing.replace(/\s*$/, '\n') + '\n' : '') + `# ${title}\n${missing.join('\n')}\n`);
81
81
  return missing.length;
82
82
  }
83
83
 
package/utils/help.js ADDED
@@ -0,0 +1,80 @@
1
+ // Aide des commandes : `poad <commande…> --help` (ou -h) affiche l'aide de la
2
+ // commande et s'arrête là, quelle que soit la commande. Le répartiteur
3
+ // (poad.js) passe ici avant tout le reste : pas de vérification de version,
4
+ // pas de Docker, rien d'exécuté. Sans ce garde-fou, une commande qui ne
5
+ // connaît pas --help le prenait pour un argument quelconque et faisait son
6
+ // travail (poad stop --help arrêtait le projet).
7
+ //
8
+ // Une commande peut exporter help() pour une aide détaillée ; sinon sa
9
+ // description de global/cli.js ou project/cli.js (et ses sous-commandes).
10
+ const path = require('path');
11
+
12
+ const HELP_FLAGS = ['--help', '-h'];
13
+
14
+ /** Aide demandée : --help ou -h n'importe où dans les arguments */
15
+ const helpRequested = (argv = []) => argv.some((a) => HELP_FLAGS.includes(String(a)));
16
+
17
+ /**
18
+ * Commande désignée par les arguments (sans --help/-h) :
19
+ * { scope: 'global'|'project', dir: ['db', 'reset'], entry } ou null.
20
+ */
21
+ function resolveCommand(argv = [], tables = loadTables()) {
22
+ const words = argv.filter((a) => !HELP_FLAGS.includes(String(a)));
23
+ for (const scope of ['global', 'project']) {
24
+ let node = tables[scope];
25
+ const dir = [];
26
+ for (const w of words) {
27
+ if (node && typeof node === 'object' && w !== 'description' && Object.prototype.hasOwnProperty.call(node, w)) {
28
+ node = node[w];
29
+ dir.push(w);
30
+ } else break;
31
+ }
32
+ if (dir.length) return { scope, dir, entry: node };
33
+ }
34
+ return null;
35
+ }
36
+
37
+ function loadTables() {
38
+ return { global: require('../global/cli'), project: require('../project/cli') };
39
+ }
40
+
41
+ /** Description sans l'étiquette [BETA]… */
42
+ const describe = (entry) => {
43
+ const text = typeof entry === 'string' ? entry : (entry && entry.description) || '';
44
+ return text.replace(/^\[[A-Z]+\]\s*/, '');
45
+ };
46
+
47
+ /**
48
+ * Affiche l'aide de la commande désignée par argv. Renvoie false si aucune
49
+ * commande ne correspond (le répartiteur montre alors la liste générale).
50
+ */
51
+ function printHelp(argv = [], { tables = loadTables(), base = path.join(__dirname, '..') } = {}) {
52
+ const chalk = require('chalk-v2');
53
+ const cmd = resolveCommand(argv, tables);
54
+ if (!cmd) return false;
55
+ // Aide détaillée exportée par le module de la commande
56
+ let unit = null;
57
+ try {
58
+ unit = require(path.join(base, cmd.scope, ...cmd.dir));
59
+ } catch {
60
+ unit = null;
61
+ }
62
+ if (unit && typeof unit.help === 'function') {
63
+ unit.help();
64
+ return true;
65
+ }
66
+ const name = `poad ${cmd.dir.join(' ')}`;
67
+ const subs = cmd.entry && typeof cmd.entry === 'object' ? Object.entries(cmd.entry).filter(([k]) => k !== 'description') : [];
68
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright(name)} ${chalk.cyan(subs.length ? '<subcommand> [<args>]' : '[<args>]')}`);
69
+ console.log(' ');
70
+ console.log(` ${describe(cmd.entry)}`);
71
+ if (subs.length) {
72
+ console.log(' ');
73
+ const width = Math.max(...subs.map(([k]) => k.length));
74
+ for (const [k, v] of subs) console.log(` ${chalk.cyanBright(`${name} ${k.padEnd(width)}`)} ${describe(v)}`);
75
+ }
76
+ console.log(' ');
77
+ return true;
78
+ }
79
+
80
+ module.exports = { HELP_FLAGS, helpRequested, resolveCommand, printHelp };
@@ -0,0 +1,145 @@
1
+ // Registre npm, sans npm ni dépendance : métadonnées d'un paquet, archive de
2
+ // sa dernière version, vérification de son intégrité (sha512 publié par le
3
+ // registre) avant tout usage.
4
+ //
5
+ // Cache : ~/.poad/starters/ garde la dernière archive vérifiée de chaque
6
+ // paquet et son empreinte ; hors ligne, c'est elle qui sert (vérifiée à
7
+ // nouveau à la lecture).
8
+ const crypto = require('crypto');
9
+ const fs = require('fs');
10
+ const os = require('os');
11
+ const path = require('path');
12
+
13
+ const REGISTRY = 'https://registry.npmjs.org';
14
+ // Archive d'un modèle d'application : quelques centaines de Ko ; au-delà de
15
+ // 50 Mo, ce n'est plus un modèle
16
+ const MAX_TARBALL = 50 * 1024 * 1024;
17
+
18
+ class RegistryError extends Error {}
19
+
20
+ const cacheDir = () => path.join(os.homedir(), '.poad', 'starters');
21
+ const cacheBase = (name) => path.join(cacheDir(), name.replace(/^@/, '').replace(/[^a-zA-Z0-9._-]+/g, '__'));
22
+
23
+ /** URL des métadonnées : le « / » d'un nom à portée (@scope/nom) est encodé */
24
+ const metadataUrl = (name, registry = REGISTRY) => `${registry.replace(/\/+$/, '')}/${name.replace('/', '%2f')}`;
25
+
26
+ /**
27
+ * Métadonnées abrégées d'un paquet (dist-tags, versions avec dist) :
28
+ * { status: 'ok', data } | { status: 'missing' } (404) | { status: 'offline', error }
29
+ */
30
+ async function packageMetadata(name, { registry = REGISTRY, timeout = 3000 } = {}) {
31
+ try {
32
+ const res = await fetch(metadataUrl(name, registry), {
33
+ signal: AbortSignal.timeout(timeout),
34
+ headers: { accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8' },
35
+ });
36
+ if (res.status === 404) return { status: 'missing' };
37
+ if (!res.ok) return { status: 'offline', error: `HTTP ${res.status}` };
38
+ return { status: 'ok', data: await res.json() };
39
+ } catch (err) {
40
+ return { status: 'offline', error: err.name === 'TimeoutError' ? 'timeout' : err.message };
41
+ }
42
+ }
43
+
44
+ /** { version, tarball, integrity } de la version « latest », ou une erreur */
45
+ function latestDist(name, data) {
46
+ const version = data && data['dist-tags'] && data['dist-tags'].latest;
47
+ const meta = version && data.versions && data.versions[version];
48
+ if (!meta || !meta.dist) throw new RegistryError(`${name}: no "latest" version in the registry`);
49
+ const { tarball, integrity } = meta.dist;
50
+ if (typeof tarball !== 'string' || !tarball.startsWith('https://')) throw new RegistryError(`${name}@${version}: the tarball URL is not HTTPS`);
51
+ if (!parseIntegrity(integrity)) throw new RegistryError(`${name}@${version}: no sha512 integrity in the registry metadata`);
52
+ return { version, tarball, integrity };
53
+ }
54
+
55
+ /** Empreinte(s) sha512 d'une chaîne SRI (« sha512-<base64> », éventuellement plusieurs) */
56
+ function parseIntegrity(integrity) {
57
+ if (typeof integrity !== 'string') return null;
58
+ const hashes = integrity
59
+ .trim()
60
+ .split(/\s+/)
61
+ .map((h) => /^sha512-([A-Za-z0-9+/]+={0,2})(\?.*)?$/.exec(h))
62
+ .filter(Boolean)
63
+ .map((m) => Buffer.from(m[1], 'base64'))
64
+ .filter((b) => b.length === 64);
65
+ return hashes.length ? hashes : null;
66
+ }
67
+
68
+ /** Lève une erreur si le contenu ne correspond pas à l'empreinte sha512 publiée */
69
+ function verifyIntegrity(buf, integrity, label = 'archive') {
70
+ const expected = parseIntegrity(integrity);
71
+ if (!expected) throw new RegistryError(`${label}: no sha512 integrity to check against`);
72
+ const actual = crypto.createHash('sha512').update(buf).digest();
73
+ if (!expected.some((e) => crypto.timingSafeEqual(e, actual))) {
74
+ throw new RegistryError(`${label}: integrity check failed (sha512 mismatch): the download was altered or corrupted, nothing was extracted`);
75
+ }
76
+ }
77
+
78
+ async function download(url, { timeout = 60000, maxBytes = MAX_TARBALL } = {}) {
79
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeout), redirect: 'follow' });
80
+ if (!res.ok) throw new RegistryError(`download failed: HTTP ${res.status}`);
81
+ if (!res.url.startsWith('https://')) throw new RegistryError('download redirected outside HTTPS');
82
+ const declared = Number(res.headers.get('content-length'));
83
+ if (declared > maxBytes) throw new RegistryError(`tarball larger than ${maxBytes} bytes`);
84
+ const chunks = [];
85
+ let total = 0;
86
+ for await (const chunk of res.body) {
87
+ total += chunk.length;
88
+ if (total > maxBytes) throw new RegistryError(`tarball larger than ${maxBytes} bytes`);
89
+ chunks.push(chunk);
90
+ }
91
+ return Buffer.concat(chunks);
92
+ }
93
+
94
+ function readCached(name) {
95
+ try {
96
+ const meta = JSON.parse(fs.readFileSync(`${cacheBase(name)}.json`, 'utf8'));
97
+ const buf = fs.readFileSync(`${cacheBase(name)}.tgz`);
98
+ verifyIntegrity(buf, meta.integrity, `${name}@${meta.version} (cache)`);
99
+ return { ...meta, buf };
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ function writeCached(name, { version, integrity, buf }) {
106
+ try {
107
+ fs.mkdirSync(cacheDir(), { recursive: true });
108
+ fs.writeFileSync(`${cacheBase(name)}.tgz`, buf);
109
+ fs.writeFileSync(`${cacheBase(name)}.json`, JSON.stringify({ name, version, integrity, at: new Date().toISOString() }));
110
+ } catch {
111
+ // cache facultatif
112
+ }
113
+ }
114
+
115
+ /** Version connue en cache (sans lire l'archive), ou null */
116
+ function cachedVersion(name) {
117
+ try {
118
+ return JSON.parse(fs.readFileSync(`${cacheBase(name)}.json`, 'utf8')).version || null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Archive vérifiée de la dernière version d'un paquet : { version, buf, source: 'registry'|'cache' }.
126
+ * metadata : résultat de packageMetadata déjà obtenu (évite une seconde requête).
127
+ */
128
+ async function fetchLatestTarball(name, { registry = REGISTRY, metadata, timeout } = {}) {
129
+ const meta = metadata || (await packageMetadata(name, { registry, timeout }));
130
+ if (meta.status === 'missing') throw new RegistryError(`${name} is not published on npm`);
131
+ if (meta.status === 'offline') {
132
+ const cached = readCached(name);
133
+ if (cached) return { version: cached.version, buf: cached.buf, source: 'cache' };
134
+ throw new RegistryError(`the npm registry cannot be reached (${meta.error}) and ${name} is not in the cache`);
135
+ }
136
+ const dist = latestDist(name, meta.data);
137
+ const cached = readCached(name);
138
+ if (cached && cached.version === dist.version && cached.integrity === dist.integrity) return { version: dist.version, buf: cached.buf, source: 'cache' };
139
+ const buf = await download(dist.tarball);
140
+ verifyIntegrity(buf, dist.integrity, `${name}@${dist.version}`);
141
+ writeCached(name, { version: dist.version, integrity: dist.integrity, buf });
142
+ return { version: dist.version, buf, source: 'registry' };
143
+ }
144
+
145
+ module.exports = { REGISTRY, RegistryError, packageMetadata, latestDist, parseIntegrity, verifyIntegrity, fetchLatestTarball, cachedVersion, metadataUrl };
package/utils/report.js CHANGED
@@ -1,8 +1,19 @@
1
1
  // Affichage de l'état du projet, commun à poad info et poad start : le projet
2
2
  // (URL, base, clés, migrations), puis le panneau des services (Mailpit,
3
3
  // Keycloak, Valkey, exécuteur des flows) avec leur état et leurs accès.
4
+ //
5
+ // Secrets : jamais affichés par défaut (un terminal se partage, se filme, se
6
+ // colle dans un ticket). Le secret JWT, la clé service_role, la clé secrète S3
7
+ // et le mot de passe admin de Keycloak sont remplacés par « hidden » ; seul
8
+ // `poad info --secrets` les montre. La clé anon reste : elle est faite pour le
9
+ // navigateur.
4
10
  const path = require('path');
5
11
 
12
+ const SECRETS_HINT = 'hidden · poad info --secrets';
13
+
14
+ /** Valeur secrète affichée seulement si demandée (opts.secrets) */
15
+ const secretValue = (value, opts = {}) => (opts.secrets ? String(value) : require('chalk-v2').grey(SECRETS_HINT));
16
+
6
17
  async function migrationsLine(root, config) {
7
18
  const migrations = require('./migrations');
8
19
  const count = migrations.files(root).list.length;
@@ -27,7 +38,7 @@ async function migrationsLine(root, config) {
27
38
  }
28
39
  }
29
40
 
30
- async function printProject(root, config) {
41
+ async function printProject(root, config, opts = {}) {
31
42
  const chalk = require('chalk-v2');
32
43
  const prettyoutput = require('prettyoutput');
33
44
  const { storageInfo, dataInfo, supportsConsole, consoleUrl } = require('./engine');
@@ -49,12 +60,12 @@ async function printProject(root, config) {
49
60
  : 'this machine only (127.0.0.1)',
50
61
  'API URL': `http://localhost:${config.web.port}`,
51
62
  'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
52
- ...storageInfo(config),
53
- ...dataInfo(config),
63
+ ...storageInfo(config, opts),
64
+ ...dataInfo(config, opts),
54
65
  ...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
55
- 'JWT secret': `${config.auth.secret}`,
66
+ 'JWT secret': secretValue(config.auth.secret, opts),
56
67
  'anon key': config.auth.anon,
57
- 'service_role key': config.auth.service,
68
+ 'service_role key': secretValue(config.auth.service, opts),
58
69
  Config: `${path.relative(process.cwd(), root)} (secrets: ${path.relative(process.cwd(), require('./config').secretsFile(root))})`,
59
70
  };
60
71
  const line = await migrationsLine(root, config);
@@ -62,7 +73,7 @@ async function printProject(root, config) {
62
73
  console.log(prettyoutput(info));
63
74
  }
64
75
 
65
- async function printServices(root, config) {
76
+ async function printServices(root, config, opts = {}) {
66
77
  const chalk = require('chalk-v2');
67
78
  const Docker = require('dockerode');
68
79
  const docker = new Docker();
@@ -91,7 +102,7 @@ async function printServices(root, config) {
91
102
  const tag = auto ? chalk.cyan(' auto') : '';
92
103
  if (running) {
93
104
  console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}${tag}`);
94
- for (const [k, v] of Object.entries(s.info(config, root))) {
105
+ for (const [k, v] of Object.entries(s.info(config, root, opts))) {
95
106
  // Une liste (comptes de test) : une ligne par entrée, alignées
96
107
  const lines = Array.isArray(v) ? v : [v];
97
108
  lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
@@ -109,10 +120,10 @@ async function printServices(root, config) {
109
120
  console.log(' ');
110
121
  }
111
122
 
112
- /** Projet puis services */
113
- async function printReport(root, config) {
114
- await printProject(root, config);
115
- await printServices(root, config);
123
+ /** Projet puis services ; opts.secrets : montrer les secrets (poad info --secrets) */
124
+ async function printReport(root, config, opts = {}) {
125
+ await printProject(root, config, opts);
126
+ await printServices(root, config, opts);
116
127
  }
117
128
 
118
- module.exports = { printReport, printProject, printServices, migrationsLine };
129
+ module.exports = { printReport, printProject, printServices, migrationsLine, secretValue, SECRETS_HINT };
package/utils/services.js CHANGED
@@ -38,7 +38,7 @@ const SERVICES = [
38
38
  configured: (config) => Boolean(config.keycloak && (config.keycloak.port || config.keycloak.shared === true)),
39
39
  autostart: (config) => Boolean(config.keycloak && config.keycloak.autostart === true),
40
40
  savePort: (root, port) => kc.savePort(root, port),
41
- info: (config, root) => {
41
+ info: (config, root, opts = {}) => {
42
42
  const shared = require('./keycloak-shared');
43
43
  const state = shared.isShared(config) ? shared.readState() : null;
44
44
  const base = `http://localhost:${state ? state.port : config.keycloak.port}`;
@@ -48,7 +48,7 @@ const SERVICES = [
48
48
  const out = { URL: base + (state ? ' (shared by the local projects)' : ''), Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
49
49
  if (project) {
50
50
  // Deux realms, deux usages : ne pas essayer alice sur la console d'admin
51
- out['Admin console'] = [`${base}/admin`, `admin ${state ? state.admin_password : project.secrets.admin_password}`];
51
+ out['Admin console'] = [`${base}/admin`, `admin ${require('./report').secretValue(state ? state.admin_password : project.secrets.admin_password, opts)}`];
52
52
  out['Test users'] = [
53
53
  `realm "${realm}" : "Continuer avec Keycloak" in the app, or ${base}/realms/${realm}/account`,
54
54
  ...project.users.map(