diff --git a/apps/web/contents/addons/v2-supply-chain.mdx b/apps/web/contents/addons/v2-supply-chain.mdx index 4b96467..06e8a76 100644 --- a/apps/web/contents/addons/v2-supply-chain.mdx +++ b/apps/web/contents/addons/v2-supply-chain.mdx @@ -5,7 +5,7 @@ description: The signed executable release protocol, byte-level verifier and pri # Reviewed executable v2 packages -NextGuide supports **read-only verification** of independently reviewed v2 executable archives. This does not enable production execution. The private ngapi server currently approves content-only v1 releases; v2 requires a separate registry deployment. +NextGuide supports **read-only verification and private Account Mode staging** of independently reviewed v2 executable archives, with owner permission-consent records. This does not enable production execution. The private ngapi server currently approves content-only v1 releases; v2 requires a separate registry deployment. ## Source to trusted bytes @@ -38,6 +38,26 @@ The registry backend must verify independent review, reproducible build provenan **The private ngapi service has not been upgraded by this milestone.** Before server deployment, prepare and test a private patch against the actual VPS backend, with a backup and rollback procedure. +## Account Mode private v2 staging + +The Account Mode **Add-ons** page now has a separate **Executable extensions** review panel below the existing, working v1 Markdown marketplace. Once your privately hosted ngapi implements the signed v2 endpoint and its public key is pinned to the host, the panel can browse reviewed v2 releases, show independent reviewer identity, version, compatibility, exact archive digest and requested capabilities. + +The server-side staging journal lives outside the Next.js project and stores only immutable, reviewed package bytes, bounded state history and version-specific permission approvals. It uses cross-process locking, atomic journal revisions and exact SHA-256 checks. Staged executable add-ons are always **blocked from execution**; no enabled flag or host-process module loader exists. + +Owner actions: + +- **Stage reviewed release:** Download the signed GitHub artifact, verify every byte, check compatibility and latest active signed status again, and save it privately with no grants. +- **Review and approve capabilities:** Require owner session, same-origin request, explicit consent and exact pinned version/digest/permission list. Permission approval is a record only, never an execution grant. +- **Update and rollback:** Only to signed active versions. Clear *all* prior grants and require fresh review. If the registry is expired, unreachable or revoked, the action fails closed. +- **Revoke permissions and uninstall:** Work offline to let the owner disable previously granted privileges or remove the staged add-on from the journal even when the signed registry is unavailable. +- **History:** The last 100 successful actions are stored privately. No executable code or credentials are exposed through the API response. + +Trusted Account Mode server configuration uses **NEXTGUIDE_ADDON_V2_REGISTRY_URL** set to the trusted HTTPS `/v2/registry` endpoint and **NEXTGUIDE_ADDON_V2_PUBLIC_KEY_B64** containing the base64-encoded pinned PEM public key. Never place a private signing key or public registry URL in browser-provided request data. + +The generated studio API uses existing site-owner session validation and origin protection for all changes. **Existing Account Mode installations must preview and explicitly apply a generated-route refresh** using the `nextguide upgrade --refresh-generated --dry-run` command and then `--refresh-generated`; NextGuide does not silently overwrite previously installed routes. + +No private ngapi v2 server upgrade has happened. Until the registry service is implemented, the panel shows configuration/unavailable status and retains safe offline access to existing staged state. The released `0.0.1-alpha.2` package also does not meet manifests requiring `>=1.0.0`, intentionally preventing premature alpha staging. + ## Remaining execution gates The experimental Linux Bubblewrap runner still needs cgroup memory/process limits and independent sandbox testing. Windows has no approved secure backend yet. Browser UI execution requires separate origin/frame isolation. The private v2 installer must transactionally pin approved versions, obtain explicit site-owner grants and recheck revocations before each activation. diff --git a/packages/nextguide/lib/account-studio-template.mjs b/packages/nextguide/lib/account-studio-template.mjs index 22970e4..8349be2 100644 --- a/packages/nextguide/lib/account-studio-template.mjs +++ b/packages/nextguide/lib/account-studio-template.mjs @@ -4,6 +4,7 @@ const STUDIO_API = `// Generated by NextGuide CLI. Edit freely; NextGuide never 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 { createAccountAddonManager } from "nextguide/extensions/site-manager" +import { createAccountV2AddonManager } from "nextguide/extensions/v2-site-manager" function response(data__DATA_TYPE__, status = 200) { @@ -70,6 +71,9 @@ export async function GET(request__REQUEST_TYPE__, { params }__PARAM_TYPE__) { if (action === "addons") { return response(await createAccountAddonManager({ project: process.cwd() }).catalog()) } + if (action === "addons-v2") { + return response(await createAccountV2AddonManager({ 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") ?? "")) if (action === "settings") return response(getStudioSettings(process.cwd())) @@ -82,9 +86,20 @@ 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","addon-install","addon-toggle","addon-rollback","addon-uninstall"].includes(action)) + if (!["save-page","delete-page","save-settings","save-navigation","upload-media","delete-media","addon-install","addon-toggle","addon-rollback","addon-uninstall","addon-v2-stage","addon-v2-grant","addon-v2-revoke","addon-v2-rollback","addon-v2-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-v2-")) { + // Owner session, same-origin and JSON size checked above. Never accept + // filesystem paths, module source, signing keys, or a caller-defined URL. + const manager = createAccountV2AddonManager({ project: process.cwd() }) + if (action === "addon-v2-stage") return response(await manager.stage(input)) + if (action === "addon-v2-grant") return response(await manager.grant(input)) + if (action === "addon-v2-revoke") return response(manager.revoke(input)) + if (action === "addon-v2-rollback") return response(await manager.rollback(input)) + if (action === "addon-v2-uninstall") return response(manager.uninstall(input)) + return response({ error: "Not found" }, 404) + } if (action.startsWith("addon-")) { const addons = createAccountAddonManager({ project: process.cwd() }) if (action === "addon-install") return response(await addons.install(input)) diff --git a/packages/nextguide/lib/extension-v2-site-manager.d.mts b/packages/nextguide/lib/extension-v2-site-manager.d.mts new file mode 100644 index 0000000..45f1c0f --- /dev/null +++ b/packages/nextguide/lib/extension-v2-site-manager.d.mts @@ -0,0 +1,60 @@ +import type { + V2Capability,ReviewedV2Release +} from "./extension-v2-catalog.mjs" +export interface StagedV2Addon { + id:string + name:string + version:string + digest:string + requestedPermissions:V2Capability[] + grantedPermissions:V2Capability[] + availableVersions:string[] + reviewer:string + reviewedAt:string + execution:"blocked" +} +export interface V2Activity { + revision:number + at:string + operation:"stage"|"update"|"grant"|"revoke"|"rollback"|"uninstall" + id:string + version:string +} +export interface V2StagingCatalog { + configured:boolean + registryUnavailable:boolean + releases:Array + installed:{revision:number;addons:StagedV2Addon[];history:V2Activity[]} + nextguideVersion:string + executionAvailable:false +} +export declare function createAccountV2AddonManager(options?:{ + project?:string + dataDir?:string + nextguideVersion?:string + registryUrl?:string + pinnedPublicKeyPem?:string + now?:()=>number + registryFetch?:typeof fetch + resolver?:(...args:any[])=>Promise> + transport?:(...args:any[])=>any +}):{ + catalog():Promise + stage(input:{ + id:string;version:string;expectedRevision:number;consent:true + }):Promise<{revision:number;addon:StagedV2Addon;executionAvailable:false}> + grant(input:{ + id:string;version:string;digest:string + permissions:V2Capability[] + expectedRevision:number;consent:true + }):Promise<{revision:number;addon:StagedV2Addon;executionAvailable:false}> + revoke(input:{ + id:string;expectedRevision:number;consent:true + }):{revision:number;addon:StagedV2Addon;executionAvailable:false} + rollback(input:{ + id:string;version:string;expectedRevision:number;consent:true + }):Promise<{revision:number;addon:StagedV2Addon;executionAvailable:false}> + uninstall(input:{ + id:string;expectedRevision:number;consent:true + }):{revision:number;removed:string;privateDataPreserved:true;executionAvailable:false} +} diff --git a/packages/nextguide/lib/extension-v2-site-manager.mjs b/packages/nextguide/lib/extension-v2-site-manager.mjs new file mode 100644 index 0000000..a4f90dd --- /dev/null +++ b/packages/nextguide/lib/extension-v2-site-manager.mjs @@ -0,0 +1,401 @@ +/** + * Account Mode v2 review intake and private owner-consent journal. + * + * IMPORTANT: this stores verified executable packages as inert private BYTES. + * No runtime handles, executable entrypoints, dynamic imports, browser scripts + * or "enabled" state are exposed. Grants are version+digest+permission bound + * but still DO NOT authorize execution until the separate isolation gate ships. + * + * V1 Markdown installations remain in their own independent journal. + */ +import { createHash, randomBytes } from "node:crypto" +import { + closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, + realpathSync, renameSync, unlinkSync, writeFileSync, linkSync, +} from "node:fs" +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path" +import { createRequire } from "node:module" +import { accountFile } from "./account-auth.mjs" +import { compatibleAddonRange } from "./extension-install-state.mjs" +import { + createVerifiedV2RegistryClient, verifySignedV2RegistryEnvelope, + listReviewedV2Releases, compareV2Permissions, +} from "./extension-v2-catalog.mjs" +import { verifyReviewedV2Archive } from "./extension-v2-artifacts.mjs" +import { downloadReviewedV2Release } from "./extension-download.mjs" + +const require=createRequire(import.meta.url) +const FRAMEWORK_VERSION=require("../package.json").version +const ID=/^[a-z0-9]+(?:-[a-z0-9]+)*\.[a-z0-9]+(?:-[a-z0-9]+)*$/ +const VERSION=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/ +const PACKAGE_VERSION=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/ +const SHA=/^[a-f0-9]{64}$/ +const MAX_ADDONS=64, MAX_VERSIONS=4, MAX_EVENTS=100 +const MAX_FILE_SIZE=3*1024*1024 +const ACTIONS=new Set(["stage","update","grant","revoke","rollback","uninstall"]) +const clone=value=>JSON.parse(JSON.stringify(value)) +const digest=bytes=>createHash("sha256").update(bytes).digest("hex") +function fail(code,message){ + const error=new Error("NextGuide v2 staging: "+message) + error.code=code + throw error +} +function object(x){return x!==null && typeof x==="object" && !Array.isArray(x)} +function validId(id){return typeof id==="string" && id.length<=100 && ID.test(id)} +function validVersion(v){return typeof v==="string" && VERSION.test(v)} +function validHash(s){return typeof s==="string" && SHA.test(s)} +function assertRegular(path){ + if(!existsSync(path))fail("MISSING_ARTIFACT","Required private file is missing") + const info=lstatSync(path) + if(!info.isFile() || info.isSymbolicLink())fail("UNSAFE_STORAGE","Refusing linked or nonregular file") + return info +} +function cleanDir(path){ + if(!existsSync(path))mkdirSync(path,{recursive:true,mode:0o700}) + if(!lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink()){ + fail("UNSAFE_STORAGE","Private directory must not be a symlink") + } +} +function compare(a,b){ + const aa=a.split(".").map(BigInt), bb=b.split(".").map(BigInt) + for(let i=0;i<3;i++)if(aa[i]!==bb[i])return aa[i]>bb[i]?1:-1 + return 0 +} +function safeSnapshot(value){ + if(!object(value) || !validVersion(value.version) || !validHash(value.digest) || + !Number.isSafeInteger(value.size) || value.size<32 || value.size>MAX_FILE_SIZE || + typeof value.name!=="string" || value.name.length<3 || value.name.length>80 || + !Array.isArray(value.permissions) || value.permissions.length>16 || + !Array.isArray(value.grants) || value.grants.length>16 || + typeof value.reviewer!=="string" || value.reviewer.length>100 || + !Number.isFinite(Date.parse(value.reviewedAt)))return false + try { + compareV2Permissions([],value.permissions,value.grants) + return value.grants.every(permission=>value.permissions.includes(permission)) + }catch{return false} +} +function safeState(value){ + if(!object(value) || value.schemaVersion!==2 || + !Number.isSafeInteger(value.revision) || value.revision<0 || + !object(value.addons) || Object.keys(value.addons).length>MAX_ADDONS || + !Array.isArray(value.history) || value.history.length>MAX_EVENTS){ + fail("DAMAGED_STATE","Invalid v2 private installation journal") + } + for(const [id,entry] of Object.entries(value.addons)){ + if(!validId(id) || !object(entry) || entry.id!==id || + !validVersion(entry.pinnedVersion) || + !Array.isArray(entry.versions) || !entry.versions.length || + entry.versions.length>MAX_VERSIONS || + new Set(entry.versions.map(v=>v.version)).size!==entry.versions.length || + !entry.versions.every(safeSnapshot) || + !entry.versions.some(v=>v.version===entry.pinnedVersion)){ + fail("DAMAGED_STATE","Invalid v2 private release entry") + } + } + let last=0 + for(const event of value.history){ + if(!object(event) || !Number.isSafeInteger(event.revision) || + event.revision<=last || event.revision>value.revision || + !validId(event.id) || !validVersion(event.version) || + !ACTIONS.has(event.operation) || !Number.isFinite(Date.parse(event.at))) { + fail("DAMAGED_STATE","Invalid v2 private activity history") + } + last=event.revision + } + return value +} +function initialState(){return {schemaVersion:2,revision:0,addons:{},history:[]}} +function publicEntry(entry){ + const selected=entry.versions.find(x=>x.version===entry.pinnedVersion) + return { + id:entry.id,name:selected.name,version:selected.version, + digest:selected.digest,requestedPermissions:[...selected.permissions], + grantedPermissions:[...selected.grants], + availableVersions:entry.versions.map(x=>x.version), + reviewer:selected.reviewer,reviewedAt:selected.reviewedAt, + // Deliberately never an "enabled" flag; host execution is unavailable. + execution:"blocked", + } +} +function publicState(s){return { + revision:s.revision,addons:Object.values(s.addons).map(publicEntry), + history:clone(s.history), +}} + +/** + * No user-driven project paths or data roots may be passed from route input. + * Only the owner-authenticated server constructs the manager. + */ +export function createAccountV2AddonManager({ + project=process.cwd(),dataDir, + nextguideVersion=FRAMEWORK_VERSION, + registryUrl=process.env.NEXTGUIDE_ADDON_V2_REGISTRY_URL, + pinnedPublicKeyPem=process.env.NEXTGUIDE_ADDON_V2_PUBLIC_KEY_B64 + ? Buffer.from(process.env.NEXTGUIDE_ADDON_V2_PUBLIC_KEY_B64,"base64").toString("utf8"):"", + now=()=>Date.now(), registryFetch,resolver,transport, +}={}){ + if(typeof nextguideVersion!=="string" || !PACKAGE_VERSION.test(nextguideVersion) || + typeof now!=="function" || !Number.isFinite(now())){ + fail("CONFIGURATION","Invalid local framework version or trusted clock") + } + const site=resolve(project) + const configFile=join(site,"nextguide.config.json") + assertRegular(configFile) + let config + try{config=JSON.parse(readFileSync(configFile,"utf8"))} + catch{fail("INVALID_CONFIG","Invalid site configuration")} + if(config?.mode!=="account" || config?.contentDir!=="content/docs"){ + fail("MODE_DENIED","Executable staging is exclusive to Account Mode") + } + const privateFile=accountFile(site,dataDir) + assertRegular(privateFile) + const privateRoot=dirname(privateFile) + if(lstatSync(privateRoot).isSymbolicLink()){ + fail("UNSAFE_STORAGE","Private root cannot be a symlink") + } + const actualSite=realpathSync(site), actualPrivate=realpathSync(privateRoot) + const rel=relative(actualSite,actualPrivate) + if(rel==="" || (rel!==".." && !rel.startsWith(".."+sep) && !isAbsolute(rel))){ + fail("UNSAFE_STORAGE","Owner data must remain outside the served project") + } + const root=join(privateRoot,"addons-v2") + const blobs=join(root,"blobs") + cleanDir(root);cleanDir(blobs) + const index=join(root,"staged.json") + const lock=join(root,".lock") + const configured=typeof registryUrl==="string" && registryUrl.length>0 && + typeof pinnedPublicKeyPem==="string" && pinnedPublicKeyPem.length>0 + const registry=configured?createVerifiedV2RegistryClient({ + registryUrl,pinnedPublicKeyPem, + ...(registryFetch?{fetchImpl:registryFetch}:{}),now, + }):null + + function state(){ + if(!existsSync(index))return initialState() + const stat=assertRegular(index) + if(stat.size>128*1024)fail("DAMAGED_STATE","Private v2 journal exceeds size quota") + try{return safeState(JSON.parse(readFileSync(index,"utf8")))} + catch{fail("DAMAGED_STATE","Private v2 journal is damaged")} + } + function blobFile(hash){ + if(!validHash(hash))fail("INVALID_DIGEST","Invalid artifact SHA-256") + return join(blobs,hash+".tgz") + } + function checkedBlob(snapshot){ + const file=blobFile(snapshot.digest) + const stat=assertRegular(file) + if(stat.size!==snapshot.size)fail("CORRUPT_ARTIFACT","Stored executable archive size changed") + const bytes=readFileSync(file) + if(digest(bytes)!==snapshot.digest)fail("CORRUPT_ARTIFACT","Stored executable SHA-256 changed") + return bytes + } + function immutableBlob(release,bytes){ + const path=blobFile(release.digest) + if(existsSync(path)){ + checkedBlob(release) + return + } + const temp=join(blobs,"."+randomBytes(16).toString("hex")+".tmp") + try{ + writeFileSync(temp,bytes,{flag:"wx",mode:0o600}) + // Hard-link publication is exclusive. Never replace an existing + // content-addressed blob in another site's concurrent write. + try{linkSync(temp,path)}catch(err){if(err.code!=="EEXIST")throw err} + }finally{if(existsSync(temp))unlinkSync(temp)} + checkedBlob(release) + } + async function signed(){ + if(!registry)fail("NO_REGISTRY","Signed executable v2 registry is not configured") + const envelope=await registry.fetchSignedEnvelope() + const catalog=verifySignedV2RegistryEnvelope(envelope,pinnedPublicKeyPem,{now:now()}) + return {envelope,catalog} + } + function activeRelease(catalog,id,version,digestValue){ + if(!validId(id) || !validVersion(version))fail("INVALID_REQUEST","Invalid add-on identity") + const release=catalog.releases.find(x=> + x.manifest.id===id && x.manifest.version===version) + if(!release || release.status!=="active" || + (digestValue && release.digest!==digestValue) || + !compatibleAddonRange(release.manifest.compatibility.nextguide,nextguideVersion)){ + fail("NOT_APPROVED","V2 release revoked, missing or incompatible with installed NextGuide") + } + return release + } + function approvalInput({id,expectedRevision,consent}){ + if(!validId(id) || !Number.isSafeInteger(expectedRevision) || + expectedRevision<0)fail("INVALID_REQUEST","An add-on ID and exact state revision are required") + if(consent!==true)fail("CONSENT_REQUIRED","Explicit owner consent is required") + } + function mutate(expectedRevision,operation,id,action){ + if(!Number.isSafeInteger(expectedRevision) || expectedRevision<0){ + fail("INVALID_REQUEST","Expected state revision required") + } + let fd + try{fd=openSync(lock,"wx",0o600)} + catch{fail("BUSY","Another add-on operation is active")} + try{ + const previous=state() + if(previous.revision!==expectedRevision){ + fail("CONFLICT","Add-on journal changed; refresh and retry") + } + const next=clone(previous) + const result=action(next) + next.revision=previous.revision+1 + const record=next.addons[id] + const version=record?.pinnedVersion??previous.addons[id]?.pinnedVersion + next.history=[...previous.history,{ + revision:next.revision,at:new Date(now()).toISOString(), + operation,id,version, + }].slice(-MAX_EVENTS) + safeState(next) + const temp=join(root,"."+randomBytes(16).toString("hex")+".tmp") + try{ + writeFileSync(temp,JSON.stringify(next)+"\n",{flag:"wx",mode:0o600}) + renameSync(temp,index) + }finally{if(existsSync(temp))unlinkSync(temp)} + return {revision:next.revision,...result} + }finally{ + closeSync(fd) + unlinkSync(lock) + } + } + return { + async catalog(){ + const installed=publicState(state()) + if(!registry)return { + configured:false,registryUnavailable:true,releases:[], + installed,nextguideVersion,executionAvailable:false, + } + try{ + const {catalog}=await signed() + return { + configured:true,registryUnavailable:false, + releases:listReviewedV2Releases(catalog,{now:now()}).map(release=>({ + ...release, + compatible:compatibleAddonRange(release.manifest.compatibility.nextguide,nextguideVersion), + })), + installed,nextguideVersion,executionAvailable:false, + } + }catch{ + return {configured:true,registryUnavailable:true, + releases:[],installed,nextguideVersion,executionAvailable:false} + } + }, + /** + * Download/verify and STAGE a reviewed, signed v2 release. No execution or + * automatic permission grant, including on updates. + */ + async stage({id,version,expectedRevision,consent}={}){ + approvalInput({id,expectedRevision,consent}) + if(!validVersion(version))fail("INVALID_REQUEST","Invalid reviewed release version") + const {envelope,catalog}=await signed() + const release=activeRelease(catalog,id,version) + const {archive,verified}=await downloadReviewedV2Release({ + envelope,pinnedPublicKeyPem,id,version, + now,...(resolver?{resolver}:{}),...(transport?{transport}:{}), + }) + if(digest(archive)!==release.digest || + verified.compiled.sha256!==release.review.serverSha256){ + fail("CORRUPT_ARTIFACT","Downloaded v2 bundle changed") + } + // Latest signed revocation check at mutation time (not only before HTTPS). + const fresh=await signed() + activeRelease(fresh.catalog,id,version,release.digest) + return mutate(expectedRevision,"stage",id,next=>{ + const prior=next.addons[id] + if(!prior && Object.keys(next.addons).length>=MAX_ADDONS){ + fail("CAPACITY","Maximum staged executable add-on count reached") + } + if(prior && compare(version,prior.pinnedVersion)<=0){ + fail("DOWNGRADE","Use explicit rollback to restore a previous reviewed version") + } + const snapshot={ + version,digest:release.digest,size:release.size, + name:release.manifest.name, + permissions:[...release.manifest.permissions], + grants:[],reviewer:release.review.reviewer, + reviewedAt:release.review.approvedAt, + } + immutableBlob(release,archive) + // Never carry over approvals from ANY previous executable version. + // A rollback will require fresh consent for that exact digest. + const versions=prior? + [...prior.versions.filter(x=>x.version!==version).map(x=>({ + ...x,grants:[], + })),snapshot].slice(-MAX_VERSIONS): + [snapshot] + next.addons[id]={id,pinnedVersion:version,versions} + return {addon:publicEntry(next.addons[id]),executionAvailable:false} + }) + }, + /** + * Consent must match the exact pinned release digest and all requested + * capabilities. Even a granted record NEVER makes code runnable. + */ + async grant({id,version,digest:expectedDigest,permissions, + expectedRevision,consent}={}){ + approvalInput({id,expectedRevision,consent}) + if(!validVersion(version) || !validHash(expectedDigest) || + !Array.isArray(permissions)){ + fail("INVALID_REQUEST","Version, exact artifact digest and permissions are required") + } + const {envelope,catalog}=await signed() + activeRelease(catalog,id,version,expectedDigest) + return mutate(expectedRevision,"grant",id,next=>{ + const entry=next.addons[id] + if(!entry || entry.pinnedVersion!==version)fail("NOT_INSTALLED","Pinned release changed") + const snapshot=entry.versions.find(x=>x.version===version) + if(!snapshot || snapshot.digest!==expectedDigest){ + fail("CONFLICT","Release hash changed; review permissions again") + } + const diff=compareV2Permissions([],snapshot.permissions,permissions) + if(diff.ungranted.length || permissions.length!==snapshot.permissions.length){ + fail("PERMISSION_DENIED","Approval must match every requested capability") + } + verifyReviewedV2Archive({ + envelope,pinnedPublicKeyPem,id,version, + archive:checkedBlob(snapshot),now:now(), + }) + snapshot.grants=[...snapshot.permissions] + return {addon:publicEntry(entry),executionAvailable:false} + }) + }, + /** Revoke all grants OFFLINE, even when the registry has disappeared. */ + revoke({id,expectedRevision,consent}={}){ + approvalInput({id,expectedRevision,consent}) + return mutate(expectedRevision,"revoke",id,next=>{ + const entry=next.addons[id] + if(!entry)fail("NOT_INSTALLED","No staged release") + entry.versions.find(x=>x.version===entry.pinnedVersion).grants=[] + return {addon:publicEntry(entry),executionAvailable:false} + }) + }, + async rollback({id,version,expectedRevision,consent}={}){ + approvalInput({id,expectedRevision,consent}) + if(!validVersion(version))fail("INVALID_REQUEST","Invalid rollback version") + const {envelope,catalog}=await signed() + return mutate(expectedRevision,"rollback",id,next=>{ + const entry=next.addons[id] + if(!entry)fail("NOT_INSTALLED","No staged executable add-on") + const snapshot=entry.versions.find(x=>x.version===version) + if(!snapshot || entry.pinnedVersion===version){ + fail("NOT_INSTALLED","Requested reviewed rollback version is unavailable") + } + activeRelease(catalog,id,version,snapshot.digest) + verifyReviewedV2Archive({envelope,pinnedPublicKeyPem,id,version, + archive:checkedBlob(snapshot),now:now()}) + entry.pinnedVersion=version + for(const prior of entry.versions)prior.grants=[] + return {addon:publicEntry(entry),executionAvailable:false} + }) + }, + uninstall({id,expectedRevision,consent}={}){ + approvalInput({id,expectedRevision,consent}) + return mutate(expectedRevision,"uninstall",id,next=>{ + if(!next.addons[id])fail("NOT_INSTALLED","No staged executable add-on") + delete next.addons[id] + return {removed:id,privateDataPreserved:true,executionAvailable:false} + }) + }, + } +} diff --git a/packages/nextguide/package.json b/packages/nextguide/package.json index b54818f..95021df 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/extension-v2.test.mjs test/extension-site-manager.test.mjs test/addon-page.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-v2.test.mjs test/extension-site-manager.test.mjs test/addon-page.test.mjs test/docs-chatgpt.test.mjs test/extension-v2-site-manager.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/extension-v2.test.mjs test/extension-site-manager.test.mjs test/addon-page.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-v2.test.mjs test/extension-site-manager.test.mjs test/addon-page.test.mjs test/docs-chatgpt.test.mjs test/extension-v2-site-manager.test.mjs", "test:unit": "bunx vitest run", "check-types": "node scripts/build.mjs" }, @@ -209,6 +209,11 @@ "types": "./lib/extension-v2-artifacts.d.mts", "node": "./lib/extension-v2-artifacts.mjs", "default": "./lib/extension-v2-artifacts.mjs" + }, + "./extensions/v2-site-manager": { + "types": "./lib/extension-v2-site-manager.d.mts", + "node": "./lib/extension-v2-site-manager.mjs", + "default": "./lib/extension-v2-site-manager.mjs" } }, "imports": { diff --git a/packages/nextguide/src/account/addon-marketplace.tsx b/packages/nextguide/src/account/addon-marketplace.tsx index 0fe0097..83779c9 100644 --- a/packages/nextguide/src/account/addon-marketplace.tsx +++ b/packages/nextguide/src/account/addon-marketplace.tsx @@ -108,7 +108,7 @@ function ReleaseDetails({ release, back, installed, onAction, busy, catalogFresh Source repository

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

