diff --git a/packages/privacy-gate/README.md b/packages/privacy-gate/README.md index a0e303f..a1fd26e 100644 --- a/packages/privacy-gate/README.md +++ b/packages/privacy-gate/README.md @@ -13,7 +13,7 @@

- version 0.4.0 + version 0.4.1 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** | 72 middleware cases + 4 page/policy checks through the repository harness | +| **Tests** | 72 middleware cases + 5 page/policy/settings checks through the repository harness | ## Install @@ -147,6 +147,24 @@ 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. +## Middleware settings page + +The **Middleware settings** tab on the plugin page edits the same `ctx.options` +that previously required `magpie plugin options`, grouped by privacy impact: + +- **Protection:** `binaryPolicy`, `allowUnknownProtocol`, `allowModels`, + `localModels`, `localProviders` and the blob thresholds +- **Advanced inspection:** `scanChars`, `maxNodes`, `maxDepth` +- **Diagnostics:** `guideTools`, `logMaxLines`, `logEveryRows` + +The form validates list shape and numeric ranges and preserves options it does +not own. Numeric values outside the middleware's range are displayed as the +effective clamped value (floor, then `[min, max]`) rather than being replaced by +a page default; an unknown select value is reported as invalid. A malformed +existing `allowModels` is reported and blocks saving rather than being silently +replaced by an empty, allow-everything list. Saving re-reads the current options +and reports a conflict if another surface changed a managed field. + ## Configuration All settings are one JSON object, stored as `ctx.options`: @@ -375,6 +393,17 @@ flowchart LR `ctx.agent` 的请求)才会跳过防护。页面会在请求可能失去保护时提示;保存开关 会更新中间件读取的同一份 `ctx.options`,无需重启。 +## 中间件设置页面 + +插件页面的 **中间件设置** 标签可直接编辑此前只能用 `magpie plugin options` +设置的 `ctx.options`:`binaryPolicy`、`allowUnknownProtocol`、`allowModels`、 +`localModels`、`localProviders`、`guideTools`、两个 blob 阈值、`scanChars`、 +`maxNodes`、`maxDepth`、`logMaxLines` 和 `logEveryRows`。 + +表单会校验列表和数值范围,并保留页面不管理的选项。已有的 `allowModels` +如果格式错误会阻止保存,而不会被静默替换成允许全部模型的空列表。保存前会 +重新读取当前配置;其他位置修改了受管字段时会提示冲突。 + ## 配置 所有配置都在一个 JSON 对象中,即 `ctx.options`: diff --git a/packages/privacy-gate/docs/design.md b/packages/privacy-gate/docs/design.md index 5aa8a5e..13f6fa9 100644 --- a/packages/privacy-gate/docs/design.md +++ b/packages/privacy-gate/docs/design.md @@ -185,8 +185,15 @@ policy selection: 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; +- The page's **Middleware settings** tab groups the options by privacy impact: + Protection (binary policy, protocol, model/provider and blob controls), + Advanced inspection (`scanChars`, `maxNodes`, `maxDepth`) and Diagnostics + (`guideTools`, log settings). It validates list shape, displays numeric values + clamped to the middleware's effective range, reports an unknown select as + invalid, preserves options it does not own, and blocks a malformed + `allowModels` rather than replacing it with an allow-everything empty list. +- Saving starts from freshly read options and changes only the 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. @@ -194,7 +201,7 @@ policy selection: ## Verification - 72 cases in `cases.json`, run through `scripts/middleware.mjs` using the same - hook calls Magpie performs. + hook calls Magpie performs, plus 5 page/policy/settings checks. - 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, diff --git a/packages/privacy-gate/docs/operations.md b/packages/privacy-gate/docs/operations.md index 8387154..20d079d 100644 --- a/packages/privacy-gate/docs/operations.md +++ b/packages/privacy-gate/docs/operations.md @@ -83,6 +83,17 @@ 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. +## Middleware settings page + +The page's **Middleware settings** tab edits the same options as +`magpie plugin options`, grouped as **Protection**, **Advanced inspection** and +**Diagnostics**. Ranges and list shape are checked before saving. Numeric +out-of-range values are shown at the effective clamped value the middleware +uses; an unknown select is reported as invalid. Options outside the form are +preserved. A malformed existing `allowModels` blocks saving instead of being +replaced by an empty, allow-everything list; fix it in the form or with +`magpie plugin options`. + ## Troubleshooting ### I get a 403 for an image diff --git a/packages/privacy-gate/package.json b/packages/privacy-gate/package.json index a45c1fd..568bb5e 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.4.0", + "version": "0.4.1", "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": [ @@ -32,7 +32,9 @@ "icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/privacy-gate/assets/shypie-icon.svg", "page": { "title": "ShyPie Filter", - "titles": { "zh": "ShyPie 防护" }, + "titles": { + "zh": "ShyPie 防护" + }, "file": "page/index.html", "icon": "page/icon.svg" }, @@ -41,7 +43,9 @@ "slot": "agents", "file": "page/agents-panel.html", "title": "ShyPie protection", - "titles": { "zh": "ShyPie 防护" } + "titles": { + "zh": "ShyPie 防护" + } } ], "actions": [ @@ -49,7 +53,9 @@ "id": "shypie-protection", "menu": "agent", "title": "ShyPie protection", - "titles": { "zh": "ShyPie 防护" } + "titles": { + "zh": "ShyPie 防护" + } } ], "permissions": [], diff --git a/packages/privacy-gate/page.test.mjs b/packages/privacy-gate/page.test.mjs index 467fb19..541e957 100644 --- a/packages/privacy-gate/page.test.mjs +++ b/packages/privacy-gate/page.test.mjs @@ -21,6 +21,7 @@ test('page and panel use only the released bridge and make no network calls', () const panel = read('panel.js') const agents = read('agents.js') const policy = read('policy.js') + const settings = read('settings.js') const page = read('index.html') const panelPage = read('agents-panel.html') const allowed = ['ready', 'options.get', 'options.set', 'onAction'] @@ -29,6 +30,7 @@ test('page and panel use only the released bridge and make no network calls', () expect(safePageScript(panel, allowed)).toBe(true) expect(safePageScript(agents, [])).toBe(true) expect(safePageScript(policy, [])).toBe(true) + expect(safePageScript(settings, [])).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) @@ -44,6 +46,7 @@ test('page and panel use only the released bridge and make no network calls', () expect(sources).toContain('_magpie/bridge.js') expect(sources).toContain('agents.js') expect(sources).toContain('policy.js') + if (html === page) expect(sources).toContain('settings.js') expect(sources).toContain(html === page ? 'app.js' : 'panel.js') expect(tags).toHaveLength(sources.length) } @@ -86,6 +89,51 @@ test('a glob policy survives an options save and unrelated options are kept', () )).toBe(false) }) +test('middleware settings are validated, merged and detect stale values', () => { + const sandbox = {} + sandbox.globalThis = sandbox + runInNewContext(read('settings.js'), sandbox) + const S = sandbox.ShyPieSettings + const parsed = S.fromOptions({ + binaryPolicy: 'guide', + allowModels: ['safe/*'], + blobBase64Chars: 400, + future: 'keep', + }) + expect(Array.from(parsed.values.allowModels)).toEqual(['safe/*']) + expect(parsed.invalid).toEqual([]) + expect(Array.from(S.parseList('a/*, b/*\nc/*'))).toEqual(['a/*', 'b/*', 'c/*']) + expect(S.fromOptions({ allowModels: { bad: true } }).invalid).toEqual(['allowModels']) + expect(S.fromOptions({ allowModels: [null] }).invalid).toEqual(['allowModels']) + const clamped = S.fromOptions({ maxDepth: 500, scanChars: 500, maxNodes: 40000.5 }) + expect(clamped.values.maxDepth).toBe(200) + expect(clamped.values.scanChars).toBe(1000) + expect(clamped.values.maxNodes).toBe(40000) + const savedClamped = S.apply( + { maxDepth: 500, scanChars: 500, maxNodes: 40000.5, disabledAgents: ['codex'] }, + clamped.values, + ) + expect(savedClamped.maxDepth).toBe(200) + expect(savedClamped.scanChars).toBe(1000) + expect(savedClamped.maxNodes).toBe(40000) + expect(S.fromOptions({ binaryPolicy: 'Guide' }).invalid).toEqual(['binaryPolicy']) + expect(S.validate({ ...parsed.values, maxDepth: 0 }).map((error) => error.key)).toEqual(['maxDepth']) + const many = Array.from({ length: 201 }, (_, i) => `model/${i}`) + expect(S.parseList(many)).toHaveLength(201) + expect(S.validate({ ...parsed.values, allowModels: many }).map((error) => error.key)).toEqual(['allowModels']) + const rawSnapshot = S.snapshot({ ...parsed.values }) + expect(S.same({ allowModels: null }, S.snapshot({ allowModels: [] }))).toBe(false) + const merged = S.apply( + { binaryPolicy: 'fail', future: 'keep' }, + { ...parsed.values, binaryPolicy: 'guide', localProviders: ['ollama'] }, + ) + expect(merged.binaryPolicy).toBe('guide') + expect(Array.from(merged.localProviders)).toEqual(['ollama']) + expect(merged.future).toBe('keep') + expect(S.same({ ...parsed.values }, rawSnapshot)).toBe(true) + expect(S.same({ ...parsed.values, blobBase64Chars: 500 }, rawSnapshot)).toBe(false) +}) + test('the shared agent catalogue validates ids and keeps custom agents', () => { const sandbox = {} sandbox.globalThis = sandbox @@ -100,7 +148,7 @@ test('the shared agent catalogue validates ids and keeps custom agents', () => { 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.version).toBe('0.4.1') expect(pkg.files).toContain('page') expect(pkg.magpie.page.file).toBe('page/index.html') expect(pkg.magpie.page.icon).toBe('page/icon.svg') diff --git a/packages/privacy-gate/page/app.js b/packages/privacy-gate/page/app.js index 5253a95..1dfcc2a 100644 --- a/packages/privacy-gate/page/app.js +++ b/packages/privacy-gate/page/app.js @@ -3,13 +3,16 @@ var A = window.ShyPieAgents var P = window.ShyPiePolicy + var S = window.ShyPieSettings 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.', + title: 'Middleware settings', + lede: 'Choose which agents ShyPie protects and how its Magpie middleware behaves.', + settingsFailed: 'Could not read the middleware settings.', + settingsInvalid: 'Fix the malformed options before saving.', search: 'Search agents', reload: 'Reload', save: 'Save changes', @@ -40,8 +43,10 @@ }, zh: { kicker: 'ShyPie 防护', - title: '按 Agent 保护', - lede: '选择哪些 Magpie Agent 受 ShyPie 保护。关闭的 Agent 会完全绕过防护。', + title: '中间件设置', + lede: '选择哪些 Agent 受 ShyPie 保护,以及 Magpie 中间件如何工作。', + settingsFailed: '无法读取中间件设置。', + settingsInvalid: '请先修复格式错误的选项再保存。', search: '搜索 Agent', reload: '重新加载', save: '保存更改', @@ -87,7 +92,11 @@ error: '', loaded: { disabledAgents: [], protectUnknownAgent: true, extraAgents: [] }, pendingAction: null, - lang: 'en' + lang: 'en', + tab: 'settings', + settings: {}, + settingsLoaded: {}, + settingsInvalidKeys: [] } function t(key) { @@ -145,6 +154,78 @@ return true } + var SETTING_IDS = { + binaryPolicy: 'opt-binary-policy', + allowUnknownProtocol: 'opt-allow-unknown', + allowModels: 'opt-allow-models', + localModels: 'opt-local-models', + localProviders: 'opt-local-providers', + guideTools: 'opt-guide-tools', + blobBase64Chars: 'opt-blob-base64', + blobHexChars: 'opt-blob-hex', + scanChars: 'opt-scan-chars', + maxNodes: 'opt-max-nodes', + maxDepth: 'opt-max-depth', + logMaxLines: 'opt-log-max-lines', + logEveryRows: 'opt-log-every-rows' + } + + function numberInput(raw) { + var text = String(raw == null ? '' : raw).trim() + if (text === '' || !/^-?\d+$/.test(text)) return NaN + return Number(text) + } + + function readSettingsForm() { + var values = {} + values.binaryPolicy = $('opt-binary-policy').value + values.allowUnknownProtocol = $('opt-allow-unknown').checked + values.allowModels = S.parseList($('opt-allow-models').value) + values.localModels = S.parseList($('opt-local-models').value) + values.localProviders = S.parseList($('opt-local-providers').value) + values.guideTools = S.parseList($('opt-guide-tools').value) + values.blobBase64Chars = numberInput($('opt-blob-base64').value) + values.blobHexChars = numberInput($('opt-blob-hex').value) + values.scanChars = numberInput($('opt-scan-chars').value) + values.maxNodes = numberInput($('opt-max-nodes').value) + values.maxDepth = numberInput($('opt-max-depth').value) + values.logMaxLines = numberInput($('opt-log-max-lines').value) + values.logEveryRows = numberInput($('opt-log-every-rows').value) + return { values: values, errors: S.validate(values) } + } + + function fillSettingsForm(values) { + $('opt-binary-policy').value = values.binaryPolicy + $('opt-allow-unknown').checked = values.allowUnknownProtocol === true + $('opt-allow-models').value = (values.allowModels || []).join('\n') + $('opt-local-models').value = (values.localModels || []).join('\n') + $('opt-local-providers').value = (values.localProviders || []).join('\n') + $('opt-guide-tools').value = (values.guideTools || []).join('\n') + $('opt-blob-base64').value = values.blobBase64Chars + $('opt-blob-hex').value = values.blobHexChars + $('opt-scan-chars').value = values.scanChars + $('opt-max-nodes').value = values.maxNodes + $('opt-max-depth').value = values.maxDepth + $('opt-log-max-lines').value = values.logMaxLines + $('opt-log-every-rows').value = values.logEveryRows + } + + function showSettingsError(text) { + var el = $('settings-error') + if (!el) return + el.textContent = text || '' + el.hidden = !text + } + + function setTab(tab) { + state.tab = tab === 'agents' ? 'agents' : 'settings' + $('agents-view').hidden = state.tab !== 'agents' + $('settings-view').hidden = state.tab !== 'settings' + $('tab-agents').setAttribute('aria-selected', state.tab === 'agents' ? 'true' : 'false') + $('tab-settings').setAttribute('aria-selected', state.tab === 'settings' ? 'true' : 'false') + $('count').hidden = state.tab !== 'agents' + } + function configure(options) { state.options = options && typeof options === 'object' ? options : {} var split = P.split(state.options.disabledAgents) @@ -159,6 +240,12 @@ protectUnknownAgent: state.protectUnknown, extraAgents: P.rawList(state.options.extraAgents) } + var parsed = S.fromOptions(state.options) + state.settings = parsed.values + state.settingsLoaded = S.snapshot(state.options) + state.settingsInvalidKeys = parsed.invalid.slice() + fillSettingsForm(state.settings) + showSettingsError(state.settingsInvalidKeys.length > 0 ? t('settingsInvalid') : '') } function patternFor(id) { @@ -287,6 +374,7 @@ var counts = protectedCount() setText('count', counts.on + ' / ' + counts.total + ' ' + t('protected')) + $('count').hidden = state.tab !== 'agents' var warning = $('warning') if (counts.on === 0) { warning.textContent = t('warningAll') @@ -301,6 +389,10 @@ $('reload').disabled = state.busy $('add-agent').disabled = state.busy $('add-id').disabled = state.busy + Object.keys(SETTING_IDS).forEach(function (key) { + var control = $(SETTING_IDS[key]) + if (control) control.disabled = state.busy + }) var status = $('status') if (state.error) { status.textContent = state.error @@ -379,6 +471,12 @@ function save() { if (state.busy || !state.dirty) return + var form = readSettingsForm() + if (state.settingsInvalidKeys.length > 0 || form.errors.length > 0) { + setTab('settings') + showSettingsError(state.settingsInvalidKeys.length > 0 ? t('settingsInvalid') : form.errors[0].message) + return + } state.busy = true clearError() render() @@ -389,18 +487,20 @@ extra: state.extra } Promise.resolve(magpie.options.get()).then(function (current) { - if (!P.sameAgentFields(current, state.loaded)) { + if (!P.sameAgentFields(current, state.loaded) || !S.same(current, state.settingsLoaded)) { var conflict = new Error('options changed elsewhere') conflict.conflict = true throw conflict } - return magpie.options.set(P.mergeOptions(current, edit)) + var next = P.mergeOptions(current, edit) + return magpie.options.set(S.apply(next, form.values)) }).then(function (saved) { configure(saved) state.busy = false state.dirty = false state.saved = true clearError() + showSettingsError('') render() }).catch(function (error) { state.busy = false @@ -416,6 +516,7 @@ var id = A.normalizeId(agent.id) if (!id) return var added = ensureExtra(id) + setTab('agents') state.rows = A.allRows(state.extra) state.search = '' $('search').value = '' @@ -464,6 +565,25 @@ if (event.key === 'Enter' && !state.busy) addAgent() }) $('save').addEventListener('click', save) + $('tab-agents').addEventListener('click', function () { setTab('agents') }) + $('tab-settings').addEventListener('click', function () { setTab('settings') }) + + function settingsTouched(key) { + state.settingsInvalidKeys = state.settingsInvalidKeys.filter(function (item) { return item !== key }) + state.dirty = true + clearError() + showSettingsError('') + render() + } + + Object.keys(SETTING_IDS).forEach(function (key) { + var el = $(SETTING_IDS[key]) + if (!el) return + el.addEventListener('input', function () { settingsTouched(key) }) + el.addEventListener('change', function () { settingsTouched(key) }) + }) + + setTab('settings') if (typeof magpie.onAction === 'function') { magpie.onAction(function (action) { diff --git a/packages/privacy-gate/page/index.html b/packages/privacy-gate/page/index.html index 6585ef5..d0293ee 100644 --- a/packages/privacy-gate/page/index.html +++ b/packages/privacy-gate/page/index.html @@ -12,41 +12,139 @@

