Commit Graph
13 Commits
Author SHA1 Message Date
yetone 62390fe92e redact: a masked word is never masked inside tool definitions or schemas, so Codex's apply_patch grammar reaches OpenAI intact (#1911, loveNangua)
What changed: MaskJSON masked custom words as raw substrings in every
string of the request, tool definitions included. A word "pd" turned
apply_patch's Lark rule name update_hunk into u{{TERM_..}}ate_hunk and
OpenAI refused the request with 400 "Invalid lark grammar". Definitions
are now kept by where they sit in the protocol, not by a key's name:
the request's top-level tools, tool_choice, functions, function_call,
toolConfig/tool_config, response_format, text (an object), reasoning,
include, output_format, output_config and generationConfig, and the
tools of a Responses input item of type additional_tools or
tool_search_output. Inside them only "description" strings are still
masked. A "tools" or "text" key in tool-call arguments, a message, a
Gemini part or a Responses message item is masked as before.

Run: go test ./internal/redact/ ./internal/provider/ (ok). The new
tests use Codex 0.162.1's real request (copied from the gateway's
testdata) with the top-level tools and as a Responses Lite
additional_tools item, plus Anthropic/Chat/Responses/Gemini schema
cases and negative cases. With the old json.go both tests fail
(update_hunk masked, every schema case changed). gofmt -l clean; go vet
-tags nogui on darwin, linux and windows. Not tried: a real request to
OpenAI with the word set.
2026-10-13 14:14:59 +08:00
yetone f045319203 redact: a masked-value test looks for the value outside the placeholders, whose random hash suffix can spell it
TestMoreKinds went red on macOS CI at 6c099edd:
  "scp a.txt ops@db3.internal:/tmp/": "ops" still in
  "scp a.txt {{USERNAME_gwaf7b44}}@{{HOSTNAME_mlopsiy3}}:/tmp/"
The username was masked; the hostname's placeholder suffix, an HMAC under
a key random per test process, happened to spell "ops". Short values in
the table (ops, raw, rinak, rkato, deploy) collide like this now and then.
The "gone" checks in TestMoreKinds and TestMask now look in the text with
placeholders taken out (placeholderRe), so a raw value left in the text
still fails them.

Ran:
- injected the CI placeholder ({{HOSTNAME_mlopsiy3}} for db3.internal) in
  placeholder(): the old tests fail with CI's exact message, the new pass
- go test -count=1 ./internal/redact; -race too
- gofmt -l; go vet on darwin, GOOS=linux, GOOS=windows
2026-10-10 22:43:37 +08:00
yetone d7a1b02032 redact: more kinds of personal data, each with its own switch: SSNs, passports, IBANs, birthdays, MAC addresses and serial numbers on by default; home-folder names, user@host, public IPs and cloud buckets off (lc on Discord)
lc asked in #feedback (message 1558300896142696549) for magpie's masking
to cover more of what identifies a person or a machine. Under Settings >
Privacy > Mask personal data, each kind now has its own Off/On
(settings.redactKinds, redact.Options.Kinds). What each one masks:

- US SSNs: dashed numbers, except ones never issued (000, 666 and 9xx
  areas) and well-known examples. Undashed ones only next to "SSN" or
  "social security".
- Passport numbers, next to passport, Reisepass, 护照 or パスポート.
- IBANs: compact or in groups of four, with the country's length and the
  mod-97 check.
- Birthdays: a date only next to birthday, DOB, born, 生日 and the like.
  A date on its own stays.
- MAC addresses, but not documentation examples or all-decimal groups.
- Serial numbers, next to S/N, serial or 序列号.
- The user name in /Users/x, /home/x and C:\Users\x. The name is masked
  and the path is kept.
- User and host in a shell prompt or an ssh/scp/rsync target (user@host
  goes out as two placeholders, not as an email address), and on
  hostname/user lines whose value ends the line. Code such as
  `hostname = socket.gethostname()` is left alone.
- Public IPv4 and IPv6 addresses. Private, loopback, link-local, CGNAT,
  documentation, multicast and well-known resolver addresses stay, and so
  do version numbers.
- Cloud bucket names in s3://, gs://, oss://, cos://, abfss:// and
  storage URLs. The object path is kept.

