lantern-harness 0.1.23 → 0.1.25

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.
Files changed (129) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/builtin/session/bash-session.mjs +91 -0
  3. package/builtin/session/lh-bash.mjs +67 -1
  4. package/builtin/session/lh-web.mjs +103 -52
  5. package/builtin/session/mcp-client.mjs +290 -0
  6. package/builtin/session/pwsh-session.mjs +90 -0
  7. package/builtin/session/session-runs.mjs +6 -1
  8. package/builtin/session/tool-run-policy.mjs +32 -0
  9. package/builtin/session/web-fetch-policy.mjs +79 -0
  10. package/cli/acp-server.mjs +19 -9
  11. package/cli/agent-policy.mjs +60 -0
  12. package/cli/headless.mjs +30 -6
  13. package/cli/jsonrpc-server.mjs +9 -3
  14. package/cli/lantern.mjs +40 -5
  15. package/cli/server.mjs +2 -0
  16. package/dist/500.html +4 -4
  17. package/dist/_astro/Base.COYvzmy5.css +1 -0
  18. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.CWRCetQl.js → Base.astro_astro_type_script_index_0_lang.Cb6ggViJ.js} +1 -1
  19. package/dist/_astro/{CaseExecBoard.Dnb8oP5i.js → CaseExecBoard.cl2Od7av.js} +1 -1
  20. package/dist/_astro/{CaseGenerateApp.ci_JowEk.js → CaseGenerateApp.nE3RR7bV.js} +5 -5
  21. package/dist/_astro/CasesLibrary.e3vlOqSQ.js +21 -0
  22. package/dist/_astro/ChatApp.CECImcJo.js +226 -0
  23. package/dist/_astro/ConfirmDialog.D5qXeML0.js +1 -0
  24. package/dist/_astro/{DashboardBoard.D-zHXRds.js → DashboardBoard.CmxqpmzI.js} +2 -2
  25. package/dist/_astro/{DocsFileBrowser.BM3nH4VD.js → DocsFileBrowser.BdpWp8zQ.js} +1 -1
  26. package/dist/_astro/DocsPager.D55FTK9d.js +1 -0
  27. package/dist/_astro/{KnowledgeLibrary.D9KnqXzr.js → KnowledgeLibrary.DKci9jN8.js} +1 -1
  28. package/dist/_astro/MultiSelectDropdown.BHxW9XLR.js +1 -0
  29. package/dist/_astro/NamePromptDialog.Csfnh5eM.js +1 -0
  30. package/dist/_astro/{NavLibraries.RH3Sinuh.js → NavLibraries.BybmHnXn.js} +1 -1
  31. package/dist/_astro/PluginsPage.B6dsHB44.js +1 -0
  32. package/dist/_astro/{PluginsPage.DBRfSxtq.js → PluginsPage.D5LXPMns.js} +2 -2
  33. package/dist/_astro/{PmBugsBoard.BnnaNP1y.js → PmBugsBoard.B6w50MHD.js} +1 -1
  34. package/dist/_astro/{PmIterationsBoard.phiyhQVA.js → PmIterationsBoard.Dk7JheCU.js} +1 -1
  35. package/dist/_astro/{PmProjectDetail.C8kRX5lu.js → PmProjectDetail.O44fnczN.js} +1 -1
  36. package/dist/_astro/{PmProjectsBoard.CFApEGPo.js → PmProjectsBoard.qgj9HAj8.js} +1 -1
  37. package/dist/_astro/PmRequirementsBoard.BKY3h4CQ.js +1 -0
  38. package/dist/_astro/{PmRequirementsBoard.DR9egcgA.js → PmRequirementsBoard.DTL_RFxq.js} +1 -1
  39. package/dist/_astro/{PmShared.BrBicDMN.js → PmShared.Bwphj4KH.js} +1 -1
  40. package/dist/_astro/{PromptsLibrary.sz6MivVn.js → PromptsLibrary.Dv5OABdK.js} +1 -1
  41. package/dist/_astro/{ReportsPage.CYZtpeiv.js → ReportsPage.B7MOskzc.js} +1 -1
  42. package/dist/_astro/ReqAnalysisBoard.nUp89z1s.js +39 -0
  43. package/dist/_astro/{RequirementsLibrary.R4dNZa9y.js → RequirementsLibrary._OviMClB.js} +1 -1
  44. package/dist/_astro/SearchableSelect.D3ODywC4.js +1 -0
  45. package/dist/_astro/SettingsDialog.D3f4EOwl.js +1 -0
  46. package/dist/_astro/SlideOverDrawer.CpQu7VMQ.js +1 -0
  47. package/dist/_astro/SpaceSwitcher.DQOG363O.js +7 -0
  48. package/dist/_astro/{TasksBoard.D0HwS5hd.js → TasksBoard.rwdPWLAh.js} +1 -1
  49. package/dist/_astro/{TemplatesLibrary.CVv5Ef30.js → TemplatesLibrary.CEVQPDDz.js} +1 -1
  50. package/dist/_astro/{TestStatsBoard._qNcNorG.js → TestStatsBoard.CO4JMh4N.js} +1 -1
  51. package/dist/_astro/{TodosBoard.CF5wbJy7.js → TodosBoard.CrZMl6Ei.js} +1 -1
  52. package/dist/_astro/UiAutoBoard.BRMCH1zB.js +9 -0
  53. package/dist/_astro/{app-config.CF1xVPmo.js → app-config.DAIyT--R.js} +1 -1
  54. package/dist/_astro/app-version.BPkgRlbu.js +1 -0
  55. package/dist/_astro/bash-tools.D4DBYc9k.js +27 -0
  56. package/dist/_astro/case-fields.Dqkws1iX.js +1 -0
  57. package/dist/_astro/case-gen-run.Byxy6M5X.js +22 -0
  58. package/dist/_astro/case-review.DlCarphW.js +3 -0
  59. package/dist/_astro/{case-types.DS1EQ5yP.js → case-types.B6MLX3iE.js} +1 -1
  60. package/dist/_astro/{hydrate-cache.CmC22o_H.js → hydrate-cache.C0F0L04c.js} +1 -1
  61. package/dist/_astro/i18n.ele1lM9e.js +7 -0
  62. package/dist/_astro/{llm.BuR7z55C.js → llm.DyweO-KK.js} +1 -1
  63. package/dist/_astro/open-docs-in-session.D608wzlx.js +1 -0
  64. package/dist/_astro/{plugins.CVM1IaoC.js → plugins.Di6uuouN.js} +1 -1
  65. package/dist/_astro/req-analysis.CIZ_cIJQ.js +23 -0
  66. package/dist/_astro/settings.DbhUT6Ao.js +2 -0
  67. package/dist/_astro/{spaces-client.DnS6MgGy.js → spaces-client.OuJPy3GP.js} +1 -1
  68. package/dist/_astro/{story-review.BbdIf5zg.js → story-review.BvgXBApZ.js} +6 -3
  69. package/dist/_astro/{view-prefs.D1snIG5o.js → view-prefs.DkS1ldnh.js} +1 -1
  70. package/dist/case-exec/index.html +5 -5
  71. package/dist/cases/generate/index.html +5 -5
  72. package/dist/cases/library/index.html +5 -5
  73. package/dist/dashboard/index.html +5 -5
  74. package/dist/docs/changelog/index.html +52 -5
  75. package/dist/docs/install/index.html +48 -4
  76. package/dist/docs/manual/index.html +40 -33
  77. package/dist/knowledge/index.html +5 -5
  78. package/dist/plugins/index.html +5 -5
  79. package/dist/pm/bugs/index.html +5 -5
  80. package/dist/pm/iterations/index.html +5 -5
  81. package/dist/pm/projects/detail/index.html +5 -5
  82. package/dist/pm/projects/index.html +5 -5
  83. package/dist/pm/requirements/index.html +5 -5
  84. package/dist/prompts/index.html +5 -5
  85. package/dist/reports/index.html +5 -5
  86. package/dist/requirement-analysis/index.html +5 -5
  87. package/dist/requirements/index.html +5 -5
  88. package/dist/tasks/index.html +5 -5
  89. package/dist/templates/index.html +5 -5
  90. package/dist/test-automation/index.html +5 -5
  91. package/dist/test-stats/index.html +5 -5
  92. package/dist/todos/index.html +5 -5
  93. package/dist/workbench/index.html +5 -5
  94. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +9 -7
  95. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +14 -2
  96. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +23 -0
  97. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +35 -27
  98. package/lh-plugins/case-review-prompt.mjs +12 -106
  99. package/lh-plugins/lh-case-review.mjs +118 -34
  100. package/lh-plugins/lh-mcp.mjs +79 -0
  101. package/lh-plugins/lh-reports.mjs +11 -29
  102. package/lh-plugins/lh-req-analysis.mjs +59 -6
  103. package/lh-plugins/req-analysis-prompt.mjs +34 -44
  104. package/lh-plugins/story-review-prompt.mjs +8 -52
  105. package/lh-plugins/uiauto-prompt.mjs +9 -65
  106. package/package.json +3 -1
  107. package/dist/_astro/Base.GThhapKd.css +0 -1
  108. package/dist/_astro/CasesLibrary.CDjuLV_E.js +0 -21
  109. package/dist/_astro/ChatApp.Td2xCiQG.js +0 -216
  110. package/dist/_astro/ConfirmDialog.CsMwWevK.js +0 -1
  111. package/dist/_astro/DocsPager.B9VhI6E3.js +0 -1
  112. package/dist/_astro/NamePromptDialog.CS1pTTVl.js +0 -1
  113. package/dist/_astro/PluginsPage.DMDyUktn.js +0 -1
  114. package/dist/_astro/PmRequirementsBoard.B-AI9iZX.js +0 -1
  115. package/dist/_astro/ReqAnalysisBoard.CazI9SU-.js +0 -29
  116. package/dist/_astro/SearchableSelect.Cbb8jMnP.js +0 -1
  117. package/dist/_astro/SettingsDialog.Bs1I8b27.js +0 -1
  118. package/dist/_astro/SlideOverDrawer.DMWJPD_W.js +0 -1
  119. package/dist/_astro/SpaceSwitcher.Dw9LjKiJ.js +0 -7
  120. package/dist/_astro/UiAutoBoard.B-7mL3ez.js +0 -9
  121. package/dist/_astro/app-version.yT2l6J8H.js +0 -1
  122. package/dist/_astro/bash-tools.CPS0ZiKi.js +0 -25
  123. package/dist/_astro/case-fields.h0roo2br.js +0 -1
  124. package/dist/_astro/case-gen-run.D8DGX0mr.js +0 -19
  125. package/dist/_astro/case-review.C1hQRbQ2.js +0 -3
  126. package/dist/_astro/i18n.CjqQGCAI.js +0 -7
  127. package/dist/_astro/open-docs-in-session.Cj0J2-XT.js +0 -1
  128. package/dist/_astro/req-analysis.dhgy4p2f.js +0 -14
  129. package/dist/_astro/settings.B1yetppp.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # 版本日志
