dsh-zipfix 0.0.0-stage → 0.4.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,597 @@
1
+ /**
2
+ * dsh-zipfix 的 HTTP API(供侧边栏 UI 包 dsh-zipfix-ui 调用)。
3
+ *
4
+ * 这条通道只做「浏览器 ↔ 本机 Host」的搬运,修复逻辑一律复用 lib/fix.js 的
5
+ * 同一套操作(与 5 个 agent 工具完全同源),因此 UI 与 agent 两条调用路径行为一致。
6
+ *
7
+ * 安全设计(面向 127.0.0.1 本地服务):
8
+ * - 路由前缀独立为 `/zipfix-api`,不与 `/api` 网关或 SPA 回退冲突;
9
+ * - 变更类请求必须带 `x-zipfix-token`(或 URL token);token 只能由同源页面
10
+ * GET `/zipfix-api/token` 读取,跨站因 CORS 无法读取响应体,构成 CSRF 防护;
11
+ * - 校验 `Origin`(若浏览器发送)必须在允许集合内;
12
+ * - 上传按流式落盘并限制体积(默认 2 GiB),校验 ZIP 魔数;
13
+ * - 下载/报告只允许访问本进程登记过的任务目录,不接受任意路径;
14
+ * - 任务目录位于系统临时目录,24 小时后自动清理(下载后也可显式清理)。
15
+ *
16
+ * 注意:该模块不注册任何东西;调用方负责 webServer.register 与 disposer 生命周期。
17
+ */
18
+
19
+ import crypto from 'node:crypto';
20
+ import fs from 'node:fs';
21
+ import fsp from 'node:fs/promises';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { pipeline } from 'node:stream/promises';
25
+ import { Transform } from 'node:stream';
26
+ import { fixZipArchive } from './fix.js';
27
+
28
+ /** HTTP 前缀。 */
29
+ export const WEB_API_PREFIX = '/zipfix-api';
30
+ /** 上传体积上限(2 GiB,与 ZIP64 能力匹配)。 */
31
+ const MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
32
+ /** JSON 请求体上限。 */
33
+ const MAX_JSON_BYTES = 1024 * 1024;
34
+ /** 任务保留时长。 */
35
+ const TASK_TTL_MS = 24 * 60 * 60 * 1000;
36
+
37
+ function sendJson(res, status, payload) {
38
+ const body = JSON.stringify(payload);
39
+ res.writeHead(status, {
40
+ 'content-type': 'application/json; charset=utf-8',
41
+ 'content-length': Buffer.byteLength(body),
42
+ 'cache-control': 'no-store',
43
+ 'x-content-type-options': 'nosniff',
44
+ });
45
+ res.end(body);
46
+ }
47
+
48
+ function sendText(res, status, text, contentType = 'text/plain; charset=utf-8') {
49
+ res.writeHead(status, {
50
+ 'content-type': contentType,
51
+ 'content-length': Buffer.byteLength(text),
52
+ 'cache-control': 'no-store',
53
+ 'x-content-type-options': 'nosniff',
54
+ });
55
+ res.end(text);
56
+ }
57
+
58
+ /** 读取 JSON 请求体(带上限)。 */
59
+ async function readJsonBody(req) {
60
+ const chunks = [];
61
+ let size = 0;
62
+ for await (const chunk of req) {
63
+ size += chunk.length;
64
+ if (size > MAX_JSON_BYTES) throw new HttpError(413, '请求体过大');
65
+ chunks.push(chunk);
66
+ }
67
+ if (chunks.length === 0) return {};
68
+ try {
69
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
70
+ } catch {
71
+ throw new HttpError(400, '无效的 JSON 请求体');
72
+ }
73
+ }
74
+
75
+ class HttpError extends Error {
76
+ constructor(status, message) {
77
+ super(message);
78
+ this.status = status;
79
+ }
80
+ }
81
+
82
+ /** 上传文件名的安全化:只保留 basename,去掉非法字符,保证 .zip 后缀。 */
83
+ function sanitizeUploadName(raw) {
84
+ let name = String(raw ?? '').replace(/\\/g, '/');
85
+ name = name.slice(name.lastIndexOf('/') + 1);
86
+ name = name.replace(/[<>:"|?*\u0000-\u001f]/g, '_').replace(/[. ]+$/g, '');
87
+ if (name.length === 0) name = 'upload.zip';
88
+ if (!/\.zip$/i.test(name)) name = `${name}.zip`;
89
+ return name.length > 180 ? `${name.slice(0, 170)}.zip` : name;
90
+ }
91
+
92
+ /** RFC 5987 附件文件名(兼容中文)。 */
93
+ function contentDisposition(filename) {
94
+ const fallback = filename.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
95
+ return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
96
+ }
97
+
98
+ function readHeadBytes(filePath, length) {
99
+ const buf = Buffer.alloc(length);
100
+ const fd = fs.openSync(filePath, 'r');
101
+ try {
102
+ const read = fs.readSync(fd, buf, 0, length, 0);
103
+ return buf.subarray(0, read);
104
+ } finally {
105
+ fs.closeSync(fd);
106
+ }
107
+ }
108
+
109
+ /** 把一次 fixZipArchive 结果裁剪成 UI 需要的形状(避免把整份报告塞进响应)。 */
110
+ function toScanPayload(result) {
111
+ return {
112
+ status: result.status,
113
+ summary: result.summary,
114
+ encoding: result.encoding,
115
+ method: result.method,
116
+ confidence: result.confidence,
117
+ scores: result.scores,
118
+ zipSize: result.zipSize,
119
+ entries: result.entries,
120
+ forms: result.forms,
121
+ stripRoot: result.stripRoot,
122
+ samples: result.rows.slice(0, 12).map((row) => ({
123
+ action: row.action,
124
+ original: row.original,
125
+ fixed: row.fixed,
126
+ basis: row.basis,
127
+ verify: row.verify,
128
+ })),
129
+ irreversible: result.irreversible.slice(0, 12),
130
+ failures: result.failures.slice(0, 12),
131
+ warnings: result.warnings.slice(0, 12),
132
+ };
133
+ }
134
+
135
+ function toFixPayload(result) {
136
+ return {
137
+ status: result.status,
138
+ summary: result.summary,
139
+ forced: result.forced === true,
140
+ extractedFiles: result.applied.extractedFiles,
141
+ extractedDirectories: result.applied.extractedDirectories,
142
+ extractionFailures: result.applied.extractionFailures,
143
+ fixedZip: result.applied.fixedZip
144
+ ? {
145
+ entries: result.applied.fixedZip.entries,
146
+ allUtf8Flag: result.applied.fixedZip.allUtf8Flag,
147
+ fullChecked: result.applied.fixedZip.fullChecked,
148
+ }
149
+ : null,
150
+ irreversible: result.irreversible.length,
151
+ rows: result.rows.slice(0, 8).map((row) => ({
152
+ action: row.action,
153
+ original: row.original,
154
+ fixed: row.fixed,
155
+ verify: row.verify,
156
+ })),
157
+ failures: result.failures.slice(0, 8),
158
+ };
159
+ }
160
+
161
+ /**
162
+ * 安装 ZIP 修复的侧边栏 HTTP API。
163
+ * @param {object} ctx Host 插件上下文
164
+ * @returns {() => void} 释放函数(注销路由、清理任务目录)
165
+ */
166
+ export function installZipfixWebApi(ctx) {
167
+ const webServer = ctx.get('webServer');
168
+ if (webServer === undefined) {
169
+ ctx.logger?.warn?.('zipfix-ui: webServer service unavailable; sidebar API disabled');
170
+ return () => {};
171
+ }
172
+ // 宿主连接认证:所有路由先过 connection.requestRejection(Host/Origin 围栏 + 浏览器会话认证)。
173
+ // 拿不到 connection 或检查抛错时一律拒绝,绝不退化到「只检查 Host/Origin/回环」。
174
+ const connection = ctx.get('connection');
175
+
176
+ const tempRoot = path.join(os.tmpdir(), 'dsh-zipfix-web');
177
+ const tasks = new Map();
178
+ const token = crypto.randomBytes(24).toString('hex');
179
+ let lastSweep = 0;
180
+
181
+ let origin = '';
182
+ try {
183
+ origin = webServer.getOrigin();
184
+ } catch {
185
+ origin = '';
186
+ }
187
+ const allowedOrigins = new Set();
188
+ const allowedHosts = new Set();
189
+ if (origin !== '') {
190
+ allowedOrigins.add(origin);
191
+ try {
192
+ const parsed = new URL(origin);
193
+ const port = parsed.port;
194
+ allowedOrigins.add(`http://127.0.0.1:${port}`);
195
+ allowedOrigins.add(`http://localhost:${port}`);
196
+ allowedHosts.add(`127.0.0.1:${port}`);
197
+ allowedHosts.add(`localhost:${port}`);
198
+ allowedHosts.add(parsed.host.toLowerCase());
199
+ } catch {
200
+ /* origin 不可解析时只保留原值 */
201
+ }
202
+ }
203
+
204
+ function sweep() {
205
+ const now = Date.now();
206
+ if (now - lastSweep < 5 * 60 * 1000) return;
207
+ lastSweep = now;
208
+ for (const [id, task] of tasks) {
209
+ if (now - task.createdAt > TASK_TTL_MS) {
210
+ tasks.delete(id);
211
+ void fsp.rm(task.dir, { recursive: true, force: true }).catch(() => {});
212
+ }
213
+ }
214
+ }
215
+
216
+ function taskOrThrow(taskId) {
217
+ const task = typeof taskId === 'string' ? tasks.get(taskId) : undefined;
218
+ if (task === undefined) throw new HttpError(404, '任务不存在或已过期,请重新上传');
219
+ return task;
220
+ }
221
+
222
+ function assertOrigin(req) {
223
+ const header = req.headers.origin;
224
+ if (typeof header !== 'string' || header.length === 0) return; // 同源 GET/本地工具通常不带 Origin
225
+ if (!allowedOrigins.has(header)) throw new HttpError(403, '请求来源不被允许');
226
+ }
227
+
228
+ /**
229
+ * 宿主认证准入:交给 DSH 的 connection 服务判断 Host/Origin 围栏与浏览器会话。
230
+ * 失败关闭(fail closed):没有 connection 服务、检查抛错、或返回 401/403 都拒绝。
231
+ */
232
+ function assertAdmitted(req) {
233
+ if (connection === undefined || typeof connection.requestRejection !== 'function') {
234
+ throw new HttpError(403, '宿主认证服务不可用,已拒绝该请求');
235
+ }
236
+ let rejection;
237
+ try {
238
+ rejection = connection.requestRejection(req);
239
+ } catch (error) {
240
+ throw new HttpError(403, `宿主认证检查失败,已拒绝该请求:${error?.message ?? error}`);
241
+ }
242
+ if (rejection === undefined) return;
243
+ if (rejection === 401) throw new HttpError(401, '需要已认证的 DSH 页面会话');
244
+ throw new HttpError(403, '请求未通过宿主 Host/Origin 围栏');
245
+ }
246
+
247
+ /** 校验 Host 头,抵御 DNS rebinding:只接受本机绑定的 loopback 主机名。 */
248
+ function assertHost(req) {
249
+ const header = req.headers.host;
250
+ if (typeof header !== 'string' || header.length === 0) throw new HttpError(403, '缺少 Host 头');
251
+ if (allowedHosts.size === 0) return; // 拿不到绑定地址时退化为 Origin/token 防护
252
+ if (!allowedHosts.has(header.toLowerCase())) throw new HttpError(403, '请求 Host 不被允许');
253
+ }
254
+
255
+ function assertToken(req, url) {
256
+ const header = req.headers['x-zipfix-token'];
257
+ const provided = Array.isArray(header) ? header[0] : header;
258
+ if (provided === token) return;
259
+ if (url.searchParams.get('token') === token) return;
260
+ throw new HttpError(403, '缺少或无效的访问令牌');
261
+ }
262
+
263
+ async function handleUpload(req, res, url) {
264
+ sweep();
265
+ const name = sanitizeUploadName(url.searchParams.get('name'));
266
+ const encoding = url.searchParams.get('encoding') ?? undefined;
267
+ const id = crypto.randomUUID();
268
+ const dir = path.join(tempRoot, `task-${id}`);
269
+ await fsp.mkdir(dir, { recursive: true });
270
+ const sourcePath = path.join(dir, 'source.zip');
271
+ const controller = new AbortController();
272
+ let finished = false;
273
+ res.on('close', () => {
274
+ if (!finished) controller.abort();
275
+ });
276
+
277
+ let bytes = 0;
278
+ const limit = new Transform({
279
+ transform(chunk, _encoding, callback) {
280
+ bytes += chunk.length;
281
+ if (bytes > MAX_UPLOAD_BYTES) {
282
+ callback(new HttpError(413, `压缩包超过上限(${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MiB)`));
283
+ return;
284
+ }
285
+ callback(null, chunk);
286
+ },
287
+ });
288
+
289
+ try {
290
+ await pipeline(req, limit, fs.createWriteStream(sourcePath), { signal: controller.signal });
291
+ } catch (error) {
292
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
293
+ if (error instanceof HttpError) throw error;
294
+ if (controller.signal.aborted) throw new HttpError(499, '上传已取消');
295
+ throw new HttpError(400, `上传失败:${error.message}`);
296
+ }
297
+
298
+ const head = readHeadBytes(sourcePath, 4);
299
+ if (head.length < 4 || head[0] !== 0x50 || head[1] !== 0x4b) {
300
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
301
+ throw new HttpError(400, '这不是一个 ZIP 压缩包(缺少 PK 魔数)');
302
+ }
303
+
304
+ const task = {
305
+ id,
306
+ dir,
307
+ sourcePath,
308
+ name,
309
+ size: bytes,
310
+ createdAt: Date.now(),
311
+ fixedPath: null,
312
+ fixedName: null,
313
+ report: null,
314
+ };
315
+ tasks.set(id, task);
316
+
317
+ let scan;
318
+ try {
319
+ scan = await fixZipArchive({
320
+ zipPath: sourcePath,
321
+ dryRun: true,
322
+ extract: false,
323
+ buildFixedZip: false,
324
+ displayName: name,
325
+ ...(encoding ? { encoding } : {}),
326
+ signal: controller.signal,
327
+ });
328
+ } catch (error) {
329
+ tasks.delete(id);
330
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
331
+ throw new HttpError(400, `ZIP 解析失败:${error.message}`);
332
+ }
333
+
334
+ finished = true;
335
+ sendJson(res, 200, {
336
+ ok: true,
337
+ taskId: id,
338
+ name,
339
+ size: bytes,
340
+ scan: toScanPayload(scan),
341
+ });
342
+ }
343
+
344
+ async function handleFix(req, res, body) {
345
+ const task = taskOrThrow(body.taskId);
346
+ const version = (task.fixVersion ?? 0) + 1;
347
+ task.fixVersion = version;
348
+ const outputDir = path.join(task.dir, `fixed-${version}`);
349
+ await fsp.mkdir(outputDir, { recursive: true });
350
+ const controller = new AbortController();
351
+ let finished = false;
352
+ res.on('close', () => {
353
+ if (!finished) controller.abort();
354
+ });
355
+ let result;
356
+ try {
357
+ result = await fixZipArchive({
358
+ zipPath: task.sourcePath,
359
+ outputDir,
360
+ dryRun: false,
361
+ extract: false,
362
+ buildFixedZip: true,
363
+ stripRoot: body.stripRoot !== false,
364
+ force: body.force === true,
365
+ displayName: task.name,
366
+ ...(body.encoding ? { encoding: body.encoding } : {}),
367
+ signal: controller.signal,
368
+ });
369
+ } catch (error) {
370
+ if (controller.signal.aborted) throw new HttpError(499, '操作已取消');
371
+ throw new HttpError(500, `生成修复版 ZIP 失败:${error.message}`);
372
+ }
373
+ finished = true;
374
+ if (result.applied.fixedZipPath) {
375
+ task.fixedPath = result.applied.fixedZipPath;
376
+ task.fixedName = path.basename(result.applied.fixedZipPath);
377
+ task.report = result.applied.report ?? null;
378
+ sendJson(res, 200, {
379
+ ok: true,
380
+ taskId: task.id,
381
+ result: toFixPayload(result),
382
+ downloadUrl: `${WEB_API_PREFIX}/download?task=${task.id}&token=${token}`,
383
+ reportUrl: task.report ? `${WEB_API_PREFIX}/report?task=${task.id}&format=md&token=${token}` : null,
384
+ csvUrl: task.report ? `${WEB_API_PREFIX}/report?task=${task.id}&format=csv&token=${token}` : null,
385
+ });
386
+ return;
387
+ }
388
+ // 判定「无需修复」且未 force:不产生文件,但把判定原样带回
389
+ task.report = result.applied.report ?? null;
390
+ sendJson(res, 200, {
391
+ ok: true,
392
+ taskId: task.id,
393
+ result: toFixPayload(result),
394
+ downloadUrl: null,
395
+ reportUrl: task.report ? `${WEB_API_PREFIX}/report?task=${task.id}&format=md&token=${token}` : null,
396
+ csvUrl: null,
397
+ });
398
+ }
399
+
400
+ async function handleExtract(req, res, body) {
401
+ const task = taskOrThrow(body.taskId);
402
+ const outputDir = String(body.outputDir ?? '').trim();
403
+ if (outputDir.length === 0) throw new HttpError(400, '请先选择输出目录');
404
+ if (!path.isAbsolute(outputDir)) throw new HttpError(400, '输出目录必须是绝对路径');
405
+ const controller = new AbortController();
406
+ let finished = false;
407
+ res.on('close', () => {
408
+ if (!finished) controller.abort();
409
+ });
410
+ let result;
411
+ try {
412
+ result = await fixZipArchive({
413
+ zipPath: task.sourcePath,
414
+ outputDir,
415
+ dryRun: false,
416
+ extract: true,
417
+ buildFixedZip: false,
418
+ stripRoot: body.stripRoot !== false,
419
+ force: body.force === true,
420
+ displayName: task.name,
421
+ ...(body.encoding ? { encoding: body.encoding } : {}),
422
+ signal: controller.signal,
423
+ });
424
+ } catch (error) {
425
+ if (controller.signal.aborted) throw new HttpError(499, '操作已取消');
426
+ throw new HttpError(500, `解压失败:${error.message}`);
427
+ }
428
+ finished = true;
429
+ sendJson(res, 200, {
430
+ ok: true,
431
+ taskId: task.id,
432
+ result: toFixPayload(result),
433
+ extract: {
434
+ outputDir: result.outputDir,
435
+ files: result.applied.extractedFiles,
436
+ directories: result.applied.extractedDirectories,
437
+ failures: result.applied.extractionFailures,
438
+ reportMarkdown: result.applied.report?.markdownPath ?? null,
439
+ },
440
+ });
441
+ }
442
+
443
+ async function handleDownload(req, res, url) {
444
+ const task = taskOrThrow(url.searchParams.get('task'));
445
+ if (!task.fixedPath) throw new HttpError(404, '还没有生成修复版 ZIP');
446
+ const stat = await fsp.stat(task.fixedPath);
447
+ res.writeHead(200, {
448
+ 'content-type': 'application/zip',
449
+ 'content-length': stat.size,
450
+ 'content-disposition': contentDisposition(task.fixedName ?? 'zipfix-fixed.zip'),
451
+ 'cache-control': 'no-store',
452
+ 'x-content-type-options': 'nosniff',
453
+ });
454
+ await pipeline(fs.createReadStream(task.fixedPath), res);
455
+ }
456
+
457
+ async function handleReport(req, res, url) {
458
+ const task = taskOrThrow(url.searchParams.get('task'));
459
+ const format = url.searchParams.get('format') === 'csv' ? 'csv' : 'md';
460
+ const filePath = format === 'csv' ? task.report?.csvPath : task.report?.markdownPath;
461
+ if (!filePath) throw new HttpError(404, '还没有可用的审计报告');
462
+ const text = await fsp.readFile(filePath, 'utf8');
463
+ sendText(res, 200, text, format === 'csv' ? 'text/csv; charset=utf-8' : 'text/markdown; charset=utf-8');
464
+ }
465
+
466
+ async function handleCleanup(req, res, body) {
467
+ const taskId = body.taskId;
468
+ const task = typeof taskId === 'string' ? tasks.get(taskId) : undefined;
469
+ if (task === undefined) {
470
+ sendJson(res, 200, { ok: true, removed: false });
471
+ return;
472
+ }
473
+ tasks.delete(task.id);
474
+ await fsp.rm(task.dir, { recursive: true, force: true }).catch(() => {});
475
+ sendJson(res, 200, { ok: true, removed: true });
476
+ }
477
+
478
+ async function handler(req, res) {
479
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
480
+ try {
481
+ if (!url.pathname.startsWith(WEB_API_PREFIX)) {
482
+ sendJson(res, 404, { ok: false, error: 'not found' });
483
+ return;
484
+ }
485
+ assertAdmitted(req);
486
+ assertOrigin(req);
487
+ assertHost(req);
488
+ const route = url.pathname.slice(WEB_API_PREFIX.length) || '/';
489
+ const method = (req.method ?? 'GET').toUpperCase();
490
+
491
+ if (method === 'GET' && (route === '/token' || route === '/health')) {
492
+ sendJson(res, 200, {
493
+ ok: true,
494
+ token,
495
+ origin,
496
+ maxUploadBytes: MAX_UPLOAD_BYTES,
497
+ taskTtlMs: TASK_TTL_MS,
498
+ version: '0.1.2',
499
+ });
500
+ return;
501
+ }
502
+
503
+ assertToken(req, url);
504
+
505
+ // 自检:告诉页面「侧边栏 UI 是否已注册进客户端模块图」,便于排查未刷新页面等情况
506
+ if (method === 'GET' && route === '/selfcheck') {
507
+ let clientRegistered = false;
508
+ let mentions = [];
509
+ try {
510
+ const clientModules = ctx.get('clientModules');
511
+ const graph = clientModules?.graph?.();
512
+ if (graph !== undefined) {
513
+ const serialized = JSON.stringify(graph);
514
+ clientRegistered = /dsh-zipfix(?:-ui)?\/client\.js/u.test(serialized);
515
+ mentions = [...new Set(serialized.match(/[^"\\]*dsh-zipfix(?:-ui)?[^"\\]*/g) ?? [])].slice(0, 20);
516
+ }
517
+ } catch {
518
+ clientRegistered = false;
519
+ }
520
+ sendJson(res, 200, {
521
+ ok: true,
522
+ hostApi: true,
523
+ clientRegistered,
524
+ clientId: 'dsh-zipfix-ui',
525
+ mentions,
526
+ hint: clientRegistered
527
+ ? '客户端模块已注册;若侧边栏仍未出现,请刷新页面。'
528
+ : '客户端模块尚未注册;请重新加载 dsh-zipfix-ui 插件或重启 Harness。',
529
+ });
530
+ return;
531
+ }
532
+
533
+ if (method === 'POST' && route === '/upload') {
534
+ await handleUpload(req, res, url);
535
+ return;
536
+ }
537
+ if (method === 'POST' && route === '/fix') {
538
+ const body = await readJsonBody(req);
539
+ await handleFix(req, res, body);
540
+ return;
541
+ }
542
+ if (method === 'POST' && route === '/extract') {
543
+ const body = await readJsonBody(req);
544
+ await handleExtract(req, res, body);
545
+ return;
546
+ }
547
+ if (method === 'POST' && route === '/cleanup') {
548
+ const body = await readJsonBody(req);
549
+ await handleCleanup(req, res, body);
550
+ return;
551
+ }
552
+ if (method === 'GET' && route === '/download') {
553
+ await handleDownload(req, res, url);
554
+ return;
555
+ }
556
+ if (method === 'GET' && route === '/report') {
557
+ await handleReport(req, res, url);
558
+ return;
559
+ }
560
+ sendJson(res, 404, { ok: false, error: `unknown endpoint ${method} ${route}` });
561
+ } catch (error) {
562
+ if (res.headersSent) {
563
+ try {
564
+ res.end();
565
+ } catch {
566
+ /* ignore */
567
+ }
568
+ return;
569
+ }
570
+ const status = error instanceof HttpError ? error.status : 500;
571
+ if (status >= 500) ctx.logger?.warn?.(`zipfix-ui: ${methodHint(req)} failed: ${error?.message ?? error}`);
572
+ sendJson(res, status, { ok: false, error: error?.message ?? String(error) });
573
+ }
574
+ }
575
+
576
+ function methodHint(req) {
577
+ return `${req.method ?? '?'} ${req.url ?? '?'}`;
578
+ }
579
+
580
+ const dispose = webServer.register({
581
+ kind: 'prefix',
582
+ path: WEB_API_PREFIX,
583
+ handler,
584
+ });
585
+
586
+ return () => {
587
+ try {
588
+ dispose();
589
+ } catch {
590
+ /* ignore */
591
+ }
592
+ for (const task of tasks.values()) {
593
+ void fsp.rm(task.dir, { recursive: true, force: true }).catch(() => {});
594
+ }
595
+ tasks.clear();
596
+ };
597
+ }