dsh-sensitive-guard 0.5.1 → 0.5.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # 变更记录
2
2
 
3
+ ## 0.5.3
4
+
5
+ - 修掉回环路径上的 DNS rebinding 漏洞:`hostHeaderOk` 此前对回环直接放行,而 rebinding 的攻击流量恰恰从回环进来、Host 却是攻击者域名;此时 `sameOriginOk` 看到的 Origin 与 Host 一致,无法区分。现在回环同样要求 Host 是字面量:放行 `localhost`(RFC 6761 保留名,不能被公网 DNS 重绑)、`127.0.0.0/8` 与 `::1`(含 IPv4-mapped 形式)。非回环分支的行为不变。
6
+ - 自测 139 → 142:新增回环来源 + 域名 Host 被 `bad-host` 拒;`localhost` 与 `[::1]` 仍放行三项。
7
+ - 桌面版用 `127.0.0.1` / `localhost` 访问不受影响;从局域网访问仍按原规则要求 `allowCidrs` 且 Host 为 IP 字面量。
8
+
9
+ ## 0.5.2
10
+
11
+ - 修掉对话内胶囊的 `aria-label` / `title` 硬编码中文:现在走宿主字典,英文宿主下是 `Show secret` / `Hide secret`;拿不到 locale 服务时仍回退到内置中文,不影响「没服务也要有锁」这条底线。
12
+ - 两个工具(`sensitive_guard_status`、`sensitive_guard_export`)的 `description` 与参数说明改成英文。tool schema 是给模型读的,英文描述对英文模型的工具选择更稳;返回的字段名与结构没动。
13
+ - 自测 137 → 139:新增「胶囊 aria-label 取字典(英文宿主)」与「无字典服务时胶囊回退中文标签」两项,覆盖上面这两条分支。
14
+ - 说明:`client.js` 里的 `密码` / `令牌` / `密钥` 是保管库存的 **kind 值**,`TONE_RULES` 里的中文是**检测规则**,两者都不是界面文案,保持中文不动。
15
+
3
16
  ## 0.5.1
4
17
 
5
18
  无代码变更,只改文档与包元数据。
package/README.en.md CHANGED
@@ -218,7 +218,7 @@ node scripts/build-gitleaks.mjs # regenerate rule data from upstream
218
218
  node scripts/build-gitleaks.mjs ./gitleaks.toml
219
219
  ```
220
220
 
221
- 137 offline tests using a temporary directory, never touching the real vault: the 0.3.x code-upgrade drill, both Settings tabs and the add dialog (including custom categories), list rows and the copy button, render smoke tests for the disable-confirmation dialog, compilation and tiering of all 221 rules, per-rule entropy/switch/manual-entry regressions, and a fresh-process restart proving persistent disable really survives.
221
+ 139 offline tests using a temporary directory, never touching the real vault: the 0.3.x code-upgrade drill, both Settings tabs and the add dialog (including custom categories), list rows and the copy button, render smoke tests for the disable-confirmation dialog, compilation and tiering of all 221 rules, per-rule entropy/switch/manual-entry regressions, and a fresh-process restart proving persistent disable really survives.
222
222
 
223
223
  | File | Role |
224
224
  | --- | --- |
package/README.md CHANGED
@@ -260,7 +260,7 @@ node scripts/build-gitleaks.mjs # 从上游重新生成规则数
260
260
  node scripts/build-gitleaks.mjs ./gitleaks.toml
261
261
  ```
262
262
 
263
- 137 项离线自测,用临时目录,不碰真实保管库。包含 0.3.x 旧代号升级演练、两个设置页标签与添加弹窗(含自定义分类)、列表行与复制按钮、关闭保护确认弹窗的渲染冒烟测试、221 条规则的编译与分级校验、逐条熵值/开关/手动录入回归,以及一次用新进程模拟重启验证持久关闭仍然生效。
263
+ 139 项离线自测,用临时目录,不碰真实保管库。包含 0.3.x 旧代号升级演练、两个设置页标签与添加弹窗(含自定义分类)、列表行与复制按钮、关闭保护确认弹窗的渲染冒烟测试、221 条规则的编译与分级校验、逐条熵值/开关/手动录入回归,以及一次用新进程模拟重启验证持久关闭仍然生效。
264
264
 
