poad 2.37.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,95 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const crypto = require('crypto');
4
+ const { verifyIntegrity, parseIntegrity, latestDist, metadataUrl, RegistryError } = require('../utils/registry');
5
+
6
+ const sri = (buf) => `sha512-${crypto.createHash('sha512').update(buf).digest('base64')}`;
7
+
8
+ test('accepts content matching its sha512 integrity', () => {
9
+ const buf = Buffer.from('template archive');
10
+ assert.doesNotThrow(() => verifyIntegrity(buf, sri(buf)));
11
+ // plusieurs empreintes SRI : une seule doit correspondre
12
+ assert.doesNotThrow(() => verifyIntegrity(buf, `${sri(Buffer.from('other'))} ${sri(buf)}`));
13
+ });
14
+
15
+ test('refuses content whose sha512 does not match (integrity mismatch)', () => {
16
+ const buf = Buffer.from('template archive');
17
+ const tampered = Buffer.from('template archivE');
18
+ assert.throws(() => verifyIntegrity(tampered, sri(buf), 'x@1.0.0'), (err) => err instanceof RegistryError && /integrity check failed/.test(err.message));
19
+ });
20
+
21
+ test('refuses a missing or non-sha512 integrity', () => {
22
+ const buf = Buffer.from('a');
23
+ assert.throws(() => verifyIntegrity(buf, undefined), /no sha512 integrity/);
24
+ assert.throws(() => verifyIntegrity(buf, `sha1-${crypto.createHash('sha1').update(buf).digest('base64')}`), /no sha512 integrity/);
25
+ assert.strictEqual(parseIntegrity('sha512-short'), null);
26
+ });
27
+
28
+ test('latest version: HTTPS tarball and sha512 integrity are required', () => {
29
+ const data = (dist) => ({ 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': { dist } } });
30
+ const integrity = sri(Buffer.from('x'));
31
+ assert.deepStrictEqual(latestDist('p', data({ tarball: 'https://r/p.tgz', integrity })), { version: '1.0.0', tarball: 'https://r/p.tgz', integrity });
32
+ assert.throws(() => latestDist('p', data({ tarball: 'http://r/p.tgz', integrity })), /not HTTPS/);
33
+ assert.throws(() => latestDist('p', data({ tarball: 'https://r/p.tgz', shasum: 'abc' })), /no sha512 integrity/);
34
+ assert.throws(() => latestDist('p', { 'dist-tags': {} }), /no "latest"/);
35
+ });
36
+
37
+ test('scoped package metadata URL', () => {
38
+ assert.strictEqual(metadataUrl('@poadio/starter-next'), 'https://registry.npmjs.org/@poadio%2fstarter-next');
39
+ });
40
+
41
+ // Téléchargement complet, fetch remplacé : ni réseau ni ~/.poad touchés
42
+ const fs = require('fs');
43
+ const os = require('os');
44
+ const path = require('path');
45
+ const { fetchLatestTarball } = require('../utils/registry');
46
+ const { tmpdir } = require('./helpers');
47
+
48
+ const withHome = (t) => {
49
+ const home = tmpdir(t, 'poad-home-');
50
+ const old = process.env.HOME;
51
+ process.env.HOME = home;
52
+ t.after(() => (process.env.HOME = old));
53
+ return home;
54
+ };
55
+
56
+ const stubFetch = (t, body) => {
57
+ const old = globalThis.fetch;
58
+ globalThis.fetch = async (url) => {
59
+ const res = new Response(body, { status: 200 });
60
+ Object.defineProperty(res, 'url', { value: url });
61
+ return res;
62
+ };
63
+ t.after(() => (globalThis.fetch = old));
64
+ };
65
+
66
+ const metadataFor = (integrity) => ({
67
+ status: 'ok',
68
+ data: { 'dist-tags': { latest: '1.2.3' }, versions: { '1.2.3': { dist: { tarball: 'https://registry.example/p-1.2.3.tgz', integrity } } } },
69
+ });
70
+
71
+ test('download: a tarball that does not match the registry integrity is refused and not cached', async (t) => {
72
+ const home = withHome(t);
73
+ assert.strictEqual(os.homedir(), home);
74
+ stubFetch(t, Buffer.from('tampered tarball'));
75
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: metadataFor(sri(Buffer.from('genuine tarball'))) }), /integrity check failed/);
76
+ assert.strictEqual(fs.existsSync(path.join(home, '.poad', 'starters')), false);
77
+ });
78
+
79
+ test('download: verified tarball is cached, then used offline; a tampered cache is ignored', async (t) => {
80
+ const home = withHome(t);
81
+ const buf = Buffer.from('genuine tarball');
82
+ stubFetch(t, buf);
83
+ const got = await fetchLatestTarball('@poadio/starter-x', { metadata: metadataFor(sri(buf)) });
84
+ assert.strictEqual(got.source, 'registry');
85
+ assert.strictEqual(got.version, '1.2.3');
86
+ const offline = await fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'offline', error: 'timeout' } });
87
+ assert.strictEqual(offline.source, 'cache');
88
+ assert.ok(offline.buf.equals(buf));
89
+ fs.writeFileSync(path.join(home, '.poad', 'starters', 'poadio__starter-x.tgz'), 'tampered');
90
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'offline', error: 'timeout' } }), /not in the cache/);
91
+ });
92
+
93
+ test('unpublished package: not published on npm', async () => {
94
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'missing' } }), /not published/);
95
+ });
@@ -0,0 +1,94 @@
1
+ // Secrets jamais affichés par défaut : poad info / poad start montrent
2
+ // « hidden · poad info --secrets » à la place du secret JWT, de la clé
3
+ // service_role, de la clé secrète S3 et du mot de passe admin de Keycloak ;
4
+ // poad info --secrets les montre. La clé anon (faite pour le navigateur) reste.
5
+ const test = require('node:test');
6
+ const assert = require('node:assert');
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { tmpdir } = require('./helpers');
10
+
11
+ const JWT = 'jwt-secret-value-for-test-0123456789';
12
+ const SERVICE = 'service-role-key-for-test-abcdef';
13
+ const ANON = 'anon-key-for-test-public';
14
+ const S3_SECRET = 's3-secret-key-for-test';
15
+ const KC_ADMIN = 'KcAdminPassForTest';
16
+
17
+ // Port 1 : rien n'écoute, la ligne des migrations échoue tout de suite
18
+ const config = (engine = '0.20.0') => ({
19
+ project_id: 'demo',
20
+ project_uuid: 'poad-test-not-a-container',
21
+ engine,
22
+ web: { port: 1 },
23
+ db: { port: 1 },
24
+ auth: { secret: JWT, anon: ANON, service: SERVICE },
25
+ s3: { port: 1, access_key: 'access', secret_key: S3_SECRET },
26
+ });
27
+
28
+ /** Sortie console d'une fonction asynchrone */
29
+ async function capture(fn) {
30
+ const lines = [];
31
+ const log = console.log;
32
+ console.log = (...a) => lines.push(a.join(' '));
33
+ try {
34
+ await fn();
35
+ } finally {
36
+ console.log = log;
37
+ }
38
+ return lines.join('\n');
39
+ }
40
+
41
+ function project(t) {
42
+ const dir = tmpdir(t);
43
+ fs.mkdirSync(path.join(dir, 'poad'));
44
+ const root = path.join(dir, 'poad', 'config.toml');
45
+ fs.writeFileSync(root, 'project_id = "demo"\n');
46
+ return root;
47
+ }
48
+
49
+ test('poad info: JWT secret, service_role key and the key in the admin docs URL hidden by default; anon key shown', async (t) => {
50
+ const { printProject } = require('../utils/report');
51
+ const out = await capture(() => printProject(project(t), config()));
52
+ assert.ok(!out.includes(JWT), 'JWT secret not printed');
53
+ assert.ok(!out.includes(SERVICE), 'service_role key not printed');
54
+ assert.ok(out.includes(ANON), 'anon key printed');
55
+ assert.match(out, /hidden · poad info --secrets/);
56
+ });
57
+
58
+ test('poad info --secrets: every value shown', async (t) => {
59
+ const { printProject } = require('../utils/report');
60
+ const out = await capture(() => printProject(project(t), config(), { secrets: true }));
61
+ assert.ok(out.includes(JWT));
62
+ assert.ok(out.includes(SERVICE));
63
+ assert.ok(out.includes(`#apikey=${SERVICE}`));
64
+ assert.ok(out.includes(ANON));
65
+ });
66
+
67
+ test('old engines (MinIO): the S3 secret key is hidden by default', () => {
68
+ const { storageInfo } = require('../utils/engine');
69
+ const hidden = JSON.stringify(storageInfo(config('0.5.0')));
70
+ assert.ok(!hidden.includes(S3_SECRET));
71
+ assert.ok(JSON.stringify(storageInfo(config('0.5.0'), { secrets: true })).includes(S3_SECRET));
72
+ });
73
+
74
+ test('Keycloak panel: the admin password is hidden by default, test users stay (versioned test set)', (t) => {
75
+ const root = project(t);
76
+ const poadDir = path.dirname(root);
77
+ fs.mkdirSync(path.join(poadDir, 'data', 'keycloak'), { recursive: true });
78
+ fs.writeFileSync(path.join(poadDir, 'data', 'keycloak', 'users.json'), JSON.stringify({ admin_password: KC_ADMIN, signing_key: 'x', client_secret: 'y', ids: { alice: 'id-a' }, passwords: {} }));
79
+ fs.writeFileSync(path.join(poadDir, 'keycloak.json'), JSON.stringify({ realm: 'demo', roles: ['user'], groups: [], users: [{ username: 'alice', email: 'alice@poad.test', password: 'alicepass', emailVerified: true, roles: ['user'], groups: [], attributes: {} }] }));
80
+ const kc = require('../utils/services').SERVICES.find((s) => s.id === 'keycloak');
81
+ const cfg = { ...config(), keycloak: { port: 1 } };
82
+ const hidden = JSON.stringify(kc.info(cfg, root));
83
+ assert.ok(!hidden.includes(KC_ADMIN), 'admin password not printed');
84
+ assert.match(hidden, /hidden · poad info --secrets/);
85
+ assert.ok(hidden.includes('alicepass'), 'test user password shown');
86
+ assert.ok(JSON.stringify(kc.info(cfg, root, { secrets: true })).includes(KC_ADMIN));
87
+ });
88
+
89
+ test('poad info flag: --secrets or secrets', () => {
90
+ const { wantsSecrets } = require('../project/info');
91
+ assert.strictEqual(wantsSecrets({}), false);
92
+ assert.strictEqual(wantsSecrets({ '--secrets': true }), true);
93
+ assert.strictEqual(wantsSecrets({ secrets: true }), true);
94
+ });
@@ -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
  }
