diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 1d41cc9e5..b4966d263 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -19,7 +19,7 @@ three. | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) | | The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | | Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) | -| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). While anything is masked, *Instead of masking, send to* (`redactRouteRow` in `plugins/redact/settings.js`, the redact plugin's part of Settings, which wraps `renderRedact` so app.js carries none of it) picks, in the app menu, a model a request masking would change goes to as written: Off by default, and only the models `/api/settings` lists as `maskRouteModels` (every route of theirs unmasked, `gateway.MaskRoute`), saved with `POST /api/settings/redact-route` (`redact-route.test.cjs`). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) | +| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`, with *Never mask* and *Masked words* drawn a value a row by `wordList` in `plugins/redact/settings.js`, saved as the same list of strings the one comma-separated box saved, `redact-words-list.test.cjs`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). While anything is masked, *Instead of masking, send to* (`redactRouteRow` in `plugins/redact/settings.js`, the redact plugin's part of Settings, which wraps `renderRedact` so app.js carries none of it) picks, in the app menu, a model a request masking would change goes to as written: Off by default, and only the models `/api/settings` lists as `maskRouteModels` (every route of theirs unmasked, `gateway.MaskRoute`), saved with `POST /api/settings/redact-route` (`redact-route.test.cjs`). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) | | Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature=""`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) | | The app's log | `runGUI` and `runPanel` (so `magpie`, `app`, `tray`, `panel`, a window view and a `magpie:` link) call `startLog` before `gui.Run`: `applog.Start` sends the standard logger, which the gateway, the plugin host and Wails' error handler write to, to `app.log` in `appdir.Logs` as well as stderr (`quiet`, which never fails, first, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr), and points `debug.SetCrashOutput` at it, so a panic is in it. Opened from the Finder, the Dock or the Start menu the app has no terminal, and wrote its log nowhere (rayem1w on X, 0.1.2330). The folder is `~/Library/Logs/magpie` on macOS (beside the launch agent's `serve.log`, which launchd writes for `magpie serve`: the two processes never share a file), `%LOCALAPPDATA%\magpie\logs` on Windows, `$XDG_STATE_HOME/magpie` (`~/.local/state/magpie`) elsewhere, and `logs` in a portable data folder. The file is 0600. At 5 MiB (`Limit`) it becomes `app.old.log`; when another magpie (an update's new process) rotated it already (`os.SameFile` of the open file and the path differs), it is only opened again, and when it can't be moved it is emptied. Each line goes through `scrub`, which masks bearer and basic credentials, key and token query parameters, and `sk-`, `AIza`, `gh?_` and JWT shapes, though nothing logged is meant to carry one. Settings › About's Log row (`#logRow`, `settingsJSON.Log` from `applog.Current`, so `magpie web`, which writes no file, shows none) has its path and an Open (`POST /api/settings/log/reveal`) that shows its folder; `magpie log` prints where every log is, `-n` the last lines, `-f` follows across a rotation (`TestTheAppWritesItsLog`, `TestLogFollows`). | [`internal/applog/applog.go`](../../internal/applog/applog.go), [`gui_on.go`](../../internal/cli/gui_on.go), [`log_cli.go`](../../internal/cli/log_cli.go) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 14afa0ce6..5bb91e844 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21788,18 +21788,7 @@ function renderRedact(s, keep) { r.append(who, val); box.append(r); } - const words = (s.redactWords || []).join(", "); - const i = input(words, t("names, codenames, hosts")); - i.className = "words"; - const save = () => { - const v = i.value.split(/[,,\n]/).map((w) => w.trim()).filter(Boolean); - if (v.join(", ") === words) return; - savePrefs({ ...keep, redactWords: v }); - }; - i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(); else if (e.key === "Escape") { i.value = words; i.blur(); } }; - i.onblur = save; - row(t("Masked words"), t("Your own words to keep from vendors, separated by commas"), i); - // plain words, matched as written unless the user asks for any case + // Masked words go above this, a list of the redact plugin's (wordList) row(t("Masked words in any case"), t("A word also matches in other capitals: Nightjar masks NIGHTJAR and nightjar too"), onOff(s.redactWordsAnyCase, (redactWordsAnyCase) => savePrefs({ ...keep, redactWordsAnyCase }))).id = "redactWordsAnyCaseRow"; row(t("Whole words only"), t("A word is not masked inside a longer one: ABC masks ABC and 'ABC' but not XABCD, and 123456 not 0.123456"), @@ -22202,21 +22191,7 @@ function renderMaskActions(s) { more.onclick = () => { maskActAll = !maskActAll; renderSettings(); }; row(t("Personal data"), t("Emails, phone numbers, names and the rest, masked unless set here"), more).classList.add("mask-act-more"); } - // the allow list: values sent as written whichever finder finds them - const allow = (s.redactAllow || []).join(", "); - const i = input(allow, t("ops@company.com, build-01")); - i.className = "words mask-allow"; - i.setAttribute("aria-label", t("Never mask")); - const save = () => { - const v = i.value.split(/[,,\n]/).map((w) => w.trim()).filter(Boolean); - if (v.join(", ") === allow) return; - writingPrefs(api("settings/redact-allow", { allow: v })) - .then((ns) => { prefs = ns; renderSettings(); status(t("Saved"), "ok", 1500); }) - .catch(settingsErr); - }; - i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(); else if (e.key === "Escape") { i.value = allow; i.blur(); } }; - i.onblur = save; - row(t("Never mask"), t("Values that always go as written, each whole and in any case, separated by commas: a team address, a test key"), i); + // Never mask's list goes under these, the redact plugin's (wordList) } // renderMaskTry: text typed here is masked as a request would be now, and diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7f3e77153..28a29b977 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1426,7 +1426,6 @@ const I18N = { "On, on the CPU: CoreML failed ({error})": "已开启,运行在 CPU:CoreML 出错({error})", "On: the model starts with the next request": "已开启:模型会在下一个请求时启动", "Off. The model is downloaded ({size})": "已关闭。模型已下载({size})", - "Your own words to keep from vendors, separated by commas": "不想让模型厂商看到的词,用逗号分隔", "names, codenames, hosts": "人名、代号、主机名", "Masking rules": "自定义脱敏规则", "Secrets magpie doesn't know, such as a gateway's own keys: what they start with, or a regular expression. Masked while Mask secrets is on": "内置规则不认识的密钥,比如自建网关的 Key:按前缀或正则匹配。「脱敏密钥」开启时生效", @@ -4463,7 +4462,6 @@ const I18N = { "Show all kinds ({n} more)": "显示全部类别(还有 {n} 个)", "Never mask": "从不脱敏", "ops@company.com, build-01": "ops@company.com, build-01", - "Values that always go as written, each whole and in any case, separated by commas: a team address, a test key": "总是按原样发送的值,整段匹配、不分大小写,用逗号分隔:比如团队邮箱、测试密钥", "Try it": "试一试", "Paste text an agent might send: it is masked here as a request would be, and kept nowhere": "粘贴一段智能体可能发送的文本:会像真实请求一样在本机脱敏,且不保存", "Deploy with key sk-proj-… and mail ops@company.com": "用密钥 sk-proj-… 部署,发邮件给 ops@company.com", @@ -5994,7 +5992,6 @@ const I18N = { "On, on the CPU: CoreML failed ({error})": "已開啟,執行於 CPU:CoreML 出錯({error})", "On: the model starts with the next request": "已開啟:模型會在下一個請求時啟動", "Off. The model is downloaded ({size})": "已關閉。模型已下載({size})", - "Your own words to keep from vendors, separated by commas": "不想讓模型廠商看到的詞,用逗號分隔", "names, codenames, hosts": "人名、代號、主機名", "Masking rules": "自定義脫敏規則", "Secrets magpie doesn't know, such as a gateway's own keys: what they start with, or a regular expression. Masked while Mask secrets is on": "內建規則不認識的金鑰,比如自建閘道的 Key:按字首或正則匹配。「脫敏金鑰」開啟時生效", @@ -9019,7 +9016,6 @@ const I18N = { "Show all kinds ({n} more)": "顯示全部類別(還有 {n} 個)", "Never mask": "從不脫敏", "ops@company.com, build-01": "ops@company.com, build-01", - "Values that always go as written, each whole and in any case, separated by commas: a team address, a test key": "一律照原樣送出的值,整段比對、不分大小寫,用逗號分隔:例如團隊信箱、測試金鑰", "Try it": "試試看", "Paste text an agent might send: it is masked here as a request would be, and kept nowhere": "貼上一段智慧體可能送出的文字:會像真實請求一樣在本機脫敏,且不保存", "Deploy with key sk-proj-… and mail ops@company.com": "用金鑰 sk-proj-… 部署,寄信給 ops@company.com", @@ -10531,7 +10527,6 @@ const I18N = { "On, on the CPU: CoreML failed ({error})": "オン、CPU で実行中:CoreML が失敗しました({error})", "On: the model starts with the next request": "オン:次のリクエストでモデルが起動します", "Off. The model is downloaded ({size})": "オフ。モデルはダウンロード済み({size})", - "Your own words to keep from vendors, separated by commas": "ベンダーに見せたくない語(カンマ区切り)", "names, codenames, hosts": "人名、コードネーム、ホスト名", "Masking rules": "マスクルール", "Secrets magpie doesn't know, such as a gateway's own keys: what they start with, or a regular expression. Masked while Mask secrets is on": "magpie が認識しないシークレット(独自ゲートウェイのキーなど)を、先頭の文字列または正規表現で指定します。「シークレットをマスク」がオンのときにマスクされます", @@ -13577,7 +13572,6 @@ const I18N = { "Show all kinds ({n} more)": "すべての種類を表示(ほか {n} 件)", "Never mask": "マスクしない", "ops@company.com, build-01": "ops@company.com, build-01", - "Values that always go as written, each whole and in any case, separated by commas: a team address, a test key": "常にそのまま送る値。全体一致、大文字小文字を区別せず、カンマ区切り:チームのアドレス、テスト用キーなど", "Try it": "試す", "Paste text an agent might send: it is masked here as a request would be, and kept nowhere": "エージェントが送りそうなテキストを貼り付けてください。実際のリクエストと同じくこのコンピューターでマスクし、どこにも保存しません", "Deploy with key sk-proj-… and mail ops@company.com": "キー sk-proj-… でデプロイし、ops@company.com にメール", @@ -15099,7 +15093,6 @@ const I18N = { "On, on the CPU: CoreML failed ({error})": "An, auf der CPU: CoreML ist ausgefallen ({error})", "On: the model starts with the next request": "An: das Modell startet mit der nächsten Anfrage", "Off. The model is downloaded ({size})": "Aus. Das Modell ist geladen ({size})", - "Your own words to keep from vendors, separated by commas": "Eigene Wörter, die Anbieter nicht sehen sollen, durch Kommas getrennt", "names, codenames, hosts": "Namen, Codenamen, Hosts", "Masking rules": "Maskierungsregeln", "Secrets magpie doesn't know, such as a gateway's own keys: what they start with, or a regular expression. Masked while Mask secrets is on": "Geheimnisse, die magpie nicht kennt, etwa eigene Schlüssel eines AI-Gateways: ihr Anfang oder ein regulärer Ausdruck. Maskiert, solange „Geheimnisse maskieren“ an ist", @@ -18135,7 +18128,6 @@ const I18N = { "Show all kinds ({n} more)": "Alle Arten zeigen ({n} weitere)", "Never mask": "Nie maskieren", "ops@company.com, build-01": "ops@company.com, build-01", - "Values that always go as written, each whole and in any case, separated by commas: a team address, a test key": "Werte, die immer unverändert gehen, jeweils ganz und ohne Groß-/Kleinschreibung, durch Kommas getrennt: eine Team-Adresse, ein Testschlüssel", "Try it": "Ausprobieren", "Paste text an agent might send: it is masked here as a request would be, and kept nowhere": "Text einfügen, den ein Agent senden könnte: er wird hier wie eine Anfrage maskiert und nirgends gespeichert", "Deploy with key sk-proj-… and mail ops@company.com": "Mit Schlüssel sk-proj-… deployen und an ops@company.com mailen", diff --git a/internal/gui/assets/plugins/redact/i18n.js b/internal/gui/assets/plugins/redact/i18n.js index 3027c8cde..40251f147 100644 --- a/internal/gui/assets/plugins/redact/i18n.js +++ b/internal/gui/assets/plugins/redact/i18n.js @@ -95,6 +95,9 @@ magpie.strings({ "Play the demo": "播放", "Where the demo is": "进度", "Sign in to github.com for me with the password {pw}, the account is {email}.": "用密码 {pw} 帮我登录 github.com,账号是 {email}。", + "Your own words to keep from vendors, one on each row": "不想让模型厂商看到的词,每行一个", + "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "总是按原样发送的值,整段匹配、不分大小写,每行一个:比如团队邮箱、测试密钥", + "Remove {word}": "移除 {word}", }, "zh-TW": { "Turn on masking": "開啟脫敏", @@ -190,6 +193,9 @@ magpie.strings({ "Play the demo": "播放", "Where the demo is": "進度", "Sign in to github.com for me with the password {pw}, the account is {email}.": "用密碼 {pw} 幫我登入 github.com,帳號是 {email}。", + "Your own words to keep from vendors, one on each row": "不想讓模型廠商看到的詞,每行一個", + "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "一律照原樣送出的值,整段比對、不分大小寫,每行一個:例如團隊信箱、測試金鑰", + "Remove {word}": "移除 {word}", }, ja: { "Turn on masking": "マスクをオンにする", @@ -285,6 +291,9 @@ magpie.strings({ "Play the demo": "再生", "Where the demo is": "再生位置", "Sign in to github.com for me with the password {pw}, the account is {email}.": "パスワード {pw} で github.com にサインインして。アカウントは {email}。", + "Your own words to keep from vendors, one on each row": "ベンダーに見せたくない語(1 行に 1 つ)", + "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "常にそのまま送る値。全体一致、大文字小文字を区別せず、1 行に 1 つ:チームのアドレス、テスト用キーなど", + "Remove {word}": "{word} を削除", }, de: { "Turn on masking": "Maskierung einschalten", @@ -380,5 +389,8 @@ magpie.strings({ "Play the demo": "Abspielen", "Where the demo is": "Fortschritt", "Sign in to github.com for me with the password {pw}, the account is {email}.": "Melden Sie mich mit dem Passwort {pw} bei github.com an, das Konto ist {email}.", + "Your own words to keep from vendors, one on each row": "Eigene Wörter, die Anbieter nicht sehen sollen, eines pro Zeile", + "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "Werte, die immer unverändert gehen, jeweils ganz und ohne Groß-/Kleinschreibung, einer pro Zeile: eine Team-Adresse, ein Testschlüssel", + "Remove {word}": "{word} entfernen", }, }); diff --git a/internal/gui/assets/plugins/redact/redact.css b/internal/gui/assets/plugins/redact/redact.css index eb04dd79c..e5caf4deb 100644 --- a/internal/gui/assets/plugins/redact/redact.css +++ b/internal/gui/assets/plugins/redact/redact.css @@ -365,3 +365,13 @@ body.window .msk-onebar::before { inset: -6px calc(var(--bar, 0px) - 16px) -6px /* Masked words as dots until Show (plugins/redact/settings.js) */ #redactList input.words.words-hidden { -webkit-text-security: disc; } #redactList .redact-eye { flex: none; } +/* Masked words and Never mask, one row a value (wordList in settings.js): + the row's words, then the list across its width */ +.row.pref.word-rows { flex-wrap: wrap; row-gap: 8px; } +.row.pref.word-rows .who { flex: 1 1 0; } +.row.pref.word-rows .sub { white-space: normal; } +.word-list { flex: 1 1 100%; display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.word-line { display: flex; align-items: center; gap: 6px; min-width: 0; } +.word-line input.words { flex: 1 1 auto; width: auto; min-width: 0; } +.word-line .word-x { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0; border-radius: 6px; font-size: 15px; color: var(--muted); } +.word-line.word-new .text { flex: none; } diff --git a/internal/gui/assets/plugins/redact/settings.js b/internal/gui/assets/plugins/redact/settings.js index 9d52b0bf6..d3367e55b 100644 --- a/internal/gui/assets/plugins/redact/settings.js +++ b/internal/gui/assets/plugins/redact/settings.js @@ -1,8 +1,8 @@ -// Settings › Privacy's Instead of masking, send to, and Masked words kept -// as dots until Show (the redact plugin's part of Settings). Run after -// app.js, whose helpers it shares (el, icon, openPicker, modelOpt, -// prefWrite, api), and before start.js draws -// Settings. It wraps renderRedact, so app.js carries none of it: the row +// Settings › Privacy's Instead of masking, send to, and Masked words and +// Never mask as lists, Masked words as dots until Show (the redact +// plugin's part of Settings). Run after app.js, whose helpers it shares +// (el, icon, openPicker, modelOpt, prefWrite, api), and before start.js +// draws Settings. It wraps renderRedact, so app.js carries none of it: the row // shows while anything is masked, after the masked-words rows. // redactRouteRow: where a request masking would change goes instead @@ -39,34 +39,136 @@ function redactRouteRow(s) { const after = $("#redactWordsWholeRow"); if (after) after.after(r); else $("#redactList").append(r); } +// wordList: Masked words and Never mask as a list, one row a value +// (noahhrreion on Discord: many words were hard to keep in one small +// box). A row is edited in place and saved on Enter or on leaving it; +// emptied, or its ×, takes it out. The box under them adds one, or +// several split at commas as the one box was, so what is saved is the +// same list of strings. A redraw keeps the box being typed in, and what +// it holds. +let wordsRedrawing = false; +const splitWords = (v) => v.split(/[,,\n]/).map((w) => w.trim()).filter(Boolean); +function wordList(key, list, ph, label, save) { + const box = el("div", "word-list"); + box.dataset.list = key; + let cur = list.map((w) => ({ w })); + const put = (next) => { + if (next.map((o) => o.w).join("\n") === cur.map((o) => o.w).join("\n")) return; + cur = next; + save(next.map((o) => o.w)); + }; + const keys = (i, done, back) => { + i.onkeydown = (e) => { + e.stopPropagation(); + if (e.isComposing || e.keyCode === 229) return; + if (e.key === "Enter") done(true); + else if (e.key === "Escape") { i.value = back; i.blur(); } + }; + // a box a redraw takes away saves nothing: wordFocusBack puts it back + i.onblur = () => { if (!wordsRedrawing && i.isConnected) done(false); }; + }; + for (const o of cur) { + const line = el("div", "word-line"), i = input(o.w, ""); + i.className = "words"; + i.dataset.word = o.w; + i.setAttribute("aria-label", label); + keys(i, (enter) => { + if (enter) return i.blur(); + if (i.value.trim() === o.w) return; + const n = cur.indexOf(o); + if (n >= 0) put([...cur.slice(0, n), ...splitWords(i.value).map((w) => ({ w })), ...cur.slice(n + 1)]); + }, o.w); + const x = el("button", "text danger word-x", "×"); + x.type = "button"; + x.title = t("Remove {word}", { word: o.w }); + x.setAttribute("aria-label", x.title); + // pressed, the box being edited keeps its focus and its words + x.onmousedown = (e) => e.preventDefault(); + x.onclick = () => put(cur.filter((c) => c !== o)); + line.append(i, x); + box.append(line); + } + const line = el("div", "word-line word-new"), add = input("", ph); + add.className = "words word-add"; + add.setAttribute("aria-label", label); + const go = el("button", "text", t("Add")); + go.type = "button"; + const take = () => { + const v = splitWords(add.value); + add.value = ""; + if (v.length) put([...cur, ...v.map((w) => ({ w }))]); + }; + keys(add, (enter) => { if (enter || add.value.trim()) take(); }, ""); + go.onmousedown = (e) => e.preventDefault(); + go.onclick = () => { take(); add.focus(NO_SCROLL); }; + line.append(add, go); + box.append(line); + return box; +} +// wordRow: the row a wordList sits under, its words above and the list +// across the row's width +function wordRow(name, sub, list, ...tools) { + const r = el("div", "row pref word-rows"), who = el("div", "who"), val = el("div", "val"); + who.append(el("div", "name", name), el("div", "sub", sub)); + val.append(...tools); + r.append(who, val, list); + return r; +} +// the box typed in before a redraw, found again after it +function wordFocusOf() { + const i = document.activeElement; + const box = i?.closest?.(".word-list"); + if (!box || i.tagName !== "INPUT") return null; + return { key: box.dataset.list, word: i.dataset.word, value: i.value, a: i.selectionStart, b: i.selectionEnd }; +} +function wordFocusBack(f) { + if (!f) return; + const box = document.querySelector(`.word-list[data-list="${f.key}"]`); + const i = [...(box?.querySelectorAll("input.words") || [])].find((i) => i.dataset.word === f.word); + if (!i) return; + i.value = f.value; + i.focus(NO_SCROLL); + try { i.setSelectionRange(f.a, f.b); } catch {} +} // redactWordsHidden: Masked words drawn as dots until Show, as a key is // (noahhrreion on Discord: a screen share showed the words kept from -// vendors). Still a text box, so an IME writes 百度; a password box only +// vendors). Still text boxes, so an IME writes 百度; password boxes only // where the engine has no text security. Show holds until the window // reloads. let redactWordsShown = false; -function redactWordsHidden() { - const r = [...$("#redactList").children].find((r) => r.querySelector(".who .name")?.textContent === t("Masked words")); - const i = r?.querySelector("input.words"); - if (!i) return; +function redactWordsHidden(r) { const dots = CSS.supports("-webkit-text-security", "disc"); const eye = el("button", "text redact-eye"); eye.type = "button"; const set = () => { - if (dots) i.classList.toggle("words-hidden", !redactWordsShown); - else i.type = redactWordsShown ? "text" : "password"; + for (const i of r.querySelectorAll("input.words")) { + if (dots) i.classList.toggle("words-hidden", !redactWordsShown); + else i.type = redactWordsShown ? "text" : "password"; + } eye.textContent = t(redactWordsShown ? "Hide" : "Show"); eye.setAttribute("aria-pressed", String(redactWordsShown)); }; eye.onclick = () => { redactWordsShown = !redactWordsShown; set(); }; set(); - i.after(eye); + r.querySelector(".val").append(eye); } { const draw = renderRedact; renderRedact = function (s, keep) { - draw(s, keep); - redactWordsHidden(); + const f = wordFocusOf(); + wordsRedrawing = true; + try { draw(s, keep); } finally { wordsRedrawing = false; } + const words = wordRow(t("Masked words"), t("Your own words to keep from vendors, one on each row"), + wordList("words", s.redactWords || [], t("names, codenames, hosts"), t("Masked words"), (redactWords) => savePrefs({ ...keep, redactWords }))); + const at = $("#redactWordsAnyCaseRow"); + if (at) at.before(words); else $("#redactList").append(words); + redactWordsHidden(words); + const acts = $("#maskActList"); + if (acts) acts.append(wordRow(t("Never mask"), t("Values that always go as written, each whole and in any case, one on each row: a team address, a test key"), + wordList("allow", s.redactAllow || [], t("ops@company.com, build-01"), t("Never mask"), (allow) => writingPrefs(api("settings/redact-allow", { allow })) + .then((ns) => { prefs = ns; renderSettings(); status(t("Saved"), "ok", 1500); }) + .catch(settingsErr)))); + wordFocusBack(f); if (s.redact || s.redactPersonal || (s.redactWords || []).length) redactRouteRow(s); }; } diff --git a/internal/gui/tests/mask-actions.test.cjs b/internal/gui/tests/mask-actions.test.cjs index 82411ba0f..4d431e390 100644 --- a/internal/gui/tests/mask-actions.test.cjs +++ b/internal/gui/tests/mask-actions.test.cjs @@ -2,7 +2,7 @@ // Settings › Privacy says what is done with each kind of value found // (#1977): Mask, Warn or Block, saved as the kind's choice, Mask saved as // no choice at all; personal kinds behind Show all kinds; a Never mask -// list saved whole; and Try it, which shows text as the vendor would get +// list saved whole, a value a row; and Try it, which shows text as the vendor would get // it, what was found and what would be done, says a block holds the // request back, keeps the text nowhere in the browser and shows no value // the preview didn't hand back. Every language, Chromium and WebKit, @@ -105,14 +105,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => !document.querySelector('#maskActList .mask-act[data-kind="EMAIL"] .sub.act-warn')); assert.deepEqual(posted.at(-1), ["actions", { actions: { API_KEY: "block" } }]); - // the allow list, split on commas and saved whole - const allow = acts.locator("input.mask-allow"); + // the allow list, its add box split on commas, saved whole and + // drawn a value a row (wordList) + const allow = acts.locator('.word-list[data-list="allow"] input.word-add'); await reach(page, allow); await allow.fill(" team@kelvarn.io,build-01 ,, "); await allow.press("Enter"); for (let i = 0; i < 100 && !posted.some(([k]) => k === "allow"); i++) await page.waitForTimeout(40); assert.deepEqual(posted.filter(([k]) => k === "allow").at(-1), ["allow", { allow: ["team@kelvarn.io", "build-01"] }]); - await page.waitForFunction(() => document.querySelector("#maskActList input.mask-allow")?.value === "team@kelvarn.io, build-01"); + await page.waitForFunction(() => [...document.querySelectorAll('#maskActList .word-list[data-list="allow"] input[data-word]')].map((i) => i.value).join("|") === "team@kelvarn.io|build-01"); // Try it: the vendor's text, what was found, and that it is held back const box = page.locator("#maskTryList textarea.mask-try-in"); diff --git a/internal/gui/tests/redact-words-hidden.test.cjs b/internal/gui/tests/redact-words-hidden.test.cjs index f59770c27..7694463f3 100644 --- a/internal/gui/tests/redact-words-hidden.test.cjs +++ b/internal/gui/tests/redact-words-hidden.test.cjs @@ -1,9 +1,9 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // Settings › Privacy's Masked words are drawn as dots until Show // (noahhrreion on Discord: a screen share showed the words kept from -// vendors), as a provider's key is. The box stays a text box, so an IME -// still writes into it; Show reveals them and holds through a redraw; -// a word typed while hidden saves as before. In every language, Chromium +// vendors), as a provider's key is. Each word's row and the add box stay +// text boxes, so an IME still writes into them; Show reveals them and +// holds through a redraw; a word added while hidden saves as before. In every language, Chromium // and WebKit, wide and narrow. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); @@ -46,17 +46,19 @@ function serve(lang, saved) { }; } -// what the box shows, read from the page as it is in one go (a save +// what the boxes show, read from the page as it is in one go (a save // redraws the list, so a row found a moment before can be gone): dots by // text security, or a password box where the engine has none const shown = (page, name) => page.evaluate((name) => { const r = [...document.querySelector("#redactList").children].find((r) => r.querySelector(".who .name")?.textContent === name); - const i = r.querySelector("input.words"), s = getComputedStyle(i), eye = r.querySelector(".redact-eye"); - const list = document.querySelector("#redactList").getBoundingClientRect(), b = i.getBoundingClientRect(), e = eye.getBoundingClientRect(); + const boxes = [...r.querySelectorAll("input.words")], eye = r.querySelector(".redact-eye"); + const hid = (i) => getComputedStyle(i).getPropertyValue("-webkit-text-security") === "disc" || i.type === "password"; + const list = document.querySelector("#redactList").getBoundingClientRect(), e = eye.getBoundingClientRect(); return { - type: i.type, dots: s.getPropertyValue("-webkit-text-security") === "disc" || i.type === "password", value: i.value, + types: [...new Set(boxes.map((i) => i.type))], dots: boxes.every(hid), shown: boxes.every((i) => !hid(i)), + value: boxes.filter((i) => i.dataset.word).map((i) => i.value).join(", "), eye: eye.textContent, pressed: eye.getAttribute("aria-pressed"), - inside: b.left >= list.left - 1 && e.right <= list.right + 1 && b.width >= 80, + inside: boxes.every((i) => { const b = i.getBoundingClientRect(); return b.left >= list.left - 1 && b.right <= list.right + 1 && b.width >= 80; }) && e.right <= list.right + 1, wide: document.documentElement.scrollWidth > document.documentElement.clientWidth, }; }, name); @@ -83,14 +85,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", let m = await shown(page, w.name); assert.equal(m.value, "Nightjar, 百度"); assert(m.dots, "hidden at first"); - assert.equal(m.type, "text", "a text box, so an IME writes into it"); + assert.deepEqual(m.types, ["text"], "text boxes, so an IME writes into them"); assert.equal(m.eye, w.show); assert.equal(m.pressed, "false"); assert(m.inside && !m.wide, "the box and Show fit the page"); await row.locator(".redact-eye").click(); m = await shown(page, w.name); - assert(!m.dots, "shown"); + assert(m.shown, "shown"); assert.equal(m.eye, w.hide); assert.equal(m.pressed, "true"); @@ -100,21 +102,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => document.querySelector("#redactWordsWholeRow .segs .opt.on")?.textContent === t("On")); await row.locator(".redact-eye").waitFor(); m = await shown(page, w.name); - assert(!m.dots && m.eye === w.hide, "Show holds through a redraw"); + assert(m.shown && m.eye === w.hide, "Show holds through a redraw"); // hidden again, a word typed saves as before await row.locator(".redact-eye").click(); assert((await shown(page, w.name)).dots); - const box = row.locator("input.words"); - await box.fill("Nightjar, 百度, Kestrel"); + const box = row.locator("input.word-add"); + await box.fill("Kestrel"); await box.press("Enter"); for (let n = 0; n < 50 && !saved.at(-1)?.redactWords?.includes("Kestrel"); n++) await new Promise((r) => setTimeout(r, 100)); assert.deepEqual(saved.at(-1).redactWords, ["Nightjar", "百度", "Kestrel"]); // the save redraws the page (Enter, then the old box's blur): wait // for the box on the page now, never one a redraw took away await page.waitForFunction(() => { - const i = document.querySelector("#redactList input.words"); - return i?.isConnected && i.value.includes("Kestrel") && i.nextElementSibling?.classList.contains("redact-eye") && getComputedStyle(i).getPropertyValue("-webkit-text-security") === "disc"; + const i = document.querySelector('#redactList input.words[data-word="Kestrel"]'); + return i?.isConnected && i.closest(".row")?.querySelector(".redact-eye") && getComputedStyle(i).getPropertyValue("-webkit-text-security") === "disc"; }, null, { timeout: 3000 }).catch(() => {}); const last = await shown(page, w.name); assert(last.dots && last.eye === w.show, "still hidden after the save's redraw " + JSON.stringify(last)); diff --git a/internal/gui/tests/redact-words-list.test.cjs b/internal/gui/tests/redact-words-list.test.cjs new file mode 100644 index 000000000..0b9b19ed7 --- /dev/null +++ b/internal/gui/tests/redact-words-list.test.cjs @@ -0,0 +1,140 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Privacy's Masked words as a list, a word a row (noahhrreion on +// Discord: many words were hard to keep in one small box). Words saved by +// the one box before are drawn a row each, untouched until edited; the add +// box takes a word, or several split at commas as the box did, and keeps +// its focus for the next; a row is edited in place, × takes it out, an +// emptied row goes, Escape puts a row back; what is saved is the same list +// of strings, and a reload draws it again. Every language, Chromium and +// WebKit, wide and narrow. +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 { reach, watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const remove = { en: "Remove Kestrel", zh: "移除 Kestrel", "zh-TW": "移除 Kestrel", ja: "Kestrel を削除", de: "Kestrel entfernen" }; + +function serve(lang, saved, box) { + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ 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: box.settings }); + if (url.pathname === "/api/settings") { + if (r.request().method() === "POST") { + box.settings = JSON.parse(r.request().postData()); + saved.push(box.settings.redactWords); + } + return json(box.settings); + } + 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.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 }); + }; +} + +const LIST = '#redactList .word-list[data-list="words"]'; +// the words on the page now, read in one go (a save redraws the list) +const rows = (page) => page.evaluate((sel) => [...document.querySelectorAll(`${sel} input[data-word]`)].map((i) => i.value), LIST); +// the page drawn again with these words, the list's own save landed +const drawn = (page, want) => page.waitForFunction(([sel, want]) => + JSON.stringify([...document.querySelectorAll(`${sel} input[data-word]`)].map((i) => i.dataset.word)) === want, [LIST, JSON.stringify(want)], { timeout: 5000 }); +const savedAs = async (saved, want) => { + for (let n = 0; n < 100 && JSON.stringify(saved.at(-1)) !== JSON.stringify(want); n++) await new Promise((r) => setTimeout(r, 50)); + assert.deepEqual(saved.at(-1), want); +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 400]) { + test(`${engine} ${lang} ${width}px: masked words are a list, added, edited and removed a row at a time`, 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 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], saved = []; + // as the one box saved them: " , " split, trimmed, in order + const box = { settings: { lang, theme: "light", redact: true, redactPersonal: false, redactWords: ["Nightjar", "百度", "build-01.internal"] } }; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, saved, box)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=privacy"); + await page.locator(LIST).waitFor(); + await settingsDrawn(page); + + // what was saved before, a row each, nothing written on open + assert.deepEqual(await rows(page), ["Nightjar", "百度", "build-01.internal"]); + assert.deepEqual(saved, [], "opening the page saves nothing"); + const fit = await page.evaluate((sel) => { + const l = document.querySelector("#redactList").getBoundingClientRect(); + return [...document.querySelectorAll(`${sel} input, ${sel} button`)].every((n) => { const b = n.getBoundingClientRect(); return b.left >= l.left - 1 && b.right <= l.right + 1; }) + && document.documentElement.scrollWidth <= document.documentElement.clientWidth; + }, LIST); + assert(fit, "every row fits the page"); + // no native select, and the words stay dots until Show + assert.equal(await page.locator(`${LIST} select`).count(), 0); + await page.locator('#redactList .row:has(.word-list[data-list="words"]) .redact-eye').click(); + + // added: one, then two pasted with commas, the box keeping its focus + const add = page.locator(`${LIST} input.word-add`); + await reach(page, add); + await add.fill("Kestrel"); + await add.press("Enter"); + await savedAs(saved, ["Nightjar", "百度", "build-01.internal", "Kestrel"]); + await drawn(page, ["Nightjar", "百度", "build-01.internal", "Kestrel"]); + await page.waitForFunction((sel) => document.activeElement?.matches(`${sel} input.word-add`) && document.activeElement.value === "", LIST); + await page.keyboard.type(" Osprey,ops.example.com ,, "); + await page.keyboard.press("Enter"); + const five = ["Nightjar", "百度", "build-01.internal", "Kestrel", "Osprey", "ops.example.com"]; + await savedAs(saved, five); + await drawn(page, five); + + // edited in place: the row keeps its place + const n = saved.length; + const baidu = page.locator(`${LIST} input[data-word="百度"]`); + await baidu.fill("百度在线"); + await baidu.press("Enter"); + const edited = ["Nightjar", "百度在线", "build-01.internal", "Kestrel", "Osprey", "ops.example.com"]; + await savedAs(saved, edited); + await drawn(page, edited); + // Escape puts a row back, and saves nothing + const night = page.locator(`${LIST} input[data-word="Nightjar"]`); + await night.fill("Nope"); + await night.press("Escape"); + assert.equal(await night.inputValue(), "Nightjar"); + assert.equal(saved.length, n + 1, "Escape saved nothing"); + + // × takes a row out, its name said in the window's language + const x = page.locator(`${LIST} .word-line:has(input[data-word="Kestrel"]) .word-x`); + assert.equal(await x.getAttribute("aria-label"), remove[lang]); + await x.click(); + const less = ["Nightjar", "百度在线", "build-01.internal", "Osprey", "ops.example.com"]; + await savedAs(saved, less); + await drawn(page, less); + // and a row emptied goes when it is left + const ops = page.locator(`${LIST} input[data-word="ops.example.com"]`); + await ops.fill(""); + await ops.press("Tab"); + const left = ["Nightjar", "百度在线", "build-01.internal", "Osprey"]; + await savedAs(saved, left); + await drawn(page, left); + + // what was saved is drawn again on the next load + await page.reload(); + await page.locator(LIST).waitFor(); + await settingsDrawn(page); + assert.deepEqual(await rows(page), left); + assert.deepEqual(box.settings.redactWords, left); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/site/public/docs/ja/masking.html b/site/public/docs/ja/masking.html index f86c52664..1d1e7405f 100644 --- a/site/public/docs/ja/masking.html +++ b/site/public/docs/ja/masking.html @@ -96,7 +96,7 @@
  • ページを開く設定 → プライバシー を開きます。
  • シークレットをマスクマスクするもの の シークレットをマスク を オン にします。API キー、秘密鍵、トークン、パスワードが対象です。
  • 必要なら個人情報も個人情報をマスク を オン にすると、メールアドレス、電話番号、ID 番号、銀行カード番号もマスクされます。オンにすると、その下に個人情報の種類ごとのスイッチが並びます。
  • -
  • 自分の語マスクする語 に、ベンダーに見せたくない名前、コードネーム、ホスト名をカンマ区切りで入れます。マスクする語の大文字・小文字を区別しない をオンにすると、Nightjar で NIGHTJAR もマスクされます。magpie が知らないシークレット(自分のゲートウェイのキーなど)は マスクルール に、先頭の文字列か正規表現で追加します。
  • +
  • 自分の語マスクする語 に、ベンダーに見せたくない名前、コードネーム、ホスト名を 1 行に 1 つずつ入れます(カンマ区切りで貼り付けると 1 つずつの行になります)。マスクする語の大文字・小文字を区別しない をオンにすると、Nightjar で NIGHTJAR もマスクされます。magpie が知らないシークレット(自分のゲートウェイのキーなど)は マスクルール に、先頭の文字列か正規表現で追加します。
  • 試す試す にテキストを貼ると、ベンダーが実際に受け取る内容が表示されます。貼った内容は保存されません。
  • 変更は次のリクエストから効き、再起動もエージェント側の変更もいりません。実際にマスクするのは組み込みプラグイン プライバシーマスキング(redact、設定 → プラグイン)で、何かのマスクが求められている間は常にオンです。

    diff --git a/site/public/docs/masking.html b/site/public/docs/masking.html index 66ce1e186..3fdded302 100644 --- a/site/public/docs/masking.html +++ b/site/public/docs/masking.html @@ -96,7 +96,7 @@
  • Open the pageGo to Settings → Privacy.
  • Mask secretsUnder What to mask, set Mask secrets to On: API keys, private keys, tokens and passwords.
  • Personal data, if you want itSet Mask personal data to On for emails, phone numbers, ID and bank card numbers. Each further kind of personal data then gets its own switch below it.
  • -
  • Your own wordsIn Masked words, list names, codenames or hosts to keep from vendors, separated by commas. Masked words in any case makes Nightjar mask NIGHTJAR too. A secret magpie doesn’t know, such as your gateway’s own keys, goes under Masking rules: what it starts with, or a regular expression.
  • +
  • Your own wordsIn Masked words, list names, codenames or hosts to keep from vendors, one on each row (several pasted with commas between become a row each). Masked words in any case makes Nightjar mask NIGHTJAR too. A secret magpie doesn’t know, such as your gateway’s own keys, goes under Masking rules: what it starts with, or a regular expression.
  • Try itPaste a text into Try it to see exactly what the vendor would get. What you paste there isn’t kept.
  • It applies from the next request, with no restart and nothing to change in your agent. The work is done by the built-in plugin Privacy masking (redact, in Settings → Plugins), which is on whenever any masking is asked for.

    diff --git a/site/public/docs/zh/masking.html b/site/public/docs/zh/masking.html index e683515d2..a2ad42a2e 100644 --- a/site/public/docs/zh/masking.html +++ b/site/public/docs/zh/masking.html @@ -96,7 +96,7 @@
  • 打开页面进入 设置 → 隐私。
  • 脱敏密钥在 要遮什么 下把 脱敏密钥 设为 开启:API Key、私钥、Token 和密码。
  • 个人信息(按需)把 脱敏个人信息 设为 开启,邮箱、手机号、身份证号和银行卡号也一并脱敏。打开后,下面会列出其他各类个人信息,每类有自己的开关。
  • -
  • 自定义词在 脱敏词 里填不想让厂商看到的人名、项目代号或主机名,用逗号分隔。脱敏词不区分大小写 打开后,Nightjar 也会遮掉 NIGHTJAR。magpie 不认识的密钥(比如你自己网关的 key)加到 自定义脱敏规则:填它的开头,或一个正则表达式。
  • +
  • 自定义词在 脱敏词 里填不想让厂商看到的人名、项目代号或主机名,每行一个(粘贴用逗号隔开的几个词,会各占一行)。脱敏词不区分大小写 打开后,Nightjar 也会遮掉 NIGHTJAR。magpie 不认识的密钥(比如你自己网关的 key)加到 自定义脱敏规则:填它的开头,或一个正则表达式。
  • 试一试把一段文字粘到 试一试,就能看到厂商实际会收到什么。粘进去的内容不会保存。
  • 改动从下一个请求开始生效,不用重启,Agent 那边也不用改。实际做脱敏的是内置插件 隐私遮盖(redact,在 设置 → 插件),只要设置里要求了任何脱敏,它就是开着的。