dsh-net-consent 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +11 -0
  2. package/client.js +90 -22
  3. package/index.js +88 -5
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -32,6 +32,15 @@
32
32
 
33
33
  `deny` 优先于「本会话放行」;本机 / 局域网地址与白名单命中项先放行。
34
34
 
35
+ ## 每会话配置
36
+
37
+ 设置面板改的是**全局默认**,对所有会话生效。单个会话可以在输入框旁点「联网审查」开关单独覆盖:
38
+
39
+ - 点击在 **跟随默认 → 本会话询问 → 本会话放行 → 本会话拒绝** 之间循环;双击恢复跟随默认。
40
+ - 按钮颜色表示当前生效策略:**绿 = 放行、蓝 = 询问、红 = 拒绝**(工具层与命令行层取更严格的一档)。文字带「·会话」后缀表示存在本会话覆盖,否则跟随全局默认。
41
+ - 覆盖只对该会话有效,存在 `~/.dsh/net-consent/sessions.json`,设置面板可查看和删除。
42
+ - 判定顺序:内置默认 < 面板全局配置 < 会话覆盖。白名单、审计开关、审计保留天数不参与会话覆盖,始终用全局配置。
43
+
35
44
  ## 审批卡片
36
45
 
37
46
  三个选项:`放行一次`、`本会话放行该目标`、`拒绝`。点「其它」填文字则默认拒绝,并把你的原话回给模型让它改路线。
@@ -74,6 +83,8 @@
74
83
  | `purposes` | `true` | 卡片展示模型自述用途 |
75
84
  | `internalTools` | 一长串只读工具 | 完全不看的工具(UI 不可改) |
76
85
 
86
+ 会话覆盖(`sessions.json` / 审批开关)可覆盖其中:`mode`、`shellMode`、`allowLocal`、`askTimeoutMs`、`onTimeout`、`purposes`。
87
+
77
88
  ## 审计
78
89
 
79
90
  每次判定写一行 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 CHANGED
