diff --git a/apps/web/contents/addons/_meta.json b/apps/web/contents/addons/_meta.json index 7acb516..ae3f947 100644 --- a/apps/web/contents/addons/_meta.json +++ b/apps/web/contents/addons/_meta.json @@ -23,6 +23,10 @@ "slug": "permissions", "title": "Permissions & security" }, + { + "slug": "v2-supply-chain", + "title": "Reviewed v2 packages" + }, { "slug": "publishing", "title": "Publishing & review" diff --git a/apps/web/contents/addons/index.mdx b/apps/web/contents/addons/index.mdx index 93cdf5f..b3bad78 100644 --- a/apps/web/contents/addons/index.mdx +++ b/apps/web/contents/addons/index.mdx @@ -34,6 +34,12 @@ The developer publisher supports GitHub App sign-in, repository selection, prefl The extension host is not a security sandbox. Executable add-ons require a separate isolated runner, verified artifacts and owner-approved permissions before we can offer them in the marketplace. +## Executable v2 developer and review track + +The [official add-on template](https://github.com/m1nsook/NextGuide-Addons) now provides a complete **offline v2 JavaScript/TypeScript developer lab**, including Bun compilation, deterministic archive packaging, source-bound SHA-256 and an example brokered admin page. NextGuide itself can verify short-lived, independently signed v2 review metadata, the exact archive, source and compiled bytes, and safely download them through a DNS-pinned GitHub asset transport. + +This **does not** make executable packages publishable through the current v1-only private ngapi registry or installable in Account Mode. See [Reviewed v2 packages](/addons/v2-supply-chain) for the signed protocol and remaining security gates. + ## Documentation routes Add-on developer docs live under `/addons` with a dedicated sidebar, search, and page navigation. For framework basics, visit [NextGuide documentation](/docs); for UI component examples, see the [component catalog](/components). diff --git a/apps/web/contents/addons/v2-supply-chain.mdx b/apps/web/contents/addons/v2-supply-chain.mdx new file mode 100644 index 0000000..4b96467 --- /dev/null +++ b/apps/web/contents/addons/v2-supply-chain.mdx @@ -0,0 +1,45 @@ +--- +title: Reviewed v2 packages +description: The signed executable release protocol, byte-level verifier and private registry rollout boundary. +--- + +# 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. + +## Source to trusted bytes + +1. Author a JavaScript/TypeScript extension in the [NextGuide-Addons template](https://github.com/m1nsook/NextGuide-Addons), then build the deterministic v2 archive. +2. Publish an immutable GitHub Release linked to a specific source commit. +3. An independent reviewer validates original source, exact bundle, requested capabilities, reproducible build and package integrity. +4. The private ngapi operator signs the reviewed release with Ed25519. The signature binds repository, commit, manifest, source SHA-256, compiled bundle SHA-256, reviewer, requested permissions and active/revoked status. +5. An Account Mode host pins the public verification key, fetches a short-lived signed index and downloads only that exact approved GitHub artifact through DNS-pinned HTTPS. +6. Installation and execution still require an explicit site-owner permission grant and production-approved OS isolation. + +## Versioned registry contract + +The future signed index lives at the separate HTTPS path **/v2/registry** and has **schemaVersion 2**, issue and expiration timestamps (maximum six-hour signed lifetime), and a list of immutable reviewed releases. Its signatures and release formats cannot be confused with the working v1 content-only format. + +Every signed release must include a complete v2 Account Mode manifest and a review attestation with the original commit, review identity, original source and compiled bundle digests. The archive uses the narrow single-file server developer format: original source file, compiled server module, exact manifest, and a per-member SHA-256 integrity descriptor. An optional signed PNG icon is supported. + +The verifier rejects unapproved executable permissions, revoked or expired metadata, invalid keys and signatures, mismatching byte hashes, unexpected archive files, symlinks, unsafe paths and decompression bombs. + +## Verify a release without executing it + + + +For already-downloaded archives use the **nextguide/extensions/v2-artifacts** verifier. The **nextguide/extensions/v2-catalog** module also provides a permission-diff helper; identifying newly requested permissions is not a grant. + +The signed catalog and archive are checked independently, without writing third-party code to disk or importing it into the Next.js host. + +## Private ngapi deployment requirements + +The registry backend must verify independent review, reproducible build provenance and immutable GitHub assets before signing. Signed indexes need expiration, revocation and signing-key rotation procedures. Server-side authorization must never accept a publisher-supplied reviewer field as proof without authenticated staff approval. No private keys or private registry server implementation belong in the public NextGuide package. + +**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. + +## 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. + +Do not treat an Ed25519 signature as permission to execute JavaScript. See the [security roadmap](https://github.com/m1nsook/NextGuide/issues/101). diff --git a/packages/nextguide/lib/extension-download.d.mts b/packages/nextguide/lib/extension-download.d.mts index 21f5497..5b8db9a 100644 --- a/packages/nextguide/lib/extension-download.d.mts +++ b/packages/nextguide/lib/extension-download.d.mts @@ -11,3 +11,19 @@ export declare function downloadVerifiedContentRelease(options: { signal?: AbortSignal timeoutMs?: number }): Promise + + +import type { VerifiedV2Artifact } from "./extension-v2-artifacts.mjs" +/** Read-only verified executable package intake. Not an installer or runner. */ +export declare function downloadReviewedV2Release(options:{ + envelope:unknown + pinnedPublicKeyPem:string + id:string + version:string + resolver?:(host:string,opts:{family:number;all:boolean;verbatim:boolean})=> + Promise> + transport?:(...args:any[])=>any + signal?:AbortSignal + timeoutMs?:number + now?:()=>number +}):Promise<{archive:Buffer;verified:VerifiedV2Artifact}> diff --git a/packages/nextguide/lib/extension-download.mjs b/packages/nextguide/lib/extension-download.mjs index 7a39809..fb06ea4 100644 --- a/packages/nextguide/lib/extension-download.mjs +++ b/packages/nextguide/lib/extension-download.mjs @@ -1,5 +1,5 @@ /** - * Strict, read-only downloader for *signed* v1 GitHub Release artifacts. + * Strict, read-only downloader for signed, reviewed GitHub Release artifacts. * * This is host-side Node code, not an add-on network capability. The target * URL comes only from a verified signed registry release. GitHub's asset @@ -11,6 +11,8 @@ import { lookup as dnsLookup } from "node:dns/promises" import { request as httpsRequest } from "node:https" import { verifySignedRegistryEnvelope } from "./extension-catalog.mjs" import { verifyApprovedContentArchive } from "./extension-artifacts.mjs" +import { verifySignedV2RegistryEnvelope } from "./extension-v2-catalog.mjs" +import { verifyReviewedV2Archive } from "./extension-v2-artifacts.mjs" import { isPublicExtensionIPv4 } from "./extension-network.mjs" const MAX_BYTES = 3 * 1024 * 1024 @@ -187,3 +189,54 @@ export async function downloadVerifiedContentRelease({ } return fail("DOWNLOAD_FAILED", "Could not download reviewed artifact") } + + +/** + * V2 read-only review intake: downloads only an active, nonexpired, signed + * release, enforces public IPv4 DNS/TLS/CDN confinement, and verifies every + * executable/source byte. It DOES NOT install, grant permissions or run code. + * + * This is intentionally independent of the v1 Account Mode installer. The + * private registry must serve a separately signed /v2/registry index before + * any public v2 release can pass these checks. + */ +export async function downloadReviewedV2Release({ + envelope,pinnedPublicKeyPem,id,version, + resolver=dnsLookup,transport=httpsRequest, + signal,timeoutMs=15000,now=()=>Date.now(), +}={}){ + if(!ID.test(id) || !VERSION.test(version) || + typeof resolver!=="function" || typeof transport!=="function" || + !Number.isSafeInteger(timeoutMs) || timeoutMs<100 || timeoutMs>30000 || + typeof now!=="function" || !Number.isFinite(now())){ + fail("CONFIGURATION","Invalid v2 release request or trusted downloader options") + } + // Authenticate and check expiry BEFORE ANY DNS request or HTTPS fetch. + const catalog=verifySignedV2RegistryEnvelope(envelope,pinnedPublicKeyPem,{now:now()}) + const release=catalog.releases.find(r=> + r.manifest.id===id && r.manifest.version===version) + if(!release || release.status!=="active" || + release.size<32 || release.size>MAX_BYTES){ + fail("NOT_APPROVED","No active, reviewed signed v2 release") + } + const first=release.assetUrl + let current=safeUrl(first,first,false) + const timer=AbortSignal.timeout(timeoutMs) + const active=signal?AbortSignal.any([signal,timer]):timer + for(let attempt=0;attempt<=MAX_REDIRECTS;attempt++){ + if(active.aborted)throw cancelled() + const result=await pinnedGet(current,release.size,{resolver,transport,signal:active}) + if(result.bytes){ + // The v2 release key and archive/source/bundle digest are rechecked + // before returning the original bytes for private storage/review. + const verified=verifyReviewedV2Archive({ + envelope,pinnedPublicKeyPem,id,version,archive:result.bytes, + now:now(), + }) + return {archive:result.bytes,verified} + } + if(attempt===MAX_REDIRECTS)fail("INVALID_REDIRECT","GitHub asset redirected too many times") + current=safeUrl(result.redirect,first,true) + } + return fail("DOWNLOAD_FAILED","Reviewed v2 release could not be downloaded") +} diff --git a/packages/nextguide/lib/extension-v2-artifacts.d.mts b/packages/nextguide/lib/extension-v2-artifacts.d.mts new file mode 100644 index 0000000..56b5c46 --- /dev/null +++ b/packages/nextguide/lib/extension-v2-artifacts.d.mts @@ -0,0 +1,24 @@ +import type { + V2ExecutableManifest,V2ReviewAttestation +} from "./extension-v2-catalog.mjs" +/** + * Approved source and compiled code BYTES in memory, not an execution grant. + * Must never be imported into Next.js. OS sandbox and owner permissions required. + */ +export interface VerifiedV2Artifact { + id:string + version:string + manifest:V2ExecutableManifest + archiveSha256:string + source:{path:string;sha256:string;text:string} + compiled:{path:"dist/server.mjs";sha256:string;code:string} + review:V2ReviewAttestation +} +export declare function verifyReviewedV2Archive(options:{ + envelope:unknown + pinnedPublicKeyPem:string + id:string + version:string + archive:Uint8Array + now?:number +}):VerifiedV2Artifact diff --git a/packages/nextguide/lib/extension-v2-artifacts.mjs b/packages/nextguide/lib/extension-v2-artifacts.mjs new file mode 100644 index 0000000..ccf6285 --- /dev/null +++ b/packages/nextguide/lib/extension-v2-artifacts.mjs @@ -0,0 +1,193 @@ +/** + * Read-only byte verifier for reviewed NextGuide executable v2 archives. + * + * Requires a fresh Ed25519-signed private ngapi v2 release approval. Confirms + * exact GitHub asset digest and immutable independently reviewed source, build + * and capability metadata before returning bytes in memory. + * + * No path extraction, no import(), no code execution, no permission grants. + */ +import { createHash } from "node:crypto" +import { gunzipSync } from "node:zlib" +import { verifySignedV2RegistryEnvelope } from "./extension-v2-catalog.mjs" + +const MAX_ARCHIVE=3*1024*1024 +const MAX_TAR=3*1024*1024 +const MAX_MEMBER=1024*1024 +const MAX_SOURCE=512*1024 +const MAX_MEMBERS=5 +const HASH=/^[a-f0-9]{64}$/ +const PATH=/^[A-Za-z0-9_-][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*$/ +const PNG=Buffer.from([137,80,78,71,13,10,26,10]) +const RECORD_KEYS=new Set(["path","size","sha256"]) +const INDEX_KEYS=new Set([ + "schemaVersion","format","manifest","source","server","icon","permissions" +]) +function fail(message){throw Error("NextGuide v2 artifact: "+message)} +function record(v){return v!==null && typeof v==="object" && !Array.isArray(v)} +function sha(bytes){return createHash("sha256").update(bytes).digest("hex")} +function utf8(bytes,label){ + try {return new TextDecoder("utf-8",{fatal:true}).decode(bytes)} + catch {fail("Invalid UTF-8 in "+label)} +} +function parse(bytes,label){ + let obj + try {obj=JSON.parse(utf8(bytes,label))} + catch {fail("Invalid JSON in "+label)} + if(!record(obj))fail(label+" must be a JSON object") + return obj +} +function stable(value){ + if(Array.isArray(value))return "["+value.map(stable).join(",")+"]" + if(record(value))return "{"+Object.keys(value).sort() + .map(key=>JSON.stringify(key)+":"+stable(value[key])).join(",")+"}" + return JSON.stringify(value) +} +function safePath(path){ + return typeof path==="string" && path.length<=100 && + PATH.test(path) && path.split("/").every(x=> + x!=="." && x!==".." && !x.startsWith(".") && !x.endsWith(".")) +} +function octal(bytes){ + const raw=bytes.toString("ascii").replace(/\0.*$/,"").trim() + if(!/^[0-7]+$/.test(raw))fail("Malformed octal tar field") + const n=Number.parseInt(raw,8) + if(!Number.isSafeInteger(n))fail("Oversized tar number") + return n +} +function archiveFiles(archive){ + if(!(archive instanceof Uint8Array) || archive.length<32 || + archive.length>MAX_ARCHIVE || archive[0]!==0x1f || archive[1]!==0x8b){ + fail("Expected bounded gzip archive") + } + let tar + try{tar=gunzipSync(archive,{maxOutputLength:MAX_TAR})} + catch{fail("Corrupt gzip or decompression quota exceeded")} + const files=new Map() + let offset=0,closed=false + while(offset+512<=tar.length){ + const header=tar.subarray(offset,offset+512) + if(header.every(x=>x===0)){ + if(tar.length-offset<1024 || + tar.subarray(offset).some(x=>x!==0))fail("Invalid tar terminator") + closed=true + break + } + if(header.subarray(257,263).toString("ascii")!=="ustar\0" || + header.subarray(263,265).toString("ascii")!=="00" || + header[156]!==48 || + header.subarray(345,500).some(x=>x!==0)) { + fail("Only regular ustar files are supported (no links or extensions)") + } + const chksum=Buffer.from(header) + chksum.fill(32,148,156) + if(chksum.reduce((a,b)=>a+b,0)!==octal(header.subarray(148,156))) { + fail("Tar header checksum changed") + } + const pathEnd=header.subarray(0,100).indexOf(0) + const name=utf8(header.subarray(0,pathEnd<0?100:pathEnd),"tar path") + if(!safePath(name) || files.has(name.toLowerCase()))fail("Unsafe or colliding tar path") + const size=octal(header.subarray(124,136)) + const start=offset+512,finish=start+size + const next=start+Math.ceil(size/512)*512 + if(size<1 || size>MAX_MEMBER || next>tar.length || + tar.subarray(finish,next).some(x=>x!==0))fail("Invalid archive member size or padding") + files.set(name.toLowerCase(),{name,bytes:Buffer.from(tar.subarray(start,finish))}) + if(files.size>MAX_MEMBERS)fail("Too many executable archive members") + offset=next + } + if(!closed)fail("Tar end-of-archive blocks missing") + return files +} +function checkedFile(files,ref,label,maxSize){ + if(!record(ref) || Object.keys(ref).sort().join(",")!=="path,sha256,size" || + !safePath(ref.path) || !HASH.test(ref.sha256) || + !Number.isSafeInteger(ref.size) || ref.size<1 || ref.size>maxSize) { + fail("Invalid "+label+" integrity record") + } + const found=files.get(ref.path.toLowerCase()) + if(!found || found.name!==ref.path || found.bytes.length!==ref.size || + sha(found.bytes)!==ref.sha256)fail("Reviewed "+label+" digest/size mismatch") + return found.bytes +} +function checkedIndex(files,release){ + const indexMember=files.get("nextguide-integrity.json") + const manifestMember=files.get("nextguide-addon.json") + if(!indexMember || !manifestMember)fail("Missing v2 manifest or integrity index") + const index=parse(indexMember.bytes,"nextguide-integrity.json") + if(!Object.keys(index).every(x=>INDEX_KEYS.has(x)) || + index.schemaVersion!==2 || + index.format!=="nextguide-single-server-v2" || + !Array.isArray(index.permissions) || + stable(index.permissions)!==stable(release.manifest.permissions) || + !record(index.source) || + index.source.path!==release.review.sourcePath || + !record(index.server) || index.server.path!=="dist/server.mjs" || + !record(index.manifest) || index.manifest.path!=="nextguide-addon.json"){ + fail("Unapproved v2 integrity descriptor or permissions") + } + const manifestBytes=checkedFile(files,index.manifest,"manifest",65536) + const sourceBytes=checkedFile(files,index.source,"source",MAX_SOURCE) + const serverBytes=checkedFile(files,index.server,"server",MAX_MEMBER) + if(sha(manifestBytes)!==release.review.manifestSha256 || + sha(sourceBytes)!==release.review.sourceSha256 || + sha(serverBytes)!==release.review.serverSha256) { + fail("Reviewed v2 source/bundle attestations do not match the archive") + } + const manifest=parse(manifestBytes,"nextguide-addon.json") + if(stable(manifest)!==stable(release.manifest))fail("Archive manifest differs from signed v2 release") + const names=[ + "nextguide-integrity.json","nextguide-addon.json", + index.source.path,"dist/server.mjs" + ] + if(manifest.icon!==undefined){ + names.push(manifest.icon) + if(!record(index.icon) || index.icon.path!==manifest.icon){ + fail("Icon integrity record missing or inconsistent") + } + const icon=checkedFile(files,index.icon,"PNG icon",256*1024) + if(icon.length<45 || !icon.subarray(0,8).equals(PNG) || + icon.subarray(12,16).toString("ascii")!=="IHDR" || + icon.readUInt32BE(8)!==13 || + icon.readUInt32BE(16)<32 || icon.readUInt32BE(20)<32 || + icon.readUInt32BE(16)>1024 || icon.readUInt32BE(20)>1024){ + fail("Invalid reviewed PNG icon") + } + } else if(index.icon!==undefined)fail("Unexpected unsigned icon") + if(files.size!==names.length || + new Set(names.map(x=>x.toLowerCase())).size!==names.length || + names.some(x=>!files.has(x.toLowerCase()))) { + fail("Executable archive contains unreviewed or duplicate members") + } + const code=utf8(serverBytes,"compiled server") + // Only data is returned. Callers must still enforce grants and OS sandboxing. + return { + manifest:JSON.parse(JSON.stringify(manifest)), + archiveSha256:release.digest, + source:{path:index.source.path,sha256:index.source.sha256, + text:utf8(sourceBytes,"reviewable source")}, + compiled:{path:"dist/server.mjs",sha256:index.server.sha256,code}, + review:JSON.parse(JSON.stringify(release.review)), + } +} + +/** + * Verifies the exact release from the signed, expiry-bound v2 catalog. + * An active release remains non-executable until an independently approved + * installed-site permission grant and actual secure OS sandbox exist. + */ +export function verifyReviewedV2Archive({ + envelope,pinnedPublicKeyPem,id,version,archive,now=Date.now(), +}={}){ + const catalog=verifySignedV2RegistryEnvelope(envelope,pinnedPublicKeyPem,{now}) + const release=catalog.releases.find(r=> + r.manifest.id===id && r.manifest.version===version) + if(!release || release.status!=="active")fail("V2 release is missing or revoked") + if(!(archive instanceof Uint8Array) || + archive.byteLength!==release.size || + sha(archive)!==release.digest){ + fail("Archive SHA-256 or size differs from signed v2 review") + } + const content=checkedIndex(archiveFiles(archive),release) + return {...content,id,version} +} diff --git a/packages/nextguide/lib/extension-v2-catalog.d.mts b/packages/nextguide/lib/extension-v2-catalog.d.mts new file mode 100644 index 0000000..909218a --- /dev/null +++ b/packages/nextguide/lib/extension-v2-catalog.d.mts @@ -0,0 +1,78 @@ +/** Read-only signed v2 registry protocol; never an execution permission grant. */ +export type V2Capability = + | "docs.pages" | "mdx.blocks" | "ui.components" | "admin.pages" + | "theme.tokens" | "icons.packs" | "i18n.locales" | "ai.providers" + | "auth.providers" | "server.routes" | "server.jobs" + | "storage.read" | "storage.write" | "network.fetch" | "secrets.read" +export interface V2ExecutableManifest { + schemaVersion: 2 + id: string + name: string + version: string + repository: string + category: string + compatibility: { mode:"account"; nextguide:string } + permissions: V2Capability[] + entrypoints: {server:"dist/server.mjs"} + icon?:string + summary?:string + description?:string + author?:{name:string;url?:string} + license?:string + keywords?:string[] + $schema?:string +} +export interface V2ReviewAttestation { + policy:"independent-human" + reviewer:string + approvedAt:string + sourceCommit:string + sourcePath:string + sourceSha256:string + serverSha256:string + manifestSha256:string + buildTool:"bun" + format:"nextguide-single-server-v2" +} +export interface ReviewedV2Release { + manifest:V2ExecutableManifest + assetUrl:string + tag:string + commit:string + digest:string + size:number + status:"active"|"revoked" + review:V2ReviewAttestation +} +export interface VerifiedV2Registry { + schemaVersion:2 + updatedAt:string + expiresAt:string + releases:ReviewedV2Release[] +} +export declare function validateV2Manifest(value:unknown):V2ExecutableManifest +export declare function verifySignedV2RegistryEnvelope( + envelope:unknown,pinnedPublicKeyPem:string,options?:{now?:number} +):VerifiedV2Registry +export declare function listReviewedV2Releases( + payload:VerifiedV2Registry,options?:{now?:number} +):ReviewedV2Release[] +export declare function compareV2Permissions( + previous:readonly V2Capability[],next:readonly V2Capability[], + approved?:readonly V2Capability[] +):{ + added:V2Capability[] + removed:V2Capability[] + ungranted:V2Capability[] + requiresOwnerApproval:boolean +} +export declare function createVerifiedV2RegistryClient(options:{ + registryUrl:string + pinnedPublicKeyPem:string + fetchImpl?:typeof fetch + now?:()=>number +}):{ + fetchSignedEnvelope():Promise + fetchVerified():Promise + listReviewed():Promise +} diff --git a/packages/nextguide/lib/extension-v2-catalog.mjs b/packages/nextguide/lib/extension-v2-catalog.mjs new file mode 100644 index 0000000..a2232f2 --- /dev/null +++ b/packages/nextguide/lib/extension-v2-catalog.mjs @@ -0,0 +1,253 @@ +/** + * Signed v2 executable-release catalog verification (read-only). + * + * Protocol draft for private ngapi: an independent reviewer signs a complete + * immutable GitHub Release, source revision, compiled byte hashes and capability + * list. V1 signatures cannot be replayed as v2 approvals. + * + * This module deliberately does not install, grant, import or run executable + * extensions. No private registry signing key is used by NextGuide sites. + */ +import { createHash, createPublicKey, verify as verifyEd25519 } from "node:crypto" + +const MAX_ENVELOPE = 4 * 1024 * 1024 +const MAX_BODY = 2 * 1024 * 1024 +const MAX_RELEASES = 5_000 +const MAX_AGE = 6 * 60 * 60 * 1000 +const FUTURE_SKEW = 5 * 60 * 1000 +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 GITHUB = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/?$/ +const SHA256 = /^[a-f0-9]{64}$/ +const SHA40 = /^[a-f0-9]{40}$/ +const B64URL = /^[A-Za-z0-9_-]+$/ +const CAPABILITIES = new Set([ + "docs.pages","mdx.blocks","ui.components","admin.pages","theme.tokens", + "icons.packs","i18n.locales","ai.providers","auth.providers", + "server.routes","server.jobs","storage.read","storage.write", + "network.fetch","secrets.read", +]) +const CATEGORIES = new Set([ + "content","theme","icons","language","ai","oauth", + "integration","accessibility","other", +]) +const manifestKeys = new Set([ + "$schema","schemaVersion","id","name","summary","description","version", + "author","repository","license","category","keywords","compatibility", + "permissions","entrypoints","icon", +]) +const seenVerified = new WeakMap() +function fail(message) { throw Error("NextGuide v2 registry: " + message) } +function record(v) { return v !== null && typeof v === "object" && !Array.isArray(v) } +function limited(v, len) { return typeof v === "string" && v.length > 0 && v.length <= len } +function sha(v) { return createHash("sha256").update(v).digest("hex") } +function exactKeys(value, names) { + return record(value) && Object.keys(value).every(x => names.has(x)) +} +function keyIdentifier(key) { + return sha(key.export({type:"spki",format:"der"})).slice(0,24) +} +function isoTime(value) { + return typeof value === "string" && + /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/.test(value) && + Number.isFinite(Date.parse(value)) +} +function semverNewer(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] + return false +} +function stable(value) { + if (Array.isArray(value)) return "["+value.map(stable).join(",")+"]" + if (record(value)) return "{"+Object.keys(value).sort() + .map(key=>JSON.stringify(key)+":"+stable(value[key])).join(",")+"}" + return JSON.stringify(value) +} +export function validateV2Manifest(manifest) { + if (!exactKeys(manifest,manifestKeys) || manifest.schemaVersion!==2 || + !ID.test(manifest.id) || manifest.id.length>100 || + !VERSION.test(manifest.version) || + !limited(manifest.name,80) || manifest.name.length<3 || + !GITHUB.test(manifest.repository) || + !CATEGORIES.has(manifest.category) || + !record(manifest.compatibility) || + Object.keys(manifest.compatibility).sort().join(",")!=="mode,nextguide" || + manifest.compatibility.mode!=="account" || + typeof manifest.compatibility.nextguide!=="string" || + !/^>=\d+\.\d+\.\d+\s+<\d+\.\d+\.\d+$/.test(manifest.compatibility.nextguide) || + !Array.isArray(manifest.permissions) || + manifest.permissions.length>16 || + manifest.permissions.some(p=>!CAPABILITIES.has(p)) || + new Set(manifest.permissions).size!==manifest.permissions.length || + !exactKeys(manifest.entrypoints,new Set(["server"])) || + manifest.entrypoints.server!=="dist/server.mjs") { + fail("Invalid v2 Account Mode server manifest or capabilities") + } + if (manifest.$schema!==undefined && !limited(manifest.$schema,512)) fail("Invalid schema path") + if (manifest.summary!==undefined && !limited(manifest.summary,160)) fail("Invalid summary") + if (manifest.description!==undefined && !limited(manifest.description,2000)) fail("Invalid description") + if (manifest.license!==undefined && !limited(manifest.license,80)) fail("Invalid license") + if (manifest.author!==undefined && + (!exactKeys(manifest.author,new Set(["name","url"])) || + !limited(manifest.author.name,100))) fail("Invalid author") + if (manifest.icon!==undefined && + (typeof manifest.icon!=="string" || manifest.icon.length>100 || + !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.png$/.test(manifest.icon))) { + fail("Invalid icon path") + } + if (manifest.keywords!==undefined && + (!Array.isArray(manifest.keywords) || manifest.keywords.length>12 || + new Set(manifest.keywords).size!==manifest.keywords.length || + manifest.keywords.some(p=>typeof p!=="string" || !/^[a-z0-9][a-z0-9-]{1,39}$/.test(p)))) { + fail("Invalid keywords") + } + return manifest +} +function validateRelease(release) { + if (!record(release) || !record(release.manifest)) fail("Invalid release record") + const m=validateV2Manifest(release.manifest) + const owner=GITHUB.exec(m.repository) + const tag="v"+m.version + const assetUrl="https://github.com/"+owner[1]+"/"+owner[2]+ + "/releases/download/"+tag+"/nextguide-addon-v2-"+m.version+".tgz" + if (release.assetUrl!==assetUrl || release.tag!==tag || + !SHA40.test(release.commit) || + !SHA256.test(release.digest) || + !Number.isSafeInteger(release.size) || release.size<32 || + release.size>3*1024*1024 || + !["active","revoked"].includes(release.status) || + !record(release.review) || + !exactKeys(release.review,new Set([ + "policy","reviewer","approvedAt","sourceCommit","sourcePath", + "sourceSha256","serverSha256","manifestSha256","buildTool","format" + ])) || + release.review.policy!=="independent-human" || + !limited(release.review.reviewer,100) || + !isoTime(release.review.approvedAt) || + release.review.sourceCommit!==release.commit || + !/^src\/server\.(?:ts|js|mjs)$/.test(release.review.sourcePath) || + !SHA256.test(release.review.sourceSha256) || + !SHA256.test(release.review.serverSha256) || + !SHA256.test(release.review.manifestSha256) || + release.review.buildTool!=="bun" || + release.review.format!=="nextguide-single-server-v2") { + fail("Invalid v2 reviewed release metadata or immutable GitHub artifact") + } +} +function validateSignedPayload(payload, now) { + if (!record(payload) || payload.schemaVersion!==2 || + !isoTime(payload.updatedAt) || !isoTime(payload.expiresAt) || + !Array.isArray(payload.releases) || payload.releases.length>MAX_RELEASES) { + fail("Invalid signed v2 payload") + } + const issued=Date.parse(payload.updatedAt), expires=Date.parse(payload.expiresAt) + if (expires<=issued || expires-issued>MAX_AGE || + now=expires) { + fail("Signed v2 catalog is expired, future-dated or exceeds its lifetime") + } + const encountered=new Set() + for (const release of payload.releases) { + validateRelease(release) + const key=release.manifest.id+"@"+release.manifest.version + if (encountered.has(key)) fail("Duplicate v2 release") + encountered.add(key) + } + return payload +} + +/** Pinned-key Ed25519; freshness/revocation checked on EVERY verification. */ +export function verifySignedV2RegistryEnvelope(envelope,pinnedPublicKeyPem,{now=Date.now()}={}) { + if (!record(envelope) || envelope.schemaVersion!==2 || + envelope.algorithm!=="Ed25519" || + !limited(envelope.keyId,64) || !limited(envelope.body,MAX_ENVELOPE) || + !limited(envelope.signature,120) || + !B64URL.test(envelope.body) || !B64URL.test(envelope.signature) || + typeof pinnedPublicKeyPem!=="string" || + !Number.isFinite(now)) fail("Invalid signed v2 envelope or trusted key") + let key + try { key=createPublicKey(pinnedPublicKeyPem) } + catch { fail("Invalid pinned v2 key") } + if (key.asymmetricKeyType!=="ed25519" || + envelope.keyId!==keyIdentifier(key)) fail("Untrusted v2 signing key") + const body=Buffer.from(envelope.body,"base64url") + const sig=Buffer.from(envelope.signature,"base64url") + if (body.length>MAX_BODY || sig.length!==64 || + body.toString("base64url")!==envelope.body || + sig.toString("base64url")!==envelope.signature || + !verifyEd25519(null,body,key,sig)) fail("V2 Ed25519 signature verification failed") + let payload + try { payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(body)) } + catch { fail("Invalid signed v2 JSON") } + validateSignedPayload(payload,now) + seenVerified.set(payload,sha(stable(payload))) + return payload +} +export function listReviewedV2Releases(payload,{now=Date.now()}={}) { + if (!record(payload) || seenVerified.get(payload)!==sha(stable(payload))) { + fail("V2 catalog is not authenticated or was modified") + } + validateSignedPayload(payload,now) + const selected=new Map() + for(const release of payload.releases){ + if(release.status!=="active")continue + const prev=selected.get(release.manifest.id) + if(!prev || semverNewer(release.manifest.version,prev.manifest.version)) { + selected.set(release.manifest.id,release) + } + } + return [...selected.values()].map(r=>JSON.parse(JSON.stringify(r))) +} +/** Presentation-only diff. Grants still require trusted site owner consent. */ +export function compareV2Permissions(previous,next,approved=[]) { + if (![previous,next,approved].every(Array.isArray) || + [...previous,...next,...approved].some(x=>!CAPABILITIES.has(x)) || + [previous,next,approved].some(x=>new Set(x).size!==x.length)) { + fail("Invalid permission comparison") + } + const old=new Set(previous), now=new Set(next), grants=new Set(approved) + const added=next.filter(x=>!old.has(x)) + const removed=previous.filter(x=>!now.has(x)) + const ungranted=next.filter(x=>!grants.has(x)) + return {added,removed,ungranted,requiresOwnerApproval:ungranted.length>0} +} +export function createVerifiedV2RegistryClient({registryUrl,pinnedPublicKeyPem,fetchImpl=fetch,now=()=>Date.now()}={}) { + let url + try { url=new URL(registryUrl) } catch { fail("Invalid v2 registry URL") } + if (url.protocol!=="https:" || url.username || url.password || + url.search || url.hash || url.pathname!=="/v2/registry" || + url.port || typeof pinnedPublicKeyPem!=="string" || !pinnedPublicKeyPem) { + fail("A pinned-key HTTPS /v2/registry is required") + } + return { + async fetchSignedEnvelope() { + const response=await fetchImpl(url.toString(),{ + method:"GET",redirect:"error",cache:"no-store", + signal:AbortSignal.timeout(8000), + headers:{Accept:"application/json"} + }) + if (!response.ok || !response.body) fail("V2 registry HTTP request failed") + const stated=response.headers.get("content-length") + if (stated!==null && (!/^\d+$/.test(stated) || + Number(stated)>MAX_ENVELOPE)) fail("Oversized v2 catalog response") + const chunks=[] + let total=0 + for await(const part of response.body){ + total+=part.length + if(total>MAX_ENVELOPE)fail("Oversized v2 catalog response") + chunks.push(Buffer.from(part)) + } + let envelope + try { envelope=JSON.parse(Buffer.concat(chunks).toString("utf8")) } + catch { fail("Invalid v2 catalog response JSON") } + verifySignedV2RegistryEnvelope(envelope,pinnedPublicKeyPem,{now:now()}) + return envelope + }, + async fetchVerified(){ + return verifySignedV2RegistryEnvelope( + await this.fetchSignedEnvelope(),pinnedPublicKeyPem,{now:now()}) + }, + async listReviewed(){ + return listReviewedV2Releases(await this.fetchVerified(),{now:now()}) + }, + } +} diff --git a/packages/nextguide/package.json b/packages/nextguide/package.json index 8c55e05..b54818f 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-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: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-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:unit": "bunx vitest run", "check-types": "node scripts/build.mjs" }, @@ -199,6 +199,16 @@ "types": "./lib/extension-site-manager.d.mts", "node": "./lib/extension-site-manager.mjs", "default": "./lib/extension-site-manager.mjs" + }, + "./extensions/v2-catalog": { + "types": "./lib/extension-v2-catalog.d.mts", + "node": "./lib/extension-v2-catalog.mjs", + "default": "./lib/extension-v2-catalog.mjs" + }, + "./extensions/v2-artifacts": { + "types": "./lib/extension-v2-artifacts.d.mts", + "node": "./lib/extension-v2-artifacts.mjs", + "default": "./lib/extension-v2-artifacts.mjs" } }, "imports": { diff --git a/packages/nextguide/test/extension-v2.test.mjs b/packages/nextguide/test/extension-v2.test.mjs new file mode 100644 index 0000000..b4b951f --- /dev/null +++ b/packages/nextguide/test/extension-v2.test.mjs @@ -0,0 +1,263 @@ +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 { + verifySignedV2RegistryEnvelope, listReviewedV2Releases, + compareV2Permissions, createVerifiedV2RegistryClient, +} from "../lib/extension-v2-catalog.mjs" +import { verifyReviewedV2Archive } from "../lib/extension-v2-artifacts.mjs" +import { downloadReviewedV2Release } from "../lib/extension-download.mjs" + +const keys=generateKeyPairSync("ed25519") +const other=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 NOW=Date.parse("2026-11-08T16:30:00Z") +const hash=bytes=>createHash("sha256").update(bytes).digest("hex") +const code="throw new Error('NEVER_EXECUTE_UNTRUSTED_CODE');\nexport async function activate() {}\n" +const source="export async function activate({ request }) { await request('extension.info') }\n" +function manifest(){ + return { + $schema:"../../schema/nextguide-addon-v2.schema.json", + schemaVersion:2,id:"acme.storage",name:"Storage Extension",version:"1.0.0", + summary:"Reviewed v2 sample",description:"Sample server module with no host side effects.", + author:{name:"Acme Inc"},repository:"https://github.com/acme/storage", + license:"MIT",category:"integration",keywords:["storage","extension"], + compatibility:{mode:"account",nextguide:">=1.0.0 <2.0.0"}, + permissions:["storage.read","admin.pages"], + entrypoints:{server:"dist/server.mjs"}, + } +} +function member(path,bytes,type="0"){ + 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(type,156) + h.write("ustar\0",257);h.write("00",263) + const checksum=h.reduce((a,b)=>a+b,0) + h.write(checksum.toString(8).padStart(6,"0")+"\0 ",148,8) + return Buffer.concat([h,bytes,Buffer.alloc((512-bytes.length%512)%512)]) +} +function tar(files) { + return gzipSync(Buffer.concat([...files.map(([name,bytes,type])=>member(name,bytes,type)), + Buffer.alloc(1024)]),{mtime:0}) +} +function archiveFor({m=manifest(),moduleCode=code,sourceCode=source, + extra=[],type="0"}={}) { + const manifestBytes=Buffer.from(JSON.stringify(m)) + const sourceBytes=Buffer.from(sourceCode) + const serverBytes=Buffer.from(moduleCode) + const record=(path,bytes)=>({path,size:bytes.length,sha256:hash(bytes)}) + const index={ + schemaVersion:2,format:"nextguide-single-server-v2", + manifest:record("nextguide-addon.json",manifestBytes), + source:record("src/server.js",sourceBytes), + server:record("dist/server.mjs",serverBytes), + permissions:m.permissions, + } + const files=[ + ["nextguide-addon.json",manifestBytes], + ["src/server.js",sourceBytes], + ["dist/server.mjs",serverBytes,type], + ["nextguide-integrity.json",Buffer.from(JSON.stringify(index))], + ...extra, + ] + const archive=tar(files) + const release={ + manifest:m,assetUrl:"https://github.com/acme/storage/releases/download/v1.0.0/nextguide-addon-v2-1.0.0.tgz", + tag:"v1.0.0",commit:"a".repeat(40),digest:hash(archive), + size:archive.length,status:"active", + review:{ + policy:"independent-human",reviewer:"nextguide-independent-reviewer", + approvedAt:"2026-11-08T16:00:00Z",sourceCommit:"a".repeat(40), + sourcePath:"src/server.js",sourceSha256:hash(sourceBytes), + serverSha256:hash(serverBytes),manifestSha256:hash(manifestBytes), + buildTool:"bun",format:"nextguide-single-server-v2", + }, + } + return {archive,release,index} +} +function envelope(releases,{schemaVersion=2, + updatedAt="2026-11-08T16:00:00Z", + expiresAt="2026-11-08T17:00:00Z",key=keys}={}) { + const body=Buffer.from(JSON.stringify({schemaVersion,updatedAt,expiresAt,releases})) + return {schemaVersion,algorithm:"Ed25519",keyId, + body:body.toString("base64url"), + signature:sign(null,body,key.privateKey).toString("base64url")} +} +const verify=(bytes,release,override={})=> + verifyReviewedV2Archive({envelope:envelope([release]),pinnedPublicKeyPem:pem, + id:"acme.storage",version:"1.0.0",archive:bytes,now:NOW,...override}) + +test("a fresh, separately signed v2 approval matches the exact reviewed source and bundle",()=>{ + const {archive,release}=archiveFor() + const signed=envelope([release]) + const payload=verifySignedV2RegistryEnvelope(signed,pem,{now:NOW}) + const listed=listReviewedV2Releases(payload,{now:NOW}) + assert.equal(listed.length,1) + assert.equal(listed[0].review.policy,"independent-human") + const verified=verify(archive,release) + assert.equal(verified.manifest.id,"acme.storage") + assert.equal(verified.archiveSha256,hash(archive)) + assert.equal(verified.compiled.sha256,release.review.serverSha256) + assert.equal(verified.compiled.code,code) + assert.equal(verified.source.sha256,release.review.sourceSha256) + assert.equal(verified.source.text,source) +}) + +test("v2 catalog expiry, key rotation, tampering, duplicate and v1 replay are rejected",()=>{ + const {release}=archiveFor() + const signed=envelope([release]) + assert.throws(()=>verifySignedV2RegistryEnvelope(signed,pem,{ + now:Date.parse("2026-11-08T18:00:00Z")}),/expired/) + assert.throws(()=>verifySignedV2RegistryEnvelope(signed, + other.publicKey.export({format:"pem",type:"spki"}),{now:NOW}),/Untrusted/) + assert.throws(()=>verifySignedV2RegistryEnvelope({...signed,signature:"a".repeat(86)}, + pem,{now:NOW}),/signature/) + assert.throws(()=>verifySignedV2RegistryEnvelope(envelope([release],{ + schemaVersion:1}),pem,{now:NOW}),/Invalid signed v2 envelope/) + assert.throws(()=>verifySignedV2RegistryEnvelope(envelope([release,release]), + pem,{now:NOW}),/Duplicate/) + assert.throws(()=>verifySignedV2RegistryEnvelope(envelope([release],{ + updatedAt:"2026-11-08T00:00:00Z",expiresAt:"2026-11-08T18:00:00Z" + }),pem,{now:NOW}),/exceeds/) + const changed={...release,review:{...release.review,policy:"self-approved"}} + assert.throws(()=>verifySignedV2RegistryEnvelope(envelope([changed]), + pem,{now:NOW}),/Invalid v2 reviewed release/) + const forged={...release,assetUrl:"https://evil.example/unreviewed.tgz"} + assert.throws(()=>verifySignedV2RegistryEnvelope(envelope([forged]), + pem,{now:NOW}),/Invalid v2 reviewed release/) + const payload=verifySignedV2RegistryEnvelope(signed,pem,{now:NOW}) + payload.releases[0].manifest.permissions.push("network.fetch") + assert.throws(()=>listReviewedV2Releases(payload,{now:NOW}),/not authenticated or was modified/) +}) + +test("permissions show new owner approval required; they never imply an execution grant",()=>{ + assert.deepEqual(compareV2Permissions( + ["storage.read"],["storage.read","network.fetch"],["storage.read"]),{ + added:["network.fetch"],removed:[],ungranted:["network.fetch"], + requiresOwnerApproval:true, + }) + assert.deepEqual(compareV2Permissions( + ["storage.read","network.fetch"],["storage.read"],["storage.read"]),{ + added:[],removed:["network.fetch"],ungranted:[], + requiresOwnerApproval:false, + }) + assert.throws(()=>compareV2Permissions([],["shell.execute"]),/Invalid permission/) + assert.throws(()=>compareV2Permissions([],["storage.read","storage.read"]),/Invalid permission/) +}) + +test("revoked, stale, altered or extra compiled members are never accepted",()=>{ + const good=archiveFor() + const modified=Buffer.from(good.archive) + modified[modified.length-1]^=1 + assert.throws(()=>verify(modified,good.release),/SHA-256 or size/) + assert.throws(()=>verify(good.archive,{...good.release,status:"revoked"}),/revoked/) + assert.throws(()=>verify(good.archive,good.release,{ + now:Date.parse("2026-11-09T00:00:00Z")}),/expired/) + const unreviewed=archiveFor({extra:[["extra.js","console.log(1)"]]}) + assert.throws(()=>verify(unreviewed.archive,unreviewed.release),/unreviewed|duplicate/) + const symlink=archiveFor({type:"2"}) + assert.throws(()=>verify(symlink.archive,symlink.release),/Only regular ustar/) + const fakeReview={...good.release, + review:{...good.release.review,serverSha256:"f".repeat(64)}} + assert.throws(()=>verify(good.archive,fakeReview),/attestations/) + const approvalChanged={...good.release, + manifest:{...good.release.manifest, + permissions:["storage.read","network.fetch"]}} + assert.throws(()=>verify(good.archive,approvalChanged),/descriptor|manifest differs/) +}) + +test("verified v2 catalog client does not redirect or accept unreviewed HTTP",async()=>{ + const {release}=archiveFor() + const signed=envelope([release]) + const requests=[] + const client=createVerifiedV2RegistryClient({ + registryUrl:"https://ngapi.example/v2/registry", + pinnedPublicKeyPem:pem,now:()=>NOW, + fetchImpl:async(url,opts)=>{ + requests.push({url,opts}) + return new Response(JSON.stringify(signed),{ + headers:{"Content-Type":"application/json"} + }) + } + }) + const latest=await client.listReviewed() + assert.equal(latest.length,1) + assert.equal(requests[0].url,"https://ngapi.example/v2/registry") + assert.equal(requests[0].opts.redirect,"error") + assert.equal(requests[0].opts.cache,"no-store") + assert.throws(()=>createVerifiedV2RegistryClient({ + registryUrl:"http://ngapi.example/v2/registry", + pinnedPublicKeyPem:pem}),/HTTPS/) +}) + +function mockedTransport(responses){ + const calls=[] + const transport=(opts,callback)=>{ + const req=new EventEmitter() + req.destroy=()=>{} + req.end=()=>{ + calls.push(opts) + const response=responses.shift() + if(!response)throw Error("unexpected downloader request") + queueMicrotask(()=>{ + const stream=new PassThrough() + stream.statusCode=response.status??200 + stream.headers={ + ...(response.redirect?{location:response.redirect}:{}), + ...(response.bytes?{"content-length":String(response.bytes.length)}:{}) + } + callback(stream) + stream.end(response.bytes??Buffer.alloc(0)) + }) + } + return req + } + return {transport,calls} +} +test("signed v2 intake reuses DNS-pinned TLS and verifies every byte",async()=>{ + const {archive,release}=archiveFor() + const redirect="https://release-assets.githubusercontent.com/github-production-release-asset/abc?token=testing" + const net=mockedTransport([{status:302,redirect},{bytes:archive}]) + const output=await downloadReviewedV2Release({ + envelope:envelope([release]),pinnedPublicKeyPem:pem, + id:"acme.storage",version:"1.0.0", + now:()=>NOW,transport:net.transport, + resolver:async()=>[{family:4,address:"93.184.216.34"}], + }) + assert.equal(output.archive.length,archive.length) + assert.equal(output.verified.compiled.sha256,release.review.serverSha256) + assert.deepEqual(net.calls.map(x=>x.hostname),[ + "github.com","release-assets.githubusercontent.com" + ]) + for(const opts of net.calls){ + assert.equal(opts.rejectUnauthorized,true) + assert.equal(opts.agent,false) + assert.equal(opts.headers["accept-encoding"],"identity") + } +}) +test("revoked or expired v2 records cannot trigger outbound DNS or HTTPS",async()=>{ + const {archive,release}=archiveFor() + let called=0 + for(const [signed,clock] of [ + [envelope([{...release,status:"revoked"}]),()=>NOW], + [envelope([release]),()=>Date.parse("2026-11-08T19:00:00Z")], + ]){ + await assert.rejects(downloadReviewedV2Release({ + envelope:signed,pinnedPublicKeyPem:pem, + id:"acme.storage",version:"1.0.0", + now:clock,resolver:async()=>{called++;throw Error("unexpected DNS")} + }),/not active|No active|expired/) + } + assert.equal(called,0) + assert.ok(archive.length>32) +})