@xlinklight/publishing 3.3.0 → 3.4.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/README.md +23 -3
- package/dist/src/acceptance-delivery-binding.d.ts +20 -0
- package/dist/src/acceptance-delivery-binding.js +59 -0
- package/dist/src/acceptance.d.ts +49 -0
- package/dist/src/acceptance.js +79 -0
- package/dist/src/client.d.ts +71 -0
- package/dist/src/client.js +146 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.js +3 -0
- package/dist/src/node/acceptance-delivery.d.ts +34 -0
- package/dist/src/node/acceptance-delivery.js +88 -0
- package/dist/src/node/activation.d.ts +5 -0
- package/dist/src/node/activation.js +3 -0
- package/dist/src/node/authorization.d.ts +31 -0
- package/dist/src/node/authorization.js +76 -0
- package/dist/src/node/cli.d.ts +2 -0
- package/dist/src/node/cli.js +22 -0
- package/dist/src/node/index.d.ts +20 -0
- package/dist/src/node/index.js +11 -0
- package/dist/src/node/journal-directory.d.ts +2 -0
- package/dist/src/node/journal-directory.js +121 -0
- package/dist/src/node/journal.d.ts +49 -0
- package/dist/src/node/journal.js +280 -0
- package/dist/src/node/local-json-file.d.ts +3 -0
- package/dist/src/node/local-json-file.js +49 -0
- package/dist/src/node/publishing-command.d.ts +46 -0
- package/dist/src/node/publishing-command.js +268 -0
- package/dist/src/node/session.d.ts +95 -0
- package/dist/src/node/session.js +223 -0
- package/dist/src/node/solution-package.d.ts +55 -0
- package/dist/src/node/solution-package.js +217 -0
- package/dist/src/node/source-error.d.ts +10 -0
- package/dist/src/node/source-error.js +15 -0
- package/dist/src/node/source-producer.d.ts +5 -0
- package/dist/src/node/source-producer.js +145 -0
- package/dist/src/node/terminal-network.d.ts +23 -0
- package/dist/src/node/terminal-network.js +122 -0
- package/dist/src/node/workflow.d.ts +74 -0
- package/dist/src/node/workflow.js +467 -0
- package/dist/src/package.d.ts +38 -0
- package/dist/src/package.js +74 -0
- package/dist/src/protocol.d.ts +83 -0
- package/dist/src/protocol.js +105 -0
- package/dist/src/shared/activation-types.d.ts +37 -0
- package/dist/src/shared/activation-types.js +1 -0
- package/dist/src/shared/activation.d.ts +17 -0
- package/dist/src/shared/activation.js +111 -0
- package/dist/src/shared/records.d.ts +10 -0
- package/dist/src/shared/records.js +26 -0
- package/dist/src/shared/release-version.d.ts +4 -0
- package/dist/src/shared/release-version.js +15 -0
- package/dist/src/worker/activation.d.ts +12 -0
- package/dist/src/worker/activation.js +11 -0
- package/dist/src/worker/durable-retention.d.ts +9 -0
- package/dist/src/worker/durable-retention.js +96 -0
- package/dist/src/worker/index.d.ts +12 -0
- package/dist/src/worker/index.js +7 -0
- package/dist/src/worker/journal.d.ts +129 -0
- package/dist/src/worker/journal.js +328 -0
- package/dist/src/worker/package.d.ts +60 -0
- package/dist/src/worker/package.js +116 -0
- package/dist/src/worker/release-retention.d.ts +34 -0
- package/dist/src/worker/release-retention.js +27 -0
- package/dist/src/worker/release.d.ts +22 -0
- package/dist/src/worker/release.js +59 -0
- package/dist/src/worker/runtime.d.ts +47 -0
- package/dist/src/worker/runtime.js +98 -0
- package/dist/src/worker/service.d.ts +128 -0
- package/dist/src/worker/service.js +520 -0
- package/package.json +23 -14
- package/src/acceptance-delivery-binding.mjs +0 -49
- package/src/acceptance.d.mts +0 -24
- package/src/acceptance.mjs +0 -67
- package/src/client.d.mts +0 -16
- package/src/client.mjs +0 -74
- package/src/index.d.mts +0 -6
- package/src/index.mjs +0 -3
- package/src/node/acceptance-delivery.d.mts +0 -11
- package/src/node/acceptance-delivery.mjs +0 -70
- package/src/node/activation.d.mts +0 -8
- package/src/node/activation.mjs +0 -3
- package/src/node/authorization.d.mts +0 -8
- package/src/node/authorization.mjs +0 -49
- package/src/node/cli.mjs +0 -12
- package/src/node/index.d.mts +0 -17
- package/src/node/index.mjs +0 -9
- package/src/node/journal.d.mts +0 -13
- package/src/node/journal.mjs +0 -135
- package/src/node/publishing-command.d.mts +0 -20
- package/src/node/publishing-command.mjs +0 -104
- package/src/node/session.d.mts +0 -25
- package/src/node/session.mjs +0 -134
- package/src/node/solution-package.d.mts +0 -15
- package/src/node/solution-package.mjs +0 -113
- package/src/node/source-error.d.mts +0 -5
- package/src/node/source-error.mjs +0 -9
- package/src/node/source-producer.mjs +0 -103
- package/src/node/workflow.d.mts +0 -37
- package/src/node/workflow.mjs +0 -320
- package/src/package.d.mts +0 -11
- package/src/package.mjs +0 -36
- package/src/protocol.d.mts +0 -27
- package/src/protocol.mjs +0 -50
- package/src/shared/activation.d.mts +0 -5
- package/src/shared/activation.mjs +0 -64
- package/src/worker/activation.d.mts +0 -7
- package/src/worker/activation.mjs +0 -4
- package/src/worker/index.d.mts +0 -6
- package/src/worker/index.mjs +0 -6
- package/src/worker/journal.d.mts +0 -21
- package/src/worker/journal.mjs +0 -151
- package/src/worker/package.d.mts +0 -16
- package/src/worker/package.mjs +0 -32
- package/src/worker/release.d.mts +0 -7
- package/src/worker/release.mjs +0 -21
- package/src/worker/runtime.d.mts +0 -4
- package/src/worker/runtime.mjs +0 -23
- package/src/worker/service.d.mts +0 -41
- package/src/worker/service.mjs +0 -251
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import {createPublicKey, verify} from 'node:crypto';
|
|
2
|
-
import {protocolRecord, publishingDigest, publishingError, publishingIdentifier} from './protocol.mjs';
|
|
3
|
-
|
|
4
|
-
export const maximumAcceptanceArchiveBytes = 50 * 1024 ** 2;
|
|
5
|
-
export const deliveryBindingFields = Object.freeze([
|
|
6
|
-
'projectId', 'solutionId', 'version', 'origin', 'keyId', 'manifestSha256', 'archiveSha256', 'artifactSha256', 'byteLength',
|
|
7
|
-
]);
|
|
8
|
-
const fail = code => publishingError('ACCEPTANCE_' + code);
|
|
9
|
-
const versionPattern = /^\d{1,8}\.\d{1,8}\.\d{1,8}$/;
|
|
10
|
-
|
|
11
|
-
export function validateDeliveryOrigin(value) {
|
|
12
|
-
const url = typeof value === 'string' ? URL.parse(value) : null;
|
|
13
|
-
if (url?.protocol !== 'https:' || url.origin !== value) throw fail('ORIGIN_INVALID');
|
|
14
|
-
return value;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function deliveryBindingBytes(value) {
|
|
18
|
-
if (!protocolRecord(value,deliveryBindingFields) || ![value.projectId,value.solutionId,value.keyId].every(publishingIdentifier) ||
|
|
19
|
-
!versionPattern.test(value.version) || ![value.manifestSha256,value.archiveSha256,value.artifactSha256].every(publishingDigest) ||
|
|
20
|
-
!Number.isSafeInteger(value.byteLength) || value.byteLength < 1 || value.byteLength > maximumAcceptanceArchiveBytes) throw fail('BINDING_INVALID');
|
|
21
|
-
validateDeliveryOrigin(value.origin);
|
|
22
|
-
return Buffer.from(JSON.stringify(['link-light/owner-acceptance-installation/v1', ...deliveryBindingFields.map(key => value[key])]));
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function verifyAcceptanceDelivery(value, signature, publicKey) {
|
|
26
|
-
if (typeof signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(signature)) throw fail('SIGNATURE_INVALID');
|
|
27
|
-
const key = typeof publicKey === 'string' ? createPublicKey(publicKey) : publicKey;
|
|
28
|
-
if (key?.asymmetricKeyType !== 'ed25519' || !verify(null,deliveryBindingBytes(value),key,Buffer.from(signature,'base64url'))) throw fail('SIGNATURE_INVALID');
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export async function readDeliveryBody(message, limit) {
|
|
32
|
-
const length = message.headers.get('content-length');
|
|
33
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > maximumAcceptanceArchiveBytes || !message.body ||
|
|
34
|
-
length !== null && (!/^\d+$/.test(length) || Number(length) > limit)) throw fail('BODY_LIMIT');
|
|
35
|
-
const reader = message.body.getReader(), chunks = [];
|
|
36
|
-
let total = 0;
|
|
37
|
-
try {
|
|
38
|
-
for (;;) {
|
|
39
|
-
const {done,value} = await reader.read();
|
|
40
|
-
if (done) break;
|
|
41
|
-
total += value.byteLength;
|
|
42
|
-
if (total > limit) throw fail('BODY_LIMIT');
|
|
43
|
-
chunks.push(value);
|
|
44
|
-
}
|
|
45
|
-
} finally {
|
|
46
|
-
try { await reader.cancel(); } finally { reader.releaseLock(); }
|
|
47
|
-
}
|
|
48
|
-
return Buffer.concat(chunks,total);
|
|
49
|
-
}
|
package/src/acceptance.d.mts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import type {KeyObject} from 'node:crypto';
|
|
2
|
-
import type {SolutionReleaseManifest} from '@xlinklight/contracts';
|
|
3
|
-
export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from './node/acceptance-delivery.mjs';
|
|
4
|
-
export type {AcceptanceDeliveryBinding} from './node/acceptance-delivery.mjs';
|
|
5
|
-
|
|
6
|
-
export interface AcceptanceIdentity {
|
|
7
|
-
projectId:string;requestId:string;intentSha256:string;policyRevision:number;
|
|
8
|
-
releaseDigest:string;acceptanceArtifactSha256:string;generation:number;
|
|
9
|
-
}
|
|
10
|
-
export interface AcceptanceJob extends AcceptanceIdentity {
|
|
11
|
-
schemaVersion:1;jobId:string;manifest:Readonly<SolutionReleaseManifest>;
|
|
12
|
-
}
|
|
13
|
-
export interface AcceptanceReceipt extends AcceptanceIdentity {
|
|
14
|
-
schemaVersion:1;jobId:string;status:'PASS';
|
|
15
|
-
proof:{syntheticInstancesCreated:number;syntheticInstancesDisabled:number;closure:{status:'closed';activeRequests:0}};
|
|
16
|
-
}
|
|
17
|
-
export interface AcceptanceEnvelope<Payload> {payload:Payload;keyId:string;signature:string}
|
|
18
|
-
export interface AcceptanceSigner {keyId:string;privateKey:string|KeyObject}
|
|
19
|
-
export interface AcceptanceVerifier {keyId:string;publicKey:string|KeyObject}
|
|
20
|
-
export function acceptanceJobId(identity:AcceptanceIdentity):string;
|
|
21
|
-
export function signAcceptanceJob(job:AcceptanceJob,options:AcceptanceSigner):AcceptanceEnvelope<AcceptanceJob>;
|
|
22
|
-
export function verifyAcceptanceJob(envelope:unknown,options:AcceptanceVerifier):AcceptanceJob;
|
|
23
|
-
export function signAcceptanceReceipt(receipt:AcceptanceReceipt,options:AcceptanceSigner):AcceptanceEnvelope<AcceptanceReceipt>;
|
|
24
|
-
export function verifyAcceptanceReceipt(envelope:unknown,options:AcceptanceVerifier):AcceptanceReceipt;
|
package/src/acceptance.mjs
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
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
|
-
export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from './acceptance-delivery-binding.mjs';
|
|
5
|
-
|
|
6
|
-
const positive=value=>Number.isSafeInteger(value)&&value>0;
|
|
7
|
-
const identityKeys=['projectId','requestId','intentSha256','policyRevision','releaseDigest','acceptanceArtifactSha256','generation'];
|
|
8
|
-
const bindingKeys=['schemaVersion','jobId',...identityKeys];
|
|
9
|
-
const invalid=part=>publishingError('ACCEPTANCE_'+part+'_INVALID');
|
|
10
|
-
|
|
11
|
-
export function acceptanceJobId(identity){
|
|
12
|
-
if(!identity||!publishingIdentifier(identity.projectId)||!publishingRequestId(identity.requestId)
|
|
13
|
-
||!publishingDigest(identity.intentSha256)||!positive(identity.policyRevision)
|
|
14
|
-
||!/^sha256:[a-f0-9]{64}$/.test(identity.releaseDigest??'')||!publishingDigest(identity.acceptanceArtifactSha256)
|
|
15
|
-
||!positive(identity.generation))throw invalid('JOB');
|
|
16
|
-
const binding=Object.fromEntries(identityKeys.map(key=>[key,identity[key]]));
|
|
17
|
-
return createHash('sha256').update('link-light/acceptance-job-id/v1\n').update(canonicalMetadata(binding)).digest('hex');
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function checkBinding(payload,kind){
|
|
21
|
-
try{return payload.schemaVersion===1&&payload.jobId===acceptanceJobId(payload);}
|
|
22
|
-
catch{throw invalid(kind);}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function jobPayload(payload){
|
|
26
|
-
if(!protocolRecord(payload,[...bindingKeys,'manifest'])||!checkBinding(payload,'JOB')
|
|
27
|
-
||payload.manifest?.releaseDigest!==payload.releaseDigest||!publishingIdentifier(payload.manifest.solutionId)
|
|
28
|
-
||!/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(payload.manifest.version??''))throw invalid('JOB');
|
|
29
|
-
return payload;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function receiptPayload(payload){
|
|
33
|
-
if(!protocolRecord(payload,[...bindingKeys,'status','proof'])||!checkBinding(payload,'RECEIPT')||payload.status!=='PASS'
|
|
34
|
-
||!protocolRecord(payload.proof,['syntheticInstancesCreated','syntheticInstancesDisabled','closure']))throw invalid('RECEIPT');
|
|
35
|
-
const {syntheticInstancesCreated,syntheticInstancesDisabled,closure}=payload.proof;
|
|
36
|
-
if(!positive(syntheticInstancesCreated)||syntheticInstancesCreated<2||syntheticInstancesCreated>1024
|
|
37
|
-
||syntheticInstancesCreated!==syntheticInstancesDisabled||!protocolRecord(closure,['status','activeRequests'])
|
|
38
|
-
||closure.status!=='closed'||closure.activeRequests!==0)throw invalid('RECEIPT');
|
|
39
|
-
return payload;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function message(kind,payload){
|
|
43
|
-
const canonical=canonicalMetadata(payload);
|
|
44
|
-
if(Buffer.byteLength(canonical)>65536)throw invalid(kind);
|
|
45
|
-
return Buffer.from('link-light/acceptance-'+kind.toLowerCase()+'/v1\n'+canonical);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function signEnvelope(payload,kind,{keyId,privateKey}){
|
|
49
|
-
const key=typeof privateKey==='string'?createPrivateKey(privateKey):privateKey;
|
|
50
|
-
if(!publishingIdentifier(keyId)||key?.type!=='private'||key.asymmetricKeyType!=='ed25519')throw invalid('SIGNATURE');
|
|
51
|
-
return {payload:structuredClone(payload),keyId,signature:sign(null,message(kind,payload),key).toString('base64url')};
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function verifyEnvelope(envelope,kind,parse,{keyId,publicKey}){
|
|
55
|
-
if(!protocolRecord(envelope,['payload','keyId','signature'])||!publishingIdentifier(keyId)||envelope.keyId!==keyId
|
|
56
|
-
||typeof envelope.signature!=='string'||!/^[A-Za-z0-9_-]{86}$/.test(envelope.signature))throw invalid('SIGNATURE');
|
|
57
|
-
const payload=parse(envelope.payload),bytes=Buffer.from(envelope.signature,'base64url');
|
|
58
|
-
const key=typeof publicKey==='string'?createPublicKey(publicKey):publicKey;
|
|
59
|
-
if(key?.type!=='public'||key.asymmetricKeyType!=='ed25519'||bytes.toString('base64url')!==envelope.signature
|
|
60
|
-
||!verify(null,message(kind,payload),key,bytes))throw invalid('SIGNATURE');
|
|
61
|
-
return structuredClone(payload);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export const signAcceptanceJob=(job,options)=>signEnvelope(jobPayload(job),'JOB',options);
|
|
65
|
-
export const verifyAcceptanceJob=(envelope,options)=>verifyEnvelope(envelope,'JOB',jobPayload,options);
|
|
66
|
-
export const signAcceptanceReceipt=(receipt,options)=>signEnvelope(receiptPayload(receipt),'RECEIPT',options);
|
|
67
|
-
export const verifyAcceptanceReceipt=(envelope,options)=>verifyEnvelope(envelope,'RECEIPT',receiptPayload,options);
|
package/src/client.d.mts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
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
|
-
getLatestRelease(input?:{signal?:AbortSignal}):Promise<{intent:PublishingIntent;status:PublishingStatus}|undefined>;
|
|
7
|
-
createRequest(input:{intent:PublishingIntent;manifestBytes:Uint8Array;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
8
|
-
getStatus(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
9
|
-
resumeRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
10
|
-
recoverRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
11
|
-
queueRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
12
|
-
abandonRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
13
|
-
uploadChunk(input:{requestId:string;file:{sha256:string;byteLength:number};offset:number;bytes:Uint8Array;signal?:AbortSignal}):Promise<{schemaVersion:1;sha256:string;receivedBytes:number}>;
|
|
14
|
-
}
|
|
15
|
-
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}
|
|
16
|
-
export function createPublishingClient(options:PublishingClientOptions):PublishingClient;
|
package/src/client.mjs
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
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 getLatestRelease({signal}={}){
|
|
49
|
-
const value=await send('GET','/v1/project/release',undefined,signal);
|
|
50
|
-
if(!protocolRecord(value,['schemaVersion','intent'])||value.schemaVersion!==1)throw publishingError('PROJECT_BINDING_INVALID');
|
|
51
|
-
if(value.intent===null)return undefined;
|
|
52
|
-
const intent=checkedIntent(value.intent);
|
|
53
|
-
try{return {intent,status:await boundStatus(await send('GET','/v1/requests/'+intent.requestId,undefined,signal),intent)};}
|
|
54
|
-
catch(error){error.requestId=intent.requestId;throw error;}
|
|
55
|
-
},
|
|
56
|
-
async createRequest({intent:input,manifestBytes,signal}){
|
|
57
|
-
const intent=checkedIntent(input);
|
|
58
|
-
if(!(manifestBytes instanceof Uint8Array)||manifestBytes.byteLength>1048576)throw publishingError('MANIFEST_INVALID');
|
|
59
|
-
let prepared;try{prepared=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(manifestBytes)));}catch{throw publishingError('MANIFEST_INVALID');}
|
|
60
|
-
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');
|
|
61
|
-
return boundStatus(await send('POST','/v1/requests',JSON.stringify({intent,manifest:prepared.manifest}),signal),intent);
|
|
62
|
-
},
|
|
63
|
-
async getStatus({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('GET','/v1/requests/'+intent.requestId,undefined,signal),intent);},
|
|
64
|
-
async resumeRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/resume',JSON.stringify({intent}),signal),intent);},
|
|
65
|
-
async recoverRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/recover',JSON.stringify({intent}),signal),intent);},
|
|
66
|
-
async queueRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/commit',JSON.stringify({intent}),signal),intent);},
|
|
67
|
-
async abandonRequest({intent:input,signal}){const intent=checkedIntent(input);return boundStatus(await send('POST','/v1/requests/'+intent.requestId+'/abandon','{}',signal),intent);},
|
|
68
|
-
async uploadChunk({requestId,file,offset,bytes,signal}){
|
|
69
|
-
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');
|
|
70
|
-
const snapshot=new Uint8Array(bytes),value=await send('PUT','/v1/requests/'+requestId+'/files/'+file.sha256+'?offset='+offset,snapshot,signal,'application/octet-stream');
|
|
71
|
-
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;
|
|
72
|
-
},
|
|
73
|
-
});
|
|
74
|
-
}
|
package/src/index.d.mts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
export {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from './package.mjs';
|
|
2
|
-
export {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,parsePublishingStatus,publishingIntentBytes} from './protocol.mjs';
|
|
3
|
-
export {createPublishingClient} from './client.mjs';
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export interface AcceptanceDeliveryCredential {origin:string;keyId:string;privateKey:string}
|
|
2
|
-
export interface AcceptanceArchive {bytes:Uint8Array;artifactSha256:string}
|
|
3
|
-
export interface AcceptanceArchiveIdentity {archiveSha256:string;artifactSha256:string;byteLength:number}
|
|
4
|
-
export interface AcceptanceDeliveryBinding extends AcceptanceArchiveIdentity {
|
|
5
|
-
projectId:string;solutionId:string;version:string;origin:string;keyId:string;manifestSha256:string;
|
|
6
|
-
}
|
|
7
|
-
export const maximumAcceptanceArchiveBytes:number;
|
|
8
|
-
export function signAcceptanceDelivery(binding:AcceptanceDeliveryBinding,privateKey:string|import('node:crypto').KeyObject):string;
|
|
9
|
-
export function deliverAcceptanceArchive(input:{intent:import('../protocol.mjs').PublishingIntent;archive:AcceptanceArchiveIdentity;bytes:Uint8Array;credential:AcceptanceDeliveryCredential;request?:typeof fetch;signal?:AbortSignal}):Promise<void>;
|
|
10
|
-
export function verifyAcceptanceDelivery(binding:AcceptanceDeliveryBinding,signature:string,publicKey:string|import('node:crypto').KeyObject):void;
|
|
11
|
-
export function readDeliveryBody(message:Request|Response,limit:number):Promise<Buffer>;
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import {createHash, createPrivateKey, createPublicKey, sign} from 'node:crypto';
|
|
2
|
-
import {protocolRecord, publishingError, publishingIdentifier} from '../protocol.mjs';
|
|
3
|
-
import {deliveryBindingBytes, deliveryBindingFields, readDeliveryBody, validateDeliveryOrigin} from '../acceptance-delivery-binding.mjs';
|
|
4
|
-
export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from '../acceptance-delivery-binding.mjs';
|
|
5
|
-
|
|
6
|
-
const fail = code => publishingError('ACCEPTANCE_' + code);
|
|
7
|
-
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
8
|
-
|
|
9
|
-
export function parseAcceptanceDeliveryCredential(value) {
|
|
10
|
-
if (!protocolRecord(value,['origin','keyId','privateKey']) || !publishingIdentifier(value.keyId) ||
|
|
11
|
-
typeof value.privateKey !== 'string' || value.privateKey.length > 4096) throw fail('CREDENTIAL_INVALID');
|
|
12
|
-
validateDeliveryOrigin(value.origin);
|
|
13
|
-
const key = createPrivateKey(value.privateKey);
|
|
14
|
-
if (key.asymmetricKeyType !== 'ed25519') throw fail('CREDENTIAL_INVALID');
|
|
15
|
-
return {origin:value.origin,keyId:value.keyId,privateKey:key.export({type:'pkcs8',format:'pem'}).toString()};
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function acceptanceDeliveryTarget(credential) {
|
|
19
|
-
const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
|
|
20
|
-
return {origin,keyId,publicKeySha256:hash(createPublicKey(privateKey).export({type:'spki',format:'der'}))};
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function signAcceptanceDelivery(value, privateKey) {
|
|
24
|
-
return sign(null,deliveryBindingBytes(value),privateKey).toString('base64url');
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** Only the dedicated owner's HTTPS origin receives this archive. A read after
|
|
28
|
-
* the immutable PUT also reconciles a lost response without repeating a release. */
|
|
29
|
-
function deliveryTarget({intent,archive,credential,request=fetch,signal}) {
|
|
30
|
-
if (!credential) throw fail('CREDENTIAL_REQUIRED');
|
|
31
|
-
const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
|
|
32
|
-
const expected={projectId:intent.projectId,solutionId:intent.package.solutionId,version:intent.package.version,
|
|
33
|
-
origin,keyId,manifestSha256:intent.package.content.manifestSha256,...archive};
|
|
34
|
-
const url=new URL('/v1/acceptance/installations/'+expected.version,origin);
|
|
35
|
-
const timeout=AbortSignal.timeout(30000);
|
|
36
|
-
const options={redirect:'error',signal:signal?AbortSignal.any([signal,timeout]):timeout};
|
|
37
|
-
async function observed(){
|
|
38
|
-
const response=await request(url,{...options,method:'GET',headers:{accept:'application/json'}});
|
|
39
|
-
if(response.status===404){await response.body?.cancel();return false;}
|
|
40
|
-
if(response.status!==200){await response.body?.cancel();throw fail('DELIVERY_UNKNOWN');}
|
|
41
|
-
const receipt=await readDeliveryBody(response,8192);
|
|
42
|
-
let value;try{value=JSON.parse(receipt.toString('utf8'));}catch{throw fail('DELIVERY_UNKNOWN');}
|
|
43
|
-
if (!protocolRecord(value,deliveryBindingFields))throw fail('DELIVERY_UNKNOWN');
|
|
44
|
-
if (!deliveryBindingBytes(value).equals(deliveryBindingBytes(expected))) throw fail('VERSION_CONFLICT');
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
return {observed,expected,privateKey,options,url,request};
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export async function observeAcceptanceDelivery(input) {
|
|
51
|
-
return deliveryTarget(input).observed();
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export async function deliverAcceptanceArchive(input) {
|
|
55
|
-
const {bytes,archive}=input;
|
|
56
|
-
if (!(bytes instanceof Uint8Array) || bytes.byteLength!==archive.byteLength || hash(bytes)!==archive.archiveSha256) throw fail('ARCHIVE_CHANGED');
|
|
57
|
-
const {observed,expected,privateKey,options,url,request}=deliveryTarget(input);
|
|
58
|
-
if(await observed())return;
|
|
59
|
-
const signature=signAcceptanceDelivery(expected,privateKey);
|
|
60
|
-
let rejection;
|
|
61
|
-
try {
|
|
62
|
-
const response=await request(url,{...options,method:'PUT',headers:{'content-type':'application/octet-stream',
|
|
63
|
-
'x-link-light-binding':Buffer.from(JSON.stringify(expected)).toString('base64url'),'x-link-light-signature':signature},body:bytes});
|
|
64
|
-
await response.body?.cancel();
|
|
65
|
-
if(response.status===403)rejection='SIGNATURE_INVALID';
|
|
66
|
-
if(response.status===409)rejection='VERSION_CONFLICT';
|
|
67
|
-
if([400,413,415,422].includes(response.status))rejection='DELIVERY_REJECTED';
|
|
68
|
-
} catch(error){if(error?.code?.startsWith('PUBLISHING_ACCEPTANCE_'))throw error;}
|
|
69
|
-
if(!await observed())throw fail(rejection??'DELIVERY_UNKNOWN');
|
|
70
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
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}>;
|
package/src/node/activation.mjs
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
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;acceptanceDelivery?:import('./acceptance-delivery.mjs').AcceptanceDeliveryCredential}
|
|
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}>;
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import {createHash,createPublicKey} from 'node:crypto';
|
|
2
|
-
import {parseAcceptanceDeliveryCredential} from './acceptance-delivery.mjs';
|
|
3
|
-
import {createPublishingClient} from '../client.mjs';
|
|
4
|
-
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
5
|
-
|
|
6
|
-
const key='client-authorization',hash=value=>createHash('sha256').update(value).digest('hex'),fail=code=>publishingError('CREDENTIAL_'+code);
|
|
7
|
-
const credentialValid=value=>typeof value==='string'&&/^[A-Za-z0-9_-]{32,4096}$/.test(value);
|
|
8
|
-
function saved(record,allowLoopback){
|
|
9
|
-
if(!record)return undefined;const value=record.payload;
|
|
10
|
-
if(!protocolRecord(value,['schemaVersion','configuration','configurationSha256','credential','credentialSha256'],['acceptanceDelivery'])||value.schemaVersion!==1||!credentialValid(value.credential))throw fail('INVALID');
|
|
11
|
-
let configuration;try{configuration=parsePublishingConfiguration(value.configuration,{allowLoopback});}catch{throw fail('INVALID');}
|
|
12
|
-
if(hash(JSON.stringify(configuration))!==value.configurationSha256||hash(value.credential)!==value.credentialSha256)throw fail('INVALID');
|
|
13
|
-
return {configuration,credential:value.credential,...(value.acceptanceDelivery?{acceptanceDelivery:parseAcceptanceDeliveryCredential(value.acceptanceDelivery)}:{})};
|
|
14
|
-
}
|
|
15
|
-
function store(journal){if(!journal||typeof journal.load!=='function'||typeof journal.compareAndSet!=='function')throw fail('STORE_INVALID');return journal;}
|
|
16
|
-
|
|
17
|
-
/** The caller supplies private persistent storage, including access controls and
|
|
18
|
-
* backup policy. No provider credential or process/global setting is stored. */
|
|
19
|
-
export async function loadPublishingAuthorization({journal,allowLoopback=false,signal}){
|
|
20
|
-
signal?.throwIfAborted();return saved(await store(journal).load(key,{signal}),allowLoopback);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** Validate installed trust and current project access before atomic install.
|
|
24
|
-
* A changed service/publisher trust never adopts an existing recovery journal. */
|
|
25
|
-
export async function installPublishingAuthorization({journal,configuration:input,credential,acceptanceDelivery,replaceCredential=false,allowLoopback=false,request,clientLimits,signal}){
|
|
26
|
-
store(journal);signal?.throwIfAborted();const configuration=parsePublishingConfiguration(input,{allowLoopback});
|
|
27
|
-
if(!credentialValid(credential)||typeof replaceCredential!=='boolean')throw fail('INVALID');
|
|
28
|
-
const previous=await journal.load(key,{signal}),current=saved(previous,allowLoopback),configurationSha256=hash(JSON.stringify(configuration)),credentialSha256=hash(credential);
|
|
29
|
-
if(current&&JSON.stringify(current.configuration)!==JSON.stringify(configuration))throw fail('TRUST_CHANGED');
|
|
30
|
-
if(current&¤t.credential!==credential&&!replaceCredential)throw fail('REPLACEMENT_REQUIRED');
|
|
31
|
-
const delivery=acceptanceDelivery===undefined?current?.acceptanceDelivery:parseAcceptanceDeliveryCredential(acceptanceDelivery);
|
|
32
|
-
if(delivery){
|
|
33
|
-
const publicBytes=key=>createPublicKey(key).export({type:'spki',format:'der'});
|
|
34
|
-
if(configuration.publisher.keys.some(key=>publicBytes(key.publicKey).equals(publicBytes(delivery.privateKey))))throw fail('TRUST_CHANGED');
|
|
35
|
-
if(current?.acceptanceDelivery&&(delivery.origin!==current.acceptanceDelivery.origin||delivery.keyId!==current.acceptanceDelivery.keyId||
|
|
36
|
-
!publicBytes(delivery.privateKey).equals(publicBytes(current.acceptanceDelivery.privateKey))))throw fail('TRUST_CHANGED');
|
|
37
|
-
if(current?.acceptanceDelivery&&JSON.stringify(current.acceptanceDelivery)!==JSON.stringify(delivery)&&!replaceCredential)throw fail('REPLACEMENT_REQUIRED');
|
|
38
|
-
}
|
|
39
|
-
const client=createPublishingClient({configuration,credential,allowLoopback,...(request?{request}:{}),...(clientLimits?{limits:clientLimits}:{})}),project=await client.getProject({signal});
|
|
40
|
-
if(current?.credential===credential&&JSON.stringify(current.acceptanceDelivery)===JSON.stringify(delivery)){
|
|
41
|
-
const latest=await journal.load(key,{signal});if(latest?.revision!==previous.revision)throw fail('CONFLICT');saved(latest,allowLoopback);
|
|
42
|
-
return {status:'VERIFIED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
|
43
|
-
}
|
|
44
|
-
let result;
|
|
45
|
-
try{result=await journal.compareAndSet({key,expectedRevision:previous?.revision??0,payload:{schemaVersion:1,configuration,configurationSha256,credential,credentialSha256,...(delivery?{acceptanceDelivery:delivery}:{})}},{signal});}
|
|
46
|
-
catch{throw fail('PERSISTENCE_UNKNOWN');}
|
|
47
|
-
if(result==='conflict')throw fail('CONFLICT');if(result!=='stored')throw fail('PERSISTENCE_UNKNOWN');
|
|
48
|
-
return {status:previous?'REPLACED':'CONFIGURED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
|
49
|
-
}
|
package/src/node/cli.mjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {existsSync,realpathSync} from 'node:fs';
|
|
3
|
-
import {fileURLToPath} from 'node:url';
|
|
4
|
-
import {runPublishingCommand} from './publishing-command.mjs';
|
|
5
|
-
|
|
6
|
-
async function main(){
|
|
7
|
-
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
8
|
-
try{const result=await runPublishingCommand(process.argv.slice(2),{signal:controller.signal});process.stdout.write(JSON.stringify(result.output)+'\n');process.exitCode=result.exitCode;}
|
|
9
|
-
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
package/src/node/index.d.mts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
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 './publishing-command.mjs';
|
|
16
|
-
export {runPublishingCommand} from './publishing-command.mjs';
|
|
17
|
-
export * from './acceptance-delivery.mjs';
|
package/src/node/index.mjs
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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 {deliverAcceptanceArchive,signAcceptanceDelivery,maximumAcceptanceArchiveBytes,readDeliveryBody,verifyAcceptanceDelivery} from './acceptance-delivery.mjs';
|
|
9
|
-
export {runPublishingCommand} from './publishing-command.mjs';
|
package/src/node/journal.d.mts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
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>;
|
package/src/node/journal.mjs
DELETED
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
-
import {isDeepStrictEqual} from 'node:util';
|
|
5
|
-
import {DatabaseSync} from 'node:sqlite';
|
|
6
|
-
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
7
|
-
import {GeneratedArtifactError,generatedArtifactErrorCodes} from '@openge/forge-generated-artifacts';
|
|
8
|
-
import {publishingError,protocolRecord,publishingRequestId,publishingDigest} from '../protocol.mjs';
|
|
9
|
-
|
|
10
|
-
const fail=code=>publishingError('JOURNAL_'+code);
|
|
11
|
-
const keyValid=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
|
|
12
|
-
const recordBytes=(key,revision,payload)=>Buffer.byteLength('{"key":'+JSON.stringify(key)+',"revision":'+revision+',"payload":'+payload+'}');
|
|
13
|
-
function storageFailure(error){
|
|
14
|
-
if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_'))throw error;
|
|
15
|
-
throw fail([5,6].includes(error?.errcode)?'BUSY':'STORAGE_UNKNOWN');
|
|
16
|
-
}
|
|
17
|
-
function checkedLimits(value){
|
|
18
|
-
if(!protocolRecord(value,['maximumBytes','maximumRecords','maximumRecordBytes','maximumBlobs','maximumBlobBytes','minimumFreeBytes'])||!Object.values(value).every(Number.isSafeInteger)||value.maximumBytes<65536||value.maximumBytes>1073741824||value.maximumRecords<1||value.maximumRecords>4096||value.maximumRecordBytes<1||value.maximumRecordBytes>1048576||value.maximumBlobs<1||value.maximumBlobs>32768||value.maximumBlobBytes<1||value.maximumBlobBytes>134217728||value.minimumFreeBytes<0)throw fail('LIMIT_INVALID');return {...value};
|
|
19
|
-
}
|
|
20
|
-
const occupied=error=>error instanceof GeneratedArtifactError&&error.code===generatedArtifactErrorCodes.destinationOccupied&&error.details.cleanupFailed!==true;
|
|
21
|
-
async function capacity(root,limits){
|
|
22
|
-
const info=await fs.statfs(root,{bigint:true});
|
|
23
|
-
if(info.bavail*info.bsize<BigInt(limits.minimumFreeBytes)+BigInt(limits.maximumBytes)*2n+65536n)throw fail('CAPACITY_REQUIRED');
|
|
24
|
-
}
|
|
25
|
-
async function markerBytes(file){
|
|
26
|
-
const before=await fs.lstat(file,{bigint:true});
|
|
27
|
-
if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||before.size>4096n||await fs.realpath(file)!==file)throw fail('OWNERSHIP_INVALID');
|
|
28
|
-
const body=await fs.readFile(file),after=await fs.lstat(file,{bigint:true});
|
|
29
|
-
if(body.byteLength>4096||['dev','ino','size','mtimeNs','ctimeNs'].some(key=>before[key]!==after[key]))throw fail('OWNERSHIP_INVALID');
|
|
30
|
-
try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(body));}catch{throw fail('OWNERSHIP_INVALID');}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
|
|
34
|
-
export async function openPublishingJournal({root,directory,filesystem,limits,signal}){
|
|
35
|
-
signal?.throwIfAborted();limits=checkedLimits(limits);
|
|
36
|
-
if(typeof root!=='string'||!path.isAbsolute(root)||!filesystem||typeof filesystem.ensureDirectory!=='function'||typeof filesystem.publishBytes!=='function')throw fail('INPUT_INVALID');
|
|
37
|
-
root=path.resolve(root);const rootInfo=await fs.lstat(root,{bigint:true});
|
|
38
|
-
if(!rootInfo.isDirectory()||rootInfo.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('BOUNDARY');
|
|
39
|
-
try{directory=validatePortableRelativePath(directory);}catch{throw fail('BOUNDARY');}
|
|
40
|
-
await capacity(root,limits);signal?.throwIfAborted();
|
|
41
|
-
try{await filesystem.ensureDirectory(root,directory);}catch{throw fail('PERSISTENCE_UNKNOWN');}
|
|
42
|
-
const absolute=path.join(root,...directory.split('/')),markerFile=path.join(absolute,'owner.json'),databaseFile=path.join(absolute,'journal.sqlite');
|
|
43
|
-
const context={schemaVersion:1,root:{dev:String(rootInfo.dev),ino:String(rootInfo.ino)},directory,limits};
|
|
44
|
-
let marker;
|
|
45
|
-
try{marker=await markerBytes(markerFile);}catch(error){
|
|
46
|
-
if(error.code!=='ENOENT')throw error;
|
|
47
|
-
if((await fs.readdir(absolute)).length)throw fail('OCCUPIED');
|
|
48
|
-
const value={...context,ownerId:randomUUID()};
|
|
49
|
-
try{await filesystem.publishBytes(root,directory+'/owner.json',new TextEncoder().encode(JSON.stringify(value)+'\n'),{mode:'exclusive'});}
|
|
50
|
-
catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
|
|
51
|
-
marker=await markerBytes(markerFile);
|
|
52
|
-
}
|
|
53
|
-
if(!protocolRecord(marker,['schemaVersion','root','directory','limits','ownerId'])||!publishingRequestId(marker.ownerId)||!isDeepStrictEqual({...marker,ownerId:undefined},{...context,ownerId:undefined}))throw fail('CONTEXT_CHANGED');
|
|
54
|
-
const allowed=new Set(['owner.json','journal.sqlite','journal.sqlite-journal']);let retained=0;
|
|
55
|
-
for(const name of await fs.readdir(absolute)){
|
|
56
|
-
if(!allowed.has(name))throw fail('OCCUPIED');const file=path.join(absolute,name),info=await fs.lstat(file);
|
|
57
|
-
if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||await fs.realpath(file)!==file)throw fail('BOUNDARY');retained+=info.size;
|
|
58
|
-
}
|
|
59
|
-
if(retained>limits.maximumBytes*2+65536)throw fail('BYTE_LIMIT');
|
|
60
|
-
try{await fs.lstat(databaseFile);}catch(error){
|
|
61
|
-
if(error.code!=='ENOENT')throw error;
|
|
62
|
-
try{await filesystem.publishBytes(root,directory+'/journal.sqlite',new Uint8Array(),{mode:'exclusive'});}
|
|
63
|
-
catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
|
|
64
|
-
}
|
|
65
|
-
signal?.throwIfAborted();let database;
|
|
66
|
-
try{
|
|
67
|
-
database=new DatabaseSync(databaseFile,{enableForeignKeyConstraints:true,enableDoubleQuotedStringLiterals:false,allowExtension:false});
|
|
68
|
-
const tables=database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND substr(name,1,7)<>'sqlite_' ORDER BY name").all().map(row=>row.name);
|
|
69
|
-
if(tables.length===0){
|
|
70
|
-
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;');
|
|
71
|
-
database.exec('BEGIN IMMEDIATE');
|
|
72
|
-
try{
|
|
73
|
-
database.exec('CREATE TABLE journal_metadata (id INTEGER PRIMARY KEY CHECK(id=1),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_records (key TEXT PRIMARY KEY,revision INTEGER NOT NULL CHECK(revision>0),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_blobs (sha256 TEXT PRIMARY KEY,byte_length INTEGER NOT NULL CHECK(byte_length>=0),bytes BLOB NOT NULL) STRICT;');
|
|
74
|
-
database.prepare('INSERT INTO journal_metadata(id,payload) VALUES(1,?)').run(JSON.stringify(marker));database.exec('COMMIT');
|
|
75
|
-
}catch(error){try{database.exec('ROLLBACK');}catch{}throw error;}
|
|
76
|
-
}else if(tables.join(',')!=='journal_blobs,journal_metadata,journal_records')throw fail('OWNERSHIP_INVALID');
|
|
77
|
-
const stored=database.prepare('SELECT payload FROM journal_metadata WHERE id=1').get();
|
|
78
|
-
if(!stored||!isDeepStrictEqual(JSON.parse(stored.payload),marker))throw fail('OWNERSHIP_INVALID');
|
|
79
|
-
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA foreign_keys=ON;PRAGMA trusted_schema=OFF;PRAGMA temp_store=MEMORY;PRAGMA busy_timeout=0;');
|
|
80
|
-
const pages=Math.floor(limits.maximumBytes/4096);database.exec('PRAGMA max_page_count='+pages);
|
|
81
|
-
if(Number(database.prepare('PRAGMA page_size').get().page_size)!==4096||Number(database.prepare('PRAGMA max_page_count').get().max_page_count)!==pages)throw fail('BYTE_LIMIT');
|
|
82
|
-
await filesystem.ensureDirectory(root,directory);signal?.throwIfAborted();
|
|
83
|
-
}catch(error){try{database?.close();}catch{}storageFailure(error);}
|
|
84
|
-
let closed=false;
|
|
85
|
-
const ready=()=>{if(closed)throw fail('CLOSED');};
|
|
86
|
-
const load=async(key,{signal}={})=>{
|
|
87
|
-
ready();signal?.throwIfAborted();if(!keyValid(key))throw fail('KEY_INVALID');
|
|
88
|
-
const row=database.prepare('SELECT revision,payload FROM journal_records WHERE key=?').get(key);
|
|
89
|
-
if(!row)return undefined;
|
|
90
|
-
if(!Number.isSafeInteger(row.revision)||row.revision<1||recordBytes(key,row.revision,row.payload)>limits.maximumRecordBytes)throw fail('RECORD_INVALID');
|
|
91
|
-
let payload;try{payload=JSON.parse(row.payload);}catch{throw fail('RECORD_INVALID');}
|
|
92
|
-
return {revision:row.revision,payload};
|
|
93
|
-
};
|
|
94
|
-
const readBlob=async({sha256,byteLength},{signal}={})=>{
|
|
95
|
-
ready();signal?.throwIfAborted();if(!publishingDigest(sha256)||!Number.isSafeInteger(byteLength)||byteLength<0||byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
|
|
96
|
-
const row=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(sha256);
|
|
97
|
-
if(!row)return undefined;
|
|
98
|
-
if(row.byte_length!==byteLength||row.bytes.byteLength!==byteLength||createHash('sha256').update(row.bytes).digest('hex')!==sha256)throw fail('BLOB_INVALID');return new Uint8Array(row.bytes);
|
|
99
|
-
};
|
|
100
|
-
const compareAndSet=async({key,expectedRevision,payload,blobs=[]},{signal}={})=>{
|
|
101
|
-
ready();signal?.throwIfAborted();if(!keyValid(key)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||expectedRevision===Number.MAX_SAFE_INTEGER)throw fail('RECORD_INVALID');
|
|
102
|
-
let encoded;try{encoded=JSON.stringify(payload);}catch{throw fail('RECORD_INVALID');}
|
|
103
|
-
if(typeof encoded!=='string')throw fail('RECORD_INVALID');if(recordBytes(key,expectedRevision+1,encoded)>limits.maximumRecordBytes)throw fail('BYTE_LIMIT');
|
|
104
|
-
if(!Array.isArray(blobs)||blobs.length>limits.maximumBlobs)throw fail('BLOB_LIMIT');
|
|
105
|
-
const snapshots=[];let blobBytes=0;
|
|
106
|
-
for(const blob of blobs){
|
|
107
|
-
if(!protocolRecord(blob,['sha256','bytes'])||!publishingDigest(blob.sha256)||!(blob.bytes instanceof Uint8Array)||blob.bytes.byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
|
|
108
|
-
blobBytes+=blob.bytes.byteLength;if(blobBytes>limits.maximumBytes)throw fail('BYTE_LIMIT');
|
|
109
|
-
const bytes=new Uint8Array(blob.bytes);if(createHash('sha256').update(bytes).digest('hex')!==blob.sha256)throw fail('BLOB_INVALID');snapshots.push({sha256:blob.sha256,bytes});
|
|
110
|
-
}
|
|
111
|
-
await capacity(root,limits);ready();signal?.throwIfAborted();
|
|
112
|
-
try{database.exec('BEGIN IMMEDIATE');}catch(error){storageFailure(error);}
|
|
113
|
-
try{
|
|
114
|
-
const row=database.prepare('SELECT revision FROM journal_records WHERE key=?').get(key);
|
|
115
|
-
if((row?.revision??0)!==expectedRevision){database.exec('ROLLBACK');return 'conflict';}
|
|
116
|
-
if(!row&&Number(database.prepare('SELECT count(*) AS amount FROM journal_records').get().amount)>=limits.maximumRecords)throw fail('RECORD_LIMIT');
|
|
117
|
-
for(const blob of snapshots){
|
|
118
|
-
const existing=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(blob.sha256);
|
|
119
|
-
if(existing){if(existing.byte_length!==blob.bytes.byteLength||!Buffer.from(existing.bytes).equals(blob.bytes))throw fail('BLOB_INVALID');}
|
|
120
|
-
else database.prepare('INSERT INTO journal_blobs(sha256,byte_length,bytes) VALUES(?,?,?)').run(blob.sha256,blob.bytes.byteLength,blob.bytes);
|
|
121
|
-
}
|
|
122
|
-
if(Number(database.prepare('SELECT count(*) AS amount FROM journal_blobs').get().amount)>limits.maximumBlobs)throw fail('BLOB_LIMIT');
|
|
123
|
-
database.prepare('INSERT INTO journal_records(key,revision,payload) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(key,expectedRevision+1,encoded);
|
|
124
|
-
database.exec('COMMIT');return 'stored';
|
|
125
|
-
}catch(error){try{database.exec('ROLLBACK');}catch{}storageFailure(error);}
|
|
126
|
-
};
|
|
127
|
-
return Object.freeze({
|
|
128
|
-
load,readBlob,compareAndSet,
|
|
129
|
-
operationJournal(){return {
|
|
130
|
-
async load(requestId,context){if(!keyValid(requestId))throw fail('KEY_INVALID');const record=await load('operation:'+requestId,context);if(record&&record.payload?.revision!==record.revision)throw fail('RECORD_INVALID');return record?.payload;},
|
|
131
|
-
async compareAndSet({expectedRevision,next},context){if(!next?.binding||!keyValid(next.binding.requestId)||next.revision!==expectedRevision+1)throw fail('RECORD_INVALID');return compareAndSet({key:'operation:'+next.binding.requestId,expectedRevision,payload:next},context);},
|
|
132
|
-
};},
|
|
133
|
-
close(){if(!closed){database.close();closed=true;}},
|
|
134
|
-
});
|
|
135
|
-
}
|