@allbluecn/dsh-compat 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +24 -2
- package/package.json +34 -3
- package/src/__tests__/package.test.ts +58 -0
- package/src/assemble/__tests__/assemble.test.ts +656 -0
- package/src/assemble/assemble.ts +383 -0
- package/src/assemble/resolve.ts +59 -0
- package/src/compat/__tests__/context.test.ts +211 -0
- package/src/compat/__tests__/events.test.ts +135 -0
- package/src/compat/__tests__/tool-adapter.test.ts +157 -0
- package/src/compat/__tests__/view-bridge.test.ts +166 -0
- package/src/compat/context.ts +496 -0
- package/src/compat/events.ts +189 -0
- package/src/compat/tool-adapter.ts +115 -0
- package/src/compat/view-bridge.ts +160 -0
- package/src/guard/assert-fetchable-url.ts +239 -0
- package/src/index.ts +52 -0
- package/src/patch/__tests__/patch.test.ts +250 -0
- package/src/patch/eval.ts +343 -0
- package/src/patch/merge.ts +45 -0
- package/src/patch/types.ts +37 -0
- package/src/patch/yaml.ts +75 -0
- package/src/plugin-safety/__tests__/build-approval.test.ts +149 -0
- package/src/plugin-safety/__tests__/install-spec.test.ts +148 -0
- package/src/plugin-safety/build-approval.ts +134 -0
- package/src/plugin-safety/index.ts +31 -0
- package/src/plugin-safety/install-spec.ts +189 -0
- package/src/report.ts +47 -0
- package/src/surface.ts +92 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// DSH 工具定义 → TanStack AnyTool 适配器(规格 §4.1.3)。
|
|
3
|
+
//
|
|
4
|
+
// - `parameters`(JSON Schema)直传官方 `inputSchema`;`output.schema` → `outputSchema`。
|
|
5
|
+
// - execute 适配官方 ToolExecutionContext(signal/runId)→ CordisToolRunContext,
|
|
6
|
+
// 调 DSH `def.execute`,再经渲染桥通道 A `attachView` 挂 `result.__dshView`。
|
|
7
|
+
// - `timeoutMs` → execute 内超时;`deferLoading` → 官方 lazy 工具。
|
|
8
|
+
// - `isConcurrencySafe` / `projectContent` / `finalizeContent` / `presentCall` 官方无对应,
|
|
9
|
+
// 忽略并记入 adapterNotes 供 F1-5 收集。
|
|
10
|
+
// - JSON Schema 净化:去除 provider 不认的冷门/已废弃关键字(经验性防御,见 SANITIZE_STRIP_KEYS)。
|
|
11
|
+
import type { AnyTool, ToolExecutionContext } from '@tanstack/ai'
|
|
12
|
+
import type { CordisToolDef, CordisToolRunContext } from './context'
|
|
13
|
+
import { attachView } from './view-bridge'
|
|
14
|
+
|
|
15
|
+
/** provider 不认 / 已废弃的 JSON Schema 关键字净化表(递归剥离)。 */
|
|
16
|
+
const SANITIZE_STRIP_KEYS: ReadonlySet<string> = new Set([
|
|
17
|
+
// JSON Schema draft-04 专属:现代 provider 用 `minimum`/`maximum` + 布尔 exclusive*。
|
|
18
|
+
// draft-04 里 exclusiveMinimum/Maximum 是「数字」且与 minimum 互斥,会被 provider 误解。
|
|
19
|
+
'exclusiveMinimum',
|
|
20
|
+
'exclusiveMaximum',
|
|
21
|
+
// 少见 / provider 普遍不实现的关键字(DSH $/schema 偶见,直传可能触发严格校验报错)。
|
|
22
|
+
'contains',
|
|
23
|
+
'propertyNames',
|
|
24
|
+
'patternProperties',
|
|
25
|
+
'dependencies',
|
|
26
|
+
'additionalItems',
|
|
27
|
+
'$schema',
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 递归净化 JSON Schema:剥离 provider 不认的关键字。保留 type/properties/required/
|
|
32
|
+
* items/enum/default/description 等通用关键字。返回新对象(不改动入参)。
|
|
33
|
+
*/
|
|
34
|
+
export function sanitizeJsonSchema(schema: unknown): unknown {
|
|
35
|
+
if (Array.isArray(schema)) return schema.map(sanitizeJsonSchema)
|
|
36
|
+
if (typeof schema === 'object' && schema !== null) {
|
|
37
|
+
const out: Record<string, unknown> = {}
|
|
38
|
+
for (const [key, value] of Object.entries(schema as Record<string, unknown>)) {
|
|
39
|
+
if (SANITIZE_STRIP_KEYS.has(key)) continue
|
|
40
|
+
out[key] = sanitizeJsonSchema(value)
|
|
41
|
+
}
|
|
42
|
+
return out
|
|
43
|
+
}
|
|
44
|
+
return schema
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 官方无对应而忽略的 DSH 工具字段(F1-5 report 备注收集用)。 */
|
|
48
|
+
export function adapterNotes(def: CordisToolDef): Array<string> {
|
|
49
|
+
const notes: Array<string> = []
|
|
50
|
+
if (def.isConcurrencySafe !== undefined) notes.push('isConcurrencySafe')
|
|
51
|
+
if (def.projectContent !== undefined) notes.push('projectContent')
|
|
52
|
+
if (def.finalizeContent !== undefined) notes.push('finalizeContent')
|
|
53
|
+
if (typeof def.presentCall === 'function') notes.push('presentCall(pending 视图无下发时机,忽略)')
|
|
54
|
+
return notes
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 官方 ToolExecutionContext → CordisToolRunContext(signal / caller)。 */
|
|
58
|
+
export function adaptToolRunContext(
|
|
59
|
+
tctx: ToolExecutionContext | undefined,
|
|
60
|
+
): CordisToolRunContext {
|
|
61
|
+
if (!tctx) return {}
|
|
62
|
+
return {
|
|
63
|
+
...(tctx.abortSignal ? { signal: tctx.abortSignal } : {}),
|
|
64
|
+
...(tctx.runId ? { caller: tctx.runId } : {}),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** execute 内超时包装:限时到 → reject(官方 execute 抛错 → 工具失败,模型收到 error)。 */
|
|
69
|
+
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
|
70
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
71
|
+
const timeout = new Promise<never>((_resolve, reject) => {
|
|
72
|
+
timer = setTimeout(
|
|
73
|
+
() => reject(new Error(`tool execute timed out after ${ms}ms`)),
|
|
74
|
+
ms,
|
|
75
|
+
)
|
|
76
|
+
})
|
|
77
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
78
|
+
if (timer) clearTimeout(timer)
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 把 DSH 工具定义翻译成官方 AnyTool。
|
|
84
|
+
* - parameters → inputSchema(经 {@link sanitizeJsonSchema} 净化后直传)
|
|
85
|
+
* - output.schema → outputSchema
|
|
86
|
+
* - deferLoading → lazy
|
|
87
|
+
* - execute:适配上下文 → DSH execute → attachView(通道 A)
|
|
88
|
+
*/
|
|
89
|
+
export function dshToolToTanStack(def: CordisToolDef): AnyTool {
|
|
90
|
+
const inputSchema = sanitizeJsonSchema(def.parameters)
|
|
91
|
+
const outputSchema = sanitizeJsonSchema(def.output?.schema)
|
|
92
|
+
const hasInput = inputSchema !== undefined
|
|
93
|
+
const hasOutput = outputSchema !== undefined
|
|
94
|
+
|
|
95
|
+
const tool: AnyTool = {
|
|
96
|
+
name: def.name,
|
|
97
|
+
description: def.description ?? '',
|
|
98
|
+
...(hasInput ? { inputSchema: inputSchema as AnyTool['inputSchema'] } : {}),
|
|
99
|
+
...(hasOutput ? { outputSchema: outputSchema as AnyTool['outputSchema'] } : {}),
|
|
100
|
+
...(def.deferLoading ? { lazy: true } : {}),
|
|
101
|
+
execute: async (args: unknown, tctx?: ToolExecutionContext) => {
|
|
102
|
+
const adapted = adaptToolRunContext(tctx)
|
|
103
|
+
const run = (): Promise<unknown> =>
|
|
104
|
+
Promise.resolve(def.execute(args, adapted))
|
|
105
|
+
const ms = def.timeoutMs
|
|
106
|
+
const raw =
|
|
107
|
+
typeof ms === 'number' && ms > 0
|
|
108
|
+
? await withTimeout(run(), ms)
|
|
109
|
+
: await run()
|
|
110
|
+
// 渲染桥通道 A:presentResult 视图挂 result.__dshView(presenter 抛错/缺省 → 不挂)。
|
|
111
|
+
return attachView(def.presentResult, args, raw)
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
return tool
|
|
115
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// 渲染桥通道 A 生产件(F1-3 spike 结论,见包 README「渲染桥通道选型」)。
|
|
3
|
+
//
|
|
4
|
+
// 通道 A:DSH 工具 `presentResult` 产出的视图 JSON 挂在 tool result 的约定字段
|
|
5
|
+
// `__dshView`(多视图并存用 `__dshView_<name>`),随 content 落 messages store
|
|
6
|
+
// (持久化/transcript 保留);一层 chat middleware 在 `onConfig` 只返回
|
|
7
|
+
// `{ providerMessages: stripped }` 剥除该字段——canonical `messages` 不动,
|
|
8
|
+
// 模型看不到,prompt cache 前缀稳定。客户端(F6 DshCardView)读
|
|
9
|
+
// `part.result?.__dshView`。
|
|
10
|
+
//
|
|
11
|
+
// 活更新语义:视图**一次性产出**(execute 期),不活更。若将来需要活更
|
|
12
|
+
// (工具后台跑完后刷新卡片),须另补 transcript 重投影路径,不经本文件。
|
|
13
|
+
import type { AnyChatMiddleware, ModelMessage } from '@tanstack/ai'
|
|
14
|
+
|
|
15
|
+
/** result 上挂视图的约定字段前缀。单视图 = `__dshView`,多视图 = `__dshView_<name>`。 */
|
|
16
|
+
export const DSH_VIEW_FIELD = '__dshView'
|
|
17
|
+
|
|
18
|
+
/** 单个视图 JSON 序列化后的最大字节(超出截断,防超大视图膨胀持久化)。 */
|
|
19
|
+
export const MAX_DSH_VIEW_JSON_BYTES = 256 * 1024
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* presenter 产出的视图 JSON 的最小形状校验(软校验)。
|
|
23
|
+
* 合法视图 = 一个普通对象(非 null、非数组)。字段形状由 DSH 视图 schema 约束,
|
|
24
|
+
* 这里只挡住「presenter 误返回标量/数组」这类明显不合法,非法则不挂 → 客户端回退
|
|
25
|
+
* GenericToolCard(对齐包 README「presenter 抛错 / 视图缺省」与规格 §8 差异表 #4)。
|
|
26
|
+
*/
|
|
27
|
+
function isPlainObjectView(view: unknown): view is Record<string, unknown> {
|
|
28
|
+
return typeof view === 'object' && view !== null && !Array.isArray(view)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 视图 JSON 的字节长度(UTF-8)。序列化失败(如循环引用)返回 null。 */
|
|
32
|
+
function viewJsonBytes(view: Record<string, unknown>): number | null {
|
|
33
|
+
try {
|
|
34
|
+
return Buffer.byteLength(JSON.stringify(view), 'utf8')
|
|
35
|
+
} catch {
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 按视图(可带 name)算出它在 result 上的挂载字段名。
|
|
42
|
+
* 单视图 → `__dshView`;带 name 的多视图并存 → `__dshView_<name>`。
|
|
43
|
+
* name 须是安全标识(字母数字下划线连字符),否则回退单视图字段避免键污染。
|
|
44
|
+
*/
|
|
45
|
+
export function dshViewField(view: Record<string, unknown>): string {
|
|
46
|
+
const name = (view as { name?: unknown }).name
|
|
47
|
+
if (
|
|
48
|
+
typeof name === 'string' &&
|
|
49
|
+
name.length > 0 &&
|
|
50
|
+
/^[A-Za-z0-9_-]+$/.test(name)
|
|
51
|
+
) {
|
|
52
|
+
return `${DSH_VIEW_FIELD}_${name}`
|
|
53
|
+
}
|
|
54
|
+
return DSH_VIEW_FIELD
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** result 上所有可能的视图字段名(剥除时用,覆盖单视图与任意 name 后缀)。 */
|
|
58
|
+
function viewFieldNames(record: Record<string, unknown>): Array<string> {
|
|
59
|
+
return Object.keys(record).filter(
|
|
60
|
+
(key) => key === DSH_VIEW_FIELD || key.startsWith(`${DSH_VIEW_FIELD}_`),
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 把 DSH `presentResult` 产出的视图 JSON 挂到 tool result 上(通道 A)。
|
|
66
|
+
*
|
|
67
|
+
* - result 是普通对象 → 直接挂 `result[__dshView]`(或 `__dshView_<name>`)。
|
|
68
|
+
* - result 非对象(string/number/…)→ 包装成 `{ value, [__dshView] }`,让视图
|
|
69
|
+
* 仍能到达客户端;模型看到的是包装对象(presentResult 存在即视为该工具的
|
|
70
|
+
* 结果本就要渲染,属可接受差异)。
|
|
71
|
+
* - presenter 未定义 / 抛错 / 产出非法视图(非普通对象或序列化失败)→ 不挂,
|
|
72
|
+
* 返回原 result → 客户端回退 GenericToolCard(软校验,不 fail turn)。
|
|
73
|
+
* - 单视图超出 {@link MAX_DSH_VIEW_JSON_BYTES} → 截断为占位视图(不挂原始大对象)。
|
|
74
|
+
*
|
|
75
|
+
* @returns 挂好视图的 result(可能因包装/截断与入参不同),或原 result。
|
|
76
|
+
*/
|
|
77
|
+
export function attachView(
|
|
78
|
+
presentResult: ((args: unknown, result: unknown) => unknown) | undefined,
|
|
79
|
+
args: unknown,
|
|
80
|
+
result: unknown,
|
|
81
|
+
): unknown {
|
|
82
|
+
if (typeof presentResult !== 'function') return result
|
|
83
|
+
let view: unknown
|
|
84
|
+
try {
|
|
85
|
+
view = presentResult(args, result)
|
|
86
|
+
} catch {
|
|
87
|
+
// presenter 抛错 → 视图缺省(不挂),客户端回退 GenericToolCard。
|
|
88
|
+
return result
|
|
89
|
+
}
|
|
90
|
+
if (!isPlainObjectView(view)) return result
|
|
91
|
+
|
|
92
|
+
const bytes = viewJsonBytes(view)
|
|
93
|
+
if (bytes === null) return result // 序列化失败(循环引用等)→ 不挂
|
|
94
|
+
let attached: Record<string, unknown> = view
|
|
95
|
+
if (bytes > MAX_DSH_VIEW_JSON_BYTES) {
|
|
96
|
+
attached = {
|
|
97
|
+
kind: 'dsh-view-truncated',
|
|
98
|
+
__dshViewTruncated: true,
|
|
99
|
+
originalBytes: bytes,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const field = dshViewField(view)
|
|
104
|
+
if (isPlainObjectView(result)) {
|
|
105
|
+
return { ...result, [field]: attached }
|
|
106
|
+
}
|
|
107
|
+
// result 非对象:包装,保住视图通道;模型看到包装对象。
|
|
108
|
+
return { value: result, [field]: attached }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 剥除 providerMessages 里所有 tool 消息 result 上的 `__dshView*` 字段(通道 A 模型不可见面)。
|
|
113
|
+
* 只改 `providerMessages`(provider-only 视图),canonical `messages` 不动 →
|
|
114
|
+
* 持久化/transcript 仍带视图,模型看不到。剥除确定性 + 只动后缀 ⇒ prompt cache
|
|
115
|
+
* 前缀稳定(依据见包 README,已从「cachedTokens 增长」改挂到本机制推理)。
|
|
116
|
+
*/
|
|
117
|
+
function stripDshViewFromMessages(
|
|
118
|
+
messages: ReadonlyArray<ModelMessage>,
|
|
119
|
+
): { messages: Array<ModelMessage>; touched: boolean } {
|
|
120
|
+
let touched = false
|
|
121
|
+
const out: Array<ModelMessage> = messages.map((message) => {
|
|
122
|
+
if (message.role !== 'tool') return message
|
|
123
|
+
const content = message.content
|
|
124
|
+
if (typeof content !== 'string' || !content.includes(DSH_VIEW_FIELD)) {
|
|
125
|
+
return message
|
|
126
|
+
}
|
|
127
|
+
let parsed: unknown
|
|
128
|
+
try {
|
|
129
|
+
parsed = JSON.parse(content)
|
|
130
|
+
} catch {
|
|
131
|
+
return message
|
|
132
|
+
}
|
|
133
|
+
if (typeof parsed !== 'object' || parsed === null) return message
|
|
134
|
+
const record = parsed as Record<string, unknown>
|
|
135
|
+
const fields = viewFieldNames(record)
|
|
136
|
+
if (fields.length === 0) return message
|
|
137
|
+
touched = true
|
|
138
|
+
const rest: Record<string, unknown> = { ...record }
|
|
139
|
+
for (const field of fields) delete rest[field]
|
|
140
|
+
return { ...message, content: JSON.stringify(rest) }
|
|
141
|
+
})
|
|
142
|
+
return { messages: out, touched }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 通道 A 剥除 middleware。挂在 harness/插件 chat middleware 链上,`onConfig`
|
|
147
|
+
* 只返回 `{ providerMessages: stripped }`——ai 核心仅当 middleware 显式返回
|
|
148
|
+
* `providerMessages` 时才改模型可见面,canonical `messages`(持久化与 transcript
|
|
149
|
+
* 来源)不被触碰。剥除确定性 + 只动工具结果消息尾部 ⇒ 跨回合 prompt cache 前缀稳定。
|
|
150
|
+
*/
|
|
151
|
+
export function stripDshViewMiddleware(): AnyChatMiddleware {
|
|
152
|
+
return {
|
|
153
|
+
name: 'dsh-compat:view-strip',
|
|
154
|
+
onConfig: (_ctx, config) => {
|
|
155
|
+
const source = config.providerMessages ?? config.messages
|
|
156
|
+
const { messages, touched } = stripDshViewFromMessages(source)
|
|
157
|
+
return touched ? { providerMessages: messages } : undefined
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// AllBlue - 理想之海
|
|
3
|
+
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
+
//
|
|
5
|
+
// 服务端 fetch 目标准入判定(SSRF 防护)——**SSRF 唯一实现**。
|
|
6
|
+
// 自 apps/web/src/server/fetch-guard.ts 下沉至本包(零 app 依赖纯模块),
|
|
7
|
+
// web 侧 `@/server/fetch-guard` 现为 re-export shim 指向本文件,导出面不变。
|
|
8
|
+
|
|
9
|
+
// 纯函数模块,仅依赖全局 URL,禁止 import prisma 等重模块,
|
|
10
|
+
// 以便同时被服务端路由与单元测试消费。
|
|
11
|
+
|
|
12
|
+
export class FetchGuardError extends Error {
|
|
13
|
+
constructor(url: string, reason: string) {
|
|
14
|
+
super(`拒绝 fetch 目标 ${url}:${reason}`)
|
|
15
|
+
this.name = "FetchGuardError"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface FetchGuardOptions {
|
|
20
|
+
/** 显式允许私网/回环目标(SearXNG 等自托管内网服务、桌面端本地 Ollama 场景) */
|
|
21
|
+
allowPrivate?: boolean
|
|
22
|
+
/** 主机白名单(提供时仅放行列表内主机,与 allowPrivate 独立判定) */
|
|
23
|
+
allowedHosts?: string[]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 桌面端运行时判定:desktop 端(Electron + PGlite,迁移设计 §3.8)单机部署,
|
|
28
|
+
* 数据库走 DATABASE_PROVIDER=pglite;此时 localhost/私网是合法服务地址(如本地
|
|
29
|
+
* Ollama http://localhost:11434),BYOK 请求的私网 baseUrl 应放行。
|
|
30
|
+
* 云端 SaaS 为 postgres,恒返回 false——SSRF 防护默认语义不变(未知取值
|
|
31
|
+
* 按云端处理,fail-closed)。
|
|
32
|
+
*/
|
|
33
|
+
export function isDesktopRuntime(): boolean {
|
|
34
|
+
return process.env.DATABASE_PROVIDER === "pglite"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 判定点分十进制 IPv4 是否落在私网/回环/链路本地/未指定/组播保留段。
|
|
39
|
+
* 这些地址段是 SSRF 的主要攻击面:本机服务(127.0.0.1)、内网资产(10/172.16/192.168)、
|
|
40
|
+
* 云元数据端点(169.254.169.254,可窃取实例凭证)。
|
|
41
|
+
* IANA 特殊用途段(2026-10 审计补齐):0.0.0.0/8、100.64/10(CGNAT,Tailscale 等
|
|
42
|
+
* overlay 网段)、192.0.0.0/24(IETF 协议分配)、198.18/15(基准测试)、
|
|
43
|
+
* 240/4 与 224/4(保留/组播,a>=224 统一拦截)。
|
|
44
|
+
*/
|
|
45
|
+
function isPrivateIPv4(host: string): boolean {
|
|
46
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host)
|
|
47
|
+
if (!m) return false
|
|
48
|
+
const a = Number(m[1])
|
|
49
|
+
const b = Number(m[2])
|
|
50
|
+
const c = Number(m[3])
|
|
51
|
+
if (a === 127 || a === 10 || a === 0) return true
|
|
52
|
+
if (a === 172 && b >= 16 && b <= 31) return true
|
|
53
|
+
if (a === 192 && b === 168) return true
|
|
54
|
+
if (a === 192 && b === 0 && c === 0) return true
|
|
55
|
+
if (a === 169 && b === 254) return true
|
|
56
|
+
if (a === 100 && b >= 64 && b <= 127) return true
|
|
57
|
+
if (a === 198 && (b === 18 || b === 19)) return true
|
|
58
|
+
if (a >= 224) return true
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 32 位整数转点分十进制,供整数形式 IPv4 与 IPv6 映射地址复用 */
|
|
63
|
+
function toDotQuad(n: number): string {
|
|
64
|
+
return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join(".")
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 解析 32 位整数形式的 IP 混淆(十进制/十六进制/八进制),返回点分十进制。
|
|
69
|
+
* 纵深防御:WHATWG URL 在 Node 24 已会把这类主机规范化,但不同运行时
|
|
70
|
+
* (浏览器 WebKit、旧版 Node、上游中间件改写后的 hostname)行为不一致,
|
|
71
|
+
* 不能依赖上游规范化结果。非整数形式或超出 32 位返回 null,交由调用方继续判定。
|
|
72
|
+
*/
|
|
73
|
+
function normalizeIntegerIp(host: string): string | null {
|
|
74
|
+
let n: number | null = null
|
|
75
|
+
if (/^\d+$/.test(host)) n = Number(host)
|
|
76
|
+
else if (/^0x[0-9a-f]+$/i.test(host)) n = Number.parseInt(host.slice(2), 16)
|
|
77
|
+
else if (/^0[0-7]+$/.test(host)) n = Number.parseInt(host.slice(1), 8)
|
|
78
|
+
if (n === null || !Number.isSafeInteger(n) || n < 0 || n > 0xffffffff) return null
|
|
79
|
+
return toDotQuad(n)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 展开 IPv6 压缩形式为 8 组 16 位整数(NaN 标记非法段),解析失败返回 null。
|
|
84
|
+
* WHATWG URL 会把 IPv4-mapped 的点分十进制归一为十六进制组(::ffff:127.0.0.1 → ::ffff:7f00:1),
|
|
85
|
+
* 但仍保留点分十进制分支,防止上游未规范化时漏判。
|
|
86
|
+
*/
|
|
87
|
+
function expandIPv6(addr: string): number[] | null {
|
|
88
|
+
if (!addr.includes(":")) return null
|
|
89
|
+
const halves = addr.split("::")
|
|
90
|
+
if (halves.length > 2) return null
|
|
91
|
+
const toGroups = (seg: string): number[] =>
|
|
92
|
+
seg === ""
|
|
93
|
+
? []
|
|
94
|
+
: seg.split(":").flatMap((t) => {
|
|
95
|
+
if (t.includes(".")) {
|
|
96
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t)
|
|
97
|
+
if (!m) return [NaN]
|
|
98
|
+
const n =
|
|
99
|
+
(Number(m[1]) << 24) | (Number(m[2]) << 16) | (Number(m[3]) << 8) | Number(m[4])
|
|
100
|
+
return [(n >>> 16) & 0xffff, n & 0xffff]
|
|
101
|
+
}
|
|
102
|
+
const v = Number.parseInt(t, 16)
|
|
103
|
+
return [v > 0xffff || Number.isNaN(v) ? NaN : v]
|
|
104
|
+
})
|
|
105
|
+
const head = toGroups(halves[0])
|
|
106
|
+
const tail = toGroups(halves[1] ?? "")
|
|
107
|
+
if (head.includes(NaN) || tail.includes(NaN)) return null
|
|
108
|
+
if (halves.length === 1 && head.length !== 8) return null
|
|
109
|
+
if (head.length + tail.length > 8) return null
|
|
110
|
+
return [...head, ...Array.from({ length: 8 - head.length - tail.length }, () => 0), ...tail]
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 判定 IPv6 是否落在私网/保留段。SSRF 最经典绕过是 IPv4-mapped(::ffff:0:0/96)
|
|
115
|
+
* 伪装成 IPv6 直连回环/内网/云元数据,必须按末两组还原 32 位后再走 IPv4 判定。
|
|
116
|
+
*/
|
|
117
|
+
function isPrivateIPv6(addr: string): boolean {
|
|
118
|
+
const g = expandIPv6(addr)
|
|
119
|
+
if (!g) return false
|
|
120
|
+
const first = g[0]
|
|
121
|
+
if (first === 0 && g.every((v) => v === 0)) return true // :: 未指定(等同 0.0.0.0)
|
|
122
|
+
if (first === 0 && g.slice(1, 7).every((v) => v === 0) && g[7] === 1) return true // ::1 回环
|
|
123
|
+
if (first >= 0xfe80 && first <= 0xfebf) return true // fe80::/10 链路本地
|
|
124
|
+
if (first >= 0xfc00 && first <= 0xfdff) return true // fc00::/7 ULA 私有段
|
|
125
|
+
// 内嵌 IPv4 统一判定:::/96 兼容、::ffff:0:0/96 映射与翻译三种形态。
|
|
126
|
+
// 结构一致——前 6 组至多一个 0xffff 标记、标记之前全零、末两组为 32 位 IPv4。
|
|
127
|
+
// 注意不能只用 indexOf(0xffff) 判定:compatible 形态无 ffff 标记会漏拦。
|
|
128
|
+
const ffffIdx = g.indexOf(0xffff)
|
|
129
|
+
const markerCount = g.slice(0, 6).filter((v) => v === 0xffff).length
|
|
130
|
+
const prefixSlice = ffffIdx === -1 ? g.slice(0, 6) : g.slice(0, ffffIdx)
|
|
131
|
+
const prefixAllZero = prefixSlice.every((v) => v === 0)
|
|
132
|
+
const isEmbeddedIPv4 = ffffIdx <= 5 && markerCount <= 1 && prefixAllZero
|
|
133
|
+
if (isEmbeddedIPv4) {
|
|
134
|
+
return isPrivateIPv4(toDotQuad((g[6] << 16) | g[7]))
|
|
135
|
+
}
|
|
136
|
+
return false
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 校验 fetch 目标 URL 可访问,通过则返回规范化后的 URL 供 fetch 使用。
|
|
141
|
+
* 不抛异常即视为放行;违规抛 FetchGuardError 携带原因说明。
|
|
142
|
+
*/
|
|
143
|
+
export function assertFetchableUrl(
|
|
144
|
+
input: string,
|
|
145
|
+
options: FetchGuardOptions = {},
|
|
146
|
+
): URL {
|
|
147
|
+
let url: URL
|
|
148
|
+
try {
|
|
149
|
+
url = new URL(input)
|
|
150
|
+
} catch {
|
|
151
|
+
throw new FetchGuardError(input, "无效 URL")
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
155
|
+
throw new FetchGuardError(input, `协议 ${url.protocol} 不在允许范围(仅 http/https)`)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// IPv6 主机在 WHATWG URL 中带方括号([::1]),剥离后与判定规则对齐
|
|
159
|
+
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "")
|
|
160
|
+
|
|
161
|
+
// 先过一遍整数形式归一化,再判定私网,防止十六进制等混淆绕过点分十进制正则。
|
|
162
|
+
// 含冒号即 IPv6 字面量,交由 IPv6 判定(含 IPv4-mapped 还原),两者互斥不叠加
|
|
163
|
+
const isPrivate =
|
|
164
|
+
host === "localhost" ||
|
|
165
|
+
host.endsWith(".localhost") ||
|
|
166
|
+
host.endsWith(".local") ||
|
|
167
|
+
host.endsWith(".internal") ||
|
|
168
|
+
(host.includes(":") ? isPrivateIPv6(host) : isPrivateIPv4(normalizeIntegerIp(host) ?? host))
|
|
169
|
+
|
|
170
|
+
if (isPrivate && !options.allowPrivate) {
|
|
171
|
+
throw new FetchGuardError(input, "私网/回环/链路本地地址被 SSRF 防护拒绝")
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (options.allowedHosts && !options.allowedHosts.includes(host)) {
|
|
175
|
+
throw new FetchGuardError(input, `主机 ${host} 不在白名单`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return url
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 主机是否为 IP 字面量(同步判定已覆盖,无需 DNS 解析复检) */
|
|
182
|
+
function isIpLiteral(host: string): boolean {
|
|
183
|
+
return host.includes(":") || /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || /^\d+$/.test(host) ||
|
|
184
|
+
/^0x[0-9a-f]+$/i.test(host) || /^0[0-7]+$/.test(host)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 解析后地址是否命中私网/回环/链路本地/元数据段(IPv4 与 IPv6 统一入口) */
|
|
188
|
+
function isPrivateResolvedAddress(address: string): boolean {
|
|
189
|
+
if (address.includes(":")) return isPrivateIPv6(address)
|
|
190
|
+
return isPrivateIPv4(normalizeIntegerIp(address) ?? address)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* DNS 解析复检(2026-10 审计 🟠 加固,可选项;assertFetchableUrl 的异步深检版):
|
|
195
|
+
* 字面量判定之外,把域名解析出的**全部** A/AAAA 记录逐个过私网判定,堵
|
|
196
|
+
* 「公网域名 A 记录指向 127.0.0.1 / 169.254.169.254」的字面量绕过面。
|
|
197
|
+
*
|
|
198
|
+
* ⚠ 残余 TOCTOU(DNS rebinding):本函数校验后、实际 fetch 前存在二次解析窗口,
|
|
199
|
+
* 攻击者可用 TTL 0 动态 DNS 令两次解析不同。彻底闭环需自定义 undici Agent
|
|
200
|
+
* 在 connect 期按本函数解析结果 pin IP(SNI/Host 分离),改动面大未实施;
|
|
201
|
+
* 调用方对高危端点可将本函数与 fetch 间延迟压到最低,并在网关层叠加 egress
|
|
202
|
+
* 白名单。故意**不做**进程内解析缓存——缓存「安全」判定会拉长 rebinding 窗口,
|
|
203
|
+
* 换取的延迟收益对本守卫的非热路径不值得。
|
|
204
|
+
*
|
|
205
|
+
* 签名语义:与 assertFetchableUrl 同参同返回(复用其全部字面量判定),
|
|
206
|
+
* 仅额外追加解析复检;新调用方(用户可控 URL 的 fetch 出口)应优先用本函数。
|
|
207
|
+
*/
|
|
208
|
+
export async function assertFetchableUrlResolved(
|
|
209
|
+
input: string,
|
|
210
|
+
options: FetchGuardOptions = {},
|
|
211
|
+
): Promise<URL> {
|
|
212
|
+
const url = assertFetchableUrl(input, options)
|
|
213
|
+
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "")
|
|
214
|
+
if (isIpLiteral(host)) return url
|
|
215
|
+
|
|
216
|
+
// LookupOptions 无 signal(Node 24 类型):race 一个 3s 定时器,DNS 挂起时不阻塞请求
|
|
217
|
+
const addresses = await Promise.race([
|
|
218
|
+
import("node:dns/promises").then(({ lookup }) =>
|
|
219
|
+
lookup(host, { all: true, verbatim: true }),
|
|
220
|
+
),
|
|
221
|
+
new Promise<never>((_, reject) =>
|
|
222
|
+
setTimeout(() => reject(new FetchGuardError(input, `DNS 解析超时`)), 3000),
|
|
223
|
+
),
|
|
224
|
+
])
|
|
225
|
+
if (addresses.length === 0) {
|
|
226
|
+
throw new FetchGuardError(input, `主机 ${host} 无 DNS 解析记录`)
|
|
227
|
+
}
|
|
228
|
+
if (options.allowPrivate) return url // 显式放行私网:解析复检同语义豁免
|
|
229
|
+
|
|
230
|
+
for (const addr of addresses) {
|
|
231
|
+
if (isPrivateResolvedAddress(addr.address)) {
|
|
232
|
+
throw new FetchGuardError(
|
|
233
|
+
input,
|
|
234
|
+
`DNS 解析结果 ${addr.address} 落在私网/回环/链路本地/元数据段,SSRF 防护拒绝`,
|
|
235
|
+
)
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return url
|
|
239
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// @allbluecn/dsh-compat —— DSH 插件兼容内核(私有包,源码直消费)。
|
|
2
|
+
// 包边界即纯度边界:禁 import prisma / serverFns / app 代码(规格 §4 P4)。
|
|
3
|
+
// 根 index:patch 数据原语(纯)+ 组装门面 assembleProfile / 兼容面 surface(服务端组装入口,
|
|
4
|
+
// 值导入会拉入 ai-harness 值链——仅 define.server 等服务端语境消费)。
|
|
5
|
+
// fetch-guard 等需隔离的工具走 package.json exports 子路径(如 ./guard/assert-fetchable-url),
|
|
6
|
+
// 不经根 index,故不被 assembleProfile 的 ai-harness 值链影响。
|
|
7
|
+
export const DSH_COMPAT_PACKAGE = '@allbluecn/dsh-compat' as const
|
|
8
|
+
|
|
9
|
+
// --- patch 数据原语(yaml 解析 / 逐 key 合并 / !!js 白名单求值)---
|
|
10
|
+
export { applyPatches } from './patch/merge'
|
|
11
|
+
export { parsePatchYaml } from './patch/yaml'
|
|
12
|
+
export { evalDisabled, evalPatchExpression } from './patch/eval'
|
|
13
|
+
export { extractInsert } from './patch/types'
|
|
14
|
+
export type { PatchLine, PatchFile } from './patch/types'
|
|
15
|
+
|
|
16
|
+
// --- 组装门面(F1-5,规格 §4.1.1:外部 API 只有一个门面 assembleProfile)---
|
|
17
|
+
// assembleProfile 值导入会拉入 compat(含 ai-harness definePlugin 值链)。这符合门面
|
|
18
|
+
// 定位:assembleProfile 是**服务端组装入口**,只在 define.server 调用。fetch-guard 子
|
|
19
|
+
// 路径隔离纪律仍成立——web 侧 fetch-guard shim 走 `./guard/assert-fetchable-url` 子路径
|
|
20
|
+
// (见 package.json exports),不经根 index,故不受 assembleProfile 拉入 ai-harness 影响。
|
|
21
|
+
export { assembleProfile } from './assemble/assemble'
|
|
22
|
+
export type {
|
|
23
|
+
AssembleProfileOptions,
|
|
24
|
+
AssembleProfileResult,
|
|
25
|
+
} from './assemble/assemble'
|
|
26
|
+
// resolver 协议(F2-2 union):PluginResolver(= CordisModuleResolver 别名)+ 内置静态
|
|
27
|
+
// 工厂结果 BuiltinFactory。define.server(F2-2b)建 `@allblue/*` → BuiltinFactory 的
|
|
28
|
+
// resolver 注入 assembleProfile,消费这两个类型。
|
|
29
|
+
export type {
|
|
30
|
+
BuiltinFactory,
|
|
31
|
+
PluginResolver,
|
|
32
|
+
PluginResolverResult,
|
|
33
|
+
} from './assemble/resolve'
|
|
34
|
+
export type { CordisModuleResolver } from './assemble/resolve'
|
|
35
|
+
export type { AssemblyReport } from './report'
|
|
36
|
+
export type {
|
|
37
|
+
CordisFs,
|
|
38
|
+
CordisL1Services,
|
|
39
|
+
CordisPluginModule,
|
|
40
|
+
CordisShell,
|
|
41
|
+
CordisShellExecOptions,
|
|
42
|
+
CordisShellExecResult,
|
|
43
|
+
CordisSandbox,
|
|
44
|
+
L1ServicesFactory,
|
|
45
|
+
} from './compat/context'
|
|
46
|
+
export {
|
|
47
|
+
DSH_COMPAT_SURFACE,
|
|
48
|
+
DSH_COMPAT_SURFACE_VERSION,
|
|
49
|
+
L0_PROVIDED_SERVICE_KEYS,
|
|
50
|
+
assertL0Surface,
|
|
51
|
+
} from './surface'
|
|
52
|
+
export type { L0SurfaceCandidate } from './surface'
|