ShyPie Filter

-

Per-agent protection

-

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

+

Middleware settings

+

Choose which agents ShyPie protects and how its Magpie middleware behaves.

-
- - + + + - -
- +
+

Grouped by privacy impact. Fields not shown here are preserved unchanged.

+ - +
+

Protection

+
+ + +

fail is the strict default; guide keeps the model in the loop without forwarding bytes.

+
+
+ +

Off rejects protocols outside chat / responses / anthropic / gemini.

+
+
+ + +

Globs such as deepseek/* or copilot/*, one per line. Empty means every model is allowed.

+
+
+ + +

Models that may receive binary parts because they run locally. Leave empty to withhold every binary part.

+
+
+ + +

Must agree with local models; onProvider checks the real provider id.

+
+
+
+ + +

64–1,000,000 characters. Raising this lets larger encoded documents through.

+
+
+ + +

64–1,000,000 characters. Raising this lets larger encoded documents through.

+
+
+
+ +
+

Advanced inspection

+
+ + +

1,000–5,000,000.

+
+
+ + +

1,000–5,000,000.

+
+
+ + +

1–200.

+
+ +
+ +
+

Diagnostics

+

These settings affect prompt guidance and logging, not what content can leave the gate.

+
+ + +

Only used with binaryPolicy guide; names are included in the local-processing prompt.

+
+
+
+ + +

0–500; 0 silences the log self-cap.

+
+
+ + +

1–100,000 usage rows.

+
+
+
-
-
-

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.

-
-
- - - -
-