magpie icon indicating copy to clipboard operation
magpie copied to clipboard

registry.d: let a package outside the community list say what it is

Open MYCF711 opened this issue 1 month ago • 5 comments

What this adds

<config>/registry.d/*.json — a directory magpie reads alongside the plugin list it fetches. Each file holds one entry, or a {"plugins": [...]} list of them, in exactly the shape registry.json uses.

An entry whose package the fetched list already names replaces it; otherwise it is appended. Nothing else changes: the fetch, the six-hour in-memory hold, the disk cache, MAGPIE_PLUGIN_MARKET and the built-in copy all behave as they do now.

Why

A package outside magpie-community/plugins cannot present itself. The card falls back to the package name and shows no licence and no source link, because those come from the list:

// internal/plugin/market.go
func marketCache() string { return filepath.Join(appdir.Cache(), "plugin-market.json") }

Three routes exist today and I have now measured all three:

User configures Survives the next fetch Author maintains
Add an entry to the community list nothing yes a PR per package
Write the entry into the cache from the plugin nothing no the plugin
MAGPIE_PLUGIN_MARKET=<url> a variable yes a repository and a workflow

The second one I built and removed. It does not work, for a reason worth recording: market() returns the in-memory marketList for six hours before it looks at the disk at all, so a write from a plugin reaches a list the window has already drawn from. Measured after a clean relaunch with the WebView2 cache cleared:

20:48:59  magpie wrote plugin-market.json — the 38 fetched entries
20:50:01  the plugin registered its entry — 39 entries, ours included
          the card still reads the package name, no licence, no source link

And a plugin cannot patch the card itself. A page plugin is framed like this:

const f = document.createElement("iframe");
f.setAttribute("sandbox", "allow-scripts");   // no allow-same-origin
f.src = e.url;

An opaque origin cannot reach the card's DOM, and the slots themselves are app.js's (box.dataset.slot). So there is no plugin-side route to those two fields, by design.

That leaves a PR to the community list — which is fine for the packages magpie ships, less so for one somebody else maintains — or this.

The change

Three call sites, one helper:

marketList, marketAt, marketErr = mergeLocal(l), time.Now(), nil

at each of the three places a list is produced (the fetch, the disk fallback, the built-in copy), plus:

func localMarketDir() string { return filepath.Join(appdir.Config(), "registry.d") }

func mergeLocal(l []Listing) []Listing {
	names, err := filepath.Glob(filepath.Join(localMarketDir(), "*.json"))
	if err != nil || len(names) == 0 {
		return l
	}
	slices.Sort(names) // a stable order, so the same files give the same list
	// ... one entry or {"plugins": [...]}, putListing each
}

slices and appdir are already imported in this file. No new dependency.

Patch

Against main as of 2026-10-25T12:40:44Z:

--- a/internal/plugin/market.go
+++ b/internal/plugin/market.go
@@ -209,10 +209,10 @@ func market(ctx context.Context) ([]Listing, error) {
 		if err == nil {
 			l, perr := parseMarket(b)
 			if perr == nil {
-				marketList, marketAt, marketErr = l, time.Now(), nil
+				marketList, marketAt, marketErr = mergeLocal(l), time.Now(), nil
 				_ = os.MkdirAll(filepath.Dir(marketCache()), 0o755)
 				_ = os.WriteFile(marketCache(), b, 0o644)
-				return l, nil
+				return marketList, nil
 			}
 			err = perr
 		}
@@ -220,14 +220,14 @@ func market(ctx context.Context) ([]Listing, error) {
 		if b, err := os.ReadFile(marketCache()); err == nil {
 			if l, err := parseMarket(b); err == nil {
 				// tried again in a minute, not six hours
-				marketList, marketAt, marketErr = l, time.Now().Add(-6*time.Hour+time.Minute), ferr
-				return l, ferr
+				marketList, marketAt, marketErr = mergeLocal(l), time.Now().Add(-6*time.Hour+time.Minute), ferr
+				return marketList, ferr
 			}
 		}
 	}
 	l, _ := parseMarket(builtinMarket)
-	marketList, marketAt, marketErr = l, time.Now().Add(-6*time.Hour+time.Minute), ferr
-	return l, ferr
+	marketList, marketAt, marketErr = mergeLocal(l), time.Now().Add(-6*time.Hour+time.Minute), ferr
+	return marketList, ferr
 }
 
 // RefreshMarket has the next Market fetch the list again, as with the
@@ -238,6 +238,67 @@ func RefreshMarket() {
 	marketMu.Unlock()
 }
 
+// localMarketDir is where an author's own entries are read from:
+// <config>/registry.d/*.json, each holding one entry or a
+// {"plugins": [...]} list of them — the same shape registry.json uses.
+//
+// The fetched list replaces the cached copy wholesale, so a package
+// outside magpie-community/plugins cannot say what it is: its card falls
+// back to the package name and shows no licence or source link. Writing
+// into the cache does not survive the next fetch, and a plugin cannot
+// reach the card itself — the window has already drawn by the time one
+// loads, and a page plugin runs in an opaque origin.
+//
+// Reading a directory alongside the list is the smallest thing that
+// works: an author writes one file, it keeps working, and the official
+// list goes on updating as it does now.
+func localMarketDir() string { return filepath.Join(appdir.Config(), "registry.d") }
+
+// mergeLocal appends the local entries to l. An entry whose package l
+// already names is replaced rather than added twice, so a package that
+// later joins the community list does not show up as two.
+func mergeLocal(l []Listing) []Listing {
+	names, err := filepath.Glob(filepath.Join(localMarketDir(), "*.json"))
+	if err != nil || len(names) == 0 {
+		return l
+	}
+	slices.Sort(names) // a stable order, so the same files give the same list
+	for _, name := range names {
+		b, err := os.ReadFile(name)
+		if err != nil {
+			continue
+		}
+		var one Listing
+		if json.Unmarshal(b, &one) == nil && one.Package != "" {
+			l = putListing(l, one)
+			continue
+		}
+		var list registry
+		if json.Unmarshal(b, &list) != nil {
+			continue
+		}
+		for _, e := range list.Plugins {
+			if e.Package != "" {
+				l = putListing(l, e)
+			}
+		}
+	}
+	return l
+}
+
+// putListing has e replace the entry naming its package, or be appended
+// when none does.
+func putListing(l []Listing, e Listing) []Listing {
+	for i := range l {
+		if l[i].Package == e.Package {
+			l[i] = e
+			return l
+		}
+	}
+	return append(l, e)
+}
+
 func fetchJSON(ctx context.Context, u string, limit int64) ([]byte, error) {
 	return fetchJSONFrom(ctx, u, limit, source.Do)
 }

git apply clean against main; verified. No new import — slices, os, encoding/json, path/filepath and appdir are all already used in this file.

How an author would use it

mkdir -p ~/.config/magpie/registry.d
cat > ~/.config/magpie/registry.d/officeace-auth.json <<'EOF'
{
  "package": "officeace-auth",
  "name": "OfficeAce",
  "providers": ["officeace"],
  "community": true,
  "summary": {
    "en": "Unofficial: OfficeAce (Huawei Cloud AgentArts) coding plans…",
    "zh": "非官方:OfficeAce(华为云 AgentArts)编码套餐…"
  }
}
EOF

One file, written once. The card is complete from the next launch, and it stays complete when the fetched list is replaced.

If this is not the shape wanted

~/.config/magpie/registry.json — a single file rather than a directory — would do the same job with less surface. I went with the directory because it lets two packages add themselves without editing each other's file, but one file is simpler and I would not argue against it.

What I would ask for regardless of shape is that the fetched list stop being the only source: today a package's card depends on one repository it may have nothing to do with, and no amount of work on the package's side changes that.

MYCF711 avatar Oct 25 '26 13:10 MYCF711

Implemented on a branch: MYCF711/magpie → feat/registry-d, commit 401b3062, based on f8cd964a (= v0.1.1767).

git fetch https://github.com/MYCF711/magpie.git feat/registry-d

(No PR: pull requests to this repo answer 404 to the REST API and FORBIDDEN to GraphQL for this account — noted in #3926. The branch is the deliverable.)

What it does. <config>/registry.d/*.json is read alongside the fetched list: each file holds one entry, or a {"plugins": [...]} list of them, in registry.json's shape. An entry whose package the list already names replaces it rather than being added twice, so a package that later joins the community list does not show up as two. mergeLocal sits on all three returns of market() — a fresh fetch, the copy on disk, and the one built in — so the local entries are there whichever of the three you get.

Run at 401b3062: gofmt -l internal/ nothing; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... clean; go build ./..., GOOS=linux go build -tags nogui ./..., GOOS=windows go build ./... clean; go test ./internal/plugin/ ok.

A test that fails without the change: TestRegistryDAddsAndReplaces — one entry in a file, one {"plugins": [...]} list replacing a package the fetched list names, and a file that doesn't parse skipped while the rest still applies. With mergeLocal short-circuited to return the list unchanged it fails with

market_test.go:223: fetched entry not replaced: {Package:opencode-x-auth Name:X ...}
market_test.go:228: the local entry 0 times, the replaced one 1 times

docs/reference.md's file list gains registry.d/.

MYCF711 avatar Oct 27 '26 18:10 MYCF711

Thanks for the patch (MYCF711/magpie feat/registry-d, 401b3062) and for measuring the cache route. We reviewed it for security and decided not to take registry.d as written. Here is why.

Writing to <config>/registry.d takes code already running as the user, so this is not a privilege escalation. The problem is what the directory is for: a plugin, or its installer, writes its own entry there. In this patch, what it writes is trusted as much as the reviewed community list. Installing one unreviewed package doesn't mean agreeing to let it do the following (all of it read from 401b3062):

  1. It can claim the review badge. mergeLocal skips parseMarket's checks. A local entry with "community": true lands in Discover's "magpie community" sections with the shield and the tooltip "Written for magpie by its community, in github.com/magpie-community/plugins" (plugins.js l.community). So any package could present itself as reviewed.
  2. It can steer what a typed name installs. market() returns the merged list, and resolve() reads that list to turn a short name into a package (magpie plugin add <name>, and the GUI's install by name). package isn't checked against pkgName either. So a local entry can map a name to any spec, including github:… or a path. For a name the community list already uses, it makes the name ambiguous, and that install fails.
  3. It can rewrite a reviewed entry. putListing replaces the community entry with the same package outright. That changes its name, summary and replaces, or drops community so it disappears from Discover.

Hardening it until it's safe (forcing community off, dropping replaces/providers, checking pkgName, keeping it out of resolve, never replacing a listed package) leaves only a name, a summary and an icon for an installed card. Even that needs a file on every user's machine, and the "just works, with no setup" rule is against that.

What we'd take instead: the package describes itself in its own package.json, the same way magpie.icon, magpie.page and magpie.kind already work. For example, magpie.name and magpie.summary ({ "en": …, "zh": … }) would be read from npm (or from the repository for a GitHub install) and shown on that package's card. These would be shown as the package's own words, never with the community badge, and never used to resolve a name. The author keeps them up to date by publishing the package, every user sees them without setup, and nothing on disk can change the reviewed list. If you'd like to write that, we'll review it. The listing's licence and source link can come from npm's license and repository, which magpie already reads.

I'll leave this issue open for discussion of that route.

yetone avatar Oct 27 '26 19:10 yetone

Thank you — the three ways it could be abused are the three I had not thought through, and resolve() reading the merged list is the one I would have shipped. The config folder was the wrong place to put a name; the package is.

Implemented your route on a branch: MYCF711/magpie → feat/magpie-name-summary, commit 1cc33700, based on e4ccf67b.

git fetch https://github.com/MYCF711/magpie.git feat/magpie-name-summary

What it does. "magpie": { "name": "OfficeAce", "summary": { "en": "…", "zh": "…" } } in a package's package.json, read the way magpie.icon is: from npm's copy of the package when it is published there, else from the repository (readTagged), and from the installed package's own folder (plugin.InstalledName). Shown on the card under Discover → Unofficial, and magpie.name on the row in Settings → Plugins. Nothing else moves: resolve() is untouched, the community's list is untouched, a package the list names is listed by that list, and registry.d is not in this branch at all.

Two decisions you may want to argue with:

  • The row as well as the card. You said the card; I also used magpie.name for the row in Settings → Plugins, because an installed package outside the list only ever appears as a row, and it read magpie-officeace there. One field, two places.
  • The bounds. A name is one line, at most 80 bytes. A summary is a sentence a language, at most 300 bytes, no newlines, under any language key the page names (en, zh, …). Anything else is ignored rather than put on a card. Those limits are mine and not measured — say if you want different ones.

Both are shown as the package's own words: a chip that says so, with "nobody reviewed them" behind it, and never the community badge.

Verified at 1cc33700 (go1.26.8, Windows 11):

  • A test that fails without the change: TestReadTaggedOwnWords, TestNPMKeepsItsOwnWords, TestOwnWordsBounds and TestInstalledName. With ownName/ownSummary returning nothing they print name "", want OfficeAce and summary map[], want both languages; with readTagged not keeping what it reads, the same. plugin-own-words.test.cjs (Chromium and WebKit, en and zh) prints actual: 'magpie-officeace', expected: 'OfficeAce' without the front-end change.
  • gofmt -l on the changed files prints nothing; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... clean; go build ./..., GOOS=linux go build -tags nogui ./..., GOOS=windows go build ./... clean; go test -tags nogui ./internal/plugin/ ok.
  • internal/gui has five tests red here — TestGatewayHeldByAContainer, TestLodyImportHandoff (%AppData% is not defined), TestImportStatusUnreadableIsUnknown, TestAionUiImportRow, TestUpdateThatWontStart (%1 is not a valid Win32 application) — and red the same with this change stashed on e4ccf67b. They are not this change's; I have not fixed them.
  • Not tried: a real repository whose package.json has magpie.name — I read all 175 tagged ones and none has one yet, so the field is exercised from fixtures only — and the desktop window itself: the card was checked in Playwright's Chromium and WebKit.

docs/reference.md's "For plugin authors" now says what the two fields are and what the limits are.

MYCF711 avatar Oct 27 '26 20:10 MYCF711

This landed in 1cc33700 (Oct 28): package.json now carries magpie: { name, summary }, read from npm's copy of the package (or from the repository for a GitHub install) and from the installed package's own folder, then shown as the package's own words — never with the community badge, and never used to resolve a name.

Verified on this machine just now: [email protected]'s package.json carries the block, and magpie's plugin list shows OfficeAce 0.1.14 with its own name rather than the repository name.

Closing — the field is in the package, so a package outside the community list no longer needs an environment variable to have a complete card.

MYCF711 avatar Oct 29 '26 16:10 MYCF711

Landed in cbb09383f, released in v0.1.2969. This ports your 1cc337001. A repository tagged magpie-plugin that isn't on the community list now shows its own words on its card under Discover → Unofficial, on GitHub:

  • the name comes from magpie.name in its package.json;
  • the summary comes from magpie.summary, by language;
  • when the card installs from npm and npm's copy says them, npm's words are used.

The card marks them with an "Its own words" chip whose tip says nobody reviewed them. They get no community badge and never resolve a name. GitHub's description stays the English line when the summary has none.

Changed from 1cc337001:

  • The summary is read as raw JSON. A "summary": "text" no longer fails the whole package.json parse and drops the repository from the list.
  • Control and format characters are refused. Bidi overrides, zero-width spaces and bad UTF-8 are not shown, as main's ownName already does.
  • No budget raise. The card's code was paid for by cutting comments.
  • Left out: the row chip and InstalledName, which main has had since d8cf4f74f, and NPM.Name/Summary, which no page reads.

Not tried: a real repository with magpie.summary, since none tagged has one yet. Docs: docs/reference.md and the plugins page on the site (en, zh, ja).

yetone avatar Nov 04 '26 15:11 yetone