@xlinklight/publishing 3.2.0 → 3.3.1
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 +1 -1
- package/dist/src/acceptance-delivery-binding.js +59 -0
- package/dist/src/acceptance.js +79 -0
- package/dist/src/client.js +146 -0
- package/dist/src/index.js +3 -0
- package/dist/src/node/acceptance-delivery.js +88 -0
- package/dist/src/node/activation.js +3 -0
- package/dist/src/node/authorization.js +76 -0
- package/dist/src/node/cli.js +20 -0
- package/dist/src/node/index.js +9 -0
- package/dist/src/node/journal.js +282 -0
- package/dist/src/node/publishing-command.js +220 -0
- package/dist/src/node/session.js +223 -0
- package/dist/src/node/solution-package.js +217 -0
- package/dist/src/node/source-error.js +15 -0
- package/dist/src/node/source-producer.js +145 -0
- package/dist/src/node/workflow.js +455 -0
- package/dist/src/package.js +74 -0
- package/dist/src/protocol.js +105 -0
- package/dist/src/shared/activation.js +111 -0
- package/dist/src/shared/records.js +26 -0
- package/dist/src/worker/activation.js +10 -0
- package/dist/src/worker/index.js +6 -0
- package/dist/src/worker/journal.js +301 -0
- package/dist/src/worker/package.js +116 -0
- package/dist/src/worker/release.js +59 -0
- package/dist/src/worker/runtime.js +98 -0
- package/dist/src/worker/service.js +494 -0
- package/package.json +17 -14
- package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -0
- package/{src/client.d.mts → types/client.d.ts} +1 -1
- package/{src/index.d.mts → types/index.d.ts} +6 -6
- package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
- package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
- package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
- package/types/node/index.d.ts +17 -0
- package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
- package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
- package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
- package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
- package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
- package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
- package/types/worker/index.d.ts +6 -0
- package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
- package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
- package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
- package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
- package/src/acceptance.mjs +0 -66
- package/src/client.mjs +0 -74
- package/src/index.mjs +0 -3
- package/src/node/acceptance-delivery.mjs +0 -109
- package/src/node/activation.mjs +0 -3
- 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.mjs +0 -135
- package/src/node/publishing-command.mjs +0 -104
- package/src/node/session.mjs +0 -134
- package/src/node/solution-package.mjs +0 -113
- package/src/node/source-error.mjs +0 -9
- package/src/node/source-producer.mjs +0 -103
- package/src/node/workflow.mjs +0 -320
- package/src/package.mjs +0 -36
- package/src/protocol.mjs +0 -50
- package/src/shared/activation.mjs +0 -64
- 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.mjs +0 -151
- package/src/worker/package.mjs +0 -32
- package/src/worker/release.mjs +0 -21
- package/src/worker/runtime.mjs +0 -23
- package/src/worker/service.mjs +0 -251
- /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
- /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
- /package/{src/package.d.mts → types/package.d.ts} +0 -0
- /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
- /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import { errorCode, jsonSnapshot, objectRecord } from '../shared/records.js';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
|
+
import { createPublishingClient } from '../client.js';
|
|
8
|
+
import { parsePublishingConfiguration, parsePublishingProject, parsePublishingIntent, publishingRequestId, protocolRecord, publishingError } from '../protocol.js';
|
|
9
|
+
import { createPublishingSession } from './session.js';
|
|
10
|
+
import { verifyPublishingActivation } from './activation.js';
|
|
11
|
+
import { PublishingSourceError } from './source-error.js';
|
|
12
|
+
import { checkoutReleaseVersion, checkoutRequiresAcceptanceDelivery, selectProducerFile, validateLocalProducer } from './source-producer.js';
|
|
13
|
+
import { acceptanceDeliveryTarget, deliverAcceptanceArchive, maximumAcceptanceArchiveBytes, observeAcceptanceDelivery } from './acceptance-delivery.js';
|
|
14
|
+
const fail = (code) => publishingError(code), sourceKey = (id) => 'source:' + id;
|
|
15
|
+
const phases = ['preparing', 'failed-closed', 'frozen', 'delivering', 'delivery-rejected', 'remote', 'abandoned', 'completed', 'failed'];
|
|
16
|
+
function hasPhase(value) { return phases.some(phase => phase === value); }
|
|
17
|
+
function frozenPackage(record) {
|
|
18
|
+
const body = record?.payload;
|
|
19
|
+
if (!objectRecord(body) || !objectRecord(body.intent) || !objectRecord(body.intent.package))
|
|
20
|
+
return undefined;
|
|
21
|
+
const { packageName, version } = body.intent.package;
|
|
22
|
+
return typeof packageName === 'string' && typeof version === 'string' ? { packageName, version } : undefined;
|
|
23
|
+
}
|
|
24
|
+
const rejectedDelivery = new Set(['PUBLISHING_ACCEPTANCE_VERSION_CONFLICT', 'PUBLISHING_ACCEPTANCE_SIGNATURE_INVALID', 'PUBLISHING_ACCEPTANCE_DELIVERY_REJECTED']);
|
|
25
|
+
function newerVersion(candidate, original) {
|
|
26
|
+
const parts = candidate.split('.').map(Number), previous = original.split('.').map(Number);
|
|
27
|
+
const index = parts.findIndex((part, n) => part !== previous[n]);
|
|
28
|
+
return index >= 0 && parts[index] > previous[index];
|
|
29
|
+
}
|
|
30
|
+
function versionRequestId(configuration, packageName, version) {
|
|
31
|
+
const bytes = createHash('sha256').update(JSON.stringify(['link-light/project-version/v1', configuration.serviceUrl, configuration.projectId, packageName, version])).digest().subarray(0, 16);
|
|
32
|
+
bytes[6] = (bytes[6] & 15) | 128;
|
|
33
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
34
|
+
const hex = bytes.toString('hex');
|
|
35
|
+
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
|
|
36
|
+
}
|
|
37
|
+
const sourceOptions = (input) => {
|
|
38
|
+
if (!protocolRecord(input, [], ['producer', 'newPreparation', 'signal']) || input.newPreparation !== undefined && typeof input.newPreparation !== 'boolean')
|
|
39
|
+
throw fail('WORKFLOW_INPUT_INVALID');
|
|
40
|
+
if (input.producer !== undefined)
|
|
41
|
+
validateLocalProducer(input.producer);
|
|
42
|
+
return input;
|
|
43
|
+
};
|
|
44
|
+
/** One active request per project/client journal. Recovery never imports source
|
|
45
|
+
* or performs an operation whose durable Foundation claim already exists. */
|
|
46
|
+
export function createPublishingWorkflow(options) {
|
|
47
|
+
const { root, journal, credential, allowLoopback = false, request, clientLimits, metadataTransport, operationLimits } = options;
|
|
48
|
+
const configuration = parsePublishingConfiguration(options.configuration, { allowLoopback }), pathCaseSensitivity = options.pathCaseSensitivity ?? (process.platform === 'win32' ? 'case-insensitive' : 'case-sensitive');
|
|
49
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !journal || !['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity))
|
|
50
|
+
throw fail('WORKFLOW_INPUT_INVALID');
|
|
51
|
+
const verifier = (signal) => async (input) => { const timeout = AbortSignal.timeout(clientLimits?.requestMs ?? 30000); await verifyPublishingActivation({ ...input, allowLoopback, signal: signal ? AbortSignal.any([signal, timeout]) : timeout, ...(metadataTransport ? { metadataTransport } : {}) }); };
|
|
52
|
+
const shared = { journal, configuration, credential, allowLoopback, ...(request ? { request } : {}), ...(clientLimits ? { clientLimits } : {}) };
|
|
53
|
+
const client = (signal) => createPublishingClient({ ...shared, ...(clientLimits ? { limits: clientLimits } : {}), verifyActivation: verifier(signal) }), activeKey = 'active:' + configuration.projectId;
|
|
54
|
+
const session = (record, signal) => createPublishingSession({ ...shared, verifyActivation: verifier(signal), packageLimits: record.payload.project.limits, pathCaseSensitivity: record.payload.pathCaseSensitivity, ...(operationLimits ? { operationLimits } : {}) });
|
|
55
|
+
const replace = async (record, phase, signal, failure, createAttempt = record.payload.createAttempt) => {
|
|
56
|
+
const payload = { ...record.payload, phase, ...(createAttempt ? { createAttempt } : {}) };
|
|
57
|
+
delete payload.failure;
|
|
58
|
+
if (failure)
|
|
59
|
+
payload.failure = failure;
|
|
60
|
+
const result = await journal.compareAndSet({ key: sourceKey(payload.requestId), expectedRevision: record.revision, payload: jsonSnapshot(payload) }, { signal });
|
|
61
|
+
if (result !== 'stored')
|
|
62
|
+
throw fail('WORKFLOW_CONFLICT');
|
|
63
|
+
return { revision: record.revision + 1, payload };
|
|
64
|
+
};
|
|
65
|
+
const current = async (signal) => {
|
|
66
|
+
const active = await journal.load(activeKey, { signal });
|
|
67
|
+
if (!active)
|
|
68
|
+
return undefined;
|
|
69
|
+
if (!protocolRecord(active.payload, ['schemaVersion', 'requestId']) || active.payload.schemaVersion !== 1 || !publishingRequestId(active.payload.requestId))
|
|
70
|
+
throw fail('WORKFLOW_STATE_INVALID');
|
|
71
|
+
const stored = await journal.load(sourceKey(active.payload.requestId), { signal }), wire = stored?.payload;
|
|
72
|
+
if (!stored || !protocolRecord(wire, ['schemaVersion', 'requestId', 'phase', 'project', 'pathCaseSensitivity'], ['failure', 'selectedVersion', 'createAttempt']) || wire.schemaVersion !== 1 || wire.requestId !== active.payload.requestId || !hasPhase(wire.phase) || wire.pathCaseSensitivity !== 'case-sensitive' && wire.pathCaseSensitivity !== 'case-insensitive')
|
|
73
|
+
throw fail('WORKFLOW_STATE_INVALID');
|
|
74
|
+
const { phase, createAttempt, selectedVersion, pathCaseSensitivity } = wire;
|
|
75
|
+
if (createAttempt !== undefined && (typeof createAttempt !== 'number' || !Number.isSafeInteger(createAttempt) || createAttempt < 1 || createAttempt > 64) || selectedVersion !== undefined && typeof selectedVersion !== 'string')
|
|
76
|
+
throw fail('WORKFLOW_STATE_INVALID');
|
|
77
|
+
let failure;
|
|
78
|
+
if (wire.failure !== undefined) {
|
|
79
|
+
if (!protocolRecord(wire.failure, ['code']) || typeof wire.failure.code !== 'string' ||
|
|
80
|
+
!(phase === 'failed-closed' && ['PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID', 'PUBLISHING_SOURCE_PREPARATION_FAILED', 'PUBLISHING_ACCEPTANCE_VERSION_CONFLICT'].includes(wire.failure.code) || phase === 'delivery-rejected' && rejectedDelivery.has(wire.failure.code)))
|
|
81
|
+
throw fail('WORKFLOW_STATE_INVALID');
|
|
82
|
+
failure = { code: wire.failure.code };
|
|
83
|
+
}
|
|
84
|
+
const project = parsePublishingProject(wire.project, { allowLoopback });
|
|
85
|
+
if (JSON.stringify(project.configuration) !== JSON.stringify(configuration))
|
|
86
|
+
throw fail('CONFIGURATION_CHANGED');
|
|
87
|
+
let record = { revision: stored.revision, payload: { schemaVersion: 1, requestId: active.payload.requestId, project, phase, pathCaseSensitivity, ...(failure ? { failure } : {}), ...(createAttempt !== undefined ? { createAttempt } : {}), ...(selectedVersion !== undefined ? { selectedVersion } : {}) } };
|
|
88
|
+
// freeze is the atomic authority: losing the outer acknowledgment must never
|
|
89
|
+
// cause a second import, build, capture or request identity.
|
|
90
|
+
if (record.payload.phase === 'preparing' && await journal.load('request:' + record.payload.requestId, { signal })) {
|
|
91
|
+
await session(record, signal).read({ requestId: record.payload.requestId, signal });
|
|
92
|
+
record = await replace(record, 'frozen', signal);
|
|
93
|
+
}
|
|
94
|
+
return { active, record };
|
|
95
|
+
};
|
|
96
|
+
const result = (record, state, extra = {}) => ({ requestId: record.payload.requestId, state, active: state === 'active', ...extra });
|
|
97
|
+
const operationClaim = (id, stage, signal, attempt = 0) => journal.load('operation:' + id + '.' + stage + (attempt ? '.' + attempt : ''), { signal });
|
|
98
|
+
const rejectedCreate = (claim) => objectRecord(claim?.payload) && claim.payload.writeState === 'rejected' && claim.payload.attemptFailure === 'CONFLICT';
|
|
99
|
+
const prepare = async (input) => {
|
|
100
|
+
const { producer, signal } = sourceOptions(input);
|
|
101
|
+
let { newPreparation = false } = input;
|
|
102
|
+
let previous = await current(signal), automatic = false, previousCreateRejected = false;
|
|
103
|
+
if (previous?.record.payload.phase === 'failed-closed' && previous.record.payload.selectedVersion && !newPreparation) {
|
|
104
|
+
const version = await checkoutReleaseVersion(root, previous.record.payload.project.packageName);
|
|
105
|
+
newPreparation = Boolean(version && newerVersion(version, previous.record.payload.selectedVersion));
|
|
106
|
+
}
|
|
107
|
+
if (previous && !newPreparation && ['remote', 'completed', 'failed', 'abandoned', 'delivery-rejected'].includes(previous.record.payload.phase)) {
|
|
108
|
+
const original = await journal.load('request:' + previous.record.payload.requestId, { signal });
|
|
109
|
+
const originalPackage = frozenPackage(original);
|
|
110
|
+
if (originalPackage) {
|
|
111
|
+
// A checkout is optional when resuming. Only a valid, explicitly higher owner
|
|
112
|
+
// version can select another identity. Its producer is loaded after closure.
|
|
113
|
+
const version = await checkoutReleaseVersion(root, originalPackage.packageName).catch(() => undefined);
|
|
114
|
+
if ((version === undefined || version === originalPackage.version) && ['completed', 'failed', 'delivery-rejected'].includes(previous.record.payload.phase))
|
|
115
|
+
return previous.record;
|
|
116
|
+
if (version && version !== originalPackage.version) {
|
|
117
|
+
if (newerVersion(version, originalPackage.version)) {
|
|
118
|
+
automatic = true;
|
|
119
|
+
newPreparation = true;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (previous && newPreparation && ['remote', 'completed', 'failed'].includes(previous.record.payload.phase)) {
|
|
125
|
+
// Observe the original identity and current admission before permitting the
|
|
126
|
+
// next release. A prior terminal observation never authorizes an unknown,
|
|
127
|
+
// still-running or currently unverified request to be replaced.
|
|
128
|
+
const observed = await inspect({ signal }, true);
|
|
129
|
+
if (observed.sideEffects !== 'closed' || !['abandoned', 'active', 'failed'].includes(observed.state)) {
|
|
130
|
+
if (automatic)
|
|
131
|
+
return { observed: { ...observed, active: false } };
|
|
132
|
+
throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
|
|
133
|
+
}
|
|
134
|
+
previousCreateRejected = observed.error?.code === 'PUBLISHING_CONFLICT' && observed.sideEffects === 'closed';
|
|
135
|
+
previous = await current(signal);
|
|
136
|
+
}
|
|
137
|
+
if (previous) {
|
|
138
|
+
const phase = previous.record.payload.phase;
|
|
139
|
+
if (phase === 'preparing')
|
|
140
|
+
throw fail('SOURCE_PREPARATION_UNKNOWN');
|
|
141
|
+
if (['frozen', 'delivering', 'remote'].includes(phase)) {
|
|
142
|
+
if (!newPreparation)
|
|
143
|
+
return previous.record;
|
|
144
|
+
if (phase !== 'remote' || !previousCreateRejected)
|
|
145
|
+
throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
|
|
146
|
+
}
|
|
147
|
+
if (!newPreparation)
|
|
148
|
+
throw fail('SOURCE_NEW_PREPARATION_REQUIRED');
|
|
149
|
+
}
|
|
150
|
+
signal?.throwIfAborted();
|
|
151
|
+
if (await fs.realpath(root) !== root || !(await fs.lstat(root)).isDirectory())
|
|
152
|
+
throw fail('SOURCE_PATH_INVALID');
|
|
153
|
+
const project = await client(signal).getProject({ signal });
|
|
154
|
+
let file, selectionFailure;
|
|
155
|
+
try {
|
|
156
|
+
file = await selectProducerFile(root, producer);
|
|
157
|
+
}
|
|
158
|
+
catch (cause) {
|
|
159
|
+
selectionFailure = new PublishingSourceError({ cause, processesClosed: true });
|
|
160
|
+
}
|
|
161
|
+
const deliver = Boolean(options.acceptanceDelivery);
|
|
162
|
+
if (!selectionFailure && !producer && await checkoutRequiresAcceptanceDelivery(root) && !deliver)
|
|
163
|
+
throw fail('ACCEPTANCE_CREDENTIAL_REQUIRED');
|
|
164
|
+
let inherited, selectedVersion, requestId = randomUUID();
|
|
165
|
+
if (deliver) {
|
|
166
|
+
const version = await checkoutReleaseVersion(root, project.packageName);
|
|
167
|
+
if (!version)
|
|
168
|
+
throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
169
|
+
selectedVersion = version;
|
|
170
|
+
const latest = await client(signal).getLatestRelease({ signal });
|
|
171
|
+
if (latest && (latest.intent.package.packageName !== project.packageName || latest.intent.package.solutionId !== project.solutionId))
|
|
172
|
+
throw fail('PROJECT_BINDING_INVALID');
|
|
173
|
+
if (latest?.intent.package.version === version) {
|
|
174
|
+
inherited = latest.intent;
|
|
175
|
+
requestId = inherited.requestId;
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
if (latest && (!['active', 'failed', 'superseded'].includes(latest.status.state) || latest.status.sideEffects !== 'closed')) {
|
|
179
|
+
return { observed: { requestId: latest.intent.requestId, state: latest.status.state, sideEffects: latest.status.sideEffects, active: false } };
|
|
180
|
+
}
|
|
181
|
+
if (latest && !newerVersion(version, latest.intent.package.version))
|
|
182
|
+
throw fail('SOURCE_VERSION_NOT_NEWER');
|
|
183
|
+
requestId = versionRequestId(configuration, project.packageName, version);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
signal?.throwIfAborted();
|
|
187
|
+
const payload = { schemaVersion: 1, requestId, project, pathCaseSensitivity, ...(selectedVersion ? { selectedVersion } : {}), ...(selectionFailure ? { phase: 'failed-closed', failure: { code: selectionFailure.code } } : { phase: 'preparing' }) };
|
|
188
|
+
const retry = previous?.record.payload.requestId === requestId && previous.record.payload.phase === 'failed-closed' && newPreparation;
|
|
189
|
+
const sourceRevision = retry && previous ? previous.record.revision : 0;
|
|
190
|
+
if (await journal.compareAndSet({ key: sourceKey(requestId), expectedRevision: sourceRevision, payload: jsonSnapshot(payload) }, { signal }) !== 'stored')
|
|
191
|
+
throw fail('WORKFLOW_CONFLICT');
|
|
192
|
+
if (await journal.compareAndSet({ key: activeKey, expectedRevision: previous?.active.revision ?? 0, payload: { schemaVersion: 1, requestId } }, { signal }) !== 'stored')
|
|
193
|
+
throw fail('WORKFLOW_CONFLICT');
|
|
194
|
+
if (selectionFailure)
|
|
195
|
+
throw selectionFailure;
|
|
196
|
+
let record = { revision: sourceRevision + 1, payload }, prepared, intent, acceptanceArchive, processesClosed = false;
|
|
197
|
+
try {
|
|
198
|
+
if (!file)
|
|
199
|
+
throw fail('SOURCE_PORT_INVALID');
|
|
200
|
+
const producerModule = await import(pathToFileURL(file).href + '?publishingRequest=' + requestId);
|
|
201
|
+
if (typeof producerModule.prepare !== 'function')
|
|
202
|
+
throw fail('SOURCE_PORT_INVALID');
|
|
203
|
+
const response = await producerModule.prepare({ root, project: structuredClone(project), signal, requestId, ...(deliver ? { includeAcceptanceArchive: true } : {}) });
|
|
204
|
+
if (!protocolRecord(response, ['prepared', 'processesClosed'], ['acceptanceArchive']) || response.processesClosed !== true)
|
|
205
|
+
throw fail('SOURCE_PROCESS_CLOSURE_UNKNOWN');
|
|
206
|
+
processesClosed = true;
|
|
207
|
+
prepared = response.prepared;
|
|
208
|
+
acceptanceArchive = response.acceptanceArchive;
|
|
209
|
+
const item = prepared?.descriptor;
|
|
210
|
+
if (deliver && (!acceptanceArchive || !(acceptanceArchive.bytes instanceof Uint8Array) || !acceptanceArchive.bytes.length ||
|
|
211
|
+
acceptanceArchive.bytes.length > maximumAcceptanceArchiveBytes || !/^[a-f0-9]{64}$/.test(acceptanceArchive.artifactSha256)))
|
|
212
|
+
throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
213
|
+
if (!deliver && acceptanceArchive)
|
|
214
|
+
throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
215
|
+
if (!item || item.solutionId !== project.solutionId || item.packageName !== project.packageName || item.publisherId !== configuration.publisher.publisherId)
|
|
216
|
+
throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
217
|
+
if (!producer) {
|
|
218
|
+
const expected = await checkoutReleaseVersion(root, project.packageName);
|
|
219
|
+
if (expected !== undefined && item.version !== expected)
|
|
220
|
+
throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
221
|
+
}
|
|
222
|
+
intent = parsePublishingIntent({ schemaVersion: 1, requestId, projectId: configuration.projectId, policyRevision: project.policyRevision, package: { solutionId: item.solutionId, publisherId: item.publisherId, packageName: item.packageName, version: item.version, content: prepared.content, fileCount: prepared.files.length, totalBytes: prepared.payloadBytes } });
|
|
223
|
+
if (inherited) {
|
|
224
|
+
if (JSON.stringify(intent.package) !== JSON.stringify(inherited.package))
|
|
225
|
+
throw fail('ACCEPTANCE_VERSION_CONFLICT');
|
|
226
|
+
intent = inherited;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
if (processesClosed || error instanceof PublishingSourceError && error.processesClosed) {
|
|
231
|
+
const causeCode = errorCode(error), code = causeCode && ['PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID', 'PUBLISHING_ACCEPTANCE_VERSION_CONFLICT'].includes(causeCode) ? causeCode : 'PUBLISHING_SOURCE_PREPARATION_FAILED';
|
|
232
|
+
await replace(record, 'failed-closed', signal, { code });
|
|
233
|
+
if (code === 'PUBLISHING_ACCEPTANCE_VERSION_CONFLICT')
|
|
234
|
+
throw error;
|
|
235
|
+
throw new PublishingSourceError({ cause: error, processesClosed: true });
|
|
236
|
+
}
|
|
237
|
+
throw new PublishingSourceError({ cause: error, processesClosed: false });
|
|
238
|
+
}
|
|
239
|
+
// Freeze and its acknowledgment deliberately remain outside the known-closed
|
|
240
|
+
// source catch: a storage error can mean the original bytes were committed.
|
|
241
|
+
await session(record, signal).freeze({ intent, prepared, acceptanceArchive, acceptanceTarget: options.acceptanceDelivery ? acceptanceDeliveryTarget(options.acceptanceDelivery) : undefined, signal });
|
|
242
|
+
record = await replace(record, 'frozen', signal);
|
|
243
|
+
return record;
|
|
244
|
+
};
|
|
245
|
+
const local = (record) => result(record, ['frozen', 'remote', 'completed', 'failed'].includes(record.payload.phase) ? 'checked' : record.payload.phase === 'preparing' ? 'preparation-unknown' : record.payload.phase === 'failed-closed' ? 'preparation-failed' : record.payload.phase === 'abandoned' ? 'abandoned' : 'unknown');
|
|
246
|
+
const observedResult = async (record, status, signal) => {
|
|
247
|
+
// The client/session authenticated this exact original intent, and ACTIVE
|
|
248
|
+
// already passed the real signature and current Core-admission verifier.
|
|
249
|
+
const terminal = { abandoned: 'abandoned', active: 'completed', failed: 'failed' };
|
|
250
|
+
const phase = status.sideEffects === 'closed' ? terminal[status.state] : undefined;
|
|
251
|
+
if (phase && record.payload.phase !== phase) {
|
|
252
|
+
try {
|
|
253
|
+
record = await replace(record, phase, signal);
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (errorCode(error) !== 'PUBLISHING_WORKFLOW_CONFLICT')
|
|
257
|
+
throw error;
|
|
258
|
+
const latest = await journal.load(sourceKey(record.payload.requestId), { signal });
|
|
259
|
+
if (!latest || !objectRecord(latest.payload) || latest.payload.phase !== phase)
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return result(record, status.state, { sideEffects: status.sideEffects });
|
|
264
|
+
};
|
|
265
|
+
const inspect = async ({ signal } = {}, observe = false, dispatchRecovery = false) => {
|
|
266
|
+
const state = await current(signal);
|
|
267
|
+
if (!state) {
|
|
268
|
+
const latest = options.acceptanceDelivery ? await client(signal).getLatestRelease({ signal }) : undefined;
|
|
269
|
+
return latest ? { requestId: latest.intent.requestId, state: latest.status.state, sideEffects: latest.status.sideEffects, active: latest.status.state === 'active' } : { state: 'empty', active: false };
|
|
270
|
+
}
|
|
271
|
+
const { record } = state;
|
|
272
|
+
if (record.payload.phase === 'delivery-rejected')
|
|
273
|
+
return result(record, 'failed', { sideEffects: 'closed', error: record.payload.failure });
|
|
274
|
+
if (record.payload.phase === 'delivering') {
|
|
275
|
+
const bundle = await session(record, signal).acceptanceMetadata({ requestId: record.payload.requestId, signal });
|
|
276
|
+
try {
|
|
277
|
+
if (!bundle || !options.acceptanceDelivery || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
|
|
278
|
+
throw fail('ACCEPTANCE_TRUST_CHANGED');
|
|
279
|
+
if (await observeAcceptanceDelivery({ ...bundle, credential: options.acceptanceDelivery, request, signal }))
|
|
280
|
+
return result(record, 'checked');
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
const code = errorCode(error);
|
|
284
|
+
if (code === 'PUBLISHING_ACCEPTANCE_VERSION_CONFLICT') {
|
|
285
|
+
await replace(record, 'delivery-rejected', signal, { code });
|
|
286
|
+
return result(record, 'failed', { sideEffects: 'closed', error: { code } });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return result(record, 'unknown');
|
|
290
|
+
}
|
|
291
|
+
if (!['frozen', 'remote', 'completed', 'failed'].includes(record.payload.phase))
|
|
292
|
+
return local(record);
|
|
293
|
+
const { requestId, createAttempt: attempt = 0 } = record.payload, commit = await operationClaim(requestId, 'commit', signal), create = await operationClaim(requestId, 'create', signal, attempt);
|
|
294
|
+
if (!commit && rejectedCreate(create))
|
|
295
|
+
return result(record, 'failed', { sideEffects: 'closed', error: { code: 'PUBLISHING_CONFLICT' } });
|
|
296
|
+
if (!commit && !create)
|
|
297
|
+
return local(record);
|
|
298
|
+
const selected = session(record, signal);
|
|
299
|
+
if (observe) {
|
|
300
|
+
const observed = await selected.observe({ requestId, stage: commit ? 'commit' : 'create', attempt: commit ? 0 : attempt, signal });
|
|
301
|
+
if (!observed.status)
|
|
302
|
+
return result(record, 'unknown');
|
|
303
|
+
// The control only asks the host to observe an already committed original
|
|
304
|
+
// operation. Uploading/local preparation never dispatches provider work.
|
|
305
|
+
const status = dispatchRecovery && commit && ['queued', 'deploying', 'awaiting-acceptance', 'unknown'].includes(observed.status.state) ? await selected.recover({ requestId, signal }) : observed.status;
|
|
306
|
+
return observedResult(record, status, signal);
|
|
307
|
+
}
|
|
308
|
+
return observedResult(record, await selected.status({ requestId, signal }), signal);
|
|
309
|
+
};
|
|
310
|
+
const waiting = (state) => ['queued', 'deploying', 'registered', 'awaiting-acceptance'].includes(state);
|
|
311
|
+
const waitFor = async (record, initial, { signal, waitMs, pollMs }) => {
|
|
312
|
+
if (!waitMs || !waiting(initial.state))
|
|
313
|
+
return initial;
|
|
314
|
+
const timeout = AbortSignal.timeout(waitMs), active = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
315
|
+
let latest = initial;
|
|
316
|
+
try {
|
|
317
|
+
while (waiting(latest.state)) {
|
|
318
|
+
await delay(pollMs, undefined, { signal: active });
|
|
319
|
+
latest = await observedResult(record, await session(record, active).status({ requestId: record.payload.requestId, signal: active }), active);
|
|
320
|
+
}
|
|
321
|
+
return latest;
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
if (timeout.aborted && !signal?.aborted)
|
|
325
|
+
return { ...latest, timedOut: true };
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
return Object.freeze({
|
|
330
|
+
async check(input = {}) {
|
|
331
|
+
const record = await prepare(input);
|
|
332
|
+
if ('observed' in record)
|
|
333
|
+
return record.observed;
|
|
334
|
+
if (['delivering', 'delivery-rejected'].includes(record.payload.phase))
|
|
335
|
+
return inspect({ signal: input.signal }, true);
|
|
336
|
+
return local(record);
|
|
337
|
+
},
|
|
338
|
+
async publish(input = {}) {
|
|
339
|
+
if (!protocolRecord(input, [], ['producer', 'newPreparation', 'signal', 'waitMs', 'pollMs']))
|
|
340
|
+
throw fail('WORKFLOW_INPUT_INVALID');
|
|
341
|
+
const { waitMs = 0, pollMs = 1000, ...source } = input;
|
|
342
|
+
if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 3600000 || !Number.isSafeInteger(pollMs) || pollMs < 1 || pollMs > 30000)
|
|
343
|
+
throw fail('WORKFLOW_INPUT_INVALID');
|
|
344
|
+
const prepared = await prepare(source);
|
|
345
|
+
if ('observed' in prepared)
|
|
346
|
+
return prepared.observed;
|
|
347
|
+
let record = prepared;
|
|
348
|
+
const requestId = record.payload.requestId, signal = input.signal, finish = (status) => waitFor(record, status, { signal, waitMs, pollMs });
|
|
349
|
+
// This CAS competes with local abandonment before any remote write. Once
|
|
350
|
+
// remote publication may start, absence of a later claim is not a closure
|
|
351
|
+
// proof for an overlapping client.
|
|
352
|
+
const selected = session(record, signal);
|
|
353
|
+
// Delivery is an immutable owner-side installation. Keep the original
|
|
354
|
+
// request frozen until its exact version and both digests can be read back.
|
|
355
|
+
if (['frozen', 'delivering', 'delivery-rejected'].includes(record.payload.phase)) {
|
|
356
|
+
const bundle = await selected.readAcceptanceArchive({ requestId, signal });
|
|
357
|
+
if (bundle) {
|
|
358
|
+
if (!options.acceptanceDelivery || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
|
|
359
|
+
return result(record, 'failed', { error: { code: 'PUBLISHING_ACCEPTANCE_TRUST_CHANGED' } });
|
|
360
|
+
if (record.payload.phase !== 'delivering')
|
|
361
|
+
record = await replace(record, 'delivering', signal);
|
|
362
|
+
try {
|
|
363
|
+
await deliverAcceptanceArchive({ ...bundle, credential: options.acceptanceDelivery, request, signal });
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
const code = errorCode(error);
|
|
367
|
+
if (code && rejectedDelivery.has(code)) {
|
|
368
|
+
await replace(record, 'delivery-rejected', signal, { code });
|
|
369
|
+
return result(record, 'failed', { sideEffects: 'closed', error: { code } });
|
|
370
|
+
}
|
|
371
|
+
return result(record, 'unknown', { error: { code: 'PUBLISHING_ACCEPTANCE_DELIVERY_UNKNOWN' } });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
record = await replace(record, 'remote', signal);
|
|
375
|
+
}
|
|
376
|
+
// Never repeat creation, upload or commit after the original commit claim.
|
|
377
|
+
// A healthy confirmed original may ask the host for its known next step;
|
|
378
|
+
// unknown requires explicit recovery and cannot perform on publish.
|
|
379
|
+
if (await operationClaim(requestId, 'commit', signal)) {
|
|
380
|
+
const original = await inspect({ signal }, true);
|
|
381
|
+
if (['queued', 'deploying'].includes(original.state))
|
|
382
|
+
return finish(await observedResult(record, await selected.resume({ requestId, signal }), signal));
|
|
383
|
+
return finish(original);
|
|
384
|
+
}
|
|
385
|
+
let attempt = record.payload.createAttempt ?? 0, createClaim = await operationClaim(requestId, 'create', signal, attempt);
|
|
386
|
+
if (rejectedCreate(createClaim)) {
|
|
387
|
+
const latest = await client(signal).getLatestRelease({ signal });
|
|
388
|
+
if (latest && latest.status.sideEffects !== 'closed')
|
|
389
|
+
return { requestId: latest.intent.requestId, state: latest.status.state, sideEffects: latest.status.sideEffects, active: false };
|
|
390
|
+
const version = record.payload.selectedVersion ?? frozenPackage(await journal.load('request:' + requestId, { signal }))?.version;
|
|
391
|
+
if (!version)
|
|
392
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
393
|
+
if (latest && latest.intent.package.version === version || attempt >= 64)
|
|
394
|
+
return result(record, 'failed', { sideEffects: 'closed', error: { code: 'PUBLISHING_CONFLICT' } });
|
|
395
|
+
// An authenticated rejection is durable. Advance only after observing
|
|
396
|
+
// closure. Unknown create acknowledgements always use the original claim.
|
|
397
|
+
record = await replace(record, 'remote', signal, undefined, ++attempt);
|
|
398
|
+
createClaim = undefined;
|
|
399
|
+
}
|
|
400
|
+
let created;
|
|
401
|
+
try {
|
|
402
|
+
created = await (createClaim ? selected.observe({ requestId, stage: 'create', attempt, signal }) : selected.create({ requestId, attempt, signal }));
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
if (rejectedCreate(await operationClaim(requestId, 'create', signal, attempt)))
|
|
406
|
+
return result(record, 'failed', { sideEffects: 'closed', error: { code: 'PUBLISHING_CONFLICT' } });
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
if (created.receipt.outcome !== 'succeeded')
|
|
410
|
+
return result(record, 'unknown');
|
|
411
|
+
if (created.status && created.status.state !== 'uploading')
|
|
412
|
+
return finish(await observedResult(record, created.status, signal));
|
|
413
|
+
const uploaded = await selected.upload({ requestId, signal });
|
|
414
|
+
if (uploaded.state !== 'uploading')
|
|
415
|
+
return finish(await observedResult(record, uploaded, signal));
|
|
416
|
+
if (uploaded.missingFiles.length)
|
|
417
|
+
throw fail('UPLOAD_INCOMPLETE');
|
|
418
|
+
const queued = await selected.queue({ requestId, signal });
|
|
419
|
+
return queued.status ? finish(await observedResult(record, queued.status, signal)) : result(record, 'unknown');
|
|
420
|
+
},
|
|
421
|
+
status: input => inspect(input), recover: input => inspect(input, true, true), verify: input => inspect(input),
|
|
422
|
+
async abandon({ signal } = {}) {
|
|
423
|
+
const state = await current(signal);
|
|
424
|
+
if (!state)
|
|
425
|
+
throw fail('SOURCE_REQUEST_MISSING');
|
|
426
|
+
let { record } = state;
|
|
427
|
+
if (record.payload.phase === 'abandoned')
|
|
428
|
+
return local(record);
|
|
429
|
+
if (record.payload.phase === 'preparing')
|
|
430
|
+
throw fail('SOURCE_PREPARATION_UNKNOWN');
|
|
431
|
+
if (!['frozen', 'remote'].includes(record.payload.phase))
|
|
432
|
+
throw fail('ABANDON_UNSAFE');
|
|
433
|
+
const requestId = record.payload.requestId;
|
|
434
|
+
if (await operationClaim(requestId, 'commit', signal))
|
|
435
|
+
throw fail('ABANDON_UNSAFE');
|
|
436
|
+
const creation = await operationClaim(requestId, 'create', signal, record.payload.createAttempt);
|
|
437
|
+
if (rejectedCreate(creation))
|
|
438
|
+
return local(await replace(record, 'abandoned', signal));
|
|
439
|
+
if (creation) {
|
|
440
|
+
const selected = session(record, signal), { intent } = await selected.read({ requestId, signal }), status = await client(signal).getStatus({ intent, signal });
|
|
441
|
+
if (status.state === 'abandoned' && status.sideEffects === 'closed')
|
|
442
|
+
return observedResult(record, status, signal);
|
|
443
|
+
if (status.state !== 'uploading' || status.sideEffects !== 'none')
|
|
444
|
+
throw fail('ABANDON_UNSAFE');
|
|
445
|
+
const abandoned = await selected.abandon({ requestId, signal });
|
|
446
|
+
if (abandoned.state !== 'abandoned' || abandoned.sideEffects !== 'closed')
|
|
447
|
+
throw fail('ABANDON_UNSAFE');
|
|
448
|
+
}
|
|
449
|
+
else if (record.payload.phase === 'remote')
|
|
450
|
+
throw fail('ABANDON_UNSAFE');
|
|
451
|
+
record = await replace(record, 'abandoned', signal);
|
|
452
|
+
return local(record);
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { validatePortableRelativePath } from '@openge/forge-path-safety';
|
|
2
|
+
function invalid() { throw Error('PUBLISHING_PACKAGE_DESCRIPTOR_INVALID'); }
|
|
3
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
4
|
+
const exact = (value, keys) => record(value) && Object.keys(value).sort().join(',') === keys.split(',').sort().join(',');
|
|
5
|
+
const identifier = (value) => typeof value === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(value);
|
|
6
|
+
export function parseSolutionPackageLimits(value) {
|
|
7
|
+
const names = ['maximumFiles', 'maximumFileBytes', 'maximumTotalBytes', 'maximumManifestBytes', 'timeoutMs'];
|
|
8
|
+
function valid(input) {
|
|
9
|
+
if (!exact(input, names.join(',')))
|
|
10
|
+
return false;
|
|
11
|
+
const maxima = { maximumFiles: 10000, maximumFileBytes: 134217728, maximumTotalBytes: 268435456, maximumManifestBytes: 1048576, timeoutMs: 300000 };
|
|
12
|
+
return names.every(key => { const field = input[key]; return typeof field === 'number' && Number.isSafeInteger(field) && field >= 1 && field <= maxima[key]; });
|
|
13
|
+
}
|
|
14
|
+
if (!valid(value))
|
|
15
|
+
throw Error('PUBLISHING_PACKAGE_LIMIT_INVALID');
|
|
16
|
+
return { ...value };
|
|
17
|
+
}
|
|
18
|
+
function entry(value, prefix) {
|
|
19
|
+
if (typeof value !== 'string' || !value.startsWith(prefix + '/'))
|
|
20
|
+
invalid();
|
|
21
|
+
try {
|
|
22
|
+
if (validatePortableRelativePath(value) !== value)
|
|
23
|
+
invalid();
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
invalid();
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function json(value, depth = 0) {
|
|
31
|
+
if (depth > 32)
|
|
32
|
+
invalid();
|
|
33
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
34
|
+
return;
|
|
35
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
36
|
+
return;
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
for (const item of value)
|
|
39
|
+
json(item, depth + 1);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (record(value)) {
|
|
43
|
+
for (const [key, item] of Object.entries(value)) {
|
|
44
|
+
if (['__proto__', 'prototype', 'constructor'].includes(key))
|
|
45
|
+
invalid();
|
|
46
|
+
json(item, depth + 1);
|
|
47
|
+
}
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
invalid();
|
|
51
|
+
}
|
|
52
|
+
/** Domain metadata stays declarative; deployment and credentials are service policy. */
|
|
53
|
+
function assertDescriptor(value) {
|
|
54
|
+
if (!exact(value, 'schemaVersion,solutionId,publisherId,packageName,version,sdkApiVersion,runtime,ui,release') || value.schemaVersion !== 1 || !identifier(value.solutionId) || !identifier(value.publisherId) || typeof value.packageName !== 'string' || !/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(value.packageName) || typeof value.version !== 'string' || !/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(value.version) || value.sdkApiVersion !== '2.0.0')
|
|
55
|
+
invalid();
|
|
56
|
+
if (!exact(value.runtime, 'entry,protocolVersion,links') || value.runtime.protocolVersion !== 2 || !Array.isArray(value.runtime.links) || value.runtime.links.length > 8192 || !exact(value.ui, 'entry,bridgeVersion') || value.ui.bridgeVersion !== 1)
|
|
57
|
+
invalid();
|
|
58
|
+
entry(value.runtime.entry, 'server');
|
|
59
|
+
entry(value.ui.entry, 'ui');
|
|
60
|
+
for (const link of value.runtime.links) {
|
|
61
|
+
if (!exact(link, 'path,target') || typeof link.target !== 'string' || !link.target || link.target.length > 1024 || /[\\:\0\r\n]/.test(link.target) || link.target.startsWith('/'))
|
|
62
|
+
invalid();
|
|
63
|
+
entry(link.path, 'server');
|
|
64
|
+
}
|
|
65
|
+
if (!exact(value.release, 'permissions,display,queries,operations,capabilities,resourcesDigest') || typeof value.release.resourcesDigest !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(value.release.resourcesDigest))
|
|
66
|
+
invalid();
|
|
67
|
+
json(value);
|
|
68
|
+
if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 262144)
|
|
69
|
+
invalid();
|
|
70
|
+
}
|
|
71
|
+
export function parseSolutionPackageDescriptor(value) {
|
|
72
|
+
assertDescriptor(value);
|
|
73
|
+
return structuredClone(value);
|
|
74
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { validatePortableRelativePath } from '@openge/forge-path-safety';
|
|
2
|
+
import { parseSolutionPackageLimits } from './package.js';
|
|
3
|
+
import { jsonValue } from './shared/records.js';
|
|
4
|
+
export const publishingError = (code) => Object.assign(Error('PUBLISHING_' + code), { code: 'PUBLISHING_' + code });
|
|
5
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
export const protocolRecord = (value, required, optional = []) => record(value) && required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key));
|
|
7
|
+
export const publishingIdentifier = (value) => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(value);
|
|
8
|
+
export const publishingDigest = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
9
|
+
export const publishingRequestId = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
10
|
+
const integer = (value, min, max) => typeof value === 'number' && Number.isSafeInteger(value) && value >= min && value <= max;
|
|
11
|
+
const member = (value, items) => items.some(item => value === item);
|
|
12
|
+
function origin(value, allowLoopback) {
|
|
13
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
14
|
+
throw publishingError('CONFIGURATION_INVALID');
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(value);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw publishingError('CONFIGURATION_INVALID');
|
|
21
|
+
}
|
|
22
|
+
if (url.origin !== value || url.username || url.password || url.hash || url.search || !(url.protocol === 'https:' || allowLoopback === true && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)))
|
|
23
|
+
throw publishingError('CONFIGURATION_INVALID');
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
export function parsePublishingConfiguration(value, { allowLoopback = false } = {}) {
|
|
27
|
+
if (!protocolRecord(value, ['schemaVersion', 'serviceUrl', 'projectId', 'coreOrigin', 'publisher']) || value.schemaVersion !== 1 || !publishingIdentifier(value.projectId) || !protocolRecord(value.publisher, ['publisherId', 'keys']) || !publishingIdentifier(value.publisher.publisherId) || !Array.isArray(value.publisher.keys) || value.publisher.keys.length < 1 || value.publisher.keys.length > 8)
|
|
28
|
+
throw publishingError('CONFIGURATION_INVALID');
|
|
29
|
+
const seen = new Set(), keys = value.publisher.keys.map(key => {
|
|
30
|
+
if (!protocolRecord(key, ['keyId', 'publicKey']) || !publishingIdentifier(key.keyId) || seen.has(key.keyId) || typeof key.publicKey !== 'string' || key.publicKey.length > 4096 || !/^-----BEGIN PUBLIC KEY-----\n[A-Za-z0-9+/=\n]+\n-----END PUBLIC KEY-----\n?$/.test(key.publicKey))
|
|
31
|
+
throw publishingError('CONFIGURATION_INVALID');
|
|
32
|
+
seen.add(key.keyId);
|
|
33
|
+
return { keyId: key.keyId, publicKey: key.publicKey };
|
|
34
|
+
});
|
|
35
|
+
return { schemaVersion: 1, serviceUrl: origin(value.serviceUrl, allowLoopback), projectId: value.projectId, coreOrigin: origin(value.coreOrigin, allowLoopback), publisher: { publisherId: value.publisher.publisherId, keys } };
|
|
36
|
+
}
|
|
37
|
+
export function parsePublishingIntent(value) {
|
|
38
|
+
if (!protocolRecord(value, ['schemaVersion', 'requestId', 'projectId', 'policyRevision', 'package'], ['provenance']) || value.schemaVersion !== 1 || !publishingRequestId(value.requestId) || !publishingIdentifier(value.projectId) || !integer(value.policyRevision, 1, Number.MAX_SAFE_INTEGER))
|
|
39
|
+
throw publishingError('INTENT_INVALID');
|
|
40
|
+
const item = value.package;
|
|
41
|
+
if (!protocolRecord(item, ['solutionId', 'publisherId', 'packageName', 'version', 'content', 'fileCount', 'totalBytes']) || !publishingIdentifier(item.solutionId) || !publishingIdentifier(item.publisherId) || typeof item.packageName !== 'string' || !/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(item.packageName) || typeof item.version !== 'string' || !/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(item.version) || !protocolRecord(item.content, ['manifestSha256']) || !publishingDigest(item.content.manifestSha256) || !integer(item.fileCount, 1, 10000) || !integer(item.totalBytes, 1, 268435456))
|
|
42
|
+
throw publishingError('INTENT_INVALID');
|
|
43
|
+
let provenance;
|
|
44
|
+
if (value.provenance !== undefined) {
|
|
45
|
+
if (!protocolRecord(value.provenance, ['gitRevision']) || typeof value.provenance.gitRevision !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.provenance.gitRevision))
|
|
46
|
+
throw publishingError('INTENT_INVALID');
|
|
47
|
+
provenance = { gitRevision: value.provenance.gitRevision };
|
|
48
|
+
}
|
|
49
|
+
return { schemaVersion: 1, requestId: value.requestId, projectId: value.projectId, policyRevision: value.policyRevision, package: { solutionId: item.solutionId, publisherId: item.publisherId, packageName: item.packageName, version: item.version, content: { manifestSha256: item.content.manifestSha256 }, fileCount: item.fileCount, totalBytes: item.totalBytes }, ...(provenance ? { provenance } : {}) };
|
|
50
|
+
}
|
|
51
|
+
export function parsePublishingProject(value, { allowLoopback = false } = {}) {
|
|
52
|
+
if (!protocolRecord(value, ['schemaVersion', 'configuration', 'policyRevision', 'solutionId', 'packageName', 'limits']) || value.schemaVersion !== 1 || !integer(value.policyRevision, 1, Number.MAX_SAFE_INTEGER) || !publishingIdentifier(value.solutionId) || typeof value.packageName !== 'string' || !/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(value.packageName))
|
|
53
|
+
throw publishingError('PROJECT_INVALID');
|
|
54
|
+
let limits;
|
|
55
|
+
try {
|
|
56
|
+
limits = parseSolutionPackageLimits(value.limits);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw publishingError('PROJECT_INVALID');
|
|
60
|
+
}
|
|
61
|
+
return { schemaVersion: 1, configuration: parsePublishingConfiguration(value.configuration, { allowLoopback }), policyRevision: value.policyRevision, solutionId: value.solutionId, packageName: value.packageName, limits };
|
|
62
|
+
}
|
|
63
|
+
export const publishingIntentBytes = value => new TextEncoder().encode(JSON.stringify(parsePublishingIntent(value)));
|
|
64
|
+
export function parsePublishingStatus(value) {
|
|
65
|
+
if (!protocolRecord(value, ['schemaVersion', 'requestId', 'projectId', 'intentSha256', 'state', 'sideEffects', 'missingFiles'], ['activation', 'error']) || value.schemaVersion !== 1 || !publishingRequestId(value.requestId) || !publishingIdentifier(value.projectId) || !publishingDigest(value.intentSha256) || !member(value.state, ['uploading', 'queued', 'deploying', 'registered', 'awaiting-acceptance', 'active', 'failed', 'unknown', 'abandoned', 'superseded']) || !member(value.sideEffects, ['none', 'pending', 'unknown', 'closed']) || !Array.isArray(value.missingFiles) || value.missingFiles.length > 10000)
|
|
66
|
+
throw publishingError('STATUS_INVALID');
|
|
67
|
+
const names = new Set(), missingFiles = value.missingFiles.map(file => {
|
|
68
|
+
if (!protocolRecord(file, ['path', 'sha256', 'byteLength', 'receivedBytes']) || !publishingDigest(file.sha256) || !integer(file.byteLength, 0, 134217728) || !integer(file.receivedBytes, 0, file.byteLength))
|
|
69
|
+
throw publishingError('STATUS_INVALID');
|
|
70
|
+
let relative;
|
|
71
|
+
try {
|
|
72
|
+
if (typeof file.path !== 'string')
|
|
73
|
+
throw publishingError('STATUS_INVALID');
|
|
74
|
+
relative = validatePortableRelativePath(file.path);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw publishingError('STATUS_INVALID');
|
|
78
|
+
}
|
|
79
|
+
if (names.has(relative))
|
|
80
|
+
throw publishingError('STATUS_INVALID');
|
|
81
|
+
names.add(relative);
|
|
82
|
+
return { path: relative, sha256: file.sha256, byteLength: file.byteLength, receivedBytes: file.receivedBytes };
|
|
83
|
+
});
|
|
84
|
+
if (value.state === 'active' && (!value.activation || value.sideEffects !== 'closed' || missingFiles.length))
|
|
85
|
+
throw publishingError('STATUS_INVALID');
|
|
86
|
+
let activation;
|
|
87
|
+
if (value.activation !== undefined) {
|
|
88
|
+
if (!record(value.activation))
|
|
89
|
+
throw publishingError('STATUS_INVALID');
|
|
90
|
+
const encoded = JSON.stringify(value.activation);
|
|
91
|
+
if (new TextEncoder().encode(encoded).byteLength > 1048576)
|
|
92
|
+
throw publishingError('STATUS_INVALID');
|
|
93
|
+
const cloned = structuredClone(value.activation);
|
|
94
|
+
if (!jsonValue(cloned))
|
|
95
|
+
throw publishingError('STATUS_INVALID');
|
|
96
|
+
activation = cloned;
|
|
97
|
+
}
|
|
98
|
+
let error;
|
|
99
|
+
if (value.error !== undefined) {
|
|
100
|
+
if (!protocolRecord(value.error, ['code']) || typeof value.error.code !== 'string' || !/^[A-Z][A-Z0-9_]{1,95}$/.test(value.error.code))
|
|
101
|
+
throw publishingError('STATUS_INVALID');
|
|
102
|
+
error = { code: value.error.code };
|
|
103
|
+
}
|
|
104
|
+
return { schemaVersion: 1, requestId: value.requestId, projectId: value.projectId, intentSha256: value.intentSha256, state: value.state, sideEffects: value.sideEffects, missingFiles, ...(activation !== undefined ? { activation } : {}), ...(error ? { error } : {}) };
|
|
105
|
+
}
|