@@ -66,19 +66,34 @@ window.__ModuleLoader__.load({
66
66
  const TIMEOUT_ACTIONS = [['deny', '自动拒绝'], ['allow', '自动放行']]
67
67
  const RETENTIONS = [['7', '7 天'], ['30', '30 天'], ['90', '90 天'], ['0', '永久保留']]
68
68
 
69
- const S = {
70
- pill: (on) => ({
69
+ // Pill tones: allow = green, ask = blue, deny = red.
70
+ const TONE = {
71
+ allow: { border: 'rgba(103,194,58,0.55)', bg: 'rgba(103,194,58,0.14)', fg: 'rgb(103,194,58)', word: '放行' },
72
+ ask: { border: 'rgba(64,158,255,0.55)', bg: 'rgba(64,158,255,0.14)', fg: 'rgb(64,158,255)', word: '询问' },
73
+ deny: { border: 'rgba(245,108,108,0.6)', bg: 'rgba(245,108,108,0.16)', fg: 'rgb(245,108,108)', word: '拒绝' },
74
+ }
75
+ const toneFor = (mode, shellMode) => {
76
+ if (mode === 'deny' || shellMode === 'deny') return 'deny'
77
+ if (mode === 'ask' || shellMode === 'ask') return 'ask'
78
+ return 'allow'
79
+ }
80
+ const pillStyle = (tone) => {
81
+ const t = TONE[tone]
82
+ return {
71
83
  display: 'inline-flex', alignItems: 'center', gap: 6,
72
84
  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',
85
+ border: '1px solid ' + t.border,
86
+ background: t.bg,
87
+ color: t.fg,
76
88
  fontSize: 12, lineHeight: '26px', whiteSpace: 'nowrap', userSelect: 'none',
77
89
  fontFamily: 'inherit',
78
- }),
79
- dot: (on) => ({
90
+ }
91
+ }
92
+
93
+ const S = {
94
+ dot: (tone) => ({
80
95
  width: 7, height: 7, borderRadius: 4,
81
- background: on ? 'rgb(64,158,255)' : 'rgba(128,128,128,0.6)',
96
+ background: TONE[tone] ? TONE[tone].fg : 'rgba(128,128,128,0.6)',
82
97
  }),
83
98
  page: { padding: '24px 28px', maxWidth: 680, fontSize: 13, lineHeight: 1.6 },
84
99
  h1: { fontSize: 16, fontWeight: 600, margin: '0 0 4px' },
@@ -108,28 +123,58 @@ window.__ModuleLoader__.load({
108
123
  warn: { fontSize: 12, color: 'rgb(230,160,60)', marginTop: 8 },
109
124
  }
110
125
 
111
- function ConsentToggle() {
126
+ function ConsentToggle(props) {
112
127
  const [value, error] = useStore()
113
- const mode = policyOf(value?.mode)
114
- const shellMode = policyOf(value?.shellMode)
115
- const on = mode !== 'allow' || shellMode !== 'allow'
128
+ // session scope: the renderer injects sessionId for session-scoped slots.
129
+ const sessionId = props?.sessionId
130
+ const override = value?.sessionOverrides?.[String(sessionId)]
131
+ const scoped = override != null
132
+ const mode = policyOf(override?.mode ?? value?.mode)
133
+ const shellMode = policyOf(override?.shellMode ?? value?.shellMode)
134
+ const tone = toneFor(mode, shellMode)
116
135
  const title = value
117
- ? `工具 ${labelOf(mode)} · 命令行 ${labelOf(shellMode)};本次已询问 ${value?.stats?.asked ?? 0} 次。点击${on ? '关闭' : '开启'}联网审查。`
136
+ ? (scoped
137
+ ? `本会话覆盖:工具 ${labelOf(mode)} · 命令行 ${labelOf(shellMode)}。点击循环切换,双击恢复跟随默认。`
138
+ : `跟随默认:工具 ${labelOf(mode)} · 命令行 ${labelOf(shellMode)};本次已询问 ${value?.stats?.asked ?? 0} 次。点击固定为本会话询问。`)
118
139
  : (error || '正在读取联网审查状态…')
119
- const flip = useCallback(() => {
120
- const next = on ? 'allow' : 'ask'
121
- store.patch({ mode: next, shellMode: next })
122
- }, [on])
140
+ const cycle = useCallback(() => {
141
+ if (sessionId === undefined || sessionId === null) {
142
+ // No session context (should not happen): fall back to the global toggle.
143
+ const next = tone === 'allow' ? 'ask' : 'allow'
144
+ store.patch({ mode: next, shellMode: next })
145
+ return
146
+ }
147
+ const id = String(sessionId)
148
+ // Cycle per session: follow default → ask → allow → deny → follow default.
149
+ // Position is decided by whether an override EXISTS (and what it pins),
150
+ // never by comparing override values with the global default — when the
151
+ // global default already equals the override, value-comparison would pin
152
+ // the toggle on that step forever (e.g. global ask + override ask).
153
+ if (!scoped) {
154
+ store.patch({ sessionId: id, override: { mode: 'ask', shellMode: 'ask' } })
155
+ } else if (mode !== 'allow') {
156
+ store.patch({ sessionId: id, override: { mode: 'allow', shellMode: 'allow' } })
157
+ } else if (mode !== 'deny') {
158
+ store.patch({ sessionId: id, override: { mode: 'deny', shellMode: 'deny' } })
159
+ } else {
160
+ store.patch({ sessionId: id, override: null })
161
+ }
162
+ }, [value, scoped, mode, sessionId])
163
+ const reset = useCallback(() => {
164
+ if (sessionId === undefined || sessionId === null) return
165
+ store.patch({ sessionId: String(sessionId), override: null })
166
+ }, [sessionId])
123
167
  return h('button', {
124
168
  type: 'button',
125
- onClick: flip,
169
+ onClick: cycle,
170
+ onDoubleClick: reset,
126
171
  title,
127
- style: S.pill(on),
128
- 'aria-pressed': on,
172
+ style: pillStyle(tone),
173
+ 'aria-pressed': scoped,
129
174
  },
130
- h('span', { style: S.dot(on) }),
175
+ h('span', { style: S.dot(tone) }),
131
176
  h('span', null, '联网审查'),
132
- h('span', { style: { opacity: on ? 0.85 : 0.55 } }, on ? '开' : '关'),
177
+ h('span', { style: { opacity: 0.85 } }, `${TONE[tone].word}${scoped ? '·会话' : ''}`),
133
178
  )
134
179
  }
135
180
 
@@ -173,6 +218,7 @@ window.__ModuleLoader__.load({
173
218
  }
174
219
  const set = patch => store.patch(patch)
175
220
  const stats = value.stats ?? {}
221
+ const overrides = value.sessionOverrides ?? {}
176
222
  return h('div', { style: S.page },
177
223
  h('div', { style: S.h1 }, '联网审查'),
178
224
 
@@ -201,6 +247,28 @@ window.__ModuleLoader__.load({
201
247
  })),
202
248
  )),
203
249
 
250
+ h('div', { style: S.group },
251
+ h('div', { style: S.groupTitle }, '本会话覆盖'),
252
+ h('div', null,
253
+ h(Row, {
254
+ name: '会话覆盖列表',
255
+ hint: '在会话输入框旁点击「联网审查」开关可为本会话单独设置;这里是全部覆盖,删除后该会话恢复使用上面的默认配置。',
256
+ },
257
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'stretch' } },
258
+ Object.keys(overrides).length === 0
259
+ ? h('div', { style: { fontSize: 12, opacity: 0.55 } }, '没有会话覆盖。')
260
+ : Object.entries(overrides).map(([id, ov]) => h('div', {
261
+ key: id,
262
+ style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 },
263
+ },
264
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: id },
265
+ id.slice(0, 12) + '…:工具 ' + labelOf(ov.mode) + ' · 命令行 ' + labelOf(ov.shellMode)),
266
+ h('button', {
267
+ type: 'button', style: S.select, onClick: () => set({ sessionId: id, override: null }),
268
+ }, '删除'),
269
+ )))),
270
+ )),
271
+
204
272
  h('div', { style: S.group },
205
273
  h('div', { style: S.groupTitle }, '审批卡片'),
206
274
  h('div', null,
package/index.js CHANGED
@@ -8,7 +8,9 @@ export const inject = ['tools', 'userQuestions']
8
8
 
9
9
  const STATE_DIR = join(homedir(), '.dsh', 'net-consent')
10
10
  const STATE_FILE = join(STATE_DIR, 'state.json')
11
+ const SESSIONS_FILE = join(STATE_DIR, 'sessions.json')
11
12
  const AUDIT_DIR = join(STATE_DIR, 'audit')
13
+ const MAX_SESSION_OVERRIDES = 100
12
14
 
13
15
  const POLICIES = ['allow', 'ask', 'deny']
14
16
  const LEGACY_POLICY = { off: 'allow', observe: 'allow' }
@@ -46,6 +48,10 @@ const WRITABLE = [
46
48
  'audit', 'auditRetentionDays', 'allowlist', 'purposes',
47
49
  ]
48
50
 
51
+ // Per-session override keys: policy layers plus the ask-card behaviour that
52
+ // a single session may want different from the global default.
53
+ const SESSION_WRITABLE = ['mode', 'shellMode', 'allowLocal', 'askTimeoutMs', 'onTimeout', 'purposes']
54
+
49
55
  const NET_TOOL = /(^web_(fetch|search)$)|(^fetch$)|(^http_)|(browser|playwright|puppeteer|websearch|search_web|selenium|chrome_|navigate)/i
50
56
 
51
57
  const SHELL_TOOL = /^(pwsh|powershell|bash|sh|zsh|cmd|shell|terminal|exec|run_code|process|spawn)/i
@@ -245,6 +251,42 @@ async function saveState(state) {
245
251
  } catch { return false }
246
252
  }
247
253
 
254
+ async function loadSessionOverrides() {
255
+ try {
256
+ const raw = JSON.parse(await readFile(SESSIONS_FILE, 'utf8'))
257
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
258
+ } catch { return {} }
259
+ }
260
+
261
+ async function saveSessionOverrides(map) {
262
+ try {
263
+ await mkdir(STATE_DIR, { recursive: true })
264
+ await writeFile(SESSIONS_FILE, JSON.stringify(map, null, 2), 'utf8')
265
+ return true
266
+ } catch { return false }
267
+ }
268
+
269
+ function sanitizeSessionOverride(raw) {
270
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
271
+ const next = {}
272
+ for (const key of SESSION_WRITABLE) {
273
+ if (!(key in raw)) continue
274
+ const value = raw[key]
275
+ if (key === 'mode' || key === 'shellMode') {
276
+ const mapped = LEGACY_POLICY[value] ?? value
277
+ if (POLICIES.includes(mapped)) next[key] = mapped
278
+ } else if (key === 'askTimeoutMs') {
279
+ const ms = Math.round(Number(value))
280
+ if (Number.isFinite(ms) && ms >= 5000 && ms <= 600000) next[key] = ms
281
+ } else if (key === 'onTimeout') {
282
+ if (value === 'allow' || value === 'deny') next[key] = value
283
+ } else {
284
+ next[key] = value !== false
285
+ }
286
+ }
287
+ return Object.keys(next).length > 0 ? next : null
288
+ }
289
+
248
290
  function migrate(raw) {
249
291
  const state = { ...(raw ?? {}) }
250
292
  let changed = false
@@ -275,34 +317,49 @@ const VERSION_PROMISE = readFile(new URL('./package.json', import.meta.url), 'ut
275
317
  export const _test = {
276
318
  classify, hostsIn, isPrivateHost, purposeOf, DEFAULTS, normalizePolicy,
277
319
  allowlisted, isHostEntry, hostAllowed, toolMatches, commandMatches, migrate,
320
+ sanitizeSessionOverride, SESSION_WRITABLE,
278
321
  }
279
322
 
280
323
  export function apply(ctx, config) {
281
324
  let stored = {}
325
+ let sessionOverrides = {}
282
326
  let version = '0.0.0'
283
327
  let lastPrune = 0
284
- const ready = Promise.all([loadState(), VERSION_PROMISE]).then(async ([raw, tag]) => {
328
+ const ready = Promise.all([loadState(), loadSessionOverrides(), VERSION_PROMISE]).then(async ([raw, rawSessions, tag]) => {
285
329
  const migrated = migrate(raw)
286
330
  stored = migrated.state
287
331
  if (migrated.changed) void saveState(stored)
332
+ const clean = {}
333
+ for (const [id, value] of Object.entries(rawSessions ?? {})) {
334
+ const override = sanitizeSessionOverride(value)
335
+ if (override) clean[id] = override
336
+ }
337
+ sessionOverrides = clean
288
338
  version = tag || '0.0.0'
289
339
  void pruneAudit(cfg().auditRetentionDays)
290
340
  lastPrune = Date.now()
291
341
  })
292
342
  const cfg = () => ({ ...DEFAULTS, ...(config ?? {}), ...stored })
293
343
 
344
+ // Effective config for one session: defaults < panel (global) < session override.
345
+ const cfgFor = (sessionId) => {
346
+ const base = cfg()
347
+ const override = sessionId === undefined ? undefined : sessionOverrides[String(sessionId)]
348
+ return override ? { ...base, ...override } : base
349
+ }
350
+
294
351
  const grants = new Map()
295
352
  const inFlight = new Set()
296
353
  const stats = { asked: 0, allowed: 0, denied: 0 }
297
354
  let lastAgent = null
298
355
 
299
- async function judge({ tool, target, hosts, command, preview, purpose, signal, callId }) {
356
+ async function judge({ tool, target, hosts, command, preview, purpose, signal, callId, effective }) {
300
357
  let decision = 'allowed'
301
358
  let via = 'once'
302
359
  let custom = ''
303
360
 
304
- const timeoutMs = Math.max(5000, Math.min(Number(cfg().askTimeoutMs ?? 30000) || 30000, 600000))
305
- const autoAllow = (cfg().onTimeout ?? 'deny') === 'allow'
361
+ const timeoutMs = Math.max(5000, Math.min(Number(effective.askTimeoutMs ?? 30000) || 30000, 600000))
362
+ const autoAllow = (effective.onTimeout ?? 'deny') === 'allow'
306
363
  const autoAction = autoAllow ? '放行' : '拒绝'
307
364
  const timer = new Promise((_, reject) => setTimeout(
308
365
  () => reject(Object.assign(new Error('timeout'), { code: 'NET_CONSENT_TIMEOUT' })),
@@ -374,7 +431,8 @@ export function apply(ctx, config) {
374
431
  try { verdict = classify(exec, cfg()) } catch { verdict = null }
375
432
  if (!verdict || !verdict.network) return next()
376
433
 
377
- const current = cfg()
434
+ const sessionId = exec.agent?.session?.id ?? exec.agent?.id
435
+ const current = cfgFor(sessionId === undefined ? undefined : String(sessionId))
378
436
  const layer = verdict.kind === 'shell' ? 'shell' : 'tool'
379
437
  const policy = normalizePolicy(layer === 'shell' ? current.shellMode : current.mode, 'ask')
380
438
  if (policy === 'allow') return next()
@@ -428,6 +486,7 @@ export function apply(ctx, config) {
428
486
  purpose: current.purposes === false ? '' : purposeOf(exec.agent),
429
487
  signal: exec.signal,
430
488
  callId: exec.callId,
489
+ effective: current,
431
490
  })
432
491
  } finally {
433
492
  inFlight.delete(askId)
@@ -474,6 +533,7 @@ export function apply(ctx, config) {
474
533
  auditRetentionDays: Number(current.auditRetentionDays ?? 30),
475
534
  allowlist: (current.allowlist ?? []).map(String),
476
535
  purposes: current.purposes !== false,
536
+ sessionOverrides: { ...sessionOverrides },
477
537
  stats: { asked: stats.asked, allowed: stats.allowed, denied: stats.denied },
478
538
  version,
479
539
  }
@@ -505,6 +565,29 @@ export function apply(ctx, config) {
505
565
  if (request.method === 'POST') {
506
566
  let patch
507
567
  try { patch = await request.json() } catch { return jsonResponse(400, { error: 'bad json' }) }
568
+
569
+ // Session-scoped override: { sessionId, override } where override is a
570
+ // partial SESSION_WRITABLE object; null clears the override so the
571
+ // session falls back to the panel defaults.
572
+ if (patch && typeof patch === 'object' && 'sessionId' in patch) {
573
+ const id = String(patch.sessionId ?? '')
574
+ if (!id) return jsonResponse(400, { error: 'sessionId required' })
575
+ const override = patch.override === null || patch.override === undefined
576
+ ? null
577
+ : sanitizeSessionOverride(patch.override)
578
+ if (patch.override !== null && patch.override !== undefined && override === null) {
579
+ return jsonResponse(400, { error: 'no valid override keys' })
580
+ }
581
+ if (override === null) delete sessionOverrides[id]
582
+ else sessionOverrides[id] = override
583
+ if (Object.keys(sessionOverrides).length > MAX_SESSION_OVERRIDES) {
584
+ const keys = Object.keys(sessionOverrides)
585
+ for (const k of keys.slice(0, keys.length - MAX_SESSION_OVERRIDES)) delete sessionOverrides[k]
586
+ }
587
+ const ok = await saveSessionOverrides(sessionOverrides)
588
+ return jsonResponse(ok ? 200 : 500, { ...snapshot(), saved: ok })
589
+ }
590
+
508
591
  const next = {}
509
592
  for (const key of WRITABLE) if (key in (patch ?? {})) next[key] = patch[key]
510
593
  for (const key of ['mode', 'shellMode']) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-net-consent",
3
- "version": "1.0.1",
4
- "description": "DSH 联网审批插件:会话里自己抓网页、在命令行跑联网工具之前,先弹卡片确认。",
3
+ "version": "1.2.0",
4
+ "description": "DSH 联网审批插件:会话里自己抓网页、在命令行跑联网工具之前,先弹卡片确认。支持每会话独立配置。",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "exports": {