diff --git a/apps/web/contents/addons/api.mdx b/apps/web/contents/addons/api.mdx index e8ddec0..cab0e6e 100644 --- a/apps/web/contents/addons/api.mdx +++ b/apps/web/contents/addons/api.mdx @@ -26,6 +26,7 @@ The single `nextguide` package now exposes these building blocks: | `nextguide/extensions/artifacts` | Read-only v1 content archive verifier: signature, exact release size/hash and safe tar members; does not install or execute files | | `nextguide/extensions/download` | Strict signed GitHub artifact downloader with pinned public-IPv4 DNS, TLS, and limited trusted GitHub CDN redirects | | `nextguide/extensions/install-state` | Server-only Account Mode journal for signed v1 content releases, version pinning, disable, verified rollback, and uninstall without executing code | +| `nextguide/extensions/site-manager` | Owner-authenticated host-side orchestration: signed discovery, safe download, lifecycle actions and revision checks | | `nextguide/extensions/network` | Restricted, host-only outbound HTTPS adapter with pinned DNS and response limits | | `nextguide/extensions/isolation` | Experimental Linux bubblewrap/prlimit process launcher for SHA-256-pinned compiled modules; no Windows or automatic fallback | diff --git a/apps/web/contents/addons/marketplace.mdx b/apps/web/contents/addons/marketplace.mdx index b095f33..9049dae 100644 --- a/apps/web/contents/addons/marketplace.mdx +++ b/apps/web/contents/addons/marketplace.mdx @@ -1,41 +1,42 @@ --- -title: Account Mode add-on discovery -description: Read-only verified registry browsing in the Account Mode studio; installation is still planned. +title: Account Mode marketplace +description: Browse signed content add-ons, manage reviewed versions and understand executable-extension restrictions. --- # Account Mode add-ons - -The Account Mode studio now includes **Add-ons** in the sidebar. Once configured, it can browse current approved **content-only v1** registry releases, filter categories, search publishers and open a full add-on detail view. Listings are verified with the site's pinned Ed25519 key on the server before being shown. **Install, enable, update and uninstall are not implemented.** + +The Account Mode studio now supports signed **content-only v1** add-on installation, version pinning, enable/disable state, verified updates, rollback and uninstall. These actions are available only to a signed-in site owner and require the independent registry's Ed25519 signature. **Installed content is stored privately but is not yet automatically mounted as public documentation pages.** Executable v2 add-ons remain disabled. -## Connect the signed catalog +## Connect a reviewed registry -Set the following environment variables on your persistent Account Mode Next.js server: +Configure the trusted catalog on a persistent Account Mode Node server: - + -The Base64 value is the trusted registry's **public** Ed25519 PEM key, encoded as UTF-8 then Base64. Obtain the exact public key through a trusted, independent channel; never accept a signing key merely because an unsigned registry response supplied it. Do not put the registry configuration in a `NEXT_PUBLIC_` variable. +The Base64 value contains a PEM-format **public** key, retrieved through a separately trusted channel. Never load the signing key from unsigned registry metadata or expose the configuration through a `NEXT_PUBLIC_` variable. Your `NEXTGUIDE_DATA_DIR` must point outside the Next.js site, and the runtime must have access to its own persistent private storage. -If those variables are missing, the Add-ons page explains that the catalog connection is not configured. If the signature or endpoint is invalid, the server rejects the response; it never falls back to unsigned data. Only a logged-in Account Mode owner can access the discovery API. +The registry must issue a newly signed index at least once an hour: stale metadata refuses installation, enabling and rollback, rather than silently using potentially revoked information. -## Current and future actions +## Install and manage content -| Action | Status | -| --- | --- | -| Discover | Search and filter approved content-only releases in Account Mode | -| Inspect | Full detail view with author, signed release, compatibility, license and requested permissions | -| Install | Planned: verify artifact bytes, request permission approval and persist installed state | -| Configure | Planned: store scoped settings and trusted credential handles | -| Enable/disable | Planned: start and stop a reviewed extension safely | -| Update | Planned: permission-diff review and transactional integrity checks | -| Rollback | Planned: restore a previously reviewed, compatible version | -| Uninstall | Planned: remove files safely, with a private-data retention choice | +1. Sign in to Account Mode and open **Add-ons**. +2. Search or filter reviewed releases and open **View details**. +3. Check publisher identity, license, NextGuide compatibility and requested permissions. +4. Confirm **Install reviewed content**. The site downloads only the signed GitHub Release and verifies its bytes before writing immutable files to private storage. +5. Use **Enable/Disable** to change the stored content state. The public docs integration is a separate milestone; enabling does not automatically publish pages yet. +6. Use **Update** when a higher reviewed version is available, or **Roll back** to a previously saved, still-approved version. Rollback leaves the add-on disabled for explicit re-enabling. +7. **Uninstall** clears its installed entry but preserves separate private settings and historical archive blobs for recovery. -The existing extension capability broker, isolated runner prototype and signed content archive verifier are foundations. They do not make executable marketplace add-ons safe to install today. + +Published v1 examples currently declare NextGuide `>=1.0.0 <2.0.0`. A site still running `0.0.1-alpha.2` is intentionally shown as **incompatible**, not allowed to bypass the publisher's declared version range. This is a release gate, not a failed install. Code-capable extensions, React widgets, secret handles and server jobs still require additional review, sandbox hardening and permission approvals. + + +## Security and rollback -## Security requirements before executable add-ons +The server validates owner sessions and request origin on every mutation. Installed data is never placed in `content/docs` or public assets. The journal checks the signed release metadata, exact SHA-256, compatible package version and current approval status. Conflicting update requests are rejected using an installation revision, and a damaged archive cannot be enabled. -Executable add-ons require independent code review, properly signed v2 artifacts, hardened OS sandboxing and resource controls, and browser-frame isolation for custom React components. The private registry service remains separately deployed and is **not** part of this public repository. +The UI uses NextGuide's native Account Mode components. No Docker requirement or new npm package is introduced. -Track implementation in [roadmap issue #101](https://github.com/m1nsook/NextGuide/issues/101). To publish a currently supported content add-on, start with [Getting started](/addons/getting-started). +See [Updates and removal](/addons/updates), [Security and permissions](/addons/permissions), and [runtime API](/addons/api). Follow [roadmap #101](https://github.com/m1nsook/NextGuide/issues/101) for executable v2 and public rendering integration. diff --git a/apps/web/contents/addons/updates.mdx b/apps/web/contents/addons/updates.mdx index 37347d2..43fc6fd 100644 --- a/apps/web/contents/addons/updates.mdx +++ b/apps/web/contents/addons/updates.mdx @@ -1,34 +1,39 @@ --- -title: Updates & removal -description: Publish new versions, revoke old releases and understand add-on withdrawal. +title: Updates and removal +description: Publisher updates, Account Mode version pinning and verified rollback for content add-ons. --- # Updates and removal -NextGuide keeps GitHub release artifacts immutable. Every update is independently checked and must be manually approved before it becomes available in the signed catalog. +## Publisher workflow -## Publish an update +Every new add-on version requires its own independently reviewed immutable GitHub Release, committed source provenance and signed registry approval. -1. Update the add-on files and increase `version` in `nextguide-addon.json`. -2. Commit and push changes to the same GitHub repository. -3. Open the [NextGuide Publisher GitHub App](https://github.com/apps/nextguide-publisher) and select the repository through its publisher portal. -4. Validate the release and submit the new version. -5. Check the pending review and wait for approval. +1. Increase `version` in `nextguide-addon.json`. +2. Commit and push the changed files to the source repository. +3. Open the [NextGuide Publisher GitHub App](https://github.com/apps/nextguide-publisher) and select the repository. +4. Validate and submit the new version for independent review. +5. Wait for the signed registry to contain the approved release. - +Do not overwrite existing GitHub Release assets to make a silent change. Create a new version instead. -## Removing a published add-on +## Account Mode installation lifecycle -A verified publisher can withdraw their own add-on; authorized moderation can revoke releases. These are **catalog actions**: approved versions are marked revoked in the signed index, and pending submissions are withdrawn. +The owner-facing **Add-ons** page can install, enable/disable, update, roll back and uninstall **content-only v1** releases when the site's NextGuide package satisfies their declared compatibility range. -Removal does **not** silently delete GitHub Releases, erase the review audit log, or uninstall copies already installed on user sites. +| Action | What happens | +| --- | --- | +| Install | Recheck signed registry, verify exact remote archive and place content in private storage, initially disabled | +| Enable | Recheck latest signed approval and local integrity before marking content enabled | +| Disable | Mark content disabled without deleting settings | +| Update | Recheck the newer reviewed version, then atomically advance the pinned version | +| Rollback | Verify an already stored, still-approved version and restore it in a disabled state | +| Uninstall | Remove the installed record; preserve private add-on settings and historical blobs for recovery | -## Future in-site update manager +Owner authentication and same-origin checks apply to every mutation. A concurrent change requires refreshing the page rather than overwriting another update. A revoked or stale release cannot be reactivated or rolled back. -Account Mode's planned marketplace will separately support installing, enabling, disabling, updating, rolling back and uninstalling add-ons. It must verify the artifact digest, compatible NextGuide version, signed catalog and permissions, and must handle revoked releases safely. - - -The [publisher GitHub App](https://github.com/apps/nextguide-publisher) is for **developers**. The planned marketplace belongs inside **each site's own Account Mode dashboard**. + +The Account Mode site does not yet mount installed Markdown pages into public documentation. Executable add-ons, privileged permissions, secrets, React components and automatic background update checks remain future milestones. Legacy v1 content is never compiled as untrusted MDX. -Read [Marketplace (planned)](/addons/marketplace) and [Permissions & security](/addons/permissions). +For details see [Account Mode marketplace](/addons/marketplace) and [runtime API](/addons/api). diff --git a/packages/nextguide/lib/account-studio-template.mjs b/packages/nextguide/lib/account-studio-template.mjs index 421c839..22970e4 100644 --- a/packages/nextguide/lib/account-studio-template.mjs +++ b/packages/nextguide/lib/account-studio-template.mjs @@ -3,7 +3,7 @@ const STUDIO_API = `// Generated by NextGuide CLI. Edit freely; NextGuide never overwrites these files. import { ACCOUNT_COOKIE, AccountError, verifySession, sameOrigin } from "nextguide/account/server" import { listStudioPages, readStudioPage, saveStudioPage, deleteStudioPage, getStudioNavigation, setStudioNavigation, getStudioSettings, saveStudioSettings, listStudioMedia, uploadStudioMedia, deleteStudioMedia } from "nextguide/account/cms" -import { createVerifiedRegistryClient } from "nextguide/extensions/catalog" +import { createAccountAddonManager } from "nextguide/extensions/site-manager" function response(data__DATA_TYPE__, status = 200) { @@ -32,6 +32,24 @@ async function body(request__REQUEST_TYPE__, limit = 3_000_000) { } function errorResponse(error__ERROR_TYPE__) { if (error instanceof AccountError) return response({ error: error.message }, error.status) + const allowed = new Map([ + ["INVALID_REQUEST",400], ["CONSENT_REQUIRED",403], ["INCOMPATIBLE",409], + ["NOT_APPROVED",409], ["DOWNGRADE",409], ["NOT_INSTALLED",404], ["CONFLICT",409], + ["CAPACITY",409], ["PERMISSION_DENIED",403], ["STALE_CATALOG",503], ["BUSY",503], + ["MODE_DENIED",403], ["MISSING_ARTIFACT",409], ["CORRUPT_ARTIFACT",409], + ["NO_REGISTRY",503], ["UNSAFE_STORAGE",503], ["DAMAGED_STATE",503], + ]) + const code = error && typeof error === "object" && "code" in error ? String(error.code) : "" + if (allowed.has(code)) { + const safe = new Map([ + ["CONFLICT","Add-on state changed. Refresh and try again."], + ["NOT_APPROVED","This release is not approved, is revoked or is incompatible."], + ["STALE_CATALOG","The signed registry metadata needs to be refreshed."], + ["INCOMPATIBLE","This add-on is incompatible with your installed NextGuide version."], + ["CONSENT_REQUIRED","Confirm the requested installation change before continuing."], + ]) + return response({ error: safe.get(code) || "Add-on operation denied (" + code + ")." }, allowed.get(code) || 503) + } console.error("[nextguide/studio] Studio error", error instanceof Error ? error.name : "Unknown") return response({ error: "Studio service failed. Check server logs." }, 503) } @@ -50,12 +68,7 @@ export async function GET(request__REQUEST_TYPE__, { params }__PARAM_TYPE__) { media: listStudioMedia(process.cwd()), }) if (action === "addons") { - const registryUrl = process.env.NEXTGUIDE_ADDON_REGISTRY_URL - const encodedPublicKey = process.env.NEXTGUIDE_ADDON_REGISTRY_PUBLIC_KEY_B64 - if (!registryUrl || !encodedPublicKey) return response({ configured: false, releases: [] }) - const pinnedPublicKeyPem = Buffer.from(encodedPublicKey, "base64").toString("utf8") - const registry = createVerifiedRegistryClient({ registryUrl, pinnedPublicKeyPem }) - return response({ configured: true, releases: await registry.listApproved() }) + return response(await createAccountAddonManager({ project: process.cwd() }).catalog()) } if (action === "page") return response(readStudioPage(process.cwd(), url.searchParams.get("slug") ?? "")) if (action === "navigation") return response(getStudioNavigation(process.cwd(), url.searchParams.get("folder") ?? "")) @@ -69,9 +82,17 @@ export async function POST(request__REQUEST_TYPE__, { params }__PARAM_TYPE__) { if (!authorized(request)) return response({ error: "Sign in to access the editor." }, 401) if (!sameOrigin(request)) return response({ error: "Invalid origin." }, 403) const action = (await params).action - if (!["save-page","delete-page","save-settings","save-navigation","upload-media","delete-media"].includes(action)) + if (!["save-page","delete-page","save-settings","save-navigation","upload-media","delete-media","addon-install","addon-toggle","addon-rollback","addon-uninstall"].includes(action)) return response({ error: "Not found" }, 404) const input = await body(request, action === "upload-media" ? 3_000_000 : 450_000) + if (action.startsWith("addon-")) { + const addons = createAccountAddonManager({ project: process.cwd() }) + if (action === "addon-install") return response(await addons.install(input)) + if (action === "addon-toggle") return response(await addons.toggle(input)) + if (action === "addon-rollback") return response(await addons.rollback(input)) + if (action === "addon-uninstall") return response(addons.uninstall(input)) + return response({ error: "Not found" }, 404) + } if (action === "save-page") return response(saveStudioPage(process.cwd(), input)) if (action === "delete-page") return response(deleteStudioPage(process.cwd(), input.slug, input.version)) if (action === "save-settings") return response(saveStudioSettings(process.cwd(), input)) diff --git a/packages/nextguide/lib/extension-catalog.mjs b/packages/nextguide/lib/extension-catalog.mjs index ed01af1..7009cd0 100644 --- a/packages/nextguide/lib/extension-catalog.mjs +++ b/packages/nextguide/lib/extension-catalog.mjs @@ -120,7 +120,7 @@ export function createVerifiedRegistryClient({ registryUrl, pinnedPublicKeyPem, const publicKey = createPublicKey(pinnedPublicKeyPem) if (publicKey.asymmetricKeyType !== "ed25519") fail("Pinned key must be Ed25519") return { - async fetchVerified() { + async fetchSignedEnvelope() { const response = await fetchImpl(url.toString(), { method: "GET", redirect: "error", cache: "no-store", signal: AbortSignal.timeout(8000), @@ -142,7 +142,11 @@ export function createVerifiedRegistryClient({ registryUrl, pinnedPublicKeyPem, let envelope try { envelope = JSON.parse(Buffer.concat(chunks).toString("utf8")) } catch { fail("Invalid registry response JSON") } - return verifySignedRegistryEnvelope(envelope, pinnedPublicKeyPem) + verifySignedRegistryEnvelope(envelope, pinnedPublicKeyPem) + return envelope + }, + async fetchVerified() { + return verifySignedRegistryEnvelope(await this.fetchSignedEnvelope(), pinnedPublicKeyPem) }, async listApproved() { return listVerifiedAddons(await this.fetchVerified()) diff --git a/packages/nextguide/lib/extension-site-manager.d.mts b/packages/nextguide/lib/extension-site-manager.d.mts new file mode 100644 index 0000000..d5dda3d --- /dev/null +++ b/packages/nextguide/lib/extension-site-manager.d.mts @@ -0,0 +1,66 @@ +import type { InstalledAddon } from "./extension-install-state.mjs" +export type AccountAddonCatalog = { + configured: boolean + catalogFresh: boolean + releases: Array<{ + manifest: { + id: string + name: string + version: string + category: string + compatibility: { mode: "account"; nextguide: string } + permissions: string[] + } + compatible: boolean + digest: string + size: number + reviewer: string + status: string + [key: string]: unknown + }> + installed: { revision: number; addons: InstalledAddon[] } + nextguideVersion: string +} +export declare function createAccountAddonManager(options?: { + project?: string + dataDir?: string + /** Trusted test override; installed package version is used by default. */ + nextguideVersion?: string + registryUrl?: string + pinnedPublicKeyPem?: string + now?: () => number + registryFetch?: typeof fetch + resolver?: (...args: any[]) => Promise> + transport?: (...args: any[]) => any +}): { + catalog(): Promise + install(input: { + id: string + version: string + expectedRevision: number + consent: true + }): Promise<{revision: number; addon: InstalledAddon}> + toggle(input: { + id: string + enabled: boolean + expectedRevision: number + }): Promise<{revision: number; addon: InstalledAddon}> + rollback(input: { + id: string + version: string + expectedRevision: number + consent: true + }): Promise<{revision: number; addon: InstalledAddon}> + uninstall(input: { + id: string + expectedRevision: number + consent: true + }): {revision: number; removed: string; privateDataPreserved: true} + readEnabled(input: {id: string}): Promise + icon: { path: string; bytes: Buffer } + pages: Array<{ path: string; markdown: string }> + }> +} diff --git a/packages/nextguide/lib/extension-site-manager.mjs b/packages/nextguide/lib/extension-site-manager.mjs new file mode 100644 index 0000000..973cda4 --- /dev/null +++ b/packages/nextguide/lib/extension-site-manager.mjs @@ -0,0 +1,124 @@ +/** + * Account Mode-only orchestration for approved, Markdown-only v1 add-ons. + * Import only from trusted, owner-authenticated Next.js server routes. + * + * The private ngapi catalog signs releases; this service never handles + * signing secrets or runs any code downloaded from the registry. + */ +import { createRequire } from "node:module" +import { createVerifiedRegistryClient, verifySignedRegistryEnvelope, + listVerifiedAddons } from "./extension-catalog.mjs" +import { downloadVerifiedContentRelease } from "./extension-download.mjs" +import { createAccountAddonStore, compatibleAddonRange } from "./extension-install-state.mjs" + +const require = createRequire(import.meta.url) +const VERSION = require("../package.json").version +const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*\.[a-z0-9]+(?:-[a-z0-9]+)*$/ +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/ +const MAX_FRESHNESS = 60 * 60 * 1000 + +function reject(code,message) { + const error = new Error("NextGuide add-on manager: " + message) + error.code = code + throw error +} +function approvedInput(id, version, expectedRevision) { + if (typeof id !== "string" || !ID.test(id) || + (version !== undefined && (typeof version !== "string" || !SEMVER.test(version))) || + !Number.isSafeInteger(expectedRevision) || expectedRevision < 0) { + reject("INVALID_REQUEST", "Invalid release identity or installation revision") + } +} +export function createAccountAddonManager({ + project = process.cwd(), + dataDir, + nextguideVersion = VERSION, + registryUrl = process.env.NEXTGUIDE_ADDON_REGISTRY_URL, + pinnedPublicKeyPem = process.env.NEXTGUIDE_ADDON_REGISTRY_PUBLIC_KEY_B64 + ? Buffer.from(process.env.NEXTGUIDE_ADDON_REGISTRY_PUBLIC_KEY_B64,"base64").toString("utf8") : "", + now = () => Date.now(), + registryFetch, + resolver, + transport, +} = {}) { + const store = createAccountAddonStore({project,dataDir,nextguideVersion,now}) + const configured = typeof registryUrl === "string" && registryUrl.length > 0 && + typeof pinnedPublicKeyPem === "string" && pinnedPublicKeyPem.length > 0 + const registry = configured ? createVerifiedRegistryClient({ + registryUrl,pinnedPublicKeyPem,...(registryFetch?{fetchImpl:registryFetch}:{}) + }) : null + + async function signed({requireFresh=true}={}) { + if (!registry) reject("NO_REGISTRY", "Trusted signed registry is not configured") + const envelope = await registry.fetchSignedEnvelope() + const payload = verifySignedRegistryEnvelope(envelope,pinnedPublicKeyPem) + const age = now() - Date.parse(payload.updatedAt) + const catalogFresh = Number.isFinite(age) && age <= MAX_FRESHNESS && age >= -5*60*1000 + if (requireFresh && !catalogFresh) { + reject("STALE_CATALOG", "Registry release catalog must be signed within the last hour") + } + return {envelope,payload,catalogFresh} + } + function requireConsent(value) { + if (value !== true) reject("CONSENT_REQUIRED", "Explicit site-owner consent is required") + } + + return { + async catalog() { + const installed=store.list() + if (!registry) return {configured:false,releases:[],installed, + nextguideVersion,catalogFresh:false} + const {payload,catalogFresh}=await signed({requireFresh:false}) + return { + configured:true, + releases:listVerifiedAddons(payload).map(release=>({ + ...release, + compatible:compatibleAddonRange( + release.manifest.compatibility.nextguide,nextguideVersion) + })), + installed,nextguideVersion,catalogFresh, + } + }, + async install({id,version,expectedRevision,consent}={}) { + approvedInput(id,version,expectedRevision) + requireConsent(consent) + const {envelope,payload}=await signed() + const release=payload.releases.find(r=>r.manifest.id===id&&r.manifest.version===version) + if (!release || release.status!=="active" || release.manifest.schemaVersion!==1 || + release.manifest.category!=="content" || release.manifest.permissions.length!==0 || + !compatibleAddonRange(release.manifest.compatibility.nextguide,nextguideVersion)) { + reject("NOT_APPROVED", "Release is not reviewed, active or compatible with this NextGuide") + } + // No arbitrary caller URL: the signed envelope supplies the only URL. + const archive=await downloadVerifiedContentRelease({ + envelope,pinnedPublicKeyPem,id,version, + ...(resolver?{resolver}:{}),...(transport?{transport}:{}) + }) + return store.install({envelope,pinnedPublicKeyPem,id,version,archive,expectedRevision}) + }, + async toggle({id,enabled,expectedRevision}={}) { + approvedInput(id,undefined,expectedRevision) + if (typeof enabled!=="boolean") reject("INVALID_REQUEST","Expected enable/disable state") + if (!enabled) return store.setEnabled({id,enabled:false,expectedRevision}) + const {envelope}=await signed() + return store.setEnabled({id,enabled:true,expectedRevision,envelope,pinnedPublicKeyPem}) + }, + async rollback({id,version,expectedRevision,consent}={}) { + approvedInput(id,version,expectedRevision) + requireConsent(consent) + const {envelope}=await signed() + return store.rollback({id,version,expectedRevision,envelope,pinnedPublicKeyPem}) + }, + uninstall({id,expectedRevision,consent}={}) { + approvedInput(id,undefined,expectedRevision) + requireConsent(consent) + return store.uninstall({id,expectedRevision}) + }, + /** Privileged API for a future safe Markdown-only public page adapter. */ + async readEnabled({id}={}) { + if (typeof id!=="string" || !ID.test(id)) reject("INVALID_REQUEST","Invalid add-on ID") + const {envelope}=await signed() + return store.readEnabled({id,envelope,pinnedPublicKeyPem}) + }, + } +} diff --git a/packages/nextguide/package.json b/packages/nextguide/package.json index d99a1e4..1a3acce 100644 --- a/packages/nextguide/package.json +++ b/packages/nextguide/package.json @@ -16,9 +16,9 @@ ], "scripts": { "build": "node scripts/build.mjs", - "test": "node scripts/build.mjs && node --test test/cli-ui.test.mjs test/account-ui-isolation.test.mjs test/account-semantics-icons.test.mjs test/doctor.test.mjs test/init.test.mjs test/distribution.test.mjs test/page.test.mjs test/page-cli.test.mjs test/version.test.mjs test/upgrade.test.mjs test/account-auth.test.mjs test/account-init.test.mjs test/account-cms.test.mjs test/extensions.test.mjs test/extension-runtime.test.mjs test/extension-storage.test.mjs test/extension-catalog.test.mjs test/extension-network.test.mjs test/extension-isolation.test.mjs test/extension-artifacts.test.mjs test/extension-install-state.test.mjs test/extension-download.test.mjs test/docs-chatgpt.test.mjs", + "test": "node scripts/build.mjs && node --test test/cli-ui.test.mjs test/account-ui-isolation.test.mjs test/account-semantics-icons.test.mjs test/doctor.test.mjs test/init.test.mjs test/distribution.test.mjs test/page.test.mjs test/page-cli.test.mjs test/version.test.mjs test/upgrade.test.mjs test/account-auth.test.mjs test/account-init.test.mjs test/account-cms.test.mjs test/extensions.test.mjs test/extension-runtime.test.mjs test/extension-storage.test.mjs test/extension-catalog.test.mjs test/extension-network.test.mjs test/extension-isolation.test.mjs test/extension-artifacts.test.mjs test/extension-install-state.test.mjs test/extension-download.test.mjs test/extension-site-manager.test.mjs test/docs-chatgpt.test.mjs", "test:dist": "node --test test/distribution.test.mjs", - "prepack": "node scripts/build.mjs && node --test test/cli-ui.test.mjs test/account-ui-isolation.test.mjs test/account-semantics-icons.test.mjs test/doctor.test.mjs test/init.test.mjs test/distribution.test.mjs test/page.test.mjs test/page-cli.test.mjs test/version.test.mjs test/upgrade.test.mjs test/account-auth.test.mjs test/account-init.test.mjs test/account-cms.test.mjs test/extensions.test.mjs test/extension-runtime.test.mjs test/extension-storage.test.mjs test/extension-catalog.test.mjs test/extension-network.test.mjs test/extension-isolation.test.mjs test/extension-artifacts.test.mjs test/extension-install-state.test.mjs test/extension-download.test.mjs test/docs-chatgpt.test.mjs", + "prepack": "node scripts/build.mjs && node --test test/cli-ui.test.mjs test/account-ui-isolation.test.mjs test/account-semantics-icons.test.mjs test/doctor.test.mjs test/init.test.mjs test/distribution.test.mjs test/page.test.mjs test/page-cli.test.mjs test/version.test.mjs test/upgrade.test.mjs test/account-auth.test.mjs test/account-init.test.mjs test/account-cms.test.mjs test/extensions.test.mjs test/extension-runtime.test.mjs test/extension-storage.test.mjs test/extension-catalog.test.mjs test/extension-network.test.mjs test/extension-isolation.test.mjs test/extension-artifacts.test.mjs test/extension-install-state.test.mjs test/extension-download.test.mjs test/extension-site-manager.test.mjs test/docs-chatgpt.test.mjs", "test:unit": "bunx vitest run", "check-types": "node scripts/build.mjs" }, @@ -194,6 +194,11 @@ "types": "./lib/extension-download.d.mts", "node": "./lib/extension-download.mjs", "default": "./lib/extension-download.mjs" + }, + "./extensions/site-manager": { + "types": "./lib/extension-site-manager.d.mts", + "node": "./lib/extension-site-manager.mjs", + "default": "./lib/extension-site-manager.mjs" } }, "imports": { diff --git a/packages/nextguide/src/account/addon-marketplace.tsx b/packages/nextguide/src/account/addon-marketplace.tsx index a5909a6..8c11de4 100644 --- a/packages/nextguide/src/account/addon-marketplace.tsx +++ b/packages/nextguide/src/account/addon-marketplace.tsx @@ -1,7 +1,14 @@ "use client" import * as React from "react" -import { ArrowLeft, ExternalLink, PackageCheck, Puzzle, Search, ShieldCheck } from "lucide-react" +import { + ArrowLeft, ExternalLink, PackageCheck, Power, Puzzle, RotateCcw, + Search, ShieldCheck, Trash2, +} from "lucide-react" +import { + AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, + AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, +} from "./ui/alert-dialog.js" import { Badge } from "./ui/badge.js" import { Button } from "./ui/button.js" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card.js" @@ -29,108 +36,301 @@ type Release = { digest: string size: number assetUrl: string + compatible: boolean } -type Catalog = { configured: boolean; releases: Release[] } +type InstalledAddon = { + id: string + enabled: boolean + version: string + name: string + availableVersions: string[] +} +type Catalog = { + configured: boolean + catalogFresh: boolean + releases: Release[] + installed: { revision: number; addons: InstalledAddon[] } + nextguideVersion: string +} +type Action = + | { kind: "install"; id: string; version: string } + | { kind: "toggle"; id: string; enabled: boolean } + | { kind: "rollback"; id: string; version: string } + | { kind: "uninstall"; id: string } -function ReleaseDetails({ release, back }: { release: Release; back: () => void }) { +function ReleaseDetails({ release, back, installed, onAction, busy, catalogFresh }: { + release: Release + back: () => void + installed?: InstalledAddon + onAction: (action: Action) => void + busy: boolean + catalogFresh: boolean +}) { const { manifest: addon } = release + const canInstall = catalogFresh && release.compatible && addon.permissions.length === 0 + const newer = (a: string, b: string) => a.split(".").map(Number).some((n,i,all) => + all.slice(0,i).every((v,j)=>v===Number(b.split(".")[j])) && n>Number(b.split(".")[i])) + const canUpdate = installed && canInstall && newer(addon.version, installed.version) return
- +
-
+
+
-

