@xlinklight/testkit 7.0.0-rc.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +171 -169
- package/package.json +11 -4
- package/src/architecture-database.d.mts +36 -36
- package/src/architecture-database.mjs +64 -64
- package/src/artifact-observation.mjs +50 -50
- package/src/browser-lifecycle.mjs +45 -45
- package/src/cloudflare-browser.mjs +41 -41
- package/src/cloudflare-pages.d.mts +34 -34
- package/src/cloudflare-pages.mjs +170 -170
- package/src/cloudflare-provider-http.mjs +32 -32
- package/src/cluster-directory.d.mts +16 -16
- package/src/cluster-directory.mjs +90 -90
- package/src/core-publishing.d.mts +75 -75
- package/src/core-publishing.mjs +214 -214
- package/src/dev-command-runner.mjs +97 -97
- package/src/fixture-path.mjs +19 -19
- package/src/function-admission.d.mts +1 -1
- package/src/function-admission.mjs +58 -58
- package/src/host-artifact.mjs +32 -32
- package/src/host-stop.mjs +15 -15
- package/src/lifecycle-trace.mjs +32 -32
- package/src/managed-native-fixture.d.mts +84 -84
- package/src/managed-native-fixture.mjs +209 -209
- package/src/native-fixture.mjs +125 -125
- package/src/native-platform.mjs +56 -56
- package/src/operator-accounts.mjs +103 -103
- package/src/owned-process.mjs +75 -75
- package/src/owner-build-cli.mjs +3 -4
- package/src/owner-database.mjs +215 -215
- package/src/owner-deployment-definition.mjs +31 -0
- package/src/owner-deployment.d.mts +32 -0
- package/src/owner-deployment.mjs +105 -0
- package/src/owner-operator-build.mjs +63 -33
- package/src/owner-production-browser.mjs +215 -215
- package/src/owner-production-instances.mjs +41 -41
- package/src/owner-production.d.mts +114 -104
- package/src/owner-production.mjs +350 -338
- package/src/owner-worker-build.mjs +83 -83
- package/src/prebuilt-output.d.mts +2 -2
- package/src/prebuilt-output.mjs +104 -104
- package/src/production-hosts.mjs +38 -38
- package/src/publisher-acceptance-host-cli.mjs +12 -5
- package/src/release-build.mjs +71 -71
- package/src/release-control.mjs +45 -45
- package/src/release-coordinator.d.mts +9 -9
- package/src/release-coordinator.mjs +222 -222
- package/src/release-credentials.d.mts +8 -8
- package/src/release-credentials.mjs +97 -97
- package/src/release-mutex.mjs +38 -38
- package/src/release-operator.d.mts +6 -6
- package/src/release-operator.mjs +59 -59
- package/src/release-supabase.d.mts +7 -7
- package/src/release-supabase.mjs +37 -37
- package/src/release-vercel.d.mts +22 -22
- package/src/release-vercel.mjs +51 -51
- package/src/release-writer.d.mts +6 -6
- package/src/release-writer.mjs +172 -172
- package/src/retained-postgres-shutdown.d.mts +51 -51
- package/src/retained-postgres-shutdown.mjs +262 -262
- package/src/temporary-acquisition.mjs +62 -62
- package/src/temporary-scope.d.mts +47 -47
- package/src/temporary-scope.mjs +268 -268
- package/src/worker-artifact.mjs +214 -214
package/src/temporary-scope.mjs
CHANGED
|
@@ -1,268 +1,268 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import {randomUUID} from 'node:crypto';
|
|
4
|
-
import {acquireTemporaryScope} from './temporary-acquisition.mjs';
|
|
5
|
-
|
|
6
|
-
const metadataLimit = 8192;
|
|
7
|
-
const fail = code => { throw Error(code); };
|
|
8
|
-
const same = (a, b) => a?.path === b?.path && a?.dev === b?.dev && a?.ino === b?.ino;
|
|
9
|
-
function frozen(value) {
|
|
10
|
-
if (value && typeof value === 'object') { for (const child of Object.values(value)) frozen(child); Object.freeze(value); }
|
|
11
|
-
return value;
|
|
12
|
-
}
|
|
13
|
-
export function temporaryChildClosed(handle) {
|
|
14
|
-
return handle.state.closed === true && !handle.state.stopError
|
|
15
|
-
&& (handle.state.stdoutEof === true || handle.child?.stdout?.readableEnded === true)
|
|
16
|
-
&& (handle.state.stderrEof === true || handle.child?.stderr?.readableEnded === true);
|
|
17
|
-
}
|
|
18
|
-
function ownerState(pid) {
|
|
19
|
-
try { process.kill(pid, 0); return 'alive'; }
|
|
20
|
-
catch (error) { return error.code === 'ESRCH' ? 'dead' : 'unknown'; }
|
|
21
|
-
}
|
|
22
|
-
function validClosureConfirmation(proof, owner) {
|
|
23
|
-
return proof && typeof proof === 'object' && Object.keys(proof).sort().join(',') === 'evidenceSha256,inputDigest,ownerToken,status'
|
|
24
|
-
&& proof.status === 'closed' && proof.ownerToken === owner.token && proof.inputDigest === owner.inputDigest
|
|
25
|
-
&& typeof proof.evidenceSha256 === 'string' && /^[a-f0-9]{64}$/.test(proof.evidenceSha256);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// One admitted payload per label. This journal owns new attempts only; it never
|
|
29
|
-
// adopts an unregistered historical directory or a package-manager store.
|
|
30
|
-
export function createTemporaryScope({root, scope, label, maximumBytes, inputDigest = null, requiresClosureProof = false, filesystem = fs, probeOwner = ownerState, confirmPreviousClosure}) {
|
|
31
|
-
const io = filesystem, repository = path.resolve(root), directory = path.resolve(scope);
|
|
32
|
-
const relative = path.relative(path.join(repository, 'tmp'), directory);
|
|
33
|
-
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) fail('TEMPORARY_SCOPE_OUTSIDE_ROOT');
|
|
34
|
-
if (relative.split(path.sep).some(part => ['consumer-pnpm-store', 'node_modules', '.git'].includes(part))) fail('TEMPORARY_SCOPE_PROTECTED');
|
|
35
|
-
if (!/^[a-z][a-z0-9-]*$/.test(label) || !Number.isSafeInteger(maximumBytes) || maximumBytes <= 0) fail('TEMPORARY_SCOPE_INVALID');
|
|
36
|
-
if (inputDigest !== null && !/^[a-f0-9]{64}$/.test(inputDigest)) fail('TEMPORARY_INPUT_DIGEST_INVALID');
|
|
37
|
-
function realDirectory(file) {
|
|
38
|
-
for (let p = path.resolve(file);; p = path.dirname(p)) {
|
|
39
|
-
const stat = io.lstatSync(p);
|
|
40
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) fail('TEMPORARY_LINKED_DIRECTORY');
|
|
41
|
-
if (p === path.dirname(p)) break;
|
|
42
|
-
}
|
|
43
|
-
const stat = io.lstatSync(file);
|
|
44
|
-
return {path: path.resolve(file), dev: String(stat.dev), ino: String(stat.ino)};
|
|
45
|
-
}
|
|
46
|
-
realDirectory(repository);
|
|
47
|
-
for (let p = directory; p !== repository; p = path.dirname(p)) {
|
|
48
|
-
if (io.existsSync(p)) realDirectory(p);
|
|
49
|
-
}
|
|
50
|
-
if (!io.existsSync(directory)) io.mkdirSync(directory, {recursive: true, mode: 0o700});
|
|
51
|
-
const rootIdentity = realDirectory(repository), scopeIdentity = realDirectory(directory);
|
|
52
|
-
const journal = path.join(directory, label + '-owner.json'), closeout = path.join(directory, label + '-closeout.json');
|
|
53
|
-
const prefix = label + '-';
|
|
54
|
-
const slot = path.join(directory, label + '-slot');
|
|
55
|
-
function verifyScope() {
|
|
56
|
-
if (!same(rootIdentity, realDirectory(repository)) || !same(scopeIdentity, realDirectory(directory))) fail('TEMPORARY_SCOPE_IDENTITY_CHANGED');
|
|
57
|
-
}
|
|
58
|
-
function write(file, value, exclusive = false) {
|
|
59
|
-
verifyScope();
|
|
60
|
-
const body = JSON.stringify(value) + '\n';
|
|
61
|
-
if (Buffer.byteLength(body) > metadataLimit) fail('TEMPORARY_METADATA_LIMIT');
|
|
62
|
-
if (io.existsSync(file)) {
|
|
63
|
-
const stat = io.lstatSync(file);
|
|
64
|
-
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) fail('TEMPORARY_METADATA_CHANGED');
|
|
65
|
-
}
|
|
66
|
-
io.writeFileSync(file, body, {mode: 0o600, flag: exclusive ? 'wx' : 'w'});
|
|
67
|
-
}
|
|
68
|
-
function readDocument(file = journal) {
|
|
69
|
-
verifyScope();
|
|
70
|
-
const before = io.lstatSync(file);
|
|
71
|
-
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
|
|
72
|
-
const body = io.readFileSync(file, 'utf8'), after = io.lstatSync(file);
|
|
73
|
-
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || Buffer.byteLength(body) !== after.size) fail('TEMPORARY_METADATA_CHANGED');
|
|
74
|
-
return {value: JSON.parse(body), body, identity: {path: file, dev: String(before.dev), ino: String(before.ino)}};
|
|
75
|
-
}
|
|
76
|
-
function read(file = journal) { return readDocument(file).value; }
|
|
77
|
-
function storeVerifiedClosure(original, previous, proof) {
|
|
78
|
-
const record = {...previous, state: 'closed', closureConfirmation: proof};
|
|
79
|
-
const pending = path.join(directory, label + '-owner-' + previous.token + '.next');
|
|
80
|
-
const staged = io.existsSync(pending);
|
|
81
|
-
if (staged && io.lstatSync(pending).size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
|
|
82
|
-
write(pending, record, !staged);
|
|
83
|
-
if (readDocument(pending).body !== JSON.stringify(record) + '\n') fail('TEMPORARY_OWNER_CHANGED');
|
|
84
|
-
const current = readDocument();
|
|
85
|
-
if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
|
|
86
|
-
verifyScope();
|
|
87
|
-
io.renameSync(pending, journal);
|
|
88
|
-
}
|
|
89
|
-
function attempts() {
|
|
90
|
-
return io.readdirSync(directory).filter(name => name.startsWith(prefix) && io.lstatSync(path.join(directory, name)).isDirectory());
|
|
91
|
-
}
|
|
92
|
-
function validate(record) {
|
|
93
|
-
if (record.version !== 1 || record.label !== label || !same(record.root, rootIdentity) || !same(record.scope, scopeIdentity) || !Number.isSafeInteger(record.ownerPid) || record.ownerPid <= 0 || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token ?? '') || typeof record.requiresClosureProof !== 'boolean' || !Array.isArray(record.children) || record.children.length > 64) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
94
|
-
if (record.inputDigest !== null && !/^[a-f0-9]{64}$/.test(record.inputDigest ?? '')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
95
|
-
if (record.payload && record.payload.path !== slot) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
96
|
-
if (record.children.some(pid => !Number.isSafeInteger(pid) || pid <= 0)) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
97
|
-
if (record.closureConfirmation !== undefined && (record.state !== 'closed' || !validClosureConfirmation(record.closureConfirmation, record))) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
98
|
-
}
|
|
99
|
-
function verifyPayload(record) {
|
|
100
|
-
verifyScope(); validate(record);
|
|
101
|
-
if (!record.payload || !same(record.payload, realDirectory(record.payload.path))) fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
|
|
102
|
-
}
|
|
103
|
-
function verifyEvidence(identity) {
|
|
104
|
-
verifyScope();
|
|
105
|
-
const relative = path.relative(path.join(repository, 'tmp'), identity?.path ?? repository);
|
|
106
|
-
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)
|
|
107
|
-
|| !same(identity, realDirectory(identity.path))) fail('TEMPORARY_EVIDENCE_CHANGED');
|
|
108
|
-
}
|
|
109
|
-
function remove(record) {
|
|
110
|
-
verifyPayload(record);
|
|
111
|
-
// Node's recursive rm unlinks internal symbolic links; it does not traverse
|
|
112
|
-
// their targets. The owned root itself must remain the original real inode.
|
|
113
|
-
io.rmSync(record.payload.path, {recursive: true});
|
|
114
|
-
}
|
|
115
|
-
let confirmedClosure;
|
|
116
|
-
function writeCloseout(value) { write(closeout, {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {}), ...value}); }
|
|
117
|
-
const release = acquireTemporaryScope({io, directory, label, probeOwner, verifyScope});
|
|
118
|
-
let acquisitionError;
|
|
119
|
-
try {
|
|
120
|
-
let previousInputMatched = false, recovery;
|
|
121
|
-
if (io.existsSync(closeout)) {
|
|
122
|
-
const previous = read(closeout);
|
|
123
|
-
if (previous.version !== 1 || previous.label !== label || !same(previous.root, rootIdentity) || !same(previous.scope, scopeIdentity)) fail('TEMPORARY_CLOSEOUT_UNKNOWN');
|
|
124
|
-
previousInputMatched = inputDigest !== null && previous.inputDigest === inputDigest && previous.status === 'success' && previous.closed === true && previous.removed === true && !io.existsSync(journal);
|
|
125
|
-
}
|
|
126
|
-
if (io.existsSync(journal)) {
|
|
127
|
-
const original = readDocument(), previous = original.value; validate(previous);
|
|
128
|
-
const found = attempts();
|
|
129
|
-
if (found.some(name => path.join(directory, name) !== previous.payload?.path)) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
|
|
130
|
-
const state = probeOwner(previous.ownerPid);
|
|
131
|
-
if (state === 'alive') fail('TEMPORARY_SCOPE_BUSY');
|
|
132
|
-
if (state !== 'dead' || previous.launching || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
133
|
-
if (previous.closureConfirmation) confirmedClosure = frozen(previous.closureConfirmation);
|
|
134
|
-
if ((previous.requiresClosureProof || previous.children.length) && previous.state !== 'closed') {
|
|
135
|
-
if (typeof confirmPreviousClosure !== 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
136
|
-
if (previous.launching !== false || !['active', 'blocked'].includes(previous.state)) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
137
|
-
verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
|
|
138
|
-
// Only a trusted local-tool owner may confirm its original resource
|
|
139
|
-
// evidence. Dead PIDs alone never prove native/tree/output closure.
|
|
140
|
-
const {token, ...metadata} = structuredClone(previous), view = frozen({...metadata, ownerToken: token});
|
|
141
|
-
try {
|
|
142
|
-
const confirmation = confirmPreviousClosure(view);
|
|
143
|
-
if (confirmation instanceof Promise) { void confirmation.catch(() => {}); fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
|
|
144
|
-
if (!confirmation || typeof confirmation !== 'object' || typeof confirmation.then === 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
145
|
-
const proof = structuredClone(confirmation);
|
|
146
|
-
if (!validClosureConfirmation(proof, previous)) fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
147
|
-
confirmedClosure = frozen(proof);
|
|
148
|
-
} catch { fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
|
|
149
|
-
verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
|
|
150
|
-
if (probeOwner(previous.ownerPid) !== 'dead' || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
151
|
-
// Persist the bound closure before touching the payload. A later
|
|
152
|
-
// acquisition can finish cleanup even if this owner stops mid-closeout.
|
|
153
|
-
const current = readDocument();
|
|
154
|
-
if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
|
|
155
|
-
storeVerifiedClosure(original, previous, confirmedClosure);
|
|
156
|
-
}
|
|
157
|
-
if (previous.payload && io.existsSync(previous.payload.path)) remove(previous);
|
|
158
|
-
else if (previous.payload && previous.state !== 'closed') fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
|
|
159
|
-
recovery = {status: 'recovered', ownerPid: previous.ownerPid, inputDigest: previous.inputDigest, removed: true, ...(confirmedClosure ? {closureConfirmation: confirmedClosure} : {})};
|
|
160
|
-
writeCloseout(recovery);
|
|
161
|
-
io.unlinkSync(journal);
|
|
162
|
-
}
|
|
163
|
-
if (attempts().length) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
|
|
164
|
-
const record = {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ownerPid: process.pid, token: randomUUID(), payload: null, children: [], launching: false, requiresClosureProof, state: 'allocating'};
|
|
165
|
-
write(journal, record, true);
|
|
166
|
-
let completed;
|
|
167
|
-
function verify() {
|
|
168
|
-
const stored = read();
|
|
169
|
-
if (stored.token !== record.token || JSON.stringify(stored) !== JSON.stringify(record)) fail('TEMPORARY_OWNER_CHANGED');
|
|
170
|
-
verifyPayload(record);
|
|
171
|
-
}
|
|
172
|
-
function finish({status, closed}) {
|
|
173
|
-
if (completed) return completed;
|
|
174
|
-
verify();
|
|
175
|
-
if (closed !== true || record.launching) {
|
|
176
|
-
record.state = 'blocked'; write(journal, record);
|
|
177
|
-
writeCloseout({status: 'closure-unknown', removed: false, closed: false});
|
|
178
|
-
fail('TEMPORARY_CLOSURE_UNKNOWN');
|
|
179
|
-
}
|
|
180
|
-
record.state = 'closed'; write(journal, record);
|
|
181
|
-
try { remove(record); }
|
|
182
|
-
catch (error) {
|
|
183
|
-
writeCloseout({status: 'cleanup-failed', removed: false, closed: true, error: String(error.code ?? error.message).slice(0, 512)});
|
|
184
|
-
throw error;
|
|
185
|
-
}
|
|
186
|
-
completed = Object.freeze({version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, status: String(status).slice(0, 64), directory: record.payload.path, ownerPid: record.ownerPid, closed: true, removed: true, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {})});
|
|
187
|
-
writeCloseout(completed); io.unlinkSync(journal);
|
|
188
|
-
return completed;
|
|
189
|
-
}
|
|
190
|
-
try {
|
|
191
|
-
io.mkdirSync(slot, {mode: 0o700});
|
|
192
|
-
record.payload = realDirectory(slot); record.state = 'active'; write(journal, record);
|
|
193
|
-
writeCloseout({status: 'active', closed: false, removed: false});
|
|
194
|
-
} catch (error) {
|
|
195
|
-
try {
|
|
196
|
-
if (record.payload) { write(journal, record); finish({status: 'initialization-failed', closed: true}); }
|
|
197
|
-
else { writeCloseout({status: 'initialization-failed', removed: false, closed: false}); io.unlinkSync(journal); }
|
|
198
|
-
} catch (cleanupError) { error.cleanupError = cleanupError; }
|
|
199
|
-
throw error;
|
|
200
|
-
}
|
|
201
|
-
return {
|
|
202
|
-
directory: record.payload.path, token: record.token, verify, finish, previousInputMatched, recovery,
|
|
203
|
-
registerEvidence(directory) { verify(); if (record.evidence) fail('TEMPORARY_EVIDENCE_ALREADY_REGISTERED'); const identity = realDirectory(directory); verifyEvidence(identity); record.evidence = identity; write(journal, record); },
|
|
204
|
-
beginLaunch() { verify(); if (record.launching || record.children.length >= 64) fail('TEMPORARY_CHILD_LIMIT'); record.launching = true; write(journal, record); },
|
|
205
|
-
trackPid(pid) { verify(); if (!Number.isSafeInteger(pid) || pid <= 0) fail('TEMPORARY_CHILD_IDENTITY_UNKNOWN'); record.children.push(pid); record.launching = false; write(journal, record); },
|
|
206
|
-
checkBudget() {
|
|
207
|
-
verify(); let bytes = 0, entries = 0; const stack = [record.payload.path];
|
|
208
|
-
while (stack.length) {
|
|
209
|
-
if (++entries > 100000) fail('TEMPORARY_ENTRY_LIMIT');
|
|
210
|
-
const file = stack.pop(), stat = io.lstatSync(file);
|
|
211
|
-
if (stat.isSymbolicLink()) bytes += Buffer.byteLength(io.readlinkSync(file));
|
|
212
|
-
else if (stat.isDirectory()) for (const name of io.readdirSync(file)) stack.push(path.join(file, name));
|
|
213
|
-
else if (stat.isFile()) bytes += stat.size;
|
|
214
|
-
else fail('TEMPORARY_FILE_TYPE_UNKNOWN');
|
|
215
|
-
if (bytes > maximumBytes) fail('TEMPORARY_BUDGET_EXCEEDED');
|
|
216
|
-
}
|
|
217
|
-
verify(); return {bytes, entries};
|
|
218
|
-
},
|
|
219
|
-
};
|
|
220
|
-
} catch (error) { acquisitionError = error; throw error; }
|
|
221
|
-
finally {
|
|
222
|
-
try { release(); }
|
|
223
|
-
catch (releaseError) { if (acquisitionError) acquisitionError.releaseError = releaseError; else throw releaseError; }
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// Ordinary verification keeps one bounded result. Generated fixtures and tool
|
|
228
|
-
// output belong to the fixed payload; an unresolved owner blocks another run.
|
|
229
|
-
export function createVerificationRun({root,scope,label,maximumBytes,inputDigest=null,filesystem=fs,probeOwner,confirmPreviousClosure}) {
|
|
230
|
-
const io=filesystem,owner=createTemporaryScope({root,scope,label,maximumBytes,inputDigest,requiresClosureProof:true,filesystem:io,probeOwner,confirmPreviousClosure});
|
|
231
|
-
const resultFile=path.join(path.resolve(scope),label+'-results.json');
|
|
232
|
-
const stat=io.lstatSync(path.resolve(scope));
|
|
233
|
-
const binding={version:1,label,root:path.resolve(root),scope:path.resolve(scope),dev:String(stat.dev),ino:String(stat.ino)};
|
|
234
|
-
function validateResult(){
|
|
235
|
-
if(!io.existsSync(resultFile))return false;
|
|
236
|
-
const before=io.lstatSync(resultFile);
|
|
237
|
-
if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1||before.size>65536)fail('VERIFICATION_RESULT_CHANGED');
|
|
238
|
-
const bytes=io.readFileSync(resultFile,'utf8'),after=io.lstatSync(resultFile);
|
|
239
|
-
if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||Buffer.byteLength(bytes)!==after.size)fail('VERIFICATION_RESULT_CHANGED');
|
|
240
|
-
const previous=JSON.parse(bytes);
|
|
241
|
-
if(Object.entries(binding).some(([key,value])=>previous[key]!==value))fail('VERIFICATION_RESULT_UNOWNED');
|
|
242
|
-
return true;
|
|
243
|
-
}
|
|
244
|
-
function publish(result){
|
|
245
|
-
const body=JSON.stringify({...binding,ownerToken:owner.token,result})+'\n';
|
|
246
|
-
if(Buffer.byteLength(body)>65536)fail('VERIFICATION_RESULT_LIMIT');
|
|
247
|
-
const existed=validateResult();io.writeFileSync(resultFile,body,{flag:existed?'w':'wx',mode:0o600});
|
|
248
|
-
}
|
|
249
|
-
try{publish({status:'RUNNING',inputDigest});}catch(error){try{owner.finish({status:'initialization-failed',closed:true});}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
|
|
250
|
-
return {directory:owner.directory,resultFile,checkBudget:owner.checkBudget,finish({result,closed}){
|
|
251
|
-
owner.verify();
|
|
252
|
-
let budgetFailure;
|
|
253
|
-
try{owner.checkBudget();}catch(error){budgetFailure=error;result={...result,status:'FAIL',budgetError:String(error)};}
|
|
254
|
-
try{publish({...result,status:closed===true?'FINALIZING':'FAIL',closed,artifactsRetained:true});}
|
|
255
|
-
catch(error){if(budgetFailure){budgetFailure.publishError=error;throw budgetFailure;}throw error;}
|
|
256
|
-
let receipt;
|
|
257
|
-
try{
|
|
258
|
-
receipt=owner.finish({status:result.status==='PASS'?'success':'failure',closed});
|
|
259
|
-
publish({...result,closed:true,artifactsRetained:false});
|
|
260
|
-
}
|
|
261
|
-
catch(error){
|
|
262
|
-
try{publish({...result,status:'FAIL',closed,artifactsRetained:receipt?.removed!==true,cleanupError:String(error)});}catch(publishError){error.publishError=publishError;}
|
|
263
|
-
if(budgetFailure){budgetFailure.cleanupError=error;throw budgetFailure;}throw error;
|
|
264
|
-
}
|
|
265
|
-
if(budgetFailure)throw budgetFailure;
|
|
266
|
-
return receipt;
|
|
267
|
-
}};
|
|
268
|
-
}
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {acquireTemporaryScope} from './temporary-acquisition.mjs';
|
|
5
|
+
|
|
6
|
+
const metadataLimit = 8192;
|
|
7
|
+
const fail = code => { throw Error(code); };
|
|
8
|
+
const same = (a, b) => a?.path === b?.path && a?.dev === b?.dev && a?.ino === b?.ino;
|
|
9
|
+
function frozen(value) {
|
|
10
|
+
if (value && typeof value === 'object') { for (const child of Object.values(value)) frozen(child); Object.freeze(value); }
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
export function temporaryChildClosed(handle) {
|
|
14
|
+
return handle.state.closed === true && !handle.state.stopError
|
|
15
|
+
&& (handle.state.stdoutEof === true || handle.child?.stdout?.readableEnded === true)
|
|
16
|
+
&& (handle.state.stderrEof === true || handle.child?.stderr?.readableEnded === true);
|
|
17
|
+
}
|
|
18
|
+
function ownerState(pid) {
|
|
19
|
+
try { process.kill(pid, 0); return 'alive'; }
|
|
20
|
+
catch (error) { return error.code === 'ESRCH' ? 'dead' : 'unknown'; }
|
|
21
|
+
}
|
|
22
|
+
function validClosureConfirmation(proof, owner) {
|
|
23
|
+
return proof && typeof proof === 'object' && Object.keys(proof).sort().join(',') === 'evidenceSha256,inputDigest,ownerToken,status'
|
|
24
|
+
&& proof.status === 'closed' && proof.ownerToken === owner.token && proof.inputDigest === owner.inputDigest
|
|
25
|
+
&& typeof proof.evidenceSha256 === 'string' && /^[a-f0-9]{64}$/.test(proof.evidenceSha256);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// One admitted payload per label. This journal owns new attempts only; it never
|
|
29
|
+
// adopts an unregistered historical directory or a package-manager store.
|
|
30
|
+
export function createTemporaryScope({root, scope, label, maximumBytes, inputDigest = null, requiresClosureProof = false, filesystem = fs, probeOwner = ownerState, confirmPreviousClosure}) {
|
|
31
|
+
const io = filesystem, repository = path.resolve(root), directory = path.resolve(scope);
|
|
32
|
+
const relative = path.relative(path.join(repository, 'tmp'), directory);
|
|
33
|
+
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) fail('TEMPORARY_SCOPE_OUTSIDE_ROOT');
|
|
34
|
+
if (relative.split(path.sep).some(part => ['consumer-pnpm-store', 'node_modules', '.git'].includes(part))) fail('TEMPORARY_SCOPE_PROTECTED');
|
|
35
|
+
if (!/^[a-z][a-z0-9-]*$/.test(label) || !Number.isSafeInteger(maximumBytes) || maximumBytes <= 0) fail('TEMPORARY_SCOPE_INVALID');
|
|
36
|
+
if (inputDigest !== null && !/^[a-f0-9]{64}$/.test(inputDigest)) fail('TEMPORARY_INPUT_DIGEST_INVALID');
|
|
37
|
+
function realDirectory(file) {
|
|
38
|
+
for (let p = path.resolve(file);; p = path.dirname(p)) {
|
|
39
|
+
const stat = io.lstatSync(p);
|
|
40
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) fail('TEMPORARY_LINKED_DIRECTORY');
|
|
41
|
+
if (p === path.dirname(p)) break;
|
|
42
|
+
}
|
|
43
|
+
const stat = io.lstatSync(file);
|
|
44
|
+
return {path: path.resolve(file), dev: String(stat.dev), ino: String(stat.ino)};
|
|
45
|
+
}
|
|
46
|
+
realDirectory(repository);
|
|
47
|
+
for (let p = directory; p !== repository; p = path.dirname(p)) {
|
|
48
|
+
if (io.existsSync(p)) realDirectory(p);
|
|
49
|
+
}
|
|
50
|
+
if (!io.existsSync(directory)) io.mkdirSync(directory, {recursive: true, mode: 0o700});
|
|
51
|
+
const rootIdentity = realDirectory(repository), scopeIdentity = realDirectory(directory);
|
|
52
|
+
const journal = path.join(directory, label + '-owner.json'), closeout = path.join(directory, label + '-closeout.json');
|
|
53
|
+
const prefix = label + '-';
|
|
54
|
+
const slot = path.join(directory, label + '-slot');
|
|
55
|
+
function verifyScope() {
|
|
56
|
+
if (!same(rootIdentity, realDirectory(repository)) || !same(scopeIdentity, realDirectory(directory))) fail('TEMPORARY_SCOPE_IDENTITY_CHANGED');
|
|
57
|
+
}
|
|
58
|
+
function write(file, value, exclusive = false) {
|
|
59
|
+
verifyScope();
|
|
60
|
+
const body = JSON.stringify(value) + '\n';
|
|
61
|
+
if (Buffer.byteLength(body) > metadataLimit) fail('TEMPORARY_METADATA_LIMIT');
|
|
62
|
+
if (io.existsSync(file)) {
|
|
63
|
+
const stat = io.lstatSync(file);
|
|
64
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) fail('TEMPORARY_METADATA_CHANGED');
|
|
65
|
+
}
|
|
66
|
+
io.writeFileSync(file, body, {mode: 0o600, flag: exclusive ? 'wx' : 'w'});
|
|
67
|
+
}
|
|
68
|
+
function readDocument(file = journal) {
|
|
69
|
+
verifyScope();
|
|
70
|
+
const before = io.lstatSync(file);
|
|
71
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
|
|
72
|
+
const body = io.readFileSync(file, 'utf8'), after = io.lstatSync(file);
|
|
73
|
+
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || Buffer.byteLength(body) !== after.size) fail('TEMPORARY_METADATA_CHANGED');
|
|
74
|
+
return {value: JSON.parse(body), body, identity: {path: file, dev: String(before.dev), ino: String(before.ino)}};
|
|
75
|
+
}
|
|
76
|
+
function read(file = journal) { return readDocument(file).value; }
|
|
77
|
+
function storeVerifiedClosure(original, previous, proof) {
|
|
78
|
+
const record = {...previous, state: 'closed', closureConfirmation: proof};
|
|
79
|
+
const pending = path.join(directory, label + '-owner-' + previous.token + '.next');
|
|
80
|
+
const staged = io.existsSync(pending);
|
|
81
|
+
if (staged && io.lstatSync(pending).size > metadataLimit) fail('TEMPORARY_METADATA_CHANGED');
|
|
82
|
+
write(pending, record, !staged);
|
|
83
|
+
if (readDocument(pending).body !== JSON.stringify(record) + '\n') fail('TEMPORARY_OWNER_CHANGED');
|
|
84
|
+
const current = readDocument();
|
|
85
|
+
if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
|
|
86
|
+
verifyScope();
|
|
87
|
+
io.renameSync(pending, journal);
|
|
88
|
+
}
|
|
89
|
+
function attempts() {
|
|
90
|
+
return io.readdirSync(directory).filter(name => name.startsWith(prefix) && io.lstatSync(path.join(directory, name)).isDirectory());
|
|
91
|
+
}
|
|
92
|
+
function validate(record) {
|
|
93
|
+
if (record.version !== 1 || record.label !== label || !same(record.root, rootIdentity) || !same(record.scope, scopeIdentity) || !Number.isSafeInteger(record.ownerPid) || record.ownerPid <= 0 || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token ?? '') || typeof record.requiresClosureProof !== 'boolean' || !Array.isArray(record.children) || record.children.length > 64) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
94
|
+
if (record.inputDigest !== null && !/^[a-f0-9]{64}$/.test(record.inputDigest ?? '')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
95
|
+
if (record.payload && record.payload.path !== slot) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
96
|
+
if (record.children.some(pid => !Number.isSafeInteger(pid) || pid <= 0)) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
97
|
+
if (record.closureConfirmation !== undefined && (record.state !== 'closed' || !validClosureConfirmation(record.closureConfirmation, record))) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
98
|
+
}
|
|
99
|
+
function verifyPayload(record) {
|
|
100
|
+
verifyScope(); validate(record);
|
|
101
|
+
if (!record.payload || !same(record.payload, realDirectory(record.payload.path))) fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
|
|
102
|
+
}
|
|
103
|
+
function verifyEvidence(identity) {
|
|
104
|
+
verifyScope();
|
|
105
|
+
const relative = path.relative(path.join(repository, 'tmp'), identity?.path ?? repository);
|
|
106
|
+
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)
|
|
107
|
+
|| !same(identity, realDirectory(identity.path))) fail('TEMPORARY_EVIDENCE_CHANGED');
|
|
108
|
+
}
|
|
109
|
+
function remove(record) {
|
|
110
|
+
verifyPayload(record);
|
|
111
|
+
// Node's recursive rm unlinks internal symbolic links; it does not traverse
|
|
112
|
+
// their targets. The owned root itself must remain the original real inode.
|
|
113
|
+
io.rmSync(record.payload.path, {recursive: true});
|
|
114
|
+
}
|
|
115
|
+
let confirmedClosure;
|
|
116
|
+
function writeCloseout(value) { write(closeout, {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {}), ...value}); }
|
|
117
|
+
const release = acquireTemporaryScope({io, directory, label, probeOwner, verifyScope});
|
|
118
|
+
let acquisitionError;
|
|
119
|
+
try {
|
|
120
|
+
let previousInputMatched = false, recovery;
|
|
121
|
+
if (io.existsSync(closeout)) {
|
|
122
|
+
const previous = read(closeout);
|
|
123
|
+
if (previous.version !== 1 || previous.label !== label || !same(previous.root, rootIdentity) || !same(previous.scope, scopeIdentity)) fail('TEMPORARY_CLOSEOUT_UNKNOWN');
|
|
124
|
+
previousInputMatched = inputDigest !== null && previous.inputDigest === inputDigest && previous.status === 'success' && previous.closed === true && previous.removed === true && !io.existsSync(journal);
|
|
125
|
+
}
|
|
126
|
+
if (io.existsSync(journal)) {
|
|
127
|
+
const original = readDocument(), previous = original.value; validate(previous);
|
|
128
|
+
const found = attempts();
|
|
129
|
+
if (found.some(name => path.join(directory, name) !== previous.payload?.path)) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
|
|
130
|
+
const state = probeOwner(previous.ownerPid);
|
|
131
|
+
if (state === 'alive') fail('TEMPORARY_SCOPE_BUSY');
|
|
132
|
+
if (state !== 'dead' || previous.launching || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
133
|
+
if (previous.closureConfirmation) confirmedClosure = frozen(previous.closureConfirmation);
|
|
134
|
+
if ((previous.requiresClosureProof || previous.children.length) && previous.state !== 'closed') {
|
|
135
|
+
if (typeof confirmPreviousClosure !== 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
136
|
+
if (previous.launching !== false || !['active', 'blocked'].includes(previous.state)) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
137
|
+
verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
|
|
138
|
+
// Only a trusted local-tool owner may confirm its original resource
|
|
139
|
+
// evidence. Dead PIDs alone never prove native/tree/output closure.
|
|
140
|
+
const {token, ...metadata} = structuredClone(previous), view = frozen({...metadata, ownerToken: token});
|
|
141
|
+
try {
|
|
142
|
+
const confirmation = confirmPreviousClosure(view);
|
|
143
|
+
if (confirmation instanceof Promise) { void confirmation.catch(() => {}); fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
|
|
144
|
+
if (!confirmation || typeof confirmation !== 'object' || typeof confirmation.then === 'function') fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
145
|
+
const proof = structuredClone(confirmation);
|
|
146
|
+
if (!validClosureConfirmation(proof, previous)) fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN');
|
|
147
|
+
confirmedClosure = frozen(proof);
|
|
148
|
+
} catch { fail('TEMPORARY_CHILD_CLOSURE_UNKNOWN'); }
|
|
149
|
+
verifyPayload(previous); if (previous.evidence) verifyEvidence(previous.evidence);
|
|
150
|
+
if (probeOwner(previous.ownerPid) !== 'dead' || previous.children.some(pid => probeOwner(pid) !== 'dead')) fail('TEMPORARY_OWNER_UNKNOWN');
|
|
151
|
+
// Persist the bound closure before touching the payload. A later
|
|
152
|
+
// acquisition can finish cleanup even if this owner stops mid-closeout.
|
|
153
|
+
const current = readDocument();
|
|
154
|
+
if (!same(original.identity, current.identity) || original.body !== current.body) fail('TEMPORARY_OWNER_CHANGED');
|
|
155
|
+
storeVerifiedClosure(original, previous, confirmedClosure);
|
|
156
|
+
}
|
|
157
|
+
if (previous.payload && io.existsSync(previous.payload.path)) remove(previous);
|
|
158
|
+
else if (previous.payload && previous.state !== 'closed') fail('TEMPORARY_PAYLOAD_IDENTITY_CHANGED');
|
|
159
|
+
recovery = {status: 'recovered', ownerPid: previous.ownerPid, inputDigest: previous.inputDigest, removed: true, ...(confirmedClosure ? {closureConfirmation: confirmedClosure} : {})};
|
|
160
|
+
writeCloseout(recovery);
|
|
161
|
+
io.unlinkSync(journal);
|
|
162
|
+
}
|
|
163
|
+
if (attempts().length) fail('TEMPORARY_UNREGISTERED_ATTEMPT');
|
|
164
|
+
const record = {version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, ownerPid: process.pid, token: randomUUID(), payload: null, children: [], launching: false, requiresClosureProof, state: 'allocating'};
|
|
165
|
+
write(journal, record, true);
|
|
166
|
+
let completed;
|
|
167
|
+
function verify() {
|
|
168
|
+
const stored = read();
|
|
169
|
+
if (stored.token !== record.token || JSON.stringify(stored) !== JSON.stringify(record)) fail('TEMPORARY_OWNER_CHANGED');
|
|
170
|
+
verifyPayload(record);
|
|
171
|
+
}
|
|
172
|
+
function finish({status, closed}) {
|
|
173
|
+
if (completed) return completed;
|
|
174
|
+
verify();
|
|
175
|
+
if (closed !== true || record.launching) {
|
|
176
|
+
record.state = 'blocked'; write(journal, record);
|
|
177
|
+
writeCloseout({status: 'closure-unknown', removed: false, closed: false});
|
|
178
|
+
fail('TEMPORARY_CLOSURE_UNKNOWN');
|
|
179
|
+
}
|
|
180
|
+
record.state = 'closed'; write(journal, record);
|
|
181
|
+
try { remove(record); }
|
|
182
|
+
catch (error) {
|
|
183
|
+
writeCloseout({status: 'cleanup-failed', removed: false, closed: true, error: String(error.code ?? error.message).slice(0, 512)});
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
completed = Object.freeze({version: 1, label, root: rootIdentity, scope: scopeIdentity, inputDigest, status: String(status).slice(0, 64), directory: record.payload.path, ownerPid: record.ownerPid, closed: true, removed: true, ...(confirmedClosure ? {previousClosure: confirmedClosure} : {})});
|
|
187
|
+
writeCloseout(completed); io.unlinkSync(journal);
|
|
188
|
+
return completed;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
io.mkdirSync(slot, {mode: 0o700});
|
|
192
|
+
record.payload = realDirectory(slot); record.state = 'active'; write(journal, record);
|
|
193
|
+
writeCloseout({status: 'active', closed: false, removed: false});
|
|
194
|
+
} catch (error) {
|
|
195
|
+
try {
|
|
196
|
+
if (record.payload) { write(journal, record); finish({status: 'initialization-failed', closed: true}); }
|
|
197
|
+
else { writeCloseout({status: 'initialization-failed', removed: false, closed: false}); io.unlinkSync(journal); }
|
|
198
|
+
} catch (cleanupError) { error.cleanupError = cleanupError; }
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
directory: record.payload.path, token: record.token, verify, finish, previousInputMatched, recovery,
|
|
203
|
+
registerEvidence(directory) { verify(); if (record.evidence) fail('TEMPORARY_EVIDENCE_ALREADY_REGISTERED'); const identity = realDirectory(directory); verifyEvidence(identity); record.evidence = identity; write(journal, record); },
|
|
204
|
+
beginLaunch() { verify(); if (record.launching || record.children.length >= 64) fail('TEMPORARY_CHILD_LIMIT'); record.launching = true; write(journal, record); },
|
|
205
|
+
trackPid(pid) { verify(); if (!Number.isSafeInteger(pid) || pid <= 0) fail('TEMPORARY_CHILD_IDENTITY_UNKNOWN'); record.children.push(pid); record.launching = false; write(journal, record); },
|
|
206
|
+
checkBudget() {
|
|
207
|
+
verify(); let bytes = 0, entries = 0; const stack = [record.payload.path];
|
|
208
|
+
while (stack.length) {
|
|
209
|
+
if (++entries > 100000) fail('TEMPORARY_ENTRY_LIMIT');
|
|
210
|
+
const file = stack.pop(), stat = io.lstatSync(file);
|
|
211
|
+
if (stat.isSymbolicLink()) bytes += Buffer.byteLength(io.readlinkSync(file));
|
|
212
|
+
else if (stat.isDirectory()) for (const name of io.readdirSync(file)) stack.push(path.join(file, name));
|
|
213
|
+
else if (stat.isFile()) bytes += stat.size;
|
|
214
|
+
else fail('TEMPORARY_FILE_TYPE_UNKNOWN');
|
|
215
|
+
if (bytes > maximumBytes) fail('TEMPORARY_BUDGET_EXCEEDED');
|
|
216
|
+
}
|
|
217
|
+
verify(); return {bytes, entries};
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
} catch (error) { acquisitionError = error; throw error; }
|
|
221
|
+
finally {
|
|
222
|
+
try { release(); }
|
|
223
|
+
catch (releaseError) { if (acquisitionError) acquisitionError.releaseError = releaseError; else throw releaseError; }
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Ordinary verification keeps one bounded result. Generated fixtures and tool
|
|
228
|
+
// output belong to the fixed payload; an unresolved owner blocks another run.
|
|
229
|
+
export function createVerificationRun({root,scope,label,maximumBytes,inputDigest=null,filesystem=fs,probeOwner,confirmPreviousClosure}) {
|
|
230
|
+
const io=filesystem,owner=createTemporaryScope({root,scope,label,maximumBytes,inputDigest,requiresClosureProof:true,filesystem:io,probeOwner,confirmPreviousClosure});
|
|
231
|
+
const resultFile=path.join(path.resolve(scope),label+'-results.json');
|
|
232
|
+
const stat=io.lstatSync(path.resolve(scope));
|
|
233
|
+
const binding={version:1,label,root:path.resolve(root),scope:path.resolve(scope),dev:String(stat.dev),ino:String(stat.ino)};
|
|
234
|
+
function validateResult(){
|
|
235
|
+
if(!io.existsSync(resultFile))return false;
|
|
236
|
+
const before=io.lstatSync(resultFile);
|
|
237
|
+
if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1||before.size>65536)fail('VERIFICATION_RESULT_CHANGED');
|
|
238
|
+
const bytes=io.readFileSync(resultFile,'utf8'),after=io.lstatSync(resultFile);
|
|
239
|
+
if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||Buffer.byteLength(bytes)!==after.size)fail('VERIFICATION_RESULT_CHANGED');
|
|
240
|
+
const previous=JSON.parse(bytes);
|
|
241
|
+
if(Object.entries(binding).some(([key,value])=>previous[key]!==value))fail('VERIFICATION_RESULT_UNOWNED');
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
function publish(result){
|
|
245
|
+
const body=JSON.stringify({...binding,ownerToken:owner.token,result})+'\n';
|
|
246
|
+
if(Buffer.byteLength(body)>65536)fail('VERIFICATION_RESULT_LIMIT');
|
|
247
|
+
const existed=validateResult();io.writeFileSync(resultFile,body,{flag:existed?'w':'wx',mode:0o600});
|
|
248
|
+
}
|
|
249
|
+
try{publish({status:'RUNNING',inputDigest});}catch(error){try{owner.finish({status:'initialization-failed',closed:true});}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
|
|
250
|
+
return {directory:owner.directory,resultFile,checkBudget:owner.checkBudget,finish({result,closed}){
|
|
251
|
+
owner.verify();
|
|
252
|
+
let budgetFailure;
|
|
253
|
+
try{owner.checkBudget();}catch(error){budgetFailure=error;result={...result,status:'FAIL',budgetError:String(error)};}
|
|
254
|
+
try{publish({...result,status:closed===true?'FINALIZING':'FAIL',closed,artifactsRetained:true});}
|
|
255
|
+
catch(error){if(budgetFailure){budgetFailure.publishError=error;throw budgetFailure;}throw error;}
|
|
256
|
+
let receipt;
|
|
257
|
+
try{
|
|
258
|
+
receipt=owner.finish({status:result.status==='PASS'?'success':'failure',closed});
|
|
259
|
+
publish({...result,closed:true,artifactsRetained:false});
|
|
260
|
+
}
|
|
261
|
+
catch(error){
|
|
262
|
+
try{publish({...result,status:'FAIL',closed,artifactsRetained:receipt?.removed!==true,cleanupError:String(error)});}catch(publishError){error.publishError=publishError;}
|
|
263
|
+
if(budgetFailure){budgetFailure.cleanupError=error;throw budgetFailure;}throw error;
|
|
264
|
+
}
|
|
265
|
+
if(budgetFailure)throw budgetFailure;
|
|
266
|
+
return receipt;
|
|
267
|
+
}};
|
|
268
|
+
}
|