265
265
  | 文件 | 作用 |
266
266
  | --- | --- |
package/client.js CHANGED
@@ -1037,7 +1037,17 @@ window.__ModuleLoader__.load({
1037
1037
  * re-masks on its own. The plaintext never enters model context: this is a
1038
1038
  * browser fetch, not a tool result.
1039
1039
  */
1040
- function RevealChip({ ph, interactive }) {
1040
+ /**
1041
+ * Chip labels come from the host dictionary when it is available. The built-in
1042
+ * Chinese stays as the fallback: a host without a locale service must not cost
1043
+ * users the in-conversation lock (see registerInlineReveal).
1044
+ */
1045
+ const chipLabel = (t, revealed) =>
1046
+ typeof t === 'function'
1047
+ ? t(revealed ? 'hide' : 'reveal')
1048
+ : revealed ? '隐藏明文' : '显示明文';
1049
+
1050
+ function RevealChip({ ph, interactive, t }) {
1041
1051
  const [value, setValue] = useState(null);
1042
1052
  const [busy, setBusy] = useState(false);
1043
1053
  const [tone, setTone] = useState(() => {
@@ -1131,8 +1141,8 @@ window.__ModuleLoader__.load({
1131
1141
  cursor: 'pointer',
1132
1142
  },
1133
1143
  'aria-pressed': value !== null,
1134
- 'aria-label': value !== null ? '隐藏明文' : '显示明文',
1135
- title: value !== null ? '隐藏明文' : '显示明文',
1144
+ 'aria-label': chipLabel(t, value !== null),
1145
+ title: chipLabel(t, value !== null),
1136
1146
  disabled: busy,
1137
1147
  onClick: toggle,
1138
1148
  }, h(LockGlyph, { open: value !== null })));
@@ -1143,7 +1153,7 @@ window.__ModuleLoader__.load({
1143
1153
  * best-effort: a missing service or a changed slot contract must degrade to
1144
1154
  * "placeholder shown as plain text", never break the message list.
1145
1155
  */
1146
- function registerInlineReveal(ctx, slots) {
1156
+ function registerInlineReveal(ctx, slots, t) {
1147
1157
  const install = (conv) => {
1148
1158
  if (!conv || !conv.userText || typeof conv.userText.register !== 'function') {
1149
1159
  inlineState = 'no-service';
@@ -1186,6 +1196,7 @@ window.__ModuleLoader__.load({
1186
1196
  }, (props) => h(RevealChip, {
1187
1197
  ph: props && props.node && props.node.data ? props.node.data.ph : '',
1188
1198
  interactive: props ? props.interactive : true,
1199
+ t,
1189
1200
  }));
1190
1201
  inlineState = 'ok';
1191
1202
  } catch (error) {
@@ -1238,18 +1249,26 @@ window.__ModuleLoader__.load({
1238
1249
  function applyEntry(ctx) {
1239
1250
  const slots = ctx && ctx.slots;
1240
1251
  if (!slots || typeof slots.inject !== 'function' || typeof slots.register !== 'function') return;
1241
- // Inline reveal only needs slots, so register it before the settings page —
1242
- // a missing locale service must not cost users the in-conversation lock.
1243
- registerInlineReveal(ctx, slots);
1252
+ // The dictionary goes first because the lock chip takes its accessible label
1253
+ // from it. It stays optional: without a locale service the chip falls back to
1254
+ // the built-in Chinese labels and only the settings page is skipped, so a
1255
+ // missing service never costs users the in-conversation lock.
1244
1256
  const locale = ctx && ctx.locale;
1245
- if (!locale) return;
1246
- if (typeof locale.register !== 'function' || typeof locale.bind !== 'function') return;
1247
- try {
1248
- ctx.effect(() => locale.register(NS, { zh, en }), 'sensitive-guard: dictionaries');
1249
- } catch (error) {
1250
- console.warn('[sensitive-guard] dictionary registration failed:', error && error.message);
1257
+ let t = null;
1258
+ if (locale && typeof locale.register === 'function' && typeof locale.bind === 'function') {
1259
+ try {
1260
+ ctx.effect(() => locale.register(NS, { zh, en }), 'sensitive-guard: dictionaries');
1261
+ } catch (error) {
1262
+ console.warn('[sensitive-guard] dictionary registration failed:', error && error.message);
1263
+ }
1264
+ try {
1265
+ t = locale.bind(NS);
1266
+ } catch (error) {
1267
+ console.warn('[sensitive-guard] dictionary bind failed:', error && error.message);
1268
+ }
1251
1269
  }
1252
- const t = locale.bind(NS);
1270
+ registerInlineReveal(ctx, slots, t);
1271
+ if (typeof t !== 'function') return;
1253
1272
  slots.inject('settings.section', () => {
1254
1273
  try {
1255
1274
  return slots.register({
package/index.js CHANGED
@@ -996,9 +996,9 @@ const STATUS_OUTPUT = {
996
996
  type: 'object',
997
997
  additionalProperties: false,
998
998
  properties: {
999
- ph: { type: 'string', description: '上下文占位符' },
1000
- rule: { type: 'string', description: '命中的规则 id' },
1001
- origin: { type: 'string', description: '首次捕获来源' },
999
+ ph: { type: 'string', description: 'Context placeholder' },
1000
+ rule: { type: 'string', description: 'Rule id that matched' },
1001
+ origin: { type: 'string', description: 'Where it was first captured' },
1002
1002
  createdAt: { type: 'string' },
1003
1003
  lastHitAt: { type: 'string' },
1004
1004
  hits: { type: 'number' },
@@ -1018,7 +1018,7 @@ const EXPORT_OUTPUT = {
1018
1018
  type: 'object',
1019
1019
  additionalProperties: false,
1020
1020
  properties: {
1021
- path: { type: 'string', description: '明文文件路径(0600)' },
1021
+ path: { type: 'string', description: 'Path of the plaintext file (0600)' },
1022
1022
  note: { type: 'string' },
1023
1023
  },
1024
1024
  required: ['path', 'note'],
@@ -1067,7 +1067,7 @@ function snapshot(view) {
1067
1067
  function registerTools(ctx) {
1068
1068
  ctx.effect(() => ctx.tools.register({
1069
1069
  name: 'sensitive_guard_status',
1070
- description: '查看「敏感保护」的运行状态:保管库条目的元数据(占位符、命中规则、来源、时间、命中次数)、计数统计与错误。返回值不含任何明文字符,也不含明文片段。',
1070
+ description: 'Show the runtime status of Sensitive guard: metadata for every vault entry (placeholder, rule that matched, capture origin, timestamps, hit count), counters and errors. The result contains no plaintext characters and no plaintext fragments.',
1071
1071
  parameters: {},
1072
1072
  output: {
1073
1073
  schema: STATUS_OUTPUT,
@@ -1091,12 +1091,12 @@ function registerTools(ctx) {
1091
1091
 
1092
1092
  ctx.effect(() => ctx.tools.register({
1093
1093
  name: 'sensitive_guard_export',
1094
- description: '把一条被遮挡的敏感数据(<SG_ 占位符)导出为本机 0600 权限的明文文件,供命令执行时引用(如 --password "$(cat <path>)"、source <path>)。明文只写入该文件,不会进入会话上下文。仅在确实需要用凭据执行操作时调用;每次导出都会记入审计。',
1094
+ description: 'Export one masked secret (an <SG_ placeholder) to a plaintext file with 0600 permissions on this machine, for use from a command (e.g. --password "$(cat <path>)", source <path>). The plaintext is written only to that file and never enters the session context. Call this only when a credential is genuinely needed to run something; every export is audited.',
1095
1095
  parameters: {
1096
1096
  type: 'object',
1097
1097
  additionalProperties: false,
1098
1098
  properties: {
1099
- placeholder: { type: 'string', description: '保管库占位符,形如 <SG_012345abcdef>' },
1099
+ placeholder: { type: 'string', description: 'Vault placeholder, such as <SG_012345abcdef>' },
1100
1100
  },
1101
1101
  required: ['placeholder'],
1102
1102
  },
@@ -1286,12 +1286,13 @@ function suggestCidr(ip) {
1286
1286
  }
1287
1287
 
1288
1288
  /**
1289
- * For non-loopback access the Host header must be an IP literal. DNS rebinding
1290
- * needs a domain name, and `sameOriginOk` cannot tell a rebound request from a
1291
- * real one — both send a matching Origin and Host.
1289
+ * The Host header must be an IP literal — loopback included. DNS rebinding
1290
+ * always arrives over loopback but carries the attacker's domain in Host, and
1291
+ * `sameOriginOk` cannot tell it from a real local page (both send a matching
1292
+ * Origin and Host). `localhost` is reserved by RFC 6761 and cannot be rebound
1293
+ * through public DNS, so it stays usable.
1292
1294
  */
1293
1295
  function hostHeaderOk(req, level) {
1294
- if (level === 'loopback') return true;
1295
1296
  const raw = String(req.headers.host || '');
1296
1297
  if (raw.length === 0) return false;
1297
1298
  let name = raw;
@@ -1302,7 +1303,14 @@ function hostHeaderOk(req, level) {
1302
1303
  } else if (name.indexOf(':') === name.lastIndexOf(':')) {
1303
1304
  name = name.split(':')[0];
1304
1305
  }
1305
- return normalizeIp(name).length > 0 && isIP(normalizeIp(name)) !== 0;
1306
+ const ip = normalizeIp(name);
1307
+ if (level === 'loopback') {
1308
+ if (name.toLowerCase() === 'localhost') return true;
1309
+ if (ip === '::1') return true;
1310
+ const v4 = ipv4Bytes(ip);
1311
+ return v4 !== null && v4[0] === 127;
1312
+ }
1313
+ return ip.length > 0 && isIP(ip) !== 0;
1306
1314
  }
1307
1315
 
1308
1316
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sensitive-guard",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "敏感信息脱敏 DSH 插件:密钥、令牌、密码、API Key 在进入模型上下文前替换为 <SG_> 占位符,内置 221 条 gitleaks 规则与 .env/JSON 字段识别;明文 AES-256-GCM 加密存本机保管库,点小锁看真值,可导出给命令用。",
5
5
  "license": "MIT",
6
6
  "icon": "icon.svg",
package/test.mjs CHANGED
@@ -279,6 +279,69 @@ const fullCtx = new Proxy({
279
279
  api.apply(fullCtx);
280
280
  check('inline renderer uses keyed registration', registered.some((r) => r.key === 'sensitive-guard'));
281
281
 
282
+ /**
283
+ * The in-conversation chip takes its accessible label from the host dictionary,
284
+ * with the built-in Chinese as fallback. Both branches are load-bearing: without
285
+ * the fallback a host that provides no locale service loses the label entirely,
286
+ * and without the dictionary an English host gets a Chinese tooltip and screen
287
+ * reader announcement.
288
+ */
289
+ function renderInlineChip(translate, revealed) {
290
+ let stateIndex = 0;
291
+ const ReactStub = {
292
+ createElement: (type, props, ...children) => (
293
+ typeof type === 'function' ? type({ ...(props || {}), children }) : { type, props, children }
294
+ ),
295
+ Fragment: 'Fragment',
296
+ useState: (initial) => {
297
+ stateIndex += 1;
298
+ if (stateIndex === 1) return [revealed ? 'plain-value' : null, () => {}];
299
+ return [typeof initial === 'function' ? initial() : initial, () => {}];
300
+ },
301
+ useEffect: () => {},
302
+ useRef: () => ({ current: 0 }),
303
+ useCallback: (fn) => fn,
304
+ };
305
+ let chipApi = null;
306
+ const win = { __ModuleLoader__: { load(def) { chipApi = def.factory((n) => (n === 'react' ? ReactStub : {})); } } };
307
+ const capturedChip = [];
308
+ const chipSlots = {
309
+ inject(_name, factory) {
310
+ const it = factory();
311
+ if (it && typeof it.next === 'function') { let s = it.next(); while (!s.done) s = it.next(); }
312
+ },
313
+ register(options, renderer) { capturedChip.push({ options, renderer }); return () => {}; },
314
+ };
315
+ const conv = { uiConversation: { userText: { register: () => {} } } };
316
+ const ctx = new Proxy({
317
+ slots: chipSlots,
318
+ effect: () => () => {},
319
+ locale: { register: () => () => {}, bind: () => translate },
320
+ get: (name) => conv[name],
321
+ inject: (_deps, cb) => cb(conv),
322
+ }, { get(t, p) { return p in t ? t[p] : undefined; } });
323
+ new Function('window', 'globalThis', clientSrc).call(globalThis, win, globalThis);
324
+ chipApi.apply(ctx);
325
+ const node = capturedChip.find((c) => c.options && c.options.name === 'conversation.user.text.node');
326
+ if (!node) return null;
327
+ const tree = node.renderer({ node: { data: { ph: '<SG_aaaaaaaaaaaa>' } }, interactive: true });
328
+ const findButton = (n) => {
329
+ if (!n || typeof n !== 'object') return null;
330
+ if (n.type === 'button') return n;
331
+ for (const kid of n.children || []) { const hit = findButton(kid); if (hit) return hit; }
332
+ return null;
333
+ };
334
+ return findButton(tree);
335
+ }
336
+
337
+ const chipEn = renderInlineChip((k) => ({ reveal: 'Show secret', hide: 'Hide secret' }[k] || k), false);
338
+ check('胶囊 aria-label 取字典(英文宿主)',
339
+ chipEn && chipEn.props['aria-label'] === 'Show secret', chipEn && chipEn.props['aria-label']);
340
+
341
+ const chipZh = renderInlineChip(null, false);
342
+ check('无字典服务时胶囊回退中文标签',
343
+ chipZh && chipZh.props['aria-label'] === '显示明文', chipZh && chipZh.props['aria-label']);
344
+
282
345
  /**
283
346
  * Render both tabs through a React stub that actually calls function
284
347
  * components. Catches runtime errors in the new settings UI (undefined.map,
@@ -433,6 +496,21 @@ const rebound = fakeRes();
433
496
  await settings.handler({ method: 'GET', socket: { remoteAddress: '198.51.100.78' }, headers: { host: 'evil.example.com:3080' } }, rebound);
434
497
  check('rebound host header rejected', rebound.status === 403 && JSON.parse(rebound.body).error === 'bad-host', rebound.body);
435
498
 
499
+ // Rebinding lands on loopback with a domain Host: same-origin passes, so the
500
+ // Host literal check is the only thing that can still stop it.
501
+ const localRebound = fakeRes();
502
+ await settings.handler({ method: 'GET', socket: { remoteAddress: '127.0.0.1' }, headers: { host: 'evil.example.com:3080' } }, localRebound);
503
+ check('loopback rebound host rejected', localRebound.status === 403 && JSON.parse(localRebound.body).error === 'bad-host', localRebound.body);
504
+
505
+ // Reserved names and literal loopback addresses stay usable.
506
+ const localHostName = fakeRes();
507
+ await settings.handler({ method: 'GET', socket: { remoteAddress: '127.0.0.1' }, headers: { host: 'localhost:3080' } }, localHostName);
508
+ check('loopback localhost still allowed', localHostName.status === 200, String(localHostName.status));
509
+
510
+ const v6Loopback = fakeRes();
511
+ await settings.handler({ method: 'GET', socket: { remoteAddress: '::1' }, headers: { host: '[::1]:3080' } }, v6Loopback);
512
+ check('loopback ::1 still allowed', v6Loopback.status === 200, String(v6Loopback.status));
513
+
436
514
  // Cross-site `text/plain` POST needs no preflight; JSON does.
437
515
  const plainPost = fakeRes();
438
516
  await settings.handler(Object.assign(Readable.from([Buffer.from('{"action":"pause","minutes":30}')]), {