lantern-harness 0.1.22 → 0.1.24

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 (130) hide show
  1. package/CHANGELOG.md +47 -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.astro_astro_type_script_index_0_lang.DHRjA0au.js +2 -0
  18. package/dist/_astro/Base.nGl8De0W.css +1 -0
  19. package/dist/_astro/{CaseExecBoard.Dnb8oP5i.js → CaseExecBoard.Xd7KUpkU.js} +1 -1
  20. package/dist/_astro/{CaseGenerateApp.ci_JowEk.js → CaseGenerateApp.BgIi4YGn.js} +2 -2
  21. package/dist/_astro/CasesLibrary.B2VCAoTt.js +21 -0
  22. package/dist/_astro/ChatApp.CeSatNSf.js +220 -0
  23. package/dist/_astro/ConfirmDialog.D5qXeML0.js +1 -0
  24. package/dist/_astro/{DashboardBoard.D8-oufgg.js → DashboardBoard.CmxqpmzI.js} +2 -2
  25. package/dist/_astro/DocsFileBrowser.Diq5zuSt.js +1 -0
  26. package/dist/_astro/{DocsPager.B9VhI6E3.js → DocsPager.WMztSW4O.js} +1 -1
  27. package/dist/_astro/{KnowledgeLibrary.DGhU2p3S.js → KnowledgeLibrary.CYutSepl.js} +1 -1
  28. package/dist/_astro/MultiSelectDropdown.BHxW9XLR.js +1 -0
  29. package/dist/_astro/NamePromptDialog.5XFIvdqv.js +1 -0
  30. package/dist/_astro/{NavLibraries.RH3Sinuh.js → NavLibraries.BybmHnXn.js} +1 -1
  31. package/dist/_astro/{PluginsPage.DjeMQX3i.js → PluginsPage.CgcXB7Ap.js} +2 -2
  32. package/dist/_astro/PluginsPage.pgN80K8r.js +1 -0
  33. package/dist/_astro/{PmBugsBoard.BnnaNP1y.js → PmBugsBoard.Ceyt3pp6.js} +1 -1
  34. package/dist/_astro/{PmIterationsBoard.phiyhQVA.js → PmIterationsBoard.Dwsntvw6.js} +1 -1
  35. package/dist/_astro/{PmProjectDetail.C8kRX5lu.js → PmProjectDetail.5tybGC46.js} +1 -1
  36. package/dist/_astro/{PmProjectsBoard.CFApEGPo.js → PmProjectsBoard.X2LZfFff.js} +1 -1
  37. package/dist/_astro/{PmRequirementsBoard.DR9egcgA.js → PmRequirementsBoard.CXaGeFl9.js} +1 -1
  38. package/dist/_astro/PmRequirementsBoard.CYbicBqS.js +1 -0
  39. package/dist/_astro/{PmShared.BrBicDMN.js → PmShared.Bzn6AGsN.js} +1 -1
  40. package/dist/_astro/PromptMountDialog.CpTT6L0a.js +62 -0
  41. package/dist/_astro/{PromptsLibrary.CbGja6mq.js → PromptsLibrary.DydrgeIw.js} +1 -1
  42. package/dist/_astro/{ReportsPage.CYZtpeiv.js → ReportsPage.BRVCnzL-.js} +1 -1
  43. package/dist/_astro/ReqAnalysisBoard.BCq_OoRo.js +39 -0
  44. package/dist/_astro/RequirementsLibrary.DtbFESBh.js +1 -0
  45. package/dist/_astro/SearchableSelect.D3ODywC4.js +1 -0
  46. package/dist/_astro/SettingsDialog.DtEJLxtx.js +1 -0
  47. package/dist/_astro/SpaceSwitcher.Cdveup1T.js +7 -0
  48. package/dist/_astro/{TasksBoard.D0HwS5hd.js → TasksBoard.rwdPWLAh.js} +1 -1
  49. package/dist/_astro/{TemplatesLibrary.CVv5Ef30.js → TemplatesLibrary.Bg-MFL57.js} +1 -1
  50. package/dist/_astro/{TestStatsBoard._qNcNorG.js → TestStatsBoard.eiMbNGpn.js} +1 -1
  51. package/dist/_astro/{TodosBoard.CF5wbJy7.js → TodosBoard.CrZMl6Ei.js} +1 -1
  52. package/dist/_astro/{UiAutoBoard.nrtcQJDl.js → UiAutoBoard.CLi9vmuE.js} +3 -3
  53. package/dist/_astro/{app-config.CF1xVPmo.js → app-config.DAIyT--R.js} +1 -1
  54. package/dist/_astro/app-version.XPYyWuno.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.BbI2iGo9.js +21 -0
  58. package/dist/_astro/case-review.D1E3ldss.js +3 -0
  59. package/dist/_astro/{case-types.DS1EQ5yP.js → case-types.B6MLX3iE.js} +1 -1
  60. package/dist/_astro/docs-format.BlGh-XA_.js +1 -0
  61. package/dist/_astro/{hydrate-cache.CmC22o_H.js → hydrate-cache.C0F0L04c.js} +1 -1
  62. package/dist/_astro/i18n.ele1lM9e.js +7 -0
  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.E_go1fvj.js → story-review.BRcUdixS.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 +48 -5
  75. package/dist/docs/install/index.html +48 -4
  76. package/dist/docs/manual/index.html +41 -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 +36 -27
  98. package/lh-plugins/case-review-prompt.mjs +12 -106
  99. package/lh-plugins/lh-case-review.mjs +3 -0
  100. package/lh-plugins/lh-mcp.mjs +79 -0
  101. package/lh-plugins/lh-reports.mjs +11 -28
  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.I--fR8aT.css +0 -1
  108. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.BQtZbum2.js +0 -1
  109. package/dist/_astro/CasesLibrary.DfuTkbJN.js +0 -21
  110. package/dist/_astro/ChatApp.CAgrwilW.js +0 -214
  111. package/dist/_astro/ConfirmDialog.CsMwWevK.js +0 -1
  112. package/dist/_astro/DocsFileBrowser.CTICuWFf.js +0 -1
  113. package/dist/_astro/NamePromptDialog.CS1pTTVl.js +0 -1
  114. package/dist/_astro/PluginsPage.C9vaY-lo.js +0 -1
  115. package/dist/_astro/PmRequirementsBoard.B-AI9iZX.js +0 -1
  116. package/dist/_astro/PromptMountDialog.YH2odDZx.js +0 -58
  117. package/dist/_astro/ReqAnalysisBoard.By08xNFf.js +0 -29
  118. package/dist/_astro/RequirementsLibrary.BSDgdppH.js +0 -1
  119. package/dist/_astro/SearchableSelect.Cbb8jMnP.js +0 -1
  120. package/dist/_astro/SettingsDialog.DgpH_BVN.js +0 -1
  121. package/dist/_astro/SpaceSwitcher.Dw9LjKiJ.js +0 -7
  122. package/dist/_astro/app-version.5UudQEyk.js +0 -1
  123. package/dist/_astro/bash-tools.CPS0ZiKi.js +0 -25
  124. package/dist/_astro/case-fields.h0roo2br.js +0 -1
  125. package/dist/_astro/case-gen-run.D8DGX0mr.js +0 -19
  126. package/dist/_astro/case-review.C1hQRbQ2.js +0 -3
  127. package/dist/_astro/i18n.CjqQGCAI.js +0 -7
  128. package/dist/_astro/open-docs-in-session.Cj0J2-XT.js +0 -1
  129. package/dist/_astro/req-analysis.dhgy4p2f.js +0 -14
  130. package/dist/_astro/settings.B1yetppp.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # 版本日志
