@xlinklight/publishing 0.0.0-stage → 3.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 +35 -2
- package/package.json +62 -3
- package/src/acceptance.d.mts +22 -0
- package/src/acceptance.mjs +66 -0
- package/src/client.d.mts +15 -0
- package/src/client.mjs +66 -0
- package/src/index.d.mts +6 -0
- package/src/index.mjs +3 -0
- package/src/node/activation.d.mts +8 -0
- package/src/node/activation.mjs +3 -0
- package/src/node/authorization.d.mts +8 -0
- package/src/node/authorization.mjs +39 -0
- package/src/node/cli.d.mts +20 -0
- package/src/node/cli.mjs +106 -0
- package/src/node/index.d.mts +16 -0
- package/src/node/index.mjs +8 -0
- package/src/node/journal.d.mts +13 -0
- package/src/node/journal.mjs +135 -0
- package/src/node/session.d.mts +23 -0
- package/src/node/session.mjs +101 -0
- package/src/node/solution-package.d.mts +15 -0
- package/src/node/solution-package.mjs +113 -0
- package/src/node/source-error.d.mts +5 -0
- package/src/node/source-error.mjs +9 -0
- package/src/node/workflow.d.mts +35 -0
- package/src/node/workflow.mjs +178 -0
- package/src/package.d.mts +11 -0
- package/src/package.mjs +36 -0
- package/src/protocol.d.mts +27 -0
- package/src/protocol.mjs +50 -0
- package/src/shared/activation.d.mts +5 -0
- package/src/shared/activation.mjs +64 -0
- package/src/worker/activation.d.mts +7 -0
- package/src/worker/activation.mjs +4 -0
- package/src/worker/index.d.mts +6 -0
- package/src/worker/index.mjs +6 -0
- package/src/worker/journal.d.mts +21 -0
- package/src/worker/journal.mjs +151 -0
- package/src/worker/package.d.mts +16 -0
- package/src/worker/package.mjs +32 -0
- package/src/worker/release.d.mts +7 -0
- package/src/worker/release.mjs +21 -0
- package/src/worker/runtime.d.mts +4 -0
- package/src/worker/runtime.mjs +23 -0
- package/src/worker/service.d.mts +41 -0
- package/src/worker/service.mjs +247 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zopenge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Link Light solution publishing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Solution publishing binds declarative metadata, an opaque Worker module closure and separately served static UI bytes to Foundation's canonical content manifest. The publisher never discovers or executes code from an uploaded package. The root entry parses the portable envelope. `@xlinklight/publishing/node` owns local capture, the CLI, credentials and the client SQLite journal. `@xlinklight/publishing/worker` owns the service, durable queue and finite deployment stages for a SQLite Durable Object. There is one cloud execution path: Cloudflare Workers and Durable Objects, with explicit provider adapters for immutable Workers and Pages deployments.
|
|
4
|
+
|
|
5
|
+
## Local preparation and client
|
|
6
|
+
|
|
7
|
+
`prepareSolutionPackage` captures an explicit file/response-policy plan with declared path case semantics and file, byte and time limits. It rejects links, escapes, missing/extra files, collisions and changing bytes. `prepareSolutionPackageBytes` composes already captured snapshots without another filesystem staging tree. Both preserve binary bytes, BOMs, line endings and response headers. Their snapshots expose bounded `readFile(path, {maximumBytes, signal})` and `streamFile(path, {signal})`; the Node snapshot also retains its owned file bytes for local freezing. These results establish byte identity, not provider deployment or business acceptance.
|
|
8
|
+
|
|
9
|
+
The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs only a pinned project configuration and token. `check` invokes the owner-installed `deployment/publishing.mjs` producer once per durable preparation; its `prepare` result must confirm `processesClosed: true`. Unknown producer closure requires recovery rather than another build. The default private client state is `state/solution-publishing`, separate from disposable build outputs. The caller owns filesystem access controls and backup policy for this secret-bearing journal.
|
|
10
|
+
|
|
11
|
+
The client never automatically repeats request creation. `publish` reuses frozen original bytes and an explicit request identity. CLI publish waits up to 300000 ms; `--no-wait` submits without waiting and `--wait-ms <1..3600000>` selects a finite wait. Programmatic `workflow.publish` defaults to one observation. Waiting uses GET only. Queued, pending or timed-out work exits 3; a closed failure exits 1; verified ACTIVE exits 0. Recovery observes the original operation without advancing its next stage. Resume may advance only after a known pending operation is observed successfully. Neither operation rebuilds, uploads or re-commits the package. Status and verification never dispatch work.
|
|
12
|
+
|
|
13
|
+
## Durable Object composition
|
|
14
|
+
|
|
15
|
+
Use the public Worker entry with Cloudflare `nodejs_compat`; mature crypto and async-context primitives are shared with the Node client. The server graph imports no filesystem, Node HTTP, DNS, subprocess or UI implementation. The application owns one singleton SQLite Durable Object and its trusted configuration, provider credentials and lifecycle:
|
|
16
|
+
|
|
17
|
+
1. `openPublishingDurableJournal({storage: ctx.storage, identity, limits, leaseMs})` binds a durable identity and exact storage limits. `configurePublishingProject` installs a project policy and credential through the trusted composition, never an uploaded module.
|
|
18
|
+
2. `createPublishingService({journal, onDispatch})` uses `X-Link-Light-Project-Id` to look up one installed project and authenticates that project's bearer credential. The public client sends the header automatically. The service commits the queue entry in the same SQL transaction as the request. `onDispatch` calls the runtime's `schedule`.
|
|
19
|
+
3. `createPublishingWorker({journal, withProjectLock: journal.withProjectLock, stages, metadataTransport, operationLimits})` invokes explicitly installed pure stage factories. The lease fences the current request and policy before and after effects and final writes. Choose `leaseMs` to cover the operation and its closure budget; it must not be shorter than the configured job budget.
|
|
20
|
+
4. `createPublishingDurableRuntime({ctx, journal, service, worker, limits})` returns `fetch`, `alarm`, `run`, `schedule` and `status`. Forward the object's fetch and alarm entrypoints to it. Construction does not listen or launch a background process. `schedule` preserves an already earlier alarm. Each alarm owns one verification batch or one original stage operation, then persists its next wake before acknowledgment. `limits` contains `jobMs`, `pollMs` and optional `maximumPolls` (default 18, maximum 128). A pending stage exhausts that finite observation budget and remains resumable; it is never accepted by timeout.
|
|
21
|
+
|
|
22
|
+
SQLite transactions jointly check CAS revision, current project policy and credential or worker lease, original request identity, immutable chunk identity and capacity. Each acknowledgment awaits `storage.sync()`. The configured recovery reserve remains available for observation and closure metadata. Immutable blobs are at most 1 MiB; there is no complete-package or 128 MiB-file assembly in the isolate. The manifest and descriptor are bounded control documents. A durable verification cursor binds the manifest, full intent and policy; each turn streams one file with incremental hash verification before recording its cursor. Deployment stages consume declaration-only `files`, `readFile` capped at 16 MiB, and streams yielding at most 1 MiB. A caller must explicitly budget each small control read and stream large content.
|
|
23
|
+
|
|
24
|
+
Queue mode, continuation permission, observation count, next wake and leases survive actor replacement. A lease that expires during a turn is recovered in observe mode with continuation disabled. Foundation `artifact-publish@0.4.1` binds and CAS-claims each exact original operation. Lost acknowledgments cannot authorize a second mutation; recovery observes that claim. An unconfirmed transport close poisons the actor and requests its reset, retaining the durable original lease. Unknown effects never activate a release. No Node host, process scheduler or PostgreSQL cloud-journal alternative is provided.
|
|
25
|
+
|
|
26
|
+
## Stages and activation
|
|
27
|
+
|
|
28
|
+
Factories are synchronous and pure. All I/O belongs in the Foundation transport's finite `execute` or `observe` lifecycle. `readResult` synchronously extracts bounded immutable evidence already observed there. Stage names, capabilities, configuration digests and prior result receipts pin the plan. A stage with `waitForSignal` settles a pending observation as `awaiting-acceptance`. Its authenticated completion can persist a receipt and enqueue the original observation in one journal transaction.
|
|
29
|
+
|
|
30
|
+
The `@xlinklight/publishing/acceptance` export provides domain-separated Ed25519 job and receipt signatures. Job identity covers the project, request, intent digest, policy revision, candidate, acceptance artifact and generation. Verification uses the explicitly registered key. A PASS receipt represents closed synthetic instances and zero active acceptance requests; the host rechecks those facts before requesting production promotion.
|
|
31
|
+
|
|
32
|
+
`preparePublishingRelease` takes the actual observed `serverUrl` and `uiUrl`, reads the original descriptor and explicitly named component receipt paths, hashes their exact bytes and reuses the public platform payload validator. It preserves root or nested provider paths without inventing a version directory. Complete uploaded bytes are verified before this function consumes their sealed lazy snapshot. It does not sign, deploy, register or run acceptance. `createPublishingActivation` requires actual acceptance and confirmed effect closure before signing. Its statement binds the original project, request, policy, configuration, complete content intent and acceptance receipt. `verifyPublishingActivation` checks both signatures and current Core admission; cached approval cannot override revocation. Worker callers explicitly provide the metadata transport. Node activation loads the optional platform peer only when used.
|
|
33
|
+
|
|
34
|
+
Provider adapters own immutable Worker/Pages identities, current physical quotas, exact response bytes and headers, registration, actual acceptance and signing. The package parser grants no domain admission and carries no provider credentials. Core never imports a business implementation or evaluates an upload.
|
|
35
|
+
|
|
36
|
+
`pnpm test` retains local durable-filesystem, protocol, client, service, stage and SQLite CAS regressions. The separate workerd test exercises actual SQLite Durable Object storage and the bundled Worker graph. Local tests establish neither cloud deployment acceptance nor production availability.
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xlinklight/publishing",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "3.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/zopenge/link-light.git",
|
|
8
|
+
"directory": "packages/publishing"
|
|
9
|
+
},
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public",
|
|
12
|
+
"registry": "https://registry.npmjs.org",
|
|
13
|
+
"provenance": false
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"files": [
|
|
18
|
+
"src",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"bin": {
|
|
22
|
+
"link-light-release": "./src/node/cli.mjs"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
"./acceptance": {
|
|
26
|
+
"types": "./src/acceptance.d.mts",
|
|
27
|
+
"import": "./src/acceptance.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./worker": {
|
|
30
|
+
"types": "./src/worker/index.d.mts",
|
|
31
|
+
"import": "./src/worker/index.mjs"
|
|
32
|
+
},
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./src/index.d.mts",
|
|
35
|
+
"import": "./src/index.mjs"
|
|
36
|
+
},
|
|
37
|
+
"./node": {
|
|
38
|
+
"types": "./src/node/index.d.mts",
|
|
39
|
+
"browser": null,
|
|
40
|
+
"import": "./src/node/index.mjs"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@openge/forge-artifact-integrity": "0.1.0",
|
|
45
|
+
"@openge/forge-artifact-publish": "0.4.1",
|
|
46
|
+
"@openge/forge-generated-artifacts": "0.2.0",
|
|
47
|
+
"@openge/forge-path-safety": "0.1.0",
|
|
48
|
+
"@xlinklight/contracts": "3.0.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@xlinklight/platform": "5.0.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"@xlinklight/platform": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=22.15.0"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "node --check src/index.mjs && node --check src/node/index.mjs",
|
|
63
|
+
"test": "node --test --test-concurrency=1 tests/*.node-test.mjs"
|
|
64
|
+
}
|
|
6
65
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type {KeyObject} from 'node:crypto';
|
|
2
|
+
import type {SolutionReleaseManifest} from '@xlinklight/contracts';
|
|
3
|
+
|
|
4
|
+
export interface AcceptanceIdentity {
|
|
5
|
+
projectId:string;requestId:string;intentSha256:string;policyRevision:number;
|
|
6
|
+
releaseDigest:string;acceptanceArtifactSha256:string;generation:number;
|
|
7
|
+
}
|
|
8
|
+
export interface AcceptanceJob extends AcceptanceIdentity {
|
|
9
|
+
schemaVersion:1;jobId:string;manifest:Readonly<SolutionReleaseManifest>;
|
|
10
|
+
}
|
|
11
|
+
export interface AcceptanceReceipt extends AcceptanceIdentity {
|
|
12
|
+
schemaVersion:1;jobId:string;status:'PASS';
|
|
13
|
+
proof:{syntheticInstancesCreated:number;syntheticInstancesDisabled:number;closure:{status:'closed';activeRequests:0}};
|
|
14
|
+
}
|
|
15
|
+
export interface AcceptanceEnvelope<Payload> {payload:Payload;keyId:string;signature:string}
|
|
16
|
+
export interface AcceptanceSigner {keyId:string;privateKey:string|KeyObject}
|
|
17
|
+
export interface AcceptanceVerifier {keyId:string;publicKey:string|KeyObject}
|
|
18
|
+
export function acceptanceJobId(identity:AcceptanceIdentity):string;
|
|
19
|
+
export function signAcceptanceJob(job:AcceptanceJob,options:AcceptanceSigner):AcceptanceEnvelope<AcceptanceJob>;
|
|
20
|
+
export function verifyAcceptanceJob(envelope:unknown,options:AcceptanceVerifier):AcceptanceJob;
|
|
21
|
+
export function signAcceptanceReceipt(receipt:AcceptanceReceipt,options:AcceptanceSigner):AcceptanceEnvelope<AcceptanceReceipt>;
|
|
22
|
+
export function verifyAcceptanceReceipt(envelope:unknown,options:AcceptanceVerifier):AcceptanceReceipt;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import {createHash,createPrivateKey,createPublicKey,sign,verify} from 'node:crypto';
|
|
2
|
+
import {canonicalMetadata} from '@xlinklight/platform/worker';
|
|
3
|
+
import {protocolRecord,publishingDigest,publishingError,publishingIdentifier,publishingRequestId} from './protocol.mjs';
|
|
4
|
+
|
|
5
|
+
const positive=value=>Number.isSafeInteger(value)&&value>0;
|
|
6
|
+
const identityKeys=['projectId','requestId','intentSha256','policyRevision','releaseDigest','acceptanceArtifactSha256','generation'];
|
|
7
|
+
const bindingKeys=['schemaVersion','jobId',...identityKeys];
|
|
8
|
+
const invalid=part=>publishingError('ACCEPTANCE_'+part+'_INVALID');
|
|
9
|
+
|
|
10
|
+
export function acceptanceJobId(identity){
|
|
11
|
+
if(!identity||!publishingIdentifier(identity.projectId)||!publishingRequestId(identity.requestId)
|
|
12
|
+
||!publishingDigest(identity.intentSha256)||!positive(identity.policyRevision)
|
|
13
|
+
||!/^sha256:[a-f0-9]{64}$/.test(identity.releaseDigest??'')||!publishingDigest(identity.acceptanceArtifactSha256)
|
|
14
|
+
||!positive(identity.generation))throw invalid('JOB');
|
|
15
|
+
const binding=Object.fromEntries(identityKeys.map(key=>[key,identity[key]]));
|
|
16
|
+
return createHash('sha256').update('link-light/acceptance-job-id/v1\n').update(canonicalMetadata(binding)).digest('hex');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function checkBinding(payload,kind){
|
|
20
|
+
try{return payload.schemaVersion===1&&payload.jobId===acceptanceJobId(payload);}
|
|
21
|
+
catch{throw invalid(kind);}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function jobPayload(payload){
|
|
25
|
+
if(!protocolRecord(payload,[...bindingKeys,'manifest'])||!checkBinding(payload,'JOB')
|
|
26
|
+
||payload.manifest?.releaseDigest!==payload.releaseDigest||!publishingIdentifier(payload.manifest.solutionId)
|
|
27
|
+
||!/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(payload.manifest.version??''))throw invalid('JOB');
|
|
28
|
+
return payload;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function receiptPayload(payload){
|
|
32
|
+
if(!protocolRecord(payload,[...bindingKeys,'status','proof'])||!checkBinding(payload,'RECEIPT')||payload.status!=='PASS'
|
|
33
|
+
||!protocolRecord(payload.proof,['syntheticInstancesCreated','syntheticInstancesDisabled','closure']))throw invalid('RECEIPT');
|
|
34
|
+
const {syntheticInstancesCreated,syntheticInstancesDisabled,closure}=payload.proof;
|
|
35
|
+
if(!positive(syntheticInstancesCreated)||syntheticInstancesCreated<2||syntheticInstancesCreated>1024
|
|
36
|
+
||syntheticInstancesCreated!==syntheticInstancesDisabled||!protocolRecord(closure,['status','activeRequests'])
|
|
37
|
+
||closure.status!=='closed'||closure.activeRequests!==0)throw invalid('RECEIPT');
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function message(kind,payload){
|
|
42
|
+
const canonical=canonicalMetadata(payload);
|
|
43
|
+
if(Buffer.byteLength(canonical)>65536)throw invalid(kind);
|
|
44
|
+
return Buffer.from('link-light/acceptance-'+kind.toLowerCase()+'/v1\n'+canonical);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function signEnvelope(payload,kind,{keyId,privateKey}){
|
|
48
|
+
const key=typeof privateKey==='string'?createPrivateKey(privateKey):privateKey;
|
|
49
|
+
if(!publishingIdentifier(keyId)||key?.type!=='private'||key.asymmetricKeyType!=='ed25519')throw invalid('SIGNATURE');
|
|
50
|
+
return {payload:structuredClone(payload),keyId,signature:sign(null,message(kind,payload),key).toString('base64url')};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function verifyEnvelope(envelope,kind,parse,{keyId,publicKey}){
|
|
54
|
+
if(!protocolRecord(envelope,['payload','keyId','signature'])||!publishingIdentifier(keyId)||envelope.keyId!==keyId
|
|
55
|
+
||typeof envelope.signature!=='string'||!/^[A-Za-z0-9_-]{86}$/.test(envelope.signature))throw invalid('SIGNATURE');
|
|
56
|
+
const payload=parse(envelope.payload),bytes=Buffer.from(envelope.signature,'base64url');
|
|
57
|
+
const key=typeof publicKey==='string'?createPublicKey(publicKey):publicKey;
|
|
58
|
+
if(key?.type!=='public'||key.asymmetricKeyType!=='ed25519'||bytes.toString('base64url')!==envelope.signature
|
|
59
|
+
||!verify(null,message(kind,payload),key,bytes))throw invalid('SIGNATURE');
|
|
60
|
+
return structuredClone(payload);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const signAcceptanceJob=(job,options)=>signEnvelope(jobPayload(job),'JOB',options);
|
|
64
|
+
export const verifyAcceptanceJob=(envelope,options)=>verifyEnvelope(envelope,'JOB',jobPayload,options);
|
|
65
|
+
export const signAcceptanceReceipt=(receipt,options)=>signEnvelope(receiptPayload(receipt),'RECEIPT',options);
|
|
66
|
+
export const verifyAcceptanceReceipt=(envelope,options)=>verifyEnvelope(envelope,'RECEIPT',receiptPayload,options);
|
package/src/client.d.mts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
+
import type {PublishingConfiguration,PublishingProject,PublishingIntent,PublishingStatus} from './protocol.mjs';
|
|
3
|
+
export interface PublishingClientLimits {requestMs:number;maximumResponseBytes:number;maximumChunkBytes:number}
|
|
4
|
+
export interface PublishingClient {
|
|
5
|
+
getProject(input?:{signal?:AbortSignal}):Promise<PublishingProject>;
|
|
6
|
+
createRequest(input:{intent:PublishingIntent;manifestBytes:Uint8Array;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
7
|
+
getStatus(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
8
|
+
resumeRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
9
|
+
recoverRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
10
|
+
queueRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
11
|
+
abandonRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
12
|
+
uploadChunk(input:{requestId:string;file:{sha256:string;byteLength:number};offset:number;bytes:Uint8Array;signal?:AbortSignal}):Promise<{schemaVersion:1;sha256:string;receivedBytes:number}>;
|
|
13
|
+
}
|
|
14
|
+
export interface PublishingClientOptions {configuration:PublishingConfiguration;credential:string;allowLoopback?:boolean;request?:typeof fetch;limits?:PublishingClientLimits;verifyActivation?:(input:{activation:JsonValue;intent:PublishingIntent;configuration:PublishingConfiguration})=>Promise<void>|void}
|
|
15
|
+
export function createPublishingClient(options:PublishingClientOptions):PublishingClient;
|
package/src/client.mjs
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import {calculateBytesIntegrity} from '@openge/forge-artifact-integrity';
|
|
2
|
+
import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
|
|
3
|
+
import {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,parsePublishingStatus,publishingIntentBytes,publishingError,publishingRequestId,publishingDigest,protocolRecord} from './protocol.mjs';
|
|
4
|
+
|
|
5
|
+
const defaults=Object.freeze({requestMs:30000,maximumResponseBytes:1048576,maximumChunkBytes:262144});
|
|
6
|
+
const serviceErrors=new Set(['NOT_AUTHORIZED','PROJECT_DISABLED','POLICY_CHANGED','CONFLICT','REQUEST_NOT_FOUND','QUOTA_PAUSED','INVALID_INPUT','UNKNOWN_EFFECTS','BUSY','NOT_READY']);
|
|
7
|
+
function boundedLimits(value){
|
|
8
|
+
if(!protocolRecord(value,['requestMs','maximumResponseBytes','maximumChunkBytes'])||Object.values(value).some(item=>!Number.isSafeInteger(item)||item<1)||value.requestMs>300000||value.maximumResponseBytes>2097152||value.maximumChunkBytes>1048576)throw publishingError('CLIENT_LIMIT_INVALID');return {...value};
|
|
9
|
+
}
|
|
10
|
+
async function responseJson(response,maximum,signal){
|
|
11
|
+
const declared=response.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>maximum)){await response.body?.cancel();throw publishingError('RESPONSE_BYTE_LIMIT');}
|
|
12
|
+
if(!response.body)throw publishingError('RESPONSE_INVALID');
|
|
13
|
+
const reader=response.body.getReader(),chunks=[];let total=0;
|
|
14
|
+
try{
|
|
15
|
+
for(;;){signal.throwIfAborted();const {done,value}=await reader.read();if(done)break;total+=value.byteLength;if(total>maximum)throw publishingError('RESPONSE_BYTE_LIMIT');chunks.push(value);}
|
|
16
|
+
}catch(error){try{await reader.cancel();}catch{}throw error;}
|
|
17
|
+
finally{reader.releaseLock();}
|
|
18
|
+
const bytes=new Uint8Array(total);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}
|
|
19
|
+
try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));}catch{throw publishingError('RESPONSE_INVALID');}
|
|
20
|
+
}
|
|
21
|
+
/** All writes are explicit. Recovery reads the original request; there is no retry loop. */
|
|
22
|
+
export function createPublishingClient({configuration,credential,allowLoopback=false,request=fetch,limits=defaults,verifyActivation}){
|
|
23
|
+
const config=parsePublishingConfiguration(configuration,{allowLoopback}),selected=boundedLimits(limits);
|
|
24
|
+
if(typeof credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(credential)||typeof request!=='function'||verifyActivation!==undefined&&typeof verifyActivation!=='function')throw publishingError('CREDENTIAL_INVALID');
|
|
25
|
+
const send=async(method,relative,body,signal,contentType='application/json')=>{
|
|
26
|
+
signal?.throwIfAborted();const timeout=AbortSignal.timeout(selected.requestMs),active=signal?AbortSignal.any([signal,timeout]):timeout;
|
|
27
|
+
let response;
|
|
28
|
+
try{response=await request(config.serviceUrl+relative,{method,headers:{authorization:'Bearer '+credential,'x-link-light-project-id':config.projectId,...(body===undefined?{}:{'content-type':contentType})},body,redirect:'error',credentials:'omit',cache:'no-store',signal:active});}
|
|
29
|
+
catch{active.throwIfAborted();throw publishingError('SERVICE_UNREACHABLE');}
|
|
30
|
+
active.throwIfAborted();const value=await responseJson(response,selected.maximumResponseBytes,active);
|
|
31
|
+
if(!response.ok)throw publishingError(serviceErrors.has(value?.error?.code)?value.error.code:'SERVICE_REQUEST_FAILED');return value;
|
|
32
|
+
};
|
|
33
|
+
const boundStatus=async(value,intent)=>{
|
|
34
|
+
const status=parsePublishingStatus(value),identity=await calculateBytesIntegrity(publishingIntentBytes(intent));
|
|
35
|
+
if(intent.projectId!==config.projectId||intent.package.publisherId!==config.publisher.publisherId||status.projectId!==config.projectId||status.requestId!==intent.requestId||status.intentSha256!==identity.sha256||status.missingFiles.length>intent.package.fileCount||status.missingFiles.reduce((sum,file)=>sum+file.byteLength,0)>intent.package.totalBytes)throw publishingError('STATUS_BINDING_INVALID');
|
|
36
|
+
if(status.activation!==undefined){
|
|
37
|
+
if(typeof verifyActivation!=='function')throw publishingError('ACTIVATION_VERIFIER_REQUIRED');
|
|
38
|
+
await verifyActivation({activation:status.activation,intent,configuration:structuredClone(config)});
|
|
39
|
+
}
|
|
40
|
+
return status;
|
|
41
|
+
};
|
|
42
|
+
const checkedIntent=value=>{const intent=parsePublishingIntent(value);if(intent.projectId!==config.projectId||intent.package.publisherId!==config.publisher.publisherId)throw publishingError('INTENT_BINDING_INVALID');return intent;};
|
|
43
|
+
return Object.freeze({
|
|
44
|
+
async getProject({signal}={}){
|
|
45
|
+
const project=parsePublishingProject(await send('GET','/v1/project',undefined,signal),{allowLoopback});
|
|
46
|
+
if(JSON.stringify(project.configuration)!==JSON.stringify(config))throw publishingError('PROJECT_BINDING_INVALID');return project;
|
|
47
|
+
},
|
|
48
|
+
async createRequest({intent:input,manifestBytes,signal}){
|
|
49
|
+
const intent=checkedIntent(input);
|
|
50
|
+
if(!(manifestBytes instanceof Uint8Array)||manifestBytes.byteLength>1048576)throw publishingError('MANIFEST_INVALID');
|
|
51
|
+
let prepared;try{prepared=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(manifestBytes)));}catch{throw publishingError('MANIFEST_INVALID');}
|
|
52
|
+
if(prepared.content.manifestSha256!==intent.package.content.manifestSha256||prepared.bytes.byteLength!==manifestBytes.byteLength||prepared.bytes.some((byte,index)=>byte!==manifestBytes[index])||prepared.manifest.files.length!==intent.package.fileCount||prepared.manifest.files.reduce((sum,file)=>sum+file.byteLength,0)!==intent.package.totalBytes)throw publishingError('MANIFEST_BINDING_INVALID');
|
|
53
|
+
return boundStatus(await send('POST','/v1/requests',JSON.stringify({intent,manifest:prepared.manifest}),signal),intent);
|
|
54
|
+
},
|
|
55
|
+
async getStatus({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('GET','/v1/requests/'+intent.requestId,undefined,signal),intent);},
|
|
56
|
+
async resumeRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/resume',JSON.stringify({intent}),signal),intent);},
|
|
57
|
+
async recoverRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/recover',JSON.stringify({intent}),signal),intent);},
|
|
58
|
+
async queueRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/commit',JSON.stringify({intent}),signal),intent);},
|
|
59
|
+
async abandonRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/abandon','{}',signal),intent);},
|
|
60
|
+
async uploadChunk({requestId,file,offset,bytes,signal}){
|
|
61
|
+
if(!publishingRequestId(requestId)||!file||!publishingDigest(file.sha256)||!Number.isSafeInteger(file.byteLength)||file.byteLength<0||file.byteLength>134217728||!Number.isSafeInteger(offset)||offset<0||!(bytes instanceof Uint8Array)||bytes.byteLength<1||bytes.byteLength>selected.maximumChunkBytes||offset+bytes.byteLength>file.byteLength)throw publishingError('CHUNK_INVALID');
|
|
62
|
+
const snapshot=new Uint8Array(bytes),value=await send('PUT','/v1/requests/'+requestId+'/files/'+file.sha256+'?offset='+offset,snapshot,signal,'application/octet-stream');
|
|
63
|
+
if(!protocolRecord(value,['schemaVersion','sha256','receivedBytes'])||value.schemaVersion!==1||value.sha256!==file.sha256||value.receivedBytes!==offset+snapshot.byteLength)throw publishingError('CHUNK_RESPONSE_INVALID');return value;
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
package/src/index.d.mts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type {SolutionPackageDescriptor,SolutionPackageLimits} from './package.mjs';
|
|
2
|
+
export {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from './package.mjs';
|
|
3
|
+
export type {PublishingConfiguration,PublishingProject,PublishingIntent,PublishingStatus,PublishingMetadataTransport} from './protocol.mjs';
|
|
4
|
+
export {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,parsePublishingStatus,publishingIntentBytes} from './protocol.mjs';
|
|
5
|
+
export type {PublishingClient,PublishingClientLimits,PublishingClientOptions} from './client.mjs';
|
|
6
|
+
export {createPublishingClient} from './client.mjs';
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from './package.mjs';
|
|
2
|
+
export {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,parsePublishingStatus,publishingIntentBytes} from './protocol.mjs';
|
|
3
|
+
export {createPublishingClient} from './client.mjs';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type {SolutionReleaseManifest} from '@xlinklight/contracts';
|
|
2
|
+
import type {PublishingMetadataTransport as ReleaseMetadataTransport} from '../protocol.mjs';
|
|
3
|
+
import type {PublishingConfiguration,PublishingIntent} from '../protocol.mjs';
|
|
4
|
+
import type {PublishingActivation} from '../shared/activation.mjs';
|
|
5
|
+
export type {PublishingActivation} from '../shared/activation.mjs';
|
|
6
|
+
interface ActivationContext {configuration:PublishingConfiguration;intent:PublishingIntent;allowLoopback?:boolean;metadataTransport?:ReleaseMetadataTransport;signal?:AbortSignal}
|
|
7
|
+
export function createPublishingActivation(input:ActivationContext&{manifest:SolutionReleaseManifest;acceptanceReceiptSha256:string;keyId:string;privateKey:string}):Promise<PublishingActivation>;
|
|
8
|
+
export function verifyPublishingActivation(input:ActivationContext&{activation:unknown}):Promise<{manifest:Readonly<SolutionReleaseManifest>;acceptanceReceiptSha256:string}>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type {PublishingConfiguration} from '../protocol.mjs';
|
|
2
|
+
import type {PublishingClientLimits} from '../client.mjs';
|
|
3
|
+
import type {PublishingJournal} from './journal.mjs';
|
|
4
|
+
export interface PublishingAuthorization {configuration:PublishingConfiguration;credential:string}
|
|
5
|
+
export function loadPublishingAuthorization(input:{journal:Pick<PublishingJournal,'load'|'compareAndSet'>;allowLoopback?:boolean;signal?:AbortSignal}):Promise<PublishingAuthorization|undefined>;
|
|
6
|
+
export function installPublishingAuthorization(input:PublishingAuthorization&{
|
|
7
|
+
journal:Pick<PublishingJournal,'load'|'compareAndSet'>;replaceCredential?:boolean;allowLoopback?:boolean;request?:typeof fetch;clientLimits?:PublishingClientLimits;signal?:AbortSignal;
|
|
8
|
+
}):Promise<{status:'CONFIGURED'|'VERIFIED'|'REPLACED';projectId:string;credentialSha256:string;policyRevision:number}>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {createPublishingClient} from '../client.mjs';
|
|
3
|
+
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
4
|
+
|
|
5
|
+
const key='client-authorization',hash=value=>createHash('sha256').update(value).digest('hex'),fail=code=>publishingError('CREDENTIAL_'+code);
|
|
6
|
+
const credentialValid=value=>typeof value==='string'&&/^[A-Za-z0-9_-]{32,4096}$/.test(value);
|
|
7
|
+
function saved(record,allowLoopback){
|
|
8
|
+
if(!record)return undefined;const value=record.payload;
|
|
9
|
+
if(!protocolRecord(value,['schemaVersion','configuration','configurationSha256','credential','credentialSha256'])||value.schemaVersion!==1||!credentialValid(value.credential))throw fail('INVALID');
|
|
10
|
+
let configuration;try{configuration=parsePublishingConfiguration(value.configuration,{allowLoopback});}catch{throw fail('INVALID');}
|
|
11
|
+
if(hash(JSON.stringify(configuration))!==value.configurationSha256||hash(value.credential)!==value.credentialSha256)throw fail('INVALID');return {configuration,credential:value.credential};
|
|
12
|
+
}
|
|
13
|
+
function store(journal){if(!journal||typeof journal.load!=='function'||typeof journal.compareAndSet!=='function')throw fail('STORE_INVALID');return journal;}
|
|
14
|
+
|
|
15
|
+
/** The caller supplies private persistent storage, including access controls and
|
|
16
|
+
* backup policy. No provider credential or process/global setting is stored. */
|
|
17
|
+
export async function loadPublishingAuthorization({journal,allowLoopback=false,signal}){
|
|
18
|
+
signal?.throwIfAborted();return saved(await store(journal).load(key,{signal}),allowLoopback);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Validate installed trust and current project access before atomic install.
|
|
22
|
+
* A changed service/publisher trust never adopts an existing recovery journal. */
|
|
23
|
+
export async function installPublishingAuthorization({journal,configuration:input,credential,replaceCredential=false,allowLoopback=false,request,clientLimits,signal}){
|
|
24
|
+
store(journal);signal?.throwIfAborted();const configuration=parsePublishingConfiguration(input,{allowLoopback});
|
|
25
|
+
if(!credentialValid(credential)||typeof replaceCredential!=='boolean')throw fail('INVALID');
|
|
26
|
+
const previous=await journal.load(key,{signal}),current=saved(previous,allowLoopback),configurationSha256=hash(JSON.stringify(configuration)),credentialSha256=hash(credential);
|
|
27
|
+
if(current&&JSON.stringify(current.configuration)!==JSON.stringify(configuration))throw fail('TRUST_CHANGED');
|
|
28
|
+
if(current&¤t.credential!==credential&&!replaceCredential)throw fail('REPLACEMENT_REQUIRED');
|
|
29
|
+
const client=createPublishingClient({configuration,credential,allowLoopback,...(request?{request}:{}),...(clientLimits?{limits:clientLimits}:{})}),project=await client.getProject({signal});
|
|
30
|
+
if(current?.credential===credential){
|
|
31
|
+
const latest=await journal.load(key,{signal});if(latest?.revision!==previous.revision)throw fail('CONFLICT');saved(latest,allowLoopback);
|
|
32
|
+
return {status:'VERIFIED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
|
33
|
+
}
|
|
34
|
+
let result;
|
|
35
|
+
try{result=await journal.compareAndSet({key,expectedRevision:previous?.revision??0,payload:{schemaVersion:1,configuration,configurationSha256,credential,credentialSha256}},{signal});}
|
|
36
|
+
catch{throw fail('PERSISTENCE_UNKNOWN');}
|
|
37
|
+
if(result==='conflict')throw fail('CONFLICT');if(result!=='stored')throw fail('PERSISTENCE_UNKNOWN');
|
|
38
|
+
return {status:previous?'REPLACED':'CONFIGURED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
|
39
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type {Readable} from 'node:stream';
|
|
2
|
+
import type {DurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
3
|
+
import type {PublishingMetadataTransport as ReleaseMetadataTransport} from '../protocol.mjs';
|
|
4
|
+
import type {PublishingJournalLimits} from './journal.mjs';
|
|
5
|
+
import type {PublishingClientLimits} from '../client.mjs';
|
|
6
|
+
import type {PublishingWorkflowResult} from './workflow.mjs';
|
|
7
|
+
export interface PublishingCommandOptions {
|
|
8
|
+
cwd?:string;stdin?:Readable&{isTTY?:boolean};signal?:AbortSignal;
|
|
9
|
+
filesystem?:DurableArtifactFilesystem;journalLimits?:PublishingJournalLimits;
|
|
10
|
+
credentialInputTimeoutMilliseconds?:number;allowLoopback?:boolean;
|
|
11
|
+
request?:typeof fetch;clientLimits?:PublishingClientLimits;metadataTransport?:ReleaseMetadataTransport;
|
|
12
|
+
operationLimits?:{timeoutMilliseconds:number;closeTimeoutMilliseconds:number};
|
|
13
|
+
}
|
|
14
|
+
export interface PublishingCommandResult {
|
|
15
|
+
/** 0: completed local action or verified active; 1: refused/failed;
|
|
16
|
+
* 2: unsupported arguments; 3: observed pending/non-active work. */
|
|
17
|
+
exitCode:number;
|
|
18
|
+
output:PublishingWorkflowResult|{error:{code:string}}|{state:string;projectId:string;policyRevision:number}|{commands:string[];sourceProducer:string;stateDirectory:string;publishWaitMs:number;publishOptions:string[]};
|
|
19
|
+
}
|
|
20
|
+
export function runPublishingCommand(args:readonly string[],options?:PublishingCommandOptions):Promise<PublishingCommandResult>;
|
package/src/node/cli.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
7
|
+
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
8
|
+
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
|
+
import {openPublishingJournal} from './journal.mjs';
|
|
10
|
+
import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
11
|
+
import {createPublishingWorkflow} from './workflow.mjs';
|
|
12
|
+
|
|
13
|
+
const commands=['credentials','check','publish','status','recover','verify','abandon'];
|
|
14
|
+
const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
|
|
15
|
+
const fail=code=>publishingError(code);
|
|
16
|
+
function parse(args){
|
|
17
|
+
if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
|
|
18
|
+
if(args.length===1&&args[0]==='--help')return {command:'help'};
|
|
19
|
+
const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
|
|
20
|
+
const selected={command},seen=new Set();
|
|
21
|
+
for(let index=1;index<args.length;index++){
|
|
22
|
+
const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
|
|
23
|
+
if(['--root','--state','--producer'].includes(flag)){
|
|
24
|
+
const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
|
|
25
|
+
}else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
|
|
26
|
+
else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
|
|
27
|
+
else if(flag==='--wait-ms'&&command==='publish'){
|
|
28
|
+
const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
|
|
29
|
+
}
|
|
30
|
+
else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
|
|
31
|
+
else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
|
|
32
|
+
else throw fail('CLI_ARGUMENT_INVALID');
|
|
33
|
+
}
|
|
34
|
+
if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
|
|
35
|
+
if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
|
|
36
|
+
for(const key of ['state','producer'])if(selected[key]!==undefined){try{if(validatePortableRelativePath(selected[key])!==selected[key]||key==='producer'&&!selected[key].endsWith('.mjs'))throw Error();}catch{throw fail('CLI_ARGUMENT_INVALID');}}
|
|
37
|
+
return selected;
|
|
38
|
+
}
|
|
39
|
+
async function credentialInput(stdin,signal,timeoutMilliseconds){
|
|
40
|
+
if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
|
|
41
|
+
if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
|
|
42
|
+
const chunks=[];let bytes=0,timer,abort,data,end,error,close;
|
|
43
|
+
let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
|
|
44
|
+
try{
|
|
45
|
+
if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
|
|
46
|
+
await new Promise((resolve,reject)=>{
|
|
47
|
+
let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
|
|
48
|
+
data=value=>{if(settled)return;if(!(value instanceof Uint8Array)&&typeof value!=='string')return rejectOnce('CREDENTIAL_INPUT_INVALID');const chunk=Buffer.from(value);bytes+=chunk.byteLength;if(bytes>16384)return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT');chunks.push(chunk);};
|
|
49
|
+
end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
|
|
50
|
+
stdin.on('data',data);stdin.once('end',end);stdin.once('error',error);stdin.once('close',close);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(()=>rejectOnce('CREDENTIAL_INPUT_TIMEOUT'),timeoutMilliseconds);stdin.resume();
|
|
51
|
+
});
|
|
52
|
+
let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
|
|
53
|
+
if(!protocolRecord(value,['configuration','credential'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
|
|
54
|
+
}catch(error){if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))throw error;throw fail(signal?.aborted?'CREDENTIAL_INPUT_CANCELLED':'CREDENTIAL_INPUT_INVALID');}
|
|
55
|
+
finally{
|
|
56
|
+
clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
|
|
57
|
+
for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
|
|
58
|
+
// Explicit credential input is owned by this call, including blocked pipes.
|
|
59
|
+
stdin.destroy();let closureTimer;
|
|
60
|
+
try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
|
|
61
|
+
finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function diagnostic(error){
|
|
65
|
+
const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Bounded one-shot CLI. No token, private producer cause, provider output or
|
|
69
|
+
* environment is returned. Callers own private storage ACLs and backup policy. */
|
|
70
|
+
async function executeCommand(selected,options){
|
|
71
|
+
let journal;
|
|
72
|
+
try{
|
|
73
|
+
const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
|
|
74
|
+
const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
|
|
75
|
+
if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
|
|
76
|
+
signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
|
|
77
|
+
if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
|
|
78
|
+
const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
|
|
79
|
+
journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
|
|
80
|
+
const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
|
|
81
|
+
if(input){
|
|
82
|
+
const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
|
|
83
|
+
return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
|
|
84
|
+
}
|
|
85
|
+
const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
|
|
86
|
+
const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
|
|
87
|
+
const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
|
|
88
|
+
const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
|
|
89
|
+
return {exitCode,output:result};
|
|
90
|
+
}finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function runPublishingCommand(args,options={}){
|
|
94
|
+
let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
|
|
95
|
+
if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:'deployment/publishing.mjs',stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
|
|
96
|
+
try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function main(){
|
|
100
|
+
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
101
|
+
try{const result=await runPublishingCommand(process.argv.slice(2),{signal:controller.signal});process.stdout.write(JSON.stringify(result.output)+'\n');process.exitCode=result.exitCode;}
|
|
102
|
+
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A producer can import the same public Node entry while the command is running.
|
|
106
|
+
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type {SolutionPackageLimits,SolutionPackageFilePlan,PreparedSolutionPackage} from './solution-package.mjs';
|
|
2
|
+
export type {PublishingMetadataTransport} from '../protocol.mjs';
|
|
3
|
+
export {prepareSolutionPackage,prepareSolutionPackageBytes,verifySolutionPackage,verifySolutionPackageBytes} from './solution-package.mjs';
|
|
4
|
+
export type {PublishingJournal,PublishingJournalRecord,PublishingJournalLimits} from './journal.mjs';
|
|
5
|
+
export {openPublishingJournal} from './journal.mjs';
|
|
6
|
+
export type {PublishingSession,PublishingSessionResult} from './session.mjs';
|
|
7
|
+
export {createPublishingSession} from './session.mjs';
|
|
8
|
+
export type {PublishingAuthorization} from './authorization.mjs';
|
|
9
|
+
export {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
10
|
+
export type {PublishingActivation} from './activation.mjs';
|
|
11
|
+
export {createPublishingActivation,verifyPublishingActivation} from './activation.mjs';
|
|
12
|
+
export {PublishingSourceError} from './source-error.mjs';
|
|
13
|
+
export type {PublishingSourceProducer,PublishingWorkflowOptions,PublishingSourceOptions,PublishingPublishOptions,PublishingWorkflowResult,PublishingWorkflow} from './workflow.mjs';
|
|
14
|
+
export {createPublishingWorkflow} from './workflow.mjs';
|
|
15
|
+
export type {PublishingCommandOptions,PublishingCommandResult} from './cli.mjs';
|
|
16
|
+
export {runPublishingCommand} from './cli.mjs';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export {prepareSolutionPackage,prepareSolutionPackageBytes,verifySolutionPackage,verifySolutionPackageBytes} from './solution-package.mjs';
|
|
2
|
+
export {openPublishingJournal} from './journal.mjs';
|
|
3
|
+
export {createPublishingSession} from './session.mjs';
|
|
4
|
+
export {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
5
|
+
export {createPublishingActivation,verifyPublishingActivation} from './activation.mjs';
|
|
6
|
+
export {PublishingSourceError} from './source-error.mjs';
|
|
7
|
+
export {createPublishingWorkflow} from './workflow.mjs';
|
|
8
|
+
export {runPublishingCommand} from './cli.mjs';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
+
import type {ArtifactOperationJournal} from '@openge/forge-artifact-publish';
|
|
3
|
+
import type {DurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
4
|
+
export interface PublishingJournalLimits {maximumBytes:number;maximumRecords:number;maximumRecordBytes:number;maximumBlobs:number;maximumBlobBytes:number;minimumFreeBytes:number}
|
|
5
|
+
export interface PublishingJournalRecord {revision:number;payload:JsonValue}
|
|
6
|
+
export interface PublishingJournal {
|
|
7
|
+
load(key:string,options?:{signal?:AbortSignal}):Promise<PublishingJournalRecord|undefined>;
|
|
8
|
+
readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>;
|
|
9
|
+
compareAndSet(input:{key:string;expectedRevision:number;payload:JsonValue;blobs?:readonly {sha256:string;bytes:Uint8Array}[]},options?:{signal?:AbortSignal}):Promise<'stored'|'conflict'>;
|
|
10
|
+
operationJournal():ArtifactOperationJournal;
|
|
11
|
+
close():void;
|
|
12
|
+
}
|
|
13
|
+
export function openPublishingJournal(input:{root:string;directory:string;filesystem:DurableArtifactFilesystem;limits:PublishingJournalLimits;signal?:AbortSignal}):Promise<PublishingJournal>;
|