2
2
 
3
+ ## [0.1.25] - 2026-10-25
4
+
5
+ 用例管理一轮体验收口:大份测试点自动分批生成、备份列表迁入正式目录并可改名上传,质量评审「已修改」重审与忽略计数对齐说明。
6
+
7
+ ### 新增
8
+
9
+ - **用例生成自动分批**:测试点超过 40 条时 UI 仍一次确认,后台按批跑模型再合并入库;进度条用软百分比,避免大份卡在收尾
10
+ - **备份列表目录**:正式备份落到「用例管理/备份列表/」(首次备份才创建,主列表不展示);不再自动按 TTL 清理
11
+ - **行内备份可改名**:备份弹窗可改文件名,默认用原名(不再加 ISO 时间戳前缀);重名自动加 `(2)`
12
+ - **上传用例**:工具栏「上传用例」导入本地 `.xlsx` / `.xls` / `.csv` / `.md` 到根目录;同名覆盖前确认
13
+ - **备份列表改名 / 双击打开**:文件名列悬停铅笔改名;双击打开本地文件,去掉行内「打开」按钮
14
+
15
+ ### 修复
16
+
17
+ - **忽略后「错误无效」计数仍挂着**:落盘重算 `counts` 时排除已忽略;筛选芯片按当前条实时计
18
+ - **重审 Failed to fetch**:本地评审请求与模型流中断给出中文提示;网络类错误纳入重试
19
+ - **改名弹窗被抽屉盖住**:`NamePromptDialog` 提到 `z-110`,与确认框同级
20
+
21
+ ### 优化
22
+
23
+ - **重新评审完成提示**:有「已修改」时展示「本轮重审 N 条 → 升可用 / 仍待修改 / 仍无效」;手册与指南改为「已修改会重审重判,不会自动变可用」
24
+ - **备份列表抽屉**:宽度与评审抽屉一致(`max-w-5xl`);列表卡片撑满剩余高度;文件名旁改名图标贴文字不右对齐
25
+ - **操作手册**:同步备份列表、上传用例、重新评审口径
26
+
27
+ ## [0.1.24] - 2026-10-25
28
+
29
+ 平台对照 DSH 的三波次 MVP:会话 Fork / 条件工具 / 子代理与无头策略对齐,MCP 与终端控制补齐,Fetch 私网与模型能力、计划审批投影落地。
30
+
31
+ ### 新增
32
+
33
+ - **独立会话 Fork**:侧栏「分叉会话」复制消息为新会话,不写 parent、不带 subagent 语义(与 `fork_subagent` 区分)
34
+ - **条件工具组装**:`buildChatTools` 按访问档与插件 caps 注入工具;关插件则对应工具消失
35
+ - **子代理控制**:`subagent_list` / `status` / `await` / `abort` / `message`(steer),按聊天 `sessionId` 隔离
36
+ - **无头策略叠层**:`agent-policy` 统一 ask / rpc / acp 的 access 与 toolProfile;ACP `tools` 支持字符串档位
37
+ - **MCP 真客户端**:空间 `.lantern/local/mcp.json`(stdio / HTTP)→ 工具名 `mcp__服务器__工具`
38
+ - **持久终端 write / signal**:`bash_session_*` / `pwsh_session_*` 可写 stdin、发 SIGINT 等信号
39
+ - **Fetch 私网开关**:通用设置「允许抓取私网地址」;默认拦截 localhost / 私网,含跳转与 DNS 校验
40
+ - **模型能力声明**:提供商可配上下文窗口 / 是否支持工具 / 是否支持视觉,并门闩运行时
41
+ - **工具执行超时**:`tool-run-policy` 为浏览器与服务端回合包默认超时
42
+ - **计划审批投影**:`planPhase` / 待批方案写入会话,刷新或切回可恢复
43
+ - **job_output tail**:可取后台任务输出末尾 N 字符
44
+ - **内置插件「规划中」**:设置页默认隐藏规划中项,可勾选显示
45
+
46
+ ### 修复
47
+
48
+ - **确认弹层关闭缩影**:关闭动画期间冻结标题/正文,避免二次确认框内容被清空后闪一下
49
+
50
+ ### 优化
51
+
52
+ - **操作 / 安装 / 会话 / 全局插件手册**:同步 MCP、私网 Fetch、计划投影、终端 write/signal、无头策略对照与内置插件展示口径
53
+
3
54
  ## [0.1.23] - 2026-10-24
