diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8533828ba..292301885 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -33,6 +33,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). 1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON. The size limit holds for the decoded bytes (413), and any other encoding is refused 415. `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`. 2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. - With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults. + - With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (`redactionOptions`), so a change applies to the next request. - `DecidesModel` gives a 400. - A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model. - Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. @@ -194,7 +195,7 @@ go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLo go test -tags nogui ./internal/gateway -run 'TestVertex' go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller' go test -tags nogui ./internal/gateway -run 'TestSearchMCP' -go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts' +go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts|TestRedactRuleEdit' go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag' go test -tags nogui ./internal/provider ./internal/gateway -run 'TestFolderUnder|TestRuleFoldersCleaned|TestRuleMatchesByFolder|TestParseRuleFolders|TestWorkDir|TestRuleByFolder' go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM' diff --git a/internal/gui/api.go b/internal/gui/api.go index f3ae8b222..86f40dc92 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1655,6 +1655,32 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // one masking rule changed in place (nf1qaz2w on Discord): the rule at + // At, which must still be Was, becomes Rule, checked as an added one is. + // A rule that can't be used is said and every rule is kept as it was. + mux.HandleFunc("POST /api/settings/redact-rule", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + At int `json:"at"` + Was redact.Rule `json:"was"` + Rule redact.Rule `json:"rule"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + s := settings.Load() + next, err := editRedactRule(s.RedactRules, in.At, in.Was, in.Rule) + if err != nil { + fail(rw, err) + return + } + s.RedactRules = next + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // the GitHub token the library's requests to GitHub carry: set, or // taken away with "" mux.HandleFunc("POST /api/settings/github-token", func(rw http.ResponseWriter, r *http.Request) { @@ -1923,3 +1949,29 @@ func codexUsers() []string { } return out } + +// editRedactRule is rules with the one at at, which must still be was, +// changed to to: tidied and checked as an added rule is, in the same place. +// It is refused when that rule is no longer there (changed or removed +// meanwhile), when to has neither a prefix nor a pattern (taking a rule +// away is Remove), and when to is another rule already listed. +func editRedactRule(rules []redact.Rule, at int, was, to redact.Rule) ([]redact.Rule, error) { + if at < 0 || at >= len(rules) || rules[at] != was { + return nil, fmt.Errorf("that masking rule is no longer there: it was changed or removed meanwhile") + } + tidy, err := redact.CheckRules([]redact.Rule{to}) + if err != nil { + return nil, err + } + if len(tidy) == 0 { + return nil, fmt.Errorf("a masking rule needs a prefix or a regular expression") + } + for i, o := range rules { + if i != at && o == tidy[0] { + return nil, fmt.Errorf("the masking rule %s is there already", o.Kind) + } + } + next := slices.Clone(rules) + next[at] = tidy[0] + return next, nil +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 2546492c0..c5dad1bf2 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2724,6 +2724,11 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m .search-api .sub.revealed { font-family: var(--code-font, var(--code)); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } :where(html[data-fonts]) .search-api .sub.revealed { font-style: var(--code-style, inherit); font-weight: var(--code-weight, inherit); font-stretch: var(--code-stretch, 100%); } .prefs .val.rule-add .segs { margin-left: 0; } +/* a rule open to edit (nf1qaz2w on Discord): laid out as the add row; a + narrow window puts the match, Save and Cancel on a line of their own under + the name and Prefix or Regex, the match keeping room to type in */ +.prefs .row.rule-editing .val.rule-add { flex-wrap: wrap; row-gap: 6px; } +.prefs .row.rule-editing .rule-tail { display: flex; align-items: center; gap: 6px; flex: 1 1 240px; min-width: 0; } .row.pref .sub.err { color: var(--red); white-space: normal; } .warm-at { display: flex; align-items: center; gap: 8px; margin-left: auto; flex: none; } .warm-at input.at { width: auto; height: 27px; padding: 0 8px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; font-size: 12.5px; font-variant-numeric: tabular-nums; outline: none; transition: border-color .12s, box-shadow .12s; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 512bab660..baf0f6ded 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21043,14 +21043,76 @@ function renderRedactRules(s, row) { head.classList.add("rule-row"); head.querySelector(".val").classList.add("rule-add"); if (d.err) head.querySelector(".sub").classList.add("err"); - // and the rules under it, each by the name its placeholders have + // and the rules under it, each by the name its placeholders have, with + // Edit and Remove + const same = (a, b) => (a.kind || "") === (b.kind || "") && (a.prefix || "") === (b.prefix || "") && (a.regex || "") === (b.regex || ""); + if (ruleEdit && !(rules[ruleEdit.at] && same(rules[ruleEdit.at], ruleEdit.was))) ruleEdit = null; rules.forEach((r, n) => { + if (ruleEdit?.at === n) return editRedactRule(r, n, row); + const ed = el("button", "text rule-edit", t("Edit")); + ed.onclick = () => { + ruleEdit = { at: n, was: r, kind: r.kind || "", by: r.regex ? "regex" : "prefix", match: r.regex || r.prefix || "", err: "" }; + renderSettings(); + $("#redactList input.rule-match.editing")?.focus({ preventScroll: true }); + }; const x = el("button", "text", t("Remove")); x.onclick = () => set(rules.filter((_, i) => i !== n)); - row(r.kind, r.prefix ? t("Starts with {p}", { p: r.prefix }) : t("Matches {re}", { re: r.regex }), x); + row(r.kind, r.prefix ? t("Starts with {p}", { p: r.prefix }) : t("Matches {re}", { re: r.regex }), ed, x); }); } +// editRedactRule: the rule at n, open to change in its place (nf1qaz2w on +// Discord: rules could only be removed) — its name, prefix or regex and +// what to match, laid out as the row that adds one. Save sends it alone, +// checked as an added rule is: one magpie can't use is said in the row, +// what was typed kept and every rule as it was. Cancel (or Escape) leaves +// the rule as it was. +let ruleEdit = null; // { at, was, kind, by, match, err } +function editRedactRule(r, n, row) { + const d = ruleEdit; + const kind = input(d.kind, "API_KEY"); + const match = input(d.match, d.by === "prefix" ? "oc_sk_" : "oc_sk_[A-Za-z0-9]{20,}"); + kind.className = "words rule-kind editing"; + match.className = "words rule-match editing"; + kind.setAttribute("aria-label", t("Name")); + match.setAttribute("aria-label", d.by === "prefix" ? t("Prefix") : t("Regex")); + const by = segs([["prefix", t("Prefix")], ["regex", t("Regex")]], d.by, (v) => { + d.by = v; + match.placeholder = v === "prefix" ? "oc_sk_" : "oc_sk_[A-Za-z0-9]{20,}"; + match.setAttribute("aria-label", v === "prefix" ? t("Prefix") : t("Regex")); + }); + const save = el("button", "text rule-save", t("Save")); + const cancel = el("button", "text rule-cancel", t("Cancel")); + cancel.onclick = () => { ruleEdit = null; renderSettings(); }; + save.onclick = () => { + d.kind = kind.value; d.match = match.value.trim(); + if (!d.match) return match.focus({ preventScroll: true }); + const rule = { kind: d.kind.trim(), [d.by === "prefix" ? "prefix" : "regex"]: d.match }; + save.disabled = true; + writingPrefs(api("settings/redact-rule", { at: n, was: d.was, rule })) + .then((ns) => { prefs = ns; ruleEdit = null; renderSettings(); status(t("Saved"), "ok", 1500); }) + .catch((e) => { if (ruleEdit === d) d.err = t(e.message); status(t(e.message), "err"); renderSettings(); }); + }; + for (const i of [kind, match]) { + i.oninput = () => { d.kind = kind.value; d.match = match.value; }; + i.onkeydown = (e) => { + e.stopPropagation(); + if (e.key === "Enter") save.onclick(); + else if (e.key === "Escape") cancel.onclick(); + }; + } + // the match with Save and Cancel, kept together: a narrow window moves + // them as one under the name and Prefix or Regex + const tail = el("div", "rule-tail"); + tail.append(match, save, cancel); + row(r.kind, d.err || (r.prefix ? t("Starts with {p}", { p: r.prefix }) : t("Matches {re}", { re: r.regex })), kind, by, tail); + // laid out as the row that adds a rule: its words, the fields under them + const head = $("#redactList").lastElementChild; + head.classList.add("rule-row", "rule-editing"); + head.querySelector(".val").classList.add("rule-add"); + if (d.err) head.querySelector(".sub").classList.add("err"); +} + // renderPort: the gateway's port on this computer (Magic_zero on Discord: // 3425 taken by another program, or one easier to tell apart). Any port // from 1024 up can be typed; magpie moves its gateway there and every diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0bb97e8f8..7fc7178c3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -956,6 +956,8 @@ const I18N = { "Regex": "正则", "Starts with {p}": "以 {p} 开头", "Matches {re}": "匹配 {re}", + "that masking rule is no longer there: it was changed or removed meanwhile": "那条脱敏规则已不在了:它刚被修改或移除", + "a masking rule needs a prefix or a regular expression": "脱敏规则需要一个前缀或正则表达式", // web search APIs (#419) "Web search": "联网搜索", "Search APIs": "搜索 API", @@ -5220,6 +5222,8 @@ const I18N = { "Regex": "正則", "Starts with {p}": "以 {p} 開頭", "Matches {re}": "匹配 {re}", + "that masking rule is no longer there: it was changed or removed meanwhile": "那條脫敏規則已不在了:它剛被修改或移除", + "a masking rule needs a prefix or a regular expression": "脫敏規則需要一個前綴或正規表示式", "Web search": "聯網搜尋", "Search APIs": "搜尋 API", "Search API": "搜尋 API", @@ -9453,6 +9457,8 @@ const I18N = { "Regex": "正規表現", "Starts with {p}": "{p} で始まる", "Matches {re}": "{re} に一致", + "that masking rule is no longer there: it was changed or removed meanwhile": "そのマスキングルールはもうありません:その間に変更または削除されました", + "a masking rule needs a prefix or a regular expression": "マスキングルールにはプレフィックスか正規表現が必要です", "Web search": "ウェブ検索", "Search APIs": "検索 API", "Search API": "検索 API", @@ -13705,6 +13711,8 @@ const I18N = { "Regex": "Regex", "Starts with {p}": "Beginnt mit {p}", "Matches {re}": "Entspricht {re}", + "that masking rule is no longer there: it was changed or removed meanwhile": "Diese Maskierungsregel gibt es nicht mehr: Sie wurde inzwischen geändert oder entfernt", + "a masking rule needs a prefix or a regular expression": "Eine Maskierungsregel braucht ein Präfix oder einen regulären Ausdruck", "Web search": "Websuche", "Search APIs": "Such-APIs", "Search API": "Such-API", diff --git a/internal/gui/redact_rule_edit_test.go b/internal/gui/redact_rule_edit_test.go new file mode 100644 index 000000000..097fd88bc --- /dev/null +++ b/internal/gui/redact_rule_edit_test.go @@ -0,0 +1,81 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/redact" + "github.com/yetone/magpie/internal/settings" +) + +// A masking rule is changed in place (nf1qaz2w on Discord: rules could only +// be removed): its name, prefix or pattern change where it stands, and what +// the gateway masks changes with it. A pattern that doesn't compile, a rule +// left with nothing to match, one already listed and a rule that is no +// longer there are refused with the reason, every rule kept as it was. +func TestRedactRuleEdit(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + srv := Handler(nil, nil) + post := func(path, body string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + return rec + } + if rec := post("/api/settings/redact-rules", `{"rules":[{"kind":"GW_KEY","prefix":"oc_sk_"},{"kind":"NS","regex":"ns-[0-9a-f]{12}"},{"kind":"LAST","prefix":"zz_tok_"}]}`); rec.Code != http.StatusOK { + t.Fatalf("rules not set: %d %s", rec.Code, rec.Body) + } + masks := func(s string) bool { + st := settings.Load() + _, n := redact.Mask(s, redact.Options{Secrets: true, Rules: st.RedactRules}) + return n > 0 + } + // each check a value of its own: one masked once is masked again + // wherever it turns up (redact's known values) + if !masks("key ns-0123456789ab here") || masks("key ns_00000000000a here") { + t.Fatal("the rule as set masks the wrong thing") + } + + rec := post("/api/settings/redact-rule", `{"at":1,"was":{"kind":"NS","regex":"ns-[0-9a-f]{12}"},"rule":{"kind":"ns key","regex":" ns_[0-9a-f]{12} "}}`) + want := []redact.Rule{{Kind: "GW_KEY", Prefix: "oc_sk_"}, {Kind: "NS_KEY", Regex: "ns_[0-9a-f]{12}"}, {Kind: "LAST", Prefix: "zz_tok_"}} + if rec.Code != http.StatusOK || !slices.Equal(settings.Load().RedactRules, want) || !strings.Contains(rec.Body.String(), `"kind":"NS_KEY","regex":"ns_[0-9a-f]{12}"`) { + t.Fatalf("edit: %d %s, saved %v", rec.Code, rec.Body, settings.Load().RedactRules) + } + if !masks("key ns_00000000000b here") || masks("key ns-00000000000c here") { + t.Fatal("the gateway's masking didn't follow the edit") + } + // a prefix rule becomes a pattern one, in its place + if rec := post("/api/settings/redact-rule", `{"at":0,"was":{"kind":"GW_KEY","prefix":"oc_sk_"},"rule":{"kind":"GW_KEY","regex":"oc_sk_[A-Za-z0-9]{20,}"}}`); rec.Code != http.StatusOK || settings.Load().RedactRules[0] != (redact.Rule{Kind: "GW_KEY", Regex: "oc_sk_[A-Za-z0-9]{20,}"}) { + t.Fatalf("prefix to regex: %d %s, saved %v", rec.Code, rec.Body, settings.Load().RedactRules) + } + want[0] = redact.Rule{Kind: "GW_KEY", Regex: "oc_sk_[A-Za-z0-9]{20,}"} + + for _, c := range []struct{ name, body, says string }{ + {"bad regex", `{"at":1,"was":{"kind":"NS_KEY","regex":"ns_[0-9a-f]{12}"},"rule":{"kind":"NS_KEY","regex":"ns_[0-9a-f"}}`, "doesn't work"}, + {"matches nothing", `{"at":1,"was":{"kind":"NS_KEY","regex":"ns_[0-9a-f]{12}"},"rule":{"kind":"NS_KEY","regex":"x*"}}`, "matches nothing"}, + {"short prefix", `{"at":2,"was":{"kind":"LAST","prefix":"zz_tok_"},"rule":{"kind":"LAST","prefix":"z"}}`, "prefix"}, + {"empty", `{"at":2,"was":{"kind":"LAST","prefix":"zz_tok_"},"rule":{"kind":"LAST","prefix":" "}}`, "needs a prefix or a regular expression"}, + {"another rule", `{"at":2,"was":{"kind":"LAST","prefix":"zz_tok_"},"rule":{"kind":"ns key","regex":"ns_[0-9a-f]{12}"}}`, "there already"}, + {"out of range", `{"at":3,"was":{"kind":"LAST","prefix":"zz_tok_"},"rule":{"kind":"X","prefix":"xx_tok_"}}`, "no longer there"}, + {"negative", `{"at":-1,"was":{"kind":"LAST","prefix":"zz_tok_"},"rule":{"kind":"X","prefix":"xx_tok_"}}`, "no longer there"}, + {"changed meanwhile", `{"at":1,"was":{"kind":"NS","regex":"ns-[0-9a-f]{12}"},"rule":{"kind":"X","prefix":"xx_tok_"}}`, "no longer there"}, + } { + rec := post("/api/settings/redact-rule", c.body) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), c.says) { + t.Errorf("%s: %d %s, want refused saying %q", c.name, rec.Code, rec.Body, c.says) + } + if got := settings.Load().RedactRules; !slices.Equal(got, want) { + t.Errorf("%s: the rules changed to %v", c.name, got) + } + } + if !masks("key ns_00000000000d here") { + t.Fatal("a refused edit changed what is masked") + } +} diff --git a/internal/gui/tests/redact-rule-edit.test.cjs b/internal/gui/tests/redact-rule-edit.test.cjs new file mode 100644 index 000000000..15e1ffd6e --- /dev/null +++ b/internal/gui/tests/redact-rule-edit.test.cjs @@ -0,0 +1,156 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A masking rule is edited in place (nf1qaz2w on Discord: 自定义脱敏规则现在 +// 只有移除,能否增加一个编辑功能): each rule's row has Edit beside Remove. +// Edit opens the rule in its own row, where it stands, with its name, prefix +// or regex and what it matches filled in, the fields on a line under its +// words, none on top of another. Cancel changes nothing and sends nothing. +// A pattern the gateway refuses is said in the row, what was typed kept and +// the rule as it was; a good one is saved in the same place. No click moves +// the page. In every language, in a wide window and a narrow one. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { edit: "Edit", save: "Save", cancel: "Cancel", matches: "Matches ns_[0-9a-f]{12}" }, + zh: { edit: "编辑", save: "保存", cancel: "取消", matches: "匹配 ns_[0-9a-f]{12}" }, + "zh-TW": { edit: "編輯", save: "儲存", cancel: "取消", matches: "匹配 ns_[0-9a-f]{12}" }, + ja: { edit: "編集", save: "保存", cancel: "キャンセル", matches: "ns_[0-9a-f]{12} に一致" }, + de: { edit: "Bearbeiten", save: "Speichern", cancel: "Abbrechen", matches: "Entspricht ns_[0-9a-f]{12}" }, +}; + +function serve(lang, calls) { + const s = { lang, theme: "light", redact: true, redactRules: [{ kind: "GATEWAY_KEY", prefix: "oc_sk_" }, { kind: "NS", regex: "ns-[0-9a-f]{12}" }, { kind: "LAST", prefix: "zz_tok_" }] }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data, status = 200) => r.fulfill({ status, json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: s }); + if (url.pathname === "/api/settings") return json(s); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/settings/redact-rule" || url.pathname === "/api/settings/redact-rules") { + const body = r.request().postDataJSON(); + calls.push({ path: url.pathname, body }); + // as the gateway checks one: a pattern that doesn't compile is refused + if (body.rule?.regex) { + try { new RegExp(body.rule.regex); } catch { + return json({ error: "the masking rule NS has a regular expression that doesn't work: error parsing regexp: missing closing ]: `[0-9a-f`" }, 400); + } + } + if (body.rule) s.redactRules = s.redactRules.map((x, i) => (i === body.at ? { kind: body.rule.kind.toUpperCase(), ...body.rule.regex ? { regex: body.rule.regex } : { prefix: body.rule.prefix } } : x)); + return json(s); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: a masking rule is edited in its place`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], calls = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, calls)); + await page.goto("http://magpie.test/?view=settings&tab=privacy"); + const head = page.locator("#redactList .row.rule-row").first(); + await head.waitFor(); + // the rules, in order, from the row that adds one + const listed = () => head.evaluate((h) => { + const out = []; + for (let n = h.nextElementSibling; n && out.length < 3; n = n.nextElementSibling) out.push({ name: n.querySelector(".name").textContent, sub: n.querySelector(".sub").textContent, editing: n.classList.contains("rule-editing") }); + return out; + }); + const rule = (name) => page.locator("#redactList .row").filter({ has: page.locator(".name", { hasText: new RegExp(`^${name}$`) }) }); + const scroll = () => page.evaluate(() => [scrollX, scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)]); + const click = async (loc) => { + await loc.scrollIntoViewIfNeeded(); + const before = await scroll(); + const b = await loc.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForTimeout(50); + assert.deepEqual(await scroll(), before, "the click moved nothing"); + }; + + const edit = rule("NS").locator("button.rule-edit"); + assert.equal(await edit.textContent(), w.edit); + await click(edit); + const ed = page.locator("#redactList .row.rule-editing"); + await ed.waitFor(); + assert.deepEqual((await listed()).map((x) => [x.name, x.editing]), [["GATEWAY_KEY", false], ["NS", true], ["LAST", false]], "opened where it stands"); + assert.equal(await ed.locator("input.rule-kind").inputValue(), "NS"); + assert.equal(await ed.locator("input.rule-match").inputValue(), "ns-[0-9a-f]{12}"); + assert.equal(await ed.locator(".segs .opt.on").count(), 1); + assert.equal(await ed.locator("button.rule-save").textContent(), w.save); + assert.equal(await ed.locator("button.rule-cancel").textContent(), w.cancel); + // its fields on a line under its words, inside the row, none on top of another + const m = await ed.evaluate((r) => { + const box = (e) => { const b = e.getBoundingClientRect(); return { l: b.left, r: b.right, t: b.top, b: b.bottom, mid: (b.top + b.bottom) / 2, w: b.width }; }; + return { row: box(r), sub: box(r.querySelector(".sub")), tools: [...r.querySelectorAll(".val input, .val .segs, .val button:not(.opt)")].map((e) => ({ cls: e.className, ...box(e) })), pageW: document.documentElement.scrollWidth, winW: innerWidth }; + }); + assert.deepEqual(m.tools.map((e) => e.cls.split(" ")[0]), ["words", "segs", "words", "text", "text"], "name, prefix or regex, match, Save, Cancel"); + for (const e of m.tools) assert(e.w > 0 && e.l >= m.row.l - 1 && e.r <= m.row.r + 1, `in the row: ${JSON.stringify(m)}`); + // a wide window has them on one line; a narrow one puts the match, + // Save and Cancel on a line under the name and Prefix or Regex + const line = (a, b) => Math.abs(a.mid - b.mid) < 2; + if (width > 760) for (const e of m.tools) assert(line(e, m.tools[0]), `on one line: ${JSON.stringify(m.tools)}`); + else { + assert(line(m.tools[0], m.tools[1]) && line(m.tools[2], m.tools[3]) && line(m.tools[2], m.tools[4]) && m.tools[2].t >= m.tools[0].b, `two lines: ${JSON.stringify(m.tools)}`); + assert(Math.abs(m.tools[2].l - m.tools[0].l) < 1.5 && Math.abs(m.tools[4].r - m.row.r) < 40, `each from the row's left: ${JSON.stringify(m)}`); + } + for (const [i, a] of m.tools.entries()) for (const b of m.tools.slice(i + 1)) { + assert(a.r <= b.l + 0.5 || b.r <= a.l + 0.5 || a.b <= b.t + 0.5 || b.b <= a.t + 0.5, `none on top of another: ${JSON.stringify(m.tools)}`); + } + assert(m.tools[2].w >= 120, `the match field has room: ${m.tools[2].w}`); + assert(m.tools[0].t >= m.sub.b, "the fields are under the words"); + assert(m.pageW <= m.winW, "the page doesn't scroll sideways"); + + // Cancel: what was typed goes, nothing is sent, the rule is as it was + await ed.locator("input.rule-match").fill("changed_[0-9]+"); + await click(ed.locator("button.rule-cancel")); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(calls, []); + const back = await listed(); + assert.deepEqual(back.map((x) => [x.name, x.editing]), [["GATEWAY_KEY", false], ["NS", false], ["LAST", false]]); + assert.match(back[1].sub, /ns-\[0-9a-f\]\{12\}/); + await click(edit); + assert.equal(await ed.locator("input.rule-match").inputValue(), "ns-[0-9a-f]{12}", "Cancel left nothing of the edit"); + + // a pattern that doesn't compile: said in the row, what was typed kept + await ed.locator("input.rule-kind").fill("NS_KEY"); + await ed.locator("input.rule-match").fill("ns_[0-9a-f"); + await click(ed.locator("button.rule-save")); + await ed.locator(".sub.err").waitFor(); + assert.match(await ed.locator(".sub.err").textContent(), /doesn't work/); + assert.equal(await ed.locator("input.rule-match").inputValue(), "ns_[0-9a-f"); + assert.equal(await ed.locator("input.rule-kind").inputValue(), "NS_KEY"); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0], { path: "/api/settings/redact-rule", body: { at: 1, was: { kind: "NS", regex: "ns-[0-9a-f]{12}" }, rule: { kind: "NS_KEY", regex: "ns_[0-9a-f" } } }); + + // fixed and saved by Enter: the rule changes where it stands + await ed.locator("input.rule-match").fill("ns_[0-9a-f]{12}"); + await ed.locator("input.rule-match").press("Enter"); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(calls[1].body, { at: 1, was: { kind: "NS", regex: "ns-[0-9a-f]{12}" }, rule: { kind: "NS_KEY", regex: "ns_[0-9a-f]{12}" } }); + assert.deepEqual(calls.map((c) => c.path), ["/api/settings/redact-rule", "/api/settings/redact-rule"], "one rule sent, not the list"); + const after = await listed(); + assert.deepEqual(after.map((x) => x.name), ["GATEWAY_KEY", "NS_KEY", "LAST"]); + assert.equal(after[1].sub, w.matches); + assert.equal(await page.locator("#redactList .row.rule-editing").count(), 0); + assert.deepEqual(errors, []); + }); + } + } +}