dsh-net-consent 1.0.0 → 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/README.md CHANGED
@@ -53,6 +53,10 @@
53
53
 
54
54
  白名单是显式例外表,先于 `deny` 策略生效。
55
55
 
56
+ ## 安全
57
+
58
+ 设置页的状态接口挂在 DSH 的 `/api` 通道上(`ctx.connection.fetch.register` 的精确路由)。Host / Origin 校验与浏览器认证由 DSH 自己完成,只有已认证的属主会话能读写;插件不再向 `webServer` 注册裸路由。
59
+
56
60
  ## 配置
57
61
 
58
62
  `cordis.patch.yml` 里 `net-consent` 行的 `config:`:
package/client.js CHANGED
@@ -5,7 +5,7 @@ window.__ModuleLoader__.load({
5
5
  const h = React.createElement
6
6
  const { useState, useEffect, useCallback } = React
7
7
 
8
- const STATE_URL = '/net-consent/state'
8
+ const STATE_URL = '/api/net-consent/state'
9
9
 
10
10
  const store = {
11
11
  value: null,
package/index.js CHANGED
@@ -4,7 +4,7 @@ import { join } from 'node:path'
4
4
 
5
5
  export const name = 'net-consent'
6
6
 
7
- export const inject = ['tools', 'userQuestions', 'webServer']
7
+ 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')
@@ -272,22 +272,6 @@ const VERSION_PROMISE = readFile(new URL('./package.json', import.meta.url), 'ut
272
272
  })
273
273
  .catch(() => '')
274
274
 
275
- function readJsonBody(req, limit = 64 * 1024) {
276
- return new Promise((resolve, reject) => {
277
- let size = 0
278
- const chunks = []
279
- req.on('data', chunk => {
280
- size += chunk.length
281
- if (size > limit) { req.destroy(); reject(new Error('body too large')); return }
282
- chunks.push(chunk)
283
- })
284
- req.on('end', () => {
285
- try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}) } catch (error) { reject(error) }
286
- })
287
- req.on('error', reject)
288
- })
289
- }
290
-
291
275
  export const _test = {
292
276
  classify, hostsIn, isPrivateHost, purposeOf, DEFAULTS, normalizePolicy,
293
277
  allowlisted, isHostEntry, hostAllowed, toolMatches, commandMatches, migrate,
@@ -496,7 +480,10 @@ export function apply(ctx, config) {
496
480
  }
497
481
 
498
482
  const ROUTE_KEY = Symbol.for('dsh-net-consent.routes')
499
- const ROUTE_BASE = '/net-consent'
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'
500
487
 
501
488
  const writeDebug = async (line) => {
502
489
  try {
@@ -505,21 +492,19 @@ export function apply(ctx, config) {
505
492
  } catch { }
506
493
  }
507
494
 
508
- const routeHandler = async (req, res) => {
509
- const url = new URL(req.url ?? '/', 'http://localhost')
510
- const send = (status, payload) => {
511
- const body = JSON.stringify(payload)
512
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
513
- res.end(body)
514
- }
515
- if (url.pathname !== `${ROUTE_BASE}/state`) return send(404, { error: 'not found' })
495
+ const jsonResponse = (status, payload) => Response.json(payload, {
496
+ status,
497
+ headers: { 'cache-control': 'no-store' },
498
+ })
499
+
500
+ const routeFetch = async (request) => {
516
501
  await ready
517
502
 
518
- if (req.method === 'GET' || req.method === 'HEAD') return send(200, snapshot())
503
+ if (request.method === 'GET' || request.method === 'HEAD') return jsonResponse(200, snapshot())
519
504
 
520
- if (req.method === 'POST') {
505
+ if (request.method === 'POST') {
521
506
  let patch
522
- try { patch = await readJsonBody(req) } catch { return send(400, { error: 'bad json' }) }
507
+ try { patch = await request.json() } catch { return jsonResponse(400, { error: 'bad json' }) }
523
508
  const next = {}
524
509
  for (const key of WRITABLE) if (key in (patch ?? {})) next[key] = patch[key]
525
510
  for (const key of ['mode', 'shellMode']) {
@@ -553,28 +538,34 @@ export function apply(ctx, config) {
553
538
  stored = { ...stored, ...next }
554
539
  const ok = await saveState(stored)
555
540
  void pruneAudit(cfg().auditRetentionDays)
556
- return send(ok ? 200 : 500, { ...snapshot(), saved: ok })
541
+ return jsonResponse(ok ? 200 : 500, { ...snapshot(), saved: ok })
557
542
  }
558
- return send(405, { error: 'method not allowed' })
543
+ return jsonResponse(405, { error: 'method not allowed' })
559
544
  }
560
545
 
561
546
  try {
562
547
  const previous = globalThis[ROUTE_KEY]
563
548
  if (Array.isArray(previous)) {
564
- for (const dispose of previous) { try { dispose() } catch { } }
549
+ for (const dispose of previous) { try { void Promise.resolve(dispose()).catch(() => {}) } catch { } }
565
550
  }
566
- const registered = []
567
- if (typeof ctx.webServer?.register === 'function') {
568
- registered.push(ctx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/state`, handler: routeHandler }))
569
- registered.push(ctx.webServer.register({ kind: 'prefix', path: ROUTE_BASE, handler: routeHandler }))
570
- globalThis[ROUTE_KEY] = registered
571
- void writeDebug(`routes registered: ${ROUTE_BASE}/state (exact) + ${ROUTE_BASE} (prefix)`)
572
- ctx.on('dispose', () => {
573
- for (const dispose of registered) { try { dispose() } catch { } }
574
- if (globalThis[ROUTE_KEY] === registered) globalThis[ROUTE_KEY] = undefined
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
+ })
575
566
  })
576
567
  } else {
577
- void writeDebug(`route skipped: typeof webServer=${typeof ctx.webServer} typeof register=${typeof ctx.webServer?.register}`)
568
+ void writeDebug('route skipped: ctx.inject unavailable')
578
569
  }
579
570
  } catch (error) {
580
571
  void writeDebug(`route registration failed: ${error?.stack ?? String(error)}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-net-consent",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "DSH 联网审批插件:会话里自己抓网页、在命令行跑联网工具之前,先弹卡片确认。",
5
5
  "type": "module",
6
6
  "main": "index.js",