diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index aad14c5af..280bb7d63 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -170,6 +170,10 @@ magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rat A model's `capabilities.output` says what it gives. The host passes on the kinds marked `true` (`kinds` in [`host.js`](../../internal/plugin/host.js), `plugin.Model.Outputs`) and whether the object said yes or no to any kind at all (`kindsSaid`, `plugin.Model.OutputsSaid`), so an embedding's `{"text": false}` is a model said to give nothing, not one said nothing of. `pluginCatalog` leaves out a model whose outputs were said and name no text, image or video (`pluginTalks` in [`plugins.go`](../../internal/provider/plugins.go)): an embedding, a TTS that gives audio alone. Every chat list builds on that list (`/v1/models`, the agents' `provider.Catalog`, `Available` and the editor's chips, routing), as the catalog's own lists leave such models out (`textModel`), #3279. A model whose plugin says nothing of its outputs is kept, whatever its id; an image or video model alone is kept where it is until #2792 places it. Tests: `TestPluginModelGivingNoTextLeavesTheChatLists` (gateway, a real host), `TestPluginModelSayingNoTextLeavesTheChatList`, `TestPluginAccountListLeavesTheSpeechlessOut`. +## The npm registry plugins come from + +Plugins are installed from, and magpie's own npm questions (a package's newest version for the market, *Update* and the hourly check, its README, the search) are asked of, one registry ([`registry.go`](../../internal/plugin/registry.go), timwangdev on X). `Registry()` takes the first of: the one set in magpie (`npmRegistry` in settings.json, *npm registry* on the Plugins page's Discover tab or `magpie plugin registry `); `BUN_CONFIG_REGISTRY`, `NPM_CONFIG_REGISTRY` or `npm_config_registry` in magpie's environment, then in the login shell's (only the cached probe, `proc.LoginEnvKnown`, so asking never waits on a shell); `install.registry` in the plugins folder's or the user's `.bunfig.toml`; `registry=` in the plugins folder's or the user's `.npmrc`; npmmirror when the 「国内镜像」 switch is on; npm's own. The switch never comes before a registry the user named. Only an http(s) address with a host, no user info, query or fragment is taken (`CleanRegistry`); anything else is refused and not saved, and a bad value written into settings.json by hand is passed over. bun reads the environment, bunfig and `.npmrc` itself, so `registryEnv` tells it the registry only where it wouldn't find it: magpie's setting (over the environment's), the login shell's, the switch's mirror. Lookups go to npm's own through the mirror logic as before when the registry is npm's or the switch's; otherwise `fetchRegistry` asks the user's registry, a package with an `@scope:registry=` of its own that scope's, with the `//host/path/:_authToken=` the `.npmrc` keeps for the longest matching prefix (`${VAR}` expanded) and no other host's; a redirect to another host drops it. The token is never logged or shown. npm's download counts are still npm's. Not read: bunfig's `[install.scopes]` for magpie's own lookups (bun reads them for installs), `.npmrc`'s `_auth` and username/password, `NPM_CONFIG_USERCONFIG` and npm's global npmrc. `/api/plugins` says which registry is in use and where it came from (`registry`). `TestRegistryPrecedence`, `TestSetRegistryRefusesWhatIsntOne`, `TestBunTakesTheUsersRegistry` and `TestLookupsAskTheUsersRegistry` in [`registry_test.go`](../../internal/plugin/registry_test.go) and `plugin-registry.test.cjs` cover these. The row is drawn by `registry.js`, which `plugins.js` imports when Discover draws it, so it weighs nothing on the core. + ## A GitHub listing's licence A repository tagged `magpie-plugin` shows the licence GitHub's search reads from its `LICENSE` file. GitHub gives `NOASSERTION` for a file it can't match to one (MIT's text with a line of credit added) and nothing for none, and magpie drops `NOASSERTION`, so such a card had no licence while the same package on npm shows its `package.json` `license`. `readTagged` in [`github.go`](../../internal/plugin/github.go) now keeps `package.json`'s `license` (a string) as `PkgLicense`, and `License` falls back to it, on a fresh read and on one kept across searches (`fresh`) ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). `TestTaggedRepos` covers both cases and the one with neither. diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index b60114fde..d1819f4cf 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -33,6 +33,7 @@ const pluginUsage = `usage: magpie plugin [list] [--json] magpie plugin move|migrate run a built-in subscription's accounts on its community plugin magpie plugin builtin [on|off ] list magpie's built-in plugins (Sessions, Library, routing groups…), or turn one on or off magpie plugin preset essentials|all start the built-in plugins from the Essentials preset, or from all of them + magpie plugin registry [ | default] show the npm registry plugins are installed from and npm is asked of, and where it comes from; or set one (an http:// or https:// address) before your .npmrc's, .bunfig.toml's and the 国内镜像 switch's, default to drop it magpie plugin dump [--json] what plugins.yml comes to: each built-in plugin, its config, and the layer each value is from` // pluginCmd: `magpie plugin …` — OpenCode's provider plugins and pi's @@ -177,6 +178,24 @@ func pluginCmd(args []string) error { } fmt.Println(green.Render("✓"), "built-in plugins start from", rest[0]) return builtinCmd(nil) + case "registry": + if len(rest) > 1 { + return errors.New(pluginUsage) + } + if len(rest) == 1 && strings.HasPrefix(rest[0], "-") { + fmt.Println(pluginUsage) + return nil + } + r := plugin.Registry() + if len(rest) == 1 { + var err error + if r, err = plugin.SetRegistry(rest[0]); err != nil { + return err + } + fmt.Print(green.Render("✓"), " ") + } + fmt.Println(r.URL, muted.Render("("+registryFrom(r)+")")) + return nil case "dump": return dumpPlugins(len(rest) > 0 && rest[0] == "--json") case "help", "-h", "--help": @@ -709,3 +728,20 @@ func sayAgentBack(a *agent.Agent) { } fmt.Println(faint.Render(" " + a.Name + " is disconnected from magpie, back to what it had before; with the plugin back, connecting it (its switch on the Agents page) puts back the model it was on")) } + +// registryFrom says where the npm registry in use came from. +func registryFrom(r plugin.RegistryInUse) string { + switch r.From { + case plugin.FromMagpie: + return "set in magpie; magpie plugin registry default drops it" + case plugin.FromEnv: + return "from " + r.Var + case plugin.FromShell: + return "from your shell's " + r.Var + case plugin.FromBunfig, plugin.FromNPMRC: + return "from " + r.Path + case plugin.FromChina: + return "the 国内镜像 switch on the Plugins page" + } + return "npm's own" +} diff --git a/internal/gui/api.go b/internal/gui/api.go index e19907af2..a3fc104f5 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1443,6 +1443,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { in.RedactRouteTo = cur.RedactRouteTo in.DesktopSubagentEffort = cur.DesktopSubagentEffort in.ChinaMirror = cur.ChinaMirror // the Plugins page's, set on its own + in.NPMRegistry = cur.NPMRegistry // and its npm registry // which Codex accounts spend a reset by themselves, set on the Usage card in.CodexAutoReset = cur.CodexAutoReset in.CodexAutoResetOnly = cur.CodexAutoResetOnly // and at which of the two times diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a6da41649..9f89b4622 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3876,6 +3876,12 @@ const I18N = { "magpie's own sign-in to this subscription is deprecated: this plugin takes its place, and accounts signed in there move to it.": "magpie 内置的此订阅登录已弃用:由此插件接替,内置里登录的账号会迁到插件。", "Search plugins and npm…": "搜索插件和 npm…", "Mirrors in China": "国内镜像", + "npm registry": "npm 源", + "set here": "在此设置", + "from {name}": "来自 {name}", + "from your shell's {name}": "来自终端环境的 {name}", + "npm's own": "npm 官方源", + "Use the registry your .npmrc, .bunfig.toml or shell names, or npm's own": "改用 .npmrc、.bunfig.toml 或终端环境中设置的源,都没有则用 npm 官方源", "Download the plugin list, plugins and Bun from mirrors in China first (npmmirror, jsDelivr), their official addresses after. Each is a copy of the very file, checked as the original is": "插件列表、插件和 Bun 优先从国内镜像(npmmirror、jsDelivr)下载,失败再用官方地址。镜像文件与官方相同,校验方式一致", "Search plugins": "搜索插件", "Couldn't load the plugins: {error}": "无法加载插件:{error}", @@ -8068,6 +8074,12 @@ const I18N = { "magpie's own sign-in to this subscription is deprecated: this plugin takes its place, and accounts signed in there move to it.": "magpie 內建的此訂閱登入已棄用:由此外掛接替,內建裡登入的帳號會遷到外掛。", "Search plugins and npm…": "搜尋外掛和 npm…", "Mirrors in China": "國內鏡像", + "npm registry": "npm 來源", + "set here": "在此設定", + "from {name}": "來自 {name}", + "from your shell's {name}": "來自終端環境的 {name}", + "npm's own": "npm 官方來源", + "Use the registry your .npmrc, .bunfig.toml or shell names, or npm's own": "改用 .npmrc、.bunfig.toml 或終端環境中設定的來源,都沒有則用 npm 官方來源", "Download the plugin list, plugins and Bun from mirrors in China first (npmmirror, jsDelivr), their official addresses after. Each is a copy of the very file, checked as the original is": "外掛列表、外掛和 Bun 優先從國內鏡像(npmmirror、jsDelivr)下載,失敗再用官方位址。鏡像檔案與官方相同,驗證方式一致", "Search plugins": "搜尋外掛", "Couldn't load the plugins: {error}": "無法載入外掛:{error}", @@ -12282,6 +12294,12 @@ const I18N = { "magpie's own sign-in to this subscription is deprecated: this plugin takes its place, and accounts signed in there move to it.": "magpie 内蔵のこのサブスクリプションへのサインインは非推奨です。このプラグインが引き継ぎ、内蔵版でサインインしたアカウントはプラグインに移ります。", "Search plugins and npm…": "プラグインと npm を検索…", "Mirrors in China": "中国のミラー", + "npm registry": "npm レジストリ", + "set here": "ここで設定", + "from {name}": "{name} から", + "from your shell's {name}": "シェルの {name} から", + "npm's own": "npm 公式", + "Use the registry your .npmrc, .bunfig.toml or shell names, or npm's own": ".npmrc、.bunfig.toml、シェルで指定したレジストリを使います。どれもなければ npm 公式を使います", "Download the plugin list, plugins and Bun from mirrors in China first (npmmirror, jsDelivr), their official addresses after. Each is a copy of the very file, checked as the original is": "プラグインリスト、プラグイン、Bun をまず中国のミラー(npmmirror、jsDelivr)から、次に公式のアドレスからダウンロードします。ミラーのものは同じファイルのコピーで、オリジナルと同じように検証されます", "Search plugins": "プラグインを検索", "Couldn't load the plugins: {error}": "プラグインを読み込めませんでした:{error}", @@ -16509,6 +16527,12 @@ const I18N = { "magpie's own sign-in to this subscription is deprecated: this plugin takes its place, and accounts signed in there move to it.": "Die integrierte Anmeldung von magpie für dieses Abo ist veraltet: Diese Erweiterung tritt an ihre Stelle, und dort angemeldete Konten ziehen zu ihr um.", "Search plugins and npm…": "Erweiterungen und npm durchsuchen…", "Mirrors in China": "Spiegel in China", + "npm registry": "npm-Registry", + "set here": "hier festgelegt", + "from {name}": "aus {name}", + "from your shell's {name}": "aus {name} deiner Shell", + "npm's own": "die offizielle von npm", + "Use the registry your .npmrc, .bunfig.toml or shell names, or npm's own": "Die Registry aus deiner .npmrc, .bunfig.toml oder Shell verwenden, sonst die offizielle von npm", "Download the plugin list, plugins and Bun from mirrors in China first (npmmirror, jsDelivr), their official addresses after. Each is a copy of the very file, checked as the original is": "Erweiterungsliste, Erweiterungen und Bun zuerst von Spiegeln in China (npmmirror, jsDelivr) laden, danach von den offiziellen Adressen. Jede ist eine Kopie genau derselben Datei und wird wie das Original geprüft", "Search plugins": "Erweiterungen suchen", "Couldn't load the plugins: {error}": "Erweiterungen konnten nicht geladen werden: {error}", diff --git a/internal/gui/assets/plugins.css b/internal/gui/assets/plugins.css index 11a925d15..fc0ef9dff 100644 --- a/internal/gui/assets/plugins.css +++ b/internal/gui/assets/plugins.css @@ -193,6 +193,10 @@ button.pm-chip:disabled { cursor: default; opacity: .6; } /* a package the market doesn't list */ .pm-manual { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-radius: 12px; border: 1px dashed var(--line); flex-wrap: wrap; } .pm-mlabel { font-size: 12px; color: var(--muted); } +.pm-registry { display: flex; align-items: center; gap: 8px; padding: 4px 12px 0; flex-wrap: wrap; font-size: 12px; min-width: 0; } +.pm-reg-url { min-width: 0; overflow-wrap: anywhere; font-size: 12px; } +.pm-reg-from { color: var(--muted); min-width: 0; overflow-wrap: anywhere; } +.pm-reg-err { flex-basis: 100%; color: var(--red); } .pm-minput { flex: 1; min-width: 180px; height: 26px; padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: var(--code-style, normal) var(--code-weight, 400) 12px var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); outline: none; } .pm-minput:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); } /* the system's folder picker, beside the field it fills */ diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 4c752188a..f4b127634 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -22,7 +22,7 @@ const heads = {}; // /api/plugins/git: a git plugin's spec → the commit its repository is at let failed = ""; // why what's installed couldn't be loaded let failedList = ""; // ...and the plugins suggested - let tab = "discover"; + let tab = "discover", regBox; try { tab = localStorage.getItem("magpie.pluginTab") || tab; } catch {} let query = ""; let hits = null; // npm's answer for query: { q, list } | { q, loading } | { q, error } @@ -635,21 +635,14 @@ return box; } - // The repositories on GitHub are many and of every kind (the owner: 这里 - // 应该有分类以及搜索框方便用户筛选), so their section has its own kinds - // to pick from, each with how many there are, and a field that narrows - // them by name, author or description as it is typed, once there are - // more than a few to look through (counted before the page's search, so - // they don't go away under someone typing). Both narrow what the page's - // search has already found; only the section is drawn again. - // What's installed is the other question the section is read with (the - // owner: 加一个未安装), and it cuts across the kinds: a reader after a - // middleware they haven't got picks Middleware and Not installed. So it - // is a second strip beside the kinds, each counting what the other, the - // field and the page's search leave — the counts follow the picks as - // they are made — and the two narrow the grid together. - // The section, its head and its field are made once and kept in the - // page, as the page's search field is (#1055). + // GitHub's repositories are many and of every kind (the owner: 这里 + // 应该有分类以及搜索框方便用户筛选): the section has its own kinds, each + // counted, and, past a few, a field narrowing by name, author or + // description as typed (counted before the page's search). A second + // strip says what's installed (the owner: 加一个未安装), across the + // kinds; each strip counts what the other, the field and the search + // leave, and they narrow the grid together. Only the section is drawn + // again; it, its head and its field are kept, as the search is (#1055). let ghKind = ""; // "" (all) | "pv" | "mw" | "ag" let ghHave = ""; // "" (all) | "have" | "none" let ghQuery = ""; @@ -961,6 +954,10 @@ else if (!tagged) out.push(ghWaiting()); else if (taggedErr && !tagged.length) out.push(ghFailed()); out.push(manual()); + if (mine?.registry) { + out.push(regBox = regBox || el("div", "pm-registry")); + import("./registry.js").then(() => pmRegistry(regBox, mine, askNPM), statusTErr); + } replaceKeeping(body, out); if (agentsFor && agSec) { // after the view is put back where the reader was, as showing it diff --git a/internal/gui/assets/registry.js b/internal/gui/assets/registry.js new file mode 100644 index 000000000..21eccb529 --- /dev/null +++ b/internal/gui/assets/registry.js @@ -0,0 +1,87 @@ +// The Plugins page's npm registry row: the registry plugins are installed +// from and npm is asked of, and where it came from (the user's .npmrc, +// bunfig or shell, the 「国内镜像」 switch, npm's own); one set here comes +// before all of them (timwangdev on X). plugins.js imports this when +// Discover draws the row, so it weighs nothing on the core. The row is +// plugins.js's box, kept across its redraws, and drawn here alone: a draft +// and its error stay while the page is drawn again. +(() => { + let box = null, mine = null, askNPM = null; + let editing = false, draft = "", err = "", saving = false; + + function from(r) { + switch (r.from) { + case "magpie": return t("set here"); + case "env": return t("from {name}", { name: r.var }); + case "shell": return t("from your shell's {name}", { name: r.var }); + case "bunfig": case "npmrc": return t("from {name}", { name: r.path }); + case "china": return t("Mirrors in China"); + } + return t("npm's own"); + } + + function button(label, cls, fn) { + const b = el("button", cls, label); + b.type = "button"; + b.disabled = saving; + b.onclick = fn; + return b; + } + + async function set(url) { + saving = true; + draw(); + try { + const r = await api("plugins/registry", { url }); + mine.registry = r.registry; + editing = false; + draft = err = ""; + // npm's answers again, now from this registry + askNPM(); + } catch (e) { + err = t(e.message); + statusTErr(e); + } + saving = false; + draw(); + } + + function draw() { + const r = mine.registry; + box.replaceChildren(el("span", "pm-mlabel", t("npm registry"))); + if (!editing) { + box.append(el("code", "pm-reg-url", r.url), el("span", "pm-reg-from", from(r)), el("span", "grow"), + button(t("Change"), "text", () => { editing = true; draft = r.from === "magpie" ? r.url : ""; draw(); })); + if (r.from === "magpie") { + const def = button(t("Use default"), "text", () => set("")); + def.title = t("Use the registry your .npmrc, .bunfig.toml or shell names, or npm's own"); + box.append(def); + } + return; + } + const i = el("input", "pm-minput pm-reg-input"); + i.value = draft; + i.placeholder = "https://registry.npmmirror.com"; + i.spellcheck = false; + i.autocomplete = "off"; + i.setAttribute("aria-label", t("npm registry")); + i.oninput = () => { draft = i.value; }; + const save = button(t("Save"), "text primary", () => { + const v = i.value.trim(); + if (v) set(v); else i.focus(NO_SCROLL); + }); + const cancel = button(t("Cancel"), "text", () => { editing = false; draft = err = ""; draw(); }); + cancel.disabled = false; + i.onkeydown = (ev) => { ev.stopPropagation(); if (ev.key === "Enter") save.onclick(); else if (ev.key === "Escape") cancel.onclick(); }; + box.append(i, cancel, save); + if (err) box.append(el("div", "pm-reg-err", err)); + i.focus(NO_SCROLL); + } + + // plugins.js calls this at each redraw; an open field is left as it is + window.pmRegistry = (b, m, ask) => { + const fresh = box !== b; + box = b; mine = m; askNPM = ask; + if (fresh || !editing) draw(); + }; +})(); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 5addef028..c4cfaf1e1 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -219,10 +219,22 @@ type pluginsJSON struct { // Mirror is the 「国内镜像」 switch: the list, npm and Bun asked of // mirrors in China first (settings.ChinaMirror) Mirror bool `json:"mirror"` + // Registry is the npm registry plugins are installed from and npm's + // answers asked of, and where it came from (plugin.Registry) + Registry plugin.RegistryInUse `json:"registry"` +} + +// registryJSON is plugin.Registry with its file's path as the page shows it. +func registryJSON() plugin.RegistryInUse { + r := plugin.Registry() + if r.Path != "" { + r.Path = tilde(r.Path) + } + return r } func pluginsState(ctx context.Context, w Windows) pluginsJSON { - s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Load().ChinaMirror} + s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Load().ChinaMirror, Registry: registryJSON()} l := plugin.Load() errs := map[string]string{} names := map[string][]string{} @@ -691,6 +703,20 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { } writeJSON(rw, map[string]bool{"mirror": in.On}) }) + // the npm registry set in magpie, "" for none of its own: an address + // that isn't an http(s) one is refused, not kept + mux.HandleFunc("POST /api/plugins/registry", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ URL string } + if err := json.NewDecoder(io.LimitReader(r.Body, 4<<10)).Decode(&in); err != nil { + fail(rw, err) + return + } + if _, err := plugin.SetRegistry(in.URL); err != nil { + fail(rw, err) + return + } + writeJSON(rw, map[string]any{"registry": registryJSON()}) + }) // add, remove, update, turn on or off: each answers with the list mux.HandleFunc("POST /api/plugins/{op}", func(rw http.ResponseWriter, r *http.Request) { var in struct { diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 152cd7808..b3b51d82f 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -167,6 +167,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { CodexSubagentModel: "codex/gpt-6-astra", DesktopSubagentModel: "fake/m2", ChinaMirror: true, + NPMRegistry: "https://npm.corp.example", CodexAutoReset: []string{"me@example.com"}, CodexAutoResetOnly: map[string]string{"me@example.com": "expiring"}, CodexResetLead: 180, diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index b1096f4df..e0f9497be 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -146,8 +146,9 @@ test("compat.js is the first of the page's own scripts", async () => { // value first, ruleedit.js on a masking rule's Edit, ratewindows.js when // a provider editor draws its rate windows, traywindows.js when the menu // bar shows a card, autoresetown.js when Settings draws Codex's auto-use - // rows; the checks above still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + // rows, registry.js when Plugins draws its npm registry; the checks above + // still read them + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/plugin-registry.test.cjs b/internal/gui/tests/plugin-registry.test.cjs new file mode 100644 index 000000000..808e7e592 --- /dev/null +++ b/internal/gui/tests/plugin-registry.test.cjs @@ -0,0 +1,115 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Plugins page's npm registry row (timwangdev on X): Discover says the +// registry plugins are installed from and where it came from (here the +// user's ~/.npmrc); Change takes an address, an address the server refuses +// is said and not kept, a saved one says it is set here and offers Use +// default, which drops it. Every language, Chromium and WebKit, and a +// narrow window that doesn't scroll sideways. The API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); + +const listings = [ + { package: "@magpie-community/opencode-zed-auth", name: "Zed", icon: "zed", providers: ["zed"], community: true, + summary: { en: "Your Zed plan.", zh: "Zed 订阅。" }, npm: { version: "0.1.0", weekly: 120 } }, +]; + +const NPMRC = { url: "https://npm.corp.example/repo", from: "npmrc", path: "~/.npmrc" }; + +function server(lang, asked) { + let registry = { ...NPMRC }; + const state = () => ({ bun: true, bunVersion: "1.3.0", plugins: [], mirror: true, registry }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data, status) => route.fulfill({ json: data, status }); + const body = () => route.request().postDataJSON(); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json(state()); + if (url.pathname === "/api/plugins/listings") return json({ listings }); + if (url.pathname === "/api/plugins/market") return json({ listings, state: state() }); + if (url.pathname === "/api/plugins/registry") { + const { url: u } = body(); + asked.push(u); + if (u && !/^https?:\/\/[^/]/.test(u)) return json({ error: `"${u}" isn't a registry's address: give an http:// or https:// one, like https://registry.npmmirror.com` }, 400); + registry = u ? { url: u.replace(/\/+$/, ""), from: "magpie" } : { ...NPMRC }; + return json({ registry }); + } + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname) || url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const L = { + en: { label: "npm registry", from: "from ~/.npmrc", here: "set here", change: "Change", save: "Save", def: "Use default" }, + zh: { label: "npm 源", from: "来自 ~/.npmrc", here: "在此设置", change: "修改", save: "保存", def: "使用默认" }, + "zh-TW": { label: "npm 來源", from: "來自 ~/.npmrc", here: "在此設定", change: "修改", save: "儲存", def: "使用預設" }, + ja: { label: "npm レジストリ", from: "~/.npmrc から", here: "ここで設定", change: "変更", save: "保存", def: "デフォルトを使用" }, + de: { label: "npm-Registry", from: "aus ~/.npmrc", here: "hier festgelegt", change: "Ändern", save: "Speichern", def: "Standard verwenden" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Plugins page's npm registry", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(L)) { + await t.test(lang, async () => { + const w = L[lang]; + for (const width of [980, 380]) { + const page = await (await browser.newContext({ viewport: { width, height: 820 } })).newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = [], asked = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, asked)); + await page.goto("http://magpie.test/?view=plugins"); + const row = page.locator("#view-plugins .pm-registry"); + await row.waitFor(); + assert.equal((await row.locator(".pm-mlabel").innerText()).trim(), w.label); + assert.equal((await row.locator(".pm-reg-url").innerText()).trim(), NPMRC.url); + assert.equal((await row.locator(".pm-reg-from").innerText()).trim(), w.from); + // nothing of the page's runs out sideways, the long address included + const sideways = await page.evaluate(() => { + const v = document.querySelector("#view-plugins"), r = document.querySelector("#view-plugins .pm-registry"); + return { page: document.documentElement.scrollWidth - document.documentElement.clientWidth, row: r.scrollWidth - r.clientWidth, right: r.getBoundingClientRect().right - v.getBoundingClientRect().right }; + }); + assert.ok(sideways.page <= 0 && sideways.row <= 1 && sideways.right <= 1, JSON.stringify(sideways)); + if (width < 900 && lang !== "en") { assert.deepEqual(errors, []); await page.context().close(); continue; } + + await row.locator("button", { hasText: w.change }).click(); + const input = row.locator("input.pm-reg-input"); + await input.waitFor(); + assert.ok(await input.evaluate((i) => document.activeElement === i), "the field has the focus"); + await input.fill("ftp://npm.example"); + await input.press("Enter"); + await row.locator(".pm-reg-err").waitFor(); + assert.match(await row.locator(".pm-reg-err").innerText(), /isn't a registry's address/); + assert.ok(await input.isVisible(), "a refused address stays in the field"); + assert.equal(await input.inputValue(), "ftp://npm.example"); + + await input.fill("https://registry.npmmirror.com/"); + await row.locator("button", { hasText: w.save }).click(); + await row.locator(".pm-reg-from", { hasText: w.here }).waitFor(); + assert.equal((await row.locator(".pm-reg-url").innerText()).trim(), "https://registry.npmmirror.com"); + const def = row.locator("button", { hasText: w.def }); + await def.click(); + await row.locator(".pm-reg-from", { hasText: w.from }).waitFor(); + assert.equal(await def.count(), 0); + assert.deepEqual(asked, ["ftp://npm.example", "https://registry.npmmirror.com/", ""]); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + } + }); +} diff --git a/internal/plugin/bun.go b/internal/plugin/bun.go index ea7c23a74..9f67b1487 100644 --- a/internal/plugin/bun.go +++ b/internal/plugin/bun.go @@ -374,9 +374,10 @@ func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]by // bunCommand runs bun with args in dir, the environment's proxy settings // passed on (a SOCKS5 one bridged, as Bun can't use it: #1409), the roots -// the system trusts added to Bun's (caEnv), and npm's registry in China -// with the 「国内镜像」 switch on (its packages are npm's own, checked -// against the integrity npm gave). +// the system trusts added to Bun's (caEnv), and the npm registry in use +// where bun wouldn't find it itself (registryEnv): one set in magpie, the +// login shell's, or npm's registry in China with the 「国内镜像」 switch on +// (its packages are npm's own, checked against the integrity npm gave). var bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd { cmd := command(ctx, bun, args...) cmd.Dir = dir @@ -385,18 +386,3 @@ var bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exe cmd.Env = append(cmd.Env, registryEnv(cmd.Env)...) return cmd } - -// registryEnv is what has bun install from npm's registry in China, with -// the switch on, unless the environment names a registry already. -func registryEnv(env []string) []string { - if !source.China() { - return nil - } - for _, kv := range env { - k, v, _ := strings.Cut(kv, "=") - if k = strings.ToUpper(k); (k == "BUN_CONFIG_REGISTRY" || k == "NPM_CONFIG_REGISTRY") && strings.TrimSpace(v) != "" { - return nil - } - } - return []string{"BUN_CONFIG_REGISTRY=" + source.NPMMirror + "/"} -} diff --git a/internal/plugin/github.go b/internal/plugin/github.go index 241ad102b..dea89ad1b 100644 --- a/internal/plugin/github.go +++ b/internal/plugin/github.go @@ -447,7 +447,7 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool // published to npm from this repository: npm's copy is the one // built to be installed (a repository often leaves its dist out, // built only to publish), so it is installed from npm - b, err := fetchJSON(pc, npmRegistry+"/"+npmPath(pj.Name)+"/latest", 1<<20) + b, err := fetchNPM(pc, pj.Name, "/"+npmPath(pj.Name)+"/latest", 1<<20) known := err == nil || errors.Is(err, errNotFound) var unknown error if !known { diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 5044ec5ce..3fdbfe086 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -448,7 +448,7 @@ func npmAsk(ctx context.Context, name string) (NPM, error) { wg.Add(2) go func() { defer wg.Done() - b, err := fetchJSON(ctx, npmRegistry+"/"+npmPath(name)+"/latest", 1<<20) + b, err := fetchNPM(ctx, name, "/"+npmPath(name)+"/latest", 1<<20) if err != nil { latestErr = err return @@ -555,7 +555,12 @@ func Search(ctx context.Context, q string) ([]Hit, error) { // (given their name and keywords, lowercased, and the keywords). func searchNPM(ctx context.Context, text string, keep func(string, []string) bool) ([]Hit, error) { v := url.Values{"text": {text}, "size": {"30"}} - b, err := fetchJSON(ctx, npmRegistry+"/-/v1/search?"+v.Encode(), 4<<20) + b, err := fetchNPM(ctx, "", "/-/v1/search?"+v.Encode(), 4<<20) + if _, _, official := npmBase(""); err != nil && !official { + // a registry of the user's that has no search (a private one): + // npm's own has the plugins' packages + b, err = fetchJSON(ctx, npmRegistry+"/-/v1/search?"+v.Encode(), 4<<20) + } if err != nil { return nil, err } @@ -624,7 +629,7 @@ func Readme(ctx context.Context, name string) (Page, error) { } ctx, cancel := context.WithTimeout(ctx, 12*time.Second) defer cancel() - b, err := fetchJSON(ctx, npmRegistry+"/"+npmPath(name), 32<<20) + b, err := fetchNPM(ctx, name, "/"+npmPath(name), 32<<20) if err != nil { // one npm doesn't have (yet): the README the community repo's // dist branch packed with it diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go new file mode 100644 index 000000000..772956e65 --- /dev/null +++ b/internal/plugin/registry.go @@ -0,0 +1,348 @@ +package plugin + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/source" +) + +// Where the npm registry in use came from (RegistryInUse.From). +const ( + FromMagpie = "magpie" // set on the Plugins page or with `magpie plugin registry` + FromEnv = "env" // magpie's environment: BUN_CONFIG_REGISTRY, NPM_CONFIG_REGISTRY + FromShell = "shell" // the login shell's, which magpie opened from the Dock doesn't have + FromBunfig = "bunfig" // install.registry in a .bunfig.toml + FromNPMRC = "npmrc" // registry= in an .npmrc + FromChina = "china" // the 「国内镜像」 switch: npmmirror + FromDefault = "default" // npm's own +) + +// RegistryInUse is the npm registry plugins are installed from and npm's +// answers are asked of, and where it came from: Var names the variable +// (env, shell) and Path the file (bunfig, npmrc). +type RegistryInUse struct { + URL string `json:"url"` + From string `json:"from"` + Var string `json:"var,omitempty"` + Path string `json:"path,omitempty"` +} + +// registryVars are the variables bun takes a registry from, in the order +// it takes them. +var registryVars = []string{"BUN_CONFIG_REGISTRY", "NPM_CONFIG_REGISTRY", "npm_config_registry"} + +// loginEnv is what the login shell said of a variable (a var for tests). +var loginEnv = proc.LoginEnvKnown + +// Registry is the npm registry in use: the one set in magpie, then one the +// user's own setup names (magpie's environment, the login shell's, a +// .bunfig.toml, an .npmrc: a registry of the user's own, which bun reads +// too), then npmmirror with the 「国内镜像」 switch on, then npm's own. A +// registry the user set is never put behind magpie's switch (timwangdev +// on X: plugins from a custom npm registry). +func Registry() RegistryInUse { + if u, err := CleanRegistry(settings.Load().NPMRegistry); err == nil && u != "" { + return RegistryInUse{URL: u, From: FromMagpie} + } + if r, ok := userRegistry(); ok { + return r + } + if source.China() { + return RegistryInUse{URL: source.NPMMirror, From: FromChina} + } + return RegistryInUse{URL: npmDefault, From: FromDefault} +} + +// npmDefault is npm's own registry, as Registry names it; lookups of it go +// to npmRegistry, which tests move. +const npmDefault = "https://registry.npmjs.org" + +// userRegistry is the registry the user's own setup names, as bun finds it: +// its variables, then the plugins folder's bunfig.toml and .npmrc, then the +// global .bunfig.toml and ~/.npmrc. +func userRegistry() (RegistryInUse, bool) { + for _, k := range registryVars { + if u, err := CleanRegistry(os.Getenv(k)); err == nil && u != "" { + return RegistryInUse{URL: u, From: FromEnv, Var: k}, true + } + } + for _, k := range registryVars { + if u, err := CleanRegistry(loginEnv(k)); err == nil && u != "" { + return RegistryInUse{URL: u, From: FromShell, Var: k}, true + } + } + for _, f := range registryFiles() { + var u string + if f.bunfig { + u = bunfigRegistry(f.path) + } else { + u = npmrcOf(f.path).registry + } + if u, err := CleanRegistry(u); err == nil && u != "" { + from := FromNPMRC + if f.bunfig { + from = FromBunfig + } + return RegistryInUse{URL: u, From: from, Path: f.path}, true + } + } + return RegistryInUse{}, false +} + +type registryFile struct { + path string + bunfig bool +} + +// registryFiles are the files bun reads a registry from, the plugins +// folder's (where it installs) before the user's. +func registryFiles() []registryFile { + out := []registryFile{{filepath.Join(Dir(), "bunfig.toml"), true}, {filepath.Join(Dir(), ".npmrc"), false}} + if x := os.Getenv("XDG_CONFIG_HOME"); filepath.IsAbs(x) { + out = append(out, registryFile{filepath.Join(x, ".bunfig.toml"), true}) + } + if home, err := os.UserHomeDir(); err == nil && home != "" { + out = append(out, registryFile{filepath.Join(home, ".bunfig.toml"), true}, registryFile{filepath.Join(home, ".npmrc"), false}) + } + return out +} + +// CleanRegistry is u as a registry's address, without its trailing slash: +// "" for "", an error for anything but an http(s) URL with a host. +func CleanRegistry(u string) (string, error) { + u = strings.TrimSpace(u) + if u == "" { + return "", nil + } + p, err := url.Parse(u) + if err != nil || (p.Scheme != "http" && p.Scheme != "https") || p.Host == "" || p.User != nil || p.RawQuery != "" || p.Fragment != "" { + return "", fmt.Errorf("%q isn't a registry's address: give an http:// or https:// one, like https://registry.npmmirror.com", u) + } + return strings.TrimRight(u, "/"), nil +} + +// SetRegistry keeps u as the registry plugins use, "" or "default" for +// none of magpie's own; an address that isn't one is refused, not kept. +func SetRegistry(u string) (RegistryInUse, error) { + if strings.EqualFold(strings.TrimSpace(u), "default") { + u = "" + } + c, err := CleanRegistry(u) + if err != nil { + return Registry(), err + } + s := settings.Load() + if s.NPMRegistry != c { + s.NPMRegistry = c + if err := settings.Save(s); err != nil { + return Registry(), err + } + ReloadInfo() + } + return Registry(), nil +} + +// registryEnv is the registry bun installs from, given the environment it +// runs in: the one set in magpie, the login shell's (which env lacks) and +// npmmirror with the switch on are told to it; one env, a bunfig or an +// .npmrc names bun reads itself, and the switch's mirror is not put over it. +func registryEnv(env []string) []string { + r := Registry() + switch r.From { + case FromMagpie, FromShell, FromChina: + default: + return nil + } + if r.From != FromMagpie { + // a variable the environment it runs in has (a test's) is its own + for _, kv := range env { + k, v, _ := strings.Cut(kv, "=") + if k = strings.ToUpper(k); (k == "BUN_CONFIG_REGISTRY" || k == "NPM_CONFIG_REGISTRY") && strings.TrimSpace(v) != "" { + return nil + } + } + } + return []string{"BUN_CONFIG_REGISTRY=" + r.URL + "/", "NPM_CONFIG_REGISTRY=" + r.URL + "/"} +} + +// npmrc is what an .npmrc says of registries: the default one, each +// scope's, and the tokens it keeps for each, by npm's "nerf dart" +// (//host/path/). +type npmrc struct { + registry string + scopes map[string]string + tokens map[string]string +} + +// npmrcVar is a ${VAR} in an .npmrc's value, which npm expands. +var npmrcVar = regexp.MustCompile(`\$\{[A-Za-z_][A-Za-z0-9_]*\}`) + +// npmrcOf reads the .npmrc at path; an empty one when it can't be read. A +// ${VAR} is the environment's, as npm expands it. +func npmrcOf(path string) npmrc { + rc := npmrc{scopes: map[string]string{}, tokens: map[string]string{}} + b, err := os.ReadFile(path) + if err != nil { + return rc + } + for _, line := range strings.Split(string(b), "\n") { + line = strings.TrimSpace(line) + if line == "" || line[0] == '#' || line[0] == ';' { + continue + } + k, v, ok := strings.Cut(line, "=") + if !ok { + continue + } + k, v = strings.TrimSpace(k), npmrcVar.ReplaceAllStringFunc(strings.Trim(strings.TrimSpace(v), `"'`), func(m string) string { return os.Getenv(m[2 : len(m)-1]) }) + switch { + case k == "registry": + rc.registry = v + case strings.HasPrefix(k, "@") && strings.HasSuffix(k, ":registry"): + rc.scopes[strings.TrimSuffix(k, ":registry")] = v + case strings.HasPrefix(k, "//") && strings.HasSuffix(k, ":_authToken"): + rc.tokens[strings.TrimSuffix(k, ":_authToken")] = v + } + } + return rc +} + +// bunfigRegistry is install.registry in the bunfig at path: an address, +// or a table with its url; "" when it names none. +func bunfigRegistry(path string) string { + b, err := os.ReadFile(path) + if err != nil { + return "" + } + var c struct { + Install struct { + Registry any `toml:"registry"` + } `toml:"install"` + } + if toml.Unmarshal(b, &c) != nil { + return "" + } + switch r := c.Install.Registry.(type) { + case string: + return r + case map[string]any: + u, _ := r["url"].(string) + return u + } + return "" +} + +// npmrcs are the .npmrc files bun reads, the plugins folder's first. +func npmrcs() []npmrc { + var out []npmrc + for _, f := range registryFiles() { + if !f.bunfig { + out = append(out, npmrcOf(f.path)) + } + } + return out +} + +// npmBase is the registry magpie asks of package name, and the token an +// .npmrc keeps for it: a scope's own registry (@scope:registry=) for a +// package of that scope (bun installs it from there whatever the default +// registry is); Registry's otherwise. official is whether it is npm's own (which the 「国内镜像」 +// switch may put npmmirror before, source.Do). +func npmBase(name string) (base, token string, official bool) { + r := Registry() + rcs := npmrcs() + if scope, _, ok := strings.Cut(name, "/"); ok && strings.HasPrefix(scope, "@") { + for _, rc := range rcs { + if u, err := CleanRegistry(rc.scopes[scope]); err == nil && u != "" { + return u, tokenFor(rcs, u), false + } + } + } + switch r.From { + case FromDefault, FromChina: + return npmRegistry, "", true + } + return r.URL, tokenFor(rcs, r.URL), false +} + +// tokenFor is the token an .npmrc keeps for the registry at base: the one +// whose nerf dart (//host/path/) is the longest that base's starts with, +// as npm matches them; "" when none. +func tokenFor(rcs []npmrc, base string) string { + u, err := url.Parse(base) + if err != nil { + return "" + } + dart := "//" + u.Host + strings.TrimRight(u.EscapedPath(), "/") + "/" + best, tok := "", "" + for _, rc := range rcs { + for k, v := range rc.tokens { + k = strings.TrimRight(k, "/") + "/" + if strings.HasPrefix(dart, k) && len(k) > len(best) && v != "" { + best, tok = k, v + } + } + } + return tok +} + +// fetchNPM is what the registry in use says at suffix (/, +// //latest), for package name. npm's own is asked as before (its +// mirror in China first with the switch on); a registry the user named is +// asked alone, with the token their .npmrc keeps for it and no other. +func fetchNPM(ctx context.Context, name, suffix string, limit int64) ([]byte, error) { + base, token, official := npmBase(name) + if official { + return fetchJSON(ctx, base+suffix, limit) + } + return fetchRegistry(ctx, base+suffix, token, limit) +} + +// fetchRegistry gets u from a registry of the user's, with its token; the +// token never goes to any other address (a mirror, a redirect elsewhere). +func fetchRegistry(ctx context.Context, u, token string, limit int64) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, "GET", u, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "magpie") + req.Header.Set("Accept", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + c := *http.DefaultClient + c.CheckRedirect = func(r *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + if r.URL.Host != via[0].URL.Host { + r.Header.Del("Authorization") + } + return nil + } + res, err := source.DoOfficial(&c, req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return nil, errNotFound + } + if res.StatusCode != http.StatusOK { + return nil, &statusError{URL: u, Code: res.StatusCode, Status: res.Status} + } + return io.ReadAll(io.LimitReader(res.Body, limit)) +} diff --git a/internal/plugin/registry_test.go b/internal/plugin/registry_test.go new file mode 100644 index 000000000..08db47d8a --- /dev/null +++ b/internal/plugin/registry_test.go @@ -0,0 +1,219 @@ +package plugin + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/source" + "github.com/yetone/magpie/internal/testenv" +) + +// registryHome is a home of its own with no registry anywhere: none in +// the environment, the login shell's, a bunfig or an .npmrc, the 「国内镜像」 +// switch off and nothing set in magpie. +func registryHome(t *testing.T) (home string, shell map[string]string) { + t.Helper() + home = t.TempDir() + testenv.SetHome(t, home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("APPDATA", filepath.Join(home, "AppData")) + for _, k := range registryVars { + t.Setenv(k, "") + } + shell = map[string]string{} + le, china := loginEnv, source.China + loginEnv = func(k string) string { return shell[k] } + source.China = func() bool { return false } + t.Cleanup(func() { loginEnv, source.China = le, china }) + return home, shell +} + +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +// Each place a registry can be named, each before the ones after it: +// magpie's own setting, the environment, the login shell, a bunfig, an +// .npmrc, the 「国内镜像」 switch, npm's own (timwangdev on X). The switch +// never comes before a registry the user named. +func TestRegistryPrecedence(t *testing.T) { + home, shell := registryHome(t) + want := func(url, from string) { + t.Helper() + if r := Registry(); r.URL != url || r.From != from { + t.Fatalf("Registry() = %+v, want %s from %s", r, url, from) + } + } + want("https://registry.npmjs.org", FromDefault) + source.China = func() bool { return true } + want("https://registry.npmmirror.com", FromChina) + writeFile(t, filepath.Join(home, ".npmrc"), "# mine\nregistry = \"https://npm.corp.example/repo/\"\n") + want("https://npm.corp.example/repo", FromNPMRC) + writeFile(t, filepath.Join(home, ".bunfig.toml"), "[install]\nregistry = { url = \"https://bun.corp.example/\", token = \"x\" }\n") + want("https://bun.corp.example", FromBunfig) + shell["NPM_CONFIG_REGISTRY"] = "https://shell.example/" + want("https://shell.example", FromShell) + t.Setenv("BUN_CONFIG_REGISTRY", "https://env.example") + want("https://env.example", FromEnv) + if _, err := SetRegistry("https://magpie.example/npm/"); err != nil { + t.Fatal(err) + } + want("https://magpie.example/npm", FromMagpie) + if _, err := SetRegistry("default"); err != nil { + t.Fatal(err) + } + want("https://env.example", FromEnv) +} + +// An address that isn't an http(s) registry's is refused and not kept; +// the one set before stays. +func TestSetRegistryRefusesWhatIsntOne(t *testing.T) { + registryHome(t) + if _, err := SetRegistry("https://ok.example/"); err != nil { + t.Fatal(err) + } + for _, bad := range []string{"ftp://npm.example", "npm.example", "javascript:alert(1)", "file:///etc/passwd", "https://", "--help", "https://user:pw@npm.example", "https://npm.example/?x=1"} { + if _, err := SetRegistry(bad); err == nil { + t.Errorf("SetRegistry(%q) was taken", bad) + } + if got := settings.Load().NPMRegistry; got != "https://ok.example" { + t.Fatalf("after %q settings say %q", bad, got) + } + } + // one written into settings.json by hand that isn't one is passed over + s := settings.Load() + s.NPMRegistry = "ftp://npm.example" + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if r := Registry(); r.From != FromDefault { + t.Fatalf("a bad setting is used: %+v", r) + } +} + +// bun is told the registry where it wouldn't find it itself: magpie's +// setting, over the environment's; the login shell's; npmmirror with the +// switch on. A registry in the user's .npmrc or bunfig is bun's to read, +// and the switch's mirror is never put over it. +func TestBunTakesTheUsersRegistry(t *testing.T) { + home, shell := registryHome(t) + reg := func() string { + var got string + for _, kv := range bunCommand(context.Background(), "bun", t.TempDir(), "add", "x").Env { + if v, ok := strings.CutPrefix(kv, "BUN_CONFIG_REGISTRY="); ok { + got = v // the last is the one bun sees + } + } + return got + } + source.China = func() bool { return true } + if r := reg(); r != "https://registry.npmmirror.com/" { + t.Fatalf("switch on: %q", r) + } + writeFile(t, filepath.Join(home, ".npmrc"), "registry=https://npm.corp.example/\n") + if r := reg(); r != "" { + t.Fatalf("with the user's .npmrc, bun is told %q", r) + } + shell["BUN_CONFIG_REGISTRY"] = "https://shell.example/" + if r := reg(); r != "https://shell.example/" { + t.Fatalf("the login shell's: %q", r) + } + t.Setenv("NPM_CONFIG_REGISTRY", "https://env.example/") + if r := reg(); r != "" { + t.Fatalf("the environment's own is bun's to read: %q", r) + } + if _, err := SetRegistry("https://magpie.example"); err != nil { + t.Fatal(err) + } + if r := reg(); r != "https://magpie.example/" { + t.Fatalf("magpie's setting: %q", r) + } +} + +// magpie asks npm's questions (a package's newest version, its README, +// the search) of the user's registry, with the token their .npmrc keeps +// for that host and for no other; a scope's own registry is asked of its +// packages. npm's own is never asked, with the switch on or off. +func TestLookupsAskTheUsersRegistry(t *testing.T) { + home, _ := registryHome(t) + source.China = func() bool { return true } + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var mu sync.Mutex + var seen []string + serve := func(name string) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + seen = append(seen, name+" "+r.URL.Path+" "+r.Header.Get("Authorization")) + mu.Unlock() + switch { + case strings.HasSuffix(r.URL.Path, "/latest"): + w.Write([]byte(`{"version":"1.2.3","description":"from ` + name + `"}`)) + case strings.HasPrefix(r.URL.Path, "/-/v1/search"): + w.Write([]byte(`{"objects":[]}`)) + default: + w.Write([]byte(`{"readme":"readme from ` + name + `"}`)) + } + })) + t.Cleanup(srv.Close) + return srv + } + mine, scoped, npm := serve("mine"), serve("scoped"), serve("npmjs") + // npm's download counts are npm's alone, whatever the registry + counts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"downloads":1}`)) })) + t.Cleanup(counts.Close) + was, wasDL := npmRegistry, npmDownloads + npmRegistry, npmDownloads = npm.URL, counts.URL + t.Cleanup(func() { npmRegistry, npmDownloads = was, wasDL }) + t.Setenv("MY_TOKEN", "s3cret") + writeFile(t, filepath.Join(home, ".npmrc"), strings.Join([]string{ + "registry=" + mine.URL + "/", + "@corp:registry=" + scoped.URL, + "//" + strings.TrimPrefix(mine.URL, "http://") + "/:_authToken=${MY_TOKEN}", + }, "\n")) + ctx := context.Background() + + info, err := npmAsk(ctx, "opencode-x-auth") + if err != nil || info.Version != "1.2.3" { + t.Fatalf("npmAsk: %+v %v", info, err) + } + if p, err := Readme(ctx, "opencode-x-auth"); err != nil || !strings.Contains(p.Readme, "from mine") { + t.Fatalf("Readme: %+v %v", p, err) + } + if _, err := npmAsk(ctx, "@corp/opencode-y-auth"); err != nil { + t.Fatal(err) + } + if _, err := searchNPM(ctx, "auth", func(string, []string) bool { return true }); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + for _, s := range seen { + switch { + case strings.HasPrefix(s, "npmjs "): + t.Errorf("npm's own was asked: %s", s) + case strings.HasPrefix(s, "mine ") && !strings.HasSuffix(s, " Bearer s3cret"): + t.Errorf("the user's registry was asked without their token: %s", s) + case strings.HasPrefix(s, "scoped ") && strings.Contains(s, "Bearer"): + t.Errorf("another host's token went to the scope's registry: %s", s) + } + } + for _, w := range []string{"mine /opencode-x-auth/latest Bearer s3cret", "mine /opencode-x-auth Bearer s3cret", "scoped /@corp/opencode-y-auth/latest ", "mine /-/v1/search Bearer s3cret"} { + if !slices.ContainsFunc(seen, func(s string) bool { return strings.EqualFold(s, w) }) { + t.Errorf("not asked: %q (asked %q)", w, seen) + } + } +} diff --git a/internal/proc/path_other.go b/internal/proc/path_other.go index 2839f6ef6..fd968dd60 100644 --- a/internal/proc/path_other.go +++ b/internal/proc/path_other.go @@ -111,10 +111,16 @@ func LoginPath() []string { // netproxy. var ProxyVars = []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} +// RegistryVars are the npm registry variables the login shell is asked +// for beside them: a registry set in .zshrc is the user's for bun's +// installs of plugins and magpie's asks of npm, which magpie opened from +// the Dock didn't see (timwangdev on X). Only read (LoginEnvKnown). +var RegistryVars = []string{"BUN_CONFIG_REGISTRY", "NPM_CONFIG_REGISTRY", "npm_config_registry"} + // shellVars are the variables shellProbe asks for, in its order. Claude // Code's provider switches (agentenv.ClaudeProviders) are only read, as the // proxy variables are. -var shellVars = slices.Concat(agentenv.Vars, ProxyVars, agentenv.ClaudeProviders) +var shellVars = slices.Concat(agentenv.Vars, ProxyVars, agentenv.ClaudeProviders, RegistryVars) // LoginEnv is the value a terminal opened now has for k, one of // agentenv.Vars, ProxyVars or agentenv.ClaudeProviders: the login shell's, asked as LoginPath asks @@ -126,6 +132,15 @@ func LoginEnv(k string) string { return login.vars[k] } +// LoginEnvKnown is what the login shell last said of k (UserPath or +// LoginPath asked it), "" when it hasn't been asked or had none; it never +// asks the shell itself, so a path every page takes doesn't wait on one. +func LoginEnvKnown(k string) string { + login.Lock() + defer login.Unlock() + return login.vars[k] +} + // UserBinDirs are the folders a user's command-line tools are installed in // that exist here — npm's prefixes, each Node version of nvm, fnm and mise, // bun, volta, pnpm, asdf, the standalone installers' ~/.local/bin, diff --git a/internal/proc/path_windows.go b/internal/proc/path_windows.go index 6fd54109c..d486fb52e 100644 --- a/internal/proc/path_windows.go +++ b/internal/proc/path_windows.go @@ -95,6 +95,9 @@ func LoginPath() []string { // environment has them. func LoginEnv(string) string { return "" } +// LoginEnvKnown is "" on Windows too (LoginEnv). +func LoginEnvKnown(string) string { return "" } + // ShellPath is LoginPath on Windows: PowerShell and cmd both take the // registry's PATH. func ShellPath(string) []string { return LoginPath() } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 4f3acf831..399ae1a28 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -678,6 +678,12 @@ type Settings struct { // downloads are asked of mirrors in China first, and of their official // addresses after (see source.China). ChinaMirror bool `json:"chinaMirror,omitempty"` + // NPMRegistry is the npm registry set on the Plugins page or with + // `magpie plugin registry`: plugins are installed from it and npm's + // answers asked of it, before a registry the user's .npmrc, bunfig or + // shell names and before the 「国内镜像」 switch (plugin.Registry). + // "" leaves it to those. + NPMRegistry string `json:"npmRegistry,omitempty"` // TextSize is how large the window's and the tray panel's pages are // drawn, in percent (one of TextSizes): the webviews' own zoom, as a // browser's, so the text and everything around it grow together. diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index b4350218a..538ce1e07 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -213,6 +213,7 @@ magpie quota # acme · Pro · 5h 37%
  • インストール。
    • npm パッケージは bun add でインストールされ、OpenCode と同じくインストールスクリプトは実行されません。postinstall でのビルドが必要な依存は動きません。
    • +
    • パッケージは普段使っている npm レジストリから取得されます。~/.npmrc の registry=、~/.bunfig.toml の install.registry、シェルの NPM_CONFIG_REGISTRY / BUN_CONFIG_REGISTRY が「中国のミラー」スイッチより優先されます。.npmrc がそのレジストリ用に持つトークンはそこにだけ送られます。別のものを使うには プラグイン → 発見 の npm レジストリ を変更するか、magpie plugin registry <url> を実行します(default で元に戻ります)。
    • git リポジトリは Bun が取得します:github:owner/repo[#ref]、git+https://…、owner/repo。
    • フォルダやファイルへのパスは、その場所から読み込まれます。
  • diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.html index 969f01a42..e1689589a 100644 --- a/site/public/docs/plugins.html +++ b/site/public/docs/plugins.html @@ -213,6 +213,7 @@ magpie quota # acme · Pro · 5h 37%
  • Installing.
    • An npm package is installed with bun add, with its install scripts left unrun, as OpenCode installs plugins. A dependency that needs a postinstall build won’t work.
    • +
    • Packages come from the npm registry you already use: the registry= in your ~/.npmrc, install.registry in ~/.bunfig.toml, or NPM_CONFIG_REGISTRY / BUN_CONFIG_REGISTRY in your shell, before the Mirrors in China switch. A token your .npmrc keeps for that registry is sent to it alone. To use another, change npm registry on Plugins → Discover, or run magpie plugin registry <url> (default goes back).
    • A git repository is fetched by Bun: github:owner/repo[#ref], git+https://… or owner/repo.
    • A path to a folder or file is loaded where it is.
  • diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.html index 1d5626cbc..282c51f07 100644 --- a/site/public/docs/zh/plugins.html +++ b/site/public/docs/zh/plugins.html @@ -213,6 +213,7 @@ magpie quota # acme · Pro · 5h 37%
  • 安装。
    • npm 包用 bun add 安装,不运行安装脚本,和 OpenCode 安装插件的方式一样。依赖 postinstall 构建的包无法使用。
    • +
    • 包从你已在用的 npm 源下载:~/.npmrc 里的 registry=、~/.bunfig.toml 里的 install.registry,或 shell 里的 NPM_CONFIG_REGISTRY / BUN_CONFIG_REGISTRY,优先于「国内镜像」开关。.npmrc 里为这个源保存的 token 只发给它。要换一个,在 插件 → 发现 里修改 npm 源,或运行 magpie plugin registry <url>(default 恢复默认)。
    • git 仓库由 Bun 拉取:github:owner/repo[#ref]、git+https://… 或 owner/repo。
    • 文件夹或文件的路径就地加载。