From 80547ec2abf7acdd608fe95c0546043d7f3bd1de Mon Sep 17 00:00:00 2001 From: Muyang Date: Sat, 14 Nov 2026 06:26:28 +0100 Subject: [PATCH] privacy-gate: per-agent controls and a graphical settings page (#1111) privacy-gate's settings page and panel gain per-agent switches and an "other agents" list. disabledAgents entries the UI can't show as one id (globs such as `claude-*`) are kept verbatim on save and lock the rows they match. A save reads the options again and refuses when the agent fields changed since load, and merges into the current object so unrelated options are kept. Run at 30956ba616b3 (the reviewed head), on WSL with a temp HOME: - packages/privacy-gate: bun test, 76 pass / 0 fail. - bun scripts/check.mjs privacy-gate: ok. - Broken by hand: with mergeDisabled dropping patterns, "a glob policy survives an options save and unrelated options are kept" goes red. Thanks @siml1169. --- packages/privacy-gate/README.md | 48 +- packages/privacy-gate/cases.json | 7 +- packages/privacy-gate/docs/design.md | 31 +- packages/privacy-gate/docs/operations.md | 19 + packages/privacy-gate/package.json | 31 +- packages/privacy-gate/page.test.mjs | 116 +++++ packages/privacy-gate/page/agents-panel.html | 31 ++ packages/privacy-gate/page/agents.js | 62 +++ packages/privacy-gate/page/app.js | 476 ++++++++++++++++++ packages/privacy-gate/page/icon.svg | 19 + packages/privacy-gate/page/index.html | 62 +++ packages/privacy-gate/page/panel.js | 261 ++++++++++ packages/privacy-gate/page/policy.js | 97 ++++ packages/privacy-gate/page/style.css | 392 +++++++++++++++ .../privacy-gate/privacy-gate.middleware.js | 27 + 15 files changed, 1671 insertions(+), 8 deletions(-) create mode 100644 packages/privacy-gate/page.test.mjs create mode 100644 packages/privacy-gate/page/agents-panel.html create mode 100644 packages/privacy-gate/page/agents.js create mode 100644 packages/privacy-gate/page/app.js create mode 100644 packages/privacy-gate/page/icon.svg create mode 100644 packages/privacy-gate/page/index.html create mode 100644 packages/privacy-gate/page/panel.js create mode 100644 packages/privacy-gate/page/policy.js create mode 100644 packages/privacy-gate/page/style.css diff --git a/packages/privacy-gate/README.md b/packages/privacy-gate/README.md index abc6f88..a0e303f 100644 --- a/packages/privacy-gate/README.md +++ b/packages/privacy-gate/README.md @@ -13,7 +13,7 @@

- version 0.3.1 + version 0.4.0 license MIT

@@ -52,7 +52,7 @@ Codex, Cursor, Claude Code and scripts. | **Default policy** | `binaryPolicy: fail` — binary part for a non-local model → **403** | | **Alternative** | `binaryPolicy: guide` — withholds bytes, injects type/media/size metadata + a neutral local-tool prompt | | **Text masking** | **Not here.** Use Magpie **Settings → Privacy** | -| **Tests** | 67 cases through the repository's `scripts/middleware.mjs` | +| **Tests** | 72 middleware cases + 4 page/policy checks through the repository harness | ## Install @@ -129,6 +129,24 @@ parts are treated as binary parts; keys with names like `signature`, `id`, `parameters` or `tools` inside tool arguments and message text are ordinary data and are still scanned. +## Per-agent controls + +The middleware is **agent-aware**: Magpie supplies `ctx.agent` to the gateway +hook, so ShyPie can protect some agents and deliberately bypass others. + +Open **Settings → Plugins → Installed → ShyPie → Open page** for the full page, +use the **ShyPie protection** card at the bottom of Magpie's **Agents** page for +quick toggles, or right-click an agent and choose **ShyPie protection** to open +the page focused on that agent. + +Every agent is protected by default, including new agents. A bypass is explicit: +only ids in `disabledAgents` (or an empty `ctx.agent` when +`protectUnknownAgent: false`) skip the gate. `disabledAgents` may also contain +globs or raw policy entries; the page preserves them verbatim and lists them +read-only, and it seeds custom disabled ids so their bypass is visible. The page +warns before a request can leave without protection; saving its switches updates +the same `ctx.options` the middleware reads, with no restart. + ## Configuration All settings are one JSON object, stored as `ctx.options`: @@ -139,6 +157,8 @@ magpie plugin options privacy-gate '{ "allowModels": ["deepseek/*", "copilot/*"], "localModels": ["ollama/*", "lmstudio/*"], "localProviders": ["ollama", "lmstudio"], + "disabledAgents": [], + "protectUnknownAgent": true, "guideTools": ["shypie.describe", "shypie.extract", "shypie.ocr"] }' ``` @@ -146,6 +166,9 @@ magpie plugin options privacy-gate '{ | Option | Default | Meaning | |---|---:|---| | `binaryPolicy` | `fail` | `fail` returns 403; `guide` withholds every binary part and injects metadata + a local-tool prompt. | +| `disabledAgents` | `[]` | Magpie agent ids (or globs) that bypass the gate completely. Empty protects every agent. | +| `protectUnknownAgent` | `true` | Whether a request Magpie cannot name is still gated. | +| `extraAgents` | `[]` | Page-only list of custom agent ids; the middleware ignores it. | | `allowModels` | `[]` | Model globs. `[]` allows every model. If present but not an array of non-empty short strings, **every request is refused** — a typo never silently removes the allowlist. | | `localModels` | `[]` | Model globs allowed to receive binary parts in `onRequest`. Pair with `localProviders`. | | `localProviders` | `[]` | Provider-id globs checked in `onProvider`. Both lists must agree. | @@ -163,6 +186,7 @@ magpie plugin options privacy-gate '{ | Image/file/audio/document parts for non-local models | 403 (`fail`) or withheld (`guide`) | | Encoded blobs in text (base64/base64url, hex, data URI, PDF/ZIP magic) | 403 | | Model outside `allowModels` | 403 | +| Agent in `disabledAgents` | passes unchanged (explicit per-agent bypass) | | Malformed `allowModels` | every request 403 | | Body too complex for the inspection budget | 403 | | Protocol outside the four supported shapes | 403 unless `allowUnknownProtocol: true` | @@ -337,6 +361,20 @@ flowchart LR 工具参数和消息文本中名为 `signature`、`id`、`parameters` 或 `tools` 的字段 属于普通数据,仍会被扫描。 +## 按 Agent 控制 + +中间件是 **Agent 感知** 的:Magpie 会把 `ctx.agent` 提供给网关钩子,因此 ShyPie +可以为部分 Agent 开启防护,并明确绕过其他 Agent。 + +打开 **设置 → 插件 → 已安装 → ShyPie → 打开页面** 使用完整页面;在 Magpie +**Agents** 页面底部的 **ShyPie 防护** 卡片中快速切换;或右键某个 Agent 选择 +**ShyPie 防护**,页面会定位到该 Agent。 + +默认保护所有 Agent,包括新出现的 Agent。绕过必须显式配置:只有 +`disabledAgents` 中的 ID(或在 `protectUnknownAgent: false` 时没有 +`ctx.agent` 的请求)才会跳过防护。页面会在请求可能失去保护时提示;保存开关 +会更新中间件读取的同一份 `ctx.options`,无需重启。 + ## 配置 所有配置都在一个 JSON 对象中,即 `ctx.options`: @@ -347,6 +385,8 @@ magpie plugin options privacy-gate '{ "allowModels": ["deepseek/*", "copilot/*"], "localModels": ["ollama/*", "lmstudio/*"], "localProviders": ["ollama", "lmstudio"], + "disabledAgents": [], + "protectUnknownAgent": true, "guideTools": ["shypie.describe", "shypie.extract", "shypie.ocr"] }' ``` @@ -354,6 +394,9 @@ magpie plugin options privacy-gate '{ | 选项 | 默认值 | 含义 | |---|---:|---| | `binaryPolicy` | `fail` | `fail` 返回 403;`guide` 扣留所有二进制内容,并注入元数据和本地工具提示。 | +| `disabledAgents` | `[]` | 完全绕过防护的 Magpie Agent ID(或 glob)。为空时保护所有 Agent。 | +| `protectUnknownAgent` | `true` | Magpie 无法识别 Agent 时是否仍执行防护。 | +| `extraAgents` | `[]` | 仅页面使用的自定义 Agent ID 列表;中间件忽略。 | | `allowModels` | `[]` | 模型 glob。`[]` 允许所有模型。如果该选项存在但不是由非空短字符串组成的数组,**所有请求都会被拒绝**,拼写错误不会静默取消允许列表。 | | `localModels` | `[]` | 允许在 `onRequest` 接收二进制内容的模型 glob;需要与 `localProviders` 配合。 | | `localProviders` | `[]` | 在 `onProvider` 中检查的 provider-id glob;两个列表必须同时匹配。 | @@ -371,6 +414,7 @@ magpie plugin options privacy-gate '{ | 面向非本地模型的图片/文件/音频/文档 part | 403(`fail`)或扣留(`guide`) | | 文本中的编码数据块(base64/base64url、hex、data URI、PDF/ZIP 头) | 403 | | 模型不在 `allowModels` 中 | 403 | +| Agent 在 `disabledAgents` 中 | 原样通过(显式按 Agent 绕过) | | `allowModels` 格式错误 | 所有请求 403 | | 请求体超出检查预算 | 403 | | 四种支持协议之外的请求 | 403,除非 `allowUnknownProtocol: true` | diff --git a/packages/privacy-gate/cases.json b/packages/privacy-gate/cases.json index 9637281..f9050af 100644 --- a/packages/privacy-gate/cases.json +++ b/packages/privacy-gate/cases.json @@ -1323,5 +1323,10 @@ {"name": "guide: office media maps to the office class", "ctx": {"protocol": "anthropic", "model": "m/x"}, "options": {"binaryPolicy": "guide"}, "request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "file", "source": {"type": "base64", "media_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "data": "iVBORw0KGgo="}}]}]}, "expect_request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "text", "text": "[A binary attachment was withheld locally and was NOT sent to you (type file; media office; bytes 9). Do not claim to have seen it. First ask how the user/agent can process or read it locally.]"}]}]}}, {"name": "guide: parameterized PDF media still maps to pdf", "ctx": {"protocol": "anthropic", "model": "m/x"}, "options": {"binaryPolicy": "guide"}, "request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "file", "source": {"type": "base64", "media_type": "application/pdf; version=1.7", "data": "iVBORw0KGgo="}}]}]}, "expect_request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "text", "text": "[A binary attachment was withheld locally and was NOT sent to you (type file; media pdf; bytes 9). Do not claim to have seen it. First ask how the user/agent can process or read it locally.]"}]}]}}, {"name": "guide: oversized media_type is not normalized", "ctx": {"protocol": "anthropic", "model": "m/x"}, "options": {"binaryPolicy": "guide"}, "request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "file", "source": {"type": "base64", "media_type": "application/pdf; version=1.7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "data": "iVBORw0KGgo="}}]}]}, "expect_request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "text", "text": "[A binary attachment was withheld locally and was NOT sent to you (type file; media unknown; bytes 9). Do not claim to have seen it. First ask how the user/agent can process or read it locally.]"}]}]}}, - {"name": "guide: input_audio kind falls back to audio", "ctx": {"protocol": "chat", "model": "m/x"}, "options": {"binaryPolicy": "guide"}, "request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}}]}]}, "expect_request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "text", "text": "[A binary attachment was withheld locally and was NOT sent to you (type input_audio; media audio). Do not claim to have seen it. First ask how the user/agent can process or read it locally.]"}]}]}} + {"name": "guide: input_audio kind falls back to audio", "ctx": {"protocol": "chat", "model": "m/x"}, "options": {"binaryPolicy": "guide"}, "request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}}]}]}, "expect_request": {"model": "m/x", "messages": [{"role": "user", "content": [{"type": "text", "text": "[A binary attachment was withheld locally and was NOT sent to you (type input_audio; media audio). Do not claim to have seen it. First ask how the user/agent can process or read it locally.]"}]}]}}, + {"name":"agent controls: disabled agent bypasses the gate","ctx":{"protocol":"chat","model":"m/x","agent":"claude"},"options":{"disabledAgents":["claude"]},"request":{"model":"m/x","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]},"provider":{"id":"remote","name":"Remote"}}, + {"name":"agent controls: another agent is still gated","ctx":{"protocol":"chat","model":"m/x","agent":"codex"},"options":{"disabledAgents":["claude"]},"request":{"model":"m/x","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]},"reject":{"status":403,"message":"privacy-gate"}}, + {"name":"agent controls: unknown agent is protected by default","ctx":{"protocol":"chat","model":"m/x"},"options":false,"request":{"model":"m/x","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]},"reject":{"status":403,"message":"privacy-gate"}}, + {"name":"agent controls: unknown agent can be bypassed explicitly","ctx":{"protocol":"chat","model":"m/x"},"options":{"protectUnknownAgent":false},"request":{"model":"m/x","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]},"provider":{"id":"remote","name":"Remote"}}, + {"name":"agent controls: malformed disabledAgents stays gated","ctx":{"protocol":"chat","model":"m/x","agent":"claude"},"options":{"disabledAgents":"claude"},"request":{"model":"m/x","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]},"reject":{"status":403,"message":"privacy-gate"}} ] diff --git a/packages/privacy-gate/docs/design.md b/packages/privacy-gate/docs/design.md index dc9f8e9..5aa8a5e 100644 --- a/packages/privacy-gate/docs/design.md +++ b/packages/privacy-gate/docs/design.md @@ -166,12 +166,37 @@ only needs enough information to choose a local extractor. MIME parameters are stripped before classification, and oversized candidates are ignored before lowercasing so untrusted metadata cannot add unbounded normalization work. +## Agent controls + +Magpie supplies `ctx.agent` to the gateway middleware. ShyPie uses it only for +policy selection: + +- `disabledAgents` (exact ids or globs) bypasses both `onRequest` and + `onProvider` for that agent; the request is returned unchanged. +- `protectUnknownAgent` defaults to `true`. An empty `ctx.agent` stays gated + unless the operator explicitly opts out. +- New agents and newly added plugin agents are protected by default. The policy + is a deny-list, not an allow-list, so an unrecognised agent cannot silently + escape the gate. +- The page, the Agents-page panel and the agent-row action all edit the same + `disabledAgents` and `protectUnknownAgent` options. The page also keeps a + page-only `extraAgents` catalogue for custom ids; the middleware ignores it. +- Disabled ids and raw policy entries are separate. Exact ids get switches; + globs and values the UI cannot represent are kept verbatim, shown read-only, + and merged back on save. The page seeds custom exact ids from + `disabledAgents` so a custom bypass is not invisible. +- Saving starts from freshly read options and changes only the three page-owned + fields. A concurrent change to those fields is reported instead of overwritten; + controls are disabled while a write is pending. +- `ctx.agent` is host-classified metadata, never a User-Agent header. Session + ids and working directories are not used for UI policy. + ## Verification -- 67 cases in `cases.json`, run through `scripts/middleware.mjs` using the same +- 72 cases in `cases.json`, run through `scripts/middleware.mjs` using the same hook calls Magpie performs. - The package has no network, timers, Node APIs or imports; the middleware file is one plain JavaScript module. - The tests cover fail/guide mode, malformed options, all four protocols, - vendor-sealed replay fields, site scoping, blob scanning, and guide-mode - bounds. + vendor-sealed replay fields, site scoping, blob scanning, agent controls, and + guide-mode bounds. diff --git a/packages/privacy-gate/docs/operations.md b/packages/privacy-gate/docs/operations.md index 98e5472..8387154 100644 --- a/packages/privacy-gate/docs/operations.md +++ b/packages/privacy-gate/docs/operations.md @@ -64,6 +64,25 @@ in the guide prompt. 5. Check Magpie's plugin log for counts and the `usage` line. The middleware never logs request content — only provider/model/status/blocked counters. +## Per-agent controls + +Open **Settings → Plugins → Installed → ShyPie → Open page** for the full +per-agent page. The same switches are available in the **ShyPie protection** +card at the bottom of Magpie's **Agents** page, and right-clicking an agent adds +**ShyPie protection** to its row menu. + +Every agent is protected by default. A switch that is off writes that agent's id +to `disabledAgents`; it bypasses both the request gate and the provider check. +Globs and raw values are preserved verbatim and shown read-only under **Policy +patterns**. A custom id already present only in `disabledAgents` is seeded into +the page so its bypass stays visible. The **Unknown / unclassified agent** switch +controls `protectUnknownAgent` and defaults to on. Saving applies to the next +request; no Magpie restart is needed. If options changed elsewhere, the page asks +you to reload rather than overwriting the newer values. + +A bypassed agent is intentionally unprotected, including binary parts and +encoded blobs. Use it only for an agent whose traffic you have chosen to trust. + ## Troubleshooting ### I get a 403 for an image diff --git a/packages/privacy-gate/package.json b/packages/privacy-gate/package.json index 018cbda..a45c1fd 100644 --- a/packages/privacy-gate/package.json +++ b/packages/privacy-gate/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/middleware-privacy-gate", - "version": "0.3.1", + "version": "0.4.0", "description": "Structural egress gate for Magpie: withholds or rejects image/file/audio parts, encoded blobs and disallowed models, and guides agents toward local extraction when Magpie cannot mask text. Companion to ShyPie for DeepSeek Harness.", "type": "module", "files": [ @@ -8,7 +8,8 @@ "README.md", "BRAND.md", "assets", - "docs" + "docs", + "page" ], "keywords": [ "magpie", @@ -29,11 +30,37 @@ "magpie": { "middleware": "./privacy-gate.middleware.js", "icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/privacy-gate/assets/shypie-icon.svg", + "page": { + "title": "ShyPie Filter", + "titles": { "zh": "ShyPie 防护" }, + "file": "page/index.html", + "icon": "page/icon.svg" + }, + "panels": [ + { + "slot": "agents", + "file": "page/agents-panel.html", + "title": "ShyPie protection", + "titles": { "zh": "ShyPie 防护" } + } + ], + "actions": [ + { + "id": "shypie-protection", + "menu": "agent", + "title": "ShyPie protection", + "titles": { "zh": "ShyPie 防护" } + } + ], + "permissions": [], "options": { "allowModels": [], "localModels": [], "localProviders": [], "binaryPolicy": "fail", + "disabledAgents": [], + "protectUnknownAgent": true, + "extraAgents": [], "guideTools": [], "allowUnknownProtocol": false, "blobBase64Chars": 400, diff --git a/packages/privacy-gate/page.test.mjs b/packages/privacy-gate/page.test.mjs new file mode 100644 index 0000000..467fb19 --- /dev/null +++ b/packages/privacy-gate/page.test.mjs @@ -0,0 +1,116 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' + +const dir = new URL('./page/', import.meta.url) +const read = (file) => readFileSync(new URL(file, dir), 'utf8') + +function bridgeCalls(source) { + return [...source.matchAll(/\bmagpie\s*(?:\?\.|\.)\s*([\w$]+(?:\s*(?:\?\.|\.)\s*[\w$]+)*)/g)] + .map(([, call]) => call.replace(/\s/g, '').replaceAll('?.', '.')) +} + +function safePageScript(source, allowed) { + if (/\b(fetch|XMLHttpRequest|WebSocket|EventSource)\b/.test(source)) return false + if (/\bmagpie\s*\[|\b(?:window|globalThis)\s*\[\s*["']magpie["']\s*\]/.test(source)) return false + return bridgeCalls(source).every((call) => allowed.includes(call)) +} + +test('page and panel use only the released bridge and make no network calls', () => { + const app = read('app.js') + const panel = read('panel.js') + const agents = read('agents.js') + const policy = read('policy.js') + const page = read('index.html') + const panelPage = read('agents-panel.html') + const allowed = ['ready', 'options.get', 'options.set', 'onAction'] + + expect(safePageScript(app, allowed)).toBe(true) + expect(safePageScript(panel, allowed)).toBe(true) + expect(safePageScript(agents, [])).toBe(true) + expect(safePageScript(policy, [])).toBe(true) + for (const source of [app, panel]) { + expect(safePageScript(`${source}\nfetch('https://evil.example/x')`, allowed)).toBe(false) + expect(safePageScript(`${source}\nmagpie.read?.('secrets')`, allowed)).toBe(false) + expect(safePageScript(`${source}\nmagpie['read']('secrets')`, allowed)).toBe(false) + } + + for (const html of [page, panelPage]) { + expect(html).not.toMatch(/]*\bsrc\s*=)[^>]*>/i) + expect(html).not.toMatch(/\b(?:src|href)\s*=\s*(?:["']\s*)?(?:https?:)?\/\//i) + expect(html).not.toMatch(/\bon[a-z]+\s*=/i) + const tags = [...html.matchAll(/]*)>/gi)] + const sources = tags.map(([, attrs]) => attrs.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1]).filter(Boolean) + expect(sources).toContain('_magpie/bridge.js') + expect(sources).toContain('agents.js') + expect(sources).toContain('policy.js') + expect(sources).toContain(html === page ? 'app.js' : 'panel.js') + expect(tags).toHaveLength(sources.length) + } +}) + +test('a glob policy survives an options save and unrelated options are kept', () => { + const sandbox = {} + sandbox.globalThis = sandbox + runInNewContext(read('agents.js'), sandbox) + runInNewContext(read('policy.js'), sandbox) + const A = sandbox.ShyPieAgents + const P = sandbox.ShyPiePolicy + expect(A.KNOWN.some((row) => row.id === 'claude-code')).toBe(false) + expect(A.KNOWN.some((row) => row.id === 'aider')).toBe(false) + const split = P.split(['claude*', 'codex', ' claude ', 'CLAUDE']) + expect(split.exact).toEqual(['codex']) + expect(split.patterns).toEqual(['claude*', ' claude ', 'CLAUDE']) + expect(P.matches('claude*', 'claude')).toBe(true) + expect(P.matches('claude*', 'claude-desktop')).toBe(true) + expect(P.matches('Claude*', 'claude')).toBe(false) + expect(P.matches('*', 'anything')).toBe(true) + expect(P.patternFor(['claude*'], 'claude')).toBe('claude*') + expect(P.mergeDisabled(split.patterns, ['codex'])).toEqual(['claude*', ' claude ', 'CLAUDE', 'codex']) + const merged = P.mergeOptions( + { binaryPolicy: 'guide', allowModels: ['safe/*'] }, + { patterns: split.patterns, exact: ['codex'], protectUnknown: false, extra: ['my-agent'] }, + ) + expect(merged.binaryPolicy).toBe('guide') + expect(merged.allowModels).toEqual(['safe/*']) + expect(merged.disabledAgents).toEqual(['claude*', ' claude ', 'CLAUDE', 'codex']) + expect(merged.protectUnknownAgent).toBe(false) + expect(merged.extraAgents).toEqual(['my-agent']) + expect(P.sameAgentFields( + { disabledAgents: ['claude*'], protectUnknownAgent: true, extraAgents: [] }, + { disabledAgents: ['claude*'], protectUnknownAgent: true, extraAgents: [] }, + )).toBe(true) + expect(P.sameAgentFields( + { disabledAgents: ['claude*'], protectUnknownAgent: true, extraAgents: [] }, + { disabledAgents: ['claude*', 'codex'], protectUnknownAgent: true, extraAgents: [] }, + )).toBe(false) +}) + +test('the shared agent catalogue validates ids and keeps custom agents', () => { + const sandbox = {} + sandbox.globalThis = sandbox + runInNewContext(read('agents.js'), sandbox) + const A = sandbox.ShyPieAgents + expect(A.normalizeId(' My-Agent ')).toBe('my-agent') + expect(A.normalizeId('bad id')).toBe('') + expect(A.normalizeList(['Claude', 'claude', 'my_agent'])).toEqual(['claude', 'my_agent']) + expect(A.allRows(['my-agent']).some((row) => row.id === 'my-agent')).toBe(true) + expect(A.KNOWN.some((row) => row.id === 'dsh')).toBe(true) +}) + +test('package declares the page, Agents panel and agent action', () => { + const pkg = JSON.parse(read('../package.json')) + expect(pkg.version).toBe('0.4.0') + expect(pkg.files).toContain('page') + expect(pkg.magpie.page.file).toBe('page/index.html') + expect(pkg.magpie.page.icon).toBe('page/icon.svg') + expect(pkg.magpie.panels).toEqual([ + expect.objectContaining({ slot: 'agents', file: 'page/agents-panel.html' }), + ]) + expect(pkg.magpie.actions).toEqual([ + expect.objectContaining({ menu: 'agent', id: 'shypie-protection' }), + ]) + expect(pkg.magpie.permissions).toEqual([]) + expect(pkg.magpie.options.disabledAgents).toEqual([]) + expect(pkg.magpie.options.protectUnknownAgent).toBe(true) +}) diff --git a/packages/privacy-gate/page/agents-panel.html b/packages/privacy-gate/page/agents-panel.html new file mode 100644 index 0000000..93f771f --- /dev/null +++ b/packages/privacy-gate/page/agents-panel.html @@ -0,0 +1,31 @@ + + + + + + ShyPie protection + + + +
+
+
+

ShyPie Filter

+

Agent protection

+

Disabled agents bypass the gate entirely.

+
+ +
+
+ +
+ + +
+
+ + + + + + diff --git a/packages/privacy-gate/page/agents.js b/packages/privacy-gate/page/agents.js new file mode 100644 index 0000000..a5ffd71 --- /dev/null +++ b/packages/privacy-gate/page/agents.js @@ -0,0 +1,62 @@ +/* Shared agent catalogue and small pure helpers for the ShyPie page and panel. + * This file is loaded as a plain browser script; it makes no network calls. */ +(function (root) { + 'use strict' + + var KNOWN = [ + { id: 'claude', name: 'Claude Code', group: 'Coding agents' }, + { id: 'claude-desktop', name: 'Claude Desktop', group: 'Desktop apps' }, + { id: 'codex', name: 'Codex', group: 'Coding agents' }, + { id: 'dsh', name: 'DeepSeek Harness', group: 'Coding agents' }, + { id: 'gemini', name: 'Gemini CLI', group: 'Coding agents' }, + { id: 'qwen', name: 'Qwen Code', group: 'Coding agents' }, + { id: 'kimi', name: 'Kimi Code', group: 'Coding agents' }, + { id: 'grok', name: 'Grok', group: 'Coding agents' }, + { id: 'opencode', name: 'OpenCode', group: 'Coding agents' }, + { id: 'pi', name: 'Pi', group: 'Coding agents' }, + { id: 'omp', name: 'omp', group: 'Coding agents' }, + { id: 'cursor', name: 'Cursor', group: 'Desktop apps' }, + { id: 'copilot', name: 'Copilot CLI', group: 'Coding agents' }, + { id: 'devin', name: 'Devin', group: 'Coding agents' } + ] + + var KNOWN_IDS = {} + for (var i = 0; i < KNOWN.length; i++) KNOWN_IDS[KNOWN[i].id] = true + + function normalizeId(value) { + if (typeof value !== 'string') return '' + var id = value.trim().toLowerCase() + return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(id) ? id : '' + } + + function normalizeList(value) { + var out = [] + if (!Array.isArray(value)) return out + for (var i = 0; i < value.length && out.length < 200; i++) { + var id = normalizeId(value[i]) + if (id && out.indexOf(id) === -1) out.push(id) + } + return out + } + + function customRows(ids) { + var out = [] + for (var i = 0; i < ids.length; i++) { + if (!KNOWN_IDS[ids[i]]) out.push({ id: ids[i], name: ids[i], group: 'Other agents' }) + } + return out + } + + function allRows(extraIds) { + return KNOWN.concat(customRows(normalizeList(extraIds))) + } + + root.ShyPieAgents = { + KNOWN: KNOWN, + KNOWN_IDS: KNOWN_IDS, + normalizeId: normalizeId, + normalizeList: normalizeList, + customRows: customRows, + allRows: allRows + } +})(typeof globalThis !== 'undefined' ? globalThis : this) diff --git a/packages/privacy-gate/page/app.js b/packages/privacy-gate/page/app.js new file mode 100644 index 0000000..5253a95 --- /dev/null +++ b/packages/privacy-gate/page/app.js @@ -0,0 +1,476 @@ +(function () { + 'use strict' + + var A = window.ShyPieAgents + var P = window.ShyPiePolicy + var $ = function (id) { return document.getElementById(id) } + + var COPY = { + en: { + kicker: 'ShyPie Filter', + title: 'Per-agent protection', + lede: 'Choose which Magpie agents ShyPie protects. A disabled agent bypasses the gate entirely.', + search: 'Search agents', + reload: 'Reload', + save: 'Save changes', + saved: 'Saved', + unsaved: 'Unsaved changes', + loading: 'Loading agents…', + failed: 'Could not read the ShyPie options.', + saveFailed: 'Could not save. Try again.', + changedElsewhere: 'These options changed elsewhere. Reload before saving.', + protected: 'protected', + bypassed: 'bypassed', + policyBypassed: 'bypassed by policy', + unknown: 'Unknown / unclassified agent', + unknownHint: 'Applies when Magpie cannot identify the calling agent.', + other: 'Other agents', + unknownGroup: 'Unclassified', + addTitle: 'Add another agent id', + addHint: 'For a plugin-added or not-yet-listed agent. You can also use the agent row menu on the Agents page.', + addPlaceholder: 'e.g. my-agent', + add: 'Add', + addError: 'Use a lowercase id like my-agent.', + empty: 'No agents match that search.', + warningAll: 'All agents are bypassed. ShyPie is not protecting any request.', + warningSome: 'A bypassed agent sends its requests without ShyPie.', + patternsTitle: 'Policy patterns', + patternsHint: 'Raw entries in disabledAgents that this page cannot show as a switch. They are preserved on save; edit them with the JSON options or CLI.', + patternsPreserved: 'Patterns are preserved on save.' + }, + zh: { + kicker: 'ShyPie 防护', + title: '按 Agent 保护', + lede: '选择哪些 Magpie Agent 受 ShyPie 保护。关闭的 Agent 会完全绕过防护。', + search: '搜索 Agent', + reload: '重新加载', + save: '保存更改', + saved: '已保存', + unsaved: '未保存的更改', + loading: '正在加载 Agent…', + failed: '无法读取 ShyPie 配置。', + saveFailed: '保存失败,请重试。', + changedElsewhere: '配置已在其他位置更改,请重新加载后再保存。', + protected: '受保护', + bypassed: '已绕过', + policyBypassed: '被策略绕过', + unknown: '未知 / 未分类 Agent', + unknownHint: '当 Magpie 无法识别调用方 Agent 时适用。', + other: '其他 Agent', + unknownGroup: '未分类', + addTitle: '添加其他 Agent ID', + addHint: '用于插件添加或尚未列出的 Agent;也可以使用 Agents 页面中的 Agent 行菜单。', + addPlaceholder: '例如 my-agent', + add: '添加', + addError: '请使用 my-agent 这样的小写 ID。', + empty: '没有匹配的 Agent。', + warningAll: '所有 Agent 都已绕过,ShyPie 当前不保护任何请求。', + warningSome: '已绕过的 Agent 会不经过 ShyPie 直接发送请求。', + patternsTitle: '策略模式', + patternsHint: 'disabledAgents 中无法以开关显示的原始条目。保存时会原样保留;请通过 JSON 配置或 CLI 编辑。', + patternsPreserved: '保存时会保留策略模式。' + } + } + + var state = { + options: {}, + exact: [], + patterns: [], + extra: [], + protectUnknown: true, + rows: [], + search: '', + target: '', + dirty: false, + saved: false, + busy: false, + error: '', + loaded: { disabledAgents: [], protectUnknownAgent: true, extraAgents: [] }, + pendingAction: null, + lang: 'en' + } + + function t(key) { + return (COPY[state.lang] || COPY.en)[key] || COPY.en[key] || key + } + + function setText(id, value) { + var el = $(id) + if (el) el.textContent = value + } + + function uniqueList(values) { + var out = [] + for (var i = 0; i < values.length; i++) { + if (values[i] && out.indexOf(values[i]) === -1) out.push(values[i]) + } + return out + } + + function clearError() { + state.error = '' + } + + function applyLanguage() { + var html = document.documentElement + html.lang = state.lang === 'zh' ? 'zh-CN' : 'en' + document.title = t('kicker') + var map = { + 'search-label': 'search', + 'add-title': 'addTitle', + 'add-hint': 'addHint', + 'add': 'add', + 'save': 'save', + 'reload': 'reload', + 'kicker': 'kicker', + 'title': 'title', + 'lede': 'lede', + 'patterns-title': 'patternsTitle', + 'patterns-hint': 'patternsHint' + } + Object.keys(map).forEach(function (id) { setText(id, t(map[id])) }) + var search = $('search') + if (search) search.placeholder = t('search') + var addInput = $('add-id') + if (addInput) addInput.placeholder = t('addPlaceholder') + var error = $('add-error') + if (error) error.textContent = t('addError') + var empty = $('empty') + if (empty) empty.textContent = t('empty') + } + + function ensureExtra(id) { + if (A.KNOWN_IDS[id] || state.extra.indexOf(id) !== -1) return false + state.extra.push(id) + return true + } + + function configure(options) { + state.options = options && typeof options === 'object' ? options : {} + var split = P.split(state.options.disabledAgents) + state.exact = split.exact + state.patterns = split.patterns + state.extra = A.normalizeList(state.options.extraAgents) + for (var i = 0; i < split.exact.length; i++) ensureExtra(split.exact[i]) + state.protectUnknown = state.options.protectUnknownAgent !== false + state.rows = A.allRows(state.extra) + state.loaded = { + disabledAgents: P.rawList(state.options.disabledAgents), + protectUnknownAgent: state.protectUnknown, + extraAgents: P.rawList(state.options.extraAgents) + } + } + + function patternFor(id) { + return P.patternFor(state.patterns, id) + } + + function isDisabled(id) { + return state.exact.indexOf(id) !== -1 || patternFor(id) !== null + } + + function setDisabled(id, disabled) { + if (patternFor(id) !== null) return + var next = state.exact.filter(function (item) { return item !== id }) + if (disabled) next.push(id) + state.exact = uniqueList(next) + clearError() + state.dirty = true + render() + } + + function protectedCount() { + var total = state.rows.length + 1 + var on = state.rows.filter(function (row) { return !isDisabled(row.id) }).length + if (state.protectUnknown) on++ + return { on: on, total: total } + } + + function avatar(name) { + var parts = String(name || '?').split(/[\s._-]+/).filter(Boolean) + return (parts.length > 1 ? parts[0].charAt(0) + parts[1].charAt(0) : String(name || '?').slice(0, 2)).toUpperCase() + } + + function makeSwitch(label, checked, onChange, disabled) { + var button = document.createElement('button') + button.type = 'button' + button.className = 'switch' + button.setAttribute('role', 'switch') + button.setAttribute('aria-checked', checked ? 'true' : 'false') + button.setAttribute('aria-label', label) + button.disabled = disabled === true + button.addEventListener('click', function () { + if (button.disabled) return + onChange(button.getAttribute('aria-checked') !== 'true') + }) + return button + } + + function agentRow(row) { + var item = document.createElement('div') + item.className = 'agent' + (state.target === row.id ? ' is-target' : '') + item.setAttribute('role', 'listitem') + var badge = document.createElement('span') + badge.className = 'avatar' + badge.textContent = avatar(row.name) + badge.setAttribute('aria-hidden', 'true') + var copy = document.createElement('span') + copy.className = 'agent-copy' + var name = document.createElement('span') + name.className = 'agent-name' + name.textContent = row.name + var id = document.createElement('span') + id.className = 'agent-id' + var pattern = patternFor(row.id) + var off = pattern !== null || state.exact.indexOf(row.id) !== -1 + id.textContent = row.id + ' · ' + (pattern !== null ? t('policyBypassed') : (off ? t('bypassed') : t('protected'))) + copy.appendChild(name) + copy.appendChild(id) + item.appendChild(badge) + item.appendChild(copy) + item.appendChild(makeSwitch( + row.id, + !off, + function (enabled) { setDisabled(row.id, !enabled) }, + pattern !== null || state.busy + )) + if (pattern !== null) item.title = t('policyBypassed') + ': ' + String(pattern) + return item + } + + function appendGroup(parent, title, rows) { + if (rows.length === 0) return + var group = document.createElement('section') + group.className = 'group' + var heading = document.createElement('h2') + heading.className = 'group-title' + heading.textContent = title + group.appendChild(heading) + for (var i = 0; i < rows.length; i++) group.appendChild(agentRow(rows[i])) + parent.appendChild(group) + } + + function renderPatterns() { + var section = $('patterns') + var list = $('pattern-list') + if (!section || !list) return + section.hidden = state.patterns.length === 0 + list.replaceChildren() + for (var i = 0; i < state.patterns.length; i++) { + var item = document.createElement('li') + var value = state.patterns[i] + item.textContent = typeof value === 'string' ? value : JSON.stringify(value) + list.appendChild(item) + } + } + + function render() { + if (!A || !P) return + var query = state.search.trim().toLowerCase() + var visible = state.rows.filter(function (row) { + return query === '' || row.id.indexOf(query) !== -1 || row.name.toLowerCase().indexOf(query) !== -1 + }) + var groups = {} + var order = [] + for (var i = 0; i < visible.length; i++) { + var group = visible[i].group || t('other') + if (!groups[group]) { groups[group] = []; order.push(group) } + groups[group].push(visible[i]) + } + var list = $('list') + list.replaceChildren() + for (var g = 0; g < order.length; g++) appendGroup(list, order[g], groups[order[g]]) + var showUnknown = query === '' || t('unknown').toLowerCase().indexOf(query) !== -1 || 'unknown'.indexOf(query) !== -1 + if (showUnknown) appendUnknown(list) + $('empty').hidden = visible.length > 0 || showUnknown + renderPatterns() + + var counts = protectedCount() + setText('count', counts.on + ' / ' + counts.total + ' ' + t('protected')) + var warning = $('warning') + if (counts.on === 0) { + warning.textContent = t('warningAll') + warning.hidden = false + } else if (counts.on < counts.total) { + warning.textContent = t('warningSome') + warning.hidden = false + } else { + warning.hidden = true + } + $('save').disabled = !state.dirty || state.busy + $('reload').disabled = state.busy + $('add-agent').disabled = state.busy + $('add-id').disabled = state.busy + var status = $('status') + if (state.error) { + status.textContent = state.error + status.setAttribute('data-error', 'true') + } else { + status.textContent = state.dirty ? t('unsaved') : (state.saved ? t('saved') : '') + status.removeAttribute('data-error') + } + } + + function appendUnknown(parent) { + var group = document.createElement('section') + group.className = 'group' + var heading = document.createElement('h2') + heading.className = 'group-title' + heading.textContent = t('unknownGroup') + group.appendChild(heading) + var item = document.createElement('div') + item.className = 'agent' + (state.target === 'unknown' ? ' is-target' : '') + item.setAttribute('role', 'listitem') + var badge = document.createElement('span') + badge.className = 'avatar' + badge.textContent = '?' + badge.setAttribute('aria-hidden', 'true') + var copy = document.createElement('span') + copy.className = 'agent-copy' + var name = document.createElement('span') + name.className = 'agent-name' + name.textContent = t('unknown') + var hint = document.createElement('span') + hint.className = 'agent-id' + hint.textContent = t('unknownHint') + copy.appendChild(name) + copy.appendChild(hint) + item.appendChild(badge) + item.appendChild(copy) + item.appendChild(makeSwitch(t('unknown'), state.protectUnknown, function (enabled) { + state.protectUnknown = enabled + clearError() + state.dirty = true + render() + }, state.busy)) + group.appendChild(item) + parent.appendChild(group) + } + + function addAgent() { + if (state.busy) return + var input = $('add-id') + var error = $('add-error') + var id = A.normalizeId(input.value) + if (!id) { + error.hidden = false + input.focus() + return + } + error.hidden = true + var added = ensureExtra(id) + state.rows = A.allRows(state.extra) + state.search = '' + $('search').value = '' + state.target = id + clearError() + if (added) state.dirty = true + input.value = '' + render() + focusTarget() + } + + function focusTarget() { + var match = $('list').querySelector('.is-target') + if (!match) return + var control = match.querySelector('.switch:not(:disabled)') + ;(control || match).focus() + } + + function save() { + if (state.busy || !state.dirty) return + state.busy = true + clearError() + render() + var edit = { + patterns: state.patterns, + exact: state.exact, + protectUnknown: state.protectUnknown, + extra: state.extra + } + Promise.resolve(magpie.options.get()).then(function (current) { + if (!P.sameAgentFields(current, state.loaded)) { + var conflict = new Error('options changed elsewhere') + conflict.conflict = true + throw conflict + } + return magpie.options.set(P.mergeOptions(current, edit)) + }).then(function (saved) { + configure(saved) + state.busy = false + state.dirty = false + state.saved = true + clearError() + render() + }).catch(function (error) { + state.busy = false + state.error = error && error.conflict ? t('changedElsewhere') : t('saveFailed') + render() + }) + } + + function focusAction(action) { + if (state.busy) return + var agent = action && action.agent + if (!agent || typeof agent.id !== 'string') return + var id = A.normalizeId(agent.id) + if (!id) return + var added = ensureExtra(id) + state.rows = A.allRows(state.extra) + state.search = '' + $('search').value = '' + state.target = id + var named = state.rows.filter(function (row) { return row.id === id })[0] + if (named && typeof agent.name === 'string' && agent.name.trim() !== '') named.name = agent.name.trim() + if (added) { + clearError() + state.dirty = true + } + render() + focusTarget() + } + + function load() { + state.saved = false + clearError() + setText('status', t('loading')) + Promise.resolve(magpie.ready).then(function (theme) { + state.lang = theme && String(theme.lang).toLowerCase().indexOf('zh') === 0 ? 'zh' : 'en' + applyLanguage() + return magpie.options.get() + }).then(function (options) { + configure(options) + render() + if (state.pendingAction) { + focusAction(state.pendingAction) + state.pendingAction = null + } + }).catch(function () { + state.error = t('failed') + render() + }) + } + + $('search').addEventListener('input', function (event) { + state.search = event.target.value || '' + render() + }) + $('reload').addEventListener('click', function () { + state.dirty = false + load() + }) + $('add-agent').addEventListener('click', addAgent) + $('add-id').addEventListener('keydown', function (event) { + if (event.key === 'Enter' && !state.busy) addAgent() + }) + $('save').addEventListener('click', save) + + if (typeof magpie.onAction === 'function') { + magpie.onAction(function (action) { + if (state.rows.length > 0) focusAction(action) + else state.pendingAction = action + }) + } + + load() +})() diff --git a/packages/privacy-gate/page/icon.svg b/packages/privacy-gate/page/icon.svg new file mode 100644 index 0000000..2028d4f --- /dev/null +++ b/packages/privacy-gate/page/icon.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/packages/privacy-gate/page/index.html b/packages/privacy-gate/page/index.html new file mode 100644 index 0000000..6585ef5 --- /dev/null +++ b/packages/privacy-gate/page/index.html @@ -0,0 +1,62 @@ + + + + + + ShyPie + + + +
+
+ +
+

ShyPie Filter

+

Per-agent protection

+

Choose which Magpie agents ShyPie protects. A disabled agent bypasses the gate entirely.

+
+

+
+ +
+ + +
+ + +
+ + + + +
+
+

Add another agent id

+

For a plugin-added or not-yet-listed Magpie agent. You can also use an agent's row menu on the Agents page.

+
+
+ + + +
+ +
+ +
+ + +
+
+ + + + + + diff --git a/packages/privacy-gate/page/panel.js b/packages/privacy-gate/page/panel.js new file mode 100644 index 0000000..3ff1a68 --- /dev/null +++ b/packages/privacy-gate/page/panel.js @@ -0,0 +1,261 @@ +(function () { + 'use strict' + + var A = window.ShyPieAgents + var P = window.ShyPiePolicy + var $ = function (id) { return document.getElementById(id) } + var SHOWN = ['claude', 'codex', 'dsh', 'gemini', 'qwen', 'kimi', 'opencode', 'cursor'] + + var COPY = { + en: { + title: 'Agent protection', + lede: 'Disabled agents bypass the gate entirely.', + save: 'Save', + saved: 'Saved', + unsaved: 'Unsaved changes', + failed: 'Could not load.', + saveFailed: 'Could not save.', + changedElsewhere: 'Changed elsewhere; reload.', + protected: 'protected', + unknown: 'Unknown agent', + policy: 'Policy patterns are preserved on save.', + policyBypassed: 'bypassed by policy' + }, + zh: { + title: '按 Agent 保护', + lede: '关闭的 Agent 会完全绕过防护。', + save: '保存', + saved: '已保存', + unsaved: '未保存', + failed: '加载失败。', + saveFailed: '保存失败。', + changedElsewhere: '配置已更改,请重新加载。', + protected: '受保护', + unknown: '未知 Agent', + policy: '策略模式会在保存时保留。', + policyBypassed: '被策略绕过' + } + } + + var state = { + exact: [], + patterns: [], + extra: [], + protectUnknown: true, + lang: 'en', + dirty: false, + saved: false, + busy: false, + error: '', + loaded: { disabledAgents: [], protectUnknownAgent: true, extraAgents: [] } + } + + function t(key) { + return (COPY[state.lang] || COPY.en)[key] || COPY.en[key] || key + } + + function setText(id, value) { + var el = $(id) + if (el) el.textContent = value + } + + function clearError() { + state.error = '' + } + + function configure(options) { + var source = options && typeof options === 'object' ? options : {} + var split = P.split(source.disabledAgents) + state.exact = split.exact + state.patterns = split.patterns + state.extra = A.normalizeList(source.extraAgents) + for (var i = 0; i < split.exact.length; i++) { + if (!A.KNOWN_IDS[split.exact[i]] && state.extra.indexOf(split.exact[i]) === -1) state.extra.push(split.exact[i]) + } + state.protectUnknown = source.protectUnknownAgent !== false + state.loaded = { + disabledAgents: P.rawList(source.disabledAgents), + protectUnknownAgent: state.protectUnknown, + extraAgents: P.rawList(source.extraAgents) + } + } + + function patternFor(id) { + return P.patternFor(state.patterns, id) + } + + function isDisabled(id) { + return state.exact.indexOf(id) !== -1 || patternFor(id) !== null + } + + function setDisabled(id, disabled) { + if (patternFor(id) !== null) return + state.exact = state.exact.filter(function (item) { return item !== id }) + if (disabled) state.exact.push(id) + clearError() + state.dirty = true + render() + } + + function shownRows() { + var out = [] + for (var i = 0; i < A.KNOWN.length; i++) { + if (SHOWN.indexOf(A.KNOWN[i].id) !== -1 || isDisabled(A.KNOWN[i].id)) out.push(A.KNOWN[i]) + } + var custom = A.customRows(state.extra) + custom.sort(function (a, b) { + var ad = isDisabled(a.id) ? 0 : 1 + var bd = isDisabled(b.id) ? 0 : 1 + return ad - bd + }) + return out.concat(custom.slice(0, 3)) + } + + function count() { + var rows = shownRows() + var on = rows.filter(function (row) { return !isDisabled(row.id) }).length + if (state.protectUnknown) on++ + return { on: on, total: rows.length + 1 } + } + + function makeSwitch(id, checked, disabled, onToggle) { + var button = document.createElement('button') + button.type = 'button' + button.className = 'switch' + button.setAttribute('role', 'switch') + button.setAttribute('aria-checked', checked ? 'true' : 'false') + button.setAttribute('aria-label', id) + button.disabled = disabled === true + button.addEventListener('click', function () { + if (button.disabled) return + if (typeof onToggle === 'function') onToggle(button.getAttribute('aria-checked') !== 'true') + else setDisabled(id, button.getAttribute('aria-checked') === 'true') + }) + return button + } + + function rowView(row) { + var item = document.createElement('div') + item.className = 'agent' + item.setAttribute('role', 'listitem') + var badge = document.createElement('span') + badge.className = 'avatar' + badge.textContent = String(row.name || row.id).slice(0, 2).toUpperCase() + badge.setAttribute('aria-hidden', 'true') + var copy = document.createElement('span') + copy.className = 'agent-copy' + var name = document.createElement('span') + name.className = 'agent-name' + name.textContent = row.name + var id = document.createElement('span') + id.className = 'agent-id' + var pattern = patternFor(row.id) + var off = pattern !== null || state.exact.indexOf(row.id) !== -1 + id.textContent = row.id + (pattern !== null ? ' · ' + t('policyBypassed') : '') + copy.appendChild(name) + copy.appendChild(id) + item.appendChild(badge) + item.appendChild(copy) + item.appendChild(makeSwitch(row.id, !off, pattern !== null || state.busy, function (enabled) { + setDisabled(row.id, !enabled) + })) + if (pattern !== null) item.title = t('policyBypassed') + ': ' + String(pattern) + return item + } + + function render() { + if (!A || !P) return + var list = $('panel-list') + list.replaceChildren() + var rows = shownRows() + for (var i = 0; i < rows.length; i++) list.appendChild(rowView(rows[i])) + var unknown = document.createElement('div') + unknown.className = 'agent' + unknown.setAttribute('role', 'listitem') + var badge = document.createElement('span') + badge.className = 'avatar' + badge.textContent = '?' + badge.setAttribute('aria-hidden', 'true') + var copy = document.createElement('span') + copy.className = 'agent-copy' + var name = document.createElement('span') + name.className = 'agent-name' + name.textContent = t('unknown') + copy.appendChild(name) + unknown.appendChild(badge) + unknown.appendChild(copy) + unknown.appendChild(makeSwitch('unknown', state.protectUnknown, state.busy, function (on) { + state.protectUnknown = on + clearError() + state.dirty = true + render() + })) + list.appendChild(unknown) + + var problem = $('panel-patterns') + problem.hidden = state.patterns.length === 0 + problem.textContent = state.patterns.length === 0 ? '' : t('policy') + + var c = count() + setText('panel-count', c.on + ' / ' + c.total + ' ' + t('protected')) + $('panel-save').disabled = !state.dirty || state.busy + var status = $('panel-status') + if (state.error) { + status.textContent = state.error + status.setAttribute('data-error', 'true') + } else { + status.textContent = state.dirty ? t('unsaved') : (state.saved ? t('saved') : '') + status.removeAttribute('data-error') + } + } + + function save() { + if (state.busy || !state.dirty) return + state.busy = true + clearError() + render() + var edit = { + patterns: state.patterns, + exact: state.exact, + protectUnknown: state.protectUnknown, + extra: state.extra + } + Promise.resolve(magpie.options.get()).then(function (current) { + if (!P.sameAgentFields(current, state.loaded)) { + var conflict = new Error('options changed elsewhere') + conflict.conflict = true + throw conflict + } + return magpie.options.set(P.mergeOptions(current, edit)) + }).then(function (saved) { + configure(saved) + state.busy = false + state.dirty = false + state.saved = true + clearError() + render() + }).catch(function (error) { + state.busy = false + state.error = error && error.conflict ? t('changedElsewhere') : t('saveFailed') + render() + }) + } + + $('panel-save').addEventListener('click', save) + + state.saved = false + clearError() + Promise.resolve(magpie.ready).then(function (theme) { + state.lang = theme && String(theme.lang).toLowerCase().indexOf('zh') === 0 ? 'zh' : 'en' + setText('panel-title', t('title')) + setText('panel-lede', t('lede')) + setText('panel-save', t('save')) + return magpie.options.get() + }).then(function (options) { + configure(options) + render() + }).catch(function () { + state.error = t('failed') + render() + }) +})() diff --git a/packages/privacy-gate/page/policy.js b/packages/privacy-gate/page/policy.js new file mode 100644 index 0000000..4217ba2 --- /dev/null +++ b/packages/privacy-gate/page/policy.js @@ -0,0 +1,97 @@ +/* Policy merging for the ShyPie page and panel. + * + * `disabledAgents` is a middleware policy list, not just a catalogue of ids: + * it may contain globs and values the UI cannot represent. Those entries are + * kept verbatim and merged back on save. This file is a plain browser script + * and makes no network calls. */ +(function (root) { + 'use strict' + + var A = root.ShyPieAgents + + function rawList(value) { + return Array.isArray(value) ? value.slice(0, 200) : [] + } + + function isExactId(value) { + return typeof value === 'string' && A.normalizeId(value) === value + } + + function split(disabled) { + var exact = [] + var patterns = [] + var raw = rawList(disabled) + for (var i = 0; i < raw.length; i++) { + if (isExactId(raw[i])) { + if (exact.indexOf(raw[i]) === -1) exact.push(raw[i]) + } else { + patterns.push(raw[i]) + } + } + return { exact: exact, patterns: patterns } + } + + function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + } + + // Mirrors the middleware's matchesAny: case-sensitive, with '*' spanning + // anything and a trailing '/*' treated as a path prefix. + function matches(pattern, agent) { + if (typeof pattern !== 'string' || typeof agent !== 'string') return false + if (pattern === agent || pattern === '*') return true + if (pattern.endsWith('/*') && agent.startsWith(pattern.slice(0, -1))) return true + if (pattern.indexOf('*') === -1) return false + var source = pattern.split('*').map(escapeRegExp).join('.*') + return new RegExp('^' + source + '$').test(agent) + } + + function patternFor(patterns, agent) { + for (var i = 0; i < patterns.length; i++) { + if (matches(patterns[i], agent)) return patterns[i] + } + return null + } + + function unique(values) { + var out = [] + for (var i = 0; i < values.length; i++) { + if (typeof values[i] === 'string' && values[i] !== '' && out.indexOf(values[i]) === -1) out.push(values[i]) + } + return out + } + + function mergeDisabled(patterns, exact) { + return rawList(patterns).concat(unique(rawList(exact))) + } + + function mergeOptions(current, edit) { + return Object.assign({}, current && typeof current === 'object' ? current : {}, { + disabledAgents: mergeDisabled(edit.patterns, edit.exact), + protectUnknownAgent: edit.protectUnknown !== false, + extraAgents: unique(rawList(edit.extra)) + }) + } + + function sameAgentFields(current, loaded) { + if (!current || typeof current !== 'object' || !loaded || typeof loaded !== 'object') return false + var currentDisabled = JSON.stringify(rawList(current.disabledAgents)) + var loadedDisabled = JSON.stringify(rawList(loaded.disabledAgents)) + if (currentDisabled !== loadedDisabled) return false + var currentUnknown = current.protectUnknownAgent !== false + var loadedUnknown = loaded.protectUnknownAgent !== false + if (currentUnknown !== loadedUnknown) return false + return JSON.stringify(rawList(current.extraAgents)) === JSON.stringify(rawList(loaded.extraAgents)) + } + + root.ShyPiePolicy = { + rawList: rawList, + isExactId: isExactId, + split: split, + matches: matches, + patternFor: patternFor, + mergeDisabled: mergeDisabled, + mergeOptions: mergeOptions, + sameAgentFields: sameAgentFields + } +})(typeof globalThis !== 'undefined' ? globalThis : this) diff --git a/packages/privacy-gate/page/style.css b/packages/privacy-gate/page/style.css new file mode 100644 index 0000000..bcdac3f --- /dev/null +++ b/packages/privacy-gate/page/style.css @@ -0,0 +1,392 @@ +:root { + --shy-bg: var(--magpie-bg, #f4faf6); + --shy-fg: var(--magpie-fg, #0d4b4e); + --shy-muted: color-mix(in srgb, var(--shy-fg) 62%, transparent); + --shy-line: color-mix(in srgb, var(--shy-fg) 14%, transparent); + --shy-card: color-mix(in srgb, var(--shy-bg) 88%, white); + --shy-accent: #0d4b4e; + --shy-gold: #f2b35a; + --shy-blush: #f08074; + --shy-danger: #b5453b; + --shy-radius: 12px; +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + padding: 0; + background: var(--shy-bg); + color: var(--shy-fg); +} + +body { + font-family: var(--magpie-font, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif); + font-size: 14px; + line-height: 1.45; +} + +.shell { + width: min(760px, 100%); + margin: 0 auto; + padding: 24px 20px 32px; +} + +.hero { + display: grid; + grid-template-columns: auto 1fr auto; + gap: 14px; + align-items: start; + margin-bottom: 22px; +} + +.logo { + width: 56px; + height: 56px; + border-radius: 14px; + background: var(--shy-card); +} + +.kicker { + margin: 0 0 3px; + color: var(--shy-muted); + font-size: 12px; + letter-spacing: .08em; + text-transform: uppercase; +} + +h1, h2, p { margin-top: 0; } + +h1 { + margin-bottom: 5px; + font-size: 24px; + line-height: 1.15; +} + +h2 { + margin-bottom: 3px; + font-size: 14px; +} + +.lede { + margin-bottom: 0; + max-width: 52ch; + color: var(--shy-muted); +} + +.count { + margin: 2px 0 0; + padding: 5px 9px; + border: 1px solid var(--shy-line); + border-radius: 999px; + color: var(--shy-muted); + font-size: 12px; + white-space: nowrap; +} + +.toolbar { + display: flex; + gap: 8px; + margin-bottom: 12px; +} + +.search { flex: 1; } + +input[type="search"], input[type="text"] { + width: 100%; + min-height: 36px; + padding: 7px 10px; + border: 1px solid var(--shy-line); + border-radius: 8px; + background: transparent; + color: inherit; + font: inherit; +} + +input:focus-visible, button:focus-visible { + outline: 2px solid var(--shy-gold); + outline-offset: 2px; +} + +button { + min-height: 36px; + padding: 7px 12px; + border: 1px solid transparent; + border-radius: 8px; + background: var(--shy-accent); + color: var(--shy-bg); + font: inherit; + font-weight: 600; + cursor: pointer; +} + +button.secondary { + border-color: var(--shy-line); + background: transparent; + color: inherit; + font-weight: 500; +} + +button:disabled { + opacity: .45; + cursor: default; +} + +.list { + border: 1px solid var(--shy-line); + border-radius: var(--shy-radius); + overflow: hidden; + background: var(--shy-card); +} + +.group { + border-top: 1px solid var(--shy-line); +} + +.group:first-child { border-top: 0; } + +.group-title { + margin: 0; + padding: 10px 14px 4px; + color: var(--shy-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: .07em; + text-transform: uppercase; +} + +.agent { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 14px; + border-top: 1px solid color-mix(in srgb, var(--shy-fg) 8%, transparent); +} + +.group:first-child .agent:first-of-type { border-top: 0; } + +.agent.is-target { + background: color-mix(in srgb, var(--shy-gold) 16%, transparent); +} + +.avatar { + display: grid; + place-items: center; + flex: 0 0 30px; + height: 30px; + border: 1px solid var(--shy-line); + border-radius: 9px; + background: var(--shy-bg); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +.agent-copy { min-width: 0; flex: 1; } + +.agent-name { + display: block; + overflow: hidden; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.agent-id { + display: block; + overflow: hidden; + color: var(--shy-muted); + font-family: var(--magpie-mono, ui-monospace, SFMono-Regular, Consolas, monospace); + font-size: 11px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.switch { + position: relative; + flex: 0 0 42px; + width: 42px; + min-height: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 999px; + background: color-mix(in srgb, var(--shy-fg) 22%, transparent); +} + +.switch::after { + position: absolute; + top: 3px; + left: 3px; + width: 18px; + height: 18px; + border-radius: 50%; + background: var(--shy-bg); + content: ""; + transition: transform .14s ease; +} + +.switch[aria-checked="true"] { background: var(--shy-accent); } +.switch[aria-checked="true"]::after { transform: translateX(18px); } +.switch[aria-label] { cursor: pointer; } + +.warning { + margin: 0 0 12px; + padding: 9px 11px; + border: 1px solid color-mix(in srgb, var(--shy-danger) 38%, transparent); + border-radius: 8px; + background: color-mix(in srgb, var(--shy-danger) 9%, transparent); + color: var(--shy-danger); + font-size: 13px; +} + +.patterns { + margin-top: 14px; + padding: 12px 14px; + border: 1px solid var(--shy-line); + border-radius: var(--shy-radius); + background: var(--shy-card); +} + +.patterns h2 { margin-bottom: 2px; } + +.pattern-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 8px 0 0; + padding: 0; + list-style: none; +} + +.pattern-list li { + padding: 3px 7px; + border: 1px solid var(--shy-line); + border-radius: 6px; + background: var(--shy-bg); + font-family: var(--magpie-mono, ui-monospace, SFMono-Regular, Consolas, monospace); + font-size: 11px; +} + +.switch:disabled { + cursor: default; + opacity: .55; +} + +.status[data-error="true"] { color: var(--shy-danger); } + +.empty { + margin: 16px 14px; + color: var(--shy-muted); +} + +.add { + display: grid; + grid-template-columns: 1fr auto; + gap: 4px 16px; + align-items: end; + margin-top: 18px; + padding: 14px; + border: 1px solid var(--shy-line); + border-radius: var(--shy-radius); + background: var(--shy-card); +} + +.add h2 { margin-bottom: 0; } + +.hint, .form-error { + margin: 0; + color: var(--shy-muted); + font-size: 12px; +} + +.add-row { + display: flex; + gap: 8px; + grid-column: 1 / -1; + margin-top: 8px; +} + +.add-row input { max-width: 240px; } +.form-error { grid-column: 1 / -1; color: var(--shy-danger); } + +.actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 12px; + margin-top: 18px; +} + +.status { + margin-right: auto; + color: var(--shy-muted); + font-size: 12px; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +@media (max-width: 560px) { + .shell { padding: 18px 14px 24px; } + .hero { grid-template-columns: auto 1fr; } + .count { grid-column: 1 / -1; justify-self: start; } + .add { grid-template-columns: 1fr; } + .add-row { flex-wrap: wrap; } + .add-row input { max-width: none; flex: 1 0 100%; } +} + +/* Agents-page panel: same widgets, tighter spacing. */ +.panel-page { background: transparent; } + +.panel-shell { + width: 100%; + padding: 4px 2px 2px; +} + +.panel-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.panel-head h1 { + margin-bottom: 2px; + font-size: 16px; +} + +.panel-head .kicker { margin-bottom: 2px; } + +.panel-head .count { + margin-top: 0; + font-size: 11px; +} + +.panel-actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + margin-top: 10px; +} + +.panel-actions .status { font-size: 11px; } +.panel-actions button { min-height: 30px; padding: 4px 10px; font-size: 13px; } +.panel-shell .group-title { padding: 7px 12px 2px; } +.panel-shell .agent { padding: 7px 12px; gap: 9px; } +.panel-shell .avatar { flex-basis: 26px; height: 26px; } +.panel-shell .switch { flex-basis: 38px; width: 38px; height: 22px; } +.panel-shell .switch::after { width: 16px; height: 16px; } +.panel-shell .switch[aria-checked="true"]::after { transform: translateX(16px); } + diff --git a/packages/privacy-gate/privacy-gate.middleware.js b/packages/privacy-gate/privacy-gate.middleware.js index 1bdafc9..2e66c6d 100644 --- a/packages/privacy-gate/privacy-gate.middleware.js +++ b/packages/privacy-gate/privacy-gate.middleware.js @@ -43,6 +43,11 @@ // binaryPolicy: 'fail'|'guide' fail (default) returns 403 for a binary part; guide // withholds every binary part and injects a local-tool prompt. // guideTools: string[] tool names advertised to the model in guide mode. +// disabledAgents: string[] Magpie agent ids that bypass this gate completely. +// [] (default) protects every agent. Only explicit ids +// (or globs) are bypassed; new agents stay protected. +// protectUnknownAgent: bool true (default). When false, a request whose +// ctx.agent is empty is allowed through unchanged. // allowUnknownProtocol: bool false (default). When false, a request whose // ctx.protocol is not chat/responses/anthropic/ // gemini is rejected (the gate cannot classify it). @@ -111,6 +116,8 @@ var DEFAULTS = { localModels: [], localProviders: [], binaryPolicy: 'fail', + disabledAgents: [], + protectUnknownAgent: true, allowUnknownProtocol: false, // A one-page invoice PDF is ~1-3 KB: ~1.4-4 k base64 chars, ~2-6 k hex chars. The // threshold is deliberately below that, because a smaller encoded document was a real @@ -178,6 +185,22 @@ function strList(opts, key) { return out; } +// The agent id magpie classified for this request. It is host-supplied metadata, +// never a User-Agent string, so it is safe to use for policy selection. +function agentOf(ctx) { + try { + return ctx && typeof ctx.agent === "string" ? clip(ctx.agent, 120) : ""; + } catch (e) { + return ""; + } +} + +function agentEnabled(opts, ctx) { + var agent = agentOf(ctx); + if (agent === "") return boolOpt(opts, "protectUnknownAgent", DEFAULTS.protectUnknownAgent); + return !matchesAny(opts.disabledAgents, agent); +} + function allowModelsOpt(opts) { var raw = opts.allowModels; if (raw === undefined) return { list: [], invalid: false }; @@ -584,6 +607,8 @@ function resolvedOptions(raw) { localModels: strList(source, "localModels"), localProviders: strList(source, "localProviders"), binaryPolicy: policyOpt(source, "binaryPolicy", DEFAULTS.binaryPolicy), + disabledAgents: strList(source, "disabledAgents"), + protectUnknownAgent: boolOpt(source, "protectUnknownAgent", DEFAULTS.protectUnknownAgent), guideTools: strList(source, "guideTools"), allowUnknownProtocol: boolOpt(source, "allowUnknownProtocol", DEFAULTS.allowUnknownProtocol), blobBase64Chars: numOpt(source, "blobBase64Chars", DEFAULTS.blobBase64Chars, 64, 1000000), @@ -972,6 +997,7 @@ function guideBody(body, ctx, opts) { // fail-closed outcome available here; returning nothing would send the body. export function onRequest(body, ctx) { var opts = gateOptions(ctx); + if (!agentEnabled(opts, ctx)) return body; counters.requests++; var decision; try { @@ -1041,6 +1067,7 @@ function findFirstBinary(value, partContext, depth, state, opts, atRoot) { // middleware's injection, or a timed-out onRequest could still put bytes here. export function onProvider(body, ctx) { var opts = gateOptions(ctx); + if (!agentEnabled(opts, ctx)) return body; var decision; try { decision = inspect(body, ctx);