2
2
 
3
+ ## [0.1.24] - 2026-10-25
4
+
5
+ 平台对照 DSH 的三波次 MVP:会话 Fork / 条件工具 / 子代理与无头策略对齐,MCP 与终端控制补齐,Fetch 私网与模型能力、计划审批投影落地。
6
+
7
+ ### 新增
8
+
9
+ - **独立会话 Fork**:侧栏「分叉会话」复制消息为新会话,不写 parent、不带 subagent 语义(与 `fork_subagent` 区分)
10
+ - **条件工具组装**:`buildChatTools` 按访问档与插件 caps 注入工具;关插件则对应工具消失
11
+ - **子代理控制**:`subagent_list` / `status` / `await` / `abort` / `message`(steer),按聊天 `sessionId` 隔离
12
+ - **无头策略叠层**:`agent-policy` 统一 ask / rpc / acp 的 access 与 toolProfile;ACP `tools` 支持字符串档位
13
+ - **MCP 真客户端**:空间 `.lantern/local/mcp.json`(stdio / HTTP)→ 工具名 `mcp__服务器__工具`
14
+ - **持久终端 write / signal**:`bash_session_*` / `pwsh_session_*` 可写 stdin、发 SIGINT 等信号
15
+ - **Fetch 私网开关**:通用设置「允许抓取私网地址」;默认拦截 localhost / 私网,含跳转与 DNS 校验
16
+ - **模型能力声明**:提供商可配上下文窗口 / 是否支持工具 / 是否支持视觉,并门闩运行时
17
+ - **工具执行超时**:`tool-run-policy` 为浏览器与服务端回合包默认超时
18
+ - **计划审批投影**:`planPhase` / 待批方案写入会话,刷新或切回可恢复
19
+ - **job_output tail**:可取后台任务输出末尾 N 字符
20
+ - **内置插件「规划中」**:设置页默认隐藏规划中项,可勾选显示
21
+
22
+ ### 修复
23
+
24
+ - **确认弹层关闭缩影**:关闭动画期间冻结标题/正文,避免二次确认框内容被清空后闪一下
25
+
26
+ ### 优化
27
+
28
+ - **操作 / 安装 / 会话 / 全局插件手册**:同步 MCP、私网 Fetch、计划投影、终端 write/signal、无头策略对照与内置插件展示口径
29
+
30
+ ## [0.1.23] - 2026-10-24
31
+
32
+ 对话里表格可读、工作汇报能带上测试数据、需求库与仪表盘几处体验收口:粘回预览不再撑爆、跳转工作台不再滚回旧卡片,休息日也不再倒计时下班。
33
+
34
+ ### 新增
35
+
36
+ - **工作汇报带入测试数据**:生成日报 / 周报 / 月报时,按区间把开启中的待办、任务、**测试统计**、**用例执行统计**拼进「本期工作数据」随消息发给模型(气泡仍只显示短指令);种子提示词「数据来源」同步写上这两类
37
+ - **需求文档库上传时间**:文件列表在大小旁显示上传时间(`ctime`,缺省 `mtime`),并按上传时间新→旧排序
38
+
39
+ ### 修复
40
+
41
+ - **跳转工作台不再滚到旧入库卡**:「去工作台写回 / 修改」不再带 focus,避免滚到绑定会话中段;滚底等 markdown 撑开后再跟
42
+ - **仪表盘「距离下班」休息日**:周末 / 法定节假日(调休补班除外)四格为 `00`,说明改为「今天休息,不上班」
43
+ - **用例表格「已修改」**:规则判定列只显示「已修改 xx」,不再叠「待修改 xx」
44
+
45
+ ### 优化
46
+
47
+ - **对话 markdown 表格**:单元格最多 4 行省略,悬停气泡看全文(保留换行),表格可横向滚动
48
+ - **需求文档库文件夹名**:左侧树与子文件夹列表名称截断时悬停出气泡
49
+
3
50
  ## [0.1.22] - 2026-10-24
4
51
 
5
52
  用例备份与评审「已修改」闭环、需求分析来源排序,以及项目管理三板的表格体验:写回/修改后不再反复被模型重挑,列表与看板更好拖、更好找。
@@ -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';