poad 2.38.0 → 2.40.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,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(
@@ -0,0 +1,241 @@
1
+ // Modèles d'application (« starters ») publiés sur npm sous @poadio/starter-<nom>,
2
+ // et ce qu'il faut faire d'un modèle extrait pour en faire une application :
3
+ // fichiers de publication retirés, .gitignore rétabli, package.json réécrit.
4
+ // Partagé par poad create et poad client init.
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+
8
+ const TEMPLATES = [
9
+ { value: 'angular', label: 'Angular', package: '@poadio/starter-angular' },
10
+ { value: 'next', label: 'Next.js', package: '@poadio/starter-next' },
11
+ { value: 'nuxt', label: 'Nuxt', package: '@poadio/starter-nuxt' },
12
+ { value: 'vanilla', label: 'Vanilla (HTML, CSS, JS)', package: '@poadio/starter-vanilla' },
13
+ ];
14
+
15
+ const templateByValue = (value) => TEMPLATES.find((t) => t.value === String(value || '').toLowerCase()) || null;
16
+
17
+ // Fichiers d'un modèle publié qui n'ont rien à faire dans une application
18
+ // neuve. poad/ : jamais repris (config.toml et secrets sont ceux de poad init).
19
+ const STRIP = ['.npmignore', 'poad/config.toml', 'poad/secrets.toml', 'poad/data', 'poad/backups', 'public/env.json', '.env.local', 'node_modules'];
20
+
21
+ // npm ne publie jamais .gitignore : un modèle le livre sous le nom « gitignore »
22
+ // (convention des create-*), ou, ancien comportement de npm, en .npmignore.
23
+ const GITIGNORE_SOURCES = ['gitignore', '_gitignore', '.npmignore'];
24
+
25
+ // package.json de l'application, règle par règle :
26
+ // fonction -> nouvelle valeur (undefined : clé retirée)
27
+ // null -> clé retirée (champs de publication du modèle)
28
+ const DROP = null;
29
+ const PACKAGE_RULES = {
30
+ name: (pkg, ctx) => ctx.name,
31
+ version: () => '0.1.0',
32
+ private: () => true,
33
+ title: (pkg, ctx) => ctx.title || pkg.title,
34
+ // La description du paquet parle du modèle : l'application prend la sienne
35
+ description: (pkg) => (pkg.poad && pkg.poad.template && pkg.poad.template.description) || undefined,
36
+ files: DROP,
37
+ publishConfig: DROP,
38
+ repository: DROP,
39
+ bugs: DROP,
40
+ homepage: DROP,
41
+ author: DROP,
42
+ contributors: DROP,
43
+ funding: DROP,
44
+ keywords: DROP,
45
+ license: DROP,
46
+ // Origine gardée pour mémoire ; les métadonnées de modèle ne servent plus
47
+ poad: (pkg, ctx) => {
48
+ const poad = { ...(pkg.poad || {}), from: ctx.from };
49
+ delete poad.template;
50
+ return poad;
51
+ },
52
+ };
53
+
54
+ /** package.json d'application à partir de celui du modèle (ctx : { name, title, from }) */
55
+ function rewritePackageJson(pkg, ctx) {
56
+ const out = { ...pkg };
57
+ for (const [key, rule] of Object.entries(PACKAGE_RULES)) {
58
+ const value = rule === DROP ? undefined : rule(pkg, ctx);
59
+ if (value === undefined) delete out[key];
60
+ else out[key] = value;
61
+ }
62
+ // Ordre lisible : name, version, private d'abord
63
+ const head = ['name', 'title', 'description', 'version', 'private'].filter((k) => k in out);
64
+ return Object.fromEntries([...head.map((k) => [k, out[k]]), ...Object.entries(out).filter(([k]) => !head.includes(k))]);
65
+ }
66
+
67
+ /** Nom de paquet npm valide tiré d'un nom de dossier */
68
+ function packageName(dir) {
69
+ const name = String(dir || '')
70
+ .toLowerCase()
71
+ .replace(/[^a-z0-9._-]+/g, '-')
72
+ .replace(/^[-._]+|[-._]+$/g, '')
73
+ .slice(0, 214);
74
+ return name || 'app';
75
+ }
76
+
77
+ /**
78
+ * Prépare un modèle extrait dans dir : .gitignore rétabli puis complété des
79
+ * lignes de poad.template.gitignore, fichiers de publication retirés.
80
+ * Renvoie { gitignore: 'restored'|'template'|null, stripped: [...] }.
81
+ */
82
+ function prepareStarter(dir) {
83
+ const result = { gitignore: null, stripped: [] };
84
+ const gi = path.join(dir, '.gitignore');
85
+ const src = GITIGNORE_SOURCES.map((n) => path.join(dir, n)).find((f) => fs.existsSync(f) && fs.statSync(f).isFile());
86
+ if (src && !fs.existsSync(gi)) {
87
+ fs.renameSync(src, gi);
88
+ result.gitignore = 'restored';
89
+ } else if (src && path.basename(src) !== '.npmignore') {
90
+ // Dossier qui a déjà son .gitignore (front posé à la racine du projet) :
91
+ // les lignes du modèle y sont ajoutées, le fichier « gitignore » disparaît
92
+ const lines = fs.readFileSync(src, 'utf8').split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
93
+ require('./git').ensureLines(dir, 'Front-end', lines);
94
+ fs.rmSync(src);
95
+ result.gitignore = 'merged';
96
+ }
97
+ for (const rel of STRIP) {
98
+ const abs = path.join(dir, ...rel.split('/'));
99
+ if (fs.existsSync(abs)) {
100
+ fs.rmSync(abs, { recursive: true, force: true });
101
+ result.stripped.push(rel);
102
+ }
103
+ }
104
+ // Lignes propres au modèle, déclarées dans package.json (poad.template.gitignore)
105
+ const pkg = readPackage(dir);
106
+ const lines = pkg && pkg.poad && pkg.poad.template && Array.isArray(pkg.poad.template.gitignore) ? pkg.poad.template.gitignore.filter((l) => typeof l === 'string' && l.trim()) : [];
107
+ if (lines.length) {
108
+ const label = (pkg.poad.template.framework || 'template').toString();
109
+ require('./git').ensureLines(dir, `Front-end (${label})`, lines);
110
+ result.gitignore = result.gitignore || 'template';
111
+ }
112
+ return result;
113
+ }
114
+
115
+ function readPackage(dir) {
116
+ try {
117
+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ const LOCKFILES = { bun: ['bun.lock', 'bun.lockb'], npm: ['package-lock.json', 'npm-shrinkwrap.json'], pnpm: ['pnpm-lock.yaml'], yarn: ['yarn.lock'] };
124
+
125
+ /**
126
+ * Gestionnaire de paquets choisi : les fichiers de verrouillage des autres
127
+ * gestionnaires sont retirés, et le champ packageManager s'il en désigne un
128
+ * autre (pnpm et corepack refusent d'installer sinon).
129
+ */
130
+ function adaptToPackageManager(dir, pm) {
131
+ const removed = [];
132
+ for (const [other, files] of Object.entries(LOCKFILES)) {
133
+ if (other === pm) continue;
134
+ for (const f of files) {
135
+ if (fs.existsSync(path.join(dir, f))) {
136
+ fs.rmSync(path.join(dir, f));
137
+ removed.push(f);
138
+ }
139
+ }
140
+ }
141
+ const pkg = readPackage(dir);
142
+ if (pkg && typeof pkg.packageManager === 'string' && !pkg.packageManager.startsWith(`${pm}@`)) {
143
+ delete pkg.packageManager;
144
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
145
+ removed.push('packageManager (package.json)');
146
+ }
147
+ return removed;
148
+ }
149
+
150
+ /** Premier port libre sur 127.0.0.1 à partir de start (4200 est souvent pris) */
151
+ async function freePort(start, max = start + 100) {
152
+ const net = require('net');
153
+ // Rien n'y répond (IPv4 ni IPv6 : un serveur sur [::1] seul n'empêche pas
154
+ // d'écouter sur 127.0.0.1) et on peut y écouter
155
+ const answers = (port, host) =>
156
+ new Promise((ok) => {
157
+ const c = net.connect({ port, host });
158
+ c.setTimeout(500, () => c.destroy() && ok(false));
159
+ c.once('connect', () => c.destroy() && ok(true));
160
+ c.once('error', () => ok(false));
161
+ });
162
+ const bindable = (port) =>
163
+ new Promise((ok) => {
164
+ const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
165
+ s.listen(port, '127.0.0.1');
166
+ });
167
+ const free = async (port) => !(await answers(port, '127.0.0.1')) && !(await answers(port, '::1')) && (await bindable(port));
168
+ let port = start;
169
+ while (!(await free(port)) && port < max) port++;
170
+ return port;
171
+ }
172
+
173
+ /** Premier port libre à partir de start qui n'est pas dans exclude */
174
+ async function nextPort(start, exclude = new Set()) {
175
+ let port = start;
176
+ for (;;) {
177
+ port = await freePort(port);
178
+ if (!exclude.has(port)) return port;
179
+ port++;
180
+ }
181
+ }
182
+
183
+ // Frameworks reconnus : étiquette affichée, dépendance qui les trahit, port de
184
+ // développement par défaut quand le modèle n'en déclare pas (celui de l'outil).
185
+ const FRAMEWORKS = {
186
+ angular: { label: 'Angular', dependency: '@angular/core', port: 4300 },
187
+ next: { label: 'Next.js', dependency: 'next', port: 3000 },
188
+ nuxt: { label: 'Nuxt', dependency: 'nuxt', port: 3000 },
189
+ vanilla: { label: 'Vanilla', dependency: null, port: null },
190
+ };
191
+
192
+ /** Framework d'un package.json : poad.template.framework, sinon ses dépendances ; null si inconnu */
193
+ function frameworkOf(pkg = {}) {
194
+ const declared = pkg && pkg.poad && pkg.poad.template && pkg.poad.template.framework;
195
+ if (declared && FRAMEWORKS[String(declared).toLowerCase()]) return String(declared).toLowerCase();
196
+ const deps = { ...((pkg && pkg.devDependencies) || {}), ...((pkg && pkg.dependencies) || {}) };
197
+ for (const [name, fw] of Object.entries(FRAMEWORKS)) if (fw.dependency && deps[fw.dependency]) return name;
198
+ return null;
199
+ }
200
+
201
+ /** Port déclaré par le modèle : poad.port (gardé dans l'application), sinon poad.template.port */
202
+ function declaredPort(pkg = {}) {
203
+ const poad = (pkg && pkg.poad) || {};
204
+ return Number(poad.port) || Number(poad.template && poad.template.port) || null;
205
+ }
206
+
207
+ /**
208
+ * Serveur de développement du front, d'après le package.json du modèle (avant
209
+ * réécriture : poad.template y est encore) :
210
+ * - Angular : premier port libre à partir du port déclaré (4300 par défaut),
211
+ * écrit dans angular.json (ng serve) ;
212
+ * - les autres (Next.js…) lisent leur port eux-mêmes (poad.port, gardé dans
213
+ * l'application) et prennent le premier libre au démarrage : rien à écrire.
214
+ * Renvoie { framework, label, port, url } (port et url null si inconnus).
215
+ */
216
+ async function devServer(dir, pkg = {}, { exclude = new Set() } = {}) {
217
+ const framework = frameworkOf(pkg);
218
+ const fw = framework ? FRAMEWORKS[framework] : null;
219
+ let port = declaredPort(pkg) || (fw && fw.port) || null;
220
+ // Port d'un autre front du projet (ou d'un de ses services) : le suivant libre
221
+ if (port && exclude.has(port)) port = await nextPort(port, exclude);
222
+ const ngFile = path.join(dir, 'angular.json');
223
+ if (fs.existsSync(ngFile)) {
224
+ port = await nextPort(port || FRAMEWORKS.angular.port, exclude);
225
+ const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
226
+ for (const p of Object.values(ng.projects || {})) {
227
+ const serve = p.architect && p.architect.serve;
228
+ if (serve) serve.options = { ...(serve.options || {}), port };
229
+ }
230
+ fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
231
+ }
232
+ return { framework, label: fw ? fw.label : null, port, url: port ? `http://localhost:${port}` : null };
233
+ }
234
+
235
+ /** Ancienne forme (port seul, Angular seulement) : gardée pour les appels existants */
236
+ async function applyDevPort(dir, template = {}) {
237
+ if (!fs.existsSync(path.join(dir, 'angular.json'))) return null;
238
+ return (await devServer(dir, { poad: { template } })).port;
239
+ }
240
+
241
+ module.exports = { LOCKFILES, freePort, nextPort, applyDevPort, devServer, frameworkOf, declaredPort, FRAMEWORKS, TEMPLATES, templateByValue, STRIP, PACKAGE_RULES, rewritePackageJson, packageName, prepareStarter, readPackage, adaptToPackageManager };
package/utils/tar.js ADDED
@@ -0,0 +1,180 @@
1
+ // Lecture et extraction d'une archive .tgz (paquet npm) avec les seuls modules
2
+ // de Node (zlib + un lecteur tar minimal), sans dépendance ni commande tar.
3
+ //
4
+ // Sûreté : toute l'archive est lue et vérifiée AVANT la première écriture.
5
+ // Refusés : chemins absolus (/x, C:\x, \\serveur), segments « .. », barres
6
+ // obliques inverses, octet nul, liens symboliques et liens physiques (un
7
+ // paquet npm n'en contient jamais), fichiers spéciaux (périphériques, fifo),
8
+ // doublons, archive trop grosse ou trop de fichiers. Les fichiers sont créés
9
+ // en 0644 (0755 s'ils étaient exécutables), jamais setuid.
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const zlib = require('zlib');
13
+
14
+ const LIMITS = { maxBytes: 200 * 1024 * 1024, maxEntries: 20000 };
15
+
16
+ class TarError extends Error {}
17
+
18
+ const str = (buf, start, len) => {
19
+ const raw = buf.subarray(start, start + len);
20
+ const end = raw.indexOf(0);
21
+ return raw.subarray(0, end === -1 ? raw.length : end).toString('utf8');
22
+ };
23
+
24
+ // Nombre octal, ou base 256 (bit de poids fort du premier octet) pour les grandes tailles
25
+ const num = (buf, start, len) => {
26
+ if (buf[start] & 0x80) {
27
+ let n = 0;
28
+ for (let i = start + 1; i < start + len; i++) n = n * 256 + buf[i];
29
+ return n;
30
+ }
31
+ const s = str(buf, start, len).trim();
32
+ return s ? parseInt(s, 8) : 0;
33
+ };
34
+
35
+ const checksumOk = (header) => {
36
+ const stored = num(header, 148, 8);
37
+ let sum = 0;
38
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
39
+ return sum === stored;
40
+ };
41
+
42
+ // En-têtes pax (« x ») : enregistrements « longueur clé=valeur\n »
43
+ const parsePax = (data) => {
44
+ const out = {};
45
+ let i = 0;
46
+ while (i < data.length) {
47
+ const sp = data.indexOf(0x20, i);
48
+ if (sp === -1) break;
49
+ const len = parseInt(data.subarray(i, sp).toString('utf8'), 10);
50
+ if (!len || len < 0 || i + len > data.length) throw new TarError('corrupt pax header');
51
+ const rec = data.subarray(sp + 1, i + len - 1).toString('utf8');
52
+ const eq = rec.indexOf('=');
53
+ if (eq > 0) out[rec.slice(0, eq)] = rec.slice(eq + 1);
54
+ i += len;
55
+ }
56
+ return out;
57
+ };
58
+
59
+ /**
60
+ * Chemin relatif sûr d'une entrée, sans le premier segment (« package/ » dans
61
+ * un paquet npm, comme npm le fait), ou une erreur. '' pour la racine.
62
+ */
63
+ function safeRelative(name, { strip = 1 } = {}) {
64
+ if (typeof name !== 'string' || !name) throw new TarError('entry without a name');
65
+ if (name.includes('\0')) throw new TarError(`refused entry ${JSON.stringify(name)}: NUL byte`);
66
+ if (name.includes('\\')) throw new TarError(`refused entry ${JSON.stringify(name)}: backslash`);
67
+ if (name.startsWith('/') || /^[A-Za-z]:/.test(name)) throw new TarError(`refused entry ${JSON.stringify(name)}: absolute path`);
68
+ const parts = name.split('/').filter((p) => p && p !== '.');
69
+ if (parts.some((p) => p === '..')) throw new TarError(`refused entry ${JSON.stringify(name)}: ".." in the path`);
70
+ return parts.slice(strip).join('/');
71
+ }
72
+
73
+ /**
74
+ * Entrées d'une archive tar (non compressée) : [{ path, type: 'file'|'dir', mode, data }].
75
+ * Lève TarError à la première entrée refusée.
76
+ */
77
+ function readTar(buf, { strip = 1, maxEntries = LIMITS.maxEntries } = {}) {
78
+ const entries = [];
79
+ const seen = new Set();
80
+ let off = 0;
81
+ let pax = {};
82
+ let longName = null;
83
+ while (off + 512 <= buf.length) {
84
+ const header = buf.subarray(off, off + 512);
85
+ if (header.every((b) => b === 0)) break; // fin de l'archive
86
+ if (!checksumOk(header)) throw new TarError('corrupt tar header (checksum)');
87
+ const size = num(header, 124, 12);
88
+ const type = String.fromCharCode(header[156] || 0x30);
89
+ const dataStart = off + 512;
90
+ const dataEnd = dataStart + size;
91
+ if (dataEnd > buf.length) throw new TarError('truncated archive');
92
+ const data = buf.subarray(dataStart, dataEnd);
93
+ off = dataStart + Math.ceil(size / 512) * 512;
94
+
95
+ // En-têtes étendus : s'appliquent à l'entrée suivante
96
+ if (type === 'x') {
97
+ pax = parsePax(data);
98
+ continue;
99
+ }
100
+ if (type === 'g') continue; // en-tête pax global : rien d'utile ici
101
+ if (type === 'L') {
102
+ longName = str(data, 0, data.length);
103
+ continue;
104
+ }
105
+
106
+ const prefix = str(header, 345, 155);
107
+ const magic = str(header, 257, 6);
108
+ let name = str(header, 0, 100);
109
+ if (magic.startsWith('ustar') && prefix) name = `${prefix}/${name}`;
110
+ if (longName !== null) name = longName;
111
+ if (pax.path) name = pax.path;
112
+ pax = {};
113
+ longName = null;
114
+
115
+ if (type === '1' || type === '2') {
116
+ throw new TarError(`refused entry ${JSON.stringify(name)}: ${type === '2' ? 'symbolic' : 'hard'} link (a template must not contain links)`);
117
+ }
118
+ if (!['0', '\0', '7', '5'].includes(type)) throw new TarError(`refused entry ${JSON.stringify(name)}: unsupported type "${type}"`);
119
+
120
+ const rel = safeRelative(name, { strip });
121
+ if (!rel) continue; // le dossier racine lui-même
122
+ if (seen.has(rel)) throw new TarError(`refused entry ${JSON.stringify(name)}: duplicate`);
123
+ seen.add(rel);
124
+ if (entries.length >= maxEntries) throw new TarError(`more than ${maxEntries} entries`);
125
+ const mode = num(header, 100, 8);
126
+ entries.push(type === '5' ? { path: rel, type: 'dir' } : { path: rel, type: 'file', mode: mode & 0o111 ? 0o755 : 0o644, data });
127
+ }
128
+ // Un fichier « a » puis un fichier « a/b » : refusé (pas de fichier pris pour un dossier)
129
+ const files = new Set(entries.filter((e) => e.type === 'file').map((e) => e.path));
130
+ for (const e of entries) {
131
+ const parts = e.path.split('/');
132
+ for (let i = 1; i < parts.length; i++) {
133
+ if (files.has(parts.slice(0, i).join('/'))) throw new TarError(`refused entry ${JSON.stringify(e.path)}: a parent is a file`);
134
+ }
135
+ }
136
+ return entries;
137
+ }
138
+
139
+ /** Décompresse une archive .tgz, en bornant la taille décompressée */
140
+ function gunzip(tgz, { maxBytes = LIMITS.maxBytes } = {}) {
141
+ try {
142
+ return zlib.gunzipSync(tgz, { maxOutputLength: maxBytes });
143
+ } catch (err) {
144
+ if (err && err.code === 'ERR_BUFFER_TOO_LARGE') throw new TarError(`archive larger than ${maxBytes} bytes once decompressed`);
145
+ throw new TarError(`not a gzip archive: ${err.message}`);
146
+ }
147
+ }
148
+
149
+ /** Écrit les entrées vérifiées dans target (qui doit exister) ; chaque chemin y reste */
150
+ function writeEntries(entries, target) {
151
+ const base = fs.realpathSync(target);
152
+ const inside = (rel) => {
153
+ const abs = path.resolve(base, ...rel.split('/'));
154
+ if (abs !== base && !abs.startsWith(base + path.sep)) throw new TarError(`refused entry ${JSON.stringify(rel)}: outside the target folder`);
155
+ return abs;
156
+ };
157
+ for (const e of entries) {
158
+ const abs = inside(e.path);
159
+ if (e.type === 'dir') {
160
+ fs.mkdirSync(abs, { recursive: true, mode: 0o755 });
161
+ continue;
162
+ }
163
+ fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o755 });
164
+ // wx : jamais d'écriture sur un fichier (ou un lien) déjà là
165
+ fs.writeFileSync(abs, e.data, { flag: 'wx', mode: e.mode });
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Extrait une archive .tgz dans target (créé s'il manque). Tout est vérifié
171
+ * avant d'écrire ; renvoie le nombre de fichiers écrits.
172
+ */
173
+ function extractTgz(tgz, target, options = {}) {
174
+ const entries = readTar(gunzip(tgz, options), options);
175
+ fs.mkdirSync(target, { recursive: true });
176
+ writeEntries(entries, target);
177
+ return entries.filter((e) => e.type === 'file').length;
178
+ }
179
+
180
+ module.exports = { extractTgz, readTar, gunzip, safeRelative, writeEntries, TarError, LIMITS };