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.
- package/global/cli.js +2 -1
- package/global/create.js +286 -0
- package/global/init.js +17 -5
- package/global/run.js +17 -10
- package/package.json +4 -2
- package/poad.js +26 -1
- package/project/cli.js +3 -3
- package/project/client/index.js +2 -2
- package/project/client/init.js +43 -59
- package/project/info.js +22 -2
- package/test/create.e2e.test.js +73 -0
- package/test/create.test.js +95 -0
- package/test/help-stub.js +29 -0
- package/test/help.test.js +124 -0
- package/test/helpers.js +53 -0
- package/test/offline-stub.js +5 -0
- package/test/registry.test.js +95 -0
- package/test/secrets.test.js +94 -0
- package/test/starter.test.js +122 -0
- package/test/tar.test.js +101 -0
- package/utils/engine.js +10 -5
- package/utils/git.js +1 -1
- package/utils/help.js +80 -0
- package/utils/registry.js +145 -0
- package/utils/report.js +23 -12
- package/utils/services.js +2 -2
- package/utils/starter.js +214 -0
- package/utils/tar.js +180 -0
package/utils/starter.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
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
|
+
if (!fs.existsSync(gi)) {
|
|
86
|
+
const src = GITIGNORE_SOURCES.map((n) => path.join(dir, n)).find((f) => fs.existsSync(f) && fs.statSync(f).isFile());
|
|
87
|
+
if (src) {
|
|
88
|
+
fs.renameSync(src, gi);
|
|
89
|
+
result.gitignore = 'restored';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const rel of STRIP) {
|
|
93
|
+
const abs = path.join(dir, ...rel.split('/'));
|
|
94
|
+
if (fs.existsSync(abs)) {
|
|
95
|
+
fs.rmSync(abs, { recursive: true, force: true });
|
|
96
|
+
result.stripped.push(rel);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// Lignes propres au modèle, déclarées dans package.json (poad.template.gitignore)
|
|
100
|
+
const pkg = readPackage(dir);
|
|
101
|
+
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()) : [];
|
|
102
|
+
if (lines.length) {
|
|
103
|
+
const label = (pkg.poad.template.framework || 'template').toString();
|
|
104
|
+
require('./git').ensureLines(dir, `Front-end (${label})`, lines);
|
|
105
|
+
result.gitignore = result.gitignore || 'template';
|
|
106
|
+
}
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function readPackage(dir) {
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const LOCKFILES = { bun: ['bun.lock', 'bun.lockb'], npm: ['package-lock.json', 'npm-shrinkwrap.json'], pnpm: ['pnpm-lock.yaml'], yarn: ['yarn.lock'] };
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Gestionnaire de paquets choisi : les fichiers de verrouillage des autres
|
|
122
|
+
* gestionnaires sont retirés, et le champ packageManager s'il en désigne un
|
|
123
|
+
* autre (pnpm et corepack refusent d'installer sinon).
|
|
124
|
+
*/
|
|
125
|
+
function adaptToPackageManager(dir, pm) {
|
|
126
|
+
const removed = [];
|
|
127
|
+
for (const [other, files] of Object.entries(LOCKFILES)) {
|
|
128
|
+
if (other === pm) continue;
|
|
129
|
+
for (const f of files) {
|
|
130
|
+
if (fs.existsSync(path.join(dir, f))) {
|
|
131
|
+
fs.rmSync(path.join(dir, f));
|
|
132
|
+
removed.push(f);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const pkg = readPackage(dir);
|
|
137
|
+
if (pkg && typeof pkg.packageManager === 'string' && !pkg.packageManager.startsWith(`${pm}@`)) {
|
|
138
|
+
delete pkg.packageManager;
|
|
139
|
+
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
|
|
140
|
+
removed.push('packageManager (package.json)');
|
|
141
|
+
}
|
|
142
|
+
return removed;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Premier port libre sur 127.0.0.1 à partir de start (4200 est souvent pris) */
|
|
146
|
+
async function freePort(start, max = start + 100) {
|
|
147
|
+
const net = require('net');
|
|
148
|
+
const free = (port) =>
|
|
149
|
+
new Promise((ok) => {
|
|
150
|
+
const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
|
|
151
|
+
s.listen(port, '127.0.0.1');
|
|
152
|
+
});
|
|
153
|
+
let port = start;
|
|
154
|
+
while (!(await free(port)) && port < max) port++;
|
|
155
|
+
return port;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Frameworks reconnus : étiquette affichée, dépendance qui les trahit, port de
|
|
159
|
+
// développement par défaut quand le modèle n'en déclare pas (celui de l'outil).
|
|
160
|
+
const FRAMEWORKS = {
|
|
161
|
+
angular: { label: 'Angular', dependency: '@angular/core', port: 4300 },
|
|
162
|
+
next: { label: 'Next.js', dependency: 'next', port: 3000 },
|
|
163
|
+
nuxt: { label: 'Nuxt', dependency: 'nuxt', port: 3000 },
|
|
164
|
+
vanilla: { label: 'Vanilla', dependency: null, port: null },
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
/** Framework d'un package.json : poad.template.framework, sinon ses dépendances ; null si inconnu */
|
|
168
|
+
function frameworkOf(pkg = {}) {
|
|
169
|
+
const declared = pkg && pkg.poad && pkg.poad.template && pkg.poad.template.framework;
|
|
170
|
+
if (declared && FRAMEWORKS[String(declared).toLowerCase()]) return String(declared).toLowerCase();
|
|
171
|
+
const deps = { ...((pkg && pkg.devDependencies) || {}), ...((pkg && pkg.dependencies) || {}) };
|
|
172
|
+
for (const [name, fw] of Object.entries(FRAMEWORKS)) if (fw.dependency && deps[fw.dependency]) return name;
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Port déclaré par le modèle : poad.port (gardé dans l'application), sinon poad.template.port */
|
|
177
|
+
function declaredPort(pkg = {}) {
|
|
178
|
+
const poad = (pkg && pkg.poad) || {};
|
|
179
|
+
return Number(poad.port) || Number(poad.template && poad.template.port) || null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Serveur de développement du front, d'après le package.json du modèle (avant
|
|
184
|
+
* réécriture : poad.template y est encore) :
|
|
185
|
+
* - Angular : premier port libre à partir du port déclaré (4300 par défaut),
|
|
186
|
+
* écrit dans angular.json (ng serve) ;
|
|
187
|
+
* - les autres (Next.js…) lisent leur port eux-mêmes (poad.port, gardé dans
|
|
188
|
+
* l'application) et prennent le premier libre au démarrage : rien à écrire.
|
|
189
|
+
* Renvoie { framework, label, port, url } (port et url null si inconnus).
|
|
190
|
+
*/
|
|
191
|
+
async function devServer(dir, pkg = {}) {
|
|
192
|
+
const framework = frameworkOf(pkg);
|
|
193
|
+
const fw = framework ? FRAMEWORKS[framework] : null;
|
|
194
|
+
let port = declaredPort(pkg) || (fw && fw.port) || null;
|
|
195
|
+
const ngFile = path.join(dir, 'angular.json');
|
|
196
|
+
if (fs.existsSync(ngFile)) {
|
|
197
|
+
port = await freePort(port || FRAMEWORKS.angular.port);
|
|
198
|
+
const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
|
|
199
|
+
for (const p of Object.values(ng.projects || {})) {
|
|
200
|
+
const serve = p.architect && p.architect.serve;
|
|
201
|
+
if (serve) serve.options = { ...(serve.options || {}), port };
|
|
202
|
+
}
|
|
203
|
+
fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
|
|
204
|
+
}
|
|
205
|
+
return { framework, label: fw ? fw.label : null, port, url: port ? `http://localhost:${port}` : null };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Ancienne forme (port seul, Angular seulement) : gardée pour les appels existants */
|
|
209
|
+
async function applyDevPort(dir, template = {}) {
|
|
210
|
+
if (!fs.existsSync(path.join(dir, 'angular.json'))) return null;
|
|
211
|
+
return (await devServer(dir, { poad: { template } })).port;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
module.exports = { freePort, 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 };
|