+ Enabled, verified Markdown pages are available in Account Mode documentation navigation and search.

Release information @@ -147,7 +147,7 @@ function ReleaseDetails({ release, back, installed, onAction, busy, catalogFresh 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.

+ signed Markdown content is rendered in dedicated, non-executable documentation routes.

@@ -165,6 +165,264 @@ function actionDescription(action: Action | null) { return (action.enabled ? "Enable" : "Disable") + " the approved content state for " + action.id + "?" } +type V2Release = { + manifest: Manifest + digest: string + size: number + status: "active" | "revoked" + compatible: boolean + review: { + reviewer: string + approvedAt: string + policy: "independent-human" + } +} +type V2Installed = { + id: string + name: string + version: string + digest: string + requestedPermissions: string[] + grantedPermissions: string[] + availableVersions: string[] + reviewer: string + reviewedAt: string + execution: "blocked" +} +type V2Catalog = { + configured: boolean + registryUnavailable: boolean + executionAvailable: false + nextguideVersion: string + releases: V2Release[] + installed: { + revision: number + addons: V2Installed[] + history: Array<{revision:number;at:string;operation:string;id:string;version:string}> + } +} +type V2Action = + | { kind:"stage";id:string;version:string } + | { kind:"grant";id:string;version:string;digest:string;permissions:string[] } + | { kind:"revoke";id:string } + | { kind:"rollback";id:string;version:string } + | { kind:"uninstall";id:string } + +function V2ActionDescription({action}: {action:V2Action | null}) { + if (!action) return null + if (action.kind==="stage") return

Download and privately stage independently reviewed + executable add-on {action.id} v{action.version}? The exact archive and every source hash will be + verified. It will stay blocked from execution and request no automatic grants.

+ if (action.kind==="grant") return
+

Record explicit owner consent for {action.id} v{action.version} and + the exact reviewed SHA-256 {action.digest.slice(0,16)}…?

+

Requested capabilities: {action.permissions.length ? action.permissions.join(", "):"None"}

+

Consent is saved for this immutable version only. This does NOT enable or run any code.

+
+ if (action.kind==="rollback") return

Return to reviewed v{action.version} + of {action.id}? Previous grants will be cleared. The add-on remains blocked.

+ if (action.kind==="revoke") return

Immediately revoke the saved owner + permissions for {action.id}? This works even if the registry is offline.

+ return

Remove staged {action.id} from the Account Mode v2 list? + Previously stored immutable bytes remain private for recovery.

+} + +/** Signed v2 review and consent only. No executable runtime or untrusted React. */ +function V2ReviewPanel() { + const [data,setData]=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 [pending,setPending]=React.useState(null) + const [query,setQuery]=React.useState("") + + const refresh=React.useCallback(async()=>{ + const response=await fetch("/api/nextguide/studio/addons-v2",{ + method:"GET",credentials:"same-origin",cache:"no-store" + }) + if(response.status===401){ + window.location.replace("/login") + throw Error("Sign in again to review executable add-ons.") + } + if(!response.ok)throw Error("Could not read private v2 add-on staging state.") + const value=await response.json() as V2Catalog + if(!value || typeof value.configured!=="boolean" || + !Array.isArray(value.releases) || !value.installed || + !Number.isSafeInteger(value.installed.revision) || + !Array.isArray(value.installed.addons)) { + throw Error("Invalid signed v2 staging catalog response.") + } + setData(value) + },[]) + React.useEffect(()=>{ + let live=true + void refresh().catch(cause=>{ + if(live)setError(cause instanceof Error?cause.message:"V2 staging unavailable.") + }).finally(()=>{if(live)setLoading(false)}) + return ()=>{live=false} + },[refresh]) + + async function apply(){ + if(!data || !pending || busy)return + setBusy(true);setError("");setNotice("") + const action=pending + try{ + const response=await fetch("/api/nextguide/studio/addon-v2-"+action.kind,{ + method:"POST",credentials:"same-origin",cache:"no-store", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({...action,expectedRevision:data.installed.revision,consent:true}), + }) + if(response.status===401){ + window.location.replace("/login") + throw Error("Session expired.") + } + const result=await response.json() as {error?:string;executionAvailable?:boolean} + if(!response.ok)throw Error(result.error || "Reviewed add-on operation denied.") + if(result.executionAvailable!==false)throw Error("Unsafe v2 state response.") + await refresh() + setNotice("Saved reviewed "+action.kind+" operation. Executable add-ons remain blocked.") + }catch(cause){setError(cause instanceof Error?cause.message:"V2 operation failed.")} + finally{setBusy(false);setPending(null)} + } + const installed=data?.installed.addons??[] + const releases=(data?.releases??[]).filter(release=>{ + const q=query.trim().toLowerCase() + return !q || [release.manifest.name,release.manifest.id, + release.manifest.author?.name,release.manifest.category] + .some(x=>String(x??"").toLowerCase().includes(q)) + }) + const latest=(v:string,w:string)=>{ + const a=v.split(".").map(Number),b=w.split(".").map(Number) + for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]>b[i] + return false + } + return
+
+
+

Executable extensions

+ V2 review preview + Execution blocked +
+

Review independently signed JavaScript/TypeScript + packages, their publisher, exact SHA-256 and requested capabilities. Stage releases + privately and record explicit owner permission approval. Nothing can run here + until the separately audited sandbox and v2 registry are production-ready.

+
+ {loading &&

Checking private v2 staging state…

} + {error && {error}} + {notice && {notice}} + {data &&
+ NextGuide {data.nextguideVersion} · {installed.length} privately staged + +
} + {data && !data.configured && + The private v2 signed registry is not connected. This preview becomes available + only when the independently reviewed /v2/registry service and pinned public + key are configured. Existing v1 Markdown add-ons are unaffected.} + {data?.configured && data.registryUnavailable && + The signed executable registry is unavailable or cannot be verified. + No new staging, grants or rollback is allowed; offline permission revocation + and uninstall remain available.} + {installed.length>0 &&
+

Privately staged

+
+ {installed.map(item=> + {item.name} + {item.id} · v{item.version} · Not running + + +

SHA-256: {item.digest}

+

Requested: {item.requestedPermissions.join(", ")||"No capabilities"}

+

Approved: {item.grantedPermissions.join(", ")||"None"}

+

Independently reviewed by {item.reviewer}

+
+ {item.grantedPermissions.length>0 ? + : + } + {item.availableVersions.filter(x=>x!==item.version).map(version=> + )} + +
+
+
)} +
+
} + {data?.configured&&!data.registryUnavailable&&<> +
+
+ {releases.length?
+ {releases.map(release=>{ + const addon=release.manifest + const installedItem=installed.find(x=>x.id===addon.id) + const canStage=release.compatible && + (!installedItem || latest(addon.version,installedItem.version)) + return +
+ Independently reviewed + + {release.compatible?"Compatible":"Incompatible"} +
+ {addon.name} + {addon.summary||addon.id} +
+

{addon.category} · v{addon.version}

+

Capabilities: {addon.permissions.join(", ")||"None"}

+

Reviewer: {release.review.reviewer}

+

SHA-256: {release.digest}

+ + Publisher source + +
+ })} +
:

No active reviewed v2 releases match your search.

} + } + {(data?.installed.history?.length??0)>0 && + Executable review activity + Last 100 successful private staging and consent changes + + {[...(data?.installed.history??[])].reverse().slice(0,10).map(event=> +
+ {event.operation} {event.id} · {event.version} + {event.at.replace("T"," ").slice(0,16)} UTC +
)} +
} + {if(!open&&!busy)setPending(null)}}> + + Review executable add-on change + + Explicit review and consent are required. No executable code will run. + +
+
+ Cancel + void apply()}> + {busy?"Verifying signed release…":"Confirm owner decision"} + +
+
+
+} + /** Owner-only Account Mode UI. All mutations go through session and origin-checked routes. */ export function AccountAddonMarketplace({basePath="/docs"}: {basePath?: string}) { const [catalog, setCatalog] = React.useState(null) @@ -260,7 +518,7 @@ export function AccountAddonMarketplace({basePath="/docs"}: {basePath?: string})

Add-ons

Reviewed content

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

+ Executable v2 extensions remain non-runnable while their review and sandbox gates are unfinished.

{catalog &&

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

} @@ -344,6 +602,7 @@ export function AccountAddonMarketplace({basePath="/docs"}: {basePath?: string})

} } + {if(!open&&!busy)setPending(null)}}> Confirm add-on change diff --git a/packages/nextguide/test/extension-v2-site-manager.test.mjs b/packages/nextguide/test/extension-v2-site-manager.test.mjs new file mode 100644 index 0000000..da37a65 --- /dev/null +++ b/packages/nextguide/test/extension-v2-site-manager.test.mjs @@ -0,0 +1,323 @@ +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 { + existsSync, lstatSync, mkdtempSync, mkdirSync, readFileSync, + readdirSync, rmSync, writeFileSync, symlinkSync, +} from "node:fs" +import { tmpdir } from "node:os" +import { dirname, join } from "node:path" +import { gzipSync } from "node:zlib" +import { accountFile, createBootstrap } from "../lib/account-auth.mjs" +import { createAccountV2AddonManager } from "../lib/extension-v2-site-manager.mjs" +import { fullStudioRouteSource } from "../lib/account-studio-template.mjs" + +const keys=generateKeyPairSync("ed25519") +const pem=keys.publicKey.export({format:"pem",type:"spki"}) +const keyId=createHash("sha256").update(keys.publicKey.export({ + format:"der",type:"spki"})).digest("hex").slice(0,24) +const sha=b=>createHash("sha256").update(b).digest("hex") +const NOW=Date.parse("2026-11-09T12:30:00Z") +const source="export async function activate({request}) { await request('extension.info') }\n" +const bundle="throw new Error('never run downloaded code');\nexport async function activate() {}\n" +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) + h.write(h.reduce((a,b)=>a+b,0).toString(8).padStart(6,"0")+"\0 ",148,8) + return Buffer.concat([h,bytes,Buffer.alloc((512-bytes.length%512)%512)]) +} +function versioned(version,permissions=["storage.read","admin.pages"],extra=[]){ + const manifest={ + schemaVersion:2,id:"acme.storage",name:"Storage Example",version, + repository:"https://github.com/acme/storage",category:"integration", + compatibility:{mode:"account",nextguide:">=1.0.0 <2.0.0"}, + entrypoints:{server:"dist/server.mjs"},permissions, + } + const manifestBytes=Buffer.from(JSON.stringify(manifest)) + const src=Buffer.from(source) + const code=Buffer.from(bundle) + const ref=(path,bytes)=>({path,size:bytes.length,sha256:sha(bytes)}) + const index={ + schemaVersion:2,format:"nextguide-single-server-v2", + manifest:ref("nextguide-addon.json",manifestBytes), + source:ref("src/server.js",src), + server:ref("dist/server.mjs",code), + permissions, + } + const archive=gzipSync(Buffer.concat([ + member("nextguide-addon.json",manifestBytes), + member("src/server.js",src), + member("dist/server.mjs",code), + member("nextguide-integrity.json",JSON.stringify(index)), + ...extra.map(([path,bytes])=>member(path,bytes)), + Buffer.alloc(1024), + ]),{mtime:0}) + const release={ + manifest,tag:"v"+version,commit:"a".repeat(40), + digest:sha(archive),size:archive.length,status:"active", + assetUrl:"https://github.com/acme/storage/releases/download/v"+version+ + "/nextguide-addon-v2-"+version+".tgz", + review:{ + policy:"independent-human",reviewer:"staff-independent", + approvedAt:"2026-11-09T12:00:00Z", + sourceCommit:"a".repeat(40),sourcePath:"src/server.js", + sourceSha256:sha(src),serverSha256:sha(code), + manifestSha256:sha(manifestBytes),buildTool:"bun", + format:"nextguide-single-server-v2", + }, + } + return {archive,release} +} +function signed(releases,expire="2026-11-09T13:00:00Z"){ + const bytes=Buffer.from(JSON.stringify({ + schemaVersion:2,updatedAt:"2026-11-09T12:00:00Z",expiresAt:expire,releases + })) + return {schemaVersion:2,algorithm:"Ed25519",keyId, + body:bytes.toString("base64url"), + signature:sign(null,bytes,keys.privateKey).toString("base64url")} +} +function transportFor(artifacts){ + const calls=[] + return { + calls, + transport(opts,respond){ + const req=new EventEmitter() + req.destroy=()=>{} + req.end=()=>{ + calls.push(opts) + const match=artifacts.find(x=> + new URL(x.release.assetUrl).pathname===opts.path) + queueMicrotask(()=>{ + const stream=new PassThrough() + stream.statusCode=match?200:404 + stream.headers=match?{"content-length":String(match.archive.length)}:{} + respond(stream) + stream.end(match?.archive??"missing") + }) + } + return req + }, + } +} +function fixture({artifacts=[versioned("1.0.0")],releases=artifacts.map(a=>a.release), + version="1.0.0",expire,mode="account",online=true}={}){ + const base=mkdtempSync(join(tmpdir(),"ng-v2-account-stage-")) + const project=join(base,"site"),dataDir=join(base,"private") + mkdirSync(project) + writeFileSync(join(project,"nextguide.config.json"),JSON.stringify({ + mode,contentDir:"content/docs", + })) + createBootstrap(project,{dataDir}) + const network=transportFor(artifacts) + let envelope=signed(releases,expire) + const manager=()=>createAccountV2AddonManager({ + project,dataDir,nextguideVersion:version,now:()=>NOW, + registryUrl:"https://registry.example/v2/registry", + pinnedPublicKeyPem:pem, + registryFetch:async()=>{ + if(!online)throw Error("registry offline") + return new Response(JSON.stringify(envelope),{ + headers:{"content-type":"application/json"} + }) + }, + resolver:async()=>[{address:"93.184.216.34",family:4}], + transport:network.transport, + }) + return { + manager,network,project,dataDir, + offline:()=>{online=false}, + envelope:(value)=>{envelope=value}, + cleanup:()=>rmSync(base,{recursive:true,force:true}), + } +} +const stage=(manager,version="1.0.0",expectedRevision=0)=>manager.stage({ + id:"acme.storage",version,expectedRevision,consent:true, +}) +const grant=(manager,addon,revision,permissions=addon.requestedPermissions)=>manager.grant({ + id:addon.id,version:addon.version,digest:addon.digest, + expectedRevision:revision,permissions,consent:true, +}) + +test("reviewed v2 packages are staged privately and NEVER executable",async()=>{ + const f=fixture() + try{ + const m=f.manager() + assert.equal((await m.catalog()).releases.length,1) + await assert.rejects(m.stage({id:"acme.storage",version:"1.0.0", + expectedRevision:0,consent:false}),/owner consent/) + assert.equal(f.network.calls.length,0) + const result=await stage(m) + assert.equal(result.revision,1) + assert.equal(result.executionAvailable,false) + assert.equal(result.addon.execution,"blocked") + assert.deepEqual(result.addon.grantedPermissions,[]) + assert.deepEqual(result.addon.requestedPermissions,["storage.read","admin.pages"]) + assert.equal((await m.catalog()).installed.addons[0].execution,"blocked") + const root=join(dirname(accountFile(f.project,f.dataDir)),"addons-v2") + assert.equal(readdirSync(join(root,"blobs")).length,1) + assert.ok(existsSync(join(root,"staged.json"))) + assert.equal(lstatSync(join(root,"staged.json")).mode&0o777,0o600) + assert.equal(f.network.calls[0].rejectUnauthorized,true) + }finally{f.cleanup()} +}) + +test("permission grants are digest pinned, exact, explicitly consented and non-executable",async()=>{ + const f=fixture() + try{ + const m=f.manager() + const {addon}=await stage(m) + await assert.rejects(grant(m,addon,0),/changed/) + await assert.rejects(m.grant({id:addon.id,version:addon.version, + digest:addon.digest,permissions:addon.requestedPermissions, + expectedRevision:1,consent:false}),/owner consent/) + await assert.rejects(grant(m,addon,1,["storage.read"]),/every requested/) + await assert.rejects(grant(m,addon,1,["storage.read","network.fetch"]),/every requested|comparison|Invalid permission/) + await assert.rejects(grant(m,{...addon,digest:"f".repeat(64)},1),/revoked|changed|incompatible|not approved/i) + const granted=await grant(m,addon,1) + assert.equal(granted.addon.execution,"blocked") + assert.deepEqual(granted.addon.grantedPermissions,addon.requestedPermissions) + assert.equal(granted.revision,2) + const revoked=m.revoke({id:addon.id,expectedRevision:2,consent:true}) + assert.deepEqual(revoked.addon.grantedPermissions,[]) + assert.equal(revoked.revision,3) + }finally{f.cleanup()} +}) + +test("updates and rollback clear old permissions; downgrade requires explicit rollback",async()=>{ + const a=versioned("1.0.0"),b=versioned("1.1.0",["storage.read","network.fetch"]) + const f=fixture({artifacts:[a,b]}) + try{ + const m=f.manager() + const first=await stage(m) + await grant(m,first.addon,1) + const upgrade=await stage(m,"1.1.0",2) + assert.equal(upgrade.revision,3) + assert.deepEqual(upgrade.addon.grantedPermissions,[]) + assert.deepEqual(upgrade.addon.requestedPermissions,["storage.read","network.fetch"]) + await assert.rejects(stage(m,"1.0.0",3),/explicit rollback/) + const rolled=await m.rollback({id:a.release.manifest.id,version:"1.0.0", + expectedRevision:3,consent:true}) + assert.equal(rolled.addon.version,"1.0.0") + assert.deepEqual(rolled.addon.grantedPermissions,[]) + assert.equal(rolled.addon.execution,"blocked") + assert.deepEqual((await m.catalog()).installed.history.map(x=>x.operation),[ + "stage","grant","stage","rollback" + ]) + await assert.rejects(grant(m,upgrade.addon,4),/Pinned release changed/) + }finally{f.cleanup()} +}) + +test("revoked and expired records fail closed BEFORE downloading",async()=>{ + const a=versioned("1.0.0") + const f=fixture({artifacts:[a],releases:[{...a.release,status:"revoked"}]}) + try{ + const m=f.manager() + assert.equal((await m.catalog()).releases.length,0) + await assert.rejects(stage(m),/revoked|incompatible|missing/) + assert.equal(f.network.calls.length,0) + }finally{f.cleanup()} + const expired=fixture({artifacts:[a],expire:"2026-11-09T12:20:00Z"}) + try{ + assert.equal((await expired.manager().catalog()).registryUnavailable,true) + await assert.rejects(stage(expired.manager()),/expired/) + assert.equal(expired.network.calls.length,0) + }finally{expired.cleanup()} +}) + +test("malformed reviewed archive, tampering and forged registry signatures cannot stage",async()=>{ + const a=versioned("1.0.0") + const modified=Buffer.from(a.archive);modified[modified.length-1]^=1 + const f=fixture({artifacts:[{archive:modified,release:a.release}]}) + try{ + const m=f.manager() + await assert.rejects(stage(m),/SHA-256|mismatch|archive/i) + assert.equal((await m.catalog()).installed.revision,0) + assert.deepEqual((await m.catalog()).installed.addons,[]) + f.envelope({...signed([a.release]),signature:"a".repeat(86)}) + await assert.rejects(stage(m),/signature|signed/) + assert.equal(f.network.calls.length,1) + }finally{f.cleanup()} + const extra=versioned("1.0.0",["storage.read"],[["inject.mjs","throw Error('hi')"]]) + const bad=fixture({artifacts:[extra]}) + try{ + await assert.rejects(stage(bad.manager()),/unreviewed|unexpected/) + assert.equal((await bad.manager().catalog()).installed.revision,0) + }finally{bad.cleanup()} +}) + +test("offline revocation and uninstall remain possible; stale grants cannot survive corruption",async()=>{ + const f=fixture() + try{ + const m=f.manager() + const first=await stage(m) + await grant(m,first.addon,1) + f.offline() + const other=f.manager() + assert.equal((await other.catalog()).registryUnavailable,true) + assert.deepEqual((await other.catalog()).installed.addons[0].grantedPermissions, + ["storage.read","admin.pages"]) + await assert.rejects(grant(other,first.addon,2),/offline|registry/i) + const revoked=other.revoke({id:first.addon.id,expectedRevision:2,consent:true}) + assert.deepEqual(revoked.addon.grantedPermissions,[]) + const removed=other.uninstall({id:first.addon.id,expectedRevision:3,consent:true}) + assert.equal(removed.privateDataPreserved,true) + assert.equal((await other.catalog()).installed.addons.length,0) + }finally{f.cleanup()} +}) + +test("Account Mode only; v1 journal never accepts v2; alpha compatibility blocks staging",async()=>{ + const f=fixture({version:"0.0.1-alpha.2"}) + try{ + const m=f.manager() + assert.equal((await m.catalog()).releases[0].compatible,false) + await assert.rejects(stage(m),/incompatible/) + assert.equal(f.network.calls.length,0) + }finally{f.cleanup()} + const denied=fixture({mode:"developer"}) + try{ + assert.throws(()=>denied.manager(),/exclusive to Account Mode/) + }finally{denied.cleanup()} +}) + +test("private journal refuses symlink replacement and survives interrupted revision conflict",async()=>{ + const f=fixture() + try{ + const m=f.manager() + await stage(m) + await assert.rejects(stage(m),/changed|conflict|refresh/i) + const path=join(dirname(accountFile(f.project,f.dataDir)),"addons-v2","staged.json") + const backup=readFileSync(path) + rmSync(path) + symlinkSync(join(f.project,"nextguide.config.json"),path) + assert.throws(()=>m.revoke({id:"acme.storage",expectedRevision:1,consent:true}), + /symlink|linked|damaged/i) + rmSync(path) + writeFileSync(path,backup,{mode:0o600}) + assert.equal((await m.catalog()).installed.revision,1) + }finally{f.cleanup()} +}) + + +test("generated Account Mode studio gates every v2 action behind owner session and origin",()=>{ + for(const typed of [true,false]){ + const route=fullStudioRouteSource(typed) + assert.match(route,/if \(!authorized\(request\)\)/) + assert.match(route,/if \(!sameOrigin\(request\)\)/) + assert.match(route,/action === "addons-v2"/) + for(const action of ["stage","grant","revoke","rollback","uninstall"]){ + assert.ok(route.includes('action === "addon-v2-'+action+'"'), + "missing owner-authenticated v2 route "+action) + } + assert.ok(route.indexOf('if (action.startsWith("addon-v2-"))') < + route.indexOf('if (action.startsWith("addon-"))'), + "v2 routes must not accidentally dispatch to the v1 content installer") + assert.match(route,/createAccountV2AddonManager\(\{ project: process\.cwd\(\) \}\)/) + } +})