dshmarket 1.77.1 → 1.78.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/lib/hot.js CHANGED
@@ -32,6 +32,7 @@ import { asChannel } from './channels.js';
32
32
  import { asRegion, normalizeGithubProxy } from './regions.js';
33
33
  import { findDshInstallDir } from './dsh-install.js';
34
34
  import { logEvent } from './log.js';
35
+ import { MAX_USER_CATALOGS, validUserCatalog } from './catalogs.js';
35
36
  import { bundlePatchTargets, declaredBundlePatchFiles, entryArtifactExists } from './profile.js';
36
37
  /**
37
38
  * Profile-scoped resolution for hot-mount imports: turn a bare package name into
@@ -309,6 +310,20 @@ export const MAX_BLOCKED_NAME = 214;
309
310
  function favoriteUrls(value) {
310
311
  return uniqueStrings(value).filter(url => url.startsWith('http://') || url.startsWith('https://'));
311
312
  }
313
+ /** Saved user catalogs: well-formed, de-duplicated, capped; stored state is untrusted. */
314
+ function userCatalogsFromUnknown(value) {
315
+ if (!Array.isArray(value))
316
+ return [];
317
+ const out = [];
318
+ for (const raw of value) {
319
+ const entry = validUserCatalog(raw);
320
+ if (entry !== null && !out.some(other => other.id === entry.id))
321
+ out.push(entry);
322
+ if (out.length >= MAX_USER_CATALOGS)
323
+ break;
324
+ }
325
+ return out;
326
+ }
312
327
  /** Package names, non-empty, order preserved, capped. */
313
328
  function cappedPackageNames(value, cap) {
314
329
  const trimmed = Array.isArray(value)
@@ -455,6 +470,7 @@ export function readMarketState(profileDir) {
455
470
  }
456
471
  }
457
472
  const githubProxy = normalizeGithubProxy(state.githubProxy);
473
+ const userCatalogs = userCatalogsFromUnknown(state.userCatalogs);
458
474
  const brokenPlugins = brokenPluginsFromUnknown(state.brokenPlugins);
459
475
  const installTimes = installTimesFromUnknown(state.installTimes);
460
476
  // The order and the map are two halves of one fact, and a state file can
@@ -484,6 +500,7 @@ export function readMarketState(profileDir) {
484
500
  ...(typeof state.backgroundUpdateChecks === 'boolean' ? { backgroundUpdateChecks: state.backgroundUpdateChecks } : {}),
485
501
  ...(isUpdateCheckIntervalHours(state.backgroundUpdateIntervalHours) ? { backgroundUpdateIntervalHours: state.backgroundUpdateIntervalHours } : {}),
486
502
  ...(githubProxy === null ? {} : { githubProxy }),
503
+ ...(userCatalogs.length === 0 ? {} : { userCatalogs }),
487
504
  ...(brokenPlugins === undefined ? {} : { brokenPlugins }),
488
505
  ...(installTimes === undefined ? {} : { installTimes }),
489
506
  // true AND false are both preserved: on a host with no settings page
@@ -594,6 +611,7 @@ function writeState(profileDir, state, ownStamps) {
594
611
  ? state.regionAuto
595
612
  : onDisk.regionAuto;
596
613
  const favorites = state.favorites ?? onDisk.favorites ?? [];
614
+ const userCatalogs = state.userCatalogs ?? onDisk.userCatalogs ?? [];
597
615
  const blocked = state.blocked ?? onDisk.blocked ?? [];
598
616
  const updateExempt = state.updateExempt ?? onDisk.updateExempt ?? [];
599
617
  const backgroundUpdateChecks = state.backgroundUpdateChecks ?? onDisk.backgroundUpdateChecks;
@@ -625,6 +643,7 @@ function writeState(profileDir, state, ownStamps) {
625
643
  groups: state.groups,
626
644
  groupOrder: state.groupOrder,
627
645
  ...(favorites.length > 0 ? { favorites } : {}),
646
+ ...(userCatalogs.length > 0 ? { userCatalogs } : {}),
628
647
  ...(blocked.length > 0 ? { blocked } : {}),
629
648
  ...(updateExempt.length > 0 ? { updateExempt } : {}),
630
649
  ...(typeof backgroundUpdateChecks === 'boolean' ? { backgroundUpdateChecks } : {}),
package/lib/http.js CHANGED
@@ -237,6 +237,19 @@ export function sameOrigin(request) {
237
237
  return false;
238
238
  }
239
239
  }
240
+ /** Read a request body as bytes, refusing anything over `maxBytes` (stops reading as soon as it is over). */
241
+ export async function readRawBody(request, maxBytes) {
242
+ const chunks = [];
243
+ let size = 0;
244
+ for await (const chunk of request) {
245
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
246
+ size += buffer.length;
247
+ if (size > maxBytes)
248
+ throw new Error('request body too large');
249
+ chunks.push(buffer);
250
+ }
251
+ return Buffer.concat(chunks);
252
+ }
240
253
  /** Read and parse a JSON request body, rejecting anything over 4 KiB. */
241
254
  export async function readJsonBody(request, maxBytes = 4096) {
242
255
  const chunks = [];
package/lib/net.js CHANGED
@@ -30,6 +30,7 @@
30
30
  * networking stays as the host configured it.
31
31
  */
32
32
  import { Agent, EnvHttpProxyAgent, fetch as undiciFetch } from 'undici';
33
+ import { authorizationFor } from './npmrc.js';
33
34
  /**
34
35
  * Hand the host's own undici the dispatcher our import took (#861).
35
36
  *
@@ -122,7 +123,14 @@ let directAgent = null;
122
123
  * through this module's own agent when it has none. Both paths pass the
123
124
  * dispatcher described on this module.
124
125
  */
125
- export async function marketFetch(url, init) {
126
+ export async function marketFetch(url, given) {
127
+ // A private npm registry's credential (an `.npmrc` scope routes there) rides
128
+ // along; a caller that set its own Authorization keeps it. A cross-origin
129
+ // redirect drops the header again, per the fetch spec.
130
+ const credential = given?.headers !== undefined && Object.keys(given.headers).some(name => name.toLowerCase() === 'authorization')
131
+ ? null
132
+ : authorizationFor(url);
133
+ const init = credential === null ? given : { ...given, headers: { ...given?.headers, authorization: credential } };
126
134
  const { http, https } = proxyFromEnv();
127
135
  if (http === null && https === null) {
128
136
  directAgent ??= new Agent();
package/lib/npmrc.js ADDED
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Private npm registries, read from the same `.npmrc` files pnpm reads.
3
+ *
4
+ * pnpm already handles installs: it reads the profile's `.npmrc` and
5
+ * `~/.npmrc` itself, so nothing here touches how a package is installed. What
6
+ * pnpm cannot do is answer the market's OWN requests — update checks,
7
+ * versions, changelog, release age, compatibility — and those used to go to
8
+ * the download region's registry for every package. For `@acme/plugin` with
9
+ * `@acme:registry=https://npm.acme.internal/` in an `.npmrc`, that meant
10
+ * asking the public registry about a package it has never heard of.
11
+ *
12
+ * Two small rules fix that, and nothing else changes:
13
+ *
14
+ * - {@link registryFor}: a scoped package goes to its scope's registry; every
15
+ * other package keeps the registry the market was already using.
16
+ * - {@link authorizationFor}: a request to a registry that an `.npmrc` routes
17
+ * a scope to carries the credential the `.npmrc` holds for it.
18
+ *
19
+ * Precedence is the profile's `.npmrc` over `~/.npmrc`, per key.
20
+ *
21
+ * The unscoped `registry=` line is read from the PROFILE's `.npmrc` only. A
22
+ * profile `.npmrc` is deliberate configuration for that profile (a company
23
+ * registry for everything), so the market asks the same registry pnpm
24
+ * installs from. `~/.npmrc` is not read for it: it is the user's own file,
25
+ * shared with every other tool, and the market's default route stays the
26
+ * download region's. An administrator's policy `mirrors.npm` outranks both.
27
+ *
28
+ * Credentials are attached only to registries the profile configuration
29
+ * routes to (a scope, or that profile default), so a publish token for
30
+ * registry.npmjs.org in `~/.npmrc` is never sent by the market just because
31
+ * it exists.
32
+ *
33
+ * A credential never leaves this module except as the header value handed to
34
+ * {@link marketFetch}; nothing here logs one.
35
+ */
36
+ import { existsSync, readFileSync, statSync } from 'node:fs';
37
+ import { homedir } from 'node:os';
38
+ import { join } from 'node:path';
39
+ import { getPolicy } from './policy.js';
40
+ /** `//host[:port]/path/` form npm keys credentials by. */
41
+ export function nerfDart(url) {
42
+ try {
43
+ const parsed = new URL(url);
44
+ const path = parsed.pathname.endsWith('/') ? parsed.pathname : `${parsed.pathname}/`;
45
+ return `//${parsed.host}${path}`;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ function unquote(value) {
52
+ const text = value.trim();
53
+ if (text.length >= 2 && (text.startsWith('"') && text.endsWith('"') || text.startsWith("'") && text.endsWith("'"))) {
54
+ return text.slice(1, -1);
55
+ }
56
+ return text;
57
+ }
58
+ /**
59
+ * Parse one `.npmrc`. Lines are `key=value`; `;` and `#` start a comment line.
60
+ * `${NAME}` is expanded from `env`, as npm does; a line that needs a variable
61
+ * that is not set is dropped (and the name reported) rather than becoming an
62
+ * empty, wrong credential.
63
+ */
64
+ export function parseNpmrc(text, env = process.env) {
65
+ const scopes = new Map();
66
+ let defaultRegistry;
67
+ const missingEnv = [];
68
+ const raw = new Map();
69
+ for (const line of text.split(/\r?\n/u)) {
70
+ const trimmed = line.trim();
71
+ if (trimmed === '' || trimmed.startsWith(';') || trimmed.startsWith('#'))
72
+ continue;
73
+ const at = trimmed.indexOf('=');
74
+ if (at <= 0)
75
+ continue;
76
+ const key = trimmed.slice(0, at).trim();
77
+ let value = unquote(trimmed.slice(at + 1));
78
+ let dropped = false;
79
+ value = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu, (_match, name) => {
80
+ const found = env[name];
81
+ if (found === undefined || found === '') {
82
+ dropped = true;
83
+ if (!missingEnv.includes(name))
84
+ missingEnv.push(name);
85
+ return '';
86
+ }
87
+ return found;
88
+ });
89
+ if (dropped)
90
+ continue;
91
+ raw.set(key, value);
92
+ }
93
+ const authByRegistry = new Map();
94
+ const slot = (registry) => {
95
+ const existing = authByRegistry.get(registry);
96
+ if (existing !== undefined)
97
+ return existing;
98
+ const created = {};
99
+ authByRegistry.set(registry, created);
100
+ return created;
101
+ };
102
+ for (const [key, value] of raw) {
103
+ if (key === 'registry') {
104
+ try {
105
+ const url = new URL(value);
106
+ if (url.protocol === 'https:' || url.protocol === 'http:')
107
+ defaultRegistry = url.href.replace(/\/+$/u, '');
108
+ }
109
+ catch { /* not a URL: pnpm will say so */ }
110
+ continue;
111
+ }
112
+ const scope = /^(@[A-Za-z0-9._~-]+):registry$/u.exec(key);
113
+ if (scope !== null) {
114
+ try {
115
+ const url = new URL(value);
116
+ if (url.protocol === 'https:' || url.protocol === 'http:')
117
+ scopes.set(scope[1].toLowerCase(), url.href.replace(/\/+$/u, ''));
118
+ }
119
+ catch { /* not a URL: ignore the line, as npm would fail it later */ }
120
+ continue;
121
+ }
122
+ if (!key.startsWith('//'))
123
+ continue;
124
+ const colon = key.lastIndexOf(':');
125
+ const field = key.slice(colon + 1);
126
+ if (!['_authToken', '_auth', 'username', '_password'].includes(field))
127
+ continue;
128
+ const base = key.slice(0, colon);
129
+ const entry = slot(base.endsWith('/') ? base : `${base}/`);
130
+ if (field === '_authToken')
131
+ entry.token = value;
132
+ else if (field === '_auth')
133
+ entry.basic = value;
134
+ else if (field === 'username')
135
+ entry.user = value;
136
+ else
137
+ entry.password = value;
138
+ }
139
+ const credentials = new Map();
140
+ for (const [registry, entry] of authByRegistry) {
141
+ if (entry.token !== undefined && entry.token !== '')
142
+ credentials.set(registry, { header: `Bearer ${entry.token}` });
143
+ else if (entry.basic !== undefined && entry.basic !== '')
144
+ credentials.set(registry, { header: `Basic ${entry.basic}` });
145
+ else if (entry.user !== undefined && entry.password !== undefined) {
146
+ // npm stores `_password` base64-encoded; Basic wants user:password.
147
+ const password = Buffer.from(entry.password, 'base64').toString('utf8');
148
+ credentials.set(registry, { header: `Basic ${Buffer.from(`${entry.user}:${password}`).toString('base64')}` });
149
+ }
150
+ }
151
+ return { scopes, credentials, missingEnv, ...(defaultRegistry === undefined ? {} : { defaultRegistry }) };
152
+ }
153
+ /** The per-key union, `over` winning. */
154
+ export function mergeNpmrc(base, over) {
155
+ return {
156
+ scopes: new Map([...base.scopes, ...over.scopes]),
157
+ ...((over.defaultRegistry ?? base.defaultRegistry) === undefined ? {} : { defaultRegistry: (over.defaultRegistry ?? base.defaultRegistry) }),
158
+ credentials: new Map([...base.credentials, ...over.credentials]),
159
+ missingEnv: [...new Set([...base.missingEnv, ...over.missingEnv])],
160
+ };
161
+ }
162
+ /** The registry for one package, given a config; `fallback` for everything else. */
163
+ export function registryIn(config, name, fallback, defaultLocked = false) {
164
+ if (name.startsWith('@')) {
165
+ const scope = name.split('/')[0].toLowerCase();
166
+ const own = config.scopes.get(scope);
167
+ if (own !== undefined)
168
+ return own;
169
+ }
170
+ // The profile's own default, unless an administrator's policy fixed the registry.
171
+ if (!defaultLocked && config.defaultRegistry !== undefined)
172
+ return config.defaultRegistry;
173
+ return fallback.replace(/\/+$/u, '');
174
+ }
175
+ /**
176
+ * The Authorization header for a URL, or null. Only registries that some scope
177
+ * points at are eligible (see the module note), matched the way npm matches:
178
+ * the longest nerf-darted prefix of the URL.
179
+ */
180
+ export function authorizationIn(config, url) {
181
+ if ((config.scopes.size === 0 && config.defaultRegistry === undefined) || config.credentials.size === 0)
182
+ return null;
183
+ const target = nerfDart(url);
184
+ if (target === null)
185
+ return null;
186
+ const routed = new Set();
187
+ if (config.defaultRegistry !== undefined) {
188
+ const key = nerfDart(config.defaultRegistry);
189
+ if (key !== null)
190
+ routed.add(key);
191
+ }
192
+ for (const registry of config.scopes.values()) {
193
+ const key = nerfDart(registry);
194
+ if (key !== null)
195
+ routed.add(key);
196
+ }
197
+ let best = null;
198
+ for (const key of config.credentials.keys()) {
199
+ if (!routed.has(key) || !target.startsWith(key))
200
+ continue;
201
+ if (best === null || key.length > best.length)
202
+ best = key;
203
+ }
204
+ return best === null ? null : config.credentials.get(best).header;
205
+ }
206
+ let profileDir = null;
207
+ /** Home override for tests; null means the real one. */
208
+ let homeOverride = null;
209
+ const RECHECK_MS = 2_000;
210
+ let loaded = null;
211
+ /** Tell this module which profile's `.npmrc` is the first one to read. */
212
+ export function setNpmrcProfileDir(dir) {
213
+ profileDir = dir;
214
+ loaded = null;
215
+ }
216
+ /** Tests only. */
217
+ export function setNpmrcHome(dir) {
218
+ homeOverride = dir;
219
+ loaded = null;
220
+ }
221
+ function npmrcFiles(env) {
222
+ const user = env.npm_config_userconfig?.trim() || env.NPM_CONFIG_USERCONFIG?.trim() || join(homeOverride ?? homedir(), '.npmrc');
223
+ return [user, ...(profileDir === null ? [] : [join(profileDir, '.npmrc')])];
224
+ }
225
+ /** The merged config in force: `~/.npmrc` first, the profile's over it. */
226
+ export function currentNpmrc(env = process.env, now = performance.now()) {
227
+ const files = npmrcFiles(env);
228
+ const where = files.join('|');
229
+ if (loaded !== null && loaded.where === where && now - loaded.at < RECHECK_MS)
230
+ return loaded.config;
231
+ const stamp = files.map(file => {
232
+ try {
233
+ const info = statSync(file);
234
+ return `${file}:${String(info.mtimeMs)}:${String(info.size)}`;
235
+ }
236
+ catch {
237
+ return `${file}:-`;
238
+ }
239
+ }).join('|');
240
+ if (loaded !== null && loaded.where === where && loaded.stamp === stamp) {
241
+ loaded = { ...loaded, at: now };
242
+ return loaded.config;
243
+ }
244
+ let config = { scopes: new Map(), credentials: new Map(), missingEnv: [] };
245
+ for (const [index, file] of files.entries()) {
246
+ if (!existsSync(file))
247
+ continue;
248
+ try {
249
+ const parsed = parseNpmrc(readFileSync(file, 'utf8'), env);
250
+ // Only the profile's file (the one after ~/.npmrc) may name the default registry.
251
+ if (index === 0)
252
+ delete parsed.defaultRegistry;
253
+ config = mergeNpmrc(config, parsed);
254
+ }
255
+ catch { /* an unreadable .npmrc is no .npmrc; pnpm will say why */ }
256
+ }
257
+ loaded = { at: now, where, stamp, config };
258
+ return config;
259
+ }
260
+ /** The registry the market should ask about `name`. */
261
+ export function registryFor(name, fallback) {
262
+ return registryIn(currentNpmrc(), name, fallback, getPolicy().mirrors.npm !== undefined);
263
+ }
264
+ /** Authorization header for a URL on a scope-routed registry, or null. */
265
+ export function authorizationFor(url) {
266
+ return authorizationIn(currentNpmrc(), url);
267
+ }
package/lib/offline.js ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Offline bundles: a catalog plus the package files it lists, in one archive,
3
+ * for machines that cannot reach npm at all.
4
+ *
5
+ * Layout of a bundle (made by scripts/offline-pack.mjs):
6
+ *
7
+ * plugins.json the catalog; each entry carries `tarball: "./tarballs/<file>.tgz"`
8
+ * tarballs/<file>.tgz the package files, one per entry
9
+ *
10
+ * Importing one is the only place the market unpacks an archive it did not
11
+ * make, so the rules here are strict and boring:
12
+ *
13
+ * - Only regular files. A link, device or directory-traversal name anywhere
14
+ * in the archive refuses the whole import; nothing is half-extracted.
15
+ * - Only the two places above: `plugins.json` at the top and `*.tgz` files
16
+ * under `tarballs/`. Anything else is refused rather than ignored.
17
+ * - Size and count limits, on the way in and after decompression.
18
+ * - Extracted into a temporary directory and moved into place only when the
19
+ * whole archive passed; a failure leaves nothing behind.
20
+ *
21
+ * A tarball path in a catalog is resolved by {@link resolveBundleFile}: it must
22
+ * be that exact shape, and the file it names must be a plain file inside the
23
+ * bundle's own directory — never a link out, never an absolute path.
24
+ */
25
+ import { createHash, randomBytes } from 'node:crypto';
26
+ import { lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
27
+ import { dirname, join, resolve, sep } from 'node:path';
28
+ import { gunzipSync } from 'node:zlib';
29
+ import { resolveDshHome } from './home-paths.js';
30
+ /** Where imported bundles live: `<DSH_HOME>/dsh-market/offline/<id>/`. */
31
+ export function offlineRoot(env = process.env) {
32
+ return join(resolveDshHome(undefined, env), 'dsh-market', 'offline');
33
+ }
34
+ /** Whether `path` is inside the imported-bundles directory. */
35
+ export function isInsideOfflineRoot(path, env = process.env) {
36
+ const root = resolve(offlineRoot(env)) + sep;
37
+ return resolve(path).startsWith(root);
38
+ }
39
+ export const MAX_BUNDLE_BYTES = 512 * 1024 * 1024;
40
+ export const MAX_BUNDLE_FILES = 2000;
41
+ const TARBALL_RE = /^(?:\.\/)?tarballs\/[A-Za-z0-9][A-Za-z0-9._@+-]*\.tgz$/u;
42
+ /**
43
+ * The absolute path a catalog entry's `tarball` names, or null when it is not
44
+ * a plain file strictly inside `baseDir`. Never trusts the string: the shape
45
+ * is fixed, and the result is checked on disk after resolving links.
46
+ */
47
+ export function resolveBundleFile(baseDir, relative) {
48
+ if (typeof relative !== 'string' || !TARBALL_RE.test(relative))
49
+ return null;
50
+ try {
51
+ const base = realpathSync(baseDir);
52
+ const candidate = join(base, relative.replace(/^\.\//u, ''));
53
+ const info = lstatSync(candidate);
54
+ if (!info.isFile() || info.isSymbolicLink())
55
+ return null;
56
+ const real = realpathSync(candidate);
57
+ return real.startsWith(base + sep) ? real : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ export class BundleError extends Error {
64
+ code;
65
+ detail;
66
+ constructor(code, detail) {
67
+ super(`${code}: ${detail}`);
68
+ this.name = 'BundleError';
69
+ this.code = code;
70
+ this.detail = detail;
71
+ }
72
+ }
73
+ const octal = (field) => {
74
+ const text = field.toString('latin1').replace(/\0.*$/su, '').trim();
75
+ return text === '' ? 0 : Number.parseInt(text, 8);
76
+ };
77
+ const text = (field) => field.toString('utf8').replace(/\0.*$/su, '');
78
+ /** Read every entry of an uncompressed tar, refusing anything but plain files and directories. */
79
+ function readTar(tar) {
80
+ const files = [];
81
+ let offset = 0;
82
+ let longName = null;
83
+ while (offset + 512 <= tar.length) {
84
+ const header = tar.subarray(offset, offset + 512);
85
+ if (header.every(byte => byte === 0))
86
+ break;
87
+ const size = octal(header.subarray(124, 136));
88
+ const type = String.fromCharCode(header[156] === 0 ? 48 : header[156]);
89
+ let name = text(header.subarray(0, 100));
90
+ const prefix = text(header.subarray(345, 500));
91
+ if (prefix !== '' && header.subarray(257, 262).toString('latin1') === 'ustar')
92
+ name = `${prefix}/${name}`;
93
+ const body = tar.subarray(offset + 512, offset + 512 + size);
94
+ if (body.length < size)
95
+ throw new BundleError('not-archive', 'the archive is cut short');
96
+ offset += 512 + Math.ceil(size / 512) * 512;
97
+ if (type === 'x' || type === 'g') {
98
+ // pax header: only `path` matters; anything it does not carry is ignored.
99
+ const match = /(?:^|\n)\d+ path=([^\n]*)\n/u.exec(body.toString('utf8'));
100
+ if (type === 'x' && match !== null)
101
+ longName = match[1];
102
+ continue;
103
+ }
104
+ if (type === 'L') {
105
+ longName = text(body);
106
+ continue;
107
+ }
108
+ if (longName !== null) {
109
+ name = longName;
110
+ longName = null;
111
+ }
112
+ if (type === '5')
113
+ continue; // a directory entry: layout is checked on the files
114
+ if (type !== '0')
115
+ throw new BundleError('unsafe', `${name} is not a plain file (type ${type})`);
116
+ files.push({ name, data: Buffer.from(body) });
117
+ }
118
+ return files;
119
+ }
120
+ /** A name is acceptable only as a relative, forward-slash path with no dot segments. */
121
+ function cleanName(name) {
122
+ const stripped = name.replace(/^\.\//u, '');
123
+ if (stripped === '' || stripped.startsWith('/') || /^[A-Za-z]:/u.test(stripped) || stripped.includes('\\') || stripped.includes('\0')) {
124
+ throw new BundleError('unsafe', `${name} is not a relative path`);
125
+ }
126
+ if (stripped.split('/').some(part => part === '' || part === '.' || part === '..')) {
127
+ throw new BundleError('unsafe', `${name} escapes the bundle`);
128
+ }
129
+ return stripped;
130
+ }
131
+ /**
132
+ * Unpack a bundle into `<root>/<id>/`, or throw {@link BundleError} having
133
+ * written nothing. `id` is derived from the content, so importing the same
134
+ * bundle twice is one directory, and importing a newer one replaces it.
135
+ */
136
+ export function extractBundle(archive, root = offlineRoot()) {
137
+ if (archive.length > MAX_BUNDLE_BYTES)
138
+ throw new BundleError('too-big', `${String(archive.length)} bytes`);
139
+ let tar;
140
+ try {
141
+ tar = gunzipSync(archive, { maxOutputLength: MAX_BUNDLE_BYTES });
142
+ }
143
+ catch (error) {
144
+ const message = error instanceof Error ? error.message : String(error);
145
+ throw new BundleError(/larger than|maxOutputLength/iu.test(message) ? 'too-big' : 'not-archive', message.slice(0, 120));
146
+ }
147
+ const files = readTar(tar);
148
+ if (files.length === 0)
149
+ throw new BundleError('empty', 'no files');
150
+ if (files.length > MAX_BUNDLE_FILES)
151
+ throw new BundleError('too-big', `${String(files.length)} files`);
152
+ const seen = new Set();
153
+ let catalog = false;
154
+ for (const file of files) {
155
+ file.name = cleanName(file.name);
156
+ if (seen.has(file.name))
157
+ throw new BundleError('layout', `${file.name} appears twice`);
158
+ seen.add(file.name);
159
+ if (file.name === 'plugins.json')
160
+ catalog = true;
161
+ else if (!TARBALL_RE.test(file.name))
162
+ throw new BundleError('layout', `${file.name} is not part of a bundle`);
163
+ }
164
+ if (!catalog)
165
+ throw new BundleError('layout', 'plugins.json is missing');
166
+ const id = `offline-${createHash('sha1').update(archive).digest('hex').slice(0, 8)}`;
167
+ mkdirSync(root, { recursive: true, mode: 0o700 });
168
+ const temporary = join(root, `.import-${randomBytes(6).toString('hex')}`);
169
+ try {
170
+ for (const file of files) {
171
+ const target = join(temporary, file.name);
172
+ mkdirSync(dirname(target), { recursive: true });
173
+ writeFileSync(target, file.data, { mode: 0o600 });
174
+ }
175
+ const dir = join(root, id);
176
+ rmSync(dir, { recursive: true, force: true });
177
+ renameSync(temporary, dir);
178
+ return { id, dir, catalogFile: join(dir, 'plugins.json'), files: files.length };
179
+ }
180
+ finally {
181
+ rmSync(temporary, { recursive: true, force: true });
182
+ }
183
+ }