providers: Send requests unmasked is the user's switch at any address, with a caution while on for one not local (AcMilan)
AcMilan (Discord) runs a vLLM at http://llm.corp.lan:8000, and the editor never offered "Send requests unmasked": the switch showed only for a localhost, *.local or private-IP address. Asked, he said the choice should be the user's for each provider. provider.SkipsRedaction is now: Unredacted, no signed-in account, not another magpie, and at least one address. Nothing is looked up on the request path. The editor shows the row for every provider but an account or remote magpie. While it is ticked, an amber caution under it names an address not on this computer or the local network (awayHost). A name of the user's own DNS is asked about, only while ticked, through POST /api/local-hosts (provider.LocalHost -> netproxy.LocalName: every address loopback, private or link-local, 400ms lookup, kept 1 minute). That answer only words the caution. CLI help and `provider show` say the same. The 'away' i18n line is in zh, zh-TW, ja and de. To stay inside the core script budget, a few nearby editor comments were cut down (no raise). Run (logs in the worktree's logs/): - Full Go suite on mote at base024393fbb(go test ./... -timeout 45m). Every package is ok except internal/gui. Its reds are the AppKit window tests (#4125, #2645, #1936, #3949, #3178) and TestRestartHandsTheGatewayOver (#4167), plus TestCoreScriptBudget, which was mine and is fixed. At the pushed head (rebased on995f84a0f): the gui, provider, netproxy, gateway and cli tests for this area, with TestCoreScriptBudget and TestI18n: ok. - GOOS=linux go vet -tags nogui ./internal/... and GOOS=windows go vet on the touched packages: ok. gofmt -l is clean. - provider-unmasked.test.cjs and decide-endpoint-label.test.cjs: 34/34 in Chromium and 34/34 in WebKit (Linux, wsl-run), on the final app.js. - The 155 GUI files that open a provider editor, both engines (WebKit on Linux, Chromium on mote). Each file red there was rerun on Linux beside the base024393fbb. The one red this change caused was decide-endpoint-label: a /api/local-hosts fetch cut off by navigation showed as a console error. That is why names are now asked only while the switch is on. The rest are red on the base too and have issues (#4431 and others). mote's browsers were crashing (#4125), so Chromium was compared on Linux. Broken by hand: - The old local-only gate put back in SkipsRedaction: TestSkipsRedaction (lan name, vendor, public IP, own proxy) and TestLANNameUnredactedProvider went red. - awayHost returning "": 12 caution tests went red. - The "only while on" guard removed: 4 "nothing is asked while the switch is off" tests went red. Not tried: a real LAN DNS server, or AcMilan's own setup; WebKit on macOS (mote's WebKit can't launch, #4125); the Windows app; the whole GUI suite beyond the provider-editor files.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -135,8 +135,8 @@ const providerUsage = `usage:
|
||||
(Ollama, LM Studio, oMLX or MLX-Serve on another port or computer: each of its
|
||||
URLs moves there, keeping its path; address= alone puts it back at the default)
|
||||
magpie provider set ollama unmasked=yes
|
||||
(a model on this computer or the local network: Settings' redaction leaves its
|
||||
requests as written; not for a local relay that passes them on to a vendor)
|
||||
(Settings' redaction leaves its requests as written, at any address: your call,
|
||||
so mind a relay that passes them on to a vendor; never a signed-in account)
|
||||
magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000'
|
||||
magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %'
|
||||
magpie provider set my-relay balance.method=POST
|
||||
@@ -840,9 +840,9 @@ func showProvider(p provider.Provider) error {
|
||||
kv("user-agent", "agent's"+muted.Render(why))
|
||||
}
|
||||
if p.Unredacted {
|
||||
why := " local: Settings' redaction leaves its requests as written"
|
||||
why := " Settings' redaction leaves its requests as written"
|
||||
if !p.SkipsRedaction() {
|
||||
why = " but masked: not every address of it is on this computer or the local network"
|
||||
why = " but masked: a signed-in account, another magpie or no address"
|
||||
}
|
||||
kv("unmasked", "yes"+muted.Render(why))
|
||||
}
|
||||
@@ -1182,9 +1182,9 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
return fmt.Errorf("compaction=native|magpie, not %q", v)
|
||||
}
|
||||
case "unmasked":
|
||||
// yes: a model on this computer or the local network gets the
|
||||
// requests as written, unmasked by Settings' redaction (lc on
|
||||
// Discord); only while every address of it is local
|
||||
// yes: the provider gets the requests as written, unmasked by
|
||||
// Settings' redaction (lc, AcMilan on Discord): the user's word
|
||||
// at any address, never for an account or another magpie
|
||||
// (provider.SkipsRedaction)
|
||||
if v != "yes" && v != "no" {
|
||||
return fmt.Errorf("unmasked=yes|no, not %q", v)
|
||||
|
||||
@@ -3,6 +3,7 @@ package gateway
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/gwmw"
|
||||
"github.com/yetone/magpie/internal/masking"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -334,3 +336,39 @@ func TestUnredactedAskedButSentElsewhereMasked(t *testing.T) {
|
||||
t.Fatalf("scanned %d times, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// AcMilan on Discord: "Send requests unmasked" is the user's switch for
|
||||
// each provider. A model at a name of the user's own DNS
|
||||
// (http://llm.corp.lan:8000) gets the request whole with it on, and
|
||||
// masked with it off; nothing is looked up to decide. The name is reached
|
||||
// through a proxy set in Settings, the test's fake, so no lookup reaches
|
||||
// the network.
|
||||
func TestLANNameUnredactedProvider(t *testing.T) {
|
||||
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
|
||||
chat := `{"model":"fake/m1","max_tokens":10,"messages":[{"role":"user","content":"my key is ` + key + `"}]}`
|
||||
for _, on := range []bool{true, false} {
|
||||
f := &fake{ctype: "application/json", reply: `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":1}}`}
|
||||
up := setup(t, provider.Anthropic, f)
|
||||
t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
|
||||
}))
|
||||
p, err := provider.Find("fake")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Unredacted = on
|
||||
p.Anthropic = "http://llm.corp.lan:8000"
|
||||
if err := provider.Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Redact: true, Proxy: up.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, reply := post(t, "/v1/messages", chat); code != 200 || f.calls != 1 {
|
||||
t.Fatalf("on %v: %d %s, the model asked %d times", on, code, reply, f.calls)
|
||||
}
|
||||
if whole := strings.Contains(string(f.got), key); whole != on {
|
||||
t.Fatalf("switch on %v, sent whole %v: %s", on, whole, f.got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3218,6 +3218,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
.editor .bar .danger { margin-left: -7px; }
|
||||
.editor .editor-error { grid-column: 1 / -1; font-size: 12px; line-height: 1.45; color: var(--red); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; }
|
||||
.editor .editor-error.warn { color: var(--amber); }
|
||||
.editor .hint.unmasked-away { color: var(--amber); }
|
||||
/* what a pasted curl command filled in (curlOf), said where an error is */
|
||||
.editor .editor-error.note { color: var(--fg-2); }
|
||||
.busy { opacity: .55; pointer-events: none; }
|
||||
|
||||
+54
-39
@@ -9754,10 +9754,7 @@ function drawEditor(p, presetID) {
|
||||
|
||||
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
|
||||
|
||||
// a relay in front of Anthropic's or OpenAI's API searches the web as
|
||||
// they do, which magpie can't tell from its host (#359): a client's web
|
||||
// search goes to it as sent, rather than through magpie's own. Only its
|
||||
// Anthropic or Responses API can be asked to: a Chat one has no such tool
|
||||
// a relay that searches the web as its vendor does gets a client's search as sent (#359)
|
||||
if (custom) {
|
||||
const [stk, scb] = tick(t("Searches the web by itself"), !!draft.searches);
|
||||
scb.onchange = () => { draft.searches = scb.checked; };
|
||||
@@ -9767,11 +9764,7 @@ function drawEditor(p, presetID) {
|
||||
advIn.append(...row);
|
||||
}
|
||||
|
||||
// which header the key goes in on a third-party Anthropic API: both by
|
||||
// default, one alone for a service that refuses the two together (Aloha
|
||||
// on Discord: "x-api-key 和 Authorization 不可以同时存在"), which magpie
|
||||
// also learns from that refusal. Anthropic's, Bedrock's (its runtime and
|
||||
// its Mantle endpoint) and Azure's own APIs take x-api-key alone already
|
||||
// a third-party Anthropic API's key header: both, or one for a service refusing two (Aloha)
|
||||
const twoKeyHeaders = () => {
|
||||
if (p?.account || vertex) return false;
|
||||
if (p && !custom) return !!p.bothAuth;
|
||||
@@ -9802,25 +9795,27 @@ function drawEditor(p, presetID) {
|
||||
advIn.append(...field(t("User-Agent"), utk, t("For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.")));
|
||||
}
|
||||
|
||||
// a model on this computer or the local network (Ollama, LM Studio, a
|
||||
// vLLM box) may be sent requests unmasked by Settings' redaction (lc on
|
||||
// Discord). Only the user can say it is local all the way: a relay run
|
||||
// locally, or Ollama's cloud models, pass a request on to a vendor
|
||||
// the user's switch at any address (AcMilan), with a caution while on
|
||||
const addressOf = (k) => (draft[k] ?? (isNew && pr ? pr[k] : "")) || "";
|
||||
const onLAN = () => !p?.account && (p?.preset || pr?.id) !== "remote-magpie" && localAddresses(["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf));
|
||||
if (!p?.account) {
|
||||
const unmaskable = () => !p?.account && (p?.preset || pr?.id) !== "remote-magpie";
|
||||
if (unmaskable()) {
|
||||
const [ltk, lcb] = tick(t("Send requests unmasked"), !!draft.unredacted);
|
||||
lcb.onchange = () => { draft.unredacted = lcb.checked; };
|
||||
lcb.onchange = () => { draft.unredacted = lcb.checked; showLocal(); };
|
||||
const row = field(t("Redaction"), ltk, t("For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor."));
|
||||
showLocal = () => { for (const e of row) e.style.display = onLAN() ? "" : "none"; };
|
||||
const away = el("div", "hint unmasked-away");
|
||||
row[1].append(away);
|
||||
showLocal = () => {
|
||||
const urls = ["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf);
|
||||
const host = draft.unredacted ? awayHost(urls) : "";
|
||||
away.textContent = host ? t("{host} isn't on this computer or your local network: turned on, requests go to it unmasked.", { host }) : "";
|
||||
away.hidden = !host;
|
||||
if (draft.unredacted) askLANNames(urls, showLocal);
|
||||
};
|
||||
showLocal();
|
||||
advIn.append(...row);
|
||||
}
|
||||
|
||||
// a provider the user added whose server has a certificate nothing
|
||||
// trusts (a vLLM on the LAN, Ollama behind a self-signed cert, a
|
||||
// company CA, #2383) may be asked without checking it: only its own
|
||||
// https:// hosts, never a preset's or a sign-in's (provider.TakesInsecureTLS)
|
||||
// a user's provider whose certificate nothing trusts (#2383, provider.TakesInsecureTLS)
|
||||
const tlsTakes = () => custom && (!p || !!p.takesInsecureTLS);
|
||||
const onHTTPS = () => ["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf).some((u) => /^\s*https:\/\//i.test(u));
|
||||
if (tlsTakes()) {
|
||||
@@ -10186,7 +10181,7 @@ function drawEditor(p, presetID) {
|
||||
body.searches = !!draft.searches && searchable();
|
||||
body.pinUpstream = !!draft.pinUpstream;
|
||||
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
|
||||
body.unredacted = !!draft.unredacted && onLAN();
|
||||
body.unredacted = !!draft.unredacted && unmaskable();
|
||||
if (tlsTakes()) body.insecureTLS = !!draft.insecureTLS && onHTTPS();
|
||||
if (custom) body.limitRestOff = !!draft.limitRestOff;
|
||||
if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction();
|
||||
@@ -20353,23 +20348,43 @@ function syncWhen(iso) {
|
||||
return new Date().toDateString() === d.toDateString() ? t("at {time}", { time }) : d.toLocaleDateString(intlLang()) + " " + time;
|
||||
}
|
||||
|
||||
// localAddresses: every address given is on this computer or the local
|
||||
// network (localhost, *.local, a loopback or private IP), as
|
||||
// provider.LocalAddresses says, and there is at least one
|
||||
function localAddresses(urls) {
|
||||
const given = urls.map((u) => (u || "").trim()).filter(Boolean);
|
||||
return given.length > 0 && given.every((u) => {
|
||||
let h;
|
||||
try { h = new URL(u).hostname.toLowerCase(); } catch { return false; }
|
||||
if (h.startsWith("[")) h = h.slice(1, -1);
|
||||
if (h === "localhost" || h.endsWith(".local") || h === "::1") return true;
|
||||
const v4 = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
||||
if (v4) {
|
||||
const a = +v4[1], b = +v4[2];
|
||||
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
||||
}
|
||||
return /^f[cd][0-9a-f]{2}:/.test(h);
|
||||
});
|
||||
// awayHost: the first host of urls not local
|
||||
function awayHost(urls) {
|
||||
for (const h of urls.map(urlHost)) if (h && (localIP(h) ?? lanNames.get(h)) === false) return h;
|
||||
return "";
|
||||
}
|
||||
|
||||
function urlHost(u) {
|
||||
try { return new URL((u || "").trim()).hostname.toLowerCase().replace(/^\[|\]$|\.$/g, ""); } catch { return null; }
|
||||
}
|
||||
|
||||
// localIP: null for a name
|
||||
function localIP(h) {
|
||||
if (h === "localhost" || h.endsWith(".local") || h === "::1") return true;
|
||||
const v4 = h.match(/^(\d+)\.(\d+)\.\d+\.\d+$/);
|
||||
if (v4) {
|
||||
const a = +v4[1], b = +v4[2];
|
||||
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254);
|
||||
}
|
||||
return h.includes(":") ? /^(f[cd]|fe[89ab])[0-9a-f]{2}:/.test(h) : null;
|
||||
}
|
||||
|
||||
// lanNames: whether a name of the user's DNS resolves only locally (null: asking)
|
||||
const lanNames = new Map();
|
||||
let lanAskTimer = 0;
|
||||
|
||||
function askLANNames(urls, then) {
|
||||
clearTimeout(lanAskTimer);
|
||||
const hosts = [...new Set(urls.map(urlHost))].filter((h) => h && localIP(h) === null && !lanNames.has(h));
|
||||
if (!hosts.length) return;
|
||||
lanAskTimer = setTimeout(async () => {
|
||||
hosts.forEach((h) => lanNames.set(h, null));
|
||||
try {
|
||||
const r = await api("local-hosts", { hosts });
|
||||
hosts.forEach((h) => lanNames.set(h, r?.local?.[h] === true));
|
||||
then();
|
||||
} catch { hosts.forEach((h) => lanNames.delete(h)); }
|
||||
}, 300);
|
||||
}
|
||||
|
||||
function tick(label, on) {
|
||||
|
||||
@@ -3670,6 +3670,7 @@ const I18N = {
|
||||
"Codex compacts on this provider": "Codex 在此服务商上原生压缩",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的压缩请求原样交给此服务商,它加密的摘要原样还给 Codex。关闭时由 magpie 写摘要。这样压缩过的对话只能在此服务商和账号上继续:换到别处会报错说明,绝不丢掉上下文发出。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "给运行在这台电脑或局域网里的模型:密钥、个人信息和你设的脱敏词按原样发给它。如果它是本地的中转或代理、会把请求转给供应商,请保持关闭。",
|
||||
"{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} 不在这台电脑或局域网里:打开后,请求会不脱敏地发给它。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "发送 Agent 自己的 User-Agent",
|
||||
"For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "给只允许指定编程 Agent 使用的套餐:每个请求带上 Agent 自己发来的 User-Agent(pi、OpenCode、Claude Code…),而不是 magpie 的。magpie 自己发出的请求,以及 Agent 没带 User-Agent 的请求,仍以 magpie 的身份发送。上面请求头里设置的 User-Agent 始终优先。",
|
||||
@@ -7853,6 +7854,7 @@ const I18N = {
|
||||
"Codex compacts on this provider": "Codex 在此服務商上原生壓縮",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的壓縮請求原樣交給此服務商,它加密的摘要原樣還給 Codex。關閉時由 magpie 寫摘要。這樣壓縮過的對話只能在此服務商和帳號上繼續:換到別處會報錯說明,絕不丟掉上下文送出。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "給執行在這臺電腦或區域網裡的模型:金鑰、個人資訊和你設的脫敏詞按原樣發給它。如果它是本地的中轉或代理、會把請求轉給供應商,請保持關閉。",
|
||||
"{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} 不在這臺電腦或區域網裡:開啟後,請求會不脫敏地發給它。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "傳送 Agent 自己的 User-Agent",
|
||||
"For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "給只允許指定程式設計 Agent 使用的方案:每個請求帶上 Agent 自己送來的 User-Agent(pi、OpenCode、Claude Code…),而不是 magpie 的。magpie 自己發出的請求,以及 Agent 沒帶 User-Agent 的請求,仍以 magpie 的身分傳送。上面請求頭裡設定的 User-Agent 永遠優先。",
|
||||
@@ -12053,6 +12055,7 @@ const I18N = {
|
||||
"Codex compacts on this provider": "Codex のコンパクションをこのプロバイダーで行う",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex のコンパクション要求をそのままこのプロバイダーに送り、暗号化された要約をそのまま Codex に返します。オフのときは magpie が要約を書きます。こうしてコンパクションした会話は、このプロバイダーとアカウントでのみ続けられます。他へはエラーで断り、コンテキストを落として送ることはしません。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "このコンピューターかローカルネットワークで動くモデル用:シークレット、個人情報、マスクする語はそのまま送られます。リクエストをベンダーに転送するローカルのリレーやプロキシではオフのままにしてください。",
|
||||
"{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} はこのコンピューターにもローカルネットワークにもありません:オンにすると、リクエストはマスクされずに送られます。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "エージェント自身の User-Agent を送る",
|
||||
"For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "指定したコーディングエージェントだけが使えるプラン向け:各リクエストは magpie のものではなく、エージェントが送ってきた User-Agent(pi、OpenCode、Claude Code…)で送られます。magpie 自身のリクエストと、エージェントが User-Agent を付けなかったリクエストは、引き続き magpie として送られます。上のヘッダーで設定した User-Agent が常に優先されます。",
|
||||
@@ -16267,6 +16270,7 @@ const I18N = {
|
||||
"Codex compacts on this provider": "Codex kompaktiert bei diesem Anbieter",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex’ Kompaktierung geht so an diesen Anbieter, wie Codex sie sendet, und die versiegelte Zusammenfassung kommt unverändert zu Codex zurück. Aus: magpie schreibt die Zusammenfassung. Ein so kompaktiertes Gespräch geht nur bei diesem Anbieter und Konto weiter: ein anderer wird mit einem Fehler abgelehnt, nie ohne den Kontext angefragt.",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "Für ein Modell auf diesem Computer oder in Ihrem lokalen Netzwerk: Geheimnisse, persönliche Daten und Ihre maskierten Wörter gehen unverändert an es. Lassen Sie es aus für ein lokales Relay oder einen Proxy, der Anfragen an einen Anbieter weiterreicht.",
|
||||
"{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} ist weder auf diesem Computer noch in Ihrem lokalen Netzwerk: Eingeschaltet gehen Anfragen unmaskiert an ihn.",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "Den eigenen User-Agent des Agenten senden",
|
||||
"For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "Für einen Tarif, der nur die genannten Coding-Agenten zulässt: Jede Anfrage geht mit dem User-Agent, den der Agent gesendet hat (pi, OpenCode, Claude Code…), nicht mit dem von magpie. Anfragen, die magpie selbst stellt, und solche, die der Agent ohne einen gesendet hat, gehen weiter als magpie. Ein oben unter Header gesetzter User-Agent hat immer Vorrang.",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// localHostsRoutes: POST /api/local-hosts {"hosts":[...]} answers
|
||||
// {"local":{host:bool}}, whether each host is on this computer or the
|
||||
// local network (provider.LocalHost). The provider editor shows a caution
|
||||
// under "Send requests unmasked" for a provider with an address that
|
||||
// isn't; a page can't resolve a name of the user's own DNS
|
||||
// (http://llm.corp.lan:8000, AcMilan on Discord), so it asks here. It
|
||||
// only words the editor: the switch is the user's, and no request asks.
|
||||
func localHostsRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/local-hosts", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Hosts []string `json:"hosts"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 16<<10)).Decode(&in); err != nil {
|
||||
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(in.Hosts) > 8 { // a provider has five addresses
|
||||
in.Hosts = in.Hosts[:8]
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
out := map[string]bool{}
|
||||
for _, h := range in.Hosts {
|
||||
h = strings.ToLower(strings.TrimSpace(h))
|
||||
if h == "" || len(h) > 253 {
|
||||
continue
|
||||
}
|
||||
wg.Go(func() {
|
||||
local := provider.LocalHost(strings.Trim(h, "[]"))
|
||||
mu.Lock()
|
||||
out[h] = local
|
||||
mu.Unlock()
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
writeJSON(rw, map[string]any{"local": out})
|
||||
})
|
||||
}
|
||||
@@ -1066,6 +1066,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
contextRoutesAPI(mux)
|
||||
tuneRoutes(mux)
|
||||
groupRoutes(mux)
|
||||
localHostsRoutes(mux)
|
||||
// how each key's or account's requests stand under its limit on
|
||||
// requests at once (#892), read every two seconds while a provider's
|
||||
// rows are shown; empty when the gateway runs elsewhere
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A model on this computer or the local network (lc on Discord): the
|
||||
// provider editor's Redaction row, "Send requests unmasked", is there while
|
||||
// every address of the provider is local (localhost, a private IP), opens as
|
||||
// it was saved, and Save posts it. A relay at a vendor's address has no such
|
||||
// row, and one whose address is changed to a vendor's is saved masked. A
|
||||
// signed-in account has none. In English and Chinese, wide and narrow.
|
||||
// "Send requests unmasked" (lc on Discord) is the user's switch for each
|
||||
// provider they added (AcMilan on Discord): the editor's Redaction row is
|
||||
// there whatever the address, opens as it was saved, and Save posts it.
|
||||
// Turned on, a caution under it names an address not on this computer or
|
||||
// the local network (a relay, a vendor, a name magpie says resolves elsewhere:
|
||||
// /api/local-hosts); a local one (localhost, a private IP, a name of the
|
||||
// user's own DNS resolving only to the local network) has none. A
|
||||
// name is asked about only once the switch is on, so an editor merely
|
||||
// opened asks nothing. A signed-in account has no row. In English and Chinese, wide and narrow.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -27,6 +30,9 @@ const base = {
|
||||
const local = { ...base, id: "local", name: "Local Box", chat: "http://localhost:11434/v1" };
|
||||
const lan = { ...base, id: "lan", name: "LAN Box", chat: "http://192.168.1.20:8000/v1", unredacted: true };
|
||||
const relay = { ...base, id: "relay", name: "Relay", chat: "https://relay.example.com/v1" };
|
||||
const named = { ...base, id: "named", name: "Corp LLM", chat: "http://llm.corp.lan:8000/v1" };
|
||||
// what magpie says each name resolves to: only the local network, or not
|
||||
const lanHosts = { "llm.corp.lan": true, "relay.example.com": false, "api.vendor.example": false };
|
||||
const codex = {
|
||||
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
@@ -34,8 +40,8 @@ const codex = {
|
||||
proxy: "",
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = { providers: [local, lan, relay, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
function serve(lang, posts, asked) {
|
||||
const providers = { providers: [local, lan, relay, named, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
@@ -45,6 +51,11 @@ function serve(lang, posts) {
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/local-hosts") {
|
||||
const { hosts } = route.request().postDataJSON();
|
||||
asked.push(...hosts);
|
||||
return json({ local: Object.fromEntries(hosts.map((h) => [h, lanHosts[h] === true])) });
|
||||
}
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
|
||||
return json(providers);
|
||||
@@ -57,8 +68,8 @@ function serve(lang, posts) {
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { tick: "Send requests unmasked", save: "Save" },
|
||||
zh: { tick: "请求不脱敏", save: "保存" },
|
||||
en: { tick: "Send requests unmasked", save: "Save", away: (h) => `${h} isn't on this computer or your local network` },
|
||||
zh: { tick: "请求不脱敏", save: "保存", away: (h) => `${h} 不在这台电脑或局域网里` },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -79,15 +90,28 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
const asked = [];
|
||||
await page.route("**/*", serve(lang, posts, asked));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: name }).click();
|
||||
await unfold(page);
|
||||
await page.locator(".editor .bar").waitFor();
|
||||
return { page, errors, posts };
|
||||
return { page, errors, posts, asked };
|
||||
};
|
||||
const row = (page) => page.locator(".editor label.tick", { hasText: w.tick });
|
||||
const box = (page) => row(page).locator("input");
|
||||
const caution = (page) => page.locator(".editor .hint.unmasked-away");
|
||||
// the caution once it has settled: a name is asked about a moment
|
||||
// after it is typed
|
||||
const cautionSays = async (page, text) => {
|
||||
let shown = "";
|
||||
for (let i = 0; i < 100; i++) {
|
||||
shown = (await caution(page).isVisible()) ? await caution(page).textContent() : "";
|
||||
if (text ? shown.includes(text) : shown === "") return;
|
||||
await page.waitForTimeout(20);
|
||||
}
|
||||
assert.fail(`the caution says ${JSON.stringify(shown)}, want ${JSON.stringify(text)}`);
|
||||
};
|
||||
const save = async (page, posts) => {
|
||||
const n = posts.length;
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
@@ -98,6 +122,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
test(`${engine} ${lang} ${width}: a model on localhost is set to go unmasked, and saved so`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Local Box");
|
||||
assert.equal(await row(page).isVisible(), true);
|
||||
await cautionSays(page, "");
|
||||
assert.equal(await box(page).isChecked(), false, "opens masked");
|
||||
const r = await row(page).boundingBox();
|
||||
assert.ok(r.width > 60 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`);
|
||||
@@ -110,6 +135,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const missing = await page.evaluate(() => [
|
||||
"Redaction", "Send requests unmasked",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.",
|
||||
"{host} isn't on this computer or your local network: turned on, requests go to it unmasked.",
|
||||
].filter((k) => !I18N.zh[k]));
|
||||
assert.deepEqual(missing, [], "every string has its Chinese");
|
||||
assert.deepEqual(errors, []);
|
||||
@@ -126,19 +152,62 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a relay has no row, and a local one moved to a vendor's address is saved masked`, async (t) => {
|
||||
{
|
||||
const { page, errors } = await open(t, "Relay");
|
||||
assert.equal(await row(page).isVisible(), false);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
test(`${engine} ${lang} ${width}: a relay has the row with a caution naming it, and turned on is saved so`, async (t) => {
|
||||
const { page, errors, posts, asked } = await open(t, "Relay");
|
||||
assert.equal(await row(page).isVisible(), true);
|
||||
await page.waitForTimeout(400);
|
||||
assert.deepEqual(asked, [], "nothing is asked while the switch is off");
|
||||
await cautionSays(page, "");
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
await box(page).check();
|
||||
await cautionSays(page, w.away("relay.example.com"));
|
||||
await caution(page).scrollIntoViewIfNeeded();
|
||||
const c = await caution(page).boundingBox();
|
||||
assert.ok(c.x >= 0 && c.x + c.width <= width, `the caution fits: ${JSON.stringify(c)}`);
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.id, "relay");
|
||||
assert.equal(saved.body.unredacted, true, "the user's word, whatever the address");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a local one moved to a vendor's address keeps the switch, now with a caution`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Local Box");
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
await box(page).check();
|
||||
await page.locator(".editor input[type=url]").first().fill("https://api.vendor.example/v1");
|
||||
assert.equal(await row(page).isVisible(), false, "the row goes with the local address");
|
||||
await cautionSays(page, w.away("api.vendor.example"));
|
||||
assert.equal(await box(page).isChecked(), true);
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.unredacted, false);
|
||||
assert.equal(saved.body.unredacted, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: one at a LAN name magpie finds local has no caution, and is saved unmasked`, async (t) => {
|
||||
const { page, errors, posts, asked } = await open(t, "Corp LLM");
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
await box(page).check();
|
||||
for (let i = 0; i < 100 && !asked.length; i++) await page.waitForTimeout(20);
|
||||
assert.deepEqual(asked, ["llm.corp.lan"], "the name is asked about once");
|
||||
await page.waitForTimeout(100);
|
||||
await cautionSays(page, "");
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.id, "named");
|
||||
assert.equal(saved.body.unredacted, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a name typed in loses the caution once magpie finds it local, and one it doesn't gets it`, async (t) => {
|
||||
const { page, errors, asked } = await open(t, "Relay");
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
await box(page).check();
|
||||
await cautionSays(page, w.away("relay.example.com"));
|
||||
await page.locator(".editor input[type=url]").first().fill("http://llm.corp.lan:8000/v1");
|
||||
for (let i = 0; i < 100 && !asked.includes("llm.corp.lan"); i++) await page.waitForTimeout(20);
|
||||
assert.ok(asked.includes("llm.corp.lan"), "the name typed is asked about");
|
||||
await page.waitForTimeout(100);
|
||||
await cautionSays(page, "");
|
||||
await page.locator(".editor input[type=url]").first().fill("https://api.vendor.example/v1");
|
||||
await cautionSays(page, w.away("api.vendor.example"));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -42,3 +47,32 @@ func TestProviderSaveKeepsUnredacted(t *testing.T) {
|
||||
t.Fatalf("saved masked again: %+v %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
// AcMilan on Discord: the editor can't resolve a name of the user's own
|
||||
// DNS, so it asks /api/local-hosts whether to caution under "Send
|
||||
// requests unmasked": a name resolving only to private addresses is local, one
|
||||
// resolving to a public address or not at all isn't, and an IP or
|
||||
// localhost is judged by what it is.
|
||||
func TestLocalHostsAPI(t *testing.T) {
|
||||
t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
switch host {
|
||||
case "llm.corp.lan":
|
||||
return []net.IPAddr{{IP: net.ParseIP("192.168.1.20")}}, nil
|
||||
case "api.vendor.example":
|
||||
return []net.IPAddr{{IP: net.ParseIP("203.0.113.7")}}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
|
||||
}))
|
||||
mux := http.NewServeMux()
|
||||
localHostsRoutes(mux)
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/local-hosts", strings.NewReader(`{"hosts":["LLM.corp.lan","api.vendor.example","gone.lan","localhost","[::1]","8.8.8.8","10.1.2.3"]}`)))
|
||||
var got struct{ Local map[string]bool }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 200 {
|
||||
t.Fatalf("%d %s %v", w.Code, w.Body, err)
|
||||
}
|
||||
want := map[string]bool{"llm.corp.lan": true, "api.vendor.example": false, "gone.lan": false, "localhost": true, "[::1]": true, "8.8.8.8": false, "10.1.2.3": true}
|
||||
if !maps.Equal(got.Local, want) {
|
||||
t.Fatalf("%v, want %v", got.Local, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LocalName says whether a name of the user's own DNS
|
||||
// (http://llm.corp.lan:8000, AcMilan on Discord) resolves only to this
|
||||
// computer or the local network. The provider editor asks it
|
||||
// (/api/local-hosts) to tell whether "Send requests unmasked" needs its
|
||||
// caution; no request is routed or dialled by it.
|
||||
|
||||
// localKeep is how long what LocalName found for a name is kept.
|
||||
const localKeep = time.Minute
|
||||
|
||||
var localCache = struct {
|
||||
sync.Mutex
|
||||
m map[string]lanSeen
|
||||
}{m: map[string]lanSeen{}}
|
||||
|
||||
// LocalName reports whether host, a name, resolves (in lanWait) to at
|
||||
// least one address and every address it resolves to is on this computer
|
||||
// or the local network (LocalIP). A name that doesn't resolve, or doesn't
|
||||
// in time, is not: what can't be read is unknown, and unknown is masked.
|
||||
func LocalName(host string) bool {
|
||||
host = strings.ToLower(strings.TrimSuffix(host, "."))
|
||||
if host == "" || net.ParseIP(host) != nil {
|
||||
return false
|
||||
}
|
||||
localCache.Lock()
|
||||
s, ok := localCache.m[host]
|
||||
localCache.Unlock()
|
||||
if ok && time.Since(s.at) < localKeep {
|
||||
return s.lan
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), lanWait)
|
||||
addrs, err := lanLookup(ctx, host)
|
||||
cancel()
|
||||
local := err == nil && allLocal(addrs)
|
||||
localCache.Lock()
|
||||
if len(localCache.m) >= 256 {
|
||||
clear(localCache.m)
|
||||
}
|
||||
localCache.m[host] = lanSeen{lan: local, at: time.Now()}
|
||||
localCache.Unlock()
|
||||
return local
|
||||
}
|
||||
|
||||
// LocalIP says ip is on this computer or the local network: a loopback,
|
||||
// private (10/8, 172.16/12, 192.168/16, fc00::/7) or link-local address.
|
||||
// Carrier-grade NAT (100.64/10) is not: it is a Tailscale address, but
|
||||
// also an ISP's.
|
||||
func LocalIP(ip net.IP) bool {
|
||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
|
||||
func allLocal(addrs []net.IPAddr) bool {
|
||||
for _, a := range addrs {
|
||||
if !LocalIP(a.IP) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(addrs) > 0
|
||||
}
|
||||
|
||||
// SetLookup has names resolved by f, for a test that must not reach the
|
||||
// network, and forgets what earlier lookups found; restore puts the
|
||||
// system's resolver back.
|
||||
func SetLookup(f func(ctx context.Context, host string) ([]net.IPAddr, error)) (restore func()) {
|
||||
old := lanLookup
|
||||
lanLookup = f
|
||||
forget := func() {
|
||||
lanCache.Lock()
|
||||
clear(lanCache.m)
|
||||
lanCache.Unlock()
|
||||
localCache.Lock()
|
||||
clear(localCache.m)
|
||||
localCache.Unlock()
|
||||
}
|
||||
forget()
|
||||
return func() { lanLookup = old; forget() }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// lookups answers names from m, several addresses each, and counts the
|
||||
// lookups made.
|
||||
func lookups(t *testing.T, m map[string][]string) *atomic.Int32 {
|
||||
t.Helper()
|
||||
n := new(atomic.Int32)
|
||||
t.Cleanup(SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
n.Add(1)
|
||||
ips, ok := m[host]
|
||||
if !ok {
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
|
||||
}
|
||||
var out []net.IPAddr
|
||||
for _, s := range ips {
|
||||
out = append(out, net.IPAddr{IP: net.ParseIP(s)})
|
||||
}
|
||||
return out, nil
|
||||
}))
|
||||
return n
|
||||
}
|
||||
|
||||
// AcMilan on Discord: a name of the user's own DNS counts as local when
|
||||
// every address it resolves to is loopback, private or link-local; one
|
||||
// resolving to a public address, to a public and a private one, or not at
|
||||
// all, is not.
|
||||
func TestLocalName(t *testing.T) {
|
||||
lookups(t, map[string][]string{
|
||||
"llm.corp.lan": {"192.168.1.20"},
|
||||
"gpu.home.arpa": {"10.0.0.7", "fd00::7"},
|
||||
"loop.test": {"127.0.0.1"},
|
||||
"linklocal.lan": {"169.254.10.2"},
|
||||
"public.example": {"203.0.113.7"},
|
||||
"mixed.example": {"10.0.0.2", "203.0.113.7"},
|
||||
"cgnat.example": {"100.101.102.103"},
|
||||
"nothing.example": {},
|
||||
})
|
||||
for host, want := range map[string]bool{
|
||||
"llm.corp.lan": true, "LLM.corp.lan.": true, "gpu.home.arpa": true, "loop.test": true, "linklocal.lan": true,
|
||||
"public.example": false, "mixed.example": false, "cgnat.example": false, "nothing.example": false,
|
||||
"gone.lan": false, "192.168.1.20": false, "": false,
|
||||
} {
|
||||
if got := LocalName(host); got != want {
|
||||
t.Errorf("%q: %v, want %v", host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A lookup that doesn't answer in lanWait is unknown, so not local.
|
||||
func TestLocalNameSlowLookupIsNot(t *testing.T) {
|
||||
t.Cleanup(SetLookup(func(ctx context.Context, host string) ([]net.IPAddr, error) {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}))
|
||||
if LocalName("slow.lan") {
|
||||
t.Fatal("a lookup that timed out counted as local")
|
||||
}
|
||||
}
|
||||
@@ -327,12 +327,13 @@ type Provider struct {
|
||||
// Azure's own APIs, which take x-api-key alone, ignore it.
|
||||
AuthHeader string `json:"authHeader,omitempty"`
|
||||
|
||||
// Unredacted has requests to a provider on this machine or the local
|
||||
// network (Ollama, LM Studio, a vLLM box) go as the agent wrote them,
|
||||
// unmasked by Settings' redaction, which keeps secrets from vendors
|
||||
// (lc on Discord). It is the user's word, not the address's: a relay
|
||||
// run locally, or Ollama's cloud models, pass a request on to a vendor.
|
||||
// See SkipsRedaction.
|
||||
// Unredacted has requests to a provider go as the agent wrote them,
|
||||
// unmasked by Settings' redaction, which keeps secrets from vendors:
|
||||
// for a model on this machine or the local network (Ollama, LM Studio,
|
||||
// a vLLM box; lc on Discord). It is the user's word, not the
|
||||
// address's (AcMilan on Discord): the editor cautions when an address
|
||||
// isn't local, and a relay run locally, or Ollama's cloud models, pass
|
||||
// a request on to a vendor whatever the address. See SkipsRedaction.
|
||||
Unredacted bool `json:"unredacted,omitempty"`
|
||||
|
||||
// InsecureTLS has magpie take the certificate of the provider's own
|
||||
|
||||
@@ -1,33 +1,41 @@
|
||||
package provider
|
||||
|
||||
import "net/url"
|
||||
import (
|
||||
"net"
|
||||
|
||||
// SkipsRedaction says requests to p go unmasked: the user set Unredacted,
|
||||
// and every address p has is on this machine or the local network. One
|
||||
// edited to a vendor's afterwards is masked again. A signed-in account, a
|
||||
// plugin's provider and another magpie are always masked: each reaches a
|
||||
// vendor.
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
)
|
||||
|
||||
// SkipsRedaction says requests to p go unmasked: the user set Unredacted
|
||||
// ("Send requests unmasked") and p has an address. It is the user's word
|
||||
// whatever the address (AcMilan on Discord: the user decides for each
|
||||
// provider); the editor cautions when an address isn't on this machine or
|
||||
// the local network (LocalHost), and nothing here looks one up. A
|
||||
// signed-in account, a plugin's provider and another magpie are always
|
||||
// masked: each reaches a vendor.
|
||||
func (p Provider) SkipsRedaction() bool {
|
||||
if !p.Unredacted || p.Account != nil || p.IsRemoteMagpie() {
|
||||
return false
|
||||
}
|
||||
return LocalAddresses(p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Decide)
|
||||
for _, b := range []string{p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Decide} {
|
||||
if b != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LocalAddresses says every non-empty base URL among bases is on this
|
||||
// machine or the local network (localhost, *.local, a loopback or private
|
||||
// IP), and there is at least one.
|
||||
func LocalAddresses(bases ...string) bool {
|
||||
n := 0
|
||||
for _, b := range bases {
|
||||
if b == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(b)
|
||||
if err != nil || u.Host == "" || !local(u.Hostname()) {
|
||||
return false
|
||||
}
|
||||
n++
|
||||
// LocalHost says host is on this machine or the local network: localhost,
|
||||
// a .local name, a loopback, private or link-local IP, or a name every
|
||||
// address of which is one (netproxy.LocalName, looked up now and kept a
|
||||
// minute; one that doesn't resolve isn't). Only the editor's caution asks
|
||||
// it (/api/local-hosts), never a request.
|
||||
func LocalHost(host string) bool {
|
||||
if local(host) {
|
||||
return true
|
||||
}
|
||||
return n > 0
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return netproxy.LocalIP(ip)
|
||||
}
|
||||
return netproxy.LocalName(host)
|
||||
}
|
||||
|
||||
@@ -1,25 +1,36 @@
|
||||
package provider
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
// Only a provider the user set to go unmasked whose every address is on
|
||||
// this machine or the local network skips redaction; one at a vendor's
|
||||
// address, a signed-in account or another magpie never does.
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
)
|
||||
|
||||
// "Send requests unmasked" is the user's switch for each provider
|
||||
// (AcMilan on Discord): set, a provider goes unmasked at whatever address,
|
||||
// a name of the user's own DNS or a vendor's; unset, it is masked. A
|
||||
// signed-in account or another magpie never goes unmasked. Nothing is
|
||||
// looked up to decide: the lookup fails the test if it is.
|
||||
func TestSkipsRedaction(t *testing.T) {
|
||||
t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
t.Errorf("SkipsRedaction looked up %s", host)
|
||||
return nil, &net.DNSError{Err: "no lookups here", Name: host}
|
||||
}))
|
||||
cases := []struct {
|
||||
name string
|
||||
p Provider
|
||||
want bool
|
||||
}{
|
||||
{"ollama", Provider{Unredacted: true, Chat: "http://localhost:11434/v1", Anthropic: "http://localhost:11434"}, true},
|
||||
{"loopback ip", Provider{Unredacted: true, Chat: "http://127.0.0.1:1234/v1"}, true},
|
||||
{"ipv6 loopback", Provider{Unredacted: true, Chat: "http://[::1]:8000/v1"}, true},
|
||||
{"lan", Provider{Unredacted: true, Chat: "http://192.168.1.20:8000/v1"}, true},
|
||||
{"mdns", Provider{Unredacted: true, Responses: "http://gpu-box.local:8000/v1"}, true},
|
||||
{"a lan name", Provider{Unredacted: true, Chat: "http://llm.corp.lan:8000/v1"}, true},
|
||||
{"a lan name, off", Provider{Chat: "http://llm.corp.lan:8000/v1"}, false},
|
||||
{"a vendor, set by the user", Provider{Unredacted: true, Chat: "https://api.deepseek.com/v1"}, true},
|
||||
{"a public ip, set by the user", Provider{Unredacted: true, Chat: "http://8.8.8.8/v1"}, true},
|
||||
{"through its own proxy", Provider{Unredacted: true, Chat: "http://llm.corp.lan:8000/v1", Proxy: "socks5://127.0.0.1:1080"}, true},
|
||||
{"not set", Provider{Chat: "http://localhost:11434/v1"}, false},
|
||||
{"a vendor", Provider{Unredacted: true, Chat: "https://api.deepseek.com/v1"}, false},
|
||||
{"one address a vendor's", Provider{Unredacted: true, Chat: "http://localhost:11434/v1", Anthropic: "https://ollama.com"}, false},
|
||||
{"a public ip", Provider{Unredacted: true, Chat: "http://8.8.8.8/v1"}, false},
|
||||
{"no address", Provider{Unredacted: true}, false},
|
||||
{"an account", Provider{Unredacted: true, Chat: "http://localhost:1/v1", Account: &Account{Agent: "codex"}}, false},
|
||||
{"another magpie", Provider{Unredacted: true, Preset: RemoteMagpiePreset, Anthropic: "http://192.168.1.5:3425"}, false},
|
||||
@@ -30,3 +41,42 @@ func TestSkipsRedaction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LocalHost, which decides only whether the editor cautions, takes
|
||||
// localhost, .local, loopback, private and link-local IPs, and a name
|
||||
// that resolves only to those; a public name or IP, one resolving to a
|
||||
// public address among private ones, or one that doesn't resolve, isn't.
|
||||
func TestLocalHost(t *testing.T) {
|
||||
fakeDNS(t, map[string][]string{
|
||||
"llm.corp.lan": {"192.168.1.20"},
|
||||
"gpu.home.arpa": {"10.0.0.7", "fd00::7"},
|
||||
"public.example": {"203.0.113.7"},
|
||||
"mixed.example": {"10.0.0.2", "203.0.113.7"},
|
||||
})
|
||||
for host, want := range map[string]bool{
|
||||
"localhost": true, "gpu-box.local": true, "127.0.0.1": true, "::1": true, "192.168.1.20": true, "169.254.10.2": true,
|
||||
"llm.corp.lan": true, "gpu.home.arpa": true,
|
||||
"public.example": false, "mixed.example": false, "gone.lan": false, "8.8.8.8": false,
|
||||
} {
|
||||
if got := LocalHost(host); got != want {
|
||||
t.Errorf("%s: %v, want %v", host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeDNS has names resolve to m's addresses and no other name resolve,
|
||||
// so no test looks a name up on the network.
|
||||
func fakeDNS(t *testing.T, m map[string][]string) {
|
||||
t.Helper()
|
||||
t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
ips, ok := m[host]
|
||||
if !ok {
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
|
||||
}
|
||||
var out []net.IPAddr
|
||||
for _, s := range ips {
|
||||
out = append(out, net.IPAddr{IP: net.ParseIP(s)})
|
||||
}
|
||||
return out, nil
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user