@xlinklight/testkit 0.0.0-stage → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +168 -2
- package/content/platform-baseline.sql +273 -0
- package/package.json +274 -3
- package/src/acceptance-oracle.d.mts +24 -0
- package/src/acceptance-oracle.mjs +79 -0
- package/src/architecture-database.d.mts +36 -0
- package/src/architecture-database.mjs +64 -0
- package/src/artifact-build.d.mts +3 -0
- package/src/artifact-build.mjs +35 -0
- package/src/artifact-declarations.mjs +24 -0
- package/src/artifact-graphs.mjs +61 -0
- package/src/artifact-lock.mjs +32 -0
- package/src/artifact-observation.mjs +50 -0
- package/src/artifact-publisher.d.mts +30 -0
- package/src/artifact-publisher.mjs +84 -0
- package/src/browser-lifecycle.mjs +45 -0
- package/src/browser-operation-owner.mjs +28 -0
- package/src/cloudflare-browser.d.mts +14 -0
- package/src/cloudflare-browser.mjs +41 -0
- package/src/cloudflare-build.d.mts +19 -0
- package/src/cloudflare-build.mjs +61 -0
- package/src/cloudflare-http.d.mts +5 -0
- package/src/cloudflare-http.mjs +65 -0
- package/src/cloudflare-pages.d.mts +34 -0
- package/src/cloudflare-pages.mjs +170 -0
- package/src/cloudflare-provider-http.d.mts +8 -0
- package/src/cloudflare-provider-http.mjs +32 -0
- package/src/cloudflare-worker-package.d.mts +6 -0
- package/src/cloudflare-worker-package.mjs +24 -0
- package/src/cloudflare-worker-qualification.d.mts +4 -0
- package/src/cloudflare-worker-qualification.mjs +63 -0
- package/src/cloudflare-workers.d.mts +37 -0
- package/src/cloudflare-workers.mjs +90 -0
- package/src/cluster-directory.d.mts +16 -0
- package/src/cluster-directory.mjs +90 -0
- package/src/core-publishing.d.mts +75 -0
- package/src/core-publishing.mjs +214 -0
- package/src/dev-command-runner.mjs +97 -0
- package/src/fixture-path.mjs +19 -0
- package/src/function-admission.d.mts +1 -0
- package/src/function-admission.mjs +58 -0
- package/src/host-artifact.mjs +32 -0
- package/src/host-stop.mjs +15 -0
- package/src/independent-artifact-qualification.mjs +67 -0
- package/src/independent-runtime-qualification.mjs +647 -0
- package/src/isolated-browser-child.mjs +29 -0
- package/src/isolated-browser.mjs +69 -0
- package/src/lifecycle-trace.mjs +32 -0
- package/src/managed-native-fixture.d.mts +84 -0
- package/src/managed-native-fixture.mjs +209 -0
- package/src/native-fixture.mjs +125 -0
- package/src/native-platform.mjs +56 -0
- package/src/operator-accounts.mjs +103 -0
- package/src/operator-vault.d.mts +2 -0
- package/src/operator-vault.mjs +9 -0
- package/src/owned-process.mjs +75 -0
- package/src/owner-build-cli.d.mts +1 -0
- package/src/owner-build-cli.mjs +31 -0
- package/src/owner-database.mjs +215 -0
- package/src/owner-operator-build.d.mts +1 -0
- package/src/owner-operator-build.mjs +33 -0
- package/src/owner-package-build.d.mts +2 -0
- package/src/owner-package-build.mjs +29 -0
- package/src/owner-production-browser.mjs +215 -0
- package/src/owner-production-instances.mjs +41 -0
- package/src/owner-production.d.mts +104 -0
- package/src/owner-production.mjs +338 -0
- package/src/owner-release.mjs +41 -0
- package/src/owner-worker-build.d.mts +3 -0
- package/src/owner-worker-build.mjs +83 -0
- package/src/prebuilt-build.d.mts +8 -0
- package/src/prebuilt-build.mjs +69 -0
- package/src/prebuilt-output.d.mts +2 -0
- package/src/prebuilt-output.mjs +104 -0
- package/src/production-hosts.mjs +38 -0
- package/src/publisher-acceptance-host-cli.mjs +23 -0
- package/src/publisher-acceptance-owner.mjs +116 -0
- package/src/publisher-acceptance-runner.mjs +250 -0
- package/src/publisher-acceptance-service.mjs +49 -0
- package/src/publisher-acceptance.d.mts +61 -0
- package/src/publisher-acceptance.mjs +3 -0
- package/src/publishing-source.d.mts +11 -0
- package/src/publishing-source.mjs +32 -0
- package/src/qualification-function-host.mjs +26 -0
- package/src/qualification-route-owner.mjs +64 -0
- package/src/qualification-transport.mjs +18 -0
- package/src/registry-core-selection.mjs +41 -0
- package/src/release-artifact.d.mts +17 -0
- package/src/release-artifact.mjs +113 -0
- package/src/release-build.d.mts +12 -0
- package/src/release-build.mjs +71 -0
- package/src/release-cli.d.mts +27 -0
- package/src/release-cli.mjs +79 -0
- package/src/release-control.mjs +45 -0
- package/src/release-coordinator.d.mts +9 -0
- package/src/release-coordinator.mjs +222 -0
- package/src/release-credentials.d.mts +8 -0
- package/src/release-credentials.mjs +97 -0
- package/src/release-environment.mjs +60 -0
- package/src/release-mutex.d.mts +10 -0
- package/src/release-mutex.mjs +38 -0
- package/src/release-operator.d.mts +6 -0
- package/src/release-operator.mjs +59 -0
- package/src/release-supabase.d.mts +7 -0
- package/src/release-supabase.mjs +37 -0
- package/src/release-vercel.d.mts +22 -0
- package/src/release-vercel.mjs +51 -0
- package/src/release-writer.d.mts +6 -0
- package/src/release-writer.mjs +172 -0
- package/src/retained-postgres-shutdown.d.mts +51 -0
- package/src/retained-postgres-shutdown.mjs +262 -0
- package/src/schema-snapshot.mjs +51 -0
- package/src/static-ui-artifact.mjs +54 -0
- package/src/static-ui-routes.mjs +3 -0
- package/src/temporary-acquisition.mjs +62 -0
- package/src/temporary-scope.d.mts +47 -0
- package/src/temporary-scope.mjs +268 -0
- package/src/unscoped-read.mjs +14 -0
- package/src/worker-artifact.mjs +214 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
|
|
4
|
+
/** Project the selected public archives onto the installation's frozen registry graph. */
|
|
5
|
+
export function projectArtifactLock({lockInput,directory,packages,dependencies,overrides}){
|
|
6
|
+
const lock=lockInput.replaceAll('\r\n','\n'),packagesAt=lock.indexOf('\npackages:\n'),snapshotsAt=lock.indexOf('\nsnapshots:\n');assert.ok(packagesAt>0&&snapshotsAt>packagesAt,'CONSUMER_LOCK_SECTIONS');
|
|
7
|
+
const file=artifact=>'file:'+path.relative(directory,artifact).replaceAll('\\','/');
|
|
8
|
+
const snapshotKeys=new Set([...lock.slice(snapshotsAt).matchAll(/^ {2}(.+?):(?: |$)/gm)].map(([,key])=>key.startsWith('"')?JSON.parse(key):key.startsWith("'")?key.slice(1,-1).replaceAll("''","'"):key));
|
|
9
|
+
const registryVersion=(name,version)=>{
|
|
10
|
+
const key=name+'@'+version;if(snapshotKeys.has(key))return version;
|
|
11
|
+
const candidates=[...snapshotKeys].filter(snapshot=>snapshot.startsWith(key+'('));
|
|
12
|
+
assert(candidates.length<=1,'CONSUMER_LOCK_SNAPSHOT_AMBIGUOUS: '+key);
|
|
13
|
+
return candidates.length?candidates[0].slice(name.length+1):version;
|
|
14
|
+
};
|
|
15
|
+
const selectedNames=new Set(packages.map(item=>item.name));
|
|
16
|
+
const selectedPeer=(metadata,name)=>metadata.peerDependenciesMeta?.[name]?.optional!==true||Object.hasOwn(dependencies,name)||selectedNames.has(name);
|
|
17
|
+
const preserve=section=>section.split(/\n(?= {2}\S)/).filter(block=>{
|
|
18
|
+
const key=block.split('\n',1)[0].trimStart().replace(/^['"]/,'');
|
|
19
|
+
const locator=key.indexOf('@file:');return locator<0||!selectedNames.has(key.slice(0,locator));
|
|
20
|
+
}).join('\n');
|
|
21
|
+
const reactVersion=dependencies.react??packages.find(p=>p.name==='react')?.version;
|
|
22
|
+
const fileVersions=Object.fromEntries(packages.map(p=>[p.name,file(p.artifact)+(p.metadata.peerDependencies?.react&&selectedPeer(p.metadata,'react')?'(react@'+reactVersion+')':'')]));
|
|
23
|
+
const importer=Object.entries(dependencies).map(([name,specifier])=>` ${JSON.stringify(name)}:\n specifier: ${JSON.stringify(specifier)}\n version: ${JSON.stringify(fileVersions[name]??registryVersion(name,specifier))}\n`).join('');
|
|
24
|
+
const artifactPackages=packages.map(p=>` ${JSON.stringify(p.name+'@'+file(p.artifact))}:\n resolution: {integrity: ${JSON.stringify(p.integrity)}, tarball: ${JSON.stringify(file(p.artifact))}}\n version: ${JSON.stringify(p.version)}\n${p.metadata.peerDependencies?' peerDependencies: '+JSON.stringify(p.metadata.peerDependencies)+'\n':''}${p.metadata.peerDependenciesMeta?' peerDependenciesMeta: '+JSON.stringify(p.metadata.peerDependenciesMeta)+'\n':''}`).join('\n');
|
|
25
|
+
const artifactSnapshots=packages.map(p=>{
|
|
26
|
+
// Unselected optional peers remain metadata, not forced installation edges.
|
|
27
|
+
const peers=Object.fromEntries(Object.entries(p.metadata.peerDependencies??{}).filter(([name])=>selectedPeer(p.metadata,name))),values={...p.metadata.dependencies,...peers};
|
|
28
|
+
const deps=Object.entries(values).map(([name,version])=>` ${JSON.stringify(name)}: ${JSON.stringify(fileVersions[name]??registryVersion(name,dependencies[name]??overrides[name]??version))}\n`).join('');return ` ${JSON.stringify(p.name+'@'+fileVersions[p.name])}:${deps?'\n dependencies:\n'+deps:' {}\n'}`;
|
|
29
|
+
}).join('\n');
|
|
30
|
+
const firstSection=Math.min(...['\noverrides:\n','\nimporters:\n','\npackages:\n','\nsnapshots:\n'].map(section=>lock.indexOf(section)).filter(index=>index>=0));assert(Number.isSafeInteger(firstSection)&&firstSection>0,'CONSUMER_LOCK_SECTIONS');
|
|
31
|
+
return lock.slice(0,firstSection)+'\noverrides:\n'+Object.entries(overrides).map(([key,value])=>` ${JSON.stringify(key)}: ${JSON.stringify(value)}\n`).join('')+'\nimporters:\n\n .:\n dependencies:\n'+importer+'\npackages:\n'+preserve(lock.slice(packagesAt+'\npackages:\n'.length,snapshotsAt))+'\n'+artifactPackages+'\nsnapshots:\n'+preserve(lock.slice(snapshotsAt+'\nsnapshots:\n'.length))+'\n'+artifactSnapshots;
|
|
32
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
3
|
+
import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
|
|
4
|
+
import {releaseBytes} from './release-control.mjs';
|
|
5
|
+
import {preparePublishingRelease} from '@xlinklight/publishing/worker';
|
|
6
|
+
import {servedStaticUiRoute} from './static-ui-routes.mjs';
|
|
7
|
+
|
|
8
|
+
const hash=bytes=>'sha256:'+createHash('sha256').update(bytes).digest('hex');
|
|
9
|
+
const fail=()=>Error('ARTIFACT_STATIC_VERIFICATION_FAILED');
|
|
10
|
+
|
|
11
|
+
/** Verify a submitted immutable package against the bytes actually served by
|
|
12
|
+
* the selected providers. No source checkout, Git marker or provider API is
|
|
13
|
+
* trusted as evidence of a successful upload. */
|
|
14
|
+
export async function observePreparedDeployment(options){
|
|
15
|
+
const {configuration,serverUrl,uiUrl,serverReceiptPath,uiReceiptPath,limits,signal}=options;
|
|
16
|
+
const prepared=options.prepared;let declared;
|
|
17
|
+
try{declared=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(prepared.manifestBytes)));}catch{throw fail();}
|
|
18
|
+
if(!isDeepStrictEqual(declared.manifest,prepared.manifest)||!isDeepStrictEqual(declared.content,prepared.content)||hash(declared.bytes)!==hash(prepared.manifestBytes))throw fail();
|
|
19
|
+
const candidate=await preparePublishingRelease({prepared,configuration,serverUrl,uiUrl,serverReceiptPath,uiReceiptPath,limits,signal}),serverOrigin=new URL(serverUrl).origin,uiOrigin=new URL(uiUrl).origin;
|
|
20
|
+
const get=async(url,expected,headers,statuses=[200])=>{
|
|
21
|
+
if(!expected)throw fail();
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
const response=await releaseBytes(url,{}, {...options,maximumBytes:Math.max(1,expected.byteLength)});
|
|
24
|
+
if(!statuses.includes(response.status)||response.bytes.byteLength!==expected.byteLength||hash(response.bytes)!=='sha256:'+expected.sha256)throw fail();
|
|
25
|
+
if(headers)for(const [name,value]of Object.entries(headers))if(response.headers.get(name)!==value)throw fail();
|
|
26
|
+
return response;
|
|
27
|
+
};
|
|
28
|
+
await get(serverOrigin+'/release-server.json',prepared.manifest.files.find(file=>file.path===serverReceiptPath));
|
|
29
|
+
await get(uiOrigin+'/release-ui.json',prepared.manifest.files.find(file=>file.path===uiReceiptPath));
|
|
30
|
+
const files=prepared.manifest.files.filter(file=>file.role==='asset'),cursor=options.cursor??0,maximumFiles=options.maximumFiles??8;
|
|
31
|
+
if(!files.length||!Number.isSafeInteger(cursor)||cursor<0||cursor>=files.length||!Number.isSafeInteger(maximumFiles)||maximumFiles<1||maximumFiles>16)throw fail();
|
|
32
|
+
const nextCursor=Math.min(files.length,cursor+maximumFiles);
|
|
33
|
+
for(const file of files.slice(cursor,nextCursor)){
|
|
34
|
+
if(!file.path.startsWith('ui/'))throw fail();
|
|
35
|
+
// The application requests static segment names with literal dollar signs.
|
|
36
|
+
const route=servedStaticUiRoute(file.path.slice(3)).replaceAll('%24','$');
|
|
37
|
+
const response=await get(uiOrigin+route,file,file.responseHeaders,['/404','/_not-found'].includes(route)?[200,404]:[200]);
|
|
38
|
+
policy(response.headers,configuration.coreOrigin);
|
|
39
|
+
}
|
|
40
|
+
return {status:nextCursor===files.length?'ARTIFACT_DEPLOYMENT_VERIFIED':'ARTIFACT_DEPLOYMENT_PENDING',content:{...prepared.content},releaseDigest:candidate.releaseDigest,serverDigest:candidate.payload.artifacts.server,uiDigest:candidate.payload.ui.integrity,staticFilesVerified:nextCursor,...(nextCursor<files.length?{nextCursor}:{})};
|
|
41
|
+
}
|
|
42
|
+
function policy(headers,coreOrigin){
|
|
43
|
+
const parts=new Map();
|
|
44
|
+
for(const value of (headers.get('content-security-policy')??'').split(';').map(value=>value.trim()).filter(Boolean)){
|
|
45
|
+
const [name,...tokens]=value.split(/\s+/);if(parts.has(name))throw fail();parts.set(name,tokens);
|
|
46
|
+
}
|
|
47
|
+
if(parts.get('frame-ancestors')?.join(' ')!==coreOrigin||!['object-src','base-uri','form-action','frame-src'].every(name=>parts.get(name)?.join(' ')==="'none'"))throw fail();
|
|
48
|
+
const scripts=parts.get('script-src');
|
|
49
|
+
if(!scripts?.length||!scripts.includes("'self'")||scripts.some(value=>value!=="'self'"&&!/^'sha256-[A-Za-z0-9+/]{43}='$/.test(value)))throw fail();
|
|
50
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type {createPublishingActivation,PublishingActivation,preparePublishingRelease} from '@xlinklight/publishing/worker';
|
|
2
|
+
|
|
3
|
+
export interface ArtifactPublisher {
|
|
4
|
+
publisherId:string;enabled:true;keys:{keyId:string;publicKey:string}[];
|
|
5
|
+
}
|
|
6
|
+
export function publicArtifactPublisher(input:unknown):ArtifactPublisher;
|
|
7
|
+
/** Explicit trusted issuer-scoped read port. Returned private JSON is validated
|
|
8
|
+
* against the pinned key and never returned publicly. */
|
|
9
|
+
export interface ArtifactPublisherIdentityStore {
|
|
10
|
+
read(input:{projectRef:string;solutionId:string;publisherId:string;signal?:AbortSignal}):Promise<{description:string;value:unknown}|undefined>;
|
|
11
|
+
}
|
|
12
|
+
export interface ArtifactPublisherContext {
|
|
13
|
+
projectRef:string;solutionId:string;publisher:ArtifactPublisher;signal?:AbortSignal;
|
|
14
|
+
identityStore:ArtifactPublisherIdentityStore;
|
|
15
|
+
}
|
|
16
|
+
export type ArtifactPublisherInspection={status:'SETUP_REQUIRED'}|{status:'PREPARED';keyId:string;publisher:ArtifactPublisher};
|
|
17
|
+
/** Accepts only schema 2 / current ownership. Never provisions or migrates. */
|
|
18
|
+
export function inspectArtifactPublisher(options:ArtifactPublisherContext):Promise<ArtifactPublisherInspection>;
|
|
19
|
+
export type ArtifactPublisherCandidate=Awaited<ReturnType<typeof preparePublishingRelease>>;
|
|
20
|
+
type ActivationInput=Parameters<typeof createPublishingActivation>[0];
|
|
21
|
+
/** Exact candidate routes are validated by the SDK against these explicitly
|
|
22
|
+
* allowed origins. No version path or endpoint is synthesized by the signer. */
|
|
23
|
+
export function signArtifactCandidate(options:ArtifactPublisherContext&{
|
|
24
|
+
candidate:ArtifactPublisherCandidate;serverOrigin:string;uiOrigin:string;version:string;
|
|
25
|
+
}):Promise<Readonly<ActivationInput['manifest']>>;
|
|
26
|
+
/** Trusted owner signs after actual acceptance; public construction verifies
|
|
27
|
+
* the original intent and current Core admission. No private identity escapes. */
|
|
28
|
+
export function signPublishingActivation(options:ArtifactPublisherContext&Pick<ActivationInput,
|
|
29
|
+
'configuration'|'intent'|'manifest'|'acceptanceReceiptSha256'|'metadataTransport'
|
|
30
|
+
>):Promise<PublishingActivation>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {createPrivateKey,createPublicKey,sign} from 'node:crypto';
|
|
2
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
3
|
+
import {validateSolutionReleasePayload,solutionReleaseDigest,verifySolutionRelease} from '@xlinklight/platform/worker';
|
|
4
|
+
import {createPublishingActivation} from '@xlinklight/publishing/worker';
|
|
5
|
+
|
|
6
|
+
const ownership='link-light-artifact-publisher/v2';
|
|
7
|
+
const fail=()=>Error('ARTIFACT_PUBLISHER_IDENTITY_UNKNOWN');
|
|
8
|
+
const scopeFields=new Set(['projectRef','solutionId','publisher','signal','identityStore','candidate','serverOrigin','uiOrigin','version','configuration','intent','manifest','acceptanceReceiptSha256','metadataTransport']);
|
|
9
|
+
const origin=value=>{try{if(typeof value!=='string'||value.length>2048)throw fail();const parsed=new URL(value);if(parsed.protocol!=='https:'||parsed.origin!==value||parsed.username||parsed.password)throw fail();return value;}catch{throw fail();}};
|
|
10
|
+
export function publicArtifactPublisher(publisher){
|
|
11
|
+
if(!publisher||Object.keys(publisher).sort().join(',')!=='enabled,keys,publisherId'||publisher.enabled!==true||typeof publisher.publisherId!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(publisher.publisherId)
|
|
12
|
+
||!Array.isArray(publisher.keys)||!publisher.keys.length||publisher.keys.length>8)throw fail();
|
|
13
|
+
const keys=publisher.keys.map(item=>{
|
|
14
|
+
if(!item||Object.keys(item).sort().join(',')!=='keyId,publicKey'||typeof item.keyId!=='string'||!/^[-A-Za-z0-9_]{1,64}$/.test(item.keyId)||typeof item.publicKey!=='string'||!item.publicKey.startsWith('-----BEGIN PUBLIC KEY-----\n')||item.publicKey.length>8192)throw fail();
|
|
15
|
+
try{const key=createPublicKey(item.publicKey);if(key.asymmetricKeyType!=='ed25519')throw fail();return {keyId:item.keyId,publicKey:key.export({type:'spki',format:'pem'}).toString()};}catch{throw fail();}
|
|
16
|
+
});
|
|
17
|
+
if(new Set(keys.map(item=>item.keyId)).size!==keys.length)throw fail();
|
|
18
|
+
return {publisherId:publisher.publisherId,enabled:true,keys};
|
|
19
|
+
}
|
|
20
|
+
function context(options){
|
|
21
|
+
const publisher=publicArtifactPublisher(options.publisher);
|
|
22
|
+
if(typeof options.projectRef!=='string'||!/^[a-z]{20}$/.test(options.projectRef)||typeof options.solutionId!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(options.solutionId))throw fail();
|
|
23
|
+
const {identityStore}=options;
|
|
24
|
+
if(!identityStore||typeof identityStore.read!=='function'||Object.keys(options).some(key=>!scopeFields.has(key)))throw fail();
|
|
25
|
+
return {projectRef:options.projectRef,solutionId:options.solutionId,publisher,identityStore};
|
|
26
|
+
}
|
|
27
|
+
function credential(value,description,expected){
|
|
28
|
+
if(!value||value.schemaVersion!==2||Object.keys(value).sort().join(',')!=='keyId,privateKey,projectRef,publisherId,schemaVersion,solutionId'||description!==ownership
|
|
29
|
+
||value.projectRef!==expected.projectRef||value.publisherId!==expected.publisher.publisherId||value.solutionId!==expected.solutionId||typeof value.privateKey!=='string'||value.privateKey.length>16384)throw fail();
|
|
30
|
+
try{
|
|
31
|
+
const key=createPrivateKey(value.privateKey),pinned=expected.publisher.keys.find(item=>item.keyId===value.keyId);
|
|
32
|
+
if(key.asymmetricKeyType!=='ed25519'||!pinned||createPublicKey(key).export({type:'spki',format:'pem'}).toString()!==pinned.publicKey)throw fail();
|
|
33
|
+
}catch{throw fail();}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
async function read(options,expected=context(options)){
|
|
37
|
+
try{
|
|
38
|
+
const signal=options.signal;signal?.throwIfAborted();let description,value;
|
|
39
|
+
const observed=await expected.identityStore.read({projectRef:expected.projectRef,solutionId:expected.solutionId,publisherId:expected.publisher.publisherId,signal});signal?.throwIfAborted();
|
|
40
|
+
if(observed===undefined)return {expected};
|
|
41
|
+
if(!observed||Object.keys(observed).sort().join(',')!=='description,value')throw fail();
|
|
42
|
+
description=observed.description;value=structuredClone(observed.value);const encoded=JSON.stringify(value);if(typeof encoded!=='string'||Buffer.byteLength(encoded)>32768)throw fail();
|
|
43
|
+
return {expected,value:credential(value,description,expected)};
|
|
44
|
+
}catch{throw fail();}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Inspect only the current owned identity. Provisioning/metadata migration is
|
|
48
|
+
* an operator task; no normal runtime path creates or replaces a signing key. */
|
|
49
|
+
export async function inspectArtifactPublisher(options){
|
|
50
|
+
const current=await read(options);
|
|
51
|
+
return current.value?{status:'PREPARED',keyId:current.value.keyId,publisher:current.expected.publisher}:{status:'SETUP_REQUIRED'};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function snapshot(value){const copy=structuredClone(value),encoded=JSON.stringify(copy);if(typeof encoded!=='string'||Buffer.byteLength(encoded)>1048576)throw fail();return copy;}
|
|
55
|
+
|
|
56
|
+
export async function signArtifactCandidate(options){
|
|
57
|
+
const expected=context(options);let candidate,publisher;
|
|
58
|
+
try{
|
|
59
|
+
const serverOrigin=origin(options.serverOrigin),uiOrigin=origin(options.uiOrigin),version=options.version;candidate=snapshot(options.candidate);
|
|
60
|
+
publisher={...expected.publisher,serverOrigins:[serverOrigin],uiOrigins:[uiOrigin]};
|
|
61
|
+
if(typeof version!=='string'||!/^(0|[1-9][0-9]{0,7})\.(0|[1-9][0-9]{0,7})\.(0|[1-9][0-9]{0,7})$/.test(version)
|
|
62
|
+
||!candidate||Object.keys(candidate).sort().join(',')!=='payload,publisher,releaseDigest'||candidate.payload?.solutionId!==expected.solutionId||candidate.payload.publisherId!==publisher.publisherId||candidate.payload.version!==version
|
|
63
|
+
||!isDeepStrictEqual(candidate.publisher,publisher)||!/^sha256:[a-f0-9]{64}$/.test(candidate.releaseDigest??''))throw fail();
|
|
64
|
+
const payload=validateSolutionReleasePayload(candidate.payload,publisher);if(solutionReleaseDigest(payload)!==candidate.releaseDigest)throw fail();
|
|
65
|
+
}catch{throw Error('ARTIFACT_PUBLISHER_CANDIDATE_INVALID');}
|
|
66
|
+
const current=await read(options,expected);if(!current.value)throw fail();
|
|
67
|
+
try{
|
|
68
|
+
options.signal?.throwIfAborted();
|
|
69
|
+
const manifest={...candidate.payload,releaseDigest:candidate.releaseDigest,signature:{keyId:current.value.keyId,algorithm:'Ed25519',value:sign(null,Buffer.from('link-light.release.v1\n'+candidate.releaseDigest),createPrivateKey(current.value.privateKey)).toString('base64url')}};
|
|
70
|
+
return verifySolutionRelease(manifest,publisher);
|
|
71
|
+
}catch{throw Error('ARTIFACT_PUBLISHER_CANDIDATE_INVALID');}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Privileged signer after owned acceptance. Public construction binds the
|
|
75
|
+
* original request/receipt and requires current signed Core admission. */
|
|
76
|
+
export async function signPublishingActivation(options){
|
|
77
|
+
try{
|
|
78
|
+
const expected=context(options),{parsePublishingConfiguration,parsePublishingIntent}=await import('@xlinklight/publishing');
|
|
79
|
+
const configuration=parsePublishingConfiguration(options.configuration),intent=parsePublishingIntent(options.intent),manifest=snapshot(options.manifest),acceptanceReceiptSha256=options.acceptanceReceiptSha256;
|
|
80
|
+
if(!isDeepStrictEqual(publicArtifactPublisher({...configuration.publisher,enabled:true}),expected.publisher)||intent.projectId!==configuration.projectId||intent.package.publisherId!==expected.publisher.publisherId||intent.package.solutionId!==expected.solutionId||!/^[a-f0-9]{64}$/.test(acceptanceReceiptSha256??''))throw fail();
|
|
81
|
+
const current=await read(options,expected);if(!current.value)throw fail();
|
|
82
|
+
return await createPublishingActivation({configuration,intent,manifest,acceptanceReceiptSha256,keyId:current.value.keyId,privateKey:current.value.privateKey,...(options.metadataTransport?{metadataTransport:options.metadataTransport}:{}),signal:options.signal});
|
|
83
|
+
}catch{throw Error('ARTIFACT_PUBLISHER_ACTIVATION_INVALID');}
|
|
84
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import {pathToFileURL} from 'node:url';
|
|
6
|
+
|
|
7
|
+
export function isDirectEntry(url){return Boolean(process.argv[1])&&pathToFileURL(path.resolve(process.argv[1])).href===url;}
|
|
8
|
+
export async function selectReadySolution(page,entryId,{deadline,onStage}={}){
|
|
9
|
+
const options=()=>{if(deadline===undefined)return undefined;const timeout=deadline-Date.now();assert(Number.isFinite(timeout)&&timeout>0,'Solution readiness timeout');return {timeout};};
|
|
10
|
+
onStage?.('hydration');
|
|
11
|
+
await page.locator('main[data-client-ready="true"]').waitFor(options());
|
|
12
|
+
onStage?.('selection');
|
|
13
|
+
await page.locator('#solution').selectOption(entryId,options());
|
|
14
|
+
}
|
|
15
|
+
export async function assertCatalogUiSlots(page,catalog){assert.deepEqual(await page.locator('#solution option').evaluateAll(options=>options.map(option=>option.value)),catalog.solutions.flatMap(solution=>solution.descriptor.uiEntryRefs.map(entry=>entry.entryId)));}
|
|
16
|
+
const listening=port=>new Promise(resolve=>{const socket=net.connect(port,'127.0.0.1');socket.setTimeout(2000,()=>{socket.destroy();resolve(true);});socket.once('connect',()=>{socket.destroy();resolve(true);});socket.once('error',()=>{socket.destroy();resolve(false);});});
|
|
17
|
+
|
|
18
|
+
// A case borrows the PG pools and Chrome. It owns only its contexts and hosts.
|
|
19
|
+
export async function runBrowserCases({database,browser,cases,evidence,artifactRecord,onCase=()=>{}}){
|
|
20
|
+
const results=cases.map(({name})=>({name,status:'NOT_RUN'}));
|
|
21
|
+
for(const [index,{name,run}]of cases.entries()){
|
|
22
|
+
if(!/^[a-z][a-z0-9-]{0,47}$/.test(name))throw Error('Invalid browser case name');
|
|
23
|
+
const row=results[index],directory=path.join(evidence,name);fs.mkdirSync(directory,{recursive:false});
|
|
24
|
+
const contexts=[],handles=[],ports=new Set(),closeErrors=[];let browserClose,databaseClose;
|
|
25
|
+
const remember=error=>{closeErrors.push(database.redact(error.stack??String(error)));return error;};
|
|
26
|
+
let firstClose;
|
|
27
|
+
const capture=async operation=>{try{await operation();}catch(error){remember(error);firstClose??=error;}};
|
|
28
|
+
const borrowed={version:()=>browser.version(),async newContext(options){const context=await browser.newContext(options);contexts.push(context);return context;},close(){return browserClose??=(async()=>{for(const context of contexts.toReversed())await capture(()=>context.close());})();}};
|
|
29
|
+
const view={...database,evidence:directory,artifactRecord,sharedBatch:true,start(...args){const handle=database.start(...args);handles.push(handle);return handle;},registerPort(port){ports.add(port);database.registerPort(port);},close(){return databaseClose??=(async()=>{
|
|
30
|
+
for(const handle of handles.toReversed())await capture(async()=>{await(handle.closeForFixture?.()??handle.stop());if(handle.state.stopError||!handle.state.closed)throw Error(handle.state.stopError??'Case host remains open');});
|
|
31
|
+
for(const port of ports)await capture(async()=>{if(await listening(port))throw Error('Case listener remains open: '+port);});
|
|
32
|
+
})();},dispose(){return this.close();}};
|
|
33
|
+
row.status='RUNNING';row.startedAt=new Date().toISOString();row.evidence=directory;onCase(row);
|
|
34
|
+
let first;
|
|
35
|
+
try{await run(view,async()=>borrowed);}catch(error){first=error;}
|
|
36
|
+
finally{await borrowed.close();await view.close();}
|
|
37
|
+
first??=firstClose;
|
|
38
|
+
if(!first)try{await database.assertUnscoped();row.unscopedReadRows=0;}catch(error){first=error;}
|
|
39
|
+
row.endedAt=new Date().toISOString();row.status=first?'FAIL':'PASS';row.closeErrors=closeErrors;row.processes=handles.map(handle=>({...handle.state}));
|
|
40
|
+
if(first)row.error=database.redact(first.stack??String(first));
|
|
41
|
+
try{onCase(row);fs.writeFileSync(path.join(directory,'case-closeout.json'),JSON.stringify(row)+'\n');}catch(error){first??=error;row.status='FAIL';row.error=database.redact(first.stack??String(first));row.evidenceError=database.redact(error.stack??String(error));}
|
|
42
|
+
if(first){first.caseResults=results;throw first;}
|
|
43
|
+
}
|
|
44
|
+
return results;
|
|
45
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
|
|
3
|
+
/** Keep the original browser exercise owned after its failure channel wins. */
|
|
4
|
+
export function createBrowserOperationOwner(){
|
|
5
|
+
let failed=false,firstError,cancel=async()=>{},cancelling,rejectFailure;
|
|
6
|
+
const failure=new Promise((_,reject)=>{rejectFailure=reject;});void failure.catch(()=>{});
|
|
7
|
+
const guard=()=>{if(failed)throw firstError;};
|
|
8
|
+
const cancelOwned=()=>cancelling??=Promise.resolve().then(cancel);
|
|
9
|
+
return {failure,guard,get failed(){return failed;},get firstError(){return firstError;},
|
|
10
|
+
setCancel(value){assert(typeof value==='function','BROWSER_OPERATION_CANCEL');cancel=value;},
|
|
11
|
+
async openContext(open){guard();const context=await open();try{guard();return context;}catch(error){try{await context.close();}catch(cleanup){throw new AggregateError([error,cleanup],'BROWSER_LATE_CONTEXT_CLOSE_FAILED',{cause:error});}throw error;}},
|
|
12
|
+
fail(error){if(failed)return;failed=true;firstError=error;rejectFailure(error);void cancelOwned().catch(()=>{});},
|
|
13
|
+
async run(work){
|
|
14
|
+
guard();const original=Promise.resolve().then(work);void original.catch(()=>{});
|
|
15
|
+
try{const value=await Promise.race([original,failure]);guard();return value;}
|
|
16
|
+
catch(error){
|
|
17
|
+
if(!failed)throw error;
|
|
18
|
+
// The race may already have rejected with work's error before a route
|
|
19
|
+
// failure sets the shared flag. Its caught reason remains authoritative.
|
|
20
|
+
const routeError=firstError,errors=[error];firstError=error;
|
|
21
|
+
if(!Object.is(routeError,error))errors.push(routeError);
|
|
22
|
+
try{await cancelOwned();}catch(cleanup){errors.push(cleanup);}
|
|
23
|
+
await original.catch(()=>{});
|
|
24
|
+
if(errors.length>1)throw new AggregateError(errors,'BROWSER_OPERATION_FAILED',{cause:error});throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface BrowserRunSessionReceipt {status:'closed';sessionId:string;closeReason:'NormalClosure';startTime:number;endTime:number}
|
|
2
|
+
export interface BrowserRunBrowser {sessionId():string;newContext(options?:unknown):Promise<unknown>;close():Promise<void>}
|
|
3
|
+
export interface BrowserRunPlaywright {
|
|
4
|
+
launch(binding:unknown,options:{keep_alive:number;guardrails:{allowedDomains:string[]}}):Promise<BrowserRunBrowser>;
|
|
5
|
+
limits(binding:unknown):Promise<{activeSessions:readonly unknown[];maxConcurrentSessions:number;allowedBrowserAcquisitions:number;timeUntilNextAllowedBrowserAcquisition:number}>;
|
|
6
|
+
sessions(binding:unknown):Promise<readonly {sessionId:string}[]>;
|
|
7
|
+
history(binding:unknown):Promise<readonly {sessionId:string;startTime:number;endTime?:number;closeReason?:number;closeReasonText?:string}[]>;
|
|
8
|
+
}
|
|
9
|
+
export function createCloudflareBrowserHost(options:{
|
|
10
|
+
binding:{fetch:typeof fetch};playwright:BrowserRunPlaywright;
|
|
11
|
+
admit(options:{signal?:AbortSignal}):Promise<void>;
|
|
12
|
+
recordSession(record:{phase:'acquired';sessionId:string;allowedOrigins:string[]}|({phase:'closed'}&BrowserRunSessionReceipt)):Promise<void>;
|
|
13
|
+
maximumCloseObservations?:number;
|
|
14
|
+
}):{open(options:{allowedOrigins:readonly string[];signal?:AbortSignal}):Promise<{browser:BrowserRunBrowser;close():Promise<BrowserRunSessionReceipt>}>};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const fail=(code,cause)=>Error('BROWSER_RUN_'+code,cause===undefined?undefined:{cause});
|
|
2
|
+
const validId=value=>typeof value==='string'&&/^[A-Za-z0-9_-]{1,128}$/.test(value);
|
|
3
|
+
const pause=milliseconds=>new Promise(resolve=>setTimeout(resolve,milliseconds));
|
|
4
|
+
|
|
5
|
+
/** The private service supplies the installed official Playwright module and
|
|
6
|
+
* a Browser Run binding. This owns acquisition and exact session closure only;
|
|
7
|
+
* domain/UI assertions remain in the shared production acceptance driver. */
|
|
8
|
+
export function createCloudflareBrowserHost({binding,playwright,admit,recordSession,maximumCloseObservations=3}){
|
|
9
|
+
if(!binding||typeof binding.fetch!=='function'||!playwright||!['launch','limits','sessions','history'].every(name=>typeof playwright[name]==='function')||typeof admit!=='function'||typeof recordSession!=='function'||!Number.isSafeInteger(maximumCloseObservations)||maximumCloseObservations<1||maximumCloseObservations>5)throw fail('CONFIGURATION_INVALID');
|
|
10
|
+
return Object.freeze({async open({allowedOrigins,signal}){
|
|
11
|
+
if(!Array.isArray(allowedOrigins)||!allowedOrigins.length||allowedOrigins.length>8||new Set(allowedOrigins).size!==allowedOrigins.length||allowedOrigins.some(origin=>{try{const url=new URL(origin);return url.protocol!=='https:'||url.origin!==origin||url.username||url.password;}catch{return true;}}))throw fail('ORIGIN_INVALID');
|
|
12
|
+
signal?.throwIfAborted();await admit({signal});signal?.throwIfAborted();
|
|
13
|
+
const available=await playwright.limits(binding);
|
|
14
|
+
if(!Number.isSafeInteger(available?.allowedBrowserAcquisitions)||available.allowedBrowserAcquisitions<1||!Number.isSafeInteger(available.maxConcurrentSessions)||!Array.isArray(available.activeSessions)||available.activeSessions.length>=available.maxConcurrentSessions||available.timeUntilNextAllowedBrowserAcquisition!==0)throw fail('CAPACITY_UNAVAILABLE');
|
|
15
|
+
signal?.throwIfAborted();
|
|
16
|
+
// launch (rather than connect) owns the session: official browser.close()
|
|
17
|
+
// terminates it instead of merely disconnecting a reused session.
|
|
18
|
+
// A free-tier scheduler turn can arrive more than one minute after a UI submit.
|
|
19
|
+
const browser=await playwright.launch(binding,{keep_alive:120000,guardrails:{allowedDomains:[...new Set(allowedOrigins.map(origin=>new URL(origin).hostname))]}});
|
|
20
|
+
const sessionId=browser?.sessionId?.();let closing;
|
|
21
|
+
const close=()=>closing??=(async()=>{
|
|
22
|
+
let cause;try{await browser.close();}catch(error){cause=error;}
|
|
23
|
+
if(!validId(sessionId))throw fail('CLOSE_UNKNOWN',cause);
|
|
24
|
+
for(let attempt=0;attempt<maximumCloseObservations;attempt++){
|
|
25
|
+
if(attempt)await pause(250);
|
|
26
|
+
let active,history;try{active=await playwright.sessions(binding);history=await playwright.history(binding);}catch(error){cause??=error;continue;}
|
|
27
|
+
const exact=Array.isArray(history)?history.filter(item=>item.sessionId===sessionId):[];
|
|
28
|
+
if(Array.isArray(active)&&!active.some(item=>item.sessionId===sessionId)&&exact.length===1&&exact[0].closeReason===1&&exact[0].closeReasonText==='NormalClosure'&&Number.isFinite(exact[0].startTime)&&Number.isFinite(exact[0].endTime)&&exact[0].endTime>=exact[0].startTime){
|
|
29
|
+
const receipt={status:'closed',sessionId,closeReason:'NormalClosure',startTime:exact[0].startTime,endTime:exact[0].endTime};
|
|
30
|
+
await recordSession({phase:'closed',...receipt});return Object.freeze(receipt);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw fail('CLOSE_UNKNOWN',cause);
|
|
34
|
+
})();
|
|
35
|
+
try{
|
|
36
|
+
if(!validId(sessionId)||typeof browser.newContext!=='function')throw fail('SESSION_IDENTITY_UNKNOWN');
|
|
37
|
+
await recordSession({phase:'acquired',sessionId,allowedOrigins:[...allowedOrigins]});signal?.throwIfAborted();
|
|
38
|
+
return Object.freeze({browser,close});
|
|
39
|
+
}catch(error){try{await close();}catch(cleanup){throw new AggregateError([error,cleanup],'BROWSER_RUN_ACQUIRE_CLOSE_UNKNOWN');}throw error;}
|
|
40
|
+
}});
|
|
41
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface CloudflareBuildProcessReceipt {closed:boolean;exitCode:number|null;stdoutEof:boolean;stderrEof:boolean;stopError?:unknown}
|
|
2
|
+
export interface CloudflareBuildOptions {
|
|
3
|
+
/** Existing caller-owned private scope; the helper never replaces its output. */
|
|
4
|
+
root:string;entry:string;
|
|
5
|
+
/** One non-hidden direct child name beneath root, distinct from control. */
|
|
6
|
+
output:string;wranglerEntry:string;
|
|
7
|
+
compatibilityDate:string;compatibilityFlags:readonly string[];
|
|
8
|
+
rules?:readonly {type:'Text'|'Data'|'CompiledWasm';globs:readonly string[];fallthrough?:boolean}[];
|
|
9
|
+
signal?:AbortSignal;timeoutMs?:number;maxOutputBytes?:number;maximumFiles?:number;maximumFileBytes?:number;maximumTotalBytes?:number;
|
|
10
|
+
}
|
|
11
|
+
export interface CloudflareBuildResult {
|
|
12
|
+
entry:string;files:readonly {path:string;bytes:Uint8Array}[];
|
|
13
|
+
metadata:{inputs:Record<string,unknown>;outputs:Record<string,{entryPoint?:string;imports?:readonly {path:string;external?:boolean;kind:string}[];exports?:readonly string[];bytes?:number}>};
|
|
14
|
+
process:CloudflareBuildProcessReceipt;stdout:Uint8Array;stderr:Uint8Array;
|
|
15
|
+
}
|
|
16
|
+
/** Pinned Wrangler4.158 official dry-run only. No provider upload or install.
|
|
17
|
+
* Failures retain the original bounded private cause and any actual process
|
|
18
|
+
* receipt; missing/unknown closure must stay unknown to the embedding scope. */
|
|
19
|
+
export function bundleCloudflareWorker(options:CloudflareBuildOptions):Promise<CloudflareBuildResult>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createRequire} from 'node:module';
|
|
4
|
+
import {pathToFileURL} from 'node:url';
|
|
5
|
+
import {captureCli} from './release-cli.mjs';
|
|
6
|
+
|
|
7
|
+
const invalid=()=>Error('CLOUDFLARE_BUILD_INPUT_INVALID');
|
|
8
|
+
const integer=(value,maximum)=>Number.isSafeInteger(value)&&value>0&&value<=maximum;
|
|
9
|
+
function portable(value){return typeof value==='string'&&value.length<2048&&!/[\\:\0-\x1f\x7f]/.test(value)&&value.split('/').every(part=>part&&part!=='.'&&part!=='..'&&!part.startsWith('.'));}
|
|
10
|
+
async function regular(file,maximum){const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>maximum||await fs.realpath(file)!==file)throw invalid();return fs.readFile(file);}
|
|
11
|
+
/** One official, offline Wrangler dry-run. All tool-owned configuration, logs
|
|
12
|
+
* and caches stay beneath the caller's existing private scope. No install,
|
|
13
|
+
* provider request, ambient credential or third-party replacement is used. */
|
|
14
|
+
export async function bundleCloudflareWorker(input){
|
|
15
|
+
const allowed=['root','entry','output','wranglerEntry','compatibilityDate','compatibilityFlags','rules','signal','timeoutMs','maxOutputBytes','maximumFiles','maximumFileBytes','maximumTotalBytes'];
|
|
16
|
+
if(!input||typeof input!=='object'||Object.keys(input).some(key=>!allowed.includes(key)))throw invalid();
|
|
17
|
+
const {root,entry,output,wranglerEntry,compatibilityDate,compatibilityFlags,rules=[],signal,timeoutMs=60000,maxOutputBytes=65536,maximumFiles=256,maximumFileBytes=16777216,maximumTotalBytes=33554432}=input;
|
|
18
|
+
if(typeof output!=='string'||output.includes('/')||output==='cloudflare-build-control')throw invalid();
|
|
19
|
+
if(![root,entry,wranglerEntry].every(value=>typeof value==='string'&&path.isAbsolute(value))||!portable(output)||!/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate??'')||!Array.isArray(compatibilityFlags)||!compatibilityFlags.includes('nodejs_compat')||compatibilityFlags.length>16||new Set(compatibilityFlags).size!==compatibilityFlags.length||compatibilityFlags.some(value=>typeof value!=='string'||!/^[_a-z][_a-z0-9]{0,127}$/.test(value))||!integer(timeoutMs,300000)||!integer(maxOutputBytes,1048576)||!integer(maximumFiles,8192)||!integer(maximumFileBytes,67108864)||!integer(maximumTotalBytes,67108864)||maximumFileBytes>maximumTotalBytes||!Array.isArray(rules)||rules.length>32||rules.some(rule=>!rule||Object.keys(rule).some(key=>!['type','globs','fallthrough'].includes(key))||!['Text','Data','CompiledWasm'].includes(rule.type)||!Array.isArray(rule.globs)||!rule.globs.length||rule.globs.length>32||rule.globs.some(value=>typeof value!=='string'||!value||value.length>1024||/[\\:\0-\x1f\x7f]/.test(value))||rule.fallthrough!==undefined&&typeof rule.fallthrough!=='boolean'))throw invalid();
|
|
20
|
+
signal?.throwIfAborted();let processReceipt;
|
|
21
|
+
try{
|
|
22
|
+
if(await fs.realpath(root)!==root||!(await fs.lstat(root)).isDirectory())throw invalid();
|
|
23
|
+
await regular(entry,maximumFileBytes);await regular(wranglerEntry,1048576);
|
|
24
|
+
const require=createRequire(pathToFileURL(wranglerEntry)),metadataPath=await fs.realpath(require.resolve('wrangler/package.json')),metadata=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await regular(metadataPath,65536)));
|
|
25
|
+
if(metadata.name!=='wrangler'||metadata.version!=='4.158.0'||typeof metadata.bin?.wrangler!=='string'||await fs.realpath(path.resolve(path.dirname(metadataPath),metadata.bin.wrangler))!==wranglerEntry)throw Error('CLOUDFLARE_BUILD_TOOL_INVALID');
|
|
26
|
+
const control=path.join(root,'cloudflare-build-control'),outdir=path.join(root,output);
|
|
27
|
+
// Both names are fixed-purpose scope children. Existing output is never
|
|
28
|
+
// replaced here; scope ownership/recovery belongs to the original caller.
|
|
29
|
+
await fs.mkdir(control);await fs.mkdir(outdir,{recursive:true});
|
|
30
|
+
if(await fs.realpath(outdir)!==outdir||(await fs.readdir(outdir)).length)throw Error('CLOUDFLARE_BUILD_OUTPUT_EXISTS');
|
|
31
|
+
const directories=Object.fromEntries(['home','config','cache','registry','temporary','appdata','localappdata'].map(name=>[name,path.join(control,name)]));
|
|
32
|
+
for(const value of Object.values(directories))await fs.mkdir(value);
|
|
33
|
+
const config=path.join(control,'wrangler.json'),metafile=path.join(control,'bundle-meta.json'),tsconfig=path.join(control,'tsconfig.json');
|
|
34
|
+
const gitConfig=path.join(control,'git-config');await fs.writeFile(gitConfig,'',{flag:'wx'});
|
|
35
|
+
// Host TypeScript paths serve its local compiler and must not override the
|
|
36
|
+
// package's workerd imports with a Node-only source entry during bundling.
|
|
37
|
+
await fs.writeFile(tsconfig,JSON.stringify({compilerOptions:{}})+'\n',{flag:'wx'});
|
|
38
|
+
await fs.writeFile(config,JSON.stringify({name:'link-light-owned-bundle',main:entry,tsconfig:'tsconfig.json',compatibility_date:compatibilityDate,compatibility_flags:compatibilityFlags,workers_dev:false,preview_urls:false,send_metrics:false,upload_source_maps:false,preserve_file_names:true,rules})+'\n',{flag:'wx'});
|
|
39
|
+
const environment=Object.fromEntries(Object.entries(process.env).filter(([key])=>['SYSTEMROOT','WINDIR','COMSPEC','PATHEXT','PATH'].includes(key.toUpperCase())));
|
|
40
|
+
Object.assign(environment,{HOME:directories.home,USERPROFILE:directories.home,APPDATA:directories.appdata,LOCALAPPDATA:directories.localappdata,XDG_CONFIG_HOME:directories.config,XDG_CACHE_HOME:directories.cache,TEMP:directories.temporary,TMP:directories.temporary,TMPDIR:directories.temporary,CI:'true',NO_COLOR:'1',WRANGLER_SEND_METRICS:'false',WRANGLER_SEND_ERROR_REPORTS:'false',WRANGLER_NO_SKILLS_UPDATE_PROMPTS:'true',WRANGLER_LOG_PATH:path.join(control,'wrangler.log'),WRANGLER_REGISTRY_PATH:directories.registry,WRANGLER_CACHE_DIR:directories.cache,CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV:'false',CLOUDFLARE_INCLUDE_PROCESS_ENV:'false',WRANGLER_BUILD_CONDITIONS:'workerd,worker,browser'});
|
|
41
|
+
Object.assign(environment,{GIT_CEILING_DIRECTORIES:root,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:gitConfig});
|
|
42
|
+
const captured=await captureCli(process.execPath,[wranglerEntry,'deploy','--dry-run','--config',config,'--outdir',outdir,'--metafile',metafile,'--experimental-provision=false','--experimental-auto-create=false','--install-skills=false'],{cwd:control,env:environment,signal,timeoutMs,maxOutputBytes});processReceipt=captured.process;
|
|
43
|
+
const metadataBytes=await regular(metafile,8388608),graph=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(metadataBytes));
|
|
44
|
+
if(!graph||typeof graph.inputs!=='object'||typeof graph.outputs!=='object')throw Error('CLOUDFLARE_BUILD_GRAPH_INVALID');
|
|
45
|
+
const entries=Object.entries(graph.outputs).filter(([name,value])=>value?.entryPoint&&!name.endsWith('.map'));
|
|
46
|
+
if(entries.length!==1)throw Error('CLOUDFLARE_BUILD_GRAPH_INVALID');
|
|
47
|
+
// Wrangler writes the resolved bundle's basename into --outdir. Its public
|
|
48
|
+
// esbuild metafile still names the internal staging path, not that copy.
|
|
49
|
+
const main=path.basename(entries[0][0]);if(!portable(main))throw Error('CLOUDFLARE_BUILD_GRAPH_INVALID');
|
|
50
|
+
const files=[];let total=0;
|
|
51
|
+
async function collect(directory,prefix=''){
|
|
52
|
+
for(const item of (await fs.readdir(directory,{withFileTypes:true})).sort((a,b)=>a.name<b.name?-1:1)){
|
|
53
|
+
const relative=prefix+item.name,selected=path.join(directory,item.name);if(!portable(relative))throw invalid();
|
|
54
|
+
if(item.isDirectory()){if(await fs.realpath(selected)!==selected)throw invalid();await collect(selected,relative+'/');}
|
|
55
|
+
else{if(files.length>=maximumFiles)throw Error('CLOUDFLARE_BUILD_LIMIT');const bytes=await regular(selected,maximumFileBytes);if((total+=bytes.byteLength)>maximumTotalBytes)throw Error('CLOUDFLARE_BUILD_LIMIT');files.push(Object.freeze({path:relative,bytes:new Uint8Array(bytes)}));}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
await collect(outdir);if(!files.some(file=>file.path===main))throw Error('CLOUDFLARE_BUILD_GRAPH_INVALID');
|
|
59
|
+
return Object.freeze({entry:main,files:Object.freeze(files),metadata:graph,process:captured.process,stdout:captured.stdout,stderr:captured.stderr});
|
|
60
|
+
}catch(cause){const receipt=processReceipt??cause?.cause?.process;if(/^CLOUDFLARE_BUILD_[A-Z_]+$/.test(cause?.message??'')){if(receipt)cause.process=receipt;throw cause;}const error=Error('CLOUDFLARE_BUILD_FAILED',{cause});if(receipt)error.process=receipt;throw error;}
|
|
61
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Host-trusted fixed targets. This port does not implement DNS/IP pinning. */
|
|
2
|
+
export function createWorkersHttpTransport(options:{
|
|
3
|
+
allowRequest(url:URL,method:string):boolean;request?:typeof fetch;signal?:AbortSignal;
|
|
4
|
+
maximumResponseBytes?:number;timeoutMs?:number;maximumRequests?:number;
|
|
5
|
+
}):{fetch:typeof fetch;close():Promise<{status:'closed';activeRequests:0}>};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const fail=(code,cause)=>Error('WORKERS_HTTP_'+code,cause===undefined?undefined:{cause});
|
|
2
|
+
|
|
3
|
+
/** Explicit host-trusted Workers fetch. This does not claim Node's all-answer
|
|
4
|
+
* DNS/IP pinning. The owner must admit each exact origin/method/path. */
|
|
5
|
+
export function createWorkersHttpTransport({allowRequest,request=fetch,signal,maximumResponseBytes=32*1024**2,timeoutMs=60000,maximumRequests=49}={}){
|
|
6
|
+
if(typeof allowRequest!=='function'||typeof request!=='function'||!Number.isSafeInteger(maximumResponseBytes)||maximumResponseBytes<1||maximumResponseBytes>32*1024**2||!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>60000||!Number.isSafeInteger(maximumRequests)||maximumRequests<1||maximumRequests>49)throw fail('CONFIGURATION_INVALID');
|
|
7
|
+
const controller=new AbortController(),pending=new Set(),bodies=new Set(),closureErrors=[];let closed=false,closing,requests=0;
|
|
8
|
+
const transport={fetch(input,init={}){
|
|
9
|
+
let url,method;
|
|
10
|
+
try{
|
|
11
|
+
const address=typeof input==='string'?input:input instanceof URL?input.href:input.url;url=new URL(address);method=(init.method??(input instanceof Request?input.method:'GET')).toUpperCase();
|
|
12
|
+
if(closed||url.protocol!=='https:'||url.href!==address||url.username||url.password||url.hash||allowRequest(url,method)!==true)throw fail('TARGET_REJECTED');
|
|
13
|
+
}catch(error){return Promise.reject(error.message?.startsWith('WORKERS_HTTP_')?error:fail('TARGET_REJECTED'));}
|
|
14
|
+
if(requests>=maximumRequests)return Promise.reject(fail('REQUEST_LIMIT'));requests++;
|
|
15
|
+
const deadline=new AbortController(),combined=AbortSignal.any([controller.signal,deadline.signal,signal,init.signal,input instanceof Request?input.signal:undefined].filter(Boolean));
|
|
16
|
+
const timer=setTimeout(()=>deadline.abort(fail('DEADLINE')),timeoutMs);
|
|
17
|
+
const task=(async()=>{
|
|
18
|
+
let response;
|
|
19
|
+
try{
|
|
20
|
+
combined.throwIfAborted();
|
|
21
|
+
const original=input instanceof Request?{method:input.method,headers:input.headers,body:['GET','HEAD'].includes(method)?undefined:input.body}:{};
|
|
22
|
+
response=await request(url.href,{...original,...init,method,redirect:'manual',credentials:'omit',signal:combined});
|
|
23
|
+
if(closed||combined.aborted){await response.body?.cancel();combined.throwIfAborted();throw fail('CLOSED');}
|
|
24
|
+
if(response.status>=300&&response.status<400){await response.body?.cancel();throw fail('REDIRECT_REJECTED');}
|
|
25
|
+
// Fetch may expose decoded bytes while retaining the wire Content-Length.
|
|
26
|
+
const encoding=response.headers.get('content-encoding'),length=!encoding||encoding==='identity'?response.headers.get('content-length'):null;
|
|
27
|
+
if(length!==null&&(!/^\d+$/.test(length)||Number(length)>maximumResponseBytes)){await response.body?.cancel();throw fail('RESPONSE_LIMIT');}
|
|
28
|
+
if(!response.body){clearTimeout(timer);return response;}
|
|
29
|
+
const reader=response.body.getReader();let total=0,streamController,finishing,done=false;
|
|
30
|
+
const finish=(error,cancel=false)=>{
|
|
31
|
+
if(finishing)return finishing;done=true;clearTimeout(timer);combined.removeEventListener('abort',abort);
|
|
32
|
+
if(error)try{streamController?.error(error);}catch{/* Already cancelled by the consumer. */}
|
|
33
|
+
finishing=(async()=>{try{if(cancel)await reader.cancel(error);}catch(failure){closureErrors.push(failure);throw failure;}finally{reader.releaseLock();bodies.delete(body);}})();return finishing;
|
|
34
|
+
};
|
|
35
|
+
const abort=()=>{void finish(combined.reason??fail('CLOSED'),true).catch(()=>{});};
|
|
36
|
+
const body={cancel:()=>finish(fail('CLOSED'),true)};bodies.add(body);
|
|
37
|
+
const stream=new ReadableStream({
|
|
38
|
+
start(value){streamController=value;},
|
|
39
|
+
async pull(value){
|
|
40
|
+
if(done)return;
|
|
41
|
+
try{const chunk=await reader.read();if(done)return;if(chunk.done){if(length!==null&&total!==Number(length)){await finish(fail('TRUNCATED'));return;}value.close();await finish();return;}total+=chunk.value.byteLength;if(total>maximumResponseBytes){await finish(fail('RESPONSE_LIMIT'),true);return;}value.enqueue(chunk.value);}
|
|
42
|
+
catch(error){await finish(error,true);}
|
|
43
|
+
},
|
|
44
|
+
cancel(reason){return finish(reason??fail('CANCELLED'),true);},
|
|
45
|
+
});
|
|
46
|
+
combined.addEventListener('abort',abort,{once:true});if(combined.aborted)abort();
|
|
47
|
+
return new Response(stream,{status:response.status,statusText:response.statusText,headers:response.headers});
|
|
48
|
+
}catch(error){clearTimeout(timer);throw error;}
|
|
49
|
+
})();
|
|
50
|
+
pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));
|
|
51
|
+
// Bound the caller without pretending a late underlying request has closed.
|
|
52
|
+
// close() still awaits the original task and cancels its eventual response.
|
|
53
|
+
return new Promise((resolve,reject)=>{
|
|
54
|
+
const abort=()=>{combined.removeEventListener('abort',abort);reject(combined.reason??fail('DEADLINE'));};
|
|
55
|
+
combined.addEventListener('abort',abort,{once:true});if(combined.aborted)abort();
|
|
56
|
+
task.then(value=>{combined.removeEventListener('abort',abort);resolve(value);},error=>{combined.removeEventListener('abort',abort);reject(error);});
|
|
57
|
+
});
|
|
58
|
+
},close(){return closing??=(async()=>{
|
|
59
|
+
closed=true;controller.abort(fail('CLOSED'));
|
|
60
|
+
await Promise.allSettled([...pending]);const results=await Promise.allSettled([...bodies].map(body=>body.cancel()));
|
|
61
|
+
if(results.some(value=>value.status==='rejected')||closureErrors.length||pending.size||bodies.size)throw fail('CLOSE_UNKNOWN');
|
|
62
|
+
return {status:'closed',activeRequests:0};
|
|
63
|
+
})();}};
|
|
64
|
+
return Object.freeze(transport);
|
|
65
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type {PublishingDeploymentStage} from '@xlinklight/publishing/worker';
|
|
2
|
+
import type {CloudflareHttpTransportFactory} from './cloudflare-provider-http.mjs';
|
|
3
|
+
export type {CloudflareOwnedHttpTransport,CloudflareHttpTransportFactory} from './cloudflare-provider-http.mjs';
|
|
4
|
+
export interface StaticPagesClientOptions {accountId:string;projectName:string;token:string;signal?:AbortSignal;request?:typeof fetch}
|
|
5
|
+
export type StaticPagesPublication={manifestSha256:string}|{publicationId:string};
|
|
6
|
+
export interface StaticPagesDeployment {id:string;origin:string;publicationId:string;state:'succeeded'|'pending'|'failed'}
|
|
7
|
+
export interface StaticPagesClient {
|
|
8
|
+
project():Promise<{name:string;productionBranch:string;subdomain?:string}>;
|
|
9
|
+
/** commit_hash is an exact provider publication binding, not asserted Git provenance. */
|
|
10
|
+
findPublication(publication:StaticPagesPublication):Promise<StaticPagesDeployment|undefined>;
|
|
11
|
+
getDeployment(reference:string,publication:StaticPagesPublication):Promise<StaticPagesDeployment|undefined>;
|
|
12
|
+
}
|
|
13
|
+
export function createStaticPagesClient(input:StaticPagesClientOptions):StaticPagesClient;
|
|
14
|
+
export interface StaticPagesPublishingLimits {maximumFiles:number;maximumFileBytes:number;maximumTotalBytes:number;maximumBatchBytes:number;maximumResponseBytes:number;maximumHeaderBytes:number;requestMs:number}
|
|
15
|
+
export interface StaticPagesPublishingOptions extends Pick<StaticPagesClientOptions,'accountId'|'projectName'|'token'> {
|
|
16
|
+
/** Stable host-owned provider principal identity; rotating its secret does not change the operation binding. */
|
|
17
|
+
credentialId:string;createHttpTransport:CloudflareHttpTransportFactory;name?:string;limits?:Partial<StaticPagesPublishingLimits>;apiVersion?:string;
|
|
18
|
+
/** Only explicit literal-loopback HTTP qualification may override the fixed production API origin. */
|
|
19
|
+
apiOrigin?:string;allowLoopback?:boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface StaticPagesPublishingReceipt {
|
|
22
|
+
schemaVersion:1;provider:'cloudflare-pages';accountId:string;projectName:string;publicationId:string;deploymentId:string;origin:string;
|
|
23
|
+
/** The observed immutable deployment origin followed by '/'. */
|
|
24
|
+
baseUrl:string;
|
|
25
|
+
/** Canonical Pages request path derived from prepared ui.entry: index.html
|
|
26
|
+
* maps to '/', nested index.html to its directory, other HTML loses '.html'. */
|
|
27
|
+
entryPath:string;
|
|
28
|
+
/** Actual immutable entry URL, without a fabricated version directory. */
|
|
29
|
+
uiUrl:string;content:{manifestSha256:string};
|
|
30
|
+
}
|
|
31
|
+
/** Optional cloudflare/noble peers load only within transport execution. Every
|
|
32
|
+
* SDK request sets maxRetries:0. No SDK types, source files, user settings or
|
|
33
|
+
* processes are required by the factory or source-free observation. */
|
|
34
|
+
export function createStaticPagesPublishingStage(input:StaticPagesPublishingOptions):PublishingDeploymentStage;
|