The last four are off by default. Agents send their working folder, the
prompt and log lines in nearly every request, and the model then has to
copy the placeholder exactly inside a path or URL. The first six are
rare and sensitive, so they are on. Each placeholder is restored in
replies, in streamed text and in tool-call JSON. Context rules run only
in a window around their words (rule.matches), so masking with the
defaults on 400KB of app.js takes 136ms (112ms before; 222ms with every
kind on).

Tests, run at this head:
- gofmt -l is clean. go vet passes on darwin, GOOS=linux and
  GOOS=windows (-tags nogui) for internal/redact, gateway, gui and
  settings.
- go test -tags nogui ./... under a temp HOME with pinned caches passed
  everywhere except internal/proc's TestNoCommandBypassesProc. That
  failure came from 2da8fbe4, and b934d64a fixed it on main. After the
  rebase, the changed packages and internal/proc were run again and
  passed. New tests:
  - internal/redact TestMoreKinds, TestMoreKindsLeaveAlone (versions,
    timestamps, hashes, UUIDs, model ids, code, ordinary dates, URLs in
    code), TestCategoryDefaults, TestMoreKindsKnown, TestMoreKindsJSON.
  - internal/gateway TestRedactedKinds.
  - internal/gui TestRedactKindsAreRedacts.
- I broke the IBAN checksum by hand and TestMoreKindsLeaveAlone went
  red.
- GUI tests pass in Chromium and WebKit:
  - the new redact-kinds.test.cjs (en, zh, zh-TW, ja and de, at 1100
    and 640 px);
  - i18n-keys, gui-de, gui-ja, gui-zh-tw, redact-rule-row,
    privacy-hides-accounts, privacy-usage-stats, settings-groups,
    settings-sections and mobile-web;
  - 29 more files that open the Privacy page (252 tests).
  privacy-usage-stats now scrolls with the wheel to reach Count me as a
  user, which the new rows push below its 760px window. WebKit doesn't
  let a script scroll Settings.
- Real gateway check: a `magpie serve` built from this tree, under a
  sandbox HOME, on 127.0.0.1:3492, with a fake OpenAI upstream on 3491.
  An Anthropic /v1/messages request went to the upstream with each kind
  as a placeholder. Turning SSNs off and home folders on changed what
  was sent the same way. The streamed reply came back with every value
  restored.