{addon.name}

v{addon.version}Signed release
-

{addon.summary || addon.description || "Verified content add-on"}

+
+

{addon.name}

+ v{addon.version} + Signed release + {installed && Installed v{installed.version}} +
+

{addon.summary || addon.description || "Reviewed content add-on"}

{addon.id}

- About this add-on{addon.category} · {addon.author?.name || "Independent publisher"} + About this add-on + {addon.category} · {addon.author?.name || "Independent publisher"} +

{addon.description || addon.summary || "No description supplied."}

- Source repository + + Source repository + +

This preview accepts reviewed plain Markdown content only. + Installed add-on pages are not yet automatically mounted into the public documentation.

- Release information
-
Compatibility
{addon.compatibility.nextguide || "Unspecified"}
-
License
{addon.license || "Not supplied"}
-
Reviewed by
{release.reviewer}
-
Permissions
{addon.permissions.length ? addon.permissions.join(", ") : "No additional capabilities"}
-
-

Catalog browsing is available. Site installation, updates and rollback have not been enabled.

+ Release information +
+
Compatibility
+
{addon.compatibility.nextguide || "Unspecified"} {release.compatible ? "· Compatible" : "· Not compatible"}
+
License
{addon.license || "Not supplied"}
+
Reviewed by
{release.reviewer}
+
Permissions
+
{addon.permissions.length ? addon.permissions.join(", ") : "No additional capabilities"}
+
+ + {installed ? <> + + {canUpdate && } + {installed.availableVersions.filter(v=>v!==installed.version).map(version=> + + )} + + : } + {!canInstall &&

+ This release is incompatible with your installed NextGuide version or requests unsupported capabilities. +

} +

