@evomap/evolver-cli 2.0.1 → 2.0.8

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.
@@ -0,0 +1,2182 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, parse, posix, resolve, win32 } from 'node:path';
5
+ import { bootstrap as coreBootstrap, util } from '@evomap/evolver-core';
6
+ export const BOOTSTRAP_JOURNAL_FILE = coreBootstrap.LIFECYCLE_BOOTSTRAP_JOURNAL_FILE;
7
+ export const BOOTSTRAP_LOCK_FILE = coreBootstrap.LIFECYCLE_BOOTSTRAP_OWNER_LOCK_FILE;
8
+ export const BOOTSTRAP_SUCCESS_FILE = coreBootstrap.LIFECYCLE_BOOTSTRAP_SUCCESS_FILE;
9
+ const BOOTSTRAP_MANUAL_TRANSITION_FILE = coreBootstrap.LIFECYCLE_BOOTSTRAP_MANUAL_TRANSITION_FILE;
10
+ const BOOTSTRAP_JOURNAL_SCHEMA = 'evolver.lifecycle-bootstrap-transaction.v1';
11
+ export const LEGACY_BOOTSTRAP_REMOVAL_OPERATION = 'legacy-v907-remove';
12
+ const LEGACY_BOOTSTRAP_ABSENT_MANAGER_BINDING = 'legacy-v907-absent';
13
+ const BOOTSTRAP_REGISTRATION_INTENT_FILE = coreBootstrap.LIFECYCLE_BOOTSTRAP_REGISTRATION_INTENT_FILE;
14
+ const JOURNAL_STAGES = new Set([
15
+ 'prepared', 'installing', 'installed', 'activating', 'activated', 'committing',
16
+ 'committed', 'rollback_pending', 'rolled_back',
17
+ ]);
18
+ const TARGETS = new Set(['launchd', 'systemd', 'windows']);
19
+ const SHA256_RE = /^[0-9a-f]{64}$/;
20
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
+ const MAX_JOURNAL_BYTES = 128 * 1024;
22
+ const MAX_MARKER_BYTES = 128 * 1024;
23
+ const MAX_READINESS_BYTES = 16 * 1024;
24
+ const MAX_ARTIFACT_BYTES = 512 * 1024 * 1024;
25
+ const HOST_WINDOWS_SYSTEM_ROOT = process.env['SystemRoot']?.trim() || 'C:\\Windows';
26
+ function isErrno(error, code) {
27
+ return typeof error === 'object' && error !== null && error.code === code;
28
+ }
29
+ function filesystemEntryPresent(path) {
30
+ try {
31
+ lstatSync(path);
32
+ return true;
33
+ }
34
+ catch (error) {
35
+ if (isErrno(error, 'ENOENT'))
36
+ return false;
37
+ throw error;
38
+ }
39
+ }
40
+ function boundedText(value, maxLength) {
41
+ return typeof value === 'string'
42
+ && value.length > 0
43
+ && value.length <= maxLength
44
+ && !containsControlCharacter(value);
45
+ }
46
+ function containsControlCharacter(value) {
47
+ for (let index = 0; index < value.length; index += 1) {
48
+ const code = value.charCodeAt(index);
49
+ if (code <= 0x1f || code === 0x7f)
50
+ return true;
51
+ }
52
+ return false;
53
+ }
54
+ function trustedWindowsSystemExecutable(name) {
55
+ if (!win32.isAbsolute(HOST_WINDOWS_SYSTEM_ROOT) || /[\r\n\0]/.test(HOST_WINDOWS_SYSTEM_ROOT)) {
56
+ throw new Error('Windows SystemRoot is not an absolute trusted path');
57
+ }
58
+ return win32.join(HOST_WINDOWS_SYSTEM_ROOT, 'System32', name);
59
+ }
60
+ let bootstrapWindowsAclTrustForTest;
61
+ /** Test-only ACL dependency seam. Production callers never configure this override. */
62
+ export function _setBootstrapWindowsAclTrustForTest(assertion) {
63
+ bootstrapWindowsAclTrustForTest = assertion;
64
+ }
65
+ function assertWindowsAclChecksTrusted(checks) {
66
+ if (process.platform !== 'win32')
67
+ return;
68
+ if (bootstrapWindowsAclTrustForTest) {
69
+ bootstrapWindowsAclTrustForTest(checks);
70
+ return;
71
+ }
72
+ const serializedChecks = checks.map((check) => (`@{ Path = '${check.path.replaceAll("'", "''")}'; ParentOnly = $${check.parentOnly ? 'true' : 'false'}; OwnerCurrentOnly = $${check.ownerCurrentOnly ? 'true' : 'false'} }`)).join(', ');
73
+ const script = [
74
+ `$checks = @(${serializedChecks})`,
75
+ '$userSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
76
+ "$trustedInstaller = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'",
77
+ "$trustedOwners = @($userSid, 'S-1-5-18', 'S-1-5-32-544', $trustedInstaller)",
78
+ "$trustedWriters = @($userSid, 'S-1-5-18', 'S-1-5-32-544', $trustedInstaller, 'S-1-3-0', 'S-1-3-4')",
79
+ '$parentDanger = [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership',
80
+ '$contentDanger = [System.Security.AccessControl.FileSystemRights]::WriteData -bor [System.Security.AccessControl.FileSystemRights]::AppendData -bor [System.Security.AccessControl.FileSystemRights]::CreateFiles -bor [System.Security.AccessControl.FileSystemRights]::CreateDirectories',
81
+ 'foreach ($check in $checks) {',
82
+ ' $acl = Get-Acl -LiteralPath $check.Path',
83
+ ' $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value',
84
+ ' if (($check.OwnerCurrentOnly -and $owner -ne $userSid) -or (-not $check.OwnerCurrentOnly -and $trustedOwners -notcontains $owner)) { exit 21 }',
85
+ ' $danger = if ($check.ParentOnly) { $parentDanger } else { $parentDanger -bor $contentDanger }',
86
+ ' foreach ($rule in @($acl.Access)) {',
87
+ ' if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { continue }',
88
+ ' if (($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0) { continue }',
89
+ ' if (($rule.FileSystemRights -band $danger) -eq 0) { continue }',
90
+ ' try { $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value } catch { exit 22 }',
91
+ ' if ($trustedWriters -notcontains $sid) { exit 23 }',
92
+ ' }',
93
+ '}',
94
+ ].join('; ');
95
+ try {
96
+ execFileSync(trustedWindowsSystemExecutable('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoProfile', '-NonInteractive', '-Command', script], {
97
+ stdio: 'ignore', timeout: 10_000, windowsHide: true,
98
+ });
99
+ }
100
+ catch (error) {
101
+ throw new Error(`bootstrap Windows ACL chain is not trusted: ${checks[0]?.path ?? '<empty>'}`, { cause: error });
102
+ }
103
+ }
104
+ function assertWindowsAclTrusted(path, ownerCurrentOnly = false) {
105
+ assertWindowsAclChecksTrusted([{ path, parentOnly: false, ownerCurrentOnly }]);
106
+ }
107
+ function assertWindowsAclChainTrusted(path) {
108
+ const checks = [];
109
+ let current = resolve(path);
110
+ const root = parse(current).root;
111
+ for (;;) {
112
+ checks.push({ path: current, parentOnly: checks.length > 0 });
113
+ if (current === root)
114
+ break;
115
+ current = dirname(current);
116
+ }
117
+ assertWindowsAclChecksTrusted(checks);
118
+ }
119
+ function assertSecureStateDirectory(stateDir) {
120
+ const stat = lstatSync(stateDir);
121
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
122
+ throw new Error(`bootstrap state directory is not a trusted directory: ${stateDir}`);
123
+ }
124
+ if (process.platform === 'win32') {
125
+ assertWindowsAclChainTrusted(stateDir);
126
+ return;
127
+ }
128
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;
129
+ if (uid !== undefined && stat.uid !== uid) {
130
+ throw new Error(`bootstrap state directory has an unexpected owner: ${stateDir}`);
131
+ }
132
+ if ((stat.mode & 0o077) !== 0) {
133
+ throw new Error(`bootstrap state directory must be owner-only: ${stateDir}`);
134
+ }
135
+ assertTrustedPosixDirectoryChain(dirname(resolve(stateDir)), process.platform, uid, 'bootstrap state directory parent', true);
136
+ }
137
+ function effectivePosixUid(platform, uid) {
138
+ if (uid !== undefined)
139
+ return uid;
140
+ if (platform === process.platform && typeof process.getuid === 'function')
141
+ return process.getuid();
142
+ return undefined;
143
+ }
144
+ function assertTrustedPosixDirectoryChain(directory, platform, uid, label, initialPrivateUserAnchor = false) {
145
+ const trustedUid = effectivePosixUid(platform, uid);
146
+ if (trustedUid === undefined) {
147
+ throw new Error(`${label} owner cannot be verified`);
148
+ }
149
+ let current = resolve(directory);
150
+ const root = parse(current).root;
151
+ let privateUserAnchor = initialPrivateUserAnchor;
152
+ for (;;) {
153
+ try {
154
+ const stat = lstatSync(current);
155
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
156
+ throw new Error(`${label} is not a trusted directory: ${current}`);
157
+ }
158
+ if (stat.uid !== trustedUid && stat.uid !== 0) {
159
+ throw new Error(`${label} has an unexpected owner: ${current}`);
160
+ }
161
+ const writableByOthers = (stat.mode & 0o022) !== 0;
162
+ const trustedStickyAncestor = privateUserAnchor
163
+ && stat.uid === 0
164
+ && (stat.mode & 0o1000) !== 0;
165
+ if (writableByOthers && !trustedStickyAncestor) {
166
+ throw new Error(`${label} is group/world writable: ${current}`);
167
+ }
168
+ if (stat.uid === trustedUid && (stat.mode & 0o077) === 0) {
169
+ privateUserAnchor = true;
170
+ }
171
+ }
172
+ catch (error) {
173
+ if (!isErrno(error, 'ENOENT'))
174
+ throw error;
175
+ }
176
+ if (current === root)
177
+ break;
178
+ current = dirname(current);
179
+ }
180
+ }
181
+ function readBoundedRegularText(path, maxBytes, label, options = {}) {
182
+ const platform = options.platform ?? process.platform;
183
+ const uid = platform === 'win32' || typeof process.getuid !== 'function'
184
+ ? undefined
185
+ : BigInt(process.getuid());
186
+ const before = lstatSync(path, { bigint: true });
187
+ if (before.isSymbolicLink() || !before.isFile() || before.size > BigInt(maxBytes)
188
+ || (options.requireOwnerOnly === true && before.nlink !== 1n)
189
+ || before.dev <= 0n || before.ino <= 0n) {
190
+ throw new Error(`${label} is not a bounded regular file: ${path}`);
191
+ }
192
+ if (options.requireOwnerOnly === true && platform !== 'win32') {
193
+ if ((uid !== undefined && before.uid !== uid) || (before.mode & 63n) !== 0n) {
194
+ throw new Error(`${label} is not owner-only: ${path}`);
195
+ }
196
+ }
197
+ if (platform === 'win32') {
198
+ (options.assertWindowsAcl ?? assertWindowsAclTrusted)(path);
199
+ }
200
+ options.afterAclCheck?.();
201
+ const descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
202
+ try {
203
+ const opened = fstatSync(descriptor, { bigint: true });
204
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino
205
+ || (options.requireOwnerOnly === true && opened.nlink !== 1n)
206
+ || (options.requireOwnerOnly === true && platform !== 'win32'
207
+ && ((uid !== undefined && opened.uid !== uid) || (opened.mode & 63n) !== 0n))
208
+ || opened.dev <= 0n || opened.ino <= 0n || opened.size > BigInt(maxBytes)
209
+ || opened.size !== before.size || opened.mtimeNs !== before.mtimeNs
210
+ || opened.ctimeNs !== before.ctimeNs) {
211
+ throw new Error(`${label} changed while opening: ${path}`);
212
+ }
213
+ const bytes = Buffer.alloc(maxBytes + 1);
214
+ let offset = 0;
215
+ while (offset < bytes.length) {
216
+ const count = readSync(descriptor, bytes, offset, bytes.length - offset, null);
217
+ if (count === 0)
218
+ break;
219
+ offset += count;
220
+ }
221
+ if (offset > maxBytes) {
222
+ throw new Error(`${label} is not a bounded regular file: ${path}`);
223
+ }
224
+ const value = bytes.subarray(0, offset).toString('utf8');
225
+ const after = fstatSync(descriptor, { bigint: true });
226
+ if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size
227
+ || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs
228
+ || (options.requireOwnerOnly === true && after.nlink !== 1n)
229
+ || (options.requireOwnerOnly === true && platform !== 'win32'
230
+ && ((uid !== undefined && after.uid !== uid) || (after.mode & 63n) !== 0n))) {
231
+ throw new Error(`${label} changed while reading: ${path}`);
232
+ }
233
+ options.afterRead?.();
234
+ if (platform === 'win32') {
235
+ (options.assertWindowsAcl ?? assertWindowsAclTrusted)(path);
236
+ }
237
+ const settled = lstatSync(path, { bigint: true });
238
+ if (!settled.isFile() || settled.isSymbolicLink()
239
+ || settled.dev !== opened.dev || settled.ino !== opened.ino || settled.size !== opened.size
240
+ || settled.mtimeNs !== opened.mtimeNs || settled.ctimeNs !== opened.ctimeNs
241
+ || (options.requireOwnerOnly === true && settled.nlink !== 1n)
242
+ || (options.requireOwnerOnly === true && platform !== 'win32'
243
+ && ((uid !== undefined && settled.uid !== uid) || (settled.mode & 63n) !== 0n))) {
244
+ throw new Error(`${label} changed after reading: ${path}`);
245
+ }
246
+ return value;
247
+ }
248
+ finally {
249
+ closeSync(descriptor);
250
+ }
251
+ }
252
+ export function _readBoundedRegularTextForTest(path, maxBytes, label, options) {
253
+ return readBoundedRegularText(path, maxBytes, label, options);
254
+ }
255
+ function syncDirectory(path) {
256
+ let descriptor;
257
+ try {
258
+ descriptor = openSync(path, constants.O_RDONLY);
259
+ fsyncSync(descriptor);
260
+ }
261
+ catch (error) {
262
+ if (isErrno(error, 'EINVAL'))
263
+ return;
264
+ if (process.platform === 'win32' && (isErrno(error, 'EPERM') || isErrno(error, 'EACCES')))
265
+ return;
266
+ throw error;
267
+ }
268
+ finally {
269
+ if (descriptor !== undefined)
270
+ closeSync(descriptor);
271
+ }
272
+ }
273
+ export function writeDurableText(path, content, mode = 0o600) {
274
+ const directory = dirname(path);
275
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
276
+ const temporary = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
277
+ let descriptor;
278
+ try {
279
+ descriptor = openSync(temporary, 'wx', mode);
280
+ writeFileSync(descriptor, content, { encoding: 'utf8' });
281
+ fchmodSync(descriptor, mode);
282
+ fsyncSync(descriptor);
283
+ closeSync(descriptor);
284
+ descriptor = undefined;
285
+ renameSync(temporary, path);
286
+ syncDirectory(directory);
287
+ }
288
+ finally {
289
+ if (descriptor !== undefined)
290
+ closeSync(descriptor);
291
+ rmSync(temporary, { force: true });
292
+ }
293
+ }
294
+ function bootstrapArtifactOwnershipReceiptPath(path, claimPath) {
295
+ const canonicalPath = resolve(path);
296
+ const canonicalClaimPath = resolve(claimPath);
297
+ const prefix = `.${basename(canonicalPath)}.bootstrap-`;
298
+ const claimName = basename(canonicalClaimPath);
299
+ if (dirname(canonicalClaimPath) !== dirname(canonicalPath)
300
+ || !claimName.startsWith(prefix)
301
+ || !claimName.endsWith('.claim')) {
302
+ throw new Error('bootstrap artifact claim does not encode a transaction owner');
303
+ }
304
+ const transactionId = claimName.slice(prefix.length, -'.claim'.length);
305
+ if (!UUID_RE.test(transactionId)
306
+ || bootstrapArtifactClaimPath(canonicalPath, transactionId) !== canonicalClaimPath) {
307
+ throw new Error('bootstrap artifact claim does not encode a transaction owner');
308
+ }
309
+ return bootstrapArtifactRollbackPath(canonicalPath, transactionId);
310
+ }
311
+ function writeDurableExclusive(path, content, mode, publication) {
312
+ const directory = dirname(path);
313
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
314
+ const claimPath = publication?.claimPath;
315
+ if (claimPath && dirname(resolve(claimPath)) !== resolve(directory)) {
316
+ throw new Error('bootstrap artifact claim must share the artifact directory');
317
+ }
318
+ const ownershipReceipt = claimPath
319
+ ? bootstrapArtifactOwnershipReceiptPath(path, claimPath)
320
+ : undefined;
321
+ // The transaction-namespaced receipt is the staging name. It is populated and
322
+ // fsynced before an atomic hard-link publishes the canonical claim name, so a
323
+ // process death can never expose a zero or partially written claim.
324
+ const temporary = ownershipReceipt
325
+ ?? join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
326
+ let descriptor;
327
+ let stagingCreated = false;
328
+ let claimPublished = false;
329
+ try {
330
+ descriptor = openSync(temporary, 'wx', mode);
331
+ stagingCreated = true;
332
+ if (typeof content === 'string')
333
+ writeFileSync(descriptor, content, { encoding: 'utf8' });
334
+ else
335
+ writeFileSync(descriptor, content);
336
+ fchmodSync(descriptor, mode);
337
+ fsyncSync(descriptor);
338
+ if (publication && claimPath && ownershipReceipt) {
339
+ syncDirectory(directory);
340
+ const opened = fstatSync(descriptor, { bigint: true });
341
+ const receipt = lstatSync(ownershipReceipt, { bigint: true });
342
+ if (!opened.isFile() || opened.dev <= 0n || opened.ino <= 0n
343
+ || receipt.dev !== opened.dev || receipt.ino !== opened.ino) {
344
+ throw new Error('bootstrap artifact ownership receipt does not bind the staged claim');
345
+ }
346
+ linkSync(ownershipReceipt, claimPath);
347
+ syncDirectory(directory);
348
+ claimPublished = true;
349
+ const claim = lstatSync(claimPath, { bigint: true });
350
+ if (claim.dev !== opened.dev || claim.ino !== opened.ino) {
351
+ throw new Error('bootstrap artifact claim does not bind the staged ownership receipt');
352
+ }
353
+ publication.onPublished(path, claimPath);
354
+ }
355
+ closeSync(descriptor);
356
+ descriptor = undefined;
357
+ linkSync(claimPath ?? temporary, path);
358
+ syncDirectory(directory);
359
+ publication?.onPublished(path, claimPath);
360
+ if (ownershipReceipt) {
361
+ rmSync(ownershipReceipt, { force: true });
362
+ syncDirectory(directory);
363
+ }
364
+ if (claimPath)
365
+ rmSync(claimPath, { force: true });
366
+ else
367
+ rmSync(temporary, { force: true });
368
+ syncDirectory(directory);
369
+ }
370
+ finally {
371
+ if (descriptor !== undefined)
372
+ closeSync(descriptor);
373
+ if (!publication) {
374
+ rmSync(temporary, { force: true });
375
+ }
376
+ else if (stagingCreated && !claimPublished) {
377
+ // A synchronous failure before claim publication cannot require restart
378
+ // recovery; the current process still owns this unpublished staging name.
379
+ rmSync(temporary, { force: true });
380
+ syncDirectory(directory);
381
+ }
382
+ }
383
+ }
384
+ export function writeDurableTextExclusive(path, content, mode = 0o600, publication) {
385
+ writeDurableExclusive(path, content, mode, publication);
386
+ }
387
+ export function writeDurableBytesExclusive(path, content, mode = 0o600, publication) {
388
+ writeDurableExclusive(path, content, mode, publication);
389
+ }
390
+ function writeDurableJson(path, value, mode = 0o600) {
391
+ writeDurableText(path, `${JSON.stringify(value)}\n`, mode);
392
+ }
393
+ export function writeDurableJsonExclusive(path, value, mode = 0o600) {
394
+ writeDurableTextExclusive(path, `${JSON.stringify(value)}\n`, mode);
395
+ }
396
+ export function removeDurableFile(path) {
397
+ try {
398
+ rmSync(path, { force: true });
399
+ syncDirectory(dirname(path));
400
+ }
401
+ catch (error) {
402
+ if (!isErrno(error, 'ENOENT'))
403
+ throw error;
404
+ }
405
+ }
406
+ export function acquireBootstrapOwnerLock(stateDir, options = {}) {
407
+ if (!existsSync(stateDir)) {
408
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;
409
+ assertTrustedArtifactParent(join(stateDir, '.bootstrap-owner'), process.platform, uid);
410
+ }
411
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
412
+ assertSecureStateDirectory(stateDir);
413
+ const path = join(stateDir, BOOTSTRAP_LOCK_FILE);
414
+ const owner = util.acquireLock(path, { maxTries: options.maxTries ?? 2_400, waitMs: options.waitMs ?? 100 });
415
+ return bootstrapLockHandle(path, owner);
416
+ }
417
+ export function acquireBootstrapReadinessLock(stateDir, options = {}) {
418
+ assertSecureStateDirectory(stateDir);
419
+ const path = join(stateDir, coreBootstrap.LIFECYCLE_BOOTSTRAP_READINESS_LOCK_FILE);
420
+ const owner = util.acquireLock(path, { maxTries: options.maxTries ?? 500, waitMs: options.waitMs ?? 10 });
421
+ return bootstrapLockHandle(path, owner);
422
+ }
423
+ function bootstrapLockHandle(path, owner) {
424
+ const expectedBytes = Buffer.from(`${JSON.stringify({
425
+ v: 2,
426
+ pid: owner.pid,
427
+ token: owner.token,
428
+ processStart: owner.processStartIdentity,
429
+ })}\n`, 'utf8');
430
+ let receipt;
431
+ try {
432
+ receipt = readBootstrapArtifactFile(path, util.MAX_LOCK_OWNER_BYTES, { role: 'owned' });
433
+ if (!receipt.bytes.equals(expectedBytes)) {
434
+ throw new Error('bootstrap owner lock acquisition did not publish the exact owner');
435
+ }
436
+ }
437
+ catch (error) {
438
+ const released = util.releaseLock(path);
439
+ if (!released.released) {
440
+ throw new Error(`bootstrap owner lock initialization failed; release failed: ${released.reason}`, { cause: error });
441
+ }
442
+ throw error;
443
+ }
444
+ let released = false;
445
+ const assertOwned = () => {
446
+ if (released) {
447
+ throw new Error('bootstrap owner lock assertion failed: not_owned');
448
+ }
449
+ let current;
450
+ try {
451
+ current = readBootstrapArtifactFile(path, util.MAX_LOCK_OWNER_BYTES, { role: 'owned' });
452
+ }
453
+ catch {
454
+ throw new Error('bootstrap owner lock assertion failed: ownership_changed');
455
+ }
456
+ if (!current.bytes.equals(expectedBytes)
457
+ || current.identity.size !== receipt.identity.size
458
+ || current.identity.sha256 !== receipt.identity.sha256
459
+ || current.identity.device !== receipt.identity.device
460
+ || current.identity.inode !== receipt.identity.inode) {
461
+ throw new Error('bootstrap owner lock assertion failed: ownership_changed');
462
+ }
463
+ };
464
+ return {
465
+ path,
466
+ owner,
467
+ assertOwned,
468
+ release: () => {
469
+ if (released)
470
+ return;
471
+ try {
472
+ assertOwned();
473
+ }
474
+ catch {
475
+ throw new Error('bootstrap owner lock release failed: ownership_changed');
476
+ }
477
+ const result = util.releaseLock(path);
478
+ if (!result.released
479
+ || (result.reason !== 'released' && result.reason !== 'released_with_cleanup_error')) {
480
+ throw new Error(`bootstrap owner lock release failed: ${result.reason}`);
481
+ }
482
+ released = true;
483
+ },
484
+ };
485
+ }
486
+ export function createBootstrapJournal(input) {
487
+ const now = input.now ?? Date.now();
488
+ if (!Number.isSafeInteger(input.owner.pid) || input.owner.pid <= 0
489
+ || !UUID_RE.test(input.owner.token)
490
+ || !parseProcessStartIdentity(input.owner.processStartIdentity)) {
491
+ throw new Error('bootstrap transaction owner must match a validated file-lock owner');
492
+ }
493
+ const uniquePaths = [...new Set(input.artifactPaths.map((path) => resolve(path)))];
494
+ if (uniquePaths.length === 0 || uniquePaths.length > 32) {
495
+ throw new Error('bootstrap transaction must declare between 1 and 32 artifacts');
496
+ }
497
+ const transactionId = input.transactionId ?? randomUUID();
498
+ if (!UUID_RE.test(transactionId))
499
+ throw new Error('bootstrap transaction id must be a UUID');
500
+ const managerArtifactPath = resolve(input.managerArtifactPath);
501
+ if (!uniquePaths.includes(managerArtifactPath)) {
502
+ throw new Error('bootstrap manager binding must reference an owned artifact');
503
+ }
504
+ const namespacePaths = uniquePaths.flatMap((path) => [
505
+ path,
506
+ bootstrapArtifactClaimPath(path, transactionId),
507
+ bootstrapArtifactRollbackPath(path, transactionId),
508
+ ]);
509
+ const namespaceKeys = namespacePaths.map((path) => bootstrapPathKey(path, input.target));
510
+ if (new Set(namespaceKeys).size !== namespaceKeys.length) {
511
+ throw new Error('bootstrap transaction artifact namespace overlaps');
512
+ }
513
+ return {
514
+ schema: BOOTSTRAP_JOURNAL_SCHEMA,
515
+ transactionId,
516
+ owner: { ...input.owner, processStartIdentity: { ...input.owner.processStartIdentity }, acquiredAt: new Date(now).toISOString() },
517
+ target: input.target,
518
+ service: input.service,
519
+ managerBefore: 'absent',
520
+ managerBinding: { artifactPath: managerArtifactPath, kind: 'transaction' },
521
+ stage: 'prepared',
522
+ deadlineMs: input.deadlineMs,
523
+ artifacts: uniquePaths.map((path) => {
524
+ const identity = input.artifactIdentities[path];
525
+ if (!identity || !validArtifactIdentity(identity, false)) {
526
+ throw new Error(`bootstrap transaction is missing an expected artifact identity: ${path}`);
527
+ }
528
+ return {
529
+ path,
530
+ claimPath: bootstrapArtifactClaimPath(path, transactionId),
531
+ rollbackPath: bootstrapArtifactRollbackPath(path, transactionId),
532
+ before: 'absent',
533
+ identity: { ...identity },
534
+ };
535
+ }),
536
+ updatedAt: new Date(now).toISOString(),
537
+ };
538
+ }
539
+ export function bootstrapJournalFromMarker(marker, owner, deadlineMs, now = Date.now()) {
540
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0
541
+ || !UUID_RE.test(owner.token)
542
+ || !parseProcessStartIdentity(owner.processStartIdentity)) {
543
+ throw new Error('bootstrap marker recovery owner must match a validated file-lock owner');
544
+ }
545
+ return {
546
+ schema: BOOTSTRAP_JOURNAL_SCHEMA,
547
+ transactionId: marker.transactionId,
548
+ owner: { ...owner, processStartIdentity: { ...owner.processStartIdentity }, acquiredAt: new Date(now).toISOString() },
549
+ target: marker.target,
550
+ service: marker.service,
551
+ managerBefore: 'absent',
552
+ managerBinding: {
553
+ artifactPath: resolve(marker.managerArtifactPath),
554
+ kind: marker.managerBindingKind ?? 'transaction',
555
+ },
556
+ stage: 'activated',
557
+ deadlineMs,
558
+ artifacts: marker.artifacts.map((artifact) => ({
559
+ path: resolve(artifact.path),
560
+ claimPath: bootstrapArtifactClaimPath(artifact.path, marker.transactionId),
561
+ rollbackPath: bootstrapArtifactRollbackPath(artifact.path, marker.transactionId),
562
+ before: 'absent',
563
+ identity: {
564
+ size: artifact.size,
565
+ sha256: artifact.sha256,
566
+ ...(artifact.device ? { device: artifact.device } : {}),
567
+ ...(artifact.inode ? { inode: artifact.inode } : {}),
568
+ },
569
+ })),
570
+ ...(marker.preservedArtifacts && marker.preservedArtifacts.length > 0
571
+ ? { preservedArtifacts: marker.preservedArtifacts.map((artifact) => ({ ...artifact })) }
572
+ : {}),
573
+ successMarkerIdentity: bootstrapArtifactIdentityForBytes(Buffer.from(`${JSON.stringify(marker)}\n`, 'utf8')),
574
+ activationStarted: true,
575
+ updatedAt: new Date(now).toISOString(),
576
+ };
577
+ }
578
+ export function bootstrapJournalManagerArtifactPath(journal) {
579
+ if (!('artifactPath' in journal.managerBinding)) {
580
+ throw new Error('bootstrap recovery journal records an absent manager without an artifact binding');
581
+ }
582
+ return journal.managerBinding.artifactPath;
583
+ }
584
+ export function createLegacyBootstrapRemovalJournal(input) {
585
+ const now = input.now ?? Date.now();
586
+ const transactionId = randomUUID();
587
+ if (!Number.isSafeInteger(input.owner.pid) || input.owner.pid <= 0
588
+ || !UUID_RE.test(input.owner.token)
589
+ || !parseProcessStartIdentity(input.owner.processStartIdentity)
590
+ || input.artifacts.length === 0) {
591
+ throw new Error('legacy bootstrap removal receipt is invalid');
592
+ }
593
+ const artifacts = input.artifacts.map((artifact) => ({
594
+ path: resolve(artifact.path),
595
+ claimPath: bootstrapArtifactClaimPath(artifact.path, transactionId),
596
+ rollbackPath: bootstrapArtifactRollbackPath(artifact.path, transactionId),
597
+ before: 'legacy_owned',
598
+ identity: {
599
+ size: artifact.size,
600
+ sha256: artifact.sha256,
601
+ ...(artifact.device ? { device: artifact.device } : {}),
602
+ ...(artifact.inode ? { inode: artifact.inode } : {}),
603
+ },
604
+ }));
605
+ const managerArtifactPath = input.managerArtifactPath === undefined
606
+ ? undefined
607
+ : resolve(input.managerArtifactPath);
608
+ if (input.managerState === 'absent') {
609
+ if (managerArtifactPath !== undefined) {
610
+ throw new Error('absent legacy manager cannot declare an artifact binding');
611
+ }
612
+ }
613
+ else if (!managerArtifactPath
614
+ || !artifacts.some((artifact) => artifact.path === managerArtifactPath)) {
615
+ throw new Error('legacy bootstrap removal manager artifact is not owned');
616
+ }
617
+ const journal = {
618
+ schema: BOOTSTRAP_JOURNAL_SCHEMA,
619
+ transactionId,
620
+ owner: {
621
+ ...input.owner,
622
+ processStartIdentity: { ...input.owner.processStartIdentity },
623
+ acquiredAt: new Date(now).toISOString(),
624
+ },
625
+ target: input.target,
626
+ service: input.service,
627
+ managerBefore: input.managerState,
628
+ managerBinding: input.managerState === 'absent'
629
+ ? { kind: LEGACY_BOOTSTRAP_ABSENT_MANAGER_BINDING, state: 'absent' }
630
+ : {
631
+ artifactPath: managerArtifactPath,
632
+ kind: coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING,
633
+ },
634
+ operation: LEGACY_BOOTSTRAP_REMOVAL_OPERATION,
635
+ stage: 'prepared',
636
+ deadlineMs: input.deadlineMs,
637
+ artifacts,
638
+ ...(input.preservedArtifacts && input.preservedArtifacts.length > 0
639
+ ? { preservedArtifacts: input.preservedArtifacts.map((artifact) => ({ ...artifact, path: resolve(artifact.path) })) }
640
+ : {}),
641
+ activationStarted: input.managerState !== 'absent',
642
+ artifactsRestored: false,
643
+ terminalAction: 'remove_committed',
644
+ updatedAt: new Date(now).toISOString(),
645
+ };
646
+ if (!parseBootstrapJournal(journal)) {
647
+ throw new Error('legacy bootstrap removal receipt is invalid');
648
+ }
649
+ return journal;
650
+ }
651
+ export function bootstrapArtifactClaimPath(path, transactionId) {
652
+ return join(dirname(resolve(path)), `.${basename(path)}.bootstrap-${transactionId}.claim`);
653
+ }
654
+ export function bootstrapArtifactRollbackPath(path, transactionId) {
655
+ return join(dirname(resolve(path)), `.${basename(path)}.bootstrap-${transactionId}.rollback`);
656
+ }
657
+ function bootstrapArtifactStagingCleanupPath(artifact) {
658
+ return `${artifact.rollbackPath}.staging-cleanup`;
659
+ }
660
+ export function updateBootstrapJournal(journal, patch, now = Date.now()) {
661
+ const artifacts = patch.artifactsRestored === true || patch.stage === 'rolled_back'
662
+ ? journal.artifacts.map((artifact) => {
663
+ const { claimOwnership: _claimOwnership, ...restoredArtifact } = artifact;
664
+ return restoredArtifact;
665
+ })
666
+ : patch.stage === 'installing'
667
+ ? journal.artifacts.map((artifact) => (artifact.before === 'absent'
668
+ && artifact.identity?.device === undefined
669
+ && artifact.claimOwnership === undefined
670
+ ? { ...artifact, claimOwnership: { phase: 'armed' } }
671
+ : artifact))
672
+ : journal.artifacts;
673
+ return { ...journal, ...patch, artifacts, updatedAt: new Date(now).toISOString() };
674
+ }
675
+ export function bootstrapJournalPath(stateDir) {
676
+ return join(stateDir, BOOTSTRAP_JOURNAL_FILE);
677
+ }
678
+ export function bootstrapMarkerPath(stateDir) {
679
+ return join(stateDir, BOOTSTRAP_SUCCESS_FILE);
680
+ }
681
+ export function bootstrapReadinessPath(stateDir) {
682
+ return join(stateDir, coreBootstrap.LIFECYCLE_BOOTSTRAP_READINESS_FILE);
683
+ }
684
+ export function bootstrapManualTransitionPath(stateDir) {
685
+ return join(stateDir, BOOTSTRAP_MANUAL_TRANSITION_FILE);
686
+ }
687
+ function bootstrapRegistrationIntentPath(stateDir) {
688
+ return join(stateDir, BOOTSTRAP_REGISTRATION_INTENT_FILE);
689
+ }
690
+ /**
691
+ * Validate the parent's active registration token while the caller owns bootstrap-owner.lock.
692
+ * Absence, a terminal receipt, or any malformed/untrusted presentation blocks before mutation.
693
+ */
694
+ export function assertActiveBootstrapRegistrationIntentToken(stateDir, tokenValue) {
695
+ const token = coreBootstrap.parseLifecycleBootstrapRegistrationToken(tokenValue);
696
+ if (!token)
697
+ throw new Error('bootstrap registration token is invalid');
698
+ assertSecureStateDirectory(stateDir);
699
+ const path = bootstrapRegistrationIntentPath(stateDir);
700
+ let parsed;
701
+ try {
702
+ parsed = coreBootstrap.parseLifecycleBootstrapRegistrationIntentJson(readBoundedRegularText(path, coreBootstrap.MAX_LIFECYCLE_BOOTSTRAP_REGISTRATION_INTENT_BYTES, 'bootstrap registration intent', { requireOwnerOnly: true }));
703
+ }
704
+ catch (error) {
705
+ throw new Error('bootstrap registration intent is unavailable or untrusted', { cause: error });
706
+ }
707
+ if (!parsed || parsed.state !== 'registering' || parsed.owner.token !== token) {
708
+ throw new Error('bootstrap registration intent does not authorize this child');
709
+ }
710
+ return parsed;
711
+ }
712
+ export function readBootstrapManualTransition(stateDir) {
713
+ const path = bootstrapManualTransitionPath(stateDir);
714
+ try {
715
+ assertSecureStateDirectory(stateDir);
716
+ const transition = coreBootstrap.parseLifecycleBootstrapManualTransitionJson(readBoundedRegularText(path, coreBootstrap.MAX_LIFECYCLE_BOOTSTRAP_MANUAL_TRANSITION_BYTES, 'bootstrap manual-transition tombstone', { requireOwnerOnly: true }));
717
+ if (!transition) {
718
+ throw new Error(`bootstrap manual-transition tombstone is corrupt: ${path}`);
719
+ }
720
+ return transition;
721
+ }
722
+ catch (error) {
723
+ if (isErrno(error, 'ENOENT'))
724
+ return undefined;
725
+ throw error;
726
+ }
727
+ }
728
+ function sameBootstrapManualTransitionSource(transition, source) {
729
+ return transition.removedTransactionId === source.transactionId
730
+ && transition.target === source.target
731
+ && transition.service === source.service;
732
+ }
733
+ /**
734
+ * Persist the operator's remove -> explicit install handoff before any committed
735
+ * manager or artifact mutation. A matching tombstone is an idempotent retry.
736
+ */
737
+ export function ensureBootstrapManualTransition(stateDir, source, now = Date.now()) {
738
+ assertSecureStateDirectory(stateDir);
739
+ const existing = readBootstrapManualTransition(stateDir);
740
+ if (existing) {
741
+ if (!sameBootstrapManualTransitionSource(existing, source)) {
742
+ throw new Error('bootstrap manual-transition tombstone belongs to another committed service');
743
+ }
744
+ return existing;
745
+ }
746
+ const transition = {
747
+ schema: coreBootstrap.LIFECYCLE_BOOTSTRAP_MANUAL_TRANSITION_SCHEMA,
748
+ transitionId: randomUUID(),
749
+ removedTransactionId: source.transactionId,
750
+ target: source.target,
751
+ service: source.service,
752
+ createdAt: new Date(now).toISOString(),
753
+ };
754
+ if (!coreBootstrap.parseLifecycleBootstrapManualTransition(transition)) {
755
+ throw new Error('bootstrap refused to persist an invalid manual-transition tombstone');
756
+ }
757
+ const path = bootstrapManualTransitionPath(stateDir);
758
+ try {
759
+ writeDurableJsonExclusive(path, transition);
760
+ }
761
+ catch (error) {
762
+ if (!filesystemEntryPresent(path))
763
+ throw error;
764
+ const raced = readBootstrapManualTransition(stateDir);
765
+ if (!raced || !sameBootstrapManualTransitionSource(raced, source))
766
+ throw error;
767
+ return raced;
768
+ }
769
+ const durable = readBootstrapManualTransition(stateDir);
770
+ if (!durable || durable.transitionId !== transition.transitionId) {
771
+ throw new Error('bootstrap manual-transition tombstone publication is unconfirmed');
772
+ }
773
+ return durable;
774
+ }
775
+ export function removeBootstrapManualTransition(stateDir, transitionId) {
776
+ const transition = readBootstrapManualTransition(stateDir);
777
+ if (!transition || transition.transitionId !== transitionId) {
778
+ throw new Error('bootstrap refused to consume a manual-transition tombstone it does not own');
779
+ }
780
+ const path = bootstrapManualTransitionPath(stateDir);
781
+ removeDurableFile(path);
782
+ if (filesystemEntryPresent(path)) {
783
+ throw new Error('bootstrap manual-transition tombstone retirement is unconfirmed');
784
+ }
785
+ }
786
+ function bootstrapCanonicalQuarantinePath(stateDir, kind, transactionId) {
787
+ if (!UUID_RE.test(transactionId))
788
+ throw new Error('bootstrap transaction id must be a UUID');
789
+ return join(resolve(stateDir), `.bootstrap-${kind}.${transactionId}.quarantine`);
790
+ }
791
+ function bootstrapPathKey(path, target) {
792
+ return process.platform === 'win32' || target === 'windows' ? path.toLowerCase() : path;
793
+ }
794
+ function bootstrapArtifactNamespaceIsUnique(artifacts, target) {
795
+ const keys = artifacts.flatMap((artifact) => [
796
+ artifact.path,
797
+ artifact.claimPath,
798
+ artifact.rollbackPath,
799
+ bootstrapArtifactStagingCleanupPath(artifact),
800
+ ])
801
+ .map((path) => bootstrapPathKey(path, target));
802
+ return new Set(keys).size === keys.length;
803
+ }
804
+ function protectedBootstrapStatePathKeys(stateDir, target) {
805
+ return new Set([
806
+ bootstrapJournalPath(stateDir),
807
+ bootstrapMarkerPath(stateDir),
808
+ bootstrapReadinessPath(stateDir),
809
+ bootstrapManualTransitionPath(stateDir),
810
+ bootstrapRegistrationIntentPath(stateDir),
811
+ join(stateDir, coreBootstrap.LIFECYCLE_BOOTSTRAP_REGISTRATION_INTENT_TERMINAL_FILE),
812
+ join(stateDir, coreBootstrap.LIFECYCLE_BOOTSTRAP_REGISTRATION_INTENT_CLEARING_FILE),
813
+ join(stateDir, coreBootstrap.LIFECYCLE_BOOTSTRAP_READINESS_LOCK_FILE),
814
+ join(stateDir, BOOTSTRAP_LOCK_FILE),
815
+ ].map((path) => bootstrapPathKey(resolve(path), target)));
816
+ }
817
+ function assertBootstrapPathsDoNotOwnProtectedState(stateDir, target, paths, label) {
818
+ const protectedPaths = protectedBootstrapStatePathKeys(stateDir, target);
819
+ if (paths.some((path) => protectedPaths.has(bootstrapPathKey(path, target)))) {
820
+ throw new Error(`${label} owns a protected state path`);
821
+ }
822
+ }
823
+ function assertBootstrapCanonicalQuarantineLayout(stateDir, journal) {
824
+ const entries = journal.canonicalQuarantine ?? [];
825
+ if (entries.length === 0)
826
+ return;
827
+ const kinds = entries.map((entry) => entry.kind);
828
+ if (new Set(kinds).size !== kinds.length) {
829
+ throw new Error('bootstrap canonical quarantine contains duplicate state kinds');
830
+ }
831
+ const artifactNamespace = new Set(journal.artifacts.flatMap((artifact) => [
832
+ artifact.path,
833
+ artifact.claimPath,
834
+ artifact.rollbackPath,
835
+ bootstrapArtifactStagingCleanupPath(artifact),
836
+ ]).map((path) => bootstrapPathKey(path, journal.target)));
837
+ for (const entry of entries) {
838
+ const expectedSource = resolve(entry.kind === 'marker'
839
+ ? bootstrapMarkerPath(stateDir)
840
+ : bootstrapReadinessPath(stateDir));
841
+ const expectedQuarantine = bootstrapCanonicalQuarantinePath(stateDir, entry.kind, journal.transactionId);
842
+ if (entry.sourcePath !== expectedSource || entry.quarantinePath !== expectedQuarantine) {
843
+ throw new Error('bootstrap canonical quarantine path is outside its durable state namespace');
844
+ }
845
+ if (artifactNamespace.has(bootstrapPathKey(entry.sourcePath, journal.target))
846
+ || artifactNamespace.has(bootstrapPathKey(entry.quarantinePath, journal.target))) {
847
+ throw new Error('bootstrap artifact namespace overlaps canonical quarantine state');
848
+ }
849
+ }
850
+ }
851
+ export function writeBootstrapJournal(stateDir, journal) {
852
+ if (!parseBootstrapJournal(journal)) {
853
+ throw new Error('bootstrap refused to persist an invalid recovery journal');
854
+ }
855
+ assertBootstrapPathsDoNotOwnProtectedState(stateDir, journal.target, [
856
+ ...journal.artifacts.flatMap((artifact) => [
857
+ artifact.path,
858
+ artifact.claimPath,
859
+ artifact.rollbackPath,
860
+ bootstrapArtifactStagingCleanupPath(artifact),
861
+ ]),
862
+ ...(journal.preservedArtifacts ?? []).map((artifact) => artifact.path),
863
+ ], 'bootstrap recovery journal');
864
+ assertBootstrapCanonicalQuarantineLayout(stateDir, journal);
865
+ writeDurableJson(bootstrapJournalPath(stateDir), journal, 0o600);
866
+ }
867
+ export function removeBootstrapJournal(stateDir) {
868
+ removeDurableFile(bootstrapJournalPath(stateDir));
869
+ }
870
+ function parseArtifact(value) {
871
+ if (!value || typeof value !== 'object' || Array.isArray(value))
872
+ return undefined;
873
+ const record = value;
874
+ const claimOwnership = parseArtifactClaimOwnership(record['claimOwnership']);
875
+ if ((record['claimOwnership'] !== undefined && claimOwnership === undefined)
876
+ || !exactRecordKeys(record, [
877
+ 'path',
878
+ 'claimPath',
879
+ 'rollbackPath',
880
+ 'before',
881
+ 'identity',
882
+ ...(record['claimOwnership'] === undefined ? [] : ['claimOwnership']),
883
+ ])
884
+ || !boundedText(record['path'], 4_096) || !isAbsolute(record['path'])
885
+ || resolve(record['path']) !== record['path']
886
+ || (record['before'] !== 'absent' && record['before'] !== 'legacy_owned'))
887
+ return undefined;
888
+ if (!boundedText(record['claimPath'], 4_096) || !isAbsolute(record['claimPath'])
889
+ || resolve(record['claimPath']) !== record['claimPath'])
890
+ return undefined;
891
+ if (!boundedText(record['rollbackPath'], 4_096) || !isAbsolute(record['rollbackPath'])
892
+ || resolve(record['rollbackPath']) !== record['rollbackPath'])
893
+ return undefined;
894
+ const identity = record['identity'];
895
+ if (!identity || typeof identity !== 'object' || Array.isArray(identity))
896
+ return undefined;
897
+ const identityRecord = identity;
898
+ const identityKeys = identityRecord['device'] === undefined
899
+ ? ['size', 'sha256']
900
+ : ['size', 'sha256', 'device', 'inode'];
901
+ if (!exactRecordKeys(identityRecord, identityKeys)
902
+ || !validArtifactIdentity(identityRecord, true)
903
+ || (record['before'] === 'legacy_owned'
904
+ && (typeof identityRecord['device'] !== 'string'
905
+ || typeof identityRecord['inode'] !== 'string')))
906
+ return undefined;
907
+ return {
908
+ path: record['path'],
909
+ claimPath: record['claimPath'],
910
+ rollbackPath: record['rollbackPath'],
911
+ before: record['before'],
912
+ identity: {
913
+ size: identityRecord['size'],
914
+ sha256: identityRecord['sha256'],
915
+ ...(typeof identityRecord['device'] === 'string' ? { device: identityRecord['device'] } : {}),
916
+ ...(typeof identityRecord['inode'] === 'string' ? { inode: identityRecord['inode'] } : {}),
917
+ },
918
+ ...(claimOwnership ? { claimOwnership } : {}),
919
+ };
920
+ }
921
+ function parseArtifactClaimOwnership(value) {
922
+ if (!value || typeof value !== 'object' || Array.isArray(value))
923
+ return undefined;
924
+ const record = value;
925
+ if (record['phase'] === 'armed') {
926
+ return exactRecordKeys(record, ['phase']) ? { phase: 'armed' } : undefined;
927
+ }
928
+ if (record['phase'] !== 'created'
929
+ || !exactRecordKeys(record, ['phase', 'device', 'inode'])
930
+ || typeof record['device'] !== 'string'
931
+ || typeof record['inode'] !== 'string'
932
+ || !/^[0-9]+$/.test(record['device'])
933
+ || !/^[0-9]+$/.test(record['inode'])
934
+ || BigInt(record['device']) <= 0n
935
+ || BigInt(record['inode']) <= 0n) {
936
+ return undefined;
937
+ }
938
+ return { phase: 'created', device: record['device'], inode: record['inode'] };
939
+ }
940
+ function exactRecordKeys(record, expected) {
941
+ const actual = Object.keys(record).sort();
942
+ const sortedExpected = [...expected].sort();
943
+ return actual.length === sortedExpected.length
944
+ && actual.every((key, index) => key === sortedExpected[index]);
945
+ }
946
+ function parsePreservedArtifact(value) {
947
+ if (!value || typeof value !== 'object' || Array.isArray(value))
948
+ return undefined;
949
+ const record = value;
950
+ if (!exactRecordKeys(record, ['path', 'size', 'sha256', 'device', 'inode'])
951
+ || !boundedText(record['path'], 4_096) || !isAbsolute(record['path'])
952
+ || resolve(record['path']) !== record['path']
953
+ || !validArtifactIdentity(record, true)
954
+ || typeof record['device'] !== 'string'
955
+ || typeof record['inode'] !== 'string')
956
+ return undefined;
957
+ return {
958
+ path: record['path'],
959
+ size: record['size'],
960
+ sha256: record['sha256'],
961
+ device: record['device'],
962
+ inode: record['inode'],
963
+ };
964
+ }
965
+ function parseCanonicalQuarantine(value) {
966
+ if (!value || typeof value !== 'object' || Array.isArray(value))
967
+ return undefined;
968
+ const record = value;
969
+ if ((record['kind'] !== 'marker' && record['kind'] !== 'readiness')
970
+ || !boundedText(record['sourcePath'], 4_096) || !isAbsolute(record['sourcePath'])
971
+ || resolve(record['sourcePath']) !== record['sourcePath']
972
+ || !boundedText(record['quarantinePath'], 4_096) || !isAbsolute(record['quarantinePath'])
973
+ || resolve(record['quarantinePath']) !== record['quarantinePath'])
974
+ return undefined;
975
+ const identity = record['identity'];
976
+ if (!identity || typeof identity !== 'object' || Array.isArray(identity))
977
+ return undefined;
978
+ const identityRecord = identity;
979
+ if (!validArtifactIdentity(identityRecord, true)
980
+ || typeof identityRecord['device'] !== 'string'
981
+ || typeof identityRecord['inode'] !== 'string')
982
+ return undefined;
983
+ return {
984
+ kind: record['kind'],
985
+ sourcePath: record['sourcePath'],
986
+ quarantinePath: record['quarantinePath'],
987
+ identity: {
988
+ size: identityRecord['size'],
989
+ sha256: identityRecord['sha256'],
990
+ device: identityRecord['device'],
991
+ inode: identityRecord['inode'],
992
+ },
993
+ };
994
+ }
995
+ function validArtifactIdentity(value, allowFileId) {
996
+ const record = value;
997
+ if (!Number.isSafeInteger(record['size']) || record['size'] < 0)
998
+ return false;
999
+ if (typeof record['sha256'] !== 'string' || !SHA256_RE.test(record['sha256']))
1000
+ return false;
1001
+ if (!allowFileId && (record['device'] !== undefined || record['inode'] !== undefined))
1002
+ return false;
1003
+ if ((record['device'] === undefined) !== (record['inode'] === undefined))
1004
+ return false;
1005
+ if (record['device'] !== undefined && (!/^[0-9]+$/.test(String(record['device']))
1006
+ || !/^[0-9]+$/.test(String(record['inode']))
1007
+ || BigInt(String(record['device'])) <= 0n
1008
+ || BigInt(String(record['inode'])) <= 0n))
1009
+ return false;
1010
+ return true;
1011
+ }
1012
+ function parseProcessStartIdentity(value) {
1013
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1014
+ return undefined;
1015
+ const record = value;
1016
+ if (record['source'] === 'linux-proc'
1017
+ && typeof record['bootId'] === 'string'
1018
+ && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(record['bootId'])
1019
+ && typeof record['startTicks'] === 'string' && /^[1-9]\d*$/.test(record['startTicks'])) {
1020
+ return { source: 'linux-proc', bootId: record['bootId'], startTicks: record['startTicks'] };
1021
+ }
1022
+ if (record['source'] === 'windows-powershell'
1023
+ && typeof record['startTimeTicks'] === 'string' && /^[1-9]\d*$/.test(record['startTimeTicks'])) {
1024
+ return { source: 'windows-powershell', startTimeTicks: record['startTimeTicks'] };
1025
+ }
1026
+ if (record['source'] === 'darwin-ps'
1027
+ && boundedText(record['startTime'], 128)) {
1028
+ return { source: 'darwin-ps', startTime: record['startTime'] };
1029
+ }
1030
+ return undefined;
1031
+ }
1032
+ export function parseBootstrapJournal(value) {
1033
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1034
+ return undefined;
1035
+ const record = value;
1036
+ const owner = record['owner'];
1037
+ const managerBinding = record['managerBinding'];
1038
+ const legacyRemoval = record['operation'] === LEGACY_BOOTSTRAP_REMOVAL_OPERATION;
1039
+ if (record['operation'] !== undefined && !legacyRemoval)
1040
+ return undefined;
1041
+ if (record['schema'] !== BOOTSTRAP_JOURNAL_SCHEMA
1042
+ || typeof record['transactionId'] !== 'string' || !UUID_RE.test(record['transactionId'])
1043
+ || !owner || typeof owner !== 'object' || Array.isArray(owner)
1044
+ || typeof record['target'] !== 'string' || !TARGETS.has(record['target'])
1045
+ || !boundedText(record['service'], 128)
1046
+ || (!legacyRemoval && record['managerBefore'] !== 'absent')
1047
+ || (legacyRemoval && !['absent', 'present', 'disabled'].includes(record['managerBefore']))
1048
+ || !managerBinding || typeof managerBinding !== 'object' || Array.isArray(managerBinding)
1049
+ || typeof record['stage'] !== 'string' || !JOURNAL_STAGES.has(record['stage'])
1050
+ || !Number.isSafeInteger(record['deadlineMs']) || record['deadlineMs'] <= 0
1051
+ || !Array.isArray(record['artifacts']) || record['artifacts'].length === 0 || record['artifacts'].length > 32
1052
+ || typeof record['updatedAt'] !== 'string' || Number.isNaN(Date.parse(record['updatedAt'])))
1053
+ return undefined;
1054
+ const ownerRecord = owner;
1055
+ const managerBindingRecord = managerBinding;
1056
+ const processStartIdentity = parseProcessStartIdentity(ownerRecord['processStartIdentity']);
1057
+ if (!Number.isSafeInteger(ownerRecord['pid']) || ownerRecord['pid'] <= 0
1058
+ || typeof ownerRecord['token'] !== 'string' || !UUID_RE.test(ownerRecord['token'])
1059
+ || !processStartIdentity
1060
+ || typeof ownerRecord['acquiredAt'] !== 'string' || Number.isNaN(Date.parse(ownerRecord['acquiredAt'])))
1061
+ return undefined;
1062
+ const absentManagerBinding = managerBindingRecord['kind'] === LEGACY_BOOTSTRAP_ABSENT_MANAGER_BINDING;
1063
+ if (absentManagerBinding) {
1064
+ if (!legacyRemoval || record['managerBefore'] !== 'absent'
1065
+ || !exactRecordKeys(managerBindingRecord, ['kind', 'state'])
1066
+ || managerBindingRecord['state'] !== 'absent')
1067
+ return undefined;
1068
+ }
1069
+ else {
1070
+ if (!boundedText(managerBindingRecord['artifactPath'], 4_096)
1071
+ || !isAbsolute(managerBindingRecord['artifactPath'])
1072
+ || resolve(managerBindingRecord['artifactPath']) !== managerBindingRecord['artifactPath'])
1073
+ return undefined;
1074
+ if (managerBindingRecord['kind'] !== undefined
1075
+ && managerBindingRecord['kind'] !== 'transaction'
1076
+ && managerBindingRecord['kind'] !== coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING)
1077
+ return undefined;
1078
+ }
1079
+ const artifacts = record['artifacts'].map(parseArtifact);
1080
+ if (artifacts.some((artifact) => artifact === undefined))
1081
+ return undefined;
1082
+ if (legacyRemoval !== artifacts.every((artifact) => artifact.before === 'legacy_owned'))
1083
+ return undefined;
1084
+ if (artifacts.some((artifact) => artifact.claimOwnership !== undefined)
1085
+ && (legacyRemoval
1086
+ || (record['stage'] !== 'installing' && record['stage'] !== 'rollback_pending'))) {
1087
+ return undefined;
1088
+ }
1089
+ const preservedValue = record['preservedArtifacts'];
1090
+ if (preservedValue !== undefined
1091
+ && (!(legacyRemoval
1092
+ || managerBindingRecord['kind'] === coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING)
1093
+ || !Array.isArray(preservedValue)
1094
+ || preservedValue.length === 0 || preservedValue.length > 32))
1095
+ return undefined;
1096
+ const preservedArtifacts = Array.isArray(preservedValue)
1097
+ ? preservedValue.map(parsePreservedArtifact)
1098
+ : [];
1099
+ if (preservedArtifacts.some((artifact) => artifact === undefined))
1100
+ return undefined;
1101
+ const successMarkerIdentity = record['successMarkerIdentity'];
1102
+ if (successMarkerIdentity !== undefined
1103
+ && (!successMarkerIdentity || typeof successMarkerIdentity !== 'object'
1104
+ || Array.isArray(successMarkerIdentity)
1105
+ || !exactRecordKeys(successMarkerIdentity, ['size', 'sha256'])
1106
+ || !validArtifactIdentity(successMarkerIdentity, false)))
1107
+ return undefined;
1108
+ if (!legacyRemoval
1109
+ && managerBindingRecord['kind'] === coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING
1110
+ && successMarkerIdentity === undefined)
1111
+ return undefined;
1112
+ const quarantineValue = record['canonicalQuarantine'];
1113
+ if (quarantineValue !== undefined
1114
+ && (!Array.isArray(quarantineValue) || quarantineValue.length === 0 || quarantineValue.length > 2))
1115
+ return undefined;
1116
+ const canonicalQuarantine = Array.isArray(quarantineValue)
1117
+ ? quarantineValue.map(parseCanonicalQuarantine)
1118
+ : [];
1119
+ if (canonicalQuarantine.some((entry) => entry === undefined))
1120
+ return undefined;
1121
+ const quarantineKinds = canonicalQuarantine.map((entry) => entry.kind);
1122
+ if (new Set(quarantineKinds).size !== quarantineKinds.length)
1123
+ return undefined;
1124
+ if (record['managerDetached'] !== undefined && typeof record['managerDetached'] !== 'boolean')
1125
+ return undefined;
1126
+ if (record['artifactsRestored'] !== undefined && typeof record['artifactsRestored'] !== 'boolean')
1127
+ return undefined;
1128
+ if (record['activationStarted'] !== undefined && typeof record['activationStarted'] !== 'boolean')
1129
+ return undefined;
1130
+ if (record['terminalAction'] !== undefined && record['terminalAction'] !== 'remove_committed')
1131
+ return undefined;
1132
+ if (record['terminalAction'] === 'remove_committed'
1133
+ && record['stage'] !== 'rollback_pending' && record['stage'] !== 'rolled_back'
1134
+ && !(legacyRemoval && record['stage'] === 'prepared'))
1135
+ return undefined;
1136
+ if (legacyRemoval && record['terminalAction'] !== 'remove_committed')
1137
+ return undefined;
1138
+ if (legacyRemoval && !['prepared', 'rollback_pending', 'rolled_back'].includes(record['stage'])) {
1139
+ return undefined;
1140
+ }
1141
+ if (record['lastError'] !== undefined && !boundedText(record['lastError'], 512))
1142
+ return undefined;
1143
+ const paths = artifacts.map((artifact) => artifact.path);
1144
+ const pathKeys = paths.map((path) => bootstrapPathKey(path, record['target']));
1145
+ if (new Set(pathKeys).size !== pathKeys.length)
1146
+ return undefined;
1147
+ if (!bootstrapArtifactNamespaceIsUnique(artifacts, record['target']))
1148
+ return undefined;
1149
+ if (artifacts.some((artifact) => (bootstrapArtifactStagingCleanupPath(artifact).length > 4_096)))
1150
+ return undefined;
1151
+ if (artifacts.some((artifact) => artifact.claimPath !== bootstrapArtifactClaimPath(artifact.path, record['transactionId'])
1152
+ || artifact.rollbackPath !== bootstrapArtifactRollbackPath(artifact.path, record['transactionId'])))
1153
+ return undefined;
1154
+ const artifactNamespaceKeys = artifacts.flatMap((artifact) => [
1155
+ artifact.path,
1156
+ artifact.claimPath,
1157
+ artifact.rollbackPath,
1158
+ bootstrapArtifactStagingCleanupPath(artifact),
1159
+ ]).map((path) => bootstrapPathKey(path, record['target']));
1160
+ const preservedKeys = preservedArtifacts.map((artifact) => bootstrapPathKey(artifact.path, record['target']));
1161
+ if (new Set([...artifactNamespaceKeys, ...preservedKeys]).size
1162
+ !== artifactNamespaceKeys.length + preservedKeys.length)
1163
+ return undefined;
1164
+ if (!absentManagerBinding) {
1165
+ const managerKey = bootstrapPathKey(managerBindingRecord['artifactPath'], record['target']);
1166
+ if (!pathKeys.includes(managerKey))
1167
+ return undefined;
1168
+ }
1169
+ return record;
1170
+ }
1171
+ export function readBootstrapJournal(stateDir) {
1172
+ const path = bootstrapJournalPath(stateDir);
1173
+ try {
1174
+ assertSecureStateDirectory(stateDir);
1175
+ const parsed = parseBootstrapJournal(JSON.parse(readBoundedRegularText(path, MAX_JOURNAL_BYTES, 'bootstrap recovery journal', { requireOwnerOnly: true })));
1176
+ if (!parsed)
1177
+ throw new Error(`bootstrap recovery journal is corrupt: ${path}`);
1178
+ assertBootstrapPathsDoNotOwnProtectedState(stateDir, parsed.target, [
1179
+ ...parsed.artifacts.flatMap((artifact) => [
1180
+ artifact.path,
1181
+ artifact.claimPath,
1182
+ artifact.rollbackPath,
1183
+ bootstrapArtifactStagingCleanupPath(artifact),
1184
+ ]),
1185
+ ...(parsed.preservedArtifacts ?? []).map((artifact) => artifact.path),
1186
+ ], 'bootstrap recovery journal');
1187
+ assertBootstrapCanonicalQuarantineLayout(stateDir, parsed);
1188
+ return parsed;
1189
+ }
1190
+ catch (error) {
1191
+ if (isErrno(error, 'ENOENT'))
1192
+ return undefined;
1193
+ if (error instanceof Error && error.message.startsWith('bootstrap recovery journal is corrupt:'))
1194
+ throw error;
1195
+ throw new Error(`bootstrap recovery journal is corrupt: ${path}`, { cause: error });
1196
+ }
1197
+ }
1198
+ export function readBootstrapMarker(stateDir) {
1199
+ try {
1200
+ assertSecureStateDirectory(stateDir);
1201
+ const marker = coreBootstrap.parseLifecycleBootstrapMarkerJson(readBoundedRegularText(bootstrapMarkerPath(stateDir), MAX_MARKER_BYTES, 'bootstrap success marker', { requireOwnerOnly: true }));
1202
+ if (!marker)
1203
+ throw new Error(`bootstrap success marker is corrupt: ${bootstrapMarkerPath(stateDir)}`);
1204
+ assertBootstrapPathsDoNotOwnProtectedState(stateDir, marker.target, [
1205
+ marker.managerArtifactPath,
1206
+ ...marker.artifacts.map((artifact) => artifact.path),
1207
+ ...(marker.preservedArtifacts ?? []).map((artifact) => artifact.path),
1208
+ ], 'bootstrap success marker');
1209
+ return marker;
1210
+ }
1211
+ catch (error) {
1212
+ if (isErrno(error, 'ENOENT'))
1213
+ return undefined;
1214
+ throw error;
1215
+ }
1216
+ }
1217
+ export function readLegacyBootstrapMarker(stateDir) {
1218
+ const path = bootstrapMarkerPath(stateDir);
1219
+ try {
1220
+ assertSecureStateDirectory(stateDir);
1221
+ const raw = readBoundedRegularText(path, MAX_MARKER_BYTES, 'legacy bootstrap success marker', { requireOwnerOnly: true });
1222
+ const marker = coreBootstrap.parseLegacyLifecycleBootstrapMarkerJson(raw);
1223
+ if (!marker)
1224
+ throw new Error(`legacy bootstrap success marker is corrupt: ${path}`);
1225
+ assertBootstrapPathsDoNotOwnProtectedState(stateDir, marker.target, marker.files, 'legacy bootstrap success marker');
1226
+ const identity = identityFor(path);
1227
+ const rawIdentity = bootstrapArtifactIdentityForBytes(Buffer.from(raw, 'utf8'));
1228
+ if (identity.size !== rawIdentity.size || identity.sha256 !== rawIdentity.sha256
1229
+ || identity.device === undefined || identity.inode === undefined) {
1230
+ throw new Error(`legacy bootstrap success marker changed while reading: ${path}`);
1231
+ }
1232
+ return {
1233
+ marker,
1234
+ raw,
1235
+ identity: identity,
1236
+ };
1237
+ }
1238
+ catch (error) {
1239
+ if (isErrno(error, 'ENOENT'))
1240
+ return undefined;
1241
+ throw error;
1242
+ }
1243
+ }
1244
+ function sameLegacyBootstrapMarkerRead(left, right) {
1245
+ return left.raw === right.raw
1246
+ && left.identity.size === right.identity.size
1247
+ && left.identity.sha256 === right.identity.sha256
1248
+ && left.identity.device === right.identity.device
1249
+ && left.identity.inode === right.identity.inode;
1250
+ }
1251
+ function sameLegacyMarkerReceipt(legacy, adopted) {
1252
+ const ownedPaths = adopted.artifacts.map((artifact) => artifact.path);
1253
+ const preservedPaths = (adopted.preservedArtifacts ?? []).map((artifact) => artifact.path);
1254
+ const historicalOwnedPaths = ownedPaths.filter((path) => legacy.files.includes(path));
1255
+ const derivedOwnedPaths = ownedPaths.filter((path) => !legacy.files.includes(path));
1256
+ const historicalPreservedPaths = preservedPaths.filter((path) => legacy.files.includes(path));
1257
+ const derivedPreservedPaths = preservedPaths.filter((path) => !legacy.files.includes(path));
1258
+ const stateRootProofPath = adopted.legacyStateRootProof?.envFilePath;
1259
+ const allowedWindowsDerived = derivedOwnedPaths.every((path) => ['evolver-proxy-task-launcher.vbs', 'evolver-recovery-controller.exe']
1260
+ .includes(win32.basename(path).toLowerCase()));
1261
+ const legacyPartition = [...historicalOwnedPaths, ...historicalPreservedPaths];
1262
+ const expectedHistoricalOwned = legacy.files.filter((path) => !historicalPreservedPaths.includes(path));
1263
+ const expectedPreserved = legacy.files.filter((path) => historicalPreservedPaths.includes(path));
1264
+ const historicalAutoexec = legacy.files.filter((path) => {
1265
+ const name = (legacy.target === 'windows' ? win32 : posix).basename(path).toLowerCase();
1266
+ return legacy.target === 'systemd'
1267
+ ? name === 'evolver-autoexec.service'
1268
+ : legacy.target === 'launchd'
1269
+ ? name === 'com.evomap.evolver-autoexec.plist'
1270
+ : /^install-evolver-autoexec-windows(?:-[0-9a-f-]+)?\.ps1$/i.test(name);
1271
+ });
1272
+ return adopted.managerBindingKind === coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING
1273
+ && legacy.bootstrappedAt === adopted.bootstrappedAt
1274
+ && legacy.target === adopted.target
1275
+ && legacy.service === adopted.service
1276
+ && adopted.files.length === ownedPaths.length + preservedPaths.length
1277
+ && adopted.files.every((path, index) => path === [...ownedPaths, ...preservedPaths][index])
1278
+ && legacy.files.length === legacyPartition.length
1279
+ && legacy.files.every((path) => legacyPartition.includes(path))
1280
+ && expectedHistoricalOwned.every((path, index) => path === historicalOwnedPaths[index])
1281
+ && expectedPreserved.every((path, index) => path === historicalPreservedPaths[index])
1282
+ && historicalAutoexec.length === historicalPreservedPaths.length
1283
+ && historicalAutoexec.every((path, index) => path === historicalPreservedPaths[index])
1284
+ && new Set(legacyPartition).size === legacyPartition.length
1285
+ && (stateRootProofPath === undefined
1286
+ ? derivedPreservedPaths.length === 0
1287
+ : derivedPreservedPaths.length === 1
1288
+ && derivedPreservedPaths[0] === stateRootProofPath
1289
+ && preservedPaths[preservedPaths.length - 1] === stateRootProofPath)
1290
+ && (derivedOwnedPaths.length === 0
1291
+ || (legacy.target === 'windows' && derivedOwnedPaths.length <= 2 && allowedWindowsDerived));
1292
+ }
1293
+ /** Adopt an exact legacy marker through the durable canonical-state transaction. */
1294
+ export async function adoptLegacyBootstrapMarker(stateDir, expectedLegacy, marker, initialJournal, now = Date.now, hooks = {}) {
1295
+ if (marker.managerBindingKind !== coreBootstrap.LIFECYCLE_BOOTSTRAP_LEGACY_BINDING) {
1296
+ throw new Error('legacy bootstrap adoption requires an explicit legacy manager binding');
1297
+ }
1298
+ if (!coreBootstrap.parseLifecycleBootstrapMarker(marker)) {
1299
+ throw new Error('legacy bootstrap adoption marker is invalid');
1300
+ }
1301
+ if (!sameLegacyMarkerReceipt(expectedLegacy.marker, marker)) {
1302
+ throw new Error('legacy bootstrap adoption marker does not bind the legacy receipt');
1303
+ }
1304
+ if (initialJournal.managerBinding.kind === LEGACY_BOOTSTRAP_ABSENT_MANAGER_BINDING) {
1305
+ throw new Error('legacy bootstrap adoption requires a present manager binding');
1306
+ }
1307
+ if (initialJournal.stage !== 'prepared'
1308
+ || initialJournal.activationStarted === true
1309
+ || initialJournal.artifactsRestored !== true
1310
+ || (initialJournal.managerBinding.kind ?? 'transaction') !== marker.managerBindingKind
1311
+ || !initialJournal.successMarkerIdentity
1312
+ || initialJournal.successMarkerIdentity.size !== Buffer.byteLength(`${JSON.stringify(marker)}\n`, 'utf8')
1313
+ || initialJournal.successMarkerIdentity.sha256 !== bootstrapArtifactIdentityForBytes(Buffer.from(`${JSON.stringify(marker)}\n`, 'utf8')).sha256
1314
+ || initialJournal.transactionId !== marker.transactionId
1315
+ || initialJournal.target !== marker.target
1316
+ || initialJournal.service !== marker.service
1317
+ || initialJournal.managerBinding.artifactPath !== resolve(marker.managerArtifactPath)
1318
+ || initialJournal.artifacts.length !== marker.artifacts.length
1319
+ || initialJournal.artifacts.some((artifact, index) => {
1320
+ const receipt = marker.artifacts[index];
1321
+ return !receipt || !artifact.identity
1322
+ || artifact.path !== resolve(receipt.path)
1323
+ || artifact.identity.size !== receipt.size
1324
+ || artifact.identity.sha256 !== receipt.sha256
1325
+ || artifact.identity.device !== receipt.device
1326
+ || artifact.identity.inode !== receipt.inode;
1327
+ })) {
1328
+ throw new Error('legacy bootstrap adoption journal does not bind the adopted receipt');
1329
+ }
1330
+ const current = readLegacyBootstrapMarker(stateDir);
1331
+ if (!current || !sameLegacyBootstrapMarkerRead(current, expectedLegacy)) {
1332
+ throw new Error('legacy bootstrap success marker changed before adoption');
1333
+ }
1334
+ let journal = planBootstrapCanonicalQuarantine(stateDir, initialJournal, ['marker']);
1335
+ const quarantine = journal.canonicalQuarantine?.[0];
1336
+ if (!quarantine
1337
+ || quarantine.kind !== 'marker'
1338
+ || quarantine.identity.size !== expectedLegacy.identity.size
1339
+ || quarantine.identity.sha256 !== expectedLegacy.identity.sha256
1340
+ || quarantine.identity.device !== expectedLegacy.identity.device
1341
+ || quarantine.identity.inode !== expectedLegacy.identity.inode) {
1342
+ throw new Error('legacy bootstrap adoption quarantine does not bind the exact legacy marker');
1343
+ }
1344
+ assertBootstrapTransactionClaimsAbsent(journal);
1345
+ hooks.assertOwner?.();
1346
+ writeBootstrapJournal(stateDir, journal);
1347
+ hooks.beforeQuarantine?.(journal);
1348
+ hooks.assertOwner?.();
1349
+ applyBootstrapCanonicalQuarantine(stateDir, journal, () => hooks.assertOwner?.());
1350
+ hooks.afterQuarantine?.();
1351
+ journal = updateBootstrapJournal(journal, { stage: 'committing' }, now());
1352
+ hooks.assertOwner?.();
1353
+ writeBootstrapJournal(stateDir, journal);
1354
+ await hooks.beforePublish?.(journal);
1355
+ hooks.assertOwner?.();
1356
+ writeDurableJsonExclusive(bootstrapMarkerPath(stateDir), marker, 0o600);
1357
+ hooks.afterPublish?.();
1358
+ const adopted = readBootstrapMarker(stateDir);
1359
+ if (!adopted || JSON.stringify(adopted) !== JSON.stringify(marker)) {
1360
+ throw new Error('legacy bootstrap adoption marker publication is ambiguous');
1361
+ }
1362
+ journal = updateBootstrapJournal(journal, { stage: 'committed' }, now());
1363
+ hooks.assertOwner?.();
1364
+ writeBootstrapJournal(stateDir, journal);
1365
+ hooks.beforeFinalize?.();
1366
+ hooks.assertOwner?.();
1367
+ finalizeBootstrapCanonicalQuarantine(stateDir, journal, {
1368
+ beforeMove: () => hooks.assertOwner?.(),
1369
+ afterMove: () => hooks.assertOwner?.(),
1370
+ beforeDelete: () => hooks.assertOwner?.(),
1371
+ });
1372
+ hooks.assertOwner?.();
1373
+ removeBootstrapJournal(stateDir);
1374
+ }
1375
+ export function readBootstrapReadiness(stateDir) {
1376
+ const path = bootstrapReadinessPath(stateDir);
1377
+ try {
1378
+ assertSecureStateDirectory(stateDir);
1379
+ const readiness = coreBootstrap.parseLifecycleBootstrapReadinessJson(readBoundedRegularText(path, MAX_READINESS_BYTES, 'bootstrap readiness receipt', { requireOwnerOnly: true }));
1380
+ if (!readiness)
1381
+ throw new Error(`bootstrap readiness receipt is corrupt: ${path}`);
1382
+ return readiness;
1383
+ }
1384
+ catch (error) {
1385
+ if (isErrno(error, 'ENOENT'))
1386
+ return undefined;
1387
+ throw error;
1388
+ }
1389
+ }
1390
+ export function removeBootstrapReadiness(stateDir, transactionId, beforeMutation = () => { }) {
1391
+ beforeMutation();
1392
+ const lock = acquireBootstrapReadinessLock(stateDir);
1393
+ let operationError;
1394
+ try {
1395
+ const readiness = readBootstrapReadiness(stateDir);
1396
+ if (readiness) {
1397
+ if (readiness.transactionId !== transactionId) {
1398
+ throw new Error('bootstrap refused to remove readiness owned by another transaction');
1399
+ }
1400
+ beforeMutation();
1401
+ removeDurableFile(bootstrapReadinessPath(stateDir));
1402
+ }
1403
+ }
1404
+ catch (error) {
1405
+ operationError = error;
1406
+ }
1407
+ beforeMutation();
1408
+ releaseBootstrapLockAfterOperation(lock, operationError, 'readiness');
1409
+ if (operationError !== undefined)
1410
+ throw operationError;
1411
+ }
1412
+ function releaseBootstrapLockAfterOperation(lock, operationError, label) {
1413
+ try {
1414
+ lock.release();
1415
+ }
1416
+ catch (releaseError) {
1417
+ throw new Error(`bootstrap ${label} lock release failed`, {
1418
+ cause: operationError === undefined ? releaseError : new AggregateError([operationError, releaseError]),
1419
+ });
1420
+ }
1421
+ }
1422
+ export function assertTrustedArtifactParent(path, platform, uid) {
1423
+ const parent = dirname(resolve(path));
1424
+ if (platform !== 'win32') {
1425
+ assertTrustedPosixDirectoryChain(parent, platform, uid, 'bootstrap artifact parent');
1426
+ return;
1427
+ }
1428
+ let current = parent;
1429
+ const root = parse(current).root;
1430
+ const windowsChecks = [];
1431
+ for (;;) {
1432
+ try {
1433
+ const stat = lstatSync(current);
1434
+ if (platform === 'win32') {
1435
+ windowsChecks.push({ path: current, parentOnly: windowsChecks.length > 0 });
1436
+ }
1437
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
1438
+ throw new Error(`bootstrap artifact parent is not a trusted directory: ${current}`);
1439
+ }
1440
+ }
1441
+ catch (error) {
1442
+ if (!isErrno(error, 'ENOENT'))
1443
+ throw error;
1444
+ }
1445
+ if (current === root)
1446
+ break;
1447
+ current = dirname(current);
1448
+ }
1449
+ assertWindowsAclChecksTrusted(windowsChecks);
1450
+ }
1451
+ export function assertPlannedArtifactsAbsent(paths, platform, uid) {
1452
+ const normalized = paths.map((path) => resolve(path));
1453
+ const keys = normalized.map((path) => platform === 'win32' ? path.toLowerCase() : path);
1454
+ if (paths.some((path, index) => !isAbsolute(path) || path !== normalized[index])
1455
+ || new Set(keys).size !== keys.length) {
1456
+ throw new Error('bootstrap artifact inventory must contain unique canonical absolute paths');
1457
+ }
1458
+ for (const path of normalized) {
1459
+ assertTrustedArtifactParent(path, platform, uid);
1460
+ try {
1461
+ lstatSync(path);
1462
+ throw new Error(`bootstrap refuses to overwrite pre-existing artifact: ${path}`);
1463
+ }
1464
+ catch (error) {
1465
+ if (!isErrno(error, 'ENOENT'))
1466
+ throw error;
1467
+ }
1468
+ }
1469
+ }
1470
+ export function assertBootstrapTransactionClaimsAbsent(journal) {
1471
+ for (const artifact of journal.artifacts) {
1472
+ for (const path of [
1473
+ artifact.claimPath,
1474
+ artifact.rollbackPath,
1475
+ bootstrapArtifactStagingCleanupPath(artifact),
1476
+ ]) {
1477
+ try {
1478
+ lstatSync(path);
1479
+ throw new Error(`bootstrap transaction path already exists: ${path}`);
1480
+ }
1481
+ catch (error) {
1482
+ if (!isErrno(error, 'ENOENT'))
1483
+ throw error;
1484
+ }
1485
+ }
1486
+ }
1487
+ for (const entry of journal.canonicalQuarantine ?? []) {
1488
+ for (const path of [entry.quarantinePath, bootstrapCanonicalFinalizePath(entry)]) {
1489
+ try {
1490
+ lstatSync(path);
1491
+ throw new Error(`bootstrap transaction path already exists: ${path}`);
1492
+ }
1493
+ catch (error) {
1494
+ if (!isErrno(error, 'ENOENT'))
1495
+ throw error;
1496
+ }
1497
+ }
1498
+ }
1499
+ }
1500
+ function assertTrustedBootstrapArtifactLeaf(stat, platform, uid, path, role) {
1501
+ if (role === 'transaction')
1502
+ return;
1503
+ const ownerTrusted = role === 'owned'
1504
+ ? uid !== undefined && stat.uid === uid
1505
+ : uid !== undefined && (stat.uid === uid || stat.uid === 0n);
1506
+ if ((role === 'owned' && stat.nlink !== 1n)
1507
+ || (platform !== 'win32'
1508
+ && (!ownerTrusted || (stat.mode & 18n) !== 0n))) {
1509
+ throw new Error(`bootstrap artifact leaf is not exclusively owner-controlled: ${path}`);
1510
+ }
1511
+ }
1512
+ export const _assertTrustedBootstrapArtifactLeafForTest = assertTrustedBootstrapArtifactLeaf;
1513
+ export function readBootstrapArtifactFile(path, maxBytes = MAX_ARTIFACT_BYTES, hooks = {}) {
1514
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_ARTIFACT_BYTES) {
1515
+ throw new Error('bootstrap artifact read limit is invalid');
1516
+ }
1517
+ const trustedUid = process.platform === 'win32' || typeof process.getuid !== 'function'
1518
+ ? undefined
1519
+ : BigInt(process.getuid());
1520
+ const role = hooks.role ?? 'transaction';
1521
+ const assertTrustedLeaf = (stat) => assertTrustedBootstrapArtifactLeaf(stat, process.platform, trustedUid, path, role);
1522
+ if (process.platform === 'win32')
1523
+ assertWindowsAclTrusted(path, role === 'owned');
1524
+ const before = lstatSync(path, { bigint: true });
1525
+ if (before.isSymbolicLink() || !before.isFile() || before.size > BigInt(maxBytes)
1526
+ || before.dev <= 0n || before.ino <= 0n) {
1527
+ throw new Error(`bootstrap artifact is not a regular owned file: ${path}`);
1528
+ }
1529
+ assertTrustedLeaf(before);
1530
+ const descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
1531
+ try {
1532
+ const opened = fstatSync(descriptor, { bigint: true });
1533
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino
1534
+ || opened.dev <= 0n || opened.ino <= 0n || opened.size > BigInt(maxBytes)) {
1535
+ throw new Error(`bootstrap artifact changed while opening: ${path}`);
1536
+ }
1537
+ assertTrustedLeaf(opened);
1538
+ const hash = createHash('sha256');
1539
+ const buffer = Buffer.allocUnsafe(64 * 1024);
1540
+ const chunks = [];
1541
+ let size = 0;
1542
+ for (;;) {
1543
+ const count = readSync(descriptor, buffer, 0, buffer.length, null);
1544
+ if (count === 0)
1545
+ break;
1546
+ size += count;
1547
+ if (size > maxBytes) {
1548
+ throw new Error(`bootstrap artifact exceeds the hashing limit: ${path}`);
1549
+ }
1550
+ const chunk = Buffer.from(buffer.subarray(0, count));
1551
+ chunks.push(chunk);
1552
+ hash.update(chunk);
1553
+ }
1554
+ const after = fstatSync(descriptor, { bigint: true });
1555
+ if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size
1556
+ || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs
1557
+ || BigInt(size) !== opened.size) {
1558
+ throw new Error(`bootstrap artifact changed while hashing: ${path}`);
1559
+ }
1560
+ assertTrustedLeaf(after);
1561
+ hooks.afterRead?.();
1562
+ if (process.platform === 'win32')
1563
+ assertWindowsAclTrusted(path, role === 'owned');
1564
+ const settled = lstatSync(path, { bigint: true });
1565
+ if (!settled.isFile() || settled.isSymbolicLink()
1566
+ || settled.dev !== opened.dev || settled.ino !== opened.ino
1567
+ || settled.size !== opened.size || settled.mtimeNs !== opened.mtimeNs
1568
+ || settled.ctimeNs !== opened.ctimeNs) {
1569
+ throw new Error(`bootstrap artifact changed after reading: ${path}`);
1570
+ }
1571
+ assertTrustedLeaf(settled);
1572
+ return {
1573
+ bytes: Buffer.concat(chunks, size),
1574
+ identity: {
1575
+ size,
1576
+ sha256: hash.digest('hex'),
1577
+ device: String(opened.dev),
1578
+ inode: String(opened.ino),
1579
+ },
1580
+ };
1581
+ }
1582
+ finally {
1583
+ closeSync(descriptor);
1584
+ }
1585
+ }
1586
+ function identityFor(path) {
1587
+ return readBootstrapArtifactFile(path).identity;
1588
+ }
1589
+ export function bootstrapArtifactIdentityForBytes(bytes) {
1590
+ return { size: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') };
1591
+ }
1592
+ export function bootstrapArtifactContentIdentityForFile(path) {
1593
+ const identity = identityFor(path);
1594
+ return { size: identity.size, sha256: identity.sha256 };
1595
+ }
1596
+ export function bootstrapArtifactIdentityForFile(path) {
1597
+ const identity = identityFor(path);
1598
+ if (identity.device === undefined || identity.inode === undefined) {
1599
+ throw new Error(`bootstrap artifact file identity is unavailable: ${path}`);
1600
+ }
1601
+ return identity;
1602
+ }
1603
+ function sameFileId(left, right) {
1604
+ return left.device !== undefined && left.inode !== undefined
1605
+ && left.device === right.device && left.inode === right.inode;
1606
+ }
1607
+ function assertExpectedArtifactIdentity(expected, actual, path) {
1608
+ if (actual.size !== expected.size || actual.sha256 !== expected.sha256) {
1609
+ throw new Error(`bootstrap artifact content does not match its durable plan: ${path}`);
1610
+ }
1611
+ if (expected.device !== undefined && !sameFileId(expected, actual)) {
1612
+ throw new Error(`bootstrap artifact file identity changed: ${path}`);
1613
+ }
1614
+ }
1615
+ function assertCanonicalQuarantineIdentity(path, expected) {
1616
+ const actual = identityFor(path);
1617
+ assertExpectedArtifactIdentity(expected, actual, path);
1618
+ if (!sameFileId(expected, actual)) {
1619
+ throw new Error(`bootstrap canonical quarantine file identity changed: ${path}`);
1620
+ }
1621
+ }
1622
+ function bootstrapCanonicalFinalizePath(entry) {
1623
+ return `${entry.quarantinePath}.finalizing`;
1624
+ }
1625
+ function preserveMovedCanonicalState(entry, movedPath, cause) {
1626
+ const movedIdentity = identityFor(movedPath);
1627
+ if (!filesystemEntryPresent(entry.sourcePath)) {
1628
+ try {
1629
+ linkSync(movedPath, entry.sourcePath);
1630
+ syncDirectory(dirname(entry.sourcePath));
1631
+ }
1632
+ catch (error) {
1633
+ if (!isErrno(error, 'EEXIST'))
1634
+ throw error;
1635
+ }
1636
+ }
1637
+ if (filesystemEntryPresent(entry.sourcePath)) {
1638
+ const restoredIdentity = identityFor(entry.sourcePath);
1639
+ if (sameFileId(restoredIdentity, movedIdentity)) {
1640
+ throw new Error(`bootstrap canonical state changed during quarantine and was restored without deleting its preserved inode: ${entry.sourcePath}`, { cause });
1641
+ }
1642
+ }
1643
+ throw new Error(`bootstrap canonical state changed during quarantine; both canonical and preserved paths remain for recovery: ${entry.sourcePath}`, { cause });
1644
+ }
1645
+ function withBootstrapCanonicalStateLock(stateDir, kind, operation) {
1646
+ if (kind === 'marker')
1647
+ return operation();
1648
+ const lock = acquireBootstrapReadinessLock(stateDir);
1649
+ let result;
1650
+ let operationError;
1651
+ try {
1652
+ result = operation();
1653
+ }
1654
+ catch (error) {
1655
+ operationError = error;
1656
+ }
1657
+ releaseBootstrapLockAfterOperation(lock, operationError, 'readiness');
1658
+ if (operationError !== undefined)
1659
+ throw operationError;
1660
+ return result;
1661
+ }
1662
+ export function planBootstrapCanonicalQuarantine(stateDir, journal, kinds) {
1663
+ if (journal.stage !== 'prepared') {
1664
+ throw new Error('bootstrap canonical quarantine must be planned before installation');
1665
+ }
1666
+ if (journal.canonicalQuarantine !== undefined) {
1667
+ throw new Error('bootstrap canonical quarantine was already planned');
1668
+ }
1669
+ if (new Set(kinds).size !== kinds.length || kinds.length > 2) {
1670
+ throw new Error('bootstrap canonical quarantine kinds must be unique');
1671
+ }
1672
+ if (kinds.length === 0)
1673
+ return journal;
1674
+ const canonicalQuarantine = kinds.map((kind) => {
1675
+ const sourcePath = resolve(kind === 'marker'
1676
+ ? bootstrapMarkerPath(stateDir)
1677
+ : bootstrapReadinessPath(stateDir));
1678
+ const quarantinePath = bootstrapCanonicalQuarantinePath(stateDir, kind, journal.transactionId);
1679
+ if (filesystemEntryPresent(quarantinePath)) {
1680
+ throw new Error(`bootstrap transaction path already exists: ${quarantinePath}`);
1681
+ }
1682
+ const identity = withBootstrapCanonicalStateLock(stateDir, kind, () => identityFor(sourcePath));
1683
+ if (!identity.device || !identity.inode) {
1684
+ throw new Error(`bootstrap canonical state has no durable file identity: ${sourcePath}`);
1685
+ }
1686
+ return {
1687
+ kind,
1688
+ sourcePath,
1689
+ quarantinePath,
1690
+ identity: { ...identity, device: identity.device, inode: identity.inode },
1691
+ };
1692
+ });
1693
+ const planned = { ...journal, canonicalQuarantine };
1694
+ assertBootstrapCanonicalQuarantineLayout(stateDir, planned);
1695
+ return planned;
1696
+ }
1697
+ export function applyBootstrapCanonicalQuarantine(stateDir, journal, beforeMutation = () => { }) {
1698
+ if (journal.stage !== 'prepared') {
1699
+ throw new Error('bootstrap canonical quarantine must be applied before installation');
1700
+ }
1701
+ assertBootstrapCanonicalQuarantineLayout(stateDir, journal);
1702
+ for (const entry of journal.canonicalQuarantine ?? []) {
1703
+ withBootstrapCanonicalStateLock(stateDir, entry.kind, () => {
1704
+ const sourcePresent = filesystemEntryPresent(entry.sourcePath);
1705
+ const quarantinePresent = filesystemEntryPresent(entry.quarantinePath);
1706
+ const finalizePresent = filesystemEntryPresent(bootstrapCanonicalFinalizePath(entry));
1707
+ if (finalizePresent) {
1708
+ throw new Error(`bootstrap canonical quarantine has an unfinished finalize path: ${entry.sourcePath}`);
1709
+ }
1710
+ if (sourcePresent && quarantinePresent) {
1711
+ throw new Error(`bootstrap canonical quarantine has both source and destination: ${entry.sourcePath}`);
1712
+ }
1713
+ if (quarantinePresent) {
1714
+ assertCanonicalQuarantineIdentity(entry.quarantinePath, entry.identity);
1715
+ return;
1716
+ }
1717
+ if (!sourcePresent) {
1718
+ throw new Error(`bootstrap canonical state disappeared before quarantine: ${entry.sourcePath}`);
1719
+ }
1720
+ assertCanonicalQuarantineIdentity(entry.sourcePath, entry.identity);
1721
+ beforeMutation();
1722
+ renameSync(entry.sourcePath, entry.quarantinePath);
1723
+ syncDirectory(dirname(entry.sourcePath));
1724
+ try {
1725
+ assertCanonicalQuarantineIdentity(entry.quarantinePath, entry.identity);
1726
+ }
1727
+ catch (error) {
1728
+ preserveMovedCanonicalState(entry, entry.quarantinePath, error);
1729
+ }
1730
+ });
1731
+ }
1732
+ }
1733
+ export function restoreBootstrapCanonicalQuarantine(stateDir, journal, hooks = {}) {
1734
+ assertBootstrapCanonicalQuarantineLayout(stateDir, journal);
1735
+ for (const entry of [...(journal.canonicalQuarantine ?? [])].reverse()) {
1736
+ withBootstrapCanonicalStateLock(stateDir, entry.kind, () => {
1737
+ const sourcePresent = filesystemEntryPresent(entry.sourcePath);
1738
+ const quarantinePresent = filesystemEntryPresent(entry.quarantinePath);
1739
+ const finalizePath = bootstrapCanonicalFinalizePath(entry);
1740
+ const finalizePresent = filesystemEntryPresent(finalizePath);
1741
+ if (quarantinePresent && finalizePresent) {
1742
+ throw new Error(`bootstrap canonical quarantine has two recovery paths: ${entry.sourcePath}`);
1743
+ }
1744
+ const recoveryPath = quarantinePresent ? entry.quarantinePath : finalizePresent ? finalizePath : undefined;
1745
+ if (sourcePresent && recoveryPath) {
1746
+ throw new Error(`bootstrap canonical quarantine cannot overwrite current state: ${entry.sourcePath}`);
1747
+ }
1748
+ if (!recoveryPath) {
1749
+ if (!sourcePresent) {
1750
+ throw new Error(`bootstrap canonical state and quarantine are both missing: ${entry.sourcePath}`);
1751
+ }
1752
+ assertCanonicalQuarantineIdentity(entry.sourcePath, entry.identity);
1753
+ return;
1754
+ }
1755
+ assertCanonicalQuarantineIdentity(recoveryPath, entry.identity);
1756
+ hooks.beforeMove?.(entry);
1757
+ renameSync(recoveryPath, entry.sourcePath);
1758
+ syncDirectory(dirname(entry.sourcePath));
1759
+ hooks.afterMove?.(entry);
1760
+ try {
1761
+ assertCanonicalQuarantineIdentity(entry.sourcePath, entry.identity);
1762
+ }
1763
+ catch (error) {
1764
+ if (!filesystemEntryPresent(recoveryPath)) {
1765
+ try {
1766
+ linkSync(entry.sourcePath, recoveryPath);
1767
+ syncDirectory(dirname(recoveryPath));
1768
+ }
1769
+ catch (linkError) {
1770
+ if (!isErrno(linkError, 'EEXIST'))
1771
+ throw linkError;
1772
+ }
1773
+ }
1774
+ throw new Error(`bootstrap canonical restore preserved an unexpected inode at both recovery paths: ${entry.sourcePath}`, { cause: error });
1775
+ }
1776
+ });
1777
+ }
1778
+ }
1779
+ export function finalizeBootstrapCanonicalQuarantine(stateDir, journal, hooks = {}) {
1780
+ assertBootstrapCanonicalQuarantineLayout(stateDir, journal);
1781
+ for (const entry of journal.canonicalQuarantine ?? []) {
1782
+ withBootstrapCanonicalStateLock(stateDir, entry.kind, () => {
1783
+ const finalizePath = bootstrapCanonicalFinalizePath(entry);
1784
+ const quarantinePresent = filesystemEntryPresent(entry.quarantinePath);
1785
+ const finalizePresent = filesystemEntryPresent(finalizePath);
1786
+ if (quarantinePresent && finalizePresent) {
1787
+ throw new Error(`bootstrap canonical quarantine has two finalize paths: ${entry.sourcePath}`);
1788
+ }
1789
+ if (!quarantinePresent && !finalizePresent)
1790
+ return;
1791
+ let ownedPath = finalizePresent ? finalizePath : entry.quarantinePath;
1792
+ assertCanonicalQuarantineIdentity(ownedPath, entry.identity);
1793
+ if (!finalizePresent) {
1794
+ hooks.beforeMove?.(entry);
1795
+ renameSync(entry.quarantinePath, finalizePath);
1796
+ syncDirectory(dirname(entry.quarantinePath));
1797
+ ownedPath = finalizePath;
1798
+ hooks.afterMove?.(entry);
1799
+ try {
1800
+ assertCanonicalQuarantineIdentity(ownedPath, entry.identity);
1801
+ }
1802
+ catch (error) {
1803
+ preserveMovedCanonicalState(entry, ownedPath, error);
1804
+ }
1805
+ }
1806
+ hooks.beforeDelete?.(entry);
1807
+ assertCanonicalQuarantineIdentity(ownedPath, entry.identity);
1808
+ removeDurableFile(ownedPath);
1809
+ });
1810
+ }
1811
+ }
1812
+ function identityFromClaim(artifact) {
1813
+ const finalIdentity = identityFor(artifact.path);
1814
+ const claimIdentity = identityFor(artifact.claimPath);
1815
+ if (!sameFileId(finalIdentity, claimIdentity)) {
1816
+ throw new Error(`bootstrap artifact claim does not bind the published inode: ${artifact.path}`);
1817
+ }
1818
+ if (filesystemEntryPresent(artifact.rollbackPath)) {
1819
+ const receiptIdentity = identityFor(artifact.rollbackPath);
1820
+ if (!sameFileId(claimIdentity, receiptIdentity)) {
1821
+ throw new Error(`bootstrap artifact ownership receipt does not bind the published inode: ${artifact.path}`);
1822
+ }
1823
+ }
1824
+ if (artifact.claimOwnership?.phase === 'created'
1825
+ && (artifact.claimOwnership.device !== finalIdentity.device
1826
+ || artifact.claimOwnership.inode !== finalIdentity.inode)) {
1827
+ throw new Error(`bootstrap artifact claim ownership changed before publication: ${artifact.path}`);
1828
+ }
1829
+ if (!artifact.identity)
1830
+ throw new Error(`bootstrap artifact has no expected identity: ${artifact.path}`);
1831
+ assertExpectedArtifactIdentity(artifact.identity, finalIdentity, artifact.path);
1832
+ return finalIdentity;
1833
+ }
1834
+ export function recordPublishedBootstrapArtifact(journal, path, claimPath, persistClaimOwnership) {
1835
+ const canonical = resolve(path);
1836
+ let found = false;
1837
+ let claimedIdentity;
1838
+ const artifacts = journal.artifacts.map((artifact) => {
1839
+ if (artifact.path !== canonical)
1840
+ return artifact;
1841
+ found = true;
1842
+ if (artifact.claimPath !== resolve(claimPath)) {
1843
+ throw new Error(`bootstrap publisher used an unexpected claim path: ${path}`);
1844
+ }
1845
+ if (filesystemEntryPresent(artifact.path)) {
1846
+ const identity = identityFromClaim(artifact);
1847
+ const { claimOwnership: _claimOwnership, ...publishedArtifact } = artifact;
1848
+ return { ...publishedArtifact, identity };
1849
+ }
1850
+ if (journal.stage !== 'installing'
1851
+ || (artifact.claimOwnership?.phase !== 'armed'
1852
+ && artifact.claimOwnership?.phase !== 'created')) {
1853
+ throw new Error(`bootstrap publisher created a claim without a durable ownership plan: ${path}`);
1854
+ }
1855
+ if (!filesystemEntryPresent(artifact.claimPath)
1856
+ || !filesystemEntryPresent(artifact.rollbackPath)) {
1857
+ throw new Error(`bootstrap artifact ownership receipt is incomplete: ${path}`);
1858
+ }
1859
+ const claimIdentity = identityFor(artifact.claimPath);
1860
+ const receiptIdentity = identityFor(artifact.rollbackPath);
1861
+ if (!sameFileId(claimIdentity, receiptIdentity)) {
1862
+ throw new Error(`bootstrap artifact ownership receipt does not bind the opened claim: ${path}`);
1863
+ }
1864
+ if (artifact.claimOwnership.phase === 'armed') {
1865
+ if (!artifact.identity)
1866
+ throw new Error(`bootstrap artifact has no expected identity: ${path}`);
1867
+ if (claimIdentity.device === undefined || claimIdentity.inode === undefined) {
1868
+ throw new Error(`bootstrap artifact claim file identity is unavailable: ${path}`);
1869
+ }
1870
+ claimedIdentity = {
1871
+ expected: artifact.identity,
1872
+ actual: claimIdentity,
1873
+ path: artifact.claimPath,
1874
+ };
1875
+ return {
1876
+ ...artifact,
1877
+ claimOwnership: {
1878
+ phase: 'created',
1879
+ device: claimIdentity.device,
1880
+ inode: claimIdentity.inode,
1881
+ },
1882
+ };
1883
+ }
1884
+ if (artifact.claimOwnership.device !== claimIdentity.device
1885
+ || artifact.claimOwnership.inode !== claimIdentity.inode) {
1886
+ throw new Error(`bootstrap artifact claim ownership changed before publication: ${path}`);
1887
+ }
1888
+ return artifact;
1889
+ });
1890
+ if (!found)
1891
+ throw new Error(`bootstrap publisher emitted an unplanned artifact: ${path}`);
1892
+ const recorded = { ...journal, artifacts };
1893
+ if (claimedIdentity) {
1894
+ // Persist exact-inode ownership before validating mutable apply bytes. A
1895
+ // plan/apply mismatch must remain recoverable without publishing canonical.
1896
+ persistClaimOwnership(recorded);
1897
+ assertExpectedArtifactIdentity(claimedIdentity.expected, claimedIdentity.actual, claimedIdentity.path);
1898
+ }
1899
+ return recorded;
1900
+ }
1901
+ export function captureBootstrapArtifactIdentities(journal, requirePresent = false) {
1902
+ return {
1903
+ ...journal,
1904
+ artifacts: journal.artifacts.map((artifact) => {
1905
+ if (!artifact.identity)
1906
+ throw new Error(`bootstrap artifact has no expected identity: ${artifact.path}`);
1907
+ if (!filesystemEntryPresent(artifact.path)) {
1908
+ if (filesystemEntryPresent(artifact.claimPath)) {
1909
+ const claimIdentity = identityFor(artifact.claimPath);
1910
+ assertExpectedArtifactIdentity(artifact.identity, claimIdentity, artifact.path);
1911
+ return { ...artifact, identity: claimIdentity };
1912
+ }
1913
+ if (requirePresent)
1914
+ throw new Error(`bootstrap artifact is missing after activation: ${artifact.path}`);
1915
+ return artifact;
1916
+ }
1917
+ const actual = identityFor(artifact.path);
1918
+ if (artifact.identity.device === undefined) {
1919
+ if (!filesystemEntryPresent(artifact.claimPath)) {
1920
+ throw new Error(`bootstrap artifact lacks a durable publisher claim: ${artifact.path}`);
1921
+ }
1922
+ return { ...artifact, identity: identityFromClaim(artifact) };
1923
+ }
1924
+ assertExpectedArtifactIdentity(artifact.identity, actual, artifact.path);
1925
+ return { ...artifact, identity: actual };
1926
+ }),
1927
+ };
1928
+ }
1929
+ export function removeOwnedBootstrapArtifacts(journal, hooks = {}) {
1930
+ for (const artifact of [...journal.artifacts].reverse()) {
1931
+ if (!artifact.identity)
1932
+ throw new Error(`bootstrap artifact has no durable ownership identity: ${artifact.path}`);
1933
+ const expectedIdentity = artifact.identity;
1934
+ const claimIdentity = filesystemEntryPresent(artifact.claimPath) ? identityFor(artifact.claimPath) : undefined;
1935
+ const receiptIdentity = filesystemEntryPresent(artifact.rollbackPath)
1936
+ ? identityFor(artifact.rollbackPath)
1937
+ : undefined;
1938
+ const stagingCleanupPath = bootstrapArtifactStagingCleanupPath(artifact);
1939
+ const stagingCleanupIdentity = filesystemEntryPresent(stagingCleanupPath)
1940
+ ? identityFor(stagingCleanupPath)
1941
+ : undefined;
1942
+ const armedStagingOnly = artifact.claimOwnership?.phase === 'armed'
1943
+ && (stagingCleanupIdentity !== undefined
1944
+ || (receiptIdentity !== undefined
1945
+ && (claimIdentity === undefined || !sameFileId(receiptIdentity, claimIdentity))));
1946
+ if (armedStagingOnly) {
1947
+ if (receiptIdentity !== undefined && stagingCleanupIdentity !== undefined) {
1948
+ throw new Error(`bootstrap artifact staging has two cleanup paths: ${artifact.path}`);
1949
+ }
1950
+ let ownedPath = stagingCleanupIdentity === undefined
1951
+ ? artifact.rollbackPath
1952
+ : stagingCleanupPath;
1953
+ let ownedIdentity = stagingCleanupIdentity ?? receiptIdentity;
1954
+ if (stagingCleanupIdentity === undefined) {
1955
+ hooks.beforeStagingQuarantine?.(artifact);
1956
+ renameSync(artifact.rollbackPath, stagingCleanupPath);
1957
+ syncDirectory(dirname(artifact.rollbackPath));
1958
+ ownedPath = stagingCleanupPath;
1959
+ hooks.afterStagingQuarantine?.(artifact);
1960
+ const movedIdentity = identityFor(stagingCleanupPath);
1961
+ if (!sameFileId(ownedIdentity, movedIdentity)) {
1962
+ try {
1963
+ linkSync(stagingCleanupPath, artifact.rollbackPath);
1964
+ syncDirectory(dirname(artifact.rollbackPath));
1965
+ }
1966
+ catch (error) {
1967
+ if (!isErrno(error, 'EEXIST'))
1968
+ throw error;
1969
+ }
1970
+ if (filesystemEntryPresent(artifact.rollbackPath)) {
1971
+ const restoredIdentity = identityFor(artifact.rollbackPath);
1972
+ if (sameFileId(restoredIdentity, movedIdentity)) {
1973
+ removeDurableFile(stagingCleanupPath);
1974
+ }
1975
+ }
1976
+ throw new Error(`bootstrap rollback restored a staging inode replaced during cleanup: ${artifact.rollbackPath}`);
1977
+ }
1978
+ ownedIdentity = movedIdentity;
1979
+ }
1980
+ hooks.beforeStagingDelete?.(artifact);
1981
+ const beforeDelete = identityFor(ownedPath);
1982
+ if (!sameFileId(ownedIdentity, beforeDelete)) {
1983
+ throw new Error(`bootstrap artifact staging identity changed before cleanup: ${ownedPath}`);
1984
+ }
1985
+ removeDurableFile(ownedPath);
1986
+ continue;
1987
+ }
1988
+ let durableOwnership;
1989
+ if (artifact.claimOwnership?.phase === 'created') {
1990
+ // A persisted publisher receipt owns this exact inode independently of
1991
+ // content. Plan drift is a rollback trigger, not a reason to orphan it.
1992
+ durableOwnership = {
1993
+ size: expectedIdentity.size,
1994
+ sha256: expectedIdentity.sha256,
1995
+ device: artifact.claimOwnership.device,
1996
+ inode: artifact.claimOwnership.inode,
1997
+ };
1998
+ if (claimIdentity && !sameFileId(claimIdentity, durableOwnership)) {
1999
+ throw new Error(`bootstrap artifact claim file identity changed: ${artifact.claimPath}`);
2000
+ }
2001
+ if (receiptIdentity && !sameFileId(receiptIdentity, durableOwnership)) {
2002
+ throw new Error(`bootstrap artifact ownership receipt file identity changed: ${artifact.rollbackPath}`);
2003
+ }
2004
+ if (filesystemEntryPresent(artifact.path)) {
2005
+ const finalIdentity = identityFor(artifact.path);
2006
+ if (!sameFileId(finalIdentity, durableOwnership)) {
2007
+ throw new Error(`bootstrap artifact file identity changed: ${artifact.path}`);
2008
+ }
2009
+ }
2010
+ }
2011
+ else if (artifact.claimOwnership?.phase === 'armed') {
2012
+ if (!claimIdentity) {
2013
+ if (receiptIdentity)
2014
+ throw new Error(`bootstrap artifact staging cleanup was not completed: ${artifact.path}`);
2015
+ }
2016
+ else {
2017
+ if (!receiptIdentity) {
2018
+ throw new Error(`bootstrap artifact claim has no durable ownership receipt: ${artifact.claimPath}`);
2019
+ }
2020
+ if (!sameFileId(claimIdentity, receiptIdentity)) {
2021
+ throw new Error(`bootstrap artifact ownership receipt does not bind the opened claim: ${artifact.path}`);
2022
+ }
2023
+ assertExpectedArtifactIdentity(expectedIdentity, claimIdentity, artifact.claimPath);
2024
+ durableOwnership = claimIdentity;
2025
+ }
2026
+ }
2027
+ else if (claimIdentity) {
2028
+ assertExpectedArtifactIdentity(expectedIdentity, claimIdentity, artifact.claimPath);
2029
+ durableOwnership = claimIdentity;
2030
+ }
2031
+ else if (expectedIdentity.device !== undefined) {
2032
+ durableOwnership = expectedIdentity;
2033
+ }
2034
+ const assertOwned = (identity) => {
2035
+ if (durableOwnership) {
2036
+ if (artifact.claimOwnership === undefined && claimIdentity === undefined) {
2037
+ assertExpectedArtifactIdentity(expectedIdentity, identity, artifact.path);
2038
+ return;
2039
+ }
2040
+ if (!sameFileId(identity, durableOwnership)) {
2041
+ throw new Error(`bootstrap rollback claim does not bind the owned artifact: ${artifact.path}`);
2042
+ }
2043
+ if (artifact.claimOwnership?.phase === 'armed') {
2044
+ assertExpectedArtifactIdentity(expectedIdentity, identity, artifact.path);
2045
+ }
2046
+ return;
2047
+ }
2048
+ if (expectedIdentity.device === undefined) {
2049
+ throw new Error(`bootstrap artifact has no durable publisher claim: ${artifact.path}`);
2050
+ }
2051
+ assertExpectedArtifactIdentity(expectedIdentity, identity, artifact.path);
2052
+ };
2053
+ const restoreMovedForeign = (sourcePath, rollbackIdentity, cause) => {
2054
+ if (filesystemEntryPresent(sourcePath)) {
2055
+ const finalIdentity = identityFor(sourcePath);
2056
+ if (!sameFileId(finalIdentity, rollbackIdentity)) {
2057
+ throw new Error(`bootstrap rollback preserved an unowned quarantine because the canonical path is occupied: ${sourcePath}`, { cause });
2058
+ }
2059
+ }
2060
+ else {
2061
+ try {
2062
+ linkSync(artifact.rollbackPath, sourcePath);
2063
+ syncDirectory(dirname(sourcePath));
2064
+ }
2065
+ catch (error) {
2066
+ if (!isErrno(error, 'EEXIST'))
2067
+ throw error;
2068
+ throw new Error(`bootstrap rollback preserved an unowned quarantine because the canonical path could not be restored: ${sourcePath}`, { cause });
2069
+ }
2070
+ const restoredIdentity = identityFor(sourcePath);
2071
+ const currentRollbackIdentity = identityFor(artifact.rollbackPath);
2072
+ if (!sameFileId(restoredIdentity, currentRollbackIdentity)
2073
+ || !sameFileId(currentRollbackIdentity, rollbackIdentity)) {
2074
+ throw new Error(`bootstrap rollback preserved an unowned quarantine after an inconclusive restore: ${sourcePath}`, { cause });
2075
+ }
2076
+ }
2077
+ removeDurableFile(artifact.rollbackPath);
2078
+ throw new Error(`bootstrap rollback restored an unowned artifact moved during cleanup: ${sourcePath}`, { cause });
2079
+ };
2080
+ const removeOwnedClaim = () => {
2081
+ if (!filesystemEntryPresent(artifact.claimPath))
2082
+ return;
2083
+ if (filesystemEntryPresent(artifact.rollbackPath)) {
2084
+ throw new Error(`bootstrap rollback quarantine is occupied before claim cleanup: ${artifact.claimPath}`);
2085
+ }
2086
+ const beforeMove = identityFor(artifact.claimPath);
2087
+ assertOwned(beforeMove);
2088
+ hooks.beforeClaimQuarantine?.(artifact);
2089
+ renameSync(artifact.claimPath, artifact.rollbackPath);
2090
+ syncDirectory(dirname(artifact.claimPath));
2091
+ const movedIdentity = identityFor(artifact.rollbackPath);
2092
+ try {
2093
+ assertOwned(movedIdentity);
2094
+ }
2095
+ catch (error) {
2096
+ restoreMovedForeign(artifact.claimPath, movedIdentity, error);
2097
+ }
2098
+ if (filesystemEntryPresent(artifact.claimPath)) {
2099
+ throw new Error(`bootstrap rollback preserved its claim quarantine because the canonical path was recreated: ${artifact.claimPath}`);
2100
+ }
2101
+ hooks.beforeClaimQuarantineDelete?.(artifact);
2102
+ const beforeDelete = identityFor(artifact.rollbackPath);
2103
+ try {
2104
+ assertOwned(beforeDelete);
2105
+ }
2106
+ catch (error) {
2107
+ restoreMovedForeign(artifact.claimPath, beforeDelete, error);
2108
+ }
2109
+ removeDurableFile(artifact.rollbackPath);
2110
+ };
2111
+ if (filesystemEntryPresent(artifact.rollbackPath)) {
2112
+ const rollbackIdentity = identityFor(artifact.rollbackPath);
2113
+ try {
2114
+ assertOwned(rollbackIdentity);
2115
+ }
2116
+ catch (error) {
2117
+ restoreMovedForeign(artifact.path, rollbackIdentity, error);
2118
+ }
2119
+ if (filesystemEntryPresent(artifact.path)) {
2120
+ const finalIdentity = identityFor(artifact.path);
2121
+ if (!sameFileId(finalIdentity, rollbackIdentity)) {
2122
+ throw new Error(`bootstrap rollback quarantine does not bind the owned artifact: ${artifact.path}`);
2123
+ }
2124
+ assertOwned(finalIdentity);
2125
+ removeDurableFile(artifact.rollbackPath);
2126
+ }
2127
+ else {
2128
+ hooks.beforeQuarantineDelete?.(artifact);
2129
+ const beforeDelete = identityFor(artifact.rollbackPath);
2130
+ try {
2131
+ assertOwned(beforeDelete);
2132
+ }
2133
+ catch (error) {
2134
+ restoreMovedForeign(artifact.path, beforeDelete, error);
2135
+ }
2136
+ removeDurableFile(artifact.rollbackPath);
2137
+ }
2138
+ if (!filesystemEntryPresent(artifact.path)) {
2139
+ removeOwnedClaim();
2140
+ continue;
2141
+ }
2142
+ }
2143
+ if (!filesystemEntryPresent(artifact.path)) {
2144
+ removeOwnedClaim();
2145
+ continue;
2146
+ }
2147
+ const finalIdentity = identityFor(artifact.path);
2148
+ assertOwned(finalIdentity);
2149
+ if (!filesystemEntryPresent(artifact.claimPath)) {
2150
+ linkSync(artifact.path, artifact.claimPath);
2151
+ syncDirectory(dirname(artifact.path));
2152
+ }
2153
+ const durableClaimIdentity = identityFor(artifact.claimPath);
2154
+ if (!sameFileId(finalIdentity, durableClaimIdentity)) {
2155
+ throw new Error(`bootstrap rollback claim does not bind the owned artifact: ${artifact.path}`);
2156
+ }
2157
+ hooks.beforeQuarantine?.(artifact);
2158
+ renameSync(artifact.path, artifact.rollbackPath);
2159
+ syncDirectory(dirname(artifact.path));
2160
+ hooks.afterQuarantine?.(artifact);
2161
+ const rollbackIdentity = identityFor(artifact.rollbackPath);
2162
+ try {
2163
+ assertOwned(rollbackIdentity);
2164
+ }
2165
+ catch (error) {
2166
+ restoreMovedForeign(artifact.path, rollbackIdentity, error);
2167
+ }
2168
+ if (filesystemEntryPresent(artifact.path)) {
2169
+ throw new Error(`bootstrap rollback preserved its quarantine because the canonical path was recreated: ${artifact.path}`);
2170
+ }
2171
+ hooks.beforeQuarantineDelete?.(artifact);
2172
+ const beforeDelete = identityFor(artifact.rollbackPath);
2173
+ try {
2174
+ assertOwned(beforeDelete);
2175
+ }
2176
+ catch (error) {
2177
+ restoreMovedForeign(artifact.path, beforeDelete, error);
2178
+ }
2179
+ removeDurableFile(artifact.rollbackPath);
2180
+ removeOwnedClaim();
2181
+ }
2182
+ }