privacy-gate 0.1.0: ShyPie Privacy Gate, a gateway middleware that keeps binary parts and blobs local (#685)

New package @magpie-community/middleware-privacy-gate 0.1.0 (siml1169): a
gateway middleware that refuses image, file and audio parts, encoded blobs
and models outside an allowlist before a request leaves magpie, or in
binaryPolicy "guide" replaces each binary part with a short text note. A
typo in any option falls back to the stricter side; a malformed allowModels
refuses every request.

Reviewed at 2a998b73b4ae5f6ae072f12ea9ef27008692c892 (earlier rounds at
ab8c0ebe and before):
- mote, HOME=$(mktemp -d), Bun 1.4.2, merged onto origin/main 6549b633:
  bun test packages/privacy-gate 62 pass; bun scripts/check.mjs ok.
- Broken by hand: the allowModels check off (2 red), guide mode's blob scan
  removed (3 red), the mime check removed (1 red).
- magpie's own middleware engine (origin/main 3cbb7e042) with this file:
  ~90 cases across binaryPolicy typos, guide mode bounds, signatures and
  allowModels typos, all as wanted apart from the documented value cap.
Not tried: a real vendor or DSH, streaming bodies, Windows and Linux.
This commit is contained in:
Muyang
2026-11-06 20:22:46 +08:00
committed by GitHub
parent 6549b6335d
commit 28108ddeec
7 changed files with 2581 additions and 1 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ShyPie contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
# privacy-gate — structural egress gate for Magpie
A Magpie **gateway middleware**. It is the Magpie half of
[ShyPie](https://github.com/siml1169/ShyPie)'s privacy-first workflow for
[DeepSeek Harness](https://github.com/deepseek-ai): DSH masks and extracts at ingestion, and this
gate enforces the structural half of the egress path.
It **does not mask text**. Text masking stays Magpie's Privacy setting; this plugin only checks the
request's structure. Image, file and audio parts get a **403 by default**. They pass only when **both** agree: the model
is in `localModels` (so `onRequest` allows it) **and** the provider id is in `localProviders` (so
`onProvider` keeps it). With `localModels` alone the request is not rejected, but `onProvider`
blanks the content — the request is changed silently, not sent. Encoded blobs smuggled through text
and models outside the allowlist are rejected too.
## Install
```sh
magpie plugin add @magpie-community/middleware-privacy-gate
magpie plugin options privacy-gate '{}' # no options = strictest (all binary parts blocked)
magpie plugin # listed as gateway middleware
```
The options object is `ctx.options`; defaults are shown by `magpie plugin options privacy-gate`.
| Option | Default | Meaning |
|---|---|---|
| `allowModels` | `[]` | Globs against the model id as the agent asked. `[]` allows every model; if the option is present but is not an array of non-empty short strings, every request is refused instead of falling back to no allowlist. |
| `localModels` | `[]` | Model globs that may receive binary parts on `onRequest`. Pair with `localProviders`, or `onProvider` blanks the content. |
| `localProviders` | `[]` | Provider-id globs that may receive binary parts; checked in `onProvider`. |
| `blobBase64Chars` / `blobHexChars` | `400` / `400` | An encoded run at or above this is a blob (403). |
| `scanChars` | `200000` | Total text-inspection budget; each field may use at most an eighth (min 1k), so one huge field cannot starve the rest of the newest turn. |
| `allowUnknownProtocol` | `false` | Reject bodies whose `ctx.protocol` is not one of chat/responses/anthropic/gemini. |
| `binaryPolicy` | `fail` | `fail` returns 403 for a non-local binary part; `guide` withholds every binary part and injects a metadata + local-tool prompt instead. |
| `guideTools` | `[]` | Tool names advertised to the model in guide mode. Leave empty unless the local MCP server is installed. |
| `maxNodes` / `maxDepth` | `40000` / `40` | Every visited value counts, including primitives and array elements; an array wider than the remaining budget is refused without iterating. Overflow blocks (fail closed). |
| `logMaxLines` / `logEveryRows` | `40` / `50` | Self-cap on `console.log` / one usage line every N rows. |
## What it does not inspect
- Text content is Magpie's Privacy masking. Secrets in message text and tool arguments pass through
this layer unchanged unless Magpie's masking catches them.
- The scan is **bounded**: newest conversation content is walked first; each text field may use at
most `max(1024, scanChars/8)` characters (only the edges of a longer field), and after the total
`scanChars` budget the rest is skipped. `system`/`instructions` are visited after the conversation,
so a blob there behind a long history can pass. Structural checks (binary parts, model allowlist,
value/depth limits) still fail closed; a request above `maxNodes` values is refused rather than
passed uninspected. In moejs, the default bound costs ~76 ms for 2,000 tool turns (~3.5 MB; 403 at
the value cap) and ~38 ms for a 200-turn (~350 KB) body that passes.
- A long encoded-looking token (a hash, a minified line) can be a false positive at 400 chars.
Raise `blobBase64Chars`/`blobHexChars` deliberately if you need that.
- `binaryPolicy: guide` never forwards binary bytes. It replaces every binary part with text containing only `type`, `mime` and `bytes`, plus a neutral prompt to select a local extraction tool. It cannot execute the tool; the agent must have the local MCP server configured.
- In guide mode, the walk is bounded by `maxNodes` and uses the same protocol sites as the inspector, so `tool_use.input`, `tool_result.content` and other model/tool data are never rewritten as if they were content parts. The same walk scans every text field for encoded blobs, including older turns and `system`/`instructions`, so the rewritten body cannot carry an unscanned blob through.
- Vendor-sealed replay fields are exempt **only inside their vendor block**: Anthropic thinking
`signature`, Responses reasoning `encrypted_content`, Gemini **model-role** part `thoughtSignature`,
and vendor item `id`/`call_id`. A same-named key in tool arguments or message text is still scanned.
- No network, timers, Node APIs or imports; one file, moejs-compatible.
## Companion DSH bundle
The ingestion half lives in ShyPie:
[`@shypie_privacy/dsh-privacy-gate`](https://github.com/siml1169/ShyPie/tree/main/plugins/dsh-privacy-gate).
It redacts tool results and document text before they enter the session log and provides local
`privacy_extract` / `privacy_ocr` / `privacy_scan` / `privacy_rehydrate` tools.
## Test
```sh
bun test
bun scripts/check.mjs # from the repository root
```
`cases.json` is run through `scripts/middleware.mjs`, the same way Magpie's gateway calls the hooks.
## License
MIT
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@magpie-community/middleware-privacy-gate",
"version": "0.1.0",
"description": "Structural egress gate for Magpie's gateway: rejects image, file and audio parts, encoded blobs and models outside the allowlist when Magpie cannot mask them locally; does not mask text. Companion to the ShyPie DSH bundle for DeepSeek Harness.",
"type": "module",
"files": [
"privacy-gate.middleware.js",
"README.md"
],
"keywords": [
"magpie",
"magpie-middleware",
"gateway-middleware",
"privacy",
"pii",
"dlp",
"security",
"shypie"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/privacy-gate"
},
"magpie": {
"middleware": "./privacy-gate.middleware.js",
"options": {
"allowModels": [],
"localModels": [],
"localProviders": [],
"binaryPolicy": "fail",
"guideTools": [],
"allowUnknownProtocol": false,
"blobBase64Chars": 400,
"blobHexChars": 400,
"scanChars": 200000,
"maxNodes": 40000,
"maxDepth": 40,
"logMaxLines": 40,
"logEveryRows": 50
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,4 @@
import * as mod from "./privacy-gate.middleware.js"
import { check } from "../../scripts/middleware.mjs"
check(import.meta.dir, mod)
+11 -1
View File
@@ -224,6 +224,16 @@
"summary": { "en": "Codar (科搭), SpeedAI's research desktop app: its 17 models (the auto router plus the DeepSeek, GLM, GPT and Claude families) over OpenAI Chat and Anthropic Messages, with the model list refreshed live from the vendor. Signs in by reading the desktop app's token file on this machine (read-only) or by pasting an access token; the daily check-in reports the claim and carries the next claim time; the card shows general and agent points and any running free-model activity.", "zh": "科搭(Codar,SpeedAI 出品的研究桌面应用):17 个模型(auto 路由 + DeepSeek、GLM、GPT、Claude 各系),走 OpenAI Chat 与 Anthropic Messages,模型列表从厂商实时刷新。登录可读取本机桌面端令牌(只读)或粘贴访问令牌;每日签到报告领取结果并带上下次可领时间;卡片显示通用与 Agent 点数及进行中的免费模型活动。" } },
{"package": "@magpie-community/gateway-agentcompass", "name": "AgentCompass", "kind": "middleware", "community": true, "summary": {"en": "AgentCompass routing for Magpie: picks <model>:<effort> from candidateModels by task intent, Model DNA and session continuity, orders pool seats by subscription quota, and optionally serves /v1/systemone for Routing Groups.", "zh": "AgentCompass 路由插件:按任务意图、模型能力与会话连续性从 candidateModels 选出 <model>:<effort>,按订阅配额排号池席位,并可选作为路由组 /v1/systemone 分类器。"}, "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSI+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjgiIHN0cm9rZT0iIzNCODJGNiIgc3Ryb2tlLXdpZHRoPSI0IiBmaWxsPSIjMEYxNzJBIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjIiIHN0cm9rZT0iIzYwQTVGQSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZS1kYXNoYXJyYXk9IjMgMyIvPjxwb2x5Z29uIHBvaW50cz0iMzIsMTIgMzgsMzIgMzIsMjggMjYsMzIiIGZpbGw9IiNFRjQ0NDQiLz48cG9seWdvbiBwb2ludHM9IjMyLDUyIDM4LDMyIDMyLDM2IDI2LDMyIiBmaWxsPSIjRTJFOEYwIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMy41IiBmaWxsPSIjRjhGQUZDIi8+PC9zdmc+"},
{ "package": "@magpie-community/opencode-mclaw-auth", "name": "MClaw", "icon": "https://yun.139.com/w/static/img/LOGO.png", "providers": ["mclaw"], "community": true,
"summary": { "en": "Unofficial MClaw provider: China Mobile Cloud's MClaw agent (ai.yun.139.com) with an OpenAI-compatible endpoint — the browser sign-in harvests the ticket by itself, auto-fetches the llm key and the token multipliers, serves the live model catalogue and the aitokens pool usage, and renews the ticket before it expires.", "zh": "非官方 MClaw 插件:中国移动云 MClaw 智能体(ai.yun.139.com),OpenAI 兼容接口——浏览器登录一次自动收票、自动取 llm key 与积分倍率,动态模型目录与 aitokens 池用量,凭证到期前自动续期。" } }
"summary": { "en": "Unofficial MClaw provider: China Mobile Cloud's MClaw agent (ai.yun.139.com) with an OpenAI-compatible endpoint — the browser sign-in harvests the ticket by itself, auto-fetches the llm key and the token multipliers, serves the live model catalogue and the aitokens pool usage, and renews the ticket before it expires.", "zh": "非官方 MClaw 插件:中国移动云 MClaw 智能体(ai.yun.139.com),OpenAI 兼容接口——浏览器登录一次自动收票、自动取 llm key 与积分倍率,动态模型目录与 aitokens 池用量,凭证到期前自动续期。" } },
{
"package": "@magpie-community/middleware-privacy-gate",
"name": "ShyPie Privacy Gate",
"kind": "middleware",
"community": true,
"summary": {
"en": "Maintained by the ShyPie project. The Magpie-side gate of ShyPie's privacy-first workflow for DeepSeek Harness: with DSH on DeepSeek models behind Magpie's gateway, it turns away image/file/audio parts, encoded blobs and models outside the allowlist whenever Magpie cannot mask them locally. It does not mask text (Magpie's Privacy masking does); images and files get a 403 by default unless localModels and localProviders both allow them. Set binaryPolicy: guide to withhold binary parts and ask the model to choose a local extraction tool instead; structural checks fail closed; a request above maxNodes values is refused, but text beyond scanChars is not inspected (newest first, each field capped), so long encoded tokens can be false positives.",
"zh": "由 ShyPie 项目维护。ShyPie 面向 DeepSeek Harness 的隐私优先工作流中 Magpie 一侧的出口门:当 DSH 通过 Magpie 网关使用 DeepSeek 模型时,对 Magpie 无法本地掩码的图片/文件/音频、编码数据块和允许列表之外的模型一律拒绝。它不做文本掩码(文本由 Magpie Privacy 负责);图片和文件默认返回 403,除非 localModels 和 localProviders 都允许。设置 binaryPolicy: guide 可暂扣二进制内容并提示模型选择本地提取工具;结构性检查按失败关闭处理;超过 maxNodes 个值的请求会被拒绝,但超过 scanChars 的文本不会被检查(优先扫描最新内容,每个字段有上限),较长的编码串可能被误判。"
}
}
]
}