No JavaScript is executed. Enabling stores content state; + public page mounting remains a separate milestone.

+
} -/** Account Mode-only, owner-authenticated discovery of signed v1 releases. */ +function actionDescription(action: Action | null) { + if (!action) return "" + if (action.kind === "install") return "Install the signed, reviewed content release " + action.id + + " at version " + action.version + "? It requests no additional capabilities. Content will be stored privately." + if (action.kind === "rollback") return "Restore the previously reviewed version " + action.version + + " of " + action.id + "? It will remain disabled until you enable it again." + if (action.kind === "uninstall") return "Remove " + action.id + + " from the installed list? This preserves private settings and stored release history for recovery." + return (action.enabled ? "Enable" : "Disable") + " the approved content state for " + action.id + "?" +} + +/** Owner-only Account Mode UI. All mutations go through session and origin-checked routes. */ export function AccountAddonMarketplace() { const [catalog, setCatalog] = React.useState(null) const [loading, setLoading] = React.useState(true) + const [busy, setBusy] = React.useState(false) const [error, setError] = React.useState("") + const [notice, setNotice] = React.useState("") const [term, setTerm] = React.useState("") const [category, setCategory] = React.useState("all") const [chosen, setChosen] = React.useState(null) + const [pending, setPending] = React.useState(null) - React.useEffect(() => { - let mounted = true - void (async () => { - try { - const response = await fetch("/api/nextguide/studio/addons", { - method: "GET", credentials: "same-origin", cache: "no-store", - }) - if (response.status === 401) { - window.location.replace("/login") - return - } - if (!response.ok) throw Error("The verified add-on catalog could not be loaded.") - const data = await response.json() as Catalog - if (!data || !Array.isArray(data.releases) || typeof data.configured !== "boolean") { - throw Error("The add-on catalog returned an invalid response.") - } - if (mounted) setCatalog(data) - } catch (cause) { - if (mounted) setError(cause instanceof Error ? cause.message : "The catalog is unavailable.") - } finally { if (mounted) setLoading(false) } - })() - return () => { mounted = false } + const refresh = React.useCallback(async () => { + const response = await fetch("/api/nextguide/studio/addons", { + method:"GET",credentials:"same-origin",cache:"no-store", + }) + if (response.status===401) { + window.location.replace("/login") + throw Error("Sign in again to manage add-ons.") + } + if (!response.ok) throw Error("Could not fetch the verified add-on catalog.") + const value = await response.json() as Catalog + if (!value || typeof value.configured!=="boolean" || !Array.isArray(value.releases) || + !value.installed || !Array.isArray(value.installed.addons) || + !Number.isInteger(value.installed.revision)) { + throw Error("The add-on catalog response is invalid.") + } + setCatalog(value) + return value }, []) + React.useEffect(() => { + let active = true + void refresh().catch(cause => { + if (active) setError(cause instanceof Error ? cause.message : "Catalog unavailable.") + }).finally(()=>{if(active)setLoading(false)}) + return () => {active=false} + }, [refresh]) - const releases = catalog?.releases ?? [] - const categories = [...new Set(releases.map(r => r.manifest.category))].sort() - const selected = chosen ? releases.find(r => r.manifest.id === chosen) : undefined - const matching = releases.filter(r => { - const m = r.manifest - const query = term.trim().toLowerCase() - return (category === "all" || m.category === category) && - (!query || [m.id, m.name, m.summary, m.description, m.category, m.author?.name] - .some(s => String(s ?? "").toLowerCase().includes(query))) - }).sort((a,b) => a.manifest.name.localeCompare(b.manifest.name)) + async function performAction() { + if (!pending || !catalog || busy) return + setBusy(true) + setError("") + setNotice("") + try { + const method = pending.kind === "install" ? "addon-install" : + pending.kind === "toggle" ? "addon-toggle" : + pending.kind === "rollback" ? "addon-rollback" : "addon-uninstall" + const payload = { + ...pending, + expectedRevision:catalog.installed.revision, + consent:true, + } + const response=await fetch("/api/nextguide/studio/"+method,{ + method:"POST",cache:"no-store",credentials:"same-origin", + headers:{"Content-Type":"application/json"},body:JSON.stringify(payload), + }) + if(response.status===401){ + window.location.replace("/login") + throw Error("Session expired. Sign in again.") + } + const result=await response.json() as {error?:string} + if(!response.ok)throw Error(result.error||"Add-on operation failed.") + await refresh() + if(pending.kind==="uninstall")setChosen(null) + setNotice("Add-on "+pending.kind+" completed. No executable extension code was run.") + }catch(cause){ + setError(cause instanceof Error ? cause.message : "Add-on operation failed.") + }finally{ + setPending(null) + setBusy(false) + } + } + + const installed=catalog?.installed.addons??[] + const releases=catalog?.releases??[] + const categories=[...new Set(releases.map(r=>r.manifest.category))].sort() + const selected=chosen?releases.find(r=>r.manifest.id===chosen):undefined + const matching=releases.filter(release=>{ + const m=release.manifest, q=term.trim().toLowerCase() + return (category==="all"||m.category===category) && + (!q||[m.id,m.name,m.summary,m.description,m.category,m.author?.name] + .some(value=>String(value??"").toLowerCase().includes(q))) + }).sort((a,b)=>a.manifest.name.localeCompare(b.manifest.name)) - if (selected) return setChosen(null)} /> return
-
-

Add-ons

Catalog preview
-

Discover independently reviewed NextGuide add-ons. Available in Account Mode only.

-
- {loading && Loading verified catalog…} {error && {error}} - {catalog && !catalog.configured && Catalog connection not configuredYour site owner must configure a trusted registry endpoint and pin its Ed25519 public key on the server. The catalog is never loaded from an unsigned or untrusted source.} - {catalog?.configured && <> -
-
setTerm(e.target.value)} />
- {matching.length} approved {matching.length === 1 ? "release" : "releases"} -
-
- {["all", ...categories].map(item => )} + {notice && {notice}} + {loading && Loading approved add-ons…} + {selected ? setChosen(null)} + installed={installed.find(a=>a.id===selected.manifest.id)} onAction={setPending} busy={busy} + catalogFresh={catalog?.catalogFresh??false}/> : <> +
+

Add-ons

+ Reviewed content
+

Install and manage signed Markdown add-ons in Account Mode. + Executable extensions and public page mounting remain disabled.

+ {catalog &&

+ Installed NextGuide {catalog.nextguideVersion} · {installed.length} stored add-ons +

}
- {matching.length ?
- {matching.map(release => -
Verified
- {release.manifest.name}{release.manifest.summary || release.manifest.description || "Approved add-on"} -

{release.manifest.author?.name || "Independent publisher"} · {release.manifest.category} · v{release.manifest.version}

-
)} -
: No approved add-ons match your search.} -

Listings have a verified registry signature, but installed-site actions are not yet available. Revocations may change between catalog refreshes.

+ {catalog && installed.length>0 &&
+

Installed on this site

+
+ {installed.map(addon=> + {addon.name} + {addon.id} · v{addon.version} · {addon.enabled?"Enabled":"Disabled"} + + {releases.some(x=>x.manifest.id===addon.id) && } + + + )} +
+
} + {catalog?.configured && !catalog.catalogFresh && The verified catalog is older than one hour. Discovery is available, but new installs, updates and enabling are suspended until the registry issues a fresh signed index. Disable and uninstall remain available.} + {catalog && !catalog.configured && + Signed registry not configured + Set a trusted registry URL and pinned Ed25519 public key on the Account Mode server. + Previously installed data remains stored privately. + } + {catalog?.configured && <> +
+
+ + setTerm(e.target.value)}/> +
+ {matching.length} reviewed releases +
+
+ {["all",...categories].map(item=>)} +
+ {matching.length?
+ {matching.map(release=> + +
+ {release.manifest.name} + {release.manifest.summary||release.manifest.description||"Reviewed content add-on"} +

+ {release.manifest.author?.name||"Independent publisher"} · {release.manifest.category} · v{release.manifest.version} +

+
+
)} +
: + No approved add-ons match your search.} +

+ Every install verifies the signed registry, exact archive bytes and compatibility again. + Revoked releases cannot be reactivated. +

+ } } + {if(!open&&!busy)setPending(null)}}> + + Confirm add-on change + {actionDescription(pending)} + + + Cancel + void performAction()}> + {busy?"Verifying…":"Confirm"} + + + +
} diff --git a/packages/nextguide/test/account-init.test.mjs b/packages/nextguide/test/account-init.test.mjs index 5bfb6a4..4edd6b1 100644 --- a/packages/nextguide/test/account-init.test.mjs +++ b/packages/nextguide/test/account-init.test.mjs @@ -137,25 +137,36 @@ test("Account Mode API and admin routes work with Cache Components and load true })) -test("Account Mode add-on discovery is owner-authenticated, signed and read-only", () => isolated(() => { +test("Account Mode add-on lifecycle routes stay owner-authenticated and read-only on Developer Mode", () => isolated(() => { const { project, inspection } = fixture() try { initAccount(project, inspection) - const route = readFileSync(join(project, "src/app/api/nextguide/studio/[action]/route.ts"), "utf8") - const view = readFileSync(new URL("../src/account/studio.tsx", import.meta.url), "utf8") - const marketplace = readFileSync(new URL("../src/account/addon-marketplace.tsx", import.meta.url), "utf8") - assert.match(route, /createVerifiedRegistryClient/) - assert.match(route, /NEXTGUIDE_ADDON_REGISTRY_PUBLIC_KEY_B64/) - assert.match(route, /NEXTGUIDE_ADDON_REGISTRY_URL/) - assert.match(route, /return response\(\{ configured: true, releases: await registry\.listApproved\(\) \}\)/) + const route=readFileSync(join(project,"src/app/api/nextguide/studio/[action]/route.ts"),"utf8") + const view=readFileSync(new URL("../src/account/studio.tsx",import.meta.url),"utf8") + const market=readFileSync(new URL("../src/account/addon-marketplace.tsx",import.meta.url),"utf8") + const manager=readFileSync(new URL("../lib/extension-site-manager.mjs",import.meta.url),"utf8") + assert.match(route,/createAccountAddonManager/) + assert.match(route,/addons\.install\(input\)/) + assert.match(route,/addons\.toggle\(input\)/) + assert.match(route,/addons\.rollback\(input\)/) + assert.match(route,/addons\.uninstall\(input\)/) assert.ok(route.indexOf("if (!authorized(request))") < route.indexOf('if (action === "addons")'), - "Unauthenticated visitors must not fetch registry data through the studio") - const post = route.slice(route.indexOf("export async function POST")) - assert.doesNotMatch(post, /install-addon|execute-addon|update-addon/) - assert.match(view, //) - assert.match(view, /id: "addons", label: "Add-ons"/) - assert.match(marketplace, /credentials: "same-origin"/) - assert.match(marketplace, /disabled>/) + assert.match(view,/id: "addons", label: "Add-ons"/) + assert.match(market,/credentials:"same-origin"/) + assert.match(market,/ { - for (const key of [".", "./core", "./mdx", "./mdx/server", "./mdx/client", "./openapi", "./components", "./ui", "./icons", "./blocks", "./ui/primitives", "./ui/interactive", "./fonts", "./fonts/catalog", "./site/next", "./styles.css", "./extensions", "./extensions/runtime", "./extensions/views", "./extensions/ui", "./extensions/storage", "./extensions/catalog"]) { + for (const key of [".", "./core", "./mdx", "./mdx/server", "./mdx/client", "./openapi", "./components", "./ui", "./icons", "./blocks", "./ui/primitives", "./ui/interactive", "./fonts", "./fonts/catalog", "./site/next", "./styles.css", "./extensions", "./extensions/runtime", "./extensions/views", "./extensions/ui", "./extensions/storage", "./extensions/catalog", "./extensions/isolation", "./extensions/artifacts", "./extensions/install-state", "./extensions/download", "./extensions/site-manager"]) { assert.ok(manifest.exports[key], key) } }) diff --git a/packages/nextguide/test/extension-site-manager.test.mjs b/packages/nextguide/test/extension-site-manager.test.mjs new file mode 100644 index 0000000..83d8159 --- /dev/null +++ b/packages/nextguide/test/extension-site-manager.test.mjs @@ -0,0 +1,196 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { createHash, generateKeyPairSync, sign } from "node:crypto" +import { EventEmitter } from "node:events" +import { PassThrough } from "node:stream" +import { gzipSync } from "node:zlib" +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createBootstrap } from "../lib/account-auth.mjs" +import { createAccountAddonManager } from "../lib/extension-site-manager.mjs" + +const keys=generateKeyPairSync("ed25519") +const pem=keys.publicKey.export({type:"spki",format:"pem"}) +const keyId=createHash("sha256").update(keys.publicKey.export({ + type:"spki",format:"der" +})).digest("hex").slice(0,24) +const NOW=Date.parse("2026-11-08T15:00:00Z") +function member(path,bytes) { + bytes=Buffer.from(bytes) + const h=Buffer.alloc(512) + h.write(path,0,100) + h.write("0000644\0",100,8) + h.write("0000000\0",108,8) + h.write("0000000\0",116,8) + h.write(bytes.length.toString(8).padStart(11,"0")+"\0",124,12) + h.write("00000000000\0",136,12) + h.fill(32,148,156) + h.write("0",156);h.write("ustar\0",257);h.write("00",263) + const sum=h.reduce((a,b)=>a+b,0) + h.write(sum.toString(8).padStart(6,"0")+"\0 ",148,8) + return Buffer.concat([h,bytes,Buffer.alloc((512-bytes.length%512)%512)]) +} +function png(){ + const b=Buffer.alloc(48) + Buffer.from([137,80,78,71,13,10,26,10]).copy(b) + b.writeUInt32BE(13,8);b.write("IHDR",12) + b.writeUInt32BE(32,16);b.writeUInt32BE(32,20) + return b +} +function versioned(version) { + const manifest={ + schemaVersion:1,id:"acme.docs",name:"Docs Extension",version, + category:"content",repository:"https://github.com/acme/docs", + permissions:[],compatibility:{mode:"account",nextguide:">=1.0.0 <2.0.0"}, + entrypoints:{content:"content"},icon:"icon.png", + } + const archive=gzipSync(Buffer.concat([ + member("nextguide-addon.json",JSON.stringify(manifest)), + member("icon.png",png()), + member("content/index.md","# Welcome "+version+"\n"), + Buffer.alloc(1024) + ]),{mtime:0}) + const release={ + manifest,tag:"v"+version,commit:"a".repeat(40), + digest:createHash("sha256").update(archive).digest("hex"), + size:archive.length, + assetUrl:"https://github.com/acme/docs/releases/download/v"+version+ + "/nextguide-addon-"+version+".tgz", + status:"active",reviewer:"registry-reviewer",approvedAt:"2026-11-08T14:59:00Z", + } + return {archive,release} +} +function signed(releases,updatedAt="2026-11-08T14:59:00Z"){ + const bytes=Buffer.from(JSON.stringify({schemaVersion:1,updatedAt,releases})) + return {schemaVersion:1,algorithm:"Ed25519",keyId, + body:bytes.toString("base64url"), + signature:sign(null,bytes,keys.privateKey).toString("base64url")} +} +function transportFor(releases) { + const calls=[] + const transport=(opts,respond)=>{ + const req=new EventEmitter() + req.end=()=>{ + calls.push(opts) + const release=releases.find(r=>opts.path===new URL(r.release.assetUrl).pathname) + queueMicrotask(()=>{ + const response=new PassThrough() + response.statusCode=release?200:404 + response.headers=release?{"content-length":String(release.archive.length)}:{} + respond(response) + response.end(release?.archive??"not found") + }) + } + req.destroy=()=>{} + return req + } + return {calls,transport} +} +function fixture({version="1.0.0",signedReleases,artifacts,now=NOW}={}) { + const base=mkdtempSync(join(tmpdir(),"nextguide-addon-manager-")) + const project=join(base,"site"),dataDir=join(base,"private") + mkdirSync(project) + writeFileSync(join(project,"nextguide.config.json"),JSON.stringify({ + mode:"account",contentDir:"content/docs" + })) + createBootstrap(project,{dataDir}) + const network=transportFor(artifacts) + const manager=createAccountAddonManager({ + project,dataDir,nextguideVersion:version,now:()=>now, + registryUrl:"https://registry.example/v1/registry",pinnedPublicKeyPem:pem, + registryFetch:async()=>new Response(JSON.stringify(signedReleases),{ + headers:{"Content-Type":"application/json"} + }), + resolver:async()=>[{family:4,address:"93.184.216.34"}], + transport:network.transport, + }) + return {manager,network,cleanup:()=>rmSync(base,{recursive:true,force:true})} +} + +test("owner catalog includes exact compatibility and durable installed state",async()=>{ + const a=versioned("1.0.0") + const f=fixture({signedReleases:signed([a.release]),artifacts:[a]}) + try{ + const catalog=await f.manager.catalog() + assert.equal(catalog.configured,true) + assert.equal(catalog.installed.revision,0) + assert.equal(catalog.releases[0].compatible,true) + assert.equal(catalog.nextguideVersion,"1.0.0") + await assert.rejects(f.manager.install({ + id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:false + }),/consent/) + assert.equal(f.network.calls.length,0) + const installed=await f.manager.install({ + id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:true + }) + assert.equal(installed.addon.enabled,false) + assert.equal(installed.revision,1) + assert.equal((await f.manager.catalog()).installed.addons[0].version,"1.0.0") + const enabled=await f.manager.toggle({id:"acme.docs",enabled:true,expectedRevision:1}) + assert.equal(enabled.addon.enabled,true) + const approved=await f.manager.readEnabled({id:"acme.docs"}) + assert.match(approved.pages[0].markdown,/Welcome 1\.0\.0/) + const disabled=await f.manager.toggle({id:"acme.docs",enabled:false,expectedRevision:2}) + assert.equal(disabled.addon.enabled,false) + assert.equal(await f.manager.readEnabled({id:"acme.docs"}),null) + const removed=f.manager.uninstall({ + id:"acme.docs",expectedRevision:3,consent:true + }) + assert.equal(removed.privateDataPreserved,true) + assert.deepEqual((await f.manager.catalog()).installed.addons,[]) + }finally{f.cleanup()} +}) + +test("owner update + rollback retains only reviewed versions and re-enables explicitly",async()=>{ + const a=versioned("1.0.0"),b=versioned("1.1.0") + const f=fixture({signedReleases:signed([a.release,b.release]),artifacts:[a,b]}) + try{ + await f.manager.install({id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:true}) + await f.manager.install({id:"acme.docs",version:"1.1.0",expectedRevision:1,consent:true}) + assert.deepEqual((await f.manager.catalog()).installed.addons[0].availableVersions, + ["1.0.0","1.1.0"]) + const result=await f.manager.rollback({ + id:"acme.docs",version:"1.0.0",expectedRevision:2,consent:true + }) + assert.equal(result.addon.enabled,false) + assert.equal(result.addon.version,"1.0.0") + await assert.rejects(f.manager.rollback({ + id:"acme.docs",version:"1.1.0",expectedRevision:3,consent:false + }),/consent/) + }finally{f.cleanup()} +}) + +test("stale signed metadata, incompatible alpha versions and revoked releases are blocked",async()=>{ + const a=versioned("1.0.0") + const stale=fixture({signedReleases:signed([a.release],"2026-11-06T00:00:00Z"),artifacts:[a]}) + try{ + const listed=await stale.manager.catalog() + assert.equal(listed.configured,true) + assert.equal(listed.catalogFresh,false) + assert.equal(listed.releases.length,1) + await assert.rejects(stale.manager.install({ + id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:true + }),/last hour/) + assert.equal(stale.network.calls.length,0) + }finally{stale.cleanup()} + const alpha=fixture({ + version:"0.0.1-alpha.2",signedReleases:signed([a.release]),artifacts:[a] + }) + try{ + assert.equal((await alpha.manager.catalog()).releases[0].compatible,false) + await assert.rejects(alpha.manager.install({ + id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:true + }),/not reviewed, active or compatible/) + assert.equal(alpha.network.calls.length,0) + }finally{alpha.cleanup()} + const revoked=fixture({ + signedReleases:signed([{...a.release,status:"revoked"}]),artifacts:[a] + }) + try{ + await assert.rejects(revoked.manager.install({ + id:"acme.docs",version:"1.0.0",expectedRevision:0,consent:true + }),/not reviewed/) + assert.equal(revoked.network.calls.length,0) + }finally{revoked.cleanup()} +})