2026-10-10 11:29:03 +08:00
yetone 3c7473eb3f redact: a value masked once is masked again wherever a request has it, whatever words are around it
The masking rules find a value by what is around it: DB_PASSWORD= before
a password, a bound an email may not touch (so an email that ends a
sentence isn't one). The vendor writes about a placeholder in words of
its own ("your password is {{SECRET_…}}", "I will write to {{EMAIL_…}}."),
the agent reads the value there (Restore), and on the next turn that text
is in the history, where no rule matches it, so it went out as written.

Now every value a placeholder was made for (redact's in-memory values,
bounded by maxValues, never written anywhere) is also matched as an exact
string in each string Mask and MaskJSON look at, and goes as the same
placeholder it had (same kind, same keyed hash), so history and vendor
caches stay stable:

- only from 8 characters (the assignment rule's minimum): the 3-character
  passwords the user:password@ rule takes, and the user's own words
  (which Options.Words matches everywhere already), are not;
- personal values only while personal masking is on, secrets only while
  secret masking is on;
- not as a piece of a longer value: a phone or card number with a digit
  beside it, an email inside a longer address (a full stop after it may
  end the sentence), a secret with a letter or digit against it;
- where a rule finds the same span, the rule's kind still wins, so
  nothing masked before changes placeholder;
- in what a vendor signed (7137feb4), the values masked elsewhere in the
  request go back as their placeholders as before, and so do known
  secrets, for a turn whose other copies were compacted away; known
  personal values don't, since a number the vendor wrote of its own
  (13800138000) may be one masked in another conversation, and masking
  it would break the signature.

A prefix index and a 4-byte bitset keep the lookup cheap: a ~1 MB body
masked in ~79 ms with 0, 1k or 200k known values alike (rules dominate).
Every route goes through redact.MaskJSON / Mask (chat, Responses,
Anthropic, Gemini, count_tokens, embeddings/rerank, the Codex backend,
image and video prompts), so each gets it; Scrub, the archive's, gets the
known secrets too.

Tests: TestEchoedValueMaskedNextTurn (gateway: two chat turns where the
fake vendor echoes the placeholders in other words; the second request
must not hold the password or the email, and keeps the first turn's
placeholders; then the echoed text alone through /v1/responses,
/v1/messages, count_tokens, Gemini generateContent, embeddings and the
Codex backend) fails on origin/main with the second turn sending
"…password is Mv4kestrelPass28, and I will write to
tomas.ng@quietfield.dev.". TestKnownValueMaskedInOtherWords and
TestKnownInSigned fail there too; TestShortValueNotMaskedEverywhere and
TestKnownReindexed pin the bounds and the eviction rebuild.

Run: gofmt -l (nothing); go vet -tags nogui ./... on darwin,
GOOS=linux and GOOS=windows; go build -tags nogui for darwin, linux,
windows; go test -tags nogui ./... under a temp HOME with pinned caches
(all ok); internal/redact -count=3 and -race. Not tried against a real
vendor.
2026-10-09 11:56:10 +08:00
yetone 1965e1f0f4 redact: a tool call's arguments are masked again, whatever their keys are called (7137feb4 let them out)
7137feb4 kept two kinds of strings from the masking rules, and both
reached what the agent itself wrote:

- Any object with a non-empty "signature", "thoughtSignature",
  "thought_signature" or "encrypted_content" counted as sealed by the
  vendor, so its strings went out unmasked but for the placeholders of
  values masked elsewhere. A tool_use input like a mail tool's
  {"signature":"Best, Bob","body":"DB_PASSWORD=… call 13800138000"} sent
  the password and the number in the clear; before 7137feb4 both were
  masked. A text block carrying a "signature" key did the same.
- Every key named id, …_id or …Id was kept, in a tool's arguments too:
  {"user_id":…,"phone_id":"13800138000"} went out as written.

Now only a thinking or reasoning block (Anthropic's signature, Responses'
encrypted content, reasoning.* details) or a part with Gemini's thought
signature counts as sealed, and nothing inside a tool_use input or a
functionCall's args does. In those arguments the keys are the tool's, so
no key keeps its value there (an encoded data: value still is); ids
outside them stay as 7137feb4 left them. A signed Gemini functionCall
part still goes back as written. The response side (writer.go) restores
ids again, which changes nothing for a real id and puts back a
placeholder the vendor echoed into a tool's user_id.

Ran (Docker golang:1.26.8, GOTOOLCHAIN=local): TestMaskJSONToolArgsMasked
(new: signature key and id keys in tool_use input, Gemini args, a text
block with a signature key) fails on origin/main in all four cases and
passes; 7137feb4's TestMaskJSONSignedGoesBackAsWritten,
TestMaskJSONKeepsIDs, TestSignedThinkingGoesBackAsSigned and
TestToolCallIDsGoBackAsGiven pass. gofmt -l clean; go vet -tags nogui
for linux, darwin and windows on internal/redact; go test -tags nogui
./internal/redact ./internal/gateway ./internal/usage pass. Not tried
against a real vendor.
2026-10-09 11:29:07 +08:00
yetone 7137feb4fc redact: what a vendor wrote and checks goes back as it wrote it — signed thinking and tool call ids (Jeremy.Zhou on Discord: OpenCode Zen answered 400 "invalid …" until 脱敏密钥 and 脱敏个人信息 were off)
Masking ran its rules over every string of the request except a fixed list
of keys, including two kinds of text the vendor itself wrote and checks
when it comes back:

- A thinking block (Anthropic's signature; also Gemini's thoughtSignature
  and Responses' encrypted reasoning). The vendor thinks about the
  placeholders it was given, the agent gets the values back (Restore), and
  on the next turn the rules masked that text again. Rules depend on
  what is around a value: "the password is {{SECRET_…}}" came back as
  "the password is hunter2abc1", which no rule matches without its
  DB_PASSWORD=, an email ending a sentence fails the email rule's bound,
  and a number the vendor wrote of its own ("13800138000") turned into a
  {{PHONE_…}}. The text no longer matched its signature, and Anthropic
  answers 400 "messages.1.content.0: Invalid `signature` in `thinking`
  block" — and the value itself went to the vendor in the clear.
  Now an object that carries a non-empty signature, thoughtSignature,
  thought_signature or encrypted_content is masked only by putting back
  the placeholders of the values masked elsewhere in the same request
  (longest first): what the vendor wrote, its own words untouched.
- A chat tool result's tool_call_id. "id", "tool_use_id" and "call_id"
  were kept, "tool_call_id" wasn't. GLM's ids are call_ and 19 digits,
  and ~5% of them pass Luhn as a bank card number, so the tool message's
  id became call_-{{BANK_CARD_…}} while the assistant's tool_calls id
  stayed, and the upstream refused the orphaned tool result ("messages
  with role 'tool' must be a response to a preceeding message with
  'tool_calls'"). Now every key named id, …_id, …Id (and their plurals)
  is left alone.

Account masking (账号打码) is display only and doesn't touch requests.

Tests: TestSignedThinkingGoesBackAsSigned (a fake Anthropic upstream that
signs its thinking with an HMAC and checks it, two turns through the
gateway) and TestToolCallIDsGoBackAsGiven (a fake chat upstream that
refuses a tool result with no matching call) fail on origin/main with
exactly those 400s; TestMaskJSONSignedGoesBackAsWritten (Anthropic,
Gemini thought and functionCall, Responses reasoning shapes, plus an
unsigned thinking block still masked) and TestMaskJSONKeepsIDs fail there
too. All pass with the change.

Run: gofmt -l (nothing), go vet -tags nogui ./... on darwin, GOOS=linux
and GOOS=windows, go build -tags nogui (darwin, linux, windows),
go test -tags nogui ./... under a temp HOME: all ok. Not tried against the
real OpenCode Zen, and the reporter's exact error text and model weren't
seen; both upstream checks are modeled on Anthropic's and OpenAI's
documented errors.
2026-10-09 11:09:22 +08:00
yetone 8fb09d03c6 cleanup: drop redact.Known and the quotaWire type — nothing calls either (deadcode -test -tags nogui, git grep). vet on darwin, linux, windows; redact and provider tests pass. 2026-10-06 06:07:02 +08:00
kevin b78a1ce0b2 redact: hold a split placeholder of a long custom kind in a stream (#862) 2026-10-05 12:42:42 +08:00
tobitege 21702d01ff Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars

Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows.

* Makefile: know magpie's folder by its go.mod, so paths with spaces work

The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs.

* i18n: German for the strings main added since, with a parity test

75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system.

* appdir: ignore relative folder variables when reading, keep them for children

CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder.

* Sandbox the tests main added since

internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE.

* agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose

omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over.

* i18n: German for the Library's multi-select and System One's decision API

The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes.

* appdir: tidy the import into magpie's group; say what Go makes of /c/x

The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x.
2026-10-04 23:30:56 +08:00
yetone 258d04f569 gateway: a request archive, off unless turned on, keeps each call's headers and bodies in the user's own S3 bucket and a recent call reads its own back (Jorben on Discord: 请求存档) — the Gateway page's recent calls only ever held the last bodies in memory, the first 256 KB of each, with no headers, gone at a restart. A switch over Recent calls ("Request archive", POST /api/settings/archive, settings' requestArchive) turns it on, refused with a reason while sync isn't set up with an s3:// bucket; with it on, each call the gateway serves gets an id (UTC HHMMSS-<16 hex>, said back in X-Magpie-Archive-Id) and, once it is recorded, its method, path and query, request headers and body and response status, headers and body go as one JSON file to <prefix>/magpie/archive/<YYYY-MM-DD>/<id>.json in the bucket sync keeps its backup in, signed with the same client (davsync.Bucket, no new SDK). Before anything leaves, Authorization, x-api-key, Cookie, Set-Cookie, any header or JSON field or query parameter named for a key, token, secret or password, and anything that looks like a key or token anywhere in the text (the redaction rules' patterns, in a stream's data lines too) become [REDACTED] — gone, no placeholder kept; the archive is plain JSON, readable in the bucket, not sealed with the passphrase. Uploads go one at a time on their own goroutine from a queue of 16 calls, each body capped at the 256 KB the call already keeps and marked truncated; a full queue drops the call with a log line, a failed upload is logged and shown under the switch until the next one goes, and no request waits on any of it. A recent call the archive kept shows its date and id under its bodies, and "Fetch from archive" (GET /api/archive?date=&id=, only a date and an id of that shape) shows the request's and response's headers and bodies as the bucket has them, or says it isn't there yet. The hook is in record() and the Call literal, so PR #239's request log lines are not touched; the archived call carries its usage, and with #239 its vendor request id. Only calls through serve() are archived, not Codex's backend, image or video calls. TestArchiveOn, TestArchiveOff, TestArchiveName, TestRequestArchiveToS3 (a real gateway request through the signature-checking fake S3), TestScrub and request-archive.test.cjs fail without the change; TestSettingsSaveKeepsWhatItDoesNotSend now sets requestArchive. A sandbox magpie web with a fake vendor and a fake S3 server uploaded nothing while off; on, it uploaded a signed archive with none of eight planted secrets in it, read it back through /api/archive and in the page, and with the S3 server down served the call in 0.1 s and said why the upload failed. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (Claude account tests and TestClaudeRunEndsWhenTheClientLeaves pass alone); request-archive, click-scroll, old-webkit, sse-body, gateway-fold pass. 2026-10-01 17:13:34 +08:00
yetone 4216d2b338 redact: a gateway's key in "key": "oc_sk_…" is masked, and Settings → Privacy takes the user's own masking rules (#195) — an OpenCode Go key in providers.json went to the vendor as it was: the API key rules wanted sk- with a hyphen, and a field called key alone was none of the secret field's names. Now a key of a gateway or relay, two to four letters and _sk_ (oc_sk_, or_sk_) with digits in it, is an API_KEY wherever it is, and a field named key and nothing more (not sort_key, monkey or obj.key) is a SECRET when its value is 16 or more letters and digits both, so a map's "key": "value" and key = "someIdentifier" are left alone; \"key\": \"…\" in JSON inside a string is found too. The secret field's names and its markers come from one list, so they can't drift apart, and of two rules finding the same value the first keeps it, so its placeholder no longer changes between an API_KEY and a SECRET from one request to the next. Masking rules, next to 脱敏词: a name for the placeholders (upper case letters, digits and _, 24 at most) and a prefix (then 8 or more key characters) or an RE2 regular expression, group 1 the value if it has one, masked with the secrets while 脱敏密钥 is on and put back as the others are, the user's name winning where one of magpie's finds the same value. They are set on their own: a pattern that doesn't compile, matches nothing at all, or is too long (300), a prefix under 3 or over 64, both at once, or more than 32 rules, is refused with the reason under the add row and what was typed kept. Tested: every row of the issue's table and the false positives, the rules' tidying, errors, stable placeholders, restore, overlaps, and kinds with digits in a stream; the settings file and the gateway's count_tokens with a rule; the page in a stub magpie web (add, a bad regex, remove, zh dark) 2026-09-29 15:26:01 +08:00
Zhizhen HeandClaude Code 41de0d87eb gateway: count_tokens counts the masked prompt, and a count that cannot be had is told apart — the count Claude Code asks for before every turn went to the vendor as the conversation was written, so Mask secrets was defeated on every one; it now goes masked, the same prompt the turn it counts sends. An endpoint that doesn't implement counting (404/405/501, or a 400 that says so, in English or Chinese) falls back to the local estimate as before; a limited key or a broken connection yields to the next checked key and rests the one that failed, as a generation would, while a client's own cancellation rests nothing; and a real error — a wrong key, a prompt past the model's context, an image it won't take — reaches the agent. The gateway tests are isolated from the machine now (a temp HOME, inert stubs for the sign-in CLIs and the keychain) so a cache that outlives a test can't reach a real login, and the redaction tests' cold starts run in parallel. (#103)
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-09-27 18:58:23 +08:00
yetone 67c539d5da gateway: secrets can stay on the machine — with Settings › Privacy › Mask secrets on, API keys, private keys, tokens, JWTs and the passwords of connection strings and assignments in what an agent sends go to the vendor as placeholders like {{API_KEY_k3v9x2mq}}, and what the vendor answers has them back, streams included (a placeholder split between two events is put back whole, a tool call's arguments get the value escaped); personal data (emails, phone numbers, ID and bank card numbers, checksum-checked) and the user's own words can be masked too. A placeholder is the same for the same value every time, so a conversation's history and what the vendor cached of it stay the same turn after turn, and the request log shows what the vendor saw. Suggested on X as maskit's idea; written from scratch 2026-09-26 14:21:14 +08:00