@befe/vault-system 0.1.18 → 0.1.19
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/INSTALL.md +15 -1
- package/SKILL.md +6 -1
- package/guides/guide_261025_vault/346/234/215/345/212/241/350/277/220/347/273/264/344/270/216/345/256/236/347/216/260/347/273/206/350/212/202.md +99 -0
- package/guides//346/214/207/345/215/227_/344/273/243/347/220/206/345/255/220/346/234/215/345/212/241.261123_562dwm8x_ctag.md +164 -0
- package/guides//346/214/207/345/215/227_/346/234/254/345/234/260demo/350/267/257/347/224/261.261121_pwgabx_ctag.md +119 -0
- package/package.json +2 -1
- package/src/core/comate-rules.ts +9 -15
- package/src/core/config.ts +4 -5
- package/src/core/migrate-legacy-cache.ts +4 -5
- package/src/core/personal-config.ts +29 -0
- package/src/core/quick-demo.ts +10 -28
- package/src/core/scan.ts +14 -0
- package/src/core/workspace.ts +38 -6
- package/src/core/wskey.ts +2 -3
- package/src/server/app.ts +92 -3
- package/src/server/index.ts +10 -1
- package/src/server/proxy.ts +596 -0
- package/web/dist/assets/{abnfDiagram-WEYOIA3C-rZaG2iSs.js → abnfDiagram-WEYOIA3C-CzLGzmT0.js} +1 -1
- package/web/dist/assets/{arc-D-YRXgrg.js → arc-BK3RYILK.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZHVYKT53-BBkgnnhu.js → architectureDiagram-ZHVYKT53-CZCt9ons.js} +1 -1
- package/web/dist/assets/{blockDiagram-RJAE7QA3-D_UPuzcL.js → blockDiagram-RJAE7QA3-AZYnyj-a.js} +1 -1
- package/web/dist/assets/{c4Diagram-XDPPPE54-rRkxxACp.js → c4Diagram-XDPPPE54-BqWPXEuV.js} +1 -1
- package/web/dist/assets/channel-BFVjYcST.js +1 -0
- package/web/dist/assets/{chunk-2E7WHVMD-BRH_4_am.js → chunk-2E7WHVMD-CvnX45iC.js} +1 -1
- package/web/dist/assets/{chunk-2Q5K7J3B-Ca9Nzrlh.js → chunk-2Q5K7J3B-BbXAdjod.js} +1 -1
- package/web/dist/assets/{chunk-4EMNKR2T-EeIUtWEL.js → chunk-4EMNKR2T-CmOwVdTA.js} +1 -1
- package/web/dist/assets/{chunk-55XCU76K-BSK00in2.js → chunk-55XCU76K-HfX5pLsY.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-C861XhrM.js → chunk-5VM5RSS4-CBV3FN1q.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-v2zmmZ8M.js → chunk-JWPE2WC7-av5KekLY.js} +1 -1
- package/web/dist/assets/{chunk-VQ5W62QI-D66wyirI.js → chunk-VQ5W62QI-BDJg5LpC.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-EVyGdP8d.js → chunk-XXDRQBXY-B03VFtHa.js} +1 -1
- package/web/dist/assets/{chunk-ZCHMQSOR-DXtpKq5T.js → chunk-ZCHMQSOR-B9BO6gTW.js} +2 -2
- package/web/dist/assets/{classDiagram-v2-4MYWR3UA-Cr43uJqI.js → classDiagram-v2-4MYWR3UA-B-CRFug7.js} +1 -1
- package/web/dist/assets/{cose-bilkent-JH36ORCC-Cuuq6WQQ.js → cose-bilkent-JH36ORCC-D11vOSVS.js} +1 -1
- package/web/dist/assets/{cynefin-EF2NZ3EQ-C3iyCS68.js → cynefin-EF2NZ3EQ-84DLvAE7.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-WF24UDRP-bKF_V24p.js → cynefinDiagram-WF24UDRP-iKQnDfvD.js} +1 -1
- package/web/dist/assets/{dagre-NK4GIZVX-BP6HiUix.js → dagre-NK4GIZVX-CgPXz8b2.js} +1 -1
- package/web/dist/assets/{diagram-CBK3MWTC--Bdnc_hg.js → diagram-CBK3MWTC-n4oz7nm5.js} +1 -1
- package/web/dist/assets/{diagram-I5XIIV2D-Cb_w9kpf.js → diagram-I5XIIV2D-CqfBbk_d.js} +1 -1
- package/web/dist/assets/{diagram-ODIL2UCW-dTgly2Fz.js → diagram-ODIL2UCW-Dyae5pld.js} +1 -1
- package/web/dist/assets/{diagram-PFBEJUXE-BjGtD0ca.js → diagram-PFBEJUXE-B9NWQ2Ya.js} +1 -1
- package/web/dist/assets/{diagram-RJA3I4VV-7yxAtb-a.js → diagram-RJA3I4VV-C2iQ4iPN.js} +1 -1
- package/web/dist/assets/{diagram-TYUNFSNR-CdDNua7n.js → diagram-TYUNFSNR-CNZ0oD-f.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-V4P3TTPT-BNdBmqlo.js → ebnfDiagram-V4P3TTPT-C-10hsPp.js} +1 -1
- package/web/dist/assets/{elk-QONTBCTQ-CmnC5D_R.js → elk-QONTBCTQ-CIERxcyg.js} +1 -1
- package/web/dist/assets/{erDiagram-KYQIGQAA-DbvWu-TF.js → erDiagram-KYQIGQAA-CBh1xB1R.js} +1 -1
- package/web/dist/assets/{flowDiagram-IUGLLWBU-ElkzAMUI.js → flowDiagram-IUGLLWBU-CUARvlqo.js} +1 -1
- package/web/dist/assets/{ganttDiagram-R7GPNTJY-CT2YIzjy.js → ganttDiagram-R7GPNTJY-C6pkCQxE.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-PDYL7XHY-DAXq_4wb.js → gitGraphDiagram-PDYL7XHY-cy9Zli1k.js} +1 -1
- package/web/dist/assets/{index-CvSLBFhG.js → index-o91WzriM.js} +39 -39
- package/web/dist/assets/{infoDiagram-MVDRKAX5-DRP-H8zh.js → infoDiagram-MVDRKAX5-Csi2VBqG.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-HPEHV2GE-BNoK_XsT.js → ishikawaDiagram-HPEHV2GE-yrldh--h.js} +1 -1
- package/web/dist/assets/{journeyDiagram-BOSHW7O7-pkpw5r9x.js → journeyDiagram-BOSHW7O7-D7gc8Qs9.js} +1 -1
- package/web/dist/assets/{kanban-definition-FNSA4HC5-Dt6SzUmC.js → kanban-definition-FNSA4HC5-CwtKtjMT.js} +1 -1
- package/web/dist/assets/{linear-FQQ9tQr_.js → linear-DLZLXP9t.js} +1 -1
- package/web/dist/assets/{mermaid.core-BZ6wQkn-.js → mermaid.core-BxPAQxuk.js} +4 -4
- package/web/dist/assets/{mindmap-definition-6OY57UG3-Bb2sk6RX.js → mindmap-definition-6OY57UG3-Bm3VJwiA.js} +1 -1
- package/web/dist/assets/{pegDiagram-ECIUJNBX-CQKk04_1.js → pegDiagram-ECIUJNBX-D2wsYqrC.js} +1 -1
- package/web/dist/assets/{pieDiagram-GNMPY74T-BfKw-loG.js → pieDiagram-GNMPY74T-vRGDHvet.js} +1 -1
- package/web/dist/assets/{quadrantDiagram-D57K4MC3-CuWo9HYa.js → quadrantDiagram-D57K4MC3-DmMfnVYF.js} +1 -1
- package/web/dist/assets/{railroadDiagram-Y72NRBL7-Di4q_SJ_.js → railroadDiagram-Y72NRBL7-DC-M56xA.js} +1 -1
- package/web/dist/assets/{requirementDiagram-EQYSW5RA-DC4GU4Pk.js → requirementDiagram-EQYSW5RA-DWqKz947.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-SY24JHO5-_fgVuzHE.js → sankeyDiagram-SY24JHO5-CrTrGYmU.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-BLEHNHQU-Bqlr7yoo.js → sequenceDiagram-BLEHNHQU-Bbi9VKjX.js} +1 -1
- package/web/dist/assets/{sizeCapture-INFHLROL-CbbBAQPu.js → sizeCapture-INFHLROL-BO5ZRCr_.js} +1 -1
- package/web/dist/assets/{stateDiagram-v2-A6IESKWZ-DoMyztsn.js → stateDiagram-v2-A6IESKWZ-C-zEWAgO.js} +1 -1
- package/web/dist/assets/{swimlanes-B3ENRKFQ-BvuDLV2j.js → swimlanes-B3ENRKFQ-DxlXRFLi.js} +1 -1
- package/web/dist/assets/swimlanesDiagram-AYQRV4AK-9cNtvfH9.js +8 -0
- package/web/dist/assets/{timeline-definition-JXYKGLGB-Bvrh9DNs.js → timeline-definition-JXYKGLGB-BlBJNxZI.js} +1 -1
- package/web/dist/assets/{usecaseDiagram-WPOLBNNX-DPY4EcsJ.js → usecaseDiagram-WPOLBNNX-Du1rBFcx.js} +1 -1
- package/web/dist/assets/{vennDiagram-Q3Y3IDCW-BFo8so0I.js → vennDiagram-Q3Y3IDCW-V_B-39x6.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-IVAIDKWA-DYzIhyA5.js → wardleyDiagram-IVAIDKWA-CRwm7D-C.js} +1 -1
- package/web/dist/assets/{xychartDiagram-4URNHDU4-l_k66Yd_.js → xychartDiagram-4URNHDU4-D1xfvzRY.js} +1 -1
- package/web/dist/index.html +1 -1
- package/web/dist/assets/channel-CX2cpODM.js +0 -1
- package/web/dist/assets/swimlanesDiagram-AYQRV4AK-Dxt3sSM3.js +0 -8
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* proxy.ts — `/proxy/{uuap}/{slug}/*` 通用反向代理背后的逻辑(不依赖 Hono)。
|
|
3
|
+
*
|
|
4
|
+
* 口径见 ref#question_playground配置内容.261123_m8i68faw_ctag.(配置与地址)、
|
|
5
|
+
* ref#question_playground条目标题与启动提示.261123_7m99h4e5_ctag.(title 与 guide)、
|
|
6
|
+
* ref#question_兜底页.261123_uodsnjwx_ctag.(兜底页)、ref#question_启动prompt.261123_evgzpjwk_ctag.(prompt):
|
|
7
|
+
* - 配置:`{WK}/.vault-service/config/{uuap}/proxy.yaml`,`version: 1` + `proxies[]`
|
|
8
|
+
* 每条 ctag(完整 `def#…_ctag.`)、port(必填,1–65535 整数,无默认值)、title / guide(可选字符串)
|
|
9
|
+
* - slug = ctag 去掉 `def#` 与末尾点;条目写坏只影响它自己的 slug;重复 ctag 只认第一条并记为问题
|
|
10
|
+
* - 地址里的 uuap 必须等于当前身份,否则 404(与 quick-demo 一样的「假隔离」)
|
|
11
|
+
* - 上游 = `http://127.0.0.1:{port}`,路径(含 /proxy/{uuap}/{slug}/ 前缀)与查询串原样转发,上游靠 base 对齐
|
|
12
|
+
* - 请求头走白名单,host 与 hop-by-hop 一律不带;回包去掉 hop-by-hop 与 content-encoding / content-length,
|
|
13
|
+
* body 以流透传
|
|
14
|
+
* - 上游连不上 502、20 秒没拿到响应头 504,都回同一张兜底页(状态码照旧)
|
|
15
|
+
* 20 秒是给 Vite 首次依赖预构建留的余量
|
|
16
|
+
* - HMR 的 websocket 不转发:要热更新就直接开上游端口调试
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readFileSync } from 'node:fs';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { DESCR, HASH_MATCH } from '../core/ctag-shape.js';
|
|
22
|
+
import { isValidQuickDemoSegment, personalConfigDir } from '../core/personal-config.js';
|
|
23
|
+
import { resolveUuap } from '../core/workspace.js';
|
|
24
|
+
|
|
25
|
+
/** 个人配置文件名(在 `.vault-service/config/{uuap}/` 下) */
|
|
26
|
+
export const PROXY_CONFIG_FILE = 'proxy.yaml';
|
|
27
|
+
|
|
28
|
+
/** 配置与身份复用时长(毫秒):2 秒内复用上次读到的结果,超时下一次访问重新读盘 */
|
|
29
|
+
export const PROXY_CONFIG_TTL_MS = 2000;
|
|
30
|
+
|
|
31
|
+
/** 等上游响应头的上限(毫秒);超时回 504 兜底页 */
|
|
32
|
+
export const PROXY_TIMEOUT_MS = 20000;
|
|
33
|
+
|
|
34
|
+
/** prompt 里 guide 原文的上限(字符数);超出截断并提示去 proxy.yaml 看全文 */
|
|
35
|
+
export const PROXY_GUIDE_MAX_CHARS = 500;
|
|
36
|
+
|
|
37
|
+
/** 报错里展示的配置相对路径(相对工作区根) */
|
|
38
|
+
export function proxyDisplayFile(uuap: string): string {
|
|
39
|
+
return `.vault-service/config/${uuap}/${PROXY_CONFIG_FILE}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 条目 ctag:整串锚定,必须 `def#` 开头、末尾点必须有;descr / hash 片段复用 ctag-shape */
|
|
43
|
+
const PROXY_CTAG_RE = new RegExp(`^def#${DESCR}\\.\\d{6}_${HASH_MATCH}_ctag\\.$`);
|
|
44
|
+
|
|
45
|
+
/** 地址段 slug:ctag 去掉 `def#` 与末尾点之后的形态 */
|
|
46
|
+
const PROXY_SLUG_RE = new RegExp(`^${DESCR}\\.\\d{6}_${HASH_MATCH}_ctag$`);
|
|
47
|
+
|
|
48
|
+
/** slug 里去掉 `.YYMMDD_hash_ctag` 之后剩下的 descr */
|
|
49
|
+
const PROXY_SLUG_TAIL_RE = new RegExp(`\\.\\d{6}_${HASH_MATCH}_ctag$`);
|
|
50
|
+
|
|
51
|
+
/** 由配置里的完整 ctag 推出地址段 slug;形态不对返回 null */
|
|
52
|
+
export function proxySlug(ctag: string): string | null {
|
|
53
|
+
return PROXY_CTAG_RE.test(ctag) ? ctag.slice('def#'.length, -1) : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 地址段(已解码)是不是 slug 形态;不是的请求不可能命中任何条目 */
|
|
57
|
+
export function isProxySlug(s: string): boolean {
|
|
58
|
+
return PROXY_SLUG_RE.test(s);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** slug 里的 descr(没写 title 时做标题);descr 为空就用 slug 整串 */
|
|
62
|
+
export function proxySlugDescr(slug: string): string {
|
|
63
|
+
return slug.replace(PROXY_SLUG_TAIL_RE, '') || slug;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 某个身份的配置文件绝对路径;uuap 不合规返回 null */
|
|
67
|
+
export function proxyConfigPath(wk: string, uuap: string): string | null {
|
|
68
|
+
const dir = personalConfigDir(wk, uuap);
|
|
69
|
+
return dir ? join(dir, PROXY_CONFIG_FILE) : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ───────────────────────── 配置解析 ─────────────────────────
|
|
73
|
+
|
|
74
|
+
/** 一条有效的代理条目 */
|
|
75
|
+
export interface ProxyEntry {
|
|
76
|
+
/** 配置里的完整 ctag(`def#…_ctag.`) */
|
|
77
|
+
ctag: string;
|
|
78
|
+
/** 地址段:ctag 去掉 `def#` 与末尾点 */
|
|
79
|
+
slug: string;
|
|
80
|
+
/** 上游开发服务端口(只转发到 127.0.0.1) */
|
|
81
|
+
port: number;
|
|
82
|
+
/** 友好标题(可选);没写时取 ctag 的 descr */
|
|
83
|
+
title?: string;
|
|
84
|
+
/** 启动指引原文(可选) */
|
|
85
|
+
guide?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 配置里的一处问题 */
|
|
89
|
+
export interface ProxyProblem {
|
|
90
|
+
field: string;
|
|
91
|
+
message: string;
|
|
92
|
+
/** 问题所属条目的 slug(条目 ctag 本身合法时才有),用来判断「这次请求的 slug 是不是被写坏了」 */
|
|
93
|
+
slug?: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type ProxyConfigResult =
|
|
97
|
+
| { state: 'missing'; file: string }
|
|
98
|
+
/** 整份文件读不了:YAML 语法错 / 顶层结构不符 / version 不对 / 文件不可读 */
|
|
99
|
+
| { state: 'broken'; file: string; problems: ProxyProblem[] }
|
|
100
|
+
/** 文件可用:entries 是有效条目;problems 是个别写坏(含重复 ctag)的条目,不影响其他 slug */
|
|
101
|
+
| { state: 'ok'; file: string; entries: Map<string, ProxyEntry>; problems: ProxyProblem[] };
|
|
102
|
+
|
|
103
|
+
type YamlParse = (text: string) => unknown;
|
|
104
|
+
|
|
105
|
+
/** 默认 YAML 解析:Bun.YAML.parse(服务跑在 bun 上,engines >=1.4.2),不新增依赖 */
|
|
106
|
+
const bunYamlParse: YamlParse = (text) => {
|
|
107
|
+
const yaml = (globalThis as { Bun?: { YAML?: { parse?: YamlParse } } }).Bun?.YAML;
|
|
108
|
+
if (!yaml?.parse) throw new Error('当前运行环境没有 Bun.YAML.parse(需要 bun >= 1.4.2)');
|
|
109
|
+
return yaml.parse(text);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
113
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 端口:1–65535 的整数才算有效 */
|
|
117
|
+
export function isProxyPort(raw: unknown): raw is number {
|
|
118
|
+
return typeof raw === 'number' && Number.isInteger(raw) && raw >= 1 && raw <= 65535;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 可选字符串字段:没写 / null / 空白串 → 'absent';非字符串 → 'bad';其余原样 */
|
|
122
|
+
function optionalString(raw: unknown): { kind: 'absent' } | { kind: 'bad' } | { kind: 'ok'; value: string } {
|
|
123
|
+
if (raw === undefined || raw === null) return { kind: 'absent' };
|
|
124
|
+
if (typeof raw !== 'string') return { kind: 'bad' };
|
|
125
|
+
return raw.trim() === '' ? { kind: 'absent' } : { kind: 'ok', value: raw };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 解析配置文本(纯函数)。结构:
|
|
130
|
+
* version: 1
|
|
131
|
+
* proxies:
|
|
132
|
+
* - ctag: "def#lino_playground.261123_xxxxxxxx_ctag."
|
|
133
|
+
* port: 5199
|
|
134
|
+
* title: lino playground # 可选
|
|
135
|
+
* guide: "启动方式见 ref#…" # 可选
|
|
136
|
+
* 个别条目写坏(缺 ctag、ctag 形态不对、port 不合规、title / guide 不是字符串、ctag 重复)只影响它自己的 slug;
|
|
137
|
+
* 整体写坏(语法 / 顶层 / version / proxies 类型)算 broken。
|
|
138
|
+
*/
|
|
139
|
+
export function parseProxyConfig(text: string, file: string, parseYaml: YamlParse = bunYamlParse): ProxyConfigResult {
|
|
140
|
+
const broken = (problems: ProxyProblem[]): ProxyConfigResult => ({ state: 'broken', file, problems });
|
|
141
|
+
let doc: unknown;
|
|
142
|
+
try {
|
|
143
|
+
doc = parseYaml(text);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
return broken([{ field: '(YAML 语法)', message: `YAML 解析失败:${String((e as Error).message ?? e)}` }]);
|
|
146
|
+
}
|
|
147
|
+
if (!isRecord(doc)) {
|
|
148
|
+
return broken([{ field: '(顶层)', message: '顶层必须是映射(含 version 与 proxies)' }]);
|
|
149
|
+
}
|
|
150
|
+
if (doc.version !== 1) {
|
|
151
|
+
const message = doc.version === undefined ? '缺少 version(当前只支持 version: 1)' : 'version 只支持 1';
|
|
152
|
+
return broken([{ field: 'version', message }]);
|
|
153
|
+
}
|
|
154
|
+
if (!('proxies' in doc)) return broken([{ field: 'proxies', message: '缺少 proxies 列表' }]);
|
|
155
|
+
const list = doc.proxies;
|
|
156
|
+
const entries = new Map<string, ProxyEntry>();
|
|
157
|
+
const problems: ProxyProblem[] = [];
|
|
158
|
+
if (list === null || list === undefined) return { state: 'ok', file, entries, problems }; // `proxies:` 留空视为没有条目
|
|
159
|
+
if (!Array.isArray(list)) {
|
|
160
|
+
return broken([{ field: 'proxies', message: 'proxies 必须是列表(每条含 ctag 与 port)' }]);
|
|
161
|
+
}
|
|
162
|
+
const seen = new Set<string>(); // 每个 slug 只认第一次出现的那条,不论它自己是否写坏
|
|
163
|
+
list.forEach((item, i) => {
|
|
164
|
+
if (!isRecord(item)) {
|
|
165
|
+
problems.push({ field: `proxies[${i}]`, message: '条目必须是含 ctag 与 port 的映射' });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const rawCtag = item.ctag;
|
|
169
|
+
const slug = typeof rawCtag === 'string' ? proxySlug(rawCtag) : null;
|
|
170
|
+
if (!slug) {
|
|
171
|
+
const message =
|
|
172
|
+
rawCtag === undefined || rawCtag === null
|
|
173
|
+
? '缺少 ctag'
|
|
174
|
+
: typeof rawCtag !== 'string'
|
|
175
|
+
? 'ctag 必须是字符串'
|
|
176
|
+
: 'ctag 必须是完整的 def#<descr>.<YYMMDD>_<hash>_ctag.(def# 开头、末尾带点)';
|
|
177
|
+
problems.push({ field: `proxies[${i}].ctag`, message });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (seen.has(slug)) {
|
|
181
|
+
problems.push({ field: `proxies[${i}].ctag`, message: 'ctag 与前面的条目重复,只认第一条', slug });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
seen.add(slug);
|
|
185
|
+
const bad = (field: string, message: string) =>
|
|
186
|
+
void problems.push({ field: `proxies[${i}].${field}`, message, slug });
|
|
187
|
+
if (item.port === undefined || item.port === null) return bad('port', '缺少 port(1 到 65535 的整数,没有默认值)');
|
|
188
|
+
if (!isProxyPort(item.port)) return bad('port', 'port 必须是 1 到 65535 的整数');
|
|
189
|
+
const title = optionalString(item.title);
|
|
190
|
+
if (title.kind === 'bad') return bad('title', 'title 必须是字符串');
|
|
191
|
+
const guide = optionalString(item.guide);
|
|
192
|
+
if (guide.kind === 'bad') return bad('guide', 'guide 必须是字符串');
|
|
193
|
+
const entry: ProxyEntry = { ctag: rawCtag as string, slug, port: item.port };
|
|
194
|
+
if (title.kind === 'ok') entry.title = title.value;
|
|
195
|
+
if (guide.kind === 'ok') entry.guide = guide.value;
|
|
196
|
+
entries.set(slug, entry);
|
|
197
|
+
});
|
|
198
|
+
return { state: 'ok', file, entries, problems };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 读盘并解析(不带缓存) */
|
|
202
|
+
export function readProxyConfig(file: string, parseYaml?: YamlParse): ProxyConfigResult {
|
|
203
|
+
let text: string;
|
|
204
|
+
try {
|
|
205
|
+
text = readFileSync(file, 'utf8');
|
|
206
|
+
} catch (e) {
|
|
207
|
+
const code = (e as NodeJS.ErrnoException).code;
|
|
208
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') return { state: 'missing', file };
|
|
209
|
+
return { state: 'broken', file, problems: [{ field: '(文件)', message: `配置文件读取失败:${code ?? String(e)}` }] };
|
|
210
|
+
}
|
|
211
|
+
return parseProxyConfig(text, file, parseYaml);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export interface ProxyConfigLoader {
|
|
215
|
+
/** 读配置:ttl 内复用上次结果(含「文件不存在」「写坏」),超时重读 */
|
|
216
|
+
load(file: string): ProxyConfigResult;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export interface ProxyConfigLoaderOptions {
|
|
220
|
+
/** 时钟(毫秒),默认 Date.now;测试注入用 */
|
|
221
|
+
now?: () => number;
|
|
222
|
+
ttlMs?: number;
|
|
223
|
+
parseYaml?: YamlParse;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function createProxyConfigLoader(opts: ProxyConfigLoaderOptions = {}): ProxyConfigLoader {
|
|
227
|
+
const now = opts.now ?? Date.now;
|
|
228
|
+
const ttl = opts.ttlMs ?? PROXY_CONFIG_TTL_MS;
|
|
229
|
+
const cache = new Map<string, { at: number; result: ProxyConfigResult }>();
|
|
230
|
+
return {
|
|
231
|
+
load(file) {
|
|
232
|
+
const t = now();
|
|
233
|
+
const hit = cache.get(file);
|
|
234
|
+
// t < hit.at:时钟被回拨时不复用,宁可重读
|
|
235
|
+
if (hit && t >= hit.at && t - hit.at < ttl) return hit.result;
|
|
236
|
+
const result = readProxyConfig(file, opts.parseYaml);
|
|
237
|
+
cache.set(file, { at: t, result });
|
|
238
|
+
return result;
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export type ProxyLookup =
|
|
244
|
+
| { kind: 'found'; entry: ProxyEntry }
|
|
245
|
+
/** 404:没配置 / 没有条目 / slug 不存在。slugs 只给地址段 */
|
|
246
|
+
| { kind: 'none'; reason: 'no-config' | 'empty' | 'unknown-slug'; slugs: string[] }
|
|
247
|
+
/** 500:配置写坏,且影响到这次请求的 slug */
|
|
248
|
+
| { kind: 'error'; file: string; problems: ProxyProblem[]; slugs: string[] };
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* 在配置里找 slug:
|
|
252
|
+
* - 文件不存在 → 404;整份写坏 → 500
|
|
253
|
+
* - 找到有效条目 → 照常服务(即便文件里别的条目写坏了)
|
|
254
|
+
* - 没找到:若有写坏的条目与这个 slug 有关(条目 ctag 推出的 slug 相同,或条目连 ctag 都没写对)→ 500,否则 404
|
|
255
|
+
*/
|
|
256
|
+
export function lookupProxy(cfg: ProxyConfigResult, slug: string): ProxyLookup {
|
|
257
|
+
if (cfg.state === 'missing') return { kind: 'none', reason: 'no-config', slugs: [] };
|
|
258
|
+
if (cfg.state === 'broken') return { kind: 'error', file: cfg.file, problems: cfg.problems, slugs: [] };
|
|
259
|
+
const slugs = [...cfg.entries.keys()];
|
|
260
|
+
const entry = cfg.entries.get(slug);
|
|
261
|
+
if (entry) return { kind: 'found', entry };
|
|
262
|
+
if (cfg.problems.some((p) => p.slug === undefined || p.slug === slug)) {
|
|
263
|
+
// 与这次 slug 直接相关的排最前,其次是推不出 slug 的,别的条目的问题垫后
|
|
264
|
+
const rank = (p: ProxyProblem) => (p.slug === slug ? 0 : p.slug === undefined ? 1 : 2);
|
|
265
|
+
return { kind: 'error', file: cfg.file, problems: [...cfg.problems].sort((a, b) => rank(a) - rank(b)), slugs };
|
|
266
|
+
}
|
|
267
|
+
return { kind: 'none', reason: slugs.length === 0 ? 'empty' : 'unknown-slug', slugs };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ───────────────────────── 转发地址与头 ─────────────────────────
|
|
271
|
+
|
|
272
|
+
/** 请求头白名单:只带浏览器到上游有用的几个,其余(含 host / cookie)一律不带 */
|
|
273
|
+
const REQUEST_HEADER_ALLOW = new Set([
|
|
274
|
+
'accept',
|
|
275
|
+
'accept-language',
|
|
276
|
+
'content-type',
|
|
277
|
+
'user-agent',
|
|
278
|
+
'cache-control',
|
|
279
|
+
'if-none-match',
|
|
280
|
+
'range',
|
|
281
|
+
]);
|
|
282
|
+
|
|
283
|
+
/** hop-by-hop 头(RFC 9110):逐跳有效,代理不转;`proxy-*` 另按前缀过滤 */
|
|
284
|
+
const HOP_BY_HOP = new Set([
|
|
285
|
+
'connection',
|
|
286
|
+
'keep-alive',
|
|
287
|
+
'transfer-encoding',
|
|
288
|
+
'upgrade',
|
|
289
|
+
'te',
|
|
290
|
+
'trailer',
|
|
291
|
+
'proxy-authenticate',
|
|
292
|
+
'proxy-authorization',
|
|
293
|
+
'proxy-connection',
|
|
294
|
+
]);
|
|
295
|
+
|
|
296
|
+
/** 回包额外要丢的头:fetch 已解压,content-encoding / content-length 与真实 body 对不上 */
|
|
297
|
+
const DROPPED_RESPONSE_HEADERS = new Set(['content-encoding', 'content-length']);
|
|
298
|
+
|
|
299
|
+
function isHopByHop(name: string): boolean {
|
|
300
|
+
return HOP_BY_HOP.has(name) || name.startsWith('proxy-');
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 上游地址:`http://127.0.0.1:{port}` + 原 path + 原 search(`/proxy/{uuap}/{slug}/` 前缀一并带上,和上游的 base 对齐) */
|
|
304
|
+
export function buildProxyUpstreamUrl(port: number, path: string, search: string): string {
|
|
305
|
+
const p = path.startsWith('/') ? path : `/${path}`;
|
|
306
|
+
const q = !search || search.startsWith('?') ? search : `?${search}`;
|
|
307
|
+
return `http://127.0.0.1:${port}${p}${q}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** 请求头白名单(纯函数):只留 REQUEST_HEADER_ALLOW 里的,头名统一小写 */
|
|
311
|
+
export function pickProxyRequestHeaders(headers: Headers): Record<string, string> {
|
|
312
|
+
const out: Record<string, string> = {};
|
|
313
|
+
headers.forEach((value, name) => {
|
|
314
|
+
const key = name.toLowerCase();
|
|
315
|
+
if (!REQUEST_HEADER_ALLOW.has(key) || isHopByHop(key)) return;
|
|
316
|
+
out[key] = value;
|
|
317
|
+
});
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 回包头过滤(纯函数):去掉 hop-by-hop、`connection` 里点名的头,以及 content-encoding / content-length */
|
|
322
|
+
export function filterProxyResponseHeaders(headers: Headers): Headers {
|
|
323
|
+
const connectionTokens = new Set(
|
|
324
|
+
(headers.get('connection') ?? '')
|
|
325
|
+
.toLowerCase()
|
|
326
|
+
.split(',')
|
|
327
|
+
.map((t) => t.trim())
|
|
328
|
+
.filter(Boolean),
|
|
329
|
+
);
|
|
330
|
+
const out = new Headers();
|
|
331
|
+
headers.forEach((value, name) => {
|
|
332
|
+
const key = name.toLowerCase();
|
|
333
|
+
if (DROPPED_RESPONSE_HEADERS.has(key) || isHopByHop(key) || connectionTokens.has(key)) return;
|
|
334
|
+
out.append(key, value);
|
|
335
|
+
});
|
|
336
|
+
return out;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ───────────────────────── 启动 prompt ─────────────────────────
|
|
340
|
+
|
|
341
|
+
export interface ProxyPromptInput {
|
|
342
|
+
/** 展示用名字(条目 title,没写取 ctag 的 descr) */
|
|
343
|
+
title: string;
|
|
344
|
+
uuap: string;
|
|
345
|
+
slug: string;
|
|
346
|
+
port: number;
|
|
347
|
+
/** 条目 guide 原文;没写就不传 */
|
|
348
|
+
guide?: string;
|
|
349
|
+
/** vault 地址的 host(含端口),取请求的 host */
|
|
350
|
+
host: string;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* 复制给 agent 的启动 prompt(纯函数)。只写要起哪个子服务、端口与 base 的要求、参考指引、怎么确认;
|
|
355
|
+
* 不写启动步骤、命令与绝对路径。guide 超过 PROXY_GUIDE_MAX_CHARS 个字符时截断并提示去 proxy.yaml 看全文。
|
|
356
|
+
*/
|
|
357
|
+
export function buildProxyPrompt(input: ProxyPromptInput): string {
|
|
358
|
+
const { title, uuap, slug, port, guide, host } = input;
|
|
359
|
+
const base = `/proxy/${uuap}/${slug}/`;
|
|
360
|
+
let guideLine: string;
|
|
361
|
+
if (guide === undefined || guide.trim() === '') {
|
|
362
|
+
guideLine = '- 参考指引:条目未写参考指引,可在 proxy.yaml 的这个条目里补 guide';
|
|
363
|
+
} else {
|
|
364
|
+
const chars = Array.from(guide);
|
|
365
|
+
const cut = chars.length > PROXY_GUIDE_MAX_CHARS;
|
|
366
|
+
const text = cut ? chars.slice(0, PROXY_GUIDE_MAX_CHARS).join('') : guide;
|
|
367
|
+
const note = cut ? `(指引过长已截断,全文见 ${proxyDisplayFile(uuap)} 里这个条目的 guide)` : '';
|
|
368
|
+
guideLine = `- 参考指引:${text}${note}(其中的 ctag 先 vault locate-ctag 找到再读;只作参考,按你的理解启动)`;
|
|
369
|
+
}
|
|
370
|
+
return [
|
|
371
|
+
`请帮我启动「${title}」子服务(在 vault 浏览页里打开 ${base} 时它没在运行):`,
|
|
372
|
+
`- 要求:监听端口 ${port}(环境变量 PROXY_PORT=${port}),页面 base 用 ${base}(环境变量 PROXY_BASE)`,
|
|
373
|
+
guideLine,
|
|
374
|
+
`- 起好后用 curl -s -o /dev/null -w "%{http_code}" http://${host}${base} 确认是 200,再告诉我可以刷新页面了`,
|
|
375
|
+
].join('\n');
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ───────────────────────── 兜底页(502 / 504) ─────────────────────────
|
|
379
|
+
|
|
380
|
+
/** HTML 转义(展示用;复制走原文,不经这里) */
|
|
381
|
+
function esc(s: string): string {
|
|
382
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 放进 <script> 里的 JSON 字面量:转义 `<` 防止提前结束 script 标签,U+2028 / U+2029 在旧 JS 里是换行 */
|
|
386
|
+
function jsonForScript(value: unknown): string {
|
|
387
|
+
return JSON.stringify(value)
|
|
388
|
+
.replace(/</g, '\\u003c')
|
|
389
|
+
.replace(/\u2028/g, '\\u2028')
|
|
390
|
+
.replace(/\u2029/g, '\\u2029');
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export interface ProxyFallbackInput {
|
|
394
|
+
status: 502 | 504;
|
|
395
|
+
/** 展示用名字(条目 title,没写取 ctag 的 descr) */
|
|
396
|
+
title: string;
|
|
397
|
+
port: number;
|
|
398
|
+
/** 条目 guide 原文;没写就不传 */
|
|
399
|
+
guide?: string;
|
|
400
|
+
/** 浏览器直连上游调试的地址(带 base 前缀,热更新正常) */
|
|
401
|
+
directUrl: string;
|
|
402
|
+
/** 要复制的 prompt 原文(buildProxyPrompt 的输出) */
|
|
403
|
+
prompt: string;
|
|
404
|
+
timeoutMs?: number;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const FALLBACK_STYLE = `
|
|
408
|
+
:root{--bg:#f5f6fa;--card:#fff;--text:#1f2330;--muted:#6b7183;--line:#e4e6ee;--primary:#3b5bdb;--primary-hover:#324fc4;--ok:#2f9e44;--warn-bg:#fff8e6;--warn-line:#f5d58a;--mono:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
409
|
+
*{box-sizing:border-box}
|
|
410
|
+
body{margin:0;min-height:100vh;background:var(--bg);color:var(--text);font:14px/1.7 -apple-system,BlinkMacSystemFont,"PingFang SC",system-ui,sans-serif;display:flex;flex-direction:column;align-items:center}
|
|
411
|
+
.card{width:min(560px,calc(100vw - 32px));margin:64px 0;padding:32px 32px 24px;background:var(--card);border:1px solid var(--line);border-radius:16px;box-shadow:0 8px 28px rgba(30,40,80,.08)}
|
|
412
|
+
.badge{display:inline-block;padding:1px 8px;border-radius:999px;background:#eef1fb;color:var(--primary);font:12px/1.8 var(--mono)}
|
|
413
|
+
h1{margin:10px 0 6px;font-size:22px;line-height:1.4}
|
|
414
|
+
.lead{margin:0 0 6px;color:var(--muted)}
|
|
415
|
+
.hint{margin:14px 0 0;padding:8px 12px;background:var(--warn-bg);border:1px solid var(--warn-line);border-radius:8px;font-size:13px}
|
|
416
|
+
.primary{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;margin:24px 0 10px;padding:14px 16px;border:0;border-radius:12px;background:var(--primary);color:#fff;font:600 16px/1.4 inherit;font-family:inherit;cursor:pointer;box-shadow:0 6px 16px rgba(59,91,219,.28);transition:background .15s,transform .05s}
|
|
417
|
+
.primary:hover{background:var(--primary-hover)}
|
|
418
|
+
.primary:active{transform:translateY(1px)}
|
|
419
|
+
.primary.done{background:var(--ok);box-shadow:0 6px 16px rgba(47,158,68,.25)}
|
|
420
|
+
.row{display:flex;align-items:center;gap:12px}
|
|
421
|
+
.secondary{padding:7px 16px;border:1px solid var(--line);border-radius:8px;background:#fff;color:var(--text);font:inherit;cursor:pointer}
|
|
422
|
+
.secondary:hover{border-color:#c9cddb}
|
|
423
|
+
.status{color:var(--muted);font-size:13px}
|
|
424
|
+
details{margin-top:16px;border-top:1px solid var(--line);padding-top:12px}
|
|
425
|
+
summary{cursor:pointer;color:var(--muted);font-size:13px}
|
|
426
|
+
pre,textarea{margin:10px 0 0;width:100%;padding:12px;background:#f4f5f9;border:1px solid var(--line);border-radius:8px;font:12.5px/1.6 var(--mono);white-space:pre-wrap;word-break:break-all;color:var(--text)}
|
|
427
|
+
textarea{height:150px;resize:vertical}
|
|
428
|
+
.manual p{margin:8px 0 0;font-size:13px}
|
|
429
|
+
.manual a{color:var(--primary)}
|
|
430
|
+
`;
|
|
431
|
+
|
|
432
|
+
/** 兜底页脚本:复制(剪贴板不可用退回全选文本框)、重新检测(请求当前地址,2xx 刷新,否则提示);不自动轮询 */
|
|
433
|
+
const FALLBACK_SCRIPT = `
|
|
434
|
+
var $=function(id){return document.getElementById(id)};
|
|
435
|
+
var copyBtn=$('copy'),copyTimer=null;
|
|
436
|
+
function markCopied(){copyBtn.classList.add('done');$('copyText').textContent='已复制,粘贴给 agent 即可';clearTimeout(copyTimer);copyTimer=setTimeout(function(){copyBtn.classList.remove('done');$('copyText').textContent='复制启动服务的 prompt'},2000)}
|
|
437
|
+
function showFallback(){var ta=$('fallback');ta.value=PROMPT;ta.hidden=false;ta.focus();ta.select();$('status').textContent='浏览器不让直接写剪贴板,已全选下面的文本,按 Mod+C(Mac 是 Cmd+C)复制'}
|
|
438
|
+
copyBtn.addEventListener('click',function(){if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(PROMPT).then(markCopied,showFallback)}else{showFallback()}});
|
|
439
|
+
$('retry').addEventListener('click',function(){var btn=this;btn.disabled=true;$('status').textContent='检测中…';
|
|
440
|
+
fetch(location.href,{cache:'no-store'}).then(function(r){if(r.ok){location.reload()}else{btn.disabled=false;$('status').textContent='还没起来,稍后再试('+new Date().toLocaleTimeString()+')'}}).catch(function(){btn.disabled=false;$('status').textContent='检测失败,稍后再试('+new Date().toLocaleTimeString()+')'})});
|
|
441
|
+
`;
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* 502 / 504 共用的兜底页(整页内联 CSS 与一小段脚本,不引外部资源):
|
|
445
|
+
* 主按钮复制启动 prompt,次按钮重新检测,prompt 预览与「手动启动」默认折叠;504 多一句 Vite 预构建提示。
|
|
446
|
+
*/
|
|
447
|
+
export function proxyFallbackPage(input: ProxyFallbackInput): string {
|
|
448
|
+
const { status, title, port, guide, directUrl, prompt } = input;
|
|
449
|
+
const timeoutSec = Math.round((input.timeoutMs ?? PROXY_TIMEOUT_MS) / 1000);
|
|
450
|
+
const is504 = status === 504;
|
|
451
|
+
const heading = is504 ? `${title} 可能还在启动` : `${title} 还没启动`;
|
|
452
|
+
const badge = is504 ? '504 · 等待响应超时' : '502 · 子服务未启动';
|
|
453
|
+
const state = is504 ? `${timeoutSec} 秒内没有响应,可能还在启动` : '现在它没在运行';
|
|
454
|
+
const hint = is504
|
|
455
|
+
? `<p class="hint">Vite 首次启动要预构建依赖,可能超过 ${timeoutSec} 秒。如果刚起过服务,先点「重新检测」。</p>`
|
|
456
|
+
: '';
|
|
457
|
+
const guideBlock =
|
|
458
|
+
guide === undefined || guide.trim() === ''
|
|
459
|
+
? '<p>这个条目没写 <code>guide</code>,可以在 <code>proxy.yaml</code> 的这个条目里补一句「怎么启动、去读什么」。</p>'
|
|
460
|
+
: `<p>启动指引(条目 guide 原文):</p><pre>${esc(guide)}</pre>`;
|
|
461
|
+
return `<!doctype html>
|
|
462
|
+
<html lang="zh-CN">
|
|
463
|
+
<head>
|
|
464
|
+
<meta charset="utf-8">
|
|
465
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
466
|
+
<title>${esc(heading)}</title>
|
|
467
|
+
<style>${FALLBACK_STYLE}</style>
|
|
468
|
+
</head>
|
|
469
|
+
<body>
|
|
470
|
+
<main class="card">
|
|
471
|
+
<span class="badge">${badge}</span>
|
|
472
|
+
<h1>${esc(heading)}</h1>
|
|
473
|
+
<p class="lead">这是 vault 导向的独立子服务,${state}。vault 本身正常,浏览页与 <code>vault status</code> 照常可用。</p>
|
|
474
|
+
${hint}
|
|
475
|
+
<button type="button" class="primary" id="copy"><span aria-hidden="true">⧉</span><span id="copyText">复制启动服务的 prompt</span></button>
|
|
476
|
+
<div class="row"><button type="button" class="secondary" id="retry">重新检测</button><span class="status" id="status">把 prompt 粘贴给 agent,起好后点这里</span></div>
|
|
477
|
+
<textarea id="fallback" hidden readonly aria-label="prompt 原文"></textarea>
|
|
478
|
+
<details><summary>查看将要复制的 prompt</summary><pre>${esc(prompt)}</pre></details>
|
|
479
|
+
<details class="manual"><summary>手动启动</summary>
|
|
480
|
+
${guideBlock}
|
|
481
|
+
<p>也可以直接打开 <a href="${esc(directUrl)}">${esc(directUrl)}</a> 调试,不经过 vault,热更新正常(端口 ${port})。</p>
|
|
482
|
+
</details>
|
|
483
|
+
</main>
|
|
484
|
+
<script>var PROMPT=${jsonForScript(prompt)};${FALLBACK_SCRIPT}</script>
|
|
485
|
+
</body>
|
|
486
|
+
</html>`;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** 兜底页响应:状态码照旧(502 上游连不上 / 504 等响应头超时),不缓存 */
|
|
490
|
+
export function proxyFallbackResponse(input: ProxyFallbackInput): Response {
|
|
491
|
+
return new Response(proxyFallbackPage(input), {
|
|
492
|
+
status: input.status,
|
|
493
|
+
headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' },
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ───────────────────────── 代理 ─────────────────────────
|
|
498
|
+
|
|
499
|
+
export interface ProxyRequestOptions {
|
|
500
|
+
/** fetch 实现,默认全局 fetch;测试注入用 */
|
|
501
|
+
fetchImpl?: typeof fetch;
|
|
502
|
+
/** 等响应头的上限(毫秒),默认 PROXY_TIMEOUT_MS;测试注入用 */
|
|
503
|
+
timeoutMs?: number;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Node 的 fetch 在 body 是流时要求显式声明半双工 */
|
|
507
|
+
interface ProxyRequestInit extends RequestInit {
|
|
508
|
+
duplex?: 'half';
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** prompt 里 curl 验证用的 host 取自请求的 Host 头;只放行主机名 / IP / 端口形态,其余退回 127.0.0.1(prompt 会被复制给 agent,不能带入任意文本) */
|
|
512
|
+
function safeHost(host: string): string {
|
|
513
|
+
return /^[A-Za-z0-9.\-[\]:]+$/.test(host) ? host : '127.0.0.1';
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* 把一条 `/proxy/{uuap}/{slug}/*` 请求转发到条目的上游,出错回兜底页。
|
|
518
|
+
* - 方法、path、search 原样;body 以流透传(非 GET / HEAD 才带)
|
|
519
|
+
* - 超时只覆盖「等响应头」:拿到头立刻撤掉 AbortController,免得把流式回传的 body 一起中断
|
|
520
|
+
* - redirect 用 manual:上游的 302 连同 location 原样交回浏览器
|
|
521
|
+
*/
|
|
522
|
+
export async function proxyRequest(
|
|
523
|
+
req: Request,
|
|
524
|
+
entry: ProxyEntry,
|
|
525
|
+
uuap: string,
|
|
526
|
+
opts: ProxyRequestOptions = {},
|
|
527
|
+
): Promise<Response> {
|
|
528
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
529
|
+
const timeoutMs = opts.timeoutMs ?? PROXY_TIMEOUT_MS;
|
|
530
|
+
const url = new URL(req.url);
|
|
531
|
+
const target = buildProxyUpstreamUrl(entry.port, url.pathname, url.search);
|
|
532
|
+
const fallback = (status: 502 | 504): Response => {
|
|
533
|
+
const title = entry.title ?? proxySlugDescr(entry.slug);
|
|
534
|
+
const base = `/proxy/${uuap}/${entry.slug}/`;
|
|
535
|
+
return proxyFallbackResponse({
|
|
536
|
+
status,
|
|
537
|
+
title,
|
|
538
|
+
port: entry.port,
|
|
539
|
+
guide: entry.guide,
|
|
540
|
+
directUrl: `http://127.0.0.1:${entry.port}${base}`,
|
|
541
|
+
prompt: buildProxyPrompt({ title, uuap, slug: entry.slug, port: entry.port, guide: entry.guide, host: safeHost(url.host) }),
|
|
542
|
+
timeoutMs,
|
|
543
|
+
});
|
|
544
|
+
};
|
|
545
|
+
const ctrl = new AbortController();
|
|
546
|
+
let timedOut = false;
|
|
547
|
+
const timer = setTimeout(() => {
|
|
548
|
+
timedOut = true;
|
|
549
|
+
ctrl.abort();
|
|
550
|
+
}, timeoutMs);
|
|
551
|
+
const init: ProxyRequestInit = {
|
|
552
|
+
method: req.method,
|
|
553
|
+
headers: pickProxyRequestHeaders(req.headers),
|
|
554
|
+
signal: ctrl.signal,
|
|
555
|
+
redirect: 'manual',
|
|
556
|
+
};
|
|
557
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && req.body) {
|
|
558
|
+
init.body = req.body;
|
|
559
|
+
init.duplex = 'half';
|
|
560
|
+
}
|
|
561
|
+
let upstream: Response;
|
|
562
|
+
try {
|
|
563
|
+
upstream = await doFetch(target, init);
|
|
564
|
+
} catch {
|
|
565
|
+
clearTimeout(timer);
|
|
566
|
+
return fallback(timedOut ? 504 : 502);
|
|
567
|
+
}
|
|
568
|
+
clearTimeout(timer);
|
|
569
|
+
// 取 body 本身也可能抛:上游声明了 content-encoding 但流不是对应压缩格式时,fetch 在取流那一刻才报错,
|
|
570
|
+
// 这类回包同样没法用,按 502 给兜底页(头已经发出去之后的流中断就只能断连,代理层面无法再改状态码)
|
|
571
|
+
let body: ReadableStream<Uint8Array> | null = null;
|
|
572
|
+
try {
|
|
573
|
+
body = req.method === 'HEAD' ? null : upstream.body;
|
|
574
|
+
} catch {
|
|
575
|
+
return fallback(502);
|
|
576
|
+
}
|
|
577
|
+
return new Response(body, {
|
|
578
|
+
status: upstream.status,
|
|
579
|
+
statusText: upstream.statusText,
|
|
580
|
+
headers: filterProxyResponseHeaders(upstream.headers),
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ───────────────────────── 配置问题的文本回应 ─────────────────────────
|
|
585
|
+
|
|
586
|
+
/** 配置缺失 / 条目不存在(404)与配置写坏(500)的纯文本说明:写明配置文件相对路径与具体问题 */
|
|
587
|
+
export function proxyProblemText(lookup: Exclude<ProxyLookup, { kind: 'found' }>, uuap: string, slug: string): string {
|
|
588
|
+
const file = proxyDisplayFile(uuap);
|
|
589
|
+
if (lookup.kind === 'none') {
|
|
590
|
+
if (lookup.reason === 'no-config') return `没有找到代理配置 ${file}。在里面登记 version: 1 与 proxies 条目后再访问。`;
|
|
591
|
+
if (lookup.reason === 'empty') return `${file} 里还没有任何代理条目(proxies 为空)。`;
|
|
592
|
+
return `${file} 里没有地址段为 ${slug} 的条目。已登记:${lookup.slugs.join('、')}`;
|
|
593
|
+
}
|
|
594
|
+
const lines = lookup.problems.map((p) => `- ${p.field}:${p.message}`);
|
|
595
|
+
return [`代理配置 ${file} 有问题,这次请求的地址(${slug})受影响:`, ...lines].join('\n');
|
|
596
|
+
}
|
package/web/dist/assets/{abnfDiagram-WEYOIA3C-rZaG2iSs.js → abnfDiagram-WEYOIA3C-CzLGzmT0.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as p,r as u,d as a}from"./chunk-2E7WHVMD-
|
|
1
|
+
import{g as p,r as u,d as a}from"./chunk-2E7WHVMD-CvnX45iC.js";import{p as f}from"./chunk-JWPE2WC7-av5KekLY.js";import{_ as n,l as o}from"./mermaid.core-BxPAQxuk.js";import{M as c,b as d}from"./cynefin-EF2NZ3EQ-84DLvAE7.js";import"./index-o91WzriM.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},B={parser:R,db:a,renderer:u,styles:p};export{B as diagram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a6 as ln,a7 as an,a8 as G,a9 as j,aa as z,ab as un,ac as g,ad as tn,ae as K,af as _,ag as rn,ah as o,ai as on,aj as sn,ak as fn}from"./mermaid.core-
|
|
1
|
+
import{a6 as ln,a7 as an,a8 as G,a9 as j,aa as z,ab as un,ac as g,ad as tn,ae as K,af as _,ag as rn,ah as o,ai as on,aj as sn,ak as fn}from"./mermaid.core-BxPAQxuk.js";function cn(l){return l.innerRadius}function gn(l){return l.outerRadius}function yn(l){return l.startAngle}function dn(l){return l.endAngle}function mn(l){return l&&l.padAngle}function pn(l,h,E,q,v,A,B,a){var I=E-l,i=q-h,n=B-v,d=a-A,u=d*I-n*i;if(!(u*u<g))return u=(n*(h-A)-d*(l-v))/u,[l+u*I,h+u*i]}function V(l,h,E,q,v,A,B){var a=l-E,I=h-q,i=(B?A:-A)/K(a*a+I*I),n=i*I,d=-i*a,u=l+n,s=h+d,f=E+n,c=q+d,C=(u+f)/2,t=(s+c)/2,m=f-u,y=c-s,R=m*m+y*y,T=v-A,P=u*c-f*s,O=(y<0?-1:1)*K(on(0,T*T*R-P*P)),S=(P*y-m*O)/R,k=(-P*m-y*O)/R,w=(P*y+m*O)/R,p=(-P*m+y*O)/R,x=S-C,e=k-t,r=w-C,F=p-t;return x*x+e*e>r*r+F*F&&(S=w,k=p),{cx:S,cy:k,x01:-n,y01:-d,x11:S*(v/T-1),y11:k*(v/T-1)}}function hn(){var l=cn,h=gn,E=z(0),q=null,v=yn,A=dn,B=mn,a=null,I=ln(i);function i(){var n,d,u=+l.apply(this,arguments),s=+h.apply(this,arguments),f=v.apply(this,arguments)-un,c=A.apply(this,arguments)-un,C=rn(c-f),t=c>f;if(a||(a=n=I()),s<u&&(d=s,s=u,u=d),!(s>g))a.moveTo(0,0);else if(C>tn-g)a.moveTo(s*G(f),s*j(f)),a.arc(0,0,s,f,c,!t),u>g&&(a.moveTo(u*G(c),u*j(c)),a.arc(0,0,u,c,f,t));else{var m=f,y=c,R=f,T=c,P=C,O=C,S=B.apply(this,arguments)/2,k=S>g&&(q?+q.apply(this,arguments):K(u*u+s*s)),w=_(rn(s-u)/2,+E.apply(this,arguments)),p=w,x=w,e,r;if(k>g){var F=sn(k/u*j(S)),L=sn(k/s*j(S));(P-=F*2)>g?(F*=t?1:-1,R+=F,T-=F):(P=0,R=T=(f+c)/2),(O-=L*2)>g?(L*=t?1:-1,m+=L,y-=L):(O=0,m=y=(f+c)/2)}var H=s*G(m),J=s*j(m),M=u*G(T),N=u*j(T);if(w>g){var Q=s*G(y),U=s*j(y),W=u*G(R),X=u*j(R),D;if(C<an)if(D=pn(H,J,W,X,Q,U,M,N)){var Y=H-D[0],Z=J-D[1],$=Q-D[0],b=U-D[1],nn=1/j(fn((Y*$+Z*b)/(K(Y*Y+Z*Z)*K($*$+b*b)))/2),en=K(D[0]*D[0]+D[1]*D[1]);p=_(w,(u-en)/(nn-1)),x=_(w,(s-en)/(nn+1))}else p=x=0}O>g?x>g?(e=V(W,X,H,J,s,x,t),r=V(Q,U,M,N,s,x,t),a.moveTo(e.cx+e.x01,e.cy+e.y01),x<w?a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,s,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),!t),a.arc(r.cx,r.cy,x,o(r.y11,r.x11),o(r.y01,r.x01),!t))):(a.moveTo(H,J),a.arc(0,0,s,m,y,!t)):a.moveTo(H,J),!(u>g)||!(P>g)?a.lineTo(M,N):p>g?(e=V(M,N,Q,U,u,-p,t),r=V(H,J,W,X,u,-p,t),a.lineTo(e.cx+e.x01,e.cy+e.y01),p<w?a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,u,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),t),a.arc(r.cx,r.cy,p,o(r.y11,r.x11),o(r.y01,r.x01),!t))):a.arc(0,0,u,T,R,t)}if(a.closePath(),n)return a=null,n+""||null}return i.centroid=function(){var n=(+l.apply(this,arguments)+ +h.apply(this,arguments))/2,d=(+v.apply(this,arguments)+ +A.apply(this,arguments))/2-an/2;return[G(d)*n,j(d)*n]},i.innerRadius=function(n){return arguments.length?(l=typeof n=="function"?n:z(+n),i):l},i.outerRadius=function(n){return arguments.length?(h=typeof n=="function"?n:z(+n),i):h},i.cornerRadius=function(n){return arguments.length?(E=typeof n=="function"?n:z(+n),i):E},i.padRadius=function(n){return arguments.length?(q=n==null?null:typeof n=="function"?n:z(+n),i):q},i.startAngle=function(n){return arguments.length?(v=typeof n=="function"?n:z(+n),i):v},i.endAngle=function(n){return arguments.length?(A=typeof n=="function"?n:z(+n),i):A},i.padAngle=function(n){return arguments.length?(B=typeof n=="function"?n:z(+n),i):B},i.context=function(n){return arguments.length?(a=n??null,i):a},i}export{hn as d};
|