privacy-gate: release 0.3.0 with branded bilingual docs (#798)

privacy-gate 0.3.0: branded bilingual docs, ShyPie icon and README.

Installs with `magpie plugin add @magpie-community/middleware-privacy-gate`
(from this repo's dist index until npm has the package). Names the
built-in "JS gateway plugins" / "JS 网关插件" (id `middleware`). Icons
are a pie, a shield and a gold chevron, with no bird. magpie.icon points
at packages/privacy-gate/assets/shypie-icon.svg. The middleware code
(privacy-gate.middleware.js) is unchanged since e0a4548a.

Reviewed at 85dbd121b833017982d0a97a2f3fab50be98caab. The last round
(67ae63c3b..85dbd121b) changed only docs/operations.md:10 (ends the
sentence) and the aria-label of the two shypie-icon SVGs ("with a gold
chevron").

Run at 85dbd121b on mote (macOS), Bun 1.4.2, HOME=$(mktemp -d):
- bun test packages/privacy-gate: 62 pass, 0 fail.
- bun scripts/check.mjs privacy-gate: ok, exit 0.
- bun scripts/check.mjs (whole repo): exit 0.
- bun test (root): 6449 pass, 20 skip, 0 fail, 472 files.
- npm pack --dry-run: 12 files, version 0.3.0.
- git merge-tree with origin/main ab0d3fe54: clean.

Not tried: installing 0.3.0 into a running magpie (dist has 0.1.0 only
until this merges). No mover or min in yetone/magpie references it.
This commit is contained in:
Muyang
2026-11-07 05:56:05 +08:00
committed by GitHub
parent ab0d3fe54a
commit da8b8d71f3
10 changed files with 833 additions and 57 deletions
+37
View File
@@ -0,0 +1,37 @@
# ShyPie brand assets
The ShyPie mark identifies the ShyPie project and this Magpie middleware. It is
the complete pie holding a shield with a gold chevron.
## Assets
| File | Use |
|---|---|
| `assets/shypie-icon.svg` | Primary mark on the pale mint background |
| `assets/shypie-icon-dark.svg` | Mark for dark surfaces |
| `assets/shypie-icon-transparent.svg` | Transparent-background artwork |
| `assets/shypie-icon-mono.svg` | One-color line/mono mark, transparent |
The README uses the primary mark with a dark-mode `picture` fallback. The gold
chevron is the shield's only emblem; it contains no third-party vendor mark.
## Palette
| Token | Hex |
|---|---|
| Mint background | `#EAF7F0` |
| Deep teal / ink | `#0D4B4E` |
| Golden crust | `#F2B35A` |
| Cream filling | `#FFF2D8` |
| Blush | `#F08074` |
| Dark background | `#062F33` |
## Ownership
The ShyPie name and logo belong to the ShyPie project. The mark contains no
third-party vendor logo.
The source-of-truth vector package is maintained in
[`siml1169/ShyPie/assets/brand/shypie`](https://github.com/siml1169/ShyPie/tree/main/assets/brand/shypie).
The in-tree copies are provided so the README and package page render without an
external dependency.
+404 -54
View File
@@ -1,76 +1,426 @@
# privacy-gate — structural egress gate for Magpie
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/shypie-icon-dark.svg">
<img src="assets/shypie-icon.svg" width="144" alt="ShyPie">
</picture>
</p>
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.
<h1 align="center">ShyPie Privacy Gate</h1>
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.
<p align="center">
<strong>Structural egress gate for Magpie's gateway</strong><br>
Withhold or reject what Magpie cannot mask; guide agents toward local extraction.
</p>
<p align="center">
<img alt="version 0.3.0" src="https://img.shields.io/badge/version-0.3.0-0D4B4E">
<img alt="license MIT" src="https://img.shields.io/badge/license-MIT-F2B35A">
</p>
---
**ShyPie Privacy Gate** is the Magpie-side half of the
[ShyPie](https://github.com/siml1169/ShyPie) privacy-first workflow for
[DeepSeek Harness](https://github.com/deepseek-ai). It runs as a Magpie
gateway middleware and enforces the **structural** part of the egress path:
images, files, audio, encoded blobs and models outside the allowlist.
It is **not a text masker**. Text masking stays Magpie's Privacy setting. This
plugin makes sure a request that still contains bytes Magpie cannot mask does
not reach a provider by accident.
## Why this exists
Magpie's masking is text-only. Its own documentation says *"Images and file data
are sent as they are. Text inside a screenshot is not masked."* A gateway cannot
mask a PDF page or a screenshot, so it must do one of two things:
- **fail closed** — reject the request, or
- **withhold** — remove the bytes and tell the model to process the file locally.
This plugin implements both. It also catches encoded documents smuggled through
text fields, and it is the same gate for every agent behind the gateway — DSH,
Codex, Cursor, Claude Code and scripts.
## At a glance
| | |
|---|---|
| **Runtime** | Magpie gateway middleware (moejs); plain JavaScript, no imports, no I/O |
| **Hooks** | `onRequest`, `onProvider`, `onUsage` |
| **Protocols** | OpenAI chat, OpenAI Responses, Anthropic Messages, Gemini |
| **Default policy** | `binaryPolicy: fail` — binary part for a non-local model → **403** |
| **Alternative** | `binaryPolicy: guide` — withholds bytes, injects type/size metadata + a neutral local-tool prompt |
| **Text masking** | **Not here.** Use Magpie **Settings → Privacy** |
| **Tests** | 62 cases through the repository's `scripts/middleware.mjs` |
## Install
Install from Magpie's plugin registry:
```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
# strictest: block every binary part on every model
magpie plugin options privacy-gate '{}'
magpie plugin # confirm the middleware is listed and on
```
The options object is `ctx.options`; defaults are shown by `magpie plugin options privacy-gate`.
Make sure Magpie's built-in **JS gateway plugins** plugin is enabled
(**Settings → Plugins → Built-in**, id `middleware`). Without it, no middleware runs.
| 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. |
## Two policies
## What it does not inspect
### `fail` — default
- 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.
A binary part for a model that is not explicitly local is rejected with a
**403** and a message that names the part type and explains how to extract it
locally. Nothing is sent.
## Companion DSH bundle
### `guide` — withhold and steer
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.
The request is rewritten into a text-only request:
## Test
```text
[A binary attachment was withheld locally and was NOT sent to you
(type image; mime image/png; bytes 481094). Do not claim to have seen it.
First ask how the user/agent can process or read it locally.]
```
No bytes are forwarded. If `guideTools` is configured, those local tool names
are included in the prompt. The middleware cannot run the tools; the agent must
have the matching local MCP/extractor available.
### Local models
Bytes pass unchanged only when **both** allowlists agree:
```yaml
localModels: ["ollama/*", "lmstudio/*"]
localProviders: ["ollama", "lmstudio"]
```
With `localModels` alone, `onRequest` allows the part but `onProvider` blanks the
content because the provider is not local. Set both or neither.
## How it works
```mermaid
flowchart LR
A["agent request"] --> B{"onRequest<br/>inspect body"}
B -->|no binary, no blob| P["pass to routing"]
B -->|binary + local model| P
B -->|binary + fail| R["403: nothing sent"]
B -->|binary + guide| G["replace binary parts<br/>with metadata + prompt"]
G --> V{"bounded re-scan<br/>no binary, no blob"}
V -->|ok| P
V -->|not ok| R
P --> C["Magpie routing"]
C --> D{"onProvider<br/>provider-known check"}
D -->|provider local| M["Magpie Privacy masking"]
D -->|provider not local| X["blank content, text-only"]
M --> L["provider"]
X --> L
```
The checks are **protocol-position-aware**. Only the protocol's own content
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.
## Configuration
All settings are one JSON object, stored as `ctx.options`:
```sh
bun test
bun scripts/check.mjs # from the repository root
magpie plugin options privacy-gate '{
"binaryPolicy": "guide",
"allowModels": ["deepseek/*", "copilot/*"],
"localModels": ["ollama/*", "lmstudio/*"],
"localProviders": ["ollama", "lmstudio"],
"guideTools": ["shypie.describe", "shypie.extract", "shypie.ocr"]
}'
```
`cases.json` is run through `scripts/middleware.mjs`, the same way Magpie's gateway calls the hooks.
| Option | Default | Meaning |
|---|---:|---|
| `binaryPolicy` | `fail` | `fail` returns 403; `guide` withholds every binary part and injects metadata + a local-tool prompt. |
| `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. |
| `guideTools` | `[]` | Tool names included in the guide prompt. Leave empty unless the local extractor is installed. |
| `blobBase64Chars` / `blobHexChars` | `400` | Encoded run at or above this is a blob. A long hash or minified line can be a false positive. |
| `scanChars` | `200000` | Total text-inspection budget. Each field may use at most an eighth (min 1k). Newest conversation content is walked first. |
| `maxNodes` / `maxDepth` | `40000` / `40` | Bounds on every visited value, including primitives and array elements. Overflow blocks. |
| `allowUnknownProtocol` | `false` | Reject bodies whose protocol is not chat/responses/anthropic/gemini. |
| `logMaxLines` / `logEveryRows` | `40` / `50` | Self-cap on log output / one usage line every N rows. |
## What is inspected
| Layer | Action |
|---|---|
| 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 |
| Malformed `allowModels` | every request 403 |
| Body too complex for the inspection budget | 403 |
| Protocol outside the four supported shapes | 403 unless `allowUnknownProtocol: true` |
| Vendor-sealed replay fields | exempt only in their own protocol block |
| Plaintext PII | **passed through** — Magpie Privacy masks it |
## Limits
- **Text masking is Magpie's job.** Free-text PII and secrets in message text or
tool arguments pass this layer unless Magpie's Privacy masking catches them.
- **The scan is bounded.** The newest content is walked first; each field has a
share of `scanChars`; beyond the total budget text is not inspected. Structural
checks still fail closed.
- **A guide prompt is not extraction.** It names local tools but cannot execute
them. Agents without a configured local extractor will only get advice.
- **Guide-mode MIME metadata has a known bug:** [issue #795](https://github.com/magpie-community/plugins/issues/795)
validates a clipped prefix rather than the whole `media_type`. It does not
forward binary bytes.
- **Magpie engine timeouts fail open.** Magpie stops a hook at 250 ms and sends
the request unchanged. This plugin keeps its own work bounded, but cannot turn
an engine timeout into a rejection. See
[magpie#5305](https://github.com/yetone/magpie/issues/5305).
- A legitimate rejected request should be handled by extracting locally and
sending text — not by turning the gate off.
## Companion: ShyPie for DeepSeek Harness
The ingestion half lives in
[`@shypie_privacy/dsh-privacy-gate`](https://github.com/siml1169/ShyPie/tree/main/plugins/dsh-privacy-gate).
It converts attached images and PDFs to local text before they enter the DSH
session log, keeps raw local text in filter mode, and enforces a fail-closed
`llm/stream` egress guard before DSH dispatches a model request. This Magpie gate
covers the structural check for every other agent behind the same gateway.
## Development
```sh
bun test packages/privacy-gate
bun scripts/check.mjs
```
The cases run through `scripts/middleware.mjs`, the same way Magpie's gateway
invokes the hooks. The middleware has no network access, timers, imports or Node
APIs; the test suite also asserts that constraint.
See:
- [Design and threat model](docs/design.md)
- [Operations and verification](docs/operations.md)
- [Brand assets](BRAND.md)
## License
MIT
MIT. The ShyPie name and logo belong to the ShyPie project. See [BRAND.md](BRAND.md).
---
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/shypie-icon-dark.svg">
<img src="assets/shypie-icon.svg" width="144" alt="ShyPie">
</picture>
</p>
<h1 align="center">ShyPie Privacy Gate(中文)</h1>
<p align="center">
<strong>Magpie 网关的结构性出口检查</strong><br>
对 Magpie 无法掩码的内容执行扣留或拒绝,并引导 agent 走本地提取。
</p>
---
**ShyPie Privacy Gate** 是 [ShyPie](https://github.com/siml1169/ShyPie)
面向 [DeepSeek Harness](https://github.com/deepseek-ai) 隐私优先工作流的
Magpie 侧组件。它以 Magpie 网关中间件的形式运行,负责出口路径中的
**结构性检查**:图片、文件、音频、编码数据块,以及不在允许列表中的模型。
它**不负责文本掩码**。文本掩码仍然是 Magpie 的 Privacy 设置。这个插件确保
Magpie 无法掩码的字节不会意外到达 provider。
## 为什么需要它
Magpie 的掩码只处理文本。其官方文档明确说明:*"Images and file data are sent
as they are. Text inside a screenshot is not masked."* 网关无法掩码 PDF 页面或
截图,因此只有两种选择:
- **失败关闭**:拒绝请求;或
- **扣留**:移除字节,并要求模型在本地处理文件。
本插件同时实现两种方式。它也会拦截通过文本字段夹带的编码文档,并覆盖网关
后面的所有 agent:DSH、Codex、Cursor、Claude Code 和脚本。
## 一览
| | |
|---|---|
| **运行环境** | Magpie 网关中间件(moejs);纯 JavaScript,无 import、无 I/O |
| **钩子** | `onRequest`、`onProvider`、`onUsage` |
| **协议** | OpenAI chat、OpenAI Responses、Anthropic Messages、Gemini |
| **默认策略** | `binaryPolicy: fail`:面向非本地模型的二进制内容 → **403** |
| **替代策略** | `binaryPolicy: guide`:扣留字节,注入类型/大小元数据和本地工具提示 |
| **文本掩码** | **不在这里做**;使用 Magpie **Settings → Privacy** |
| **测试** | 62 个测试用例,通过仓库的 `scripts/middleware.mjs` 运行 |
## 安装
从 Magpie 插件注册表安装:
```sh
magpie plugin add @magpie-community/middleware-privacy-gate
# 最严格模式:所有模型的所有二进制内容都被拒绝
magpie plugin options privacy-gate '{}'
magpie plugin # 确认中间件已列出并启用
```
确认 Magpie 内置的 **JS 网关插件**(id `middleware`)已开启
(**Settings → Plugins → Built-in**)。关闭时不会运行任何中间件。
## 两种策略
### `fail`:默认
当模型未被明确声明为本地时,二进制内容会被拒绝,返回 **403**,并在消息中
说明内容类型以及如何改为本地提取。不会发送任何内容。
### `guide`:扣留并引导
请求会被改写为纯文本请求:
```text
[A binary attachment was withheld locally and was NOT sent to you
(type image; mime image/png; bytes 481094). Do not claim to have seen it.
First ask how the user/agent can process or read it locally.]
```
不会转发任何字节。如果配置了 `guideTools`,这些本地工具名会出现在提示中。
中间件本身不能运行这些工具;agent 必须配置好对应的本地 MCP/提取器。
### 本地模型
只有**两个**允许列表同时匹配时,字节才会原样通过:
```yaml
localModels: ["ollama/*", "lmstudio/*"]
localProviders: ["ollama", "lmstudio"]
```
只配置 `localModels` 时,`onRequest` 会放行,但由于 provider 不是本地,
`onProvider` 会清空内容。两个列表要么都配置,要么都不配置。
## 工作方式
```mermaid
flowchart LR
A["agent 请求"] --> B{"onRequest<br/>检查请求体"}
B -->|无二进制、无 blob| P["进入路由"]
B -->|二进制 + 本地模型| P
B -->|二进制 + fail| R["403:不发送"]
B -->|二进制 + guide| G["替换二进制内容<br/>为元数据 + 提示"]
G --> V{"有界复查<br/>无二进制、无 blob"}
V -->|通过| P
V -->|不通过| R
P --> C["Magpie 路由"]
C --> D{"onProvider<br/>已知 provider 检查"}
D -->|provider 本地| M["Magpie Privacy 掩码"]
D -->|provider 非本地| X["清空内容,仅保留文本"]
M --> L["provider"]
X --> L
```
检查是**协议位置感知**的。只有协议规定的内容 part 才会被当作二进制内容;
工具参数和消息文本中名为 `signature`、`id`、`parameters` 或 `tools` 的字段
属于普通数据,仍会被扫描。
## 配置
所有配置都在一个 JSON 对象中,即 `ctx.options`:
```sh
magpie plugin options privacy-gate '{
"binaryPolicy": "guide",
"allowModels": ["deepseek/*", "copilot/*"],
"localModels": ["ollama/*", "lmstudio/*"],
"localProviders": ["ollama", "lmstudio"],
"guideTools": ["shypie.describe", "shypie.extract", "shypie.ocr"]
}'
```
| 选项 | 默认值 | 含义 |
|---|---:|---|
| `binaryPolicy` | `fail` | `fail` 返回 403;`guide` 扣留所有二进制内容,并注入元数据和本地工具提示。 |
| `allowModels` | `[]` | 模型 glob。`[]` 允许所有模型。如果该选项存在但不是由非空短字符串组成的数组,**所有请求都会被拒绝**,拼写错误不会静默取消允许列表。 |
| `localModels` | `[]` | 允许在 `onRequest` 接收二进制内容的模型 glob;需要与 `localProviders` 配合。 |
| `localProviders` | `[]` | 在 `onProvider` 中检查的 provider-id glob;两个列表必须同时匹配。 |
| `guideTools` | `[]` | guide 提示中包含的本地工具名。未安装本地提取器时保持为空。 |
| `blobBase64Chars` / `blobHexChars` | `400` | 达到或超过该长度的编码串视为 blob。很长的哈希或压缩行可能误报。 |
| `scanChars` | `200000` | 文本检查总预算;每个字段最多使用八分之一(至少 1k)。优先检查最新会话内容。 |
| `maxNodes` / `maxDepth` | `40000` / `40` | 所有访问值的边界,包括原始值和数组元素。超限则阻断。 |
| `allowUnknownProtocol` | `false` | 拒绝协议不是 chat/responses/anthropic/gemini 的请求。 |
| `logMaxLines` / `logEveryRows` | `40` / `50` | 日志输出上限 / 每 N 行一条 usage 日志。 |
## 检查内容
| 层面 | 行为 |
|---|---|
| 面向非本地模型的图片/文件/音频/文档 part | 403(`fail`)或扣留(`guide`) |
| 文本中的编码数据块(base64/base64url、hex、data URI、PDF/ZIP 头) | 403 |
| 模型不在 `allowModels` 中 | 403 |
| `allowModels` 格式错误 | 所有请求 403 |
| 请求体超出检查预算 | 403 |
| 四种支持协议之外的请求 | 403,除非 `allowUnknownProtocol: true` |
| 供应商封装的回放字段 | 只在本协议块内豁免 |
| 明文 PII | **放行**,由 Magpie Privacy 掩码 |
## 限制
- **文本掩码是 Magpie 的职责。** 消息文本或工具参数中的自由文本 PII 和密钥
不会在这个层被处理,除非 Magpie Privacy 掩码捕获它们。
- **扫描是有边界的。** 优先检查最新内容;每个字段只占 `scanChars` 的一部分;
超过总预算的文本不会被检查。结构性检查仍然失败关闭。
- **guide 提示不是提取。** 它会列出本地工具名,但不能执行工具。没有配置本地
提取器的 agent 只会得到建议。
- **guide 模式的 MIME 元数据存在已知问题:**
[issue #795](https://github.com/magpie-community/plugins/issues/795)
检查的是截断后的前缀,而不是完整的 `media_type`。它不会转发二进制字节。
- **Magpie 引擎超时会失败开放。** Magpie 在 250 ms 时停止钩子并原样发送请求。
本插件会限制自身工作耗时,但无法把引擎超时变成拒绝。参见
[magpie#5305](https://github.com/yetone/magpie/issues/5305)。
- 合法的被拒请求应在本地提取后发送文本,而不是关闭网关。
## 配套:DeepSeek Harness
本地摄取部分位于
[`@shypie_privacy/dsh-privacy-gate`](https://github.com/siml1169/ShyPie/tree/main/plugins/dsh-privacy-gate)。
它在 DSH 会话日志写入之前,把附件图片和 PDF 转换为本地文本;filter 模式保留
本地原文;并在 DSH 发出模型请求之前执行失败关闭的 `llm/stream` 出口检查。
本 Magpie 网关插件则为同一网关后面的其他 agent 提供结构性检查。
## 开发
```sh
bun test packages/privacy-gate
bun scripts/check.mjs
```
测试通过 `scripts/middleware.mjs` 运行,调用方式与 Magpie 网关一致。中间件没有
网络访问、定时器、import 或 Node API;测试套件也会检查这一约束。
参见:
- [设计与威胁模型](docs/design.md)
- [运维与验证](docs/operations.md)
- [品牌资产](BRAND.md)
## 许可证
MIT。ShyPie 名称和 logo 属于 ShyPie 项目。详见 [BRAND.md](BRAND.md)。
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024" role="img" aria-label="ShyPie — dark variant">
<rect width="1024" height="1024" fill="#062F33"/>
<g>
<path d="M 512 212 Q 574.82 196.19 626.81 234.84 Q 690.89 244.27 724.13 299.87 Q 779.73 333.11 789.16 397.19 Q 827.81 449.18 812 512 Q 827.81 574.82 789.16 626.81 Q 779.73 690.89 724.13 724.13 Q 690.89 779.73 626.81 789.16 Q 574.82 827.81 512 812 Q 449.18 827.81 397.19 789.16 Q 333.11 779.73 299.87 724.13 Q 244.27 690.89 234.84 626.81 Q 196.19 574.82 212 512 Q 196.19 449.18 234.84 397.19 Q 244.27 333.11 299.87 299.87 Q 333.11 244.27 397.19 234.84 Q 449.18 196.19 512 212 Z" fill="#F2B35A" stroke="#EAF7F0" stroke-width="18" stroke-linejoin="round"/>
<circle cx="512" cy="512" r="250" fill="#FFF2D8" stroke="#EAF7F0" stroke-width="14"/>
<g fill="none" stroke="#062F33" stroke-width="18" stroke-linecap="round">
<path d="M 395 426 C 410 452 442 452 458 426"/>
<path d="M 566 426 C 582 452 614 452 630 426"/>
</g>
<ellipse cx="335" cy="470" rx="36" ry="21" fill="#F08074"/>
<ellipse cx="689" cy="470" rx="36" ry="21" fill="#F08074"/>
<path d="M 512 486 L 700 520 C 724 640 646 742 512 810 C 378 742 300 640 324 520 Z" fill="#0D4B4E" stroke="#EAF7F0" stroke-width="18" stroke-linejoin="round"/><path d="M 360 585 L 512 645 L 664 585 L 664 635 L 512 695 L 360 635 Z" fill="#F2B35A" stroke="#08383B" stroke-width="12" stroke-linejoin="round"/>
<g fill="#FFF2D8" stroke="#EAF7F0" stroke-width="14" stroke-linejoin="round">
<path d="M 310 610 C 275 620 265 670 292 695 C 318 718 350 704 354 675 C 357 654 345 635 330 622 Z"/>
<path d="M 714 610 C 749 620 759 670 732 695 C 706 718 674 704 670 675 C 667 654 679 635 694 622 Z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024" role="img" aria-label="ShyPie — monochrome mark">
<g color="#0D4B4E">
<g fill="none" stroke="currentColor" stroke-width="22" stroke-linejoin="round" stroke-linecap="round">
<path d="M 512 212 Q 574.82 196.19 626.81 234.84 Q 690.89 244.27 724.13 299.87 Q 779.73 333.11 789.16 397.19 Q 827.81 449.18 812 512 Q 827.81 574.82 789.16 626.81 Q 779.73 690.89 724.13 724.13 Q 690.89 779.73 626.81 789.16 Q 574.82 827.81 512 812 Q 449.18 827.81 397.19 789.16 Q 333.11 779.73 299.87 724.13 Q 244.27 690.89 234.84 626.81 Q 196.19 574.82 212 512 Q 196.19 449.18 234.84 397.19 Q 244.27 333.11 299.87 299.87 Q 333.11 244.27 397.19 234.84 Q 449.18 196.19 512 212 Z"/><circle cx="512" cy="512" r="250" stroke-width="16"/>
<path d="M 512 486 L 700 520 C 724 640 646 742 512 810 C 378 742 300 640 324 520 Z"/>
<path d="M 395 426 C 410 452 442 452 458 426"/><path d="M 566 426 C 582 452 614 452 630 426"/>
</g>
<g fill="currentColor"><path d="M 360 585 L 512 645 L 664 585 L 664 635 L 512 695 L 360 635 Z" fill="currentColor" stroke="currentColor" stroke-width="12" stroke-linejoin="round"/><circle cx="305" cy="650" r="36"/><circle cx="344" cy="681" r="21"/><circle cx="719" cy="650" r="36"/><circle cx="680" cy="681" r="21"/></g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024" role="img" aria-label="ShyPie — complete pie holding a shield with a gold chevron">
<g>
<path d="M 512 212 Q 574.82 196.19 626.81 234.84 Q 690.89 244.27 724.13 299.87 Q 779.73 333.11 789.16 397.19 Q 827.81 449.18 812 512 Q 827.81 574.82 789.16 626.81 Q 779.73 690.89 724.13 724.13 Q 690.89 779.73 626.81 789.16 Q 574.82 827.81 512 812 Q 449.18 827.81 397.19 789.16 Q 333.11 779.73 299.87 724.13 Q 244.27 690.89 234.84 626.81 Q 196.19 574.82 212 512 Q 196.19 449.18 234.84 397.19 Q 244.27 333.11 299.87 299.87 Q 333.11 244.27 397.19 234.84 Q 449.18 196.19 512 212 Z" fill="#F2B35A" stroke="#0D4B4E" stroke-width="18" stroke-linejoin="round"/>
<circle cx="512" cy="512" r="250" fill="#FFF2D8" stroke="#0D4B4E" stroke-width="14"/>
<g fill="none" stroke="#0D4B4E" stroke-width="18" stroke-linecap="round">
<path d="M 395 426 C 410 452 442 452 458 426"/>
<path d="M 566 426 C 582 452 614 452 630 426"/>
</g>
<ellipse cx="335" cy="470" rx="36" ry="21" fill="#F08074"/>
<ellipse cx="689" cy="470" rx="36" ry="21" fill="#F08074"/>
<path d="M 512 486 L 700 520 C 724 640 646 742 512 810 C 378 742 300 640 324 520 Z" fill="#0D4B4E" stroke="#08383B" stroke-width="18" stroke-linejoin="round"/><path d="M 360 585 L 512 645 L 664 585 L 664 635 L 512 695 L 360 635 Z" fill="#F2B35A" stroke="#08383B" stroke-width="12" stroke-linejoin="round"/>
<g fill="#FFF2D8" stroke="#0D4B4E" stroke-width="14" stroke-linejoin="round">
<path d="M 310 610 C 275 620 265 670 292 695 C 318 718 350 704 354 675 C 357 654 345 635 330 622 Z"/>
<path d="M 714 610 C 749 620 759 670 732 695 C 706 718 674 704 670 675 C 667 654 679 635 694 622 Z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024" role="img" aria-label="ShyPie — complete pie holding a shield with a gold chevron">
<rect width="1024" height="1024" fill="#EAF7F0"/>
<g>
<path d="M 512 212 Q 574.82 196.19 626.81 234.84 Q 690.89 244.27 724.13 299.87 Q 779.73 333.11 789.16 397.19 Q 827.81 449.18 812 512 Q 827.81 574.82 789.16 626.81 Q 779.73 690.89 724.13 724.13 Q 690.89 779.73 626.81 789.16 Q 574.82 827.81 512 812 Q 449.18 827.81 397.19 789.16 Q 333.11 779.73 299.87 724.13 Q 244.27 690.89 234.84 626.81 Q 196.19 574.82 212 512 Q 196.19 449.18 234.84 397.19 Q 244.27 333.11 299.87 299.87 Q 333.11 244.27 397.19 234.84 Q 449.18 196.19 512 212 Z" fill="#F2B35A" stroke="#0D4B4E" stroke-width="18" stroke-linejoin="round"/>
<circle cx="512" cy="512" r="250" fill="#FFF2D8" stroke="#0D4B4E" stroke-width="14"/>
<g fill="none" stroke="#0D4B4E" stroke-width="18" stroke-linecap="round">
<path d="M 395 426 C 410 452 442 452 458 426"/>
<path d="M 566 426 C 582 452 614 452 630 426"/>
</g>
<ellipse cx="335" cy="470" rx="36" ry="21" fill="#F08074"/>
<ellipse cx="689" cy="470" rx="36" ry="21" fill="#F08074"/>
<path d="M 512 486 L 700 520 C 724 640 646 742 512 810 C 378 742 300 640 324 520 Z" fill="#0D4B4E" stroke="#08383B" stroke-width="18" stroke-linejoin="round"/><path d="M 360 585 L 512 645 L 664 585 L 664 635 L 512 695 L 360 635 Z" fill="#F2B35A" stroke="#08383B" stroke-width="12" stroke-linejoin="round"/>
<g fill="#FFF2D8" stroke="#0D4B4E" stroke-width="14" stroke-linejoin="round">
<path d="M 310 610 C 275 620 265 670 292 695 C 318 718 350 704 354 675 C 357 654 345 635 330 622 Z"/>
<path d="M 714 610 C 749 620 759 670 732 695 C 706 718 674 704 670 675 C 667 654 679 635 694 622 Z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+13
View File
@@ -0,0 +1,13 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../assets/shypie-icon-dark.svg">
<img src="../assets/shypie-icon.svg" width="96" alt="ShyPie">
</picture>
</p>
# Privacy Gate documentation
- [README](../README.md) — overview, install, options and policies
- [Design and threat model](./design.md) — protocol positions, checks, budgets, limits
- [Operations](./operations.md) — install, baseline config, verification, troubleshooting
- [Brand assets](../BRAND.md) — logo files, palette and ownership
+176
View File
@@ -0,0 +1,176 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../assets/shypie-icon-dark.svg">
<img src="../assets/shypie-icon.svg" width="96" alt="ShyPie">
</picture>
</p>
# Design and threat model
This document describes the structural gate's design, the protocol positions it
trusts, the request budgets, and the limits that remain.
## Goals
1. **No unmaskable bytes leave.** Image, file, audio, video and document parts
must never reach a non-local provider.
2. **No encoded document bypass.** Base64, hex, data URIs and PDF/ZIP magic
smuggled through a text field are rejected.
3. **Deterministic policy.** A malformed option must not silently disable a
check; an unreadable request must not be passed.
4. **Two user outcomes.** `fail` rejects; `guide` withholds the bytes and asks
the model to use a local extractor.
5. **Cheap and bounded.** Magpie gives a request hook 250 ms. The inspection and
guide walk must have hard value/depth limits and no clocks, I/O or imports.
## Non-goals
- This plugin does **not** mask text. Magpie's Privacy setting does that.
- It does not execute OCR or PDF extraction. The DSH bundle or a local MCP tool
does that.
- It does not make a timed-out Magpie hook fail closed. That is an engine
property, not something a middleware can guarantee.
## Request lifecycle
```mermaid
sequenceDiagram
participant A as Agent
participant G as privacy-gate
participant M as Magpie
participant P as Provider
A->>M: request + protocol body
M->>G: onRequest(body, ctx)
alt clean request
G-->>M: body unchanged
else binary part, non-local model, policy=fail
G-->>M: reject(403)
else binary part, non-local model, policy=guide
G-->>M: text-only body with metadata
end
M->>G: onProvider(body, ctx)
alt provider is local
G-->>M: body unchanged
else provider is not local
G-->>M: body with content containers blanked
end
M->>P: provider request
M->>G: onUsage(row)
```
## Policy modes
| Input | `binaryPolicy: fail` | `binaryPolicy: guide` |
|---|---|---|
| No binary parts | pass | pass |
| Binary part, model + provider local | pass | pass |
| Binary part, non-local | 403 | replace every binary part with text metadata and a local-tool prompt |
| Binary part and encoded blob | 403 | guide walk scans all text; blob → 403 |
| Malformed `binaryPolicy` | falls back to `fail` | — |
`localModels` and `localProviders` are independent:
- `onRequest` knows the model; it allows a binary part only when the model is in
`localModels`.
- `onProvider` knows the provider; it blanks content unless the provider is in
`localProviders`.
- Therefore **both** must match for bytes to reach a local endpoint.
## Structural inspection
The walker is protocol-position-aware. A part is treated as binary only when it
sits where that protocol puts content parts:
| Protocol | Site where binary parts are recognized |
|---|---|
| OpenAI chat | `messages[].content[]` |
| OpenAI Responses | `input[]` items and their content parts |
| Anthropic Messages | `messages[].content[]` |
| Gemini | `contents[].parts[]` |
That matters because a tool argument or a tool result can contain arbitrary
objects. `tool_use.input`, `tool_result.content`, `function_call.arguments`,
`functionResponse.response` and message text are scanned as ordinary data, not
as trusted protocol content positions.
### Binary part types
The gate recognizes image, file, audio, video and document content shapes,
including `image_url`, `input_image`, `input_file`, `image`, `file`, `document`,
`inlineData`, `inline_data`, `fileData` and their common protocol variants.
### Encoded text
A text field is rejected when it contains:
- a base64/base64url run at or above `blobBase64Chars` (default 400),
- a hex run at or above `blobHexChars` (default 400),
- a `data:` URI,
- `%PDF-` or `PK\x03\x04` file magic.
The run-length scan is linear; the old `{400,}` regexes are gone.
### Vendor-sealed replay fields
Some values are returned by a vendor and replayed on every later turn. They are
exempt **only inside their vendor block**, and only when the field belongs to
that protocol:
| Protocol | Exempt field |
|---|---|
| Anthropic thinking | `signature` |
| Anthropic redacted thinking | `data` |
| Responses reasoning | `encrypted_content`, vendor `id` |
| Chat/DSH assistant tool call | `id`, `call_id`, `thoughtSignature` |
| Gemini **model-role** part | `thoughtSignature`, `textSignature` |
The same key in tool arguments or message text is still scanned. The
exemption is scoped by position and by type — never by key name alone.
## Budgets
| Budget | Default | Purpose |
|---|---:|---|
| `scanChars` | 200,000 | Total text scanned per request. Conversation content is newest-first; each field may use at most an eighth of the budget. |
| `maxNodes` | 40,000 | Every visited value, including primitives and array elements. Overflow refuses the request. |
| `maxDepth` | 40 | Nesting bound. |
The guide walk uses the same site rules and the same value bound. It refuses the
request if it hits a bound rather than passing a partially rewritten body.
Measured in the Magpie engine (moejs on the reference machine): a 2,000-turn
Claude-Code-shaped body (about 3.5 MB / 40k values) is refused at the value cap
in about 76 ms; a 200-turn body passes in about 38 ms. These are capacity
measurements, not a guarantee that the engine's 250 ms hook limit is never hit.
## Failure semantics
- Options are parsed defensively. `binaryPolicy: "Guide"` falls back to `fail`;
a present-but-malformed `allowModels` refuses every request instead of
silently removing the allowlist.
- Unreadable body, unsupported protocol, inspection limit: 403.
- Guide rewrite or verification limit: 403.
- `onProvider` cannot reject. If a binary part reaches it, it blanks the content
containers and lets a text-only request continue.
- The host may still drop the hook on timeout and send the original body. That
is the engine's fail-open behavior, tracked in
[magpie#5305](https://github.com/yetone/magpie/issues/5305).
## Known issue
[Issue #795](https://github.com/magpie-community/plugins/issues/795): guide-mode
`guideMime` validates a 100-character clip rather than the whole `media_type`.
A long base64-like value with a slash in the first 100 characters can contribute
a fake MIME prefix to the guide prompt. This is a metadata-validation bug, not a
binary egress bypass; the part's bytes are still withheld.
## Verification
- 62 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.
+128
View File
@@ -0,0 +1,128 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../assets/shypie-icon-dark.svg">
<img src="../assets/shypie-icon.svg" width="88" alt="ShyPie">
</picture>
</p>
# Operations
Installation, configuration, verification and troubleshooting for the Magpie
middleware.
## Install
```sh
magpie plugin add @magpie-community/middleware-privacy-gate
magpie plugin
```
Confirm that Magpie's built-in **JS gateway plugins** plugin is on
(**Settings → Plugins → Built-in**, id `middleware`). If it is off, no
middleware runs.
## Recommended baseline
For a gateway where only Magpie-routed DSH traffic should carry PII as text:
```json
{
"binaryPolicy": "guide",
"allowModels": ["deepseek/*", "copilot/*"],
"localModels": ["ollama/*", "lmstudio/*"],
"localProviders": ["ollama", "lmstudio"],
"guideTools": []
}
```
Use `"binaryPolicy": "fail"` if you want a hard 403 instead of a withhold-and-
prompt response.
`guideTools` should stay empty unless a matching local MCP extractor is actually
configured for the agent. The middleware cannot execute a tool; it only names it
in the guide prompt.
## Verify
1. Save options:
```sh
magpie plugin options privacy-gate '{"binaryPolicy":"guide"}'
magpie plugin
```
2. Send a request with an image part to a non-local model.
- `guide`: HTTP 200, the model asks how to process the file locally, and no
image bytes appear at the provider.
- `fail`: HTTP 403 and a `privacy-gate:` message.
3. Send a text-only request through the same model. It should pass.
4. Send a request whose text contains a 600-character base64 run. It should be
rejected with a BLOB message even if there is no image part.
5. Check Magpie's plugin log for counts and the `usage` line. The middleware
never logs request content — only provider/model/status/blocked counters.
## Troubleshooting
### I get a 403 for an image
Expected in `fail` mode. Either extract the image locally and send text, or set
`binaryPolicy: "guide"` so the model receives metadata and a local-processing
prompt instead.
### Guide mode returns 200 but the model cannot see the file
Correct. The middleware never forwards the bytes. The model must use a local
MCP/extractor that the agent has configured. Without one, the response is advice,
not extraction.
### An image reaches a local but non-local provider
Set **both** `localModels` and `localProviders`; with only `localModels`,
`onProvider` blanks the content rather than sending it.
### A legitimate request is rejected with BLOB
A long hash, minified line or base64-ish text can exceed the 400-character
threshold. Raise `blobBase64Chars` / `blobHexChars` deliberately and understand
that a larger document can then pass. Do not disable the gate.
### Guide mode returns a MIME-looking string that is not a MIME
Known open issue [#795](https://github.com/magpie-community/plugins/issues/795):
the guide prompt may carry a clipped long `media_type` prefix. The binary bytes
are still withheld; this is metadata-only.
### The request went through even though the gate is on
Check the Magpie log for `onRequest: took too long`. Magpie drops a hook after
250 ms and forwards the original request. This is the engine's fail-open
behavior, tracked in [magpie#5305](https://github.com/yetone/magpie/issues/5305).
The middleware's own budgets reduce the chance of a timeout but cannot change
that outcome.
## Update and rollback
Update through Magpie's plugin manager (`magpie plugin update`) and re-check the
saved options after a version change.
To roll back to the strictest behavior, remove the options (`{}`) or set
`binaryPolicy: fail` and clear `localModels`/`localProviders`. Removing the
plugin leaves agents without the structural check; text masking is unaffected.
## Companion deployment
The DSH half is `@shypie_privacy/dsh-privacy-gate` 0.3.0. It performs local
image/PDF extraction before the DSH transcript and enforces the DSH
`llm/stream` egress guard. This Magpie gate then covers every other agent behind
the same gateway.
## Support
- [README](../README.md)
- [Design](./design.md)
- [Brand assets](../BRAND.md)
- Magpie engine timeout: [magpie#5305](https://github.com/yetone/magpie/issues/5305)
- Guide MIME issue: [#795](https://github.com/magpie-community/plugins/issues/795)
+7 -3
View File
@@ -1,11 +1,14 @@
{
"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.",
"version": "0.3.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": [
"privacy-gate.middleware.js",
"README.md"
"README.md",
"BRAND.md",
"assets",
"docs"
],
"keywords": [
"magpie",
@@ -25,6 +28,7 @@
},
"magpie": {
"middleware": "./privacy-gate.middleware.js",
"icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/privacy-gate/assets/shypie-icon.svg",
"options": {
"allowModels": [],
"localModels": [],