@@ -71,13 +76,10 @@ module.exports = { usesMinio, storageInfo, supportsData, supportsRealtime, suppo
71
76
  // est d'abord sauvegardé dans poad/backups (poad upgrade --rollback y revient).
72
77
  // poad start ne la propose qu'au sein de la même version mineure (seules des
73
78
  // migrations s'appliquent) ; poad upgrade accepte aussi un saut de mineure.
74
- const parseVersion = (v) => String(v || '').split('.').map(Number);
75
- const isNewer = (a, b) => {
76
- const pa = parseVersion(a);
77
- const pb = parseVersion(b);
78
- for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0);
79
- return false;
80
- };
79
+ const { compareVersions } = require('./version');
80
+ const parseVersion = (v) => String(v || '').split(/[.-]/).slice(0, 3).map((n) => parseInt(n, 10) || 0);
81
+ // x.y.z-beta.N passe avant x.y.z (utils/version.js)
82
+ const isNewer = (a, b) => compareVersions(a, b) > 0;
81
83
 
82
84
  const ask = (question) =>
83
85
  new Promise((resolve) => {
@@ -137,7 +139,8 @@ const offerEngineUpgrade = async (root, config, args = {}) => {
137
139
  const chalk = require('chalk-v2');
138
140
  const current = config.engine;
139
141
  if (args.noOffer) return current;
140
- const target = String(args.target || (await require('./latest').engineRelease()) || '');
142
+ const latest = require('./latest');
143
+ const target = String(args.target || (await latest.engineRelease({ channel: latest.engineChannel(config, args) })) || '');
141
144
  if (!target || !isNewer(target, current)) return current;
142
145
  const [cMaj, cMin] = parseVersion(current);
143
146
  const [tMaj, tMin] = parseVersion(target);
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 };