dsh-net-consent 0.0.0-stage → 1.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 +21 -0
- package/README.md +78 -2
- package/client.js +260 -0
- package/cordis.patch.yml +13 -0
- package/index.js +573 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fuqing
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-net-consent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[]()
|
|
4
|
+
[]()
|
|
5
|
+
|
|
6
|
+
联网闸门:会话里 Agent 发起的联网,都要用户来批准
|
|
7
|
+
|
|
8
|
+
## 使用场景
|
|
9
|
+
|
|
10
|
+
需要手动控制联网行为/流量成本。弱网/漫游/卫星/海事
|
|
11
|
+
|
|
12
|
+
> 这是一套**审批/拦截**工具,不是流量计数器。它只审查不统计。有统计观测需求请使用[dsh-traffic-statistics](https://github.com/hsushjk/dsh-traffic-statistics)
|
|
13
|
+
|
|
14
|
+
## 审什么
|
|
15
|
+
|
|
16
|
+
会话自己发起的:
|
|
17
|
+
|
|
18
|
+
| 层 | 覆盖 | 策略键 |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| 工具 | `web_fetch`、`web_search`、浏览器 / Playwright 类工具、带 http(s) URL 的第三方插件工具 | `mode` |
|
|
21
|
+
| 命令行 | `curl`、`wget`、`ssh`、`scp`、`rsync`、`git clone`、`pnpm install`、`pip install`、`apt`、`snap refresh`、`pacman -S`、`svn checkout` … | `shellMode` |
|
|
22
|
+
|
|
23
|
+
这些除外:聊天请求、插件市场与插件详情的后台拉取、更新检查、遥测。这些不经过会话工具,也就不在插件的职责里。插件不包 `globalThis.fetch`,不改 `node:http(s).request`,只挂一个 `tools/pre-execute` 监听。
|
|
24
|
+
|
|
25
|
+
## 策略
|
|
26
|
+
|
|
27
|
+
策略为 **放行 / 每次询问 / 拒绝**,工具层与命令行层各有一档(`mode` / `shellMode`)。
|
|
28
|
+
|
|
29
|
+
- `allow`:不弹卡片。
|
|
30
|
+
- `ask`:弹卡片(默认)。
|
|
31
|
+
- `deny`:直接阻止,不弹卡片。
|
|
32
|
+
|
|
33
|
+
`deny` 优先于「本会话放行」;本机 / 局域网地址与白名单命中项先放行。
|
|
34
|
+
|
|
35
|
+
## 审批卡片
|
|
36
|
+
|
|
37
|
+
三个选项:`放行一次`、`本会话放行该目标`、`拒绝`。点「其它」填文字则默认拒绝,并把你的原话回给模型让它改路线。
|
|
38
|
+
|
|
39
|
+
- 卡片包括 AI 的用途自述(可关),命令行走命令原文,其它工具走调用参数摘要。
|
|
40
|
+
- 卡片末尾写明本次时限与超时动作,例如「30 秒内未选择将自动拒绝。」等待时间与超时动作(自动拒绝 / 自动放行)都在设置里改。
|
|
41
|
+
- 子代理内无法弹卡片(DSH 禁止子代理向用户提问),按拒绝处理并提示让主代理来做。
|
|
42
|
+
|
|
43
|
+
## 白名单
|
|
44
|
+
|
|
45
|
+
一条只用一种写法,命中即免问:
|
|
46
|
+
|
|
47
|
+
| 写法 | 例子 | 命中方式 |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| 工具名 | `web_fetch`、`browser_*` | 工具名全等;结尾 `*` 作前缀通配 |
|
|
50
|
+
| 命令名 | `curl`、`git`、`pnpm` | 在命令文本里按整词匹配 |
|
|
51
|
+
| 域名 | `example.com`、`*.example.com` | 该次调用的主机全部命中才放行 |
|
|
52
|
+
| IP | `8.8.8.8`、`::1` | 精确匹配 |
|
|
53
|
+
|
|
54
|
+
白名单是显式例外表,先于 `deny` 策略生效。
|
|
55
|
+
|
|
56
|
+
## 安全
|
|
57
|
+
|
|
58
|
+
设置页的状态接口挂在 DSH 的 `/api` 通道上(`ctx.connection.fetch.register` 的精确路由)。Host / Origin 校验与浏览器认证由 DSH 自己完成,只有已认证的属主会话能读写;插件不再向 `webServer` 注册裸路由。
|
|
59
|
+
|
|
60
|
+
## 配置
|
|
61
|
+
|
|
62
|
+
`cordis.patch.yml` 里 `net-consent` 行的 `config:`:
|
|
63
|
+
|
|
64
|
+
| 键 | 默认 | 含义 |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `mode` | `ask` | 工具层:`allow` / `ask` / `deny` |
|
|
67
|
+
| `shellMode` | `ask` | 命令行联网动词:`allow` / `ask` / `deny` |
|
|
68
|
+
| `allowLocal` | `true` | 回环与局域网地址免问 |
|
|
69
|
+
| `askTimeoutMs` | `30000` | 等用户回答的超时(5s–10min) |
|
|
70
|
+
| `onTimeout` | `deny` | 超时后:`deny` 自动拒绝 / `allow` 自动放行 |
|
|
71
|
+
| `audit` | `true` | 写审计 jsonl |
|
|
72
|
+
| `auditRetentionDays` | `30` | 审计保留天数,`0` = 永久 |
|
|
73
|
+
| `allowlist` | `[]` | 工具 / 命令 / 域名 / IP,见上表 |
|
|
74
|
+
| `purposes` | `true` | 卡片展示模型自述用途 |
|
|
75
|
+
| `internalTools` | 一长串只读工具 | 完全不看的工具(UI 不可改) |
|
|
76
|
+
|
|
77
|
+
## 审计
|
|
78
|
+
|
|
79
|
+
每次判定写一行 JSON 到 `~/.dsh/net-consent/audit/YYYY-MM-DD.jsonl`,`via` 字段区分放行 / 拒绝原因(`once`、`session-grant`、`user-reject`、`policy=deny`、`timeout-allow`、`NET_CONSENT_TIMEOUT` …)。超过保留天数的按天文件在启动时与写入后自动清理。
|
package/client.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'dsh-net-consent',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const React = require('react')
|
|
5
|
+
const h = React.createElement
|
|
6
|
+
const { useState, useEffect, useCallback } = React
|
|
7
|
+
|
|
8
|
+
const STATE_URL = '/api/net-consent/state'
|
|
9
|
+
|
|
10
|
+
const store = {
|
|
11
|
+
value: null,
|
|
12
|
+
error: null,
|
|
13
|
+
listeners: new Set(),
|
|
14
|
+
emit() { for (const fn of this.listeners) fn(this.value) },
|
|
15
|
+
subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn) },
|
|
16
|
+
async load() {
|
|
17
|
+
try {
|
|
18
|
+
const res = await fetch(STATE_URL, { headers: { accept: 'application/json' } })
|
|
19
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
20
|
+
this.value = await res.json()
|
|
21
|
+
this.error = null
|
|
22
|
+
} catch (error) { this.error = String(error && error.message || error) }
|
|
23
|
+
this.emit()
|
|
24
|
+
},
|
|
25
|
+
async patch(patch) {
|
|
26
|
+
const previous = this.value
|
|
27
|
+
this.value = { ...(this.value || {}), ...patch }
|
|
28
|
+
this.emit()
|
|
29
|
+
try {
|
|
30
|
+
const res = await fetch(STATE_URL, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: { 'content-type': 'application/json' },
|
|
33
|
+
body: JSON.stringify(patch),
|
|
34
|
+
})
|
|
35
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
36
|
+
this.value = await res.json()
|
|
37
|
+
this.error = null
|
|
38
|
+
} catch (error) {
|
|
39
|
+
this.value = previous
|
|
40
|
+
this.error = String(error && error.message || error)
|
|
41
|
+
}
|
|
42
|
+
this.emit()
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
store.load()
|
|
46
|
+
setInterval(() => store.load(), 5000)
|
|
47
|
+
|
|
48
|
+
function useStore() {
|
|
49
|
+
const [value, setValue] = useState(store.value)
|
|
50
|
+
useEffect(() => {
|
|
51
|
+
const off = store.subscribe(next => setValue(next))
|
|
52
|
+
if (!store.value) store.load()
|
|
53
|
+
return off
|
|
54
|
+
}, [])
|
|
55
|
+
return [value, store.error]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const POLICY = [['allow', '放行'], ['ask', '每次询问'], ['deny', '拒绝']]
|
|
59
|
+
const policyOf = value => (value === 'allow' || value === 'deny' ? value : 'ask')
|
|
60
|
+
const labelOf = value => (POLICY.find(([key]) => key === policyOf(value)) ?? POLICY[1])[1]
|
|
61
|
+
|
|
62
|
+
const TIMEOUTS = [
|
|
63
|
+
['15000', '15 秒'], ['30000', '30 秒'], ['60000', '1 分钟'],
|
|
64
|
+
['180000', '3 分钟'], ['600000', '10 分钟'],
|
|
65
|
+
]
|
|
66
|
+
const TIMEOUT_ACTIONS = [['deny', '自动拒绝'], ['allow', '自动放行']]
|
|
67
|
+
const RETENTIONS = [['7', '7 天'], ['30', '30 天'], ['90', '90 天'], ['0', '永久保留']]
|
|
68
|
+
|
|
69
|
+
const S = {
|
|
70
|
+
pill: (on) => ({
|
|
71
|
+
display: 'inline-flex', alignItems: 'center', gap: 6,
|
|
72
|
+
height: 28, padding: '0 10px', borderRadius: 14, cursor: 'pointer',
|
|
73
|
+
border: '1px solid ' + (on ? 'rgba(64,158,255,0.55)' : 'rgba(128,128,128,0.35)'),
|
|
74
|
+
background: on ? 'rgba(64,158,255,0.14)' : 'transparent',
|
|
75
|
+
color: on ? 'rgb(64,158,255)' : 'inherit',
|
|
76
|
+
fontSize: 12, lineHeight: '26px', whiteSpace: 'nowrap', userSelect: 'none',
|
|
77
|
+
fontFamily: 'inherit',
|
|
78
|
+
}),
|
|
79
|
+
dot: (on) => ({
|
|
80
|
+
width: 7, height: 7, borderRadius: 4,
|
|
81
|
+
background: on ? 'rgb(64,158,255)' : 'rgba(128,128,128,0.6)',
|
|
82
|
+
}),
|
|
83
|
+
page: { padding: '24px 28px', maxWidth: 680, fontSize: 13, lineHeight: 1.6 },
|
|
84
|
+
h1: { fontSize: 16, fontWeight: 600, margin: '0 0 4px' },
|
|
85
|
+
lead: { opacity: 0.65, margin: '0 0 20px' },
|
|
86
|
+
group: { margin: '0 0 22px' },
|
|
87
|
+
groupTitle: { fontSize: 12, fontWeight: 600, opacity: 0.55, letterSpacing: '0.04em', margin: '0 0 8px' },
|
|
88
|
+
row: {
|
|
89
|
+
display: 'flex', alignItems: 'flex-start', gap: 10,
|
|
90
|
+
padding: '9px 0', borderTop: '1px solid rgba(128,128,128,0.16)',
|
|
91
|
+
},
|
|
92
|
+
rowText: { flex: 1, minWidth: 0 },
|
|
93
|
+
rowName: { fontSize: 13 },
|
|
94
|
+
rowHint: { fontSize: 12, opacity: 0.55, marginTop: 2 },
|
|
95
|
+
select: {
|
|
96
|
+
fontSize: 12, padding: '3px 6px', borderRadius: 6, fontFamily: 'inherit',
|
|
97
|
+
border: '1px solid rgba(128,128,128,0.35)', background: 'transparent', color: 'inherit',
|
|
98
|
+
},
|
|
99
|
+
textarea: {
|
|
100
|
+
fontSize: 12, padding: '6px 8px', borderRadius: 6, fontFamily: 'inherit',
|
|
101
|
+
border: '1px solid rgba(128,128,128,0.35)', background: 'transparent', color: 'inherit',
|
|
102
|
+
width: '100%', minHeight: 88, resize: 'vertical', lineHeight: 1.6,
|
|
103
|
+
},
|
|
104
|
+
footer: {
|
|
105
|
+
display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
|
|
106
|
+
fontSize: 12, opacity: 0.55, marginTop: 26,
|
|
107
|
+
},
|
|
108
|
+
warn: { fontSize: 12, color: 'rgb(230,160,60)', marginTop: 8 },
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function ConsentToggle() {
|
|
112
|
+
const [value, error] = useStore()
|
|
113
|
+
const mode = policyOf(value?.mode)
|
|
114
|
+
const shellMode = policyOf(value?.shellMode)
|
|
115
|
+
const on = mode !== 'allow' || shellMode !== 'allow'
|
|
116
|
+
const title = value
|
|
117
|
+
? `工具 ${labelOf(mode)} · 命令行 ${labelOf(shellMode)};本次已询问 ${value?.stats?.asked ?? 0} 次。点击${on ? '关闭' : '开启'}联网审查。`
|
|
118
|
+
: (error || '正在读取联网审查状态…')
|
|
119
|
+
const flip = useCallback(() => {
|
|
120
|
+
const next = on ? 'allow' : 'ask'
|
|
121
|
+
store.patch({ mode: next, shellMode: next })
|
|
122
|
+
}, [on])
|
|
123
|
+
return h('button', {
|
|
124
|
+
type: 'button',
|
|
125
|
+
onClick: flip,
|
|
126
|
+
title,
|
|
127
|
+
style: S.pill(on),
|
|
128
|
+
'aria-pressed': on,
|
|
129
|
+
},
|
|
130
|
+
h('span', { style: S.dot(on) }),
|
|
131
|
+
h('span', null, '联网审查'),
|
|
132
|
+
h('span', { style: { opacity: on ? 0.85 : 0.55 } }, on ? '开' : '关'),
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function Row({ name, hint, children }) {
|
|
137
|
+
return h('div', { style: S.row },
|
|
138
|
+
h('div', { style: S.rowText },
|
|
139
|
+
h('div', { style: S.rowName }, name),
|
|
140
|
+
hint ? h('div', { style: S.rowHint }, hint) : null,
|
|
141
|
+
),
|
|
142
|
+
h('div', { style: { flex: 'none', paddingTop: 1 } }, children),
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function Select({ value, options, onChange }) {
|
|
147
|
+
return h('select', {
|
|
148
|
+
style: S.select,
|
|
149
|
+
value,
|
|
150
|
+
onChange: event => onChange(event.target.value),
|
|
151
|
+
}, options.map(([key, label]) => h('option', { key, value: key }, label)))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function Check({ value, onChange }) {
|
|
155
|
+
return h('input', {
|
|
156
|
+
type: 'checkbox',
|
|
157
|
+
checked: !!value,
|
|
158
|
+
onChange: event => onChange(event.target.checked),
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function PolicySelect({ value, onChange }) {
|
|
163
|
+
return h(Select, { value: policyOf(value), options: POLICY, onChange })
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function NetConsentSection() {
|
|
167
|
+
const [value, error] = useStore()
|
|
168
|
+
if (!value) {
|
|
169
|
+
return h('div', { style: S.page },
|
|
170
|
+
h('div', { style: S.h1 }, '联网审查'),
|
|
171
|
+
h('div', { style: S.lead }, error ? '读不到状态:' + error : '正在读取…'),
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
const set = patch => store.patch(patch)
|
|
175
|
+
const stats = value.stats ?? {}
|
|
176
|
+
return h('div', { style: S.page },
|
|
177
|
+
h('div', { style: S.h1 }, '联网审查'),
|
|
178
|
+
|
|
179
|
+
h('div', { style: S.group },
|
|
180
|
+
h('div', { style: S.groupTitle }, '联网动作'),
|
|
181
|
+
h('div', null,
|
|
182
|
+
h(Row, { name: '工具', hint: 'web_fetch、web_search、浏览器工具、带 URL 的第三方工具' },
|
|
183
|
+
h(PolicySelect, { value: value.mode, onChange: next => set({ mode: next }) })),
|
|
184
|
+
h(Row, { name: '命令行', hint: 'curl、wget、git clone、pnpm install 等' },
|
|
185
|
+
h(PolicySelect, { value: value.shellMode, onChange: next => set({ shellMode: next }) })),
|
|
186
|
+
h(Row, { name: '本机与局域网地址免询问', hint: '127.0.0.1、192.168.x 等' },
|
|
187
|
+
h(Check, { value: value.allowLocal !== false, onChange: next => set({ allowLocal: next }) })),
|
|
188
|
+
)),
|
|
189
|
+
|
|
190
|
+
h('div', { style: S.group },
|
|
191
|
+
h('div', { style: S.groupTitle }, '白名单'),
|
|
192
|
+
h('div', null,
|
|
193
|
+
h(Row, { name: '免问条目', hint: '一行一条:工具名、命令名、域名或 IP。例:web_fetch、curl、example.com、*.example.com、8.8.8.8' },
|
|
194
|
+
h('textarea', {
|
|
195
|
+
defaultValue: (value.allowlist || []).join('\n'),
|
|
196
|
+
placeholder: 'web_fetch\ncurl\nexample.com\n*.example.com\n8.8.8.8',
|
|
197
|
+
onBlur: event => set({
|
|
198
|
+
allowlist: event.target.value.split(/[\n,,]/).map(s => s.trim()).filter(Boolean),
|
|
199
|
+
}),
|
|
200
|
+
style: S.textarea,
|
|
201
|
+
})),
|
|
202
|
+
)),
|
|
203
|
+
|
|
204
|
+
h('div', { style: S.group },
|
|
205
|
+
h('div', { style: S.groupTitle }, '审批卡片'),
|
|
206
|
+
h('div', null,
|
|
207
|
+
h(Row, { name: '等待时间', hint: '卡片上写明本次时限' },
|
|
208
|
+
h(Select, {
|
|
209
|
+
value: String(value.askTimeoutMs ?? 30000),
|
|
210
|
+
options: TIMEOUTS,
|
|
211
|
+
onChange: next => set({ askTimeoutMs: Number(next) }),
|
|
212
|
+
})),
|
|
213
|
+
h(Row, { name: '超时后', hint: '倒计时结束仍未选择时执行' },
|
|
214
|
+
h(Select, {
|
|
215
|
+
value: value.onTimeout === 'allow' ? 'allow' : 'deny',
|
|
216
|
+
options: TIMEOUT_ACTIONS,
|
|
217
|
+
onChange: next => set({ onTimeout: next }),
|
|
218
|
+
})),
|
|
219
|
+
h(Row, { name: '显示 AI 用途自述', hint: '卡片展示模型联网前的说明' },
|
|
220
|
+
h(Check, { value: value.purposes !== false, onChange: next => set({ purposes: next }) })),
|
|
221
|
+
)),
|
|
222
|
+
|
|
223
|
+
h('div', { style: S.group },
|
|
224
|
+
h('div', { style: S.groupTitle }, '审计'),
|
|
225
|
+
h('div', null,
|
|
226
|
+
h(Row, { name: '记录审计日志', hint: '~/.dsh/net-consent/audit/,按天分文件' },
|
|
227
|
+
h(Check, { value: value.audit !== false, onChange: next => set({ audit: next }) })),
|
|
228
|
+
h(Row, { name: '保留天数', hint: '过期文件自动清理' },
|
|
229
|
+
h(Select, {
|
|
230
|
+
value: String(value.auditRetentionDays ?? 30),
|
|
231
|
+
options: RETENTIONS,
|
|
232
|
+
onChange: next => set({ auditRetentionDays: Number(next) }),
|
|
233
|
+
})),
|
|
234
|
+
)),
|
|
235
|
+
|
|
236
|
+
error ? h('div', { style: S.warn }, '上次保存失败:' + error) : null,
|
|
237
|
+
|
|
238
|
+
h('div', { style: S.footer },
|
|
239
|
+
h('span', null,
|
|
240
|
+
`本次运行:询问 ${stats.asked ?? 0} 次,放行 ${stats.allowed ?? 0} 次,拒绝 ${stats.denied ?? 0} 次。`),
|
|
241
|
+
h('span', null, value.version ? 'v' + value.version : ''),
|
|
242
|
+
),
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
inject: ['slots'],
|
|
248
|
+
apply(ctx) {
|
|
249
|
+
ctx.slots.inject('conversation.input.right', () => ctx.slots.register(
|
|
250
|
+
{ name: 'conversation.input.right', id: 'net-consent-toggle', order: 10 },
|
|
251
|
+
ConsentToggle,
|
|
252
|
+
))
|
|
253
|
+
ctx.slots.inject('settings.section', () => ctx.slots.register(
|
|
254
|
+
{ name: 'settings.section', id: 'net-consent', order: 50, label: '联网审查' },
|
|
255
|
+
NetConsentSection,
|
|
256
|
+
))
|
|
257
|
+
},
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
})
|
package/cordis.patch.yml
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import { appendFile, mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
export const name = 'net-consent'
|
|
6
|
+
|
|
7
|
+
export const inject = ['tools', 'userQuestions']
|
|
8
|
+
|
|
9
|
+
const STATE_DIR = join(homedir(), '.dsh', 'net-consent')
|
|
10
|
+
const STATE_FILE = join(STATE_DIR, 'state.json')
|
|
11
|
+
const AUDIT_DIR = join(STATE_DIR, 'audit')
|
|
12
|
+
|
|
13
|
+
const POLICIES = ['allow', 'ask', 'deny']
|
|
14
|
+
const LEGACY_POLICY = { off: 'allow', observe: 'allow' }
|
|
15
|
+
|
|
16
|
+
export function normalizePolicy(value, fallback = 'ask') {
|
|
17
|
+
const mapped = LEGACY_POLICY[value] ?? value
|
|
18
|
+
return POLICIES.includes(mapped) ? mapped : fallback
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const DEFAULTS = {
|
|
22
|
+
mode: 'ask',
|
|
23
|
+
shellMode: 'ask',
|
|
24
|
+
allowLocal: true,
|
|
25
|
+
askTimeoutMs: 30000,
|
|
26
|
+
onTimeout: 'deny',
|
|
27
|
+
audit: true,
|
|
28
|
+
auditRetentionDays: 30,
|
|
29
|
+
allowlist: [],
|
|
30
|
+
purposes: true,
|
|
31
|
+
internalTools: [
|
|
32
|
+
'ask_user_question', 'todo_write', 'read', 'write', 'edit', 'glob', 'grep',
|
|
33
|
+
'skill', 'present', 'compress', 'decompress', 'acp_status', 'acp_cache',
|
|
34
|
+
'search_context', 'save_token_expand', 'wait_agent', 'send_message',
|
|
35
|
+
'list_agents', 'list_subagent_models', 'job_output', 'job_list', 'job_kill',
|
|
36
|
+
'terminal_read', 'terminal_list', 'terminal_close', 'user_terminal_list',
|
|
37
|
+
'user_terminal_read', 'working_directory', 'load_workspace_dependencies',
|
|
38
|
+
'get_goal', 'create_goal', 'update_goal', 'schedule_list', 'schedule_view',
|
|
39
|
+
'screen_view', 'desktop_control', 'desktop_sequence',
|
|
40
|
+
'acp_read_original_image', 'read_image', 'terminal_signal',
|
|
41
|
+
],
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const WRITABLE = [
|
|
45
|
+
'mode', 'shellMode', 'allowLocal', 'askTimeoutMs', 'onTimeout',
|
|
46
|
+
'audit', 'auditRetentionDays', 'allowlist', 'purposes',
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
const NET_TOOL = /(^web_(fetch|search)$)|(^fetch$)|(^http_)|(browser|playwright|puppeteer|websearch|search_web|selenium|chrome_|navigate)/i
|
|
50
|
+
|
|
51
|
+
const SHELL_TOOL = /^(pwsh|powershell|bash|sh|zsh|cmd|shell|terminal|exec|run_code|process|spawn)/i
|
|
52
|
+
|
|
53
|
+
const NET_VERB = new RegExp([
|
|
54
|
+
String.raw`\b(curl|wget|aria2c|yt-dlp|youtube-dl|axel|httpie|ncat|netcat|telnet|socat)\b`,
|
|
55
|
+
String.raw`(^|[\s;&|(])nc\s+(-|\d)`,
|
|
56
|
+
String.raw`\b(ssh|scp|sftp|rsync|ftp|tftp|ssh-keyscan)\b`,
|
|
57
|
+
String.raw`\bgit\s+(clone|fetch|pull|push|ls-remote|submodule|archive\s+--remote|remote\s+update)\b`,
|
|
58
|
+
String.raw`\b(pnpm|npm|yarn|bun|npx|pnpx|pipx|uvx)\b[^\n]{0,80}\b(install|i|add|update|up|upgrade|view|info|search|publish|pack|dlx|create)\b`,
|
|
59
|
+
String.raw`\bpip3?\s+(install|download|wheel)\b`,
|
|
60
|
+
String.raw`\b(python|py|node)\b[^\n]{0,60}\b(urllib|requests|httpx|aiohttp|socket|fetch|https?\.request|axios|got|undici)\b`,
|
|
61
|
+
String.raw`\b(cargo|rustup|go|gem|composer|dotnet|nuget|choco|scoop|winget|brew|apt|apt-get|yum|dnf|apk|pacman)\b[^\n]{0,60}\b(install|add|update|upgrade|download|get|fetch|pull)\b`,
|
|
62
|
+
String.raw`\b(snap\s+(install|refresh|download)|flatpak\s+(install|update|remote-add)|pacman\s+-S|zypper\s+(in|install|update)|nix-env\s+-iA?|nix\s+(profile\s+install|flake\s+update)|apk\s+add)\b`,
|
|
63
|
+
String.raw`\b(lynx|w3m|links2|mosh|smbclient)\b`,
|
|
64
|
+
String.raw`\bsvn\s+(checkout|co|update|up|commit|export|ls|cat|log|diff|switch|import|merge)\b`,
|
|
65
|
+
String.raw`\b(docker|podman)\s+(pull|push|login|buildx)\b`,
|
|
66
|
+
String.raw`\b(kubectl|helm|aws|az|gcloud|gh|heroku|vercel|netlify|firebase|terraform|ansible|oci)\b`,
|
|
67
|
+
String.raw`(?<![\w-])(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm|Start-BitsTransfer|Test-NetConnection|tnc|Resolve-DnsName|nslookup|dig|ping|tracert|mtr)\b`,
|
|
68
|
+
String.raw`\b(openssl\s+s_client|ssrf|webhook)\b`,
|
|
69
|
+
].join('|'), 'i')
|
|
70
|
+
|
|
71
|
+
const URL_RE = /https?:\/\/([^\s'"`<>()/?#:]+)/gi
|
|
72
|
+
const SCP_RE = /\b[a-z0-9._-]+@([a-z0-9.-]+\.[a-z]{2,})[:-]/gi
|
|
73
|
+
|
|
74
|
+
const PRIVATE_HOST = /^(localhost|127\.\d+\.\d+\.\d+|0\.0\.0\.0|\[?::1\]?|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+)$/i
|
|
75
|
+
const PRIVATE_SUFFIX = /\.(local|lan|internal|home\.arpa|localhost)$/i
|
|
76
|
+
|
|
77
|
+
function isPrivateHost(host) {
|
|
78
|
+
const h = String(host).toLowerCase().replace(/^\[|\]$/g, '')
|
|
79
|
+
if (PRIVATE_HOST.test(h)) return true
|
|
80
|
+
if (PRIVATE_SUFFIX.test(h)) return true
|
|
81
|
+
if (!h.includes('.') && !h.includes(':')) return true
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function asStrings(value, out = [], depth = 0) {
|
|
86
|
+
if (depth > 3 || value === null || value === undefined) return out
|
|
87
|
+
if (typeof value === 'string') { out.push(value); return out }
|
|
88
|
+
if (Array.isArray(value)) { for (const v of value) asStrings(v, out, depth + 1); return out }
|
|
89
|
+
if (typeof value === 'object') { for (const v of Object.values(value)) asStrings(v, out, depth + 1) }
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function hostsIn(text) {
|
|
94
|
+
const hosts = new Set()
|
|
95
|
+
for (const m of String(text).matchAll(URL_RE)) hosts.add(m[1].toLowerCase())
|
|
96
|
+
for (const m of String(text).matchAll(SCP_RE)) hosts.add(m[1].toLowerCase())
|
|
97
|
+
return [...hosts]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isHostEntry(entry) {
|
|
101
|
+
const e = String(entry ?? '').trim()
|
|
102
|
+
if (!e) return false
|
|
103
|
+
if (e === '*' || e.startsWith('*.')) return true
|
|
104
|
+
if (e.includes(':')) return true
|
|
105
|
+
if (/^[\d.]+$/.test(e)) return true
|
|
106
|
+
if (/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(e)) return true
|
|
107
|
+
return /^localhost$/i.test(e)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function hostAllowed(host, list) {
|
|
111
|
+
const h = String(host ?? '').toLowerCase()
|
|
112
|
+
return (list ?? []).some(item => {
|
|
113
|
+
const p = String(item).toLowerCase().trim()
|
|
114
|
+
if (!p) return false
|
|
115
|
+
if (p === '*') return true
|
|
116
|
+
if (p.startsWith('*.')) return h === p.slice(2) || h.endsWith(p.slice(1))
|
|
117
|
+
return h === p || h.endsWith('.' + p)
|
|
118
|
+
})
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function toolMatches(tool, list) {
|
|
122
|
+
const t = String(tool ?? '').toLowerCase()
|
|
123
|
+
return (list ?? []).some(item => {
|
|
124
|
+
const p = String(item).toLowerCase().trim()
|
|
125
|
+
if (!p) return false
|
|
126
|
+
if (p === '*') return true
|
|
127
|
+
if (p.endsWith('*')) return t.startsWith(p.slice(0, -1))
|
|
128
|
+
return t === p
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function commandMatches(command, list) {
|
|
133
|
+
const text = String(command ?? '')
|
|
134
|
+
if (!text) return false
|
|
135
|
+
return (list ?? []).some(item => {
|
|
136
|
+
const p = String(item).trim()
|
|
137
|
+
if (!p || isHostEntry(p)) return false
|
|
138
|
+
const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
139
|
+
return new RegExp(`(?<![\\w.-])${escaped}(?![\\w.-])`, 'i').test(text)
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function classify(exec, cfg) {
|
|
144
|
+
const tool = String(exec.name ?? '')
|
|
145
|
+
const lower = tool.toLowerCase()
|
|
146
|
+
if ((cfg.internalTools ?? DEFAULTS.internalTools).some(t => lower === String(t).toLowerCase())) return null
|
|
147
|
+
|
|
148
|
+
const strings = asStrings(exec.arguments)
|
|
149
|
+
const joined = strings.join('\n')
|
|
150
|
+
const hosts = hostsIn(joined)
|
|
151
|
+
const preview = (strings.find(s => s.length > 3) ?? '').slice(0, 400)
|
|
152
|
+
|
|
153
|
+
if (NET_TOOL.test(tool)) return { network: true, kind: 'tool', hosts, preview }
|
|
154
|
+
if (SHELL_TOOL.test(tool)) {
|
|
155
|
+
const command = strings.join(' ')
|
|
156
|
+
if (NET_VERB.test(command) || hosts.length > 0) return { network: true, kind: 'shell', hosts, command, preview }
|
|
157
|
+
return null
|
|
158
|
+
}
|
|
159
|
+
if (hosts.length > 0) return { network: true, kind: 'tool', hosts, preview }
|
|
160
|
+
return null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function allowlisted(verdict, cfg) {
|
|
164
|
+
const entries = Array.isArray(cfg.allowlist) ? cfg.allowlist : []
|
|
165
|
+
if (entries.length === 0) return null
|
|
166
|
+
const tool = String(verdict?.tool ?? '').toLowerCase()
|
|
167
|
+
const hosts = verdict?.hosts ?? []
|
|
168
|
+
|
|
169
|
+
const toolHit = entries.find(e => !isHostEntry(e) && toolMatches(tool, [e]))
|
|
170
|
+
if (toolHit) return { entry: toolHit, kind: 'tool' }
|
|
171
|
+
|
|
172
|
+
if (hosts.length > 0) {
|
|
173
|
+
const hostEntries = entries.filter(isHostEntry)
|
|
174
|
+
if (hosts.every(h => hostAllowed(h, hostEntries))) return { entry: hostEntries.join(','), kind: 'host' }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (verdict?.kind === 'shell' && verdict.command) {
|
|
178
|
+
const commandHit = entries.find(e => !isHostEntry(e) && commandMatches(verdict.command, [e]))
|
|
179
|
+
if (commandHit) return { entry: commandHit, kind: 'command' }
|
|
180
|
+
}
|
|
181
|
+
return null
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function flattenText(value, depth = 0) {
|
|
185
|
+
if (depth > 4 || value === null || value === undefined) return ''
|
|
186
|
+
if (typeof value === 'string') return value
|
|
187
|
+
if (Array.isArray(value)) return value.map(v => flattenText(v, depth + 1)).filter(Boolean).join('\n')
|
|
188
|
+
if (typeof value === 'object') {
|
|
189
|
+
if (typeof value.text === 'string') return value.text
|
|
190
|
+
if (value.content !== undefined) return flattenText(value.content, depth + 1)
|
|
191
|
+
}
|
|
192
|
+
return ''
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function purposeOf(agent, limit = 600) {
|
|
196
|
+
try {
|
|
197
|
+
const events = agent?.session?.ownEvents?.() ?? agent?.session?.events?.() ?? []
|
|
198
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
199
|
+
const evt = events[i]
|
|
200
|
+
if (!evt || typeof evt !== 'object') continue
|
|
201
|
+
const role = evt.role ?? evt.message?.role ?? evt.data?.role
|
|
202
|
+
if (role && role !== 'assistant') continue
|
|
203
|
+
const text = flattenText([evt.text, evt.message?.content, evt.data?.content, evt.content].filter(Boolean)).trim()
|
|
204
|
+
if (text) return text.slice(0, limit)
|
|
205
|
+
}
|
|
206
|
+
} catch { }
|
|
207
|
+
return ''
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function sessionKey(exec) {
|
|
211
|
+
return String(exec.agent?.session?.id ?? exec.agent?.id ?? 'unknown')
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function writeAudit(entry) {
|
|
215
|
+
try {
|
|
216
|
+
await mkdir(AUDIT_DIR, { recursive: true })
|
|
217
|
+
const file = join(AUDIT_DIR, `${new Date().toISOString().slice(0, 10)}.jsonl`)
|
|
218
|
+
await appendFile(file, JSON.stringify(entry) + '\n', 'utf8')
|
|
219
|
+
} catch { }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function pruneAudit(days) {
|
|
223
|
+
const keep = Number(days)
|
|
224
|
+
if (!Number.isFinite(keep) || keep <= 0) return
|
|
225
|
+
let names
|
|
226
|
+
try { names = await readdir(AUDIT_DIR) } catch { return }
|
|
227
|
+
const cutoff = Date.now() - keep * 86400000
|
|
228
|
+
for (const file of names) {
|
|
229
|
+
const match = /^(\d{4}-\d{2}-\d{2})\.jsonl$/.exec(file)
|
|
230
|
+
if (!match) continue
|
|
231
|
+
const stamp = Date.parse(`${match[1]}T00:00:00Z`)
|
|
232
|
+
if (Number.isFinite(stamp) && stamp < cutoff) await unlink(join(AUDIT_DIR, file)).catch(() => {})
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function loadState() {
|
|
237
|
+
try { return JSON.parse(await readFile(STATE_FILE, 'utf8')) } catch { return {} }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function saveState(state) {
|
|
241
|
+
try {
|
|
242
|
+
await mkdir(STATE_DIR, { recursive: true })
|
|
243
|
+
await writeFile(STATE_FILE, JSON.stringify(state, null, 2), 'utf8')
|
|
244
|
+
return true
|
|
245
|
+
} catch { return false }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function migrate(raw) {
|
|
249
|
+
const state = { ...(raw ?? {}) }
|
|
250
|
+
let changed = false
|
|
251
|
+
if (!Array.isArray(state.allowlist)) { state.allowlist = Array.isArray(state.allowlist) ? state.allowlist : []; changed = true }
|
|
252
|
+
const legacy = [
|
|
253
|
+
...(Array.isArray(state.autoAllowHosts) ? state.autoAllowHosts : []),
|
|
254
|
+
...(Array.isArray(state.extraNetworkTools) ? state.extraNetworkTools : []),
|
|
255
|
+
].map(item => String(item).trim()).filter(Boolean)
|
|
256
|
+
for (const item of legacy) {
|
|
257
|
+
if (!state.allowlist.some(existing => String(existing).toLowerCase() === item.toLowerCase())) {
|
|
258
|
+
state.allowlist.push(item)
|
|
259
|
+
changed = true
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
for (const key of ['autoAllowHosts', 'extraNetworkTools', 'exemptHosts', 'hostMode', 'onHostTimeout']) {
|
|
263
|
+
if (key in state) { delete state[key]; changed = true }
|
|
264
|
+
}
|
|
265
|
+
return { state, changed }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const VERSION_PROMISE = readFile(new URL('./package.json', import.meta.url), 'utf8')
|
|
269
|
+
.then(text => {
|
|
270
|
+
const value = JSON.parse(text)?.version
|
|
271
|
+
return typeof value === 'string' && value ? value : ''
|
|
272
|
+
})
|
|
273
|
+
.catch(() => '')
|
|
274
|
+
|
|
275
|
+
export const _test = {
|
|
276
|
+
classify, hostsIn, isPrivateHost, purposeOf, DEFAULTS, normalizePolicy,
|
|
277
|
+
allowlisted, isHostEntry, hostAllowed, toolMatches, commandMatches, migrate,
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function apply(ctx, config) {
|
|
281
|
+
let stored = {}
|
|
282
|
+
let version = '0.0.0'
|
|
283
|
+
let lastPrune = 0
|
|
284
|
+
const ready = Promise.all([loadState(), VERSION_PROMISE]).then(async ([raw, tag]) => {
|
|
285
|
+
const migrated = migrate(raw)
|
|
286
|
+
stored = migrated.state
|
|
287
|
+
if (migrated.changed) void saveState(stored)
|
|
288
|
+
version = tag || '0.0.0'
|
|
289
|
+
void pruneAudit(cfg().auditRetentionDays)
|
|
290
|
+
lastPrune = Date.now()
|
|
291
|
+
})
|
|
292
|
+
const cfg = () => ({ ...DEFAULTS, ...(config ?? {}), ...stored })
|
|
293
|
+
|
|
294
|
+
const grants = new Map()
|
|
295
|
+
const inFlight = new Set()
|
|
296
|
+
const stats = { asked: 0, allowed: 0, denied: 0 }
|
|
297
|
+
let lastAgent = null
|
|
298
|
+
|
|
299
|
+
async function judge({ tool, target, hosts, command, preview, purpose, signal, callId }) {
|
|
300
|
+
let decision = 'allowed'
|
|
301
|
+
let via = 'once'
|
|
302
|
+
let custom = ''
|
|
303
|
+
|
|
304
|
+
const timeoutMs = Math.max(5000, Math.min(Number(cfg().askTimeoutMs ?? 30000) || 30000, 600000))
|
|
305
|
+
const autoAllow = (cfg().onTimeout ?? 'deny') === 'allow'
|
|
306
|
+
const autoAction = autoAllow ? '放行' : '拒绝'
|
|
307
|
+
const timer = new Promise((_, reject) => setTimeout(
|
|
308
|
+
() => reject(Object.assign(new Error('timeout'), { code: 'NET_CONSENT_TIMEOUT' })),
|
|
309
|
+
timeoutMs,
|
|
310
|
+
))
|
|
311
|
+
|
|
312
|
+
try {
|
|
313
|
+
const answer = await Promise.race([
|
|
314
|
+
ctx.userQuestions.ask({
|
|
315
|
+
agent: lastAgent ?? undefined,
|
|
316
|
+
signal,
|
|
317
|
+
questions: [{
|
|
318
|
+
id: 'net-consent',
|
|
319
|
+
header: '联网审批',
|
|
320
|
+
question: `${tool} 申请联网:${target}`,
|
|
321
|
+
detail: [
|
|
322
|
+
purpose ? `AI 自述用途:\n${purpose}` : '模型没有先说明用途。',
|
|
323
|
+
command ? `命令:\n${command.slice(0, 600)}` : '',
|
|
324
|
+
preview && preview !== command ? `调用内容摘要:\n${preview}` : '',
|
|
325
|
+
`${Math.round(timeoutMs / 1000)} 秒内未选择将自动${autoAction}。`,
|
|
326
|
+
].filter(Boolean).join('\n\n'),
|
|
327
|
+
options: [
|
|
328
|
+
{ label: '放行一次', description: '只放行这一次' },
|
|
329
|
+
{ label: '本会话放行该目标', description: '本会话内对这些目标不再询问' },
|
|
330
|
+
{ label: '拒绝', description: '阻止本次联网' },
|
|
331
|
+
],
|
|
332
|
+
}],
|
|
333
|
+
}),
|
|
334
|
+
timer,
|
|
335
|
+
])
|
|
336
|
+
const item = answer?.answers?.find(a => a.id === 'net-consent') ?? answer?.answers?.[0]
|
|
337
|
+
const selected = item?.selected ?? []
|
|
338
|
+
custom = (item?.custom ?? '').trim()
|
|
339
|
+
if (custom && selected.length === 0) { decision = 'denied'; via = 'custom' }
|
|
340
|
+
else if (selected.some(label => String(label).includes('会话'))) { decision = 'allowed'; via = 'session-grant' }
|
|
341
|
+
else if (selected.some(label => /^(放行一次|允许一次)/.test(String(label)))) { decision = 'allowed'; via = 'once' }
|
|
342
|
+
else { decision = 'denied'; via = 'user-reject' }
|
|
343
|
+
} catch (error) {
|
|
344
|
+
const code = error?.code ?? ''
|
|
345
|
+
decision = 'denied'
|
|
346
|
+
via = code || 'error'
|
|
347
|
+
if (code === 'DELEGATED_CALLER') via = 'delegated'
|
|
348
|
+
if (code === 'NET_CONSENT_TIMEOUT' && autoAllow) {
|
|
349
|
+
decision = 'allowed'
|
|
350
|
+
via = 'timeout-allow'
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (cfg().audit !== false) {
|
|
355
|
+
writeAudit({
|
|
356
|
+
ts: new Date().toISOString(), tool, callId: String(callId ?? ''),
|
|
357
|
+
session: lastAgent ? String(lastAgent?.session?.id ?? lastAgent?.id ?? '') : '',
|
|
358
|
+
hosts, command: (command ?? '').slice(0, 400),
|
|
359
|
+
preview: (preview ?? '').slice(0, 400), purpose: (purpose ?? '').slice(0, 400),
|
|
360
|
+
decision, via, custom: custom || undefined,
|
|
361
|
+
})
|
|
362
|
+
if (Date.now() - lastPrune > 3600000) {
|
|
363
|
+
lastPrune = Date.now()
|
|
364
|
+
void pruneAudit(cfg().auditRetentionDays)
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return { decision, via, custom, timeoutMs }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
371
|
+
if (exec.agent) lastAgent = exec.agent
|
|
372
|
+
|
|
373
|
+
let verdict
|
|
374
|
+
try { verdict = classify(exec, cfg()) } catch { verdict = null }
|
|
375
|
+
if (!verdict || !verdict.network) return next()
|
|
376
|
+
|
|
377
|
+
const current = cfg()
|
|
378
|
+
const layer = verdict.kind === 'shell' ? 'shell' : 'tool'
|
|
379
|
+
const policy = normalizePolicy(layer === 'shell' ? current.shellMode : current.mode, 'ask')
|
|
380
|
+
if (policy === 'allow') return next()
|
|
381
|
+
|
|
382
|
+
const hosts = verdict.hosts ?? []
|
|
383
|
+
const publicHosts = hosts.filter(h => !(current.allowLocal && isPrivateHost(h)))
|
|
384
|
+
const onlyLocal = hosts.length > 0 && publicHosts.length === 0
|
|
385
|
+
if (current.allowLocal && onlyLocal) return next()
|
|
386
|
+
|
|
387
|
+
const probe = { ...verdict, tool: String(exec.name ?? '') }
|
|
388
|
+
const whitelisted = allowlisted(probe, current)
|
|
389
|
+
if (whitelisted) return next()
|
|
390
|
+
|
|
391
|
+
const key = sessionKey(exec)
|
|
392
|
+
const target = publicHosts.length > 0
|
|
393
|
+
? publicHosts.join(', ')
|
|
394
|
+
: (layer === 'shell' ? '目的地未知(命令里没解析出主机名)' : '目的地未知')
|
|
395
|
+
|
|
396
|
+
if (policy === 'deny') {
|
|
397
|
+
stats.denied++
|
|
398
|
+
if (current.audit !== false) writeAudit({
|
|
399
|
+
ts: new Date().toISOString(), tool: exec.name, callId: String(exec.callId ?? ''),
|
|
400
|
+
session: key, hosts: publicHosts, command: (verdict.command ?? '').slice(0, 400),
|
|
401
|
+
preview: verdict.preview, decision: 'denied', via: 'policy=deny',
|
|
402
|
+
})
|
|
403
|
+
return { kind: 'deny', reason: `net-consent:${exec.name} 需要联网(${target}),当前策略为拒绝,已阻止。` }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const granted = grants.get(key) ?? new Set()
|
|
407
|
+
if (hosts.length > 0 && publicHosts.every(h => granted.has(h))) return next()
|
|
408
|
+
if (hosts.length === 0 && granted.has('*')) return next()
|
|
409
|
+
|
|
410
|
+
if (!ctx.userQuestions) {
|
|
411
|
+
stats.denied++
|
|
412
|
+
return { kind: 'deny', reason: 'net-consent:审批服务不可用,已按失败关闭原则阻止本次联网。' }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const askId = String(exec.callId ?? `${exec.name}-${Date.now()}`)
|
|
416
|
+
if (inFlight.has(askId)) return { kind: 'deny', reason: 'net-consent:同一次调用重复进入审批,已阻止。' }
|
|
417
|
+
inFlight.add(askId)
|
|
418
|
+
|
|
419
|
+
let outcome
|
|
420
|
+
try {
|
|
421
|
+
stats.asked++
|
|
422
|
+
outcome = await judge({
|
|
423
|
+
tool: String(exec.name),
|
|
424
|
+
target,
|
|
425
|
+
hosts: publicHosts,
|
|
426
|
+
command: verdict.command,
|
|
427
|
+
preview: verdict.preview,
|
|
428
|
+
purpose: current.purposes === false ? '' : purposeOf(exec.agent),
|
|
429
|
+
signal: exec.signal,
|
|
430
|
+
callId: exec.callId,
|
|
431
|
+
})
|
|
432
|
+
} finally {
|
|
433
|
+
inFlight.delete(askId)
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (outcome.decision === 'allowed') {
|
|
437
|
+
stats.allowed++
|
|
438
|
+
if (outcome.via === 'session-grant') {
|
|
439
|
+
if (hosts.length === 0) granted.add('*')
|
|
440
|
+
for (const h of publicHosts) granted.add(h)
|
|
441
|
+
grants.set(key, granted)
|
|
442
|
+
}
|
|
443
|
+
return next()
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
stats.denied++
|
|
447
|
+
if (outcome.via === 'custom') {
|
|
448
|
+
return { kind: 'deny', reason: `net-consent:用户没有批准这次联网,而是补充说明:「${outcome.custom}」。请按该说明调整做法;若仍需联网,会被再次询问。` }
|
|
449
|
+
}
|
|
450
|
+
if (outcome.via === 'delegated') {
|
|
451
|
+
return { kind: 'deny', reason: 'net-consent:子代理内无法弹审批(DSH 禁止子代理向用户提问),已阻止。请让主代理来做联网操作。' }
|
|
452
|
+
}
|
|
453
|
+
if (outcome.via === 'NET_CONSENT_TIMEOUT') {
|
|
454
|
+
return { kind: 'deny', reason: `net-consent:等待审批超时(${Math.round(outcome.timeoutMs / 1000)}s),已阻止本次联网。` }
|
|
455
|
+
}
|
|
456
|
+
if (outcome.via === 'ASK_ABORTED') {
|
|
457
|
+
return { kind: 'deny', reason: 'net-consent:审批被取消,本次联网未执行。' }
|
|
458
|
+
}
|
|
459
|
+
if (outcome.via === 'user-reject') {
|
|
460
|
+
return { kind: 'deny', reason: `net-consent:用户拒绝了对 ${target} 的联网访问。不要重试同一目标,除非用户明确要求。` }
|
|
461
|
+
}
|
|
462
|
+
return { kind: 'deny', reason: `net-consent:审批未通过(${outcome.via}),已阻止本次联网。` }
|
|
463
|
+
})
|
|
464
|
+
|
|
465
|
+
const snapshot = () => {
|
|
466
|
+
const current = cfg()
|
|
467
|
+
return {
|
|
468
|
+
mode: normalizePolicy(current.mode, 'ask'),
|
|
469
|
+
shellMode: normalizePolicy(current.shellMode, 'ask'),
|
|
470
|
+
allowLocal: current.allowLocal !== false,
|
|
471
|
+
askTimeoutMs: Number(current.askTimeoutMs ?? 30000),
|
|
472
|
+
onTimeout: current.onTimeout === 'allow' ? 'allow' : 'deny',
|
|
473
|
+
audit: current.audit !== false,
|
|
474
|
+
auditRetentionDays: Number(current.auditRetentionDays ?? 30),
|
|
475
|
+
allowlist: (current.allowlist ?? []).map(String),
|
|
476
|
+
purposes: current.purposes !== false,
|
|
477
|
+
stats: { asked: stats.asked, allowed: stats.allowed, denied: stats.denied },
|
|
478
|
+
version,
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const ROUTE_KEY = Symbol.for('dsh-net-consent.routes')
|
|
483
|
+
// Mounted on Connection's shared /api channel, so DSH itself applies its
|
|
484
|
+
// Host/Origin fence and browser authentication before this handler runs, and
|
|
485
|
+
// only the authenticated owner Peer reaches it.
|
|
486
|
+
const ROUTE_PATH = '/api/net-consent/state'
|
|
487
|
+
|
|
488
|
+
const writeDebug = async (line) => {
|
|
489
|
+
try {
|
|
490
|
+
await mkdir(STATE_DIR, { recursive: true })
|
|
491
|
+
await appendFile(join(STATE_DIR, 'debug.log'), `${new Date().toISOString()} ${line}\n`)
|
|
492
|
+
} catch { }
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const jsonResponse = (status, payload) => Response.json(payload, {
|
|
496
|
+
status,
|
|
497
|
+
headers: { 'cache-control': 'no-store' },
|
|
498
|
+
})
|
|
499
|
+
|
|
500
|
+
const routeFetch = async (request) => {
|
|
501
|
+
await ready
|
|
502
|
+
|
|
503
|
+
if (request.method === 'GET' || request.method === 'HEAD') return jsonResponse(200, snapshot())
|
|
504
|
+
|
|
505
|
+
if (request.method === 'POST') {
|
|
506
|
+
let patch
|
|
507
|
+
try { patch = await request.json() } catch { return jsonResponse(400, { error: 'bad json' }) }
|
|
508
|
+
const next = {}
|
|
509
|
+
for (const key of WRITABLE) if (key in (patch ?? {})) next[key] = patch[key]
|
|
510
|
+
for (const key of ['mode', 'shellMode']) {
|
|
511
|
+
if (next[key] === undefined) continue
|
|
512
|
+
const value = LEGACY_POLICY[next[key]] ?? next[key]
|
|
513
|
+
if (POLICIES.includes(value)) next[key] = value
|
|
514
|
+
else delete next[key]
|
|
515
|
+
}
|
|
516
|
+
if (next.allowLocal !== undefined) next.allowLocal = next.allowLocal !== false
|
|
517
|
+
if (next.audit !== undefined) next.audit = next.audit !== false
|
|
518
|
+
if (next.purposes !== undefined) next.purposes = next.purposes !== false
|
|
519
|
+
if (next.allowlist !== undefined) {
|
|
520
|
+
if (!Array.isArray(next.allowlist)) delete next.allowlist
|
|
521
|
+
else next.allowlist = [...new Set(next.allowlist.map(String).map(s => s.trim()).filter(Boolean))]
|
|
522
|
+
}
|
|
523
|
+
if (next.askTimeoutMs !== undefined) {
|
|
524
|
+
const ms = Number(next.askTimeoutMs)
|
|
525
|
+
if (Number.isFinite(ms) && ms >= 5000 && ms <= 600000) next.askTimeoutMs = Math.round(ms)
|
|
526
|
+
else delete next.askTimeoutMs
|
|
527
|
+
}
|
|
528
|
+
if (next.auditRetentionDays !== undefined) {
|
|
529
|
+
const days = Math.round(Number(next.auditRetentionDays))
|
|
530
|
+
if (Number.isFinite(days) && days >= 0 && days <= 3650) next.auditRetentionDays = days
|
|
531
|
+
else delete next.auditRetentionDays
|
|
532
|
+
}
|
|
533
|
+
if (next.onTimeout !== undefined) {
|
|
534
|
+
const value = LEGACY_POLICY[next.onTimeout] ?? next.onTimeout
|
|
535
|
+
if (value === 'allow' || value === 'deny') next.onTimeout = value
|
|
536
|
+
else delete next.onTimeout
|
|
537
|
+
}
|
|
538
|
+
stored = { ...stored, ...next }
|
|
539
|
+
const ok = await saveState(stored)
|
|
540
|
+
void pruneAudit(cfg().auditRetentionDays)
|
|
541
|
+
return jsonResponse(ok ? 200 : 500, { ...snapshot(), saved: ok })
|
|
542
|
+
}
|
|
543
|
+
return jsonResponse(405, { error: 'method not allowed' })
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
try {
|
|
547
|
+
const previous = globalThis[ROUTE_KEY]
|
|
548
|
+
if (Array.isArray(previous)) {
|
|
549
|
+
for (const dispose of previous) { try { void Promise.resolve(dispose()).catch(() => {}) } catch { } }
|
|
550
|
+
}
|
|
551
|
+
if (typeof ctx.inject === 'function') {
|
|
552
|
+
ctx.inject(['connection'], (connectionCtx) => {
|
|
553
|
+
const dispose = connectionCtx.connection.fetch.register({
|
|
554
|
+
path: ROUTE_PATH,
|
|
555
|
+
methods: ['GET', 'HEAD', 'POST'],
|
|
556
|
+
requestBody: 'buffered',
|
|
557
|
+
fetch: routeFetch,
|
|
558
|
+
})
|
|
559
|
+
globalThis[ROUTE_KEY] = [dispose]
|
|
560
|
+
void writeDebug(`route registered: ${ROUTE_PATH} (connection.fetch exact)`)
|
|
561
|
+
connectionCtx.on('dispose', () => {
|
|
562
|
+
if (globalThis[ROUTE_KEY] === undefined) return
|
|
563
|
+
if (globalThis[ROUTE_KEY][0] !== dispose) return
|
|
564
|
+
globalThis[ROUTE_KEY] = undefined
|
|
565
|
+
})
|
|
566
|
+
})
|
|
567
|
+
} else {
|
|
568
|
+
void writeDebug('route skipped: ctx.inject unavailable')
|
|
569
|
+
}
|
|
570
|
+
} catch (error) {
|
|
571
|
+
void writeDebug(`route registration failed: ${error?.stack ?? String(error)}`)
|
|
572
|
+
}
|
|
573
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-net-consent",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "DSH 联网审批插件:会话里自己抓网页、在命令行跑联网工具之前,先弹卡片确认。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./client": "./client.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"client.js",
|
|
14
|
+
"cordis.patch.yml",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"keywords": [
|
|
19
|
+
"dsh",
|
|
20
|
+
"deepseek-harness",
|
|
21
|
+
"plugin",
|
|
22
|
+
"security",
|
|
23
|
+
"network",
|
|
24
|
+
"approval",
|
|
25
|
+
"consent"
|
|
26
|
+
],
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/hsushjk/dsh-net-consent.git"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/hsushjk/dsh-net-consent#readme",
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/hsushjk/dsh-net-consent/issues"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20"
|
|
38
|
+
},
|
|
39
|
+
"dsh": {
|
|
40
|
+
"bundle": {
|
|
41
|
+
"patch": "./cordis.patch.yml"
|
|
42
|
+
},
|
|
43
|
+
"client": {
|
|
44
|
+
"platform": "web",
|
|
45
|
+
"immediately": true,
|
|
46
|
+
"inject": ["@deepseek-ai/dsh-client-ui-conversation"]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|