4
55
 
5
56
  对话里表格可读、工作汇报能带上测试数据、需求库与仪表盘几处体验收口:粘回预览不再撑爆、跳转工作台不再滚回旧卡片,休息日也不再倒计时下班。
@@ -344,6 +344,97 @@ export function readBashSession(sessionId, offset = 0) {
344
344
  };
345
345
  }
346
346
 
347
+ const ALLOWED_SIGNALS = new Set(['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGHUP']);
348
+
349
+ /**
350
+ * 向持久会话 stdin 写入原始文本(不等待 PS1)。
351
+ * @param {{ sessionId: string, data?: string, text?: string, submit?: boolean }} opts
352
+ */
353
+ export function writeBashSession(opts) {
354
+ const id = String(opts.sessionId || '').trim();
355
+ const session = sessions.get(id);
356
+ if (!session) return { ok: false, error: 'session not found' };
357
+ if (session.status !== 'running') {
358
+ return {
359
+ ok: false,
360
+ error: `session not running (${session.status})`,
361
+ session: publicSession(session),
362
+ };
363
+ }
364
+ let payload = String(opts.data ?? opts.text ?? '');
365
+ if (opts.submit !== false && !payload.endsWith('\n')) payload += '\n';
366
+ if (!payload) return { ok: false, error: 'data is required' };
367
+ try {
368
+ if (session.backend === 'pty' && session.pty) {
369
+ session.pty.write(payload);
370
+ } else if (session.child?.stdin) {
371
+ session.child.stdin.write(payload);
372
+ } else {
373
+ return { ok: false, error: 'session has no writable stdin' };
374
+ }
375
+ } catch (e) {
376
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
377
+ }
378
+ session.lastActiveAt = Date.now();
379
+ return {
380
+ ok: true,
381
+ sessionId: session.id,
382
+ backend: session.backend,
383
+ bytes: Buffer.byteLength(payload, 'utf8'),
384
+ session: publicSession(session),
385
+ };
386
+ }
387
+
388
+ /**
389
+ * @param {{ sessionId: string, signal?: string }} opts
390
+ */
391
+ export function signalBashSession(opts) {
392
+ const id = String(opts.sessionId || '').trim();
393
+ const signal = String(opts.signal || 'SIGINT')
394
+ .trim()
395
+ .toUpperCase();
396
+ if (!ALLOWED_SIGNALS.has(signal)) {
397
+ return {
398
+ ok: false,
399
+ error: `unsupported signal (allowed: ${[...ALLOWED_SIGNALS].join(', ')})`,
400
+ };
401
+ }
402
+ const session = sessions.get(id);
403
+ if (!session) return { ok: false, error: 'session not found' };
404
+ if (session.status !== 'running') {
405
+ return {
406
+ ok: false,
407
+ error: `session not running (${session.status})`,
408
+ session: publicSession(session),
409
+ };
410
+ }
411
+ try {
412
+ if (session.backend === 'pty' && session.pty) {
413
+ if (typeof session.pty.kill === 'function') {
414
+ session.pty.kill(signal);
415
+ } else if (session.pty.pid) {
416
+ process.kill(session.pty.pid, signal);
417
+ } else {
418
+ return { ok: false, error: 'pty has no kill' };
419
+ }
420
+ } else if (session.child) {
421
+ session.child.kill(signal);
422
+ } else {
423
+ return { ok: false, error: 'session has no process' };
424
+ }
425
+ } catch (e) {
426
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
427
+ }
428
+ session.lastActiveAt = Date.now();
429
+ return {
430
+ ok: true,
431
+ sessionId: session.id,
432
+ signal,
433
+ backend: session.backend,
434
+ session: publicSession(session),
435
+ };
436
+ }
437
+
347
438
  export function closeBashSession(sessionId) {
348
439
  return closeSessionInternal(String(sessionId || '').trim());
349
440
  }
@@ -21,6 +21,8 @@ import {
21
21
  openBashSession,
22
22
  readBashSession,
23
23
  sessionStats,
24
+ signalBashSession,
25
+ writeBashSession,
24
26
  } from './bash-session.mjs';
25
27
  import {
26
28
  closePwshSession,
@@ -29,6 +31,8 @@ import {
29
31
  openPwshSession,
30
32
  pwshSessionStats,
31
33
  readPwshSession,
34
+ signalPwshSession,
35
+ writePwshSession,
32
36
  } from './pwsh-session.mjs';
33
37
 
34
38
  const execFileAsync = promisify(execFile);
@@ -626,6 +630,50 @@ async function handleSessionRoutes(shell, req, res, projectRoot, url) {
626
630
  return sendJson(res, result.ok ? 200 : 404, result);
627
631
  }
628
632
 
633
+ if (url === `${prefix}/session/write` && req.method === 'POST') {
634
+ const body = JSON.parse((await readBody(req)) || '{}');
635
+ const access = normalizeAccess(body.access);
636
+ if (access === 'readonly') {
637
+ return sendJson(res, 403, {
638
+ error: `${label} 需要「工作区内修改」或「完全权限」`,
639
+ });
640
+ }
641
+ const result =
642
+ shell === 'pwsh'
643
+ ? writePwshSession({
644
+ sessionId: body.sessionId || body.id,
645
+ data: body.data ?? body.text,
646
+ submit: body.submit,
647
+ })
648
+ : writeBashSession({
649
+ sessionId: body.sessionId || body.id,
650
+ data: body.data ?? body.text,
651
+ submit: body.submit,
652
+ });
653
+ return sendJson(res, result.ok ? 200 : 400, result);
654
+ }
655
+
656
+ if (url === `${prefix}/session/signal` && req.method === 'POST') {
657
+ const body = JSON.parse((await readBody(req)) || '{}');
658
+ const access = normalizeAccess(body.access);
659
+ if (access === 'readonly') {
660
+ return sendJson(res, 403, {
661
+ error: `${label} 需要「工作区内修改」或「完全权限」`,
662
+ });
663
+ }
664
+ const result =
665
+ shell === 'pwsh'
666
+ ? signalPwshSession({
667
+ sessionId: body.sessionId || body.id,
668
+ signal: body.signal,
669
+ })
670
+ : signalBashSession({
671
+ sessionId: body.sessionId || body.id,
672
+ signal: body.signal,
673
+ });
674
+ return sendJson(res, result.ok ? 200 : 400, result);
675
+ }
676
+
629
677
  if (url === `${prefix}/session/close` && req.method === 'POST') {
630
678
  const body = JSON.parse((await readBody(req)) || '{}');
631
679
  const access = normalizeAccess(body.access);
@@ -735,8 +783,26 @@ export function lhBashPlugin() {
735
783
  if (!jobId) return sendJson(res, 400, { error: 'jobId is required' });
736
784
  const job = jobs.get(jobId);
737
785
  if (!job) return sendJson(res, 404, { error: 'job not found', jobId });
738
- const offset = Math.max(0, Number(body.offset) || 0);
739
786
  const combined = `${job.stdout}${job.stderr ? (job.stdout ? '\n' : '') + job.stderr : ''}`;
787
+ // tail:取末尾 N 字符(与 offset 二选一,优先 tail)
788
+ const tailRaw = Number(body.tail);
789
+ if (Number.isFinite(tailRaw) && tailRaw > 0) {
790
+ const n = Math.min(256_000, Math.floor(tailRaw));
791
+ const start = Math.max(0, combined.length - n);
792
+ const slice = combined.slice(start);
793
+ return sendJson(res, 200, {
794
+ ok: true,
795
+ job: publicJob(job),
796
+ stdout: job.stdout,
797
+ stderr: job.stderr,
798
+ output: slice,
799
+ offset: start,
800
+ nextOffset: combined.length,
801
+ tail: n,
802
+ truncated: job.truncated || start > 0,
803
+ });
804
+ }
805
+ const offset = Math.max(0, Number(body.offset) || 0);
740
806
  const slice = combined.slice(offset);
741
807
  return sendJson(res, 200, {
742
808
  ok: true,
@@ -2,10 +2,13 @@
2
2
  * 本地网页搜索 / 获取代理:仅 `astro dev` 与 lantern-harness 一体服务可用。
3
3
  * 服务端代抓,绕过浏览器 CORS;搜索走 DuckDuckGo HTML。
4
4
  */
5
+ import dns from 'node:dns/promises';
6
+ import { shouldBlockHost, shouldBlockIp } from './web-fetch-policy.mjs';
5
7
 
6
8
  const PREFIX = '/__tb_web';
7
9
  const MAX_FETCH = 400_000;
8
10
  const MAX_TEXT = 24_000;
11
+ const MAX_REDIRECTS = 8;
9
12
  const UA =
10
13
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 LanternHarness/0.1';
11
14
 
@@ -63,17 +66,31 @@ function unwrapDdgHref(href) {
63
66
  return href;
64
67
  }
65
68
 
66
- function isBlockedHost(hostname) {
67
- const h = String(hostname || '').toLowerCase();
68
- if (!h) return true;
69
- if (h === 'localhost' || h.endsWith('.localhost')) return true;
70
- if (h === '127.0.0.1' || h === '0.0.0.0' || h === '::1') return true;
71
- if (/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(h)) return true;
72
- if (h.endsWith('.local') || h.endsWith('.internal')) return true;
73
- return false;
69
+ /**
70
+ * @param {URL} parsed
71
+ * @param {boolean} allowPrivate
72
+ */
73
+ async function assertSafeDestination(parsed, allowPrivate) {
74
+ if (!/^https?:$/i.test(parsed.protocol)) {
75
+ return { error: 'only http/https allowed' };
76
+ }
77
+ if (shouldBlockHost(parsed.hostname, allowPrivate)) {
78
+ return { error: 'blocked host' };
79
+ }
80
+ try {
81
+ const records = await dns.lookup(parsed.hostname, { all: true, verbatim: true });
82
+ for (const r of records) {
83
+ if (shouldBlockIp(r.address, allowPrivate)) {
84
+ return { error: 'blocked host (resolved private)' };
85
+ }
86
+ }
87
+ } catch {
88
+ // DNS 失败时仍按 hostname 规则;lookup 失败留给后续 fetch
89
+ }
90
+ return null;
74
91
  }
75
92
 
76
- async function searchDuckDuckGo(query, maxResults = 8) {
93
+ async function searchDuckDuckGo(query, maxResults = 8, allowPrivate = false) {
77
94
  const q = String(query || '').trim();
78
95
  if (!q) return { results: [], error: 'empty query' };
79
96
  const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`;
@@ -97,13 +114,12 @@ async function searchDuckDuckGo(query, maxResults = 8) {
97
114
  const title = stripTags(m[2]).slice(0, 200);
98
115
  if (!href.startsWith('http') || !title) continue;
99
116
  try {
100
- if (isBlockedHost(new URL(href).hostname)) continue;
117
+ if (shouldBlockHost(new URL(href).hostname, allowPrivate)) continue;
101
118
  } catch {
102
119
  continue;
103
120
  }
104
121
  results.push({ title, url: href });
105
122
  }
106
- // snippet: nearby result__snippet
107
123
  if (results.length) {
108
124
  const snipRe =
109
125
  /<a[^>]*class="[^"]*result__a[^"]*"[^>]*>[\s\S]*?<\/a>[\s\S]*?(?:class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/(?:a|td|div)>)/gi;
@@ -117,53 +133,79 @@ async function searchDuckDuckGo(query, maxResults = 8) {
117
133
  return { results, provider: 'duckduckgo-html' };
118
134
  }
119
135
 
120
- async function fetchPage(rawUrl) {
121
- let parsed;
136
+ /**
137
+ * @param {string} rawUrl
138
+ * @param {boolean} allowPrivate
139
+ */
140
+ export async function fetchPage(rawUrl, allowPrivate = false) {
141
+ let current;
122
142
  try {
123
- parsed = new URL(String(rawUrl || '').trim());
143
+ current = new URL(String(rawUrl || '').trim());
124
144
  } catch {
125
145
  return { error: 'invalid url' };
126
146
  }
127
- if (!/^https?:$/i.test(parsed.protocol)) {
128
- return { error: 'only http/https allowed' };
129
- }
130
- if (isBlockedHost(parsed.hostname)) {
131
- return { error: 'blocked host' };
132
- }
133
- const res = await fetch(parsed.toString(), {
134
- headers: {
135
- 'User-Agent': UA,
136
- Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
137
- },
138
- redirect: 'follow',
139
- signal: AbortSignal.timeout(25000),
140
- });
141
- const ctype = (res.headers.get('content-type') || '').toLowerCase();
142
- const buf = Buffer.from(await res.arrayBuffer());
143
- if (buf.length > MAX_FETCH) {
147
+
148
+ let lastStatus = 0;
149
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
150
+ const blocked = await assertSafeDestination(current, allowPrivate);
151
+ if (blocked) return blocked;
152
+
153
+ const res = await fetch(current.toString(), {
154
+ headers: {
155
+ 'User-Agent': UA,
156
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
157
+ },
158
+ redirect: 'manual',
159
+ signal: AbortSignal.timeout(25000),
160
+ });
161
+ lastStatus = res.status;
162
+
163
+ if (res.status >= 300 && res.status < 400) {
164
+ const loc = res.headers.get('location');
165
+ if (!loc)
166
+ return { error: 'redirect without location', status: res.status, url: current.toString() };
167
+ try {
168
+ current = new URL(loc, current);
169
+ } catch {
170
+ return { error: 'invalid redirect location', status: res.status, url: current.toString() };
171
+ }
172
+ // drain body
173
+ try {
174
+ await res.arrayBuffer();
175
+ } catch {
176
+ // ignore
177
+ }
178
+ continue;
179
+ }
180
+
181
+ const ctype = (res.headers.get('content-type') || '').toLowerCase();
182
+ const buf = Buffer.from(await res.arrayBuffer());
183
+ if (buf.length > MAX_FETCH) {
184
+ return {
185
+ error: `response too large (>${MAX_FETCH} bytes)`,
186
+ status: res.status,
187
+ url: current.toString(),
188
+ };
189
+ }
190
+ const raw = buf.toString('utf8');
191
+ let title = '';
192
+ const tm = raw.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
193
+ if (tm) title = stripTags(tm[1]).slice(0, 200);
194
+ let text = raw;
195
+ if (ctype.includes('html') || /<html[\s>]/i.test(raw)) {
196
+ text = stripTags(raw);
197
+ }
198
+ if (text.length > MAX_TEXT) text = `${text.slice(0, MAX_TEXT)}\n…(truncated)`;
144
199
  return {
145
- error: `response too large (>${MAX_FETCH} bytes)`,
200
+ ok: true,
146
201
  status: res.status,
147
- url: res.url || parsed.toString(),
202
+ url: current.toString(),
203
+ contentType: ctype,
204
+ title,
205
+ text,
148
206
  };
149
207
  }
150
- const raw = buf.toString('utf8');
151
- let title = '';
152
- const tm = raw.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
153
- if (tm) title = stripTags(tm[1]).slice(0, 200);
154
- let text = raw;
155
- if (ctype.includes('html') || /<html[\s>]/i.test(raw)) {
156
- text = stripTags(raw);
157
- }
158
- if (text.length > MAX_TEXT) text = `${text.slice(0, MAX_TEXT)}\n…(truncated)`;
159
- return {
160
- ok: true,
161
- status: res.status,
162
- url: res.url || parsed.toString(),
163
- contentType: ctype,
164
- title,
165
- text,
166
- };
208
+ return { error: 'too many redirects', status: lastStatus, url: current.toString() };
167
209
  }
168
210
 
169
211
  /**
@@ -185,13 +227,15 @@ export function lhWebPlugin() {
185
227
  if (url === `${PREFIX}/search` && req.method === 'POST') {
186
228
  const body = JSON.parse((await readBody(req)) || '{}');
187
229
  const maxResults = Math.min(12, Math.max(1, Number(body.maxResults) || 8));
188
- const data = await searchDuckDuckGo(body.query, maxResults);
230
+ const allowPrivate = body.allowPrivate === true;
231
+ const data = await searchDuckDuckGo(body.query, maxResults, allowPrivate);
189
232
  return sendJson(res, data.error && !data.results?.length ? 502 : 200, data);
190
233
  }
191
234
 
192
235
  if (url === `${PREFIX}/fetch` && req.method === 'POST') {
193
236
  const body = JSON.parse((await readBody(req)) || '{}');
194
- const data = await fetchPage(body.url);
237
+ const allowPrivate = body.allowPrivate === true;
238
+ const data = await fetchPage(body.url, allowPrivate);
195
239
  return sendJson(res, data.error && !data.ok ? 400 : 200, data);
196
240
  }
197
241
 
@@ -203,3 +247,10 @@ export function lhWebPlugin() {
203
247
  },
204
248
  };
205
249
  }
250
+
251
+ export {
252
+ shouldBlockHost,
253
+ shouldBlockIp,
254
+ isPrivateHostname,
255
+ isPrivateIp,
256
+ } from './web-fetch-policy.mjs';