dsh-plugin-packer 0.0.0-stage → 2.1.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/LICENSE +21 -0
- package/README.md +161 -2
- package/cordis.patch.yml +5 -0
- package/lib/assets.js +556 -0
- package/lib/client.js +573 -0
- package/lib/index.js +501 -0
- package/lib/packer.js +694 -0
- package/lib/zip.js +207 -0
- package/package.json +29 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-plugin-packer host half.
|
|
3
|
+
*
|
|
4
|
+
* One loopback JSON API for the settings tab: list, latest, export, import,
|
|
5
|
+
* assets, health. Beyond the plain export/import pair it adds:
|
|
6
|
+
*
|
|
7
|
+
* - `assets` on the catalogue rows and in exported manifests, so a plugin
|
|
8
|
+
* that needs a runtime environment travels with it;
|
|
9
|
+
* - `GET /api/assets` for the on-disk state of those assets;
|
|
10
|
+
* - an import that materialises runtime assets after copying the shell;
|
|
11
|
+
* - dates and ordering (`sort`/`order`) so the tab can show when a plugin was
|
|
12
|
+
* installed and when it last changed.
|
|
13
|
+
*
|
|
14
|
+
* Import accepts both archive formats (`PACK_FORMAT_VERSION` 1 and 2); export
|
|
15
|
+
* writes format 1 for a plugin without assets, so an archive stays readable by
|
|
16
|
+
* older tooling.
|
|
17
|
+
*/
|
|
18
|
+
import { once } from 'node:events';
|
|
19
|
+
import { basename, dirname, join } from 'node:path';
|
|
20
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
21
|
+
import { tmpdir } from 'node:os';
|
|
22
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { createZipStream, readZip } from './zip.js';
|
|
25
|
+
import {
|
|
26
|
+
PACK_FORMAT_VERSION,
|
|
27
|
+
buildManifest,
|
|
28
|
+
expandClosure,
|
|
29
|
+
extractArchive,
|
|
30
|
+
installPack,
|
|
31
|
+
listPlugins,
|
|
32
|
+
planArchive,
|
|
33
|
+
pruneBackups,
|
|
34
|
+
readProfileFacts,
|
|
35
|
+
} from './packer.js';
|
|
36
|
+
import { describeAssets, installAssets, stageAssets } from './assets.js';
|
|
37
|
+
|
|
38
|
+
/** Prefix the settings tab and the browser fetch use. */
|
|
39
|
+
const ROUTE_PREFIX = '/plugin-packer';
|
|
40
|
+
|
|
41
|
+
/** This package's version, recorded in every archive manifest. */
|
|
42
|
+
const OWN_VERSION = (() => {
|
|
43
|
+
try {
|
|
44
|
+
const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
|
|
45
|
+
return typeof manifest.version === 'string' ? manifest.version : '0.0.0';
|
|
46
|
+
} catch {
|
|
47
|
+
return '0.0.0';
|
|
48
|
+
}
|
|
49
|
+
})();
|
|
50
|
+
|
|
51
|
+
function sendJson(response, status, body) {
|
|
52
|
+
const payload = Buffer.from(JSON.stringify(body), 'utf8');
|
|
53
|
+
response.writeHead(status, {
|
|
54
|
+
'content-type': 'application/json; charset=utf-8',
|
|
55
|
+
'cache-control': 'no-store',
|
|
56
|
+
'content-length': String(payload.length),
|
|
57
|
+
});
|
|
58
|
+
response.end(payload);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function fail(response, status, message) {
|
|
62
|
+
sendJson(response, status, { ok: false, error: { message } });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Reject anything that did not arrive over loopback: this API installs code
|
|
67
|
+
* into the profile and must not be reachable from the network.
|
|
68
|
+
* @param {import('node:http').IncomingMessage} request - incoming request.
|
|
69
|
+
* @returns {boolean} true when the peer is local.
|
|
70
|
+
*/
|
|
71
|
+
function isLoopback(request) {
|
|
72
|
+
const address = request.socket.remoteAddress ?? '';
|
|
73
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Reject browser requests a foreign page started: a cross-site form or fetch
|
|
78
|
+
* must not reach an API that writes code into the profile.
|
|
79
|
+
* @param {import('node:http').IncomingMessage} request - incoming request.
|
|
80
|
+
* @returns {boolean} true when the request did not come from another site.
|
|
81
|
+
*/
|
|
82
|
+
function isSameOrigin(request) {
|
|
83
|
+
const site = request.headers['sec-fetch-site'];
|
|
84
|
+
if (site === undefined) return true;
|
|
85
|
+
return site !== 'cross-site';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Describe a filesystem location without leaking an absolute path.
|
|
90
|
+
* @param {string} profileDir - absolute profile directory.
|
|
91
|
+
* @param {string} absolute - path to describe.
|
|
92
|
+
* @returns {string} profile-relative location.
|
|
93
|
+
*/
|
|
94
|
+
function describePath(profileDir, absolute) {
|
|
95
|
+
const parts = String(absolute).split(/[\\/]+/).filter((part) => part !== '');
|
|
96
|
+
const profileParts = String(profileDir).split(/[\\/]+/).filter((part) => part !== '');
|
|
97
|
+
let shared = 0;
|
|
98
|
+
while (shared < parts.length && shared < profileParts.length && parts[shared].toLowerCase() === profileParts[shared].toLowerCase()) shared += 1;
|
|
99
|
+
if (shared === profileParts.length) return '<profile>/' + parts.slice(shared).join('/');
|
|
100
|
+
return '<external>/' + parts.slice(-1).join('/');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Replace machine paths inside a message with the labels {@link describePath} uses.
|
|
105
|
+
* @param {string} message - raw message.
|
|
106
|
+
* @param {string} profileDir - absolute profile directory.
|
|
107
|
+
* @returns {string} message safe to return to the browser.
|
|
108
|
+
*/
|
|
109
|
+
function redactPaths(message, profileDir) {
|
|
110
|
+
let text = String(message);
|
|
111
|
+
if (typeof profileDir === 'string' && profileDir !== '') {
|
|
112
|
+
const variants = new Set([profileDir, profileDir.replace(/\\/g, '/'), profileDir.replace(/\//g, '\\')]);
|
|
113
|
+
for (const variant of variants) text = text.split(variant).join('<profile>');
|
|
114
|
+
}
|
|
115
|
+
return text.replace(/[A-Za-z]:[\\/][^\s"',;)]*/g, (match) => '<external>/' + match.split(/[\\/]+/).pop());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Read a request body with an upper bound.
|
|
120
|
+
* @param {import('node:http').IncomingMessage} request - incoming request.
|
|
121
|
+
* @param {number} limit - maximum bytes.
|
|
122
|
+
* @returns {Promise<Buffer>} body bytes.
|
|
123
|
+
*/
|
|
124
|
+
async function readBody(request, limit) {
|
|
125
|
+
const chunks = [];
|
|
126
|
+
let size = 0;
|
|
127
|
+
for await (const chunk of request) {
|
|
128
|
+
size += chunk.length;
|
|
129
|
+
if (size > limit) throw new Error('archive exceeds the ' + Math.round(limit / (1024 * 1024)) + ' MiB import limit');
|
|
130
|
+
chunks.push(chunk);
|
|
131
|
+
}
|
|
132
|
+
return Buffer.concat(chunks);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Stream a zip response, honouring backpressure.
|
|
137
|
+
* @param {import('node:http').ServerResponse} response - response to write.
|
|
138
|
+
* @param {AsyncGenerator<Buffer>} chunks - archive chunks.
|
|
139
|
+
* @param {string} downloadName - file name offered to the browser.
|
|
140
|
+
* @returns {Promise<void>} resolves once the response is complete.
|
|
141
|
+
*/
|
|
142
|
+
async function streamZip(response, chunks, downloadName) {
|
|
143
|
+
const ascii = downloadName.replace(/[^\x20-\x7e]/g, '_');
|
|
144
|
+
response.writeHead(200, {
|
|
145
|
+
'content-type': 'application/zip',
|
|
146
|
+
'cache-control': 'no-store',
|
|
147
|
+
'content-disposition': 'attachment; filename="' + ascii + '"; filename*=UTF-8\'\'' + encodeURIComponent(downloadName),
|
|
148
|
+
});
|
|
149
|
+
for await (const chunk of chunks) {
|
|
150
|
+
if (!response.write(chunk)) await once(response, 'drain');
|
|
151
|
+
}
|
|
152
|
+
response.end();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Resolve the profile directory the running host was launched with.
|
|
157
|
+
* @param {any} ctx - Cordis context of the host plugin.
|
|
158
|
+
* @returns {string} absolute profile directory.
|
|
159
|
+
*/
|
|
160
|
+
function profileDirOf(ctx) {
|
|
161
|
+
const profile = ctx.get('profileContext');
|
|
162
|
+
const dir = profile?.dir;
|
|
163
|
+
if (typeof dir !== 'string' || dir === '') {
|
|
164
|
+
throw new Error('this DSH process was not started from a profile directory, so plugin packaging is unavailable');
|
|
165
|
+
}
|
|
166
|
+
return dir;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* DSH home: the environment's `DSH_HOME`, else the profile's grandparent when
|
|
171
|
+
* the layout is `<home>/profiles/<name>`.
|
|
172
|
+
* @param {string} profileDir - absolute profile directory.
|
|
173
|
+
* @returns {string} absolute home directory.
|
|
174
|
+
*/
|
|
175
|
+
function dshHomeOf(profileDir) {
|
|
176
|
+
/* A profile at <home>/profiles/<name> names its own home. The environment is
|
|
177
|
+
* the fallback, not the authority: tooling and tests mount profiles from
|
|
178
|
+
* other homes inside a process that already exports DSH_HOME. */
|
|
179
|
+
const parent = dirname(profileDir);
|
|
180
|
+
if (basename(parent) === 'profiles') return dirname(parent);
|
|
181
|
+
const fromEnvironment = String(process.env.DSH_HOME ?? '').trim();
|
|
182
|
+
return fromEnvironment !== '' ? fromEnvironment : profileDir;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Select an imported bundle in the profile manifest when the plugin manager is
|
|
187
|
+
* not loaded: the package is on disk and in the dependency list either way, so
|
|
188
|
+
* the next start mounts it.
|
|
189
|
+
* @param {string} profileDir - absolute profile directory.
|
|
190
|
+
* @param {string} name - bundle package name.
|
|
191
|
+
* @returns {boolean} whether the bundle list changed.
|
|
192
|
+
*/
|
|
193
|
+
function selectBundleInManifest(profileDir, name) {
|
|
194
|
+
const file = join(profileDir, 'package.json');
|
|
195
|
+
const manifest = JSON.parse(readFileSync(file, 'utf8'));
|
|
196
|
+
const profile = manifest.dsh?.profile;
|
|
197
|
+
if (manifest.dsh === undefined || profile === undefined) return false;
|
|
198
|
+
const bundles = Array.isArray(profile.bundles) ? [...profile.bundles] : [];
|
|
199
|
+
if (bundles.includes(name)) return false;
|
|
200
|
+
bundles.push(name);
|
|
201
|
+
manifest.dsh.profile = { ...profile, bundles };
|
|
202
|
+
writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n');
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Enable an imported bundle through the official plugin manager so the running
|
|
208
|
+
* composition picks it up without a restart, or select it in the profile
|
|
209
|
+
* manifest when that service is unavailable.
|
|
210
|
+
* @param {any} ctx - Cordis context of the host plugin.
|
|
211
|
+
* @param {any} root - archive root descriptor.
|
|
212
|
+
* @param {string} profileDir - absolute profile directory.
|
|
213
|
+
* @returns {Promise<{ application: string, reason?: string }>} how the change was applied.
|
|
214
|
+
*/
|
|
215
|
+
async function enableImported(ctx, root, profileDir) {
|
|
216
|
+
if (root?.bundle !== true) return { application: 'dependencies-only' };
|
|
217
|
+
const manager = ctx.get('pluginManager');
|
|
218
|
+
if (manager === undefined) {
|
|
219
|
+
try {
|
|
220
|
+
const selected = selectBundleInManifest(profileDir, root.name);
|
|
221
|
+
return {
|
|
222
|
+
application: 'restart-required',
|
|
223
|
+
reason: selected
|
|
224
|
+
? 'added to the profile bundle list; restart DSH to load it'
|
|
225
|
+
: 'the plugin manager service is not loaded',
|
|
226
|
+
};
|
|
227
|
+
} catch (error) {
|
|
228
|
+
return { application: 'restart-required', reason: redactPaths(error instanceof Error ? error.message : String(error), profileDir) };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
const report = await manager.setBundleEnabled(root.name, true);
|
|
233
|
+
return { application: report?.application === 'restart-required' ? 'restart-required' : 'applied' };
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return { application: 'restart-required', reason: redactPaths(error instanceof Error ? error.message : String(error), profileDir) };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Ask the npm registry for the newest published version of each package.
|
|
241
|
+
*
|
|
242
|
+
* The catalogue shows what is installed; "is this the newest release" is the
|
|
243
|
+
* one fact a profile cannot answer on its own, and a package that only exists
|
|
244
|
+
* as a `link:` or `file:` dependency was never published at all. Every failure
|
|
245
|
+
* is per-package and silent: an offline machine simply sees "未知".
|
|
246
|
+
* @param {string[]} names - package names to look up.
|
|
247
|
+
* @param {number} [timeoutMs] - per-request budget.
|
|
248
|
+
* @returns {Promise<Record<string, { latest: string | null, error: string | null }>>} answers.
|
|
249
|
+
*/
|
|
250
|
+
async function fetchLatestVersions(names, timeoutMs = 6000) {
|
|
251
|
+
const out = {};
|
|
252
|
+
const queue = [...names];
|
|
253
|
+
const worker = async () => {
|
|
254
|
+
for (;;) {
|
|
255
|
+
const name = queue.shift();
|
|
256
|
+
if (name === undefined) return;
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
259
|
+
try {
|
|
260
|
+
const response = await fetch('https://registry.npmjs.org/' + encodeURIComponent(name).replace(/^%40/, '@') + '/latest', {
|
|
261
|
+
headers: { accept: 'application/vnd.npm.install-v1+json, application/json' },
|
|
262
|
+
signal: controller.signal,
|
|
263
|
+
});
|
|
264
|
+
if (!response.ok) {
|
|
265
|
+
out[name] = { latest: null, error: response.status === 404 ? 'unpublished' : 'HTTP ' + response.status };
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const payload = await response.json();
|
|
269
|
+
out[name] = { latest: typeof payload?.version === 'string' ? payload.version : null, error: payload?.version ? null : 'unpublished' };
|
|
270
|
+
} catch (error) {
|
|
271
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
272
|
+
out[name] = { latest: null, error: /abort/i.test(message) ? 'timeout' : 'offline' };
|
|
273
|
+
} finally {
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
await Promise.all(Array.from({ length: Math.min(6, names.length) }, worker));
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Handle one API request.
|
|
284
|
+
* @param {any} ctx - Cordis context of the host plugin.
|
|
285
|
+
* @param {import('node:http').IncomingMessage} request - incoming request.
|
|
286
|
+
* @param {import('node:http').ServerResponse} response - response to fill.
|
|
287
|
+
* @param {{ maxImportBytes: number }} config - resolved plugin config.
|
|
288
|
+
* @returns {Promise<void>} resolves when the response is finished.
|
|
289
|
+
*/
|
|
290
|
+
async function handle(ctx, request, response, config) {
|
|
291
|
+
if (!isLoopback(request)) {
|
|
292
|
+
fail(response, 403, 'plugin packaging is only available over loopback');
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (!isSameOrigin(request)) {
|
|
296
|
+
fail(response, 403, 'plugin packaging refuses cross-site requests');
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
300
|
+
if (url.pathname !== ROUTE_PREFIX && !url.pathname.startsWith(ROUTE_PREFIX + '/')) {
|
|
301
|
+
fail(response, 404, 'unknown plugin-packer route ' + url.pathname);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const route = url.pathname.slice(ROUTE_PREFIX.length + 1);
|
|
305
|
+
const profileDir = profileDirOf(ctx);
|
|
306
|
+
const home = dshHomeOf(profileDir);
|
|
307
|
+
|
|
308
|
+
if (route === 'api/list' && request.method === 'GET') {
|
|
309
|
+
const catalogue = listPlugins(profileDir, {
|
|
310
|
+
sort: url.searchParams.get('sort') ?? undefined,
|
|
311
|
+
order: url.searchParams.get('order') ?? undefined,
|
|
312
|
+
});
|
|
313
|
+
const facts = readProfileFacts(profileDir);
|
|
314
|
+
const inventory = describeAssets(profileDir, home);
|
|
315
|
+
const assetCount = new Map();
|
|
316
|
+
for (const descriptor of inventory.descriptors) assetCount.set(descriptor.plugin, (assetCount.get(descriptor.plugin) ?? 0) + descriptor.assets.length);
|
|
317
|
+
const rows = catalogue.rows.map((row) => ({ ...row, assets: assetCount.get(row.name) ?? 0 }));
|
|
318
|
+
const totalBytes = rows.reduce((sum, row) => sum + (typeof row.bytes === 'number' ? row.bytes : 0), 0);
|
|
319
|
+
const totalFiles = rows.reduce((sum, row) => sum + (typeof row.files === 'number' ? row.files : 0), 0);
|
|
320
|
+
sendJson(response, 200, {
|
|
321
|
+
ok: true,
|
|
322
|
+
formatVersion: PACK_FORMAT_VERSION,
|
|
323
|
+
sort: catalogue.sort,
|
|
324
|
+
order: catalogue.order,
|
|
325
|
+
profile: { name: ctx.get('profileContext')?.name ?? null, packages: rows.length },
|
|
326
|
+
totals: {
|
|
327
|
+
bytes: totalBytes,
|
|
328
|
+
files: totalFiles,
|
|
329
|
+
plugins: rows.filter((row) => row.exportable).length,
|
|
330
|
+
exportableBytes: rows.filter((row) => row.exportable).reduce((sum, row) => sum + (typeof row.bytes === 'number' ? row.bytes : 0), 0),
|
|
331
|
+
},
|
|
332
|
+
bundles: [...facts.bundles],
|
|
333
|
+
rows,
|
|
334
|
+
assetErrors: inventory.errors,
|
|
335
|
+
});
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (route === 'api/latest' && request.method === 'GET') {
|
|
340
|
+
const names = (url.searchParams.get('names') ?? '')
|
|
341
|
+
.split(',')
|
|
342
|
+
.map((entry) => entry.trim())
|
|
343
|
+
.filter((entry) => entry !== '')
|
|
344
|
+
.slice(0, 200);
|
|
345
|
+
if (names.length === 0) {
|
|
346
|
+
fail(response, 400, 'missing names parameter');
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
sendJson(response, 200, { ok: true, versions: await fetchLatestVersions(names) });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (route === 'api/assets' && request.method === 'GET') {
|
|
354
|
+
const inventory = describeAssets(profileDir, home);
|
|
355
|
+
sendJson(response, 200, {
|
|
356
|
+
ok: true,
|
|
357
|
+
home: describePath(profileDir, home),
|
|
358
|
+
descriptors: inventory.descriptors.map((descriptor) => ({
|
|
359
|
+
...descriptor,
|
|
360
|
+
assets: descriptor.assets.map((asset) => ({
|
|
361
|
+
...asset,
|
|
362
|
+
installDir: describePath(profileDir, asset.installDir),
|
|
363
|
+
bundleDir: describePath(profileDir, asset.bundleDir),
|
|
364
|
+
expect: asset.expect.map((entry) => ({ ...entry, path: describePath(profileDir, entry.path) })),
|
|
365
|
+
})),
|
|
366
|
+
})),
|
|
367
|
+
errors: inventory.errors,
|
|
368
|
+
});
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (route === 'api/export' && request.method === 'GET') {
|
|
373
|
+
const name = url.searchParams.get('name') ?? '';
|
|
374
|
+
if (name === '') {
|
|
375
|
+
fail(response, 400, 'missing name parameter');
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const closure = expandClosure(profileDir, name);
|
|
379
|
+
const plan = planArchive(profileDir, closure);
|
|
380
|
+
const staged = await stageAssets(profileDir, name);
|
|
381
|
+
const facts = readProfileFacts(profileDir);
|
|
382
|
+
const manifest = buildManifest(closure, plan, {
|
|
383
|
+
profileName: ctx.get('profileContext')?.name ?? 'unknown',
|
|
384
|
+
enabled: facts.bundles.has(name),
|
|
385
|
+
generatorVersion: OWN_VERSION,
|
|
386
|
+
assets: staged.entries,
|
|
387
|
+
});
|
|
388
|
+
const header = { name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest, null, 2), 'utf8') };
|
|
389
|
+
const safeName = name.replace(/^@/, '').replace(/[^a-zA-Z0-9._-]+/g, '-');
|
|
390
|
+
const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '');
|
|
391
|
+
const downloadName = safeName + '-' + (closure.root.version ?? 'pack') + '-' + stamp + '.dsh-plugin.zip';
|
|
392
|
+
await streamZip(response, createZipStream([header, ...plan.sources, ...staged.sources]), downloadName);
|
|
393
|
+
ctx.logger?.info?.(
|
|
394
|
+
'plugin-packer: exported ' + name + ' (' + plan.files + ' package files, ' + plan.total + ' bytes' +
|
|
395
|
+
(staged.entries.length === 0 ? '' : '; ' + staged.totals.files + ' asset files, ' + staged.totals.bytes + ' bytes') + ')',
|
|
396
|
+
);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (route === 'api/import' && request.method === 'POST') {
|
|
401
|
+
const body = await readBody(request, config.maxImportBytes);
|
|
402
|
+
if (body.length === 0) {
|
|
403
|
+
fail(response, 400, 'empty request body');
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
const members = readZip(body);
|
|
407
|
+
const sandbox = await mkdtemp(join(tmpdir(), 'dsh-plugin-pack2-'));
|
|
408
|
+
try {
|
|
409
|
+
const extracted = join(sandbox, 'pack');
|
|
410
|
+
await extractArchive(extracted, members);
|
|
411
|
+
const backupRoot = join(profileDir, '.plugin-packer', 'backups');
|
|
412
|
+
await mkdir(backupRoot, { recursive: true });
|
|
413
|
+
const report = await installPack(profileDir, extracted, backupRoot);
|
|
414
|
+
const assets = await installAssets({
|
|
415
|
+
packDir: report.packDir,
|
|
416
|
+
profileDir,
|
|
417
|
+
home,
|
|
418
|
+
manifest: report.manifest,
|
|
419
|
+
backupRoot,
|
|
420
|
+
logger: ctx.logger,
|
|
421
|
+
});
|
|
422
|
+
const application = await enableImported(ctx, report.root, profileDir);
|
|
423
|
+
/* Displaced packages and environments pile up one batch per import.
|
|
424
|
+
* Five batches is plenty to roll back a bad install; everything older is
|
|
425
|
+
* dead weight in the profile. */
|
|
426
|
+
const pruned = await pruneBackups(backupRoot, 5);
|
|
427
|
+
sendJson(response, 200, {
|
|
428
|
+
ok: true,
|
|
429
|
+
formatVersion: report.formatVersion,
|
|
430
|
+
root: report.root,
|
|
431
|
+
installed: report.installed,
|
|
432
|
+
replaced: report.replaced,
|
|
433
|
+
backupRoot: describePath(profileDir, backupRoot),
|
|
434
|
+
backupsPruned: pruned.removed.length,
|
|
435
|
+
assets: assets.map((asset) => ({
|
|
436
|
+
id: asset.id,
|
|
437
|
+
kind: asset.kind,
|
|
438
|
+
label: asset.label,
|
|
439
|
+
installDir: describePath(profileDir, asset.installDir),
|
|
440
|
+
replaced: asset.replaced,
|
|
441
|
+
files: asset.files,
|
|
442
|
+
bytes: asset.bytes,
|
|
443
|
+
install: asset.install === null ? null : { code: asset.install.code, ms: asset.install.ms },
|
|
444
|
+
postInstall: asset.postInstall === null ? null : { code: asset.postInstall.code, ms: asset.postInstall.ms },
|
|
445
|
+
})),
|
|
446
|
+
application,
|
|
447
|
+
});
|
|
448
|
+
ctx.logger?.info?.(
|
|
449
|
+
'plugin-packer: imported ' + String(report.root?.name) + ' (' + report.installed.length + ' packages, ' +
|
|
450
|
+
assets.length + ' assets, ' + application.application + ')',
|
|
451
|
+
);
|
|
452
|
+
} finally {
|
|
453
|
+
await rm(sandbox, { recursive: true, force: true });
|
|
454
|
+
}
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
if (route === 'api/health' && request.method === 'GET') {
|
|
459
|
+
sendJson(response, 200, {
|
|
460
|
+
ok: true,
|
|
461
|
+
version: OWN_VERSION,
|
|
462
|
+
packFormatVersion: PACK_FORMAT_VERSION,
|
|
463
|
+
acceptsFormats: [1, 2],
|
|
464
|
+
assets: true,
|
|
465
|
+
home: existsSync(home),
|
|
466
|
+
});
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
fail(response, 404, 'unknown plugin-packer route ' + route);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Plugin body: claim the loopback API routes on the host web server. */
|
|
473
|
+
export function apply(ctx, config = {}) {
|
|
474
|
+
const resolved = { maxImportBytes: config.maxImportBytes ?? 512 * 1024 * 1024 };
|
|
475
|
+
const dispose = ctx.webServer.register({
|
|
476
|
+
kind: 'prefix',
|
|
477
|
+
path: ROUTE_PREFIX,
|
|
478
|
+
handler: async (request, response) => {
|
|
479
|
+
try {
|
|
480
|
+
await handle(ctx, request, response, resolved);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
483
|
+
let profileDir = '';
|
|
484
|
+
try {
|
|
485
|
+
profileDir = profileDirOf(ctx);
|
|
486
|
+
} catch {
|
|
487
|
+
profileDir = '';
|
|
488
|
+
}
|
|
489
|
+
const safe = redactPaths(message, profileDir);
|
|
490
|
+
ctx.logger?.warn?.('plugin-packer: ' + safe);
|
|
491
|
+
if (!response.headersSent) fail(response, 500, safe);
|
|
492
|
+
else response.destroy();
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
});
|
|
496
|
+
ctx.effect(() => dispose, 'plugin-packer routes');
|
|
497
|
+
ctx.logger?.info?.('plugin-packer: API ready at ' + ROUTE_PREFIX + '/api');
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Services this plugin needs before it can register routes. */
|
|
501
|
+
export const inject = ['webServer'];
|