@xlinklight/testkit 7.0.0-rc.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +169 -169
  3. package/package.json +4 -4
  4. package/src/architecture-database.d.mts +36 -36
  5. package/src/architecture-database.mjs +64 -64
  6. package/src/artifact-observation.mjs +50 -50
  7. package/src/browser-lifecycle.mjs +45 -45
  8. package/src/cloudflare-browser.mjs +41 -41
  9. package/src/cloudflare-pages.d.mts +34 -34
  10. package/src/cloudflare-pages.mjs +170 -170
  11. package/src/cloudflare-provider-http.mjs +32 -32
  12. package/src/cluster-directory.d.mts +16 -16
  13. package/src/cluster-directory.mjs +90 -90
  14. package/src/core-publishing.d.mts +75 -75
  15. package/src/core-publishing.mjs +214 -214
  16. package/src/dev-command-runner.mjs +97 -97
  17. package/src/fixture-path.mjs +19 -19
  18. package/src/function-admission.d.mts +1 -1
  19. package/src/function-admission.mjs +58 -58
  20. package/src/host-artifact.mjs +32 -32
  21. package/src/host-stop.mjs +15 -15
  22. package/src/lifecycle-trace.mjs +32 -32
  23. package/src/managed-native-fixture.d.mts +84 -84
  24. package/src/managed-native-fixture.mjs +209 -209
  25. package/src/native-fixture.mjs +125 -125
  26. package/src/native-platform.mjs +56 -56
  27. package/src/operator-accounts.mjs +103 -103
  28. package/src/owned-process.mjs +75 -75
  29. package/src/owner-database.mjs +215 -215
  30. package/src/owner-operator-build.mjs +33 -33
  31. package/src/owner-production-browser.mjs +215 -215
  32. package/src/owner-production-instances.mjs +41 -41
  33. package/src/owner-production.d.mts +104 -104
  34. package/src/owner-production.mjs +338 -338
  35. package/src/owner-worker-build.mjs +83 -83
  36. package/src/prebuilt-output.d.mts +2 -2
  37. package/src/prebuilt-output.mjs +104 -104
  38. package/src/production-hosts.mjs +38 -38
  39. package/src/release-build.mjs +71 -71
  40. package/src/release-control.mjs +45 -45
  41. package/src/release-coordinator.d.mts +9 -9
  42. package/src/release-coordinator.mjs +222 -222
  43. package/src/release-credentials.d.mts +8 -8
  44. package/src/release-credentials.mjs +97 -97
  45. package/src/release-mutex.mjs +38 -38
  46. package/src/release-operator.d.mts +6 -6
  47. package/src/release-operator.mjs +59 -59
  48. package/src/release-supabase.d.mts +7 -7
  49. package/src/release-supabase.mjs +37 -37
  50. package/src/release-vercel.d.mts +22 -22
  51. package/src/release-vercel.mjs +51 -51
  52. package/src/release-writer.d.mts +6 -6
  53. package/src/release-writer.mjs +172 -172
  54. package/src/retained-postgres-shutdown.d.mts +51 -51
  55. package/src/retained-postgres-shutdown.mjs +262 -262
  56. package/src/temporary-acquisition.mjs +62 -62
  57. package/src/temporary-scope.d.mts +47 -47
  58. package/src/temporary-scope.mjs +268 -268
  59. package/src/worker-artifact.mjs +214 -214
@@ -1,84 +1,84 @@
1
- export interface ManagedDirectoryIdentity {
2
- readonly path: string;
3
- readonly dev: string;
4
- readonly ino: string;
5
- }
6
-
7
- export interface ManagedNativeFixtureEnvironment {
8
- readonly [key: string]: string | undefined;
9
- readonly LLR14_EVIDENCE_ROOT?: string;
10
- readonly LLR14_NATIVE_FIXTURE_BASE?: string;
11
- readonly TEMP?: string;
12
- readonly TMP?: string;
13
- readonly TMPDIR?: string;
14
- }
15
-
16
- export interface ManagedNativeFixtureBinding {
17
- readonly version: 1;
18
- readonly namespace: string;
19
- readonly ownerPid: number;
20
- readonly marker: string;
21
- readonly taskRoot: ManagedDirectoryIdentity;
22
- readonly nativeRoot: ManagedDirectoryIdentity;
23
- readonly attempt: ManagedDirectoryIdentity;
24
- readonly evidence: ManagedDirectoryIdentity;
25
- readonly temporary: ManagedDirectoryIdentity;
26
- readonly ownership: ManagedDirectoryIdentity & { readonly bytes: number; readonly sha256: string };
27
- }
28
-
29
- export interface ManagedNativeRetentionReceipt {
30
- readonly schemaVersion: 2;
31
- readonly at: string;
32
- readonly namespace: string;
33
- readonly ownerPid: number;
34
- readonly directory: string;
35
- readonly temporary: string;
36
- readonly evidence: string;
37
- readonly ownershipSha256: string;
38
- readonly ownershipVerified: true;
39
- readonly status: string;
40
- readonly retained: false;
41
- readonly copied: false;
42
- readonly removed: boolean;
43
- }
44
-
45
- export interface ManagedRetainedFixture {
46
- readonly directory: string;
47
- readonly temporary: string;
48
- readonly evidence: string;
49
- readonly managed: true;
50
- readonly binding: ManagedNativeFixtureBinding;
51
- verify(): void;
52
- checkBudget(): { bytes: number; entries: number };
53
- beginLaunch(): void;
54
- trackPid(pid: number): void;
55
- finalize(outcome: {status: string; closed: boolean}): ManagedNativeRetentionReceipt;
56
- }
57
-
58
- export function resolveManagedFixtureEvidenceBase(
59
- legacyBase: string,
60
- namespace: string,
61
- environment?: ManagedNativeFixtureEnvironment,
62
- ): string;
63
-
64
- export function assertFixtureEvidenceCapacity(base: string, options?: {attemptPrefix?: string}): {bytes: number; entries: number};
65
-
66
- export function assertManagedFixtureAuthority(environment?: ManagedNativeFixtureEnvironment): {
67
- task: ManagedDirectoryIdentity;
68
- native: ManagedDirectoryIdentity;
69
- };
70
-
71
- export function createManagedRetainedFixture(options: {
72
- root: string;
73
- evidence: string;
74
- namespace: string;
75
- environment?: ManagedNativeFixtureEnvironment;
76
- }): ManagedRetainedFixture | undefined;
77
-
78
- export function validateManagedFixtureEvidence(options: {
79
- evidence: string;
80
- legacyBase: string;
81
- namespace: string;
82
- binding?: ManagedNativeFixtureBinding;
83
- environment?: ManagedNativeFixtureEnvironment;
84
- }): void;
1
+ export interface ManagedDirectoryIdentity {
2
+ readonly path: string;
3
+ readonly dev: string;
4
+ readonly ino: string;
5
+ }
6
+
7
+ export interface ManagedNativeFixtureEnvironment {
8
+ readonly [key: string]: string | undefined;
9
+ readonly LLR14_EVIDENCE_ROOT?: string;
10
+ readonly LLR14_NATIVE_FIXTURE_BASE?: string;
11
+ readonly TEMP?: string;
12
+ readonly TMP?: string;
13
+ readonly TMPDIR?: string;
14
+ }
15
+
16
+ export interface ManagedNativeFixtureBinding {
17
+ readonly version: 1;
18
+ readonly namespace: string;
19
+ readonly ownerPid: number;
20
+ readonly marker: string;
21
+ readonly taskRoot: ManagedDirectoryIdentity;
22
+ readonly nativeRoot: ManagedDirectoryIdentity;
23
+ readonly attempt: ManagedDirectoryIdentity;
24
+ readonly evidence: ManagedDirectoryIdentity;
25
+ readonly temporary: ManagedDirectoryIdentity;
26
+ readonly ownership: ManagedDirectoryIdentity & { readonly bytes: number; readonly sha256: string };
27
+ }
28
+
29
+ export interface ManagedNativeRetentionReceipt {
30
+ readonly schemaVersion: 2;
31
+ readonly at: string;
32
+ readonly namespace: string;
33
+ readonly ownerPid: number;
34
+ readonly directory: string;
35
+ readonly temporary: string;
36
+ readonly evidence: string;
37
+ readonly ownershipSha256: string;
38
+ readonly ownershipVerified: true;
39
+ readonly status: string;
40
+ readonly retained: false;
41
+ readonly copied: false;
42
+ readonly removed: boolean;
43
+ }
44
+
45
+ export interface ManagedRetainedFixture {
46
+ readonly directory: string;
47
+ readonly temporary: string;
48
+ readonly evidence: string;
49
+ readonly managed: true;
50
+ readonly binding: ManagedNativeFixtureBinding;
51
+ verify(): void;
52
+ checkBudget(): { bytes: number; entries: number };
53
+ beginLaunch(): void;
54
+ trackPid(pid: number): void;
55
+ finalize(outcome: {status: string; closed: boolean}): ManagedNativeRetentionReceipt;
56
+ }
57
+
58
+ export function resolveManagedFixtureEvidenceBase(
59
+ legacyBase: string,
60
+ namespace: string,
61
+ environment?: ManagedNativeFixtureEnvironment,
62
+ ): string;
63
+
64
+ export function assertFixtureEvidenceCapacity(base: string, options?: {attemptPrefix?: string}): {bytes: number; entries: number};
65
+
66
+ export function assertManagedFixtureAuthority(environment?: ManagedNativeFixtureEnvironment): {
67
+ task: ManagedDirectoryIdentity;
68
+ native: ManagedDirectoryIdentity;
69
+ };
70
+
71
+ export function createManagedRetainedFixture(options: {
72
+ root: string;
73
+ evidence: string;
74
+ namespace: string;
75
+ environment?: ManagedNativeFixtureEnvironment;
76
+ }): ManagedRetainedFixture | undefined;
77
+
78
+ export function validateManagedFixtureEvidence(options: {
79
+ evidence: string;
80
+ legacyBase: string;
81
+ namespace: string;
82
+ binding?: ManagedNativeFixtureBinding;
83
+ environment?: ManagedNativeFixtureEnvironment;
84
+ }): void;
@@ -1,209 +1,209 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import crypto from "node:crypto";
4
- import { createTemporaryScope } from "./temporary-scope.mjs";
5
-
6
- const markerName = "managed-native-ownership.json";
7
- const receiptName = "native-retention.json";
8
- const maximumMetadataBytes = 8192;
9
- const beneath = (root, file) => file !== root && file.startsWith(root + path.sep);
10
- const hash = bytes => crypto.createHash("sha256").update(bytes).digest("hex");
11
-
12
- export function assertFixtureEvidenceCapacity(base, {attemptPrefix = 'attempt-'} = {}) {
13
- if (!/^[a-z][a-z0-9-]*-$/.test(attemptPrefix)) throw Error('INVALID_FIXTURE_EVIDENCE_PREFIX');
14
- absoluteDirectory(base);
15
- const attempts = fs.readdirSync(base).filter(name => name.startsWith(attemptPrefix) && fs.lstatSync(path.join(base, name)).isDirectory());
16
- if (attempts.length >= 64) throw Error('FIXTURE_EVIDENCE_ATTEMPT_LIMIT');
17
- let bytes = 0, entries = 0; const stack = [base];
18
- while (stack.length) {
19
- if (++entries > 100000) throw Error('FIXTURE_EVIDENCE_ENTRY_LIMIT');
20
- const file = stack.pop(), stat = fs.lstatSync(file);
21
- if (stat.isSymbolicLink()) throw Error('FIXTURE_EVIDENCE_LINKED');
22
- if (stat.isDirectory()) for (const name of fs.readdirSync(file)) stack.push(path.join(file, name));
23
- else if (stat.isFile()) bytes += stat.size;
24
- else throw Error('FIXTURE_EVIDENCE_TYPE_UNKNOWN');
25
- if (bytes > 512 * 1024 ** 2) throw Error('FIXTURE_EVIDENCE_BUDGET_EXCEEDED');
26
- }
27
- return {bytes, entries};
28
- }
29
-
30
- function namespaceParts(namespace) {
31
- if (typeof namespace !== "string" || !namespace.split("/").every(part => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(part))) throw Error("INVALID_MANAGED_FIXTURE_NAMESPACE");
32
- return namespace.split("/");
33
- }
34
- function absoluteDirectory(value) {
35
- if (typeof value !== "string" || !path.isAbsolute(value)) throw Error("INVALID_MANAGED_FIXTURE_ROOT");
36
- const directory = path.resolve(value);
37
- const ancestors = [];
38
- for (let current = directory;; current = path.dirname(current)) {
39
- ancestors.push(current);
40
- if (path.dirname(current) === current) break;
41
- }
42
- // Check ancestors before touching a child through a potentially linked parent.
43
- for (const current of ancestors.reverse()) {
44
- const stat = fs.lstatSync(current, { bigint: true });
45
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
46
- }
47
- return fs.realpathSync(directory);
48
- }
49
- function identity(directory) {
50
- const canonical = absoluteDirectory(directory);
51
- const stat = fs.lstatSync(canonical, { bigint: true });
52
- if (typeof stat.dev !== "bigint" || typeof stat.ino !== "bigint" || stat.dev < 0n || stat.ino <= 0n) throw Error("INVALID_MANAGED_FIXTURE_IDENTITY");
53
- return { path: canonical, dev: String(stat.dev), ino: String(stat.ino) };
54
- }
55
- function privateDirectory(directory) {
56
- const stat = fs.lstatSync(directory, { bigint: true });
57
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
58
- if (process.platform !== "win32" && (stat.uid !== BigInt(process.getuid()) || (stat.mode & 0o777n) !== 0o700n)) throw Error("MANAGED_FIXTURE_REQUIRES_PRIVATE_DIRECTORY");
59
- }
60
- function sameIdentity(expected, observed) {
61
- return expected && expected.path === observed.path && expected.dev === observed.dev && expected.ino === observed.ino;
62
- }
63
- function verifyIdentity(expected) {
64
- if (!expected || typeof expected.path !== "string" || !sameIdentity(expected, identity(expected.path))) throw Error("MANAGED_FIXTURE_DIRECTORY_IDENTITY_CHANGED");
65
- }
66
- function ensureChildDirectories(root, parts) {
67
- let directory = root;
68
- for (const part of parts) {
69
- directory = path.join(directory, part);
70
- try { fs.lstatSync(directory); }
71
- catch (error) { if (error.code !== "ENOENT") throw error; fs.mkdirSync(directory, { mode: 0o700 }); }
72
- absoluteDirectory(directory);
73
- privateDirectory(directory);
74
- }
75
- return fs.realpathSync(directory);
76
- }
77
- function metadataIdentity(file, stat) {
78
- if (stat.isSymbolicLink() || !stat.isFile() || typeof stat.dev !== "bigint" || typeof stat.ino !== "bigint" || typeof stat.nlink !== "bigint" || typeof stat.size !== "bigint" || stat.dev < 0n || stat.ino <= 0n || stat.nlink !== 1n || stat.size <= 0n || stat.size > BigInt(maximumMetadataBytes)) throw Error("INVALID_MANAGED_FIXTURE_METADATA");
79
- return { path: file, dev: String(stat.dev), ino: String(stat.ino), bytes: Number(stat.size) };
80
- }
81
- function readMetadata(file, expected) {
82
- absoluteDirectory(path.dirname(file));
83
- const before = metadataIdentity(file, fs.lstatSync(file, { bigint: true }));
84
- if (expected && (!sameIdentity(expected, before) || expected.bytes !== before.bytes)) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
85
- const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
86
- let bytes;
87
- try {
88
- const opened = metadataIdentity(file, fs.fstatSync(descriptor, { bigint: true }));
89
- if (!sameIdentity(before, opened) || before.bytes !== opened.bytes) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
90
- bytes = fs.readFileSync(descriptor);
91
- if (bytes.length !== opened.bytes) throw Error("MANAGED_FIXTURE_METADATA_CHANGED");
92
- } finally { fs.closeSync(descriptor); }
93
- const after = metadataIdentity(file, fs.lstatSync(file, { bigint: true }));
94
- if (!sameIdentity(before, after) || before.bytes !== after.bytes) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
95
- absoluteDirectory(path.dirname(file));
96
- const sha256 = hash(bytes);
97
- if (expected && expected.sha256 !== sha256) throw Error("MANAGED_FIXTURE_METADATA_CHANGED");
98
- return { identity: { ...after, sha256 }, value: JSON.parse(bytes.toString("utf8")) };
99
- }
100
- function markerBody(binding) {
101
- return { version: binding.version, namespace: binding.namespace, ownerPid: binding.ownerPid, marker: binding.marker, taskRoot: binding.taskRoot, nativeRoot: binding.nativeRoot, attempt: binding.attempt, evidence: binding.evidence, temporary: binding.temporary };
102
- }
103
- function verifyBinding(binding, namespace, task, native) {
104
- namespaceParts(namespace);
105
- if (!binding || binding.version !== 1 || binding.namespace !== namespace || !Number.isSafeInteger(binding.ownerPid) || binding.ownerPid <= 0 || typeof binding.marker !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(binding.marker)) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
106
- if ([binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary].some(value => !value || typeof value.path !== "string" || !path.isAbsolute(value.path) || typeof value.dev !== "string" || !/^\d+$/.test(value.dev) || typeof value.ino !== "string" || !/^[1-9]\d*$/.test(value.ino))) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
107
- if (!sameIdentity(binding.taskRoot, task) || !sameIdentity(binding.nativeRoot, native)) throw Error("MANAGED_FIXTURE_AUTHORITY_CHANGED");
108
- const expectedParent = path.join(native.path, "llr14-native-fixtures", ...namespaceParts(namespace));
109
- if (!binding.attempt || path.dirname(binding.attempt.path) !== expectedParent || path.basename(binding.attempt.path) !== 'attempt-slot') throw Error("MANAGED_FIXTURE_ATTEMPT_OUTSIDE_AUTHORITY");
110
- if (!binding.evidence || (!beneath(task.path, binding.evidence.path) && binding.evidence.path !== binding.attempt.path)) throw Error("MANAGED_FIXTURE_EVIDENCE_OUTSIDE_AUTHORITY");
111
- if (!binding.temporary || binding.temporary.path !== path.join(binding.attempt.path, "temporary")) throw Error("MANAGED_FIXTURE_TEMPORARY_OUTSIDE_ATTEMPT");
112
- for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) verifyIdentity(value);
113
- privateDirectory(binding.attempt.path);
114
- privateDirectory(binding.temporary.path);
115
- const marker = path.join(binding.attempt.path, markerName);
116
- if (!binding.ownership || binding.ownership.path !== marker) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
117
- const stored = readMetadata(marker, binding.ownership);
118
- if (JSON.stringify(stored.value) !== JSON.stringify(markerBody(binding))) throw Error("MANAGED_FIXTURE_MARKER_BINDING_CHANGED");
119
- for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) verifyIdentity(value);
120
- }
121
-
122
- // The injected roots come from the resource owner. Routing grants no capacity,
123
- // service permission or closure proof, and never falls back when a root is bad.
124
- export function resolveManagedFixtureEvidenceBase(legacyBase, namespace, environment = process.env) {
125
- if (environment.LLR14_EVIDENCE_ROOT === undefined) return legacyBase;
126
- const task = identity(environment.LLR14_EVIDENCE_ROOT);
127
- const parts = namespaceParts(namespace);
128
- let current = task.path;
129
- for (const part of parts) {
130
- current = path.join(current, part);
131
- let stat;
132
- try { stat = fs.lstatSync(current, { bigint: true }); }
133
- catch (error) { if (error.code !== "ENOENT") throw error; break; }
134
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
135
- absoluteDirectory(current);
136
- }
137
- verifyIdentity(task);
138
- return path.join(task.path, ...parts);
139
- }
140
-
141
- export function assertManagedFixtureAuthority(environment = process.env) {
142
- if (environment.LLR14_EVIDENCE_ROOT === undefined) throw Error('MANAGED_FIXTURE_AUTHORITY_REQUIRED');
143
- const task = identity(environment.LLR14_EVIDENCE_ROOT);
144
- const native = identity(environment.TEMP), alternate = identity(environment.TMP);
145
- if (!sameIdentity(native, alternate) || (environment.TMPDIR !== undefined && !sameIdentity(native, identity(environment.TMPDIR))) || (environment.LLR14_NATIVE_FIXTURE_BASE !== undefined && !sameIdentity(native, identity(environment.LLR14_NATIVE_FIXTURE_BASE)))) throw Error("MANAGED_FIXTURE_TEMP_AUTHORITY_MISMATCH");
146
- if (native.path === task.path || beneath(native.path, task.path) || beneath(task.path, native.path)) throw Error("MANAGED_FIXTURE_AUTHORITY_ROOTS_OVERLAP");
147
- return { task, native };
148
- }
149
-
150
- export function createManagedRetainedFixture({ root, evidence, namespace, environment = process.env }) {
151
- if (typeof root !== "string" || !path.isAbsolute(root)) throw Error("MANAGED_FIXTURE_ROOT_REQUIRED");
152
- if (environment.LLR14_EVIDENCE_ROOT === undefined) return undefined;
153
- const parts = namespaceParts(namespace), { task, native } = assertManagedFixtureAuthority(environment);
154
- const requestedEvidence = identity(evidence);
155
- if (!beneath(task.path, requestedEvidence.path)) throw Error("MANAGED_FIXTURE_EVIDENCE_OUTSIDE_AUTHORITY");
156
- const parent = ensureChildDirectories(native.path, ["llr14-native-fixtures", ...parts]);
157
- verifyIdentity(task); verifyIdentity(native); verifyIdentity(requestedEvidence);
158
- const lifecycle = createTemporaryScope({ root, scope: parent, label: 'attempt', maximumBytes: 1024 ** 3, requiresClosureProof: true });
159
- const directory = lifecycle.directory;
160
- try {
161
- privateDirectory(directory);
162
- const temporary = path.join(directory, "temporary");
163
- fs.mkdirSync(temporary, { mode: 0o700 });
164
- privateDirectory(temporary);
165
- const body = { version: 1, namespace, ownerPid: process.pid, marker: crypto.randomUUID(), taskRoot: task, nativeRoot: native, attempt: identity(directory), evidence: requestedEvidence, temporary: identity(temporary) };
166
- const marker = path.join(directory, markerName);
167
- fs.writeFileSync(marker, JSON.stringify(body) + "\n", { mode: 0o600, flag: "wx" });
168
- const ownership = readMetadata(marker).identity;
169
- const binding = Object.freeze({ ...body, ownership: Object.freeze(ownership) });
170
- for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) Object.freeze(value);
171
- const verify = () => verifyBinding(binding, namespace, identity(task.path), identity(native.path));
172
- verify();
173
- let finalized;
174
- return Object.freeze({
175
- directory, temporary, evidence: binding.evidence.path, managed: true, binding, verify,
176
- checkBudget: lifecycle.checkBudget,
177
- beginLaunch: lifecycle.beginLaunch,
178
- trackPid: lifecycle.trackPid,
179
- finalize({ status, closed }) {
180
- if (finalized) return finalized;
181
- verify();
182
- const receipt = path.join(binding.evidence.path, receiptName);
183
- const value = { schemaVersion: 2, at: new Date().toISOString(), namespace, ownerPid: binding.ownerPid, directory, temporary, evidence: binding.evidence.path, ownershipSha256: binding.ownership.sha256, ownershipVerified: true, status, retained: false, copied: false, removed: false };
184
- fs.writeFileSync(receipt, JSON.stringify(value) + "\n", { mode: 0o600, flag: 'wx' });
185
- const receiptIdentity = readMetadata(receipt).identity;
186
- try { lifecycle.finish({ status, closed }); value.removed = true; }
187
- finally { readMetadata(receipt, receiptIdentity); fs.writeFileSync(receipt, JSON.stringify(value) + "\n", { mode: 0o600 }); }
188
- finalized = Object.freeze(value);
189
- return finalized;
190
- },
191
- });
192
- } catch (error) {
193
- try { lifecycle.finish({ status: 'initialization-failed', closed: true }); }
194
- catch (cleanupError) { error.cleanupError = cleanupError; }
195
- throw error;
196
- }
197
- }
198
-
199
- export function validateManagedFixtureEvidence({ evidence, legacyBase, namespace, binding, environment = process.env }) {
200
- if (binding === undefined) {
201
- if (environment.LLR14_EVIDENCE_ROOT !== undefined) throw Error("MANAGED_FIXTURE_BINDING_REQUIRED");
202
- if (typeof evidence !== "string" || !beneath(fs.realpathSync(legacyBase), fs.realpathSync(evidence))) throw Error("Unapproved service fixture");
203
- return;
204
- }
205
- if (environment.LLR14_EVIDENCE_ROOT === undefined || environment.LLR14_NATIVE_FIXTURE_BASE === undefined) throw Error("MANAGED_FIXTURE_STABLE_AUTHORITY_REQUIRED");
206
- const task = identity(environment.LLR14_EVIDENCE_ROOT), native = identity(environment.LLR14_NATIVE_FIXTURE_BASE);
207
- verifyBinding(binding, namespace, task, native);
208
- if (typeof evidence !== "string" || evidence !== binding.evidence.path || !sameIdentity(binding.evidence, identity(evidence))) throw Error("MANAGED_FIXTURE_EVIDENCE_BINDING_CHANGED");
209
- }
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import { createTemporaryScope } from "./temporary-scope.mjs";
5
+
6
+ const markerName = "managed-native-ownership.json";
7
+ const receiptName = "native-retention.json";
8
+ const maximumMetadataBytes = 8192;
9
+ const beneath = (root, file) => file !== root && file.startsWith(root + path.sep);
10
+ const hash = bytes => crypto.createHash("sha256").update(bytes).digest("hex");
11
+
12
+ export function assertFixtureEvidenceCapacity(base, {attemptPrefix = 'attempt-'} = {}) {
13
+ if (!/^[a-z][a-z0-9-]*-$/.test(attemptPrefix)) throw Error('INVALID_FIXTURE_EVIDENCE_PREFIX');
14
+ absoluteDirectory(base);
15
+ const attempts = fs.readdirSync(base).filter(name => name.startsWith(attemptPrefix) && fs.lstatSync(path.join(base, name)).isDirectory());
16
+ if (attempts.length >= 64) throw Error('FIXTURE_EVIDENCE_ATTEMPT_LIMIT');
17
+ let bytes = 0, entries = 0; const stack = [base];
18
+ while (stack.length) {
19
+ if (++entries > 100000) throw Error('FIXTURE_EVIDENCE_ENTRY_LIMIT');
20
+ const file = stack.pop(), stat = fs.lstatSync(file);
21
+ if (stat.isSymbolicLink()) throw Error('FIXTURE_EVIDENCE_LINKED');
22
+ if (stat.isDirectory()) for (const name of fs.readdirSync(file)) stack.push(path.join(file, name));
23
+ else if (stat.isFile()) bytes += stat.size;
24
+ else throw Error('FIXTURE_EVIDENCE_TYPE_UNKNOWN');
25
+ if (bytes > 512 * 1024 ** 2) throw Error('FIXTURE_EVIDENCE_BUDGET_EXCEEDED');
26
+ }
27
+ return {bytes, entries};
28
+ }
29
+
30
+ function namespaceParts(namespace) {
31
+ if (typeof namespace !== "string" || !namespace.split("/").every(part => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(part))) throw Error("INVALID_MANAGED_FIXTURE_NAMESPACE");
32
+ return namespace.split("/");
33
+ }
34
+ function absoluteDirectory(value) {
35
+ if (typeof value !== "string" || !path.isAbsolute(value)) throw Error("INVALID_MANAGED_FIXTURE_ROOT");
36
+ const directory = path.resolve(value);
37
+ const ancestors = [];
38
+ for (let current = directory;; current = path.dirname(current)) {
39
+ ancestors.push(current);
40
+ if (path.dirname(current) === current) break;
41
+ }
42
+ // Check ancestors before touching a child through a potentially linked parent.
43
+ for (const current of ancestors.reverse()) {
44
+ const stat = fs.lstatSync(current, { bigint: true });
45
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
46
+ }
47
+ return fs.realpathSync(directory);
48
+ }
49
+ function identity(directory) {
50
+ const canonical = absoluteDirectory(directory);
51
+ const stat = fs.lstatSync(canonical, { bigint: true });
52
+ if (typeof stat.dev !== "bigint" || typeof stat.ino !== "bigint" || stat.dev < 0n || stat.ino <= 0n) throw Error("INVALID_MANAGED_FIXTURE_IDENTITY");
53
+ return { path: canonical, dev: String(stat.dev), ino: String(stat.ino) };
54
+ }
55
+ function privateDirectory(directory) {
56
+ const stat = fs.lstatSync(directory, { bigint: true });
57
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
58
+ if (process.platform !== "win32" && (stat.uid !== BigInt(process.getuid()) || (stat.mode & 0o777n) !== 0o700n)) throw Error("MANAGED_FIXTURE_REQUIRES_PRIVATE_DIRECTORY");
59
+ }
60
+ function sameIdentity(expected, observed) {
61
+ return expected && expected.path === observed.path && expected.dev === observed.dev && expected.ino === observed.ino;
62
+ }
63
+ function verifyIdentity(expected) {
64
+ if (!expected || typeof expected.path !== "string" || !sameIdentity(expected, identity(expected.path))) throw Error("MANAGED_FIXTURE_DIRECTORY_IDENTITY_CHANGED");
65
+ }
66
+ function ensureChildDirectories(root, parts) {
67
+ let directory = root;
68
+ for (const part of parts) {
69
+ directory = path.join(directory, part);
70
+ try { fs.lstatSync(directory); }
71
+ catch (error) { if (error.code !== "ENOENT") throw error; fs.mkdirSync(directory, { mode: 0o700 }); }
72
+ absoluteDirectory(directory);
73
+ privateDirectory(directory);
74
+ }
75
+ return fs.realpathSync(directory);
76
+ }
77
+ function metadataIdentity(file, stat) {
78
+ if (stat.isSymbolicLink() || !stat.isFile() || typeof stat.dev !== "bigint" || typeof stat.ino !== "bigint" || typeof stat.nlink !== "bigint" || typeof stat.size !== "bigint" || stat.dev < 0n || stat.ino <= 0n || stat.nlink !== 1n || stat.size <= 0n || stat.size > BigInt(maximumMetadataBytes)) throw Error("INVALID_MANAGED_FIXTURE_METADATA");
79
+ return { path: file, dev: String(stat.dev), ino: String(stat.ino), bytes: Number(stat.size) };
80
+ }
81
+ function readMetadata(file, expected) {
82
+ absoluteDirectory(path.dirname(file));
83
+ const before = metadataIdentity(file, fs.lstatSync(file, { bigint: true }));
84
+ if (expected && (!sameIdentity(expected, before) || expected.bytes !== before.bytes)) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
85
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
86
+ let bytes;
87
+ try {
88
+ const opened = metadataIdentity(file, fs.fstatSync(descriptor, { bigint: true }));
89
+ if (!sameIdentity(before, opened) || before.bytes !== opened.bytes) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
90
+ bytes = fs.readFileSync(descriptor);
91
+ if (bytes.length !== opened.bytes) throw Error("MANAGED_FIXTURE_METADATA_CHANGED");
92
+ } finally { fs.closeSync(descriptor); }
93
+ const after = metadataIdentity(file, fs.lstatSync(file, { bigint: true }));
94
+ if (!sameIdentity(before, after) || before.bytes !== after.bytes) throw Error("MANAGED_FIXTURE_METADATA_IDENTITY_CHANGED");
95
+ absoluteDirectory(path.dirname(file));
96
+ const sha256 = hash(bytes);
97
+ if (expected && expected.sha256 !== sha256) throw Error("MANAGED_FIXTURE_METADATA_CHANGED");
98
+ return { identity: { ...after, sha256 }, value: JSON.parse(bytes.toString("utf8")) };
99
+ }
100
+ function markerBody(binding) {
101
+ return { version: binding.version, namespace: binding.namespace, ownerPid: binding.ownerPid, marker: binding.marker, taskRoot: binding.taskRoot, nativeRoot: binding.nativeRoot, attempt: binding.attempt, evidence: binding.evidence, temporary: binding.temporary };
102
+ }
103
+ function verifyBinding(binding, namespace, task, native) {
104
+ namespaceParts(namespace);
105
+ if (!binding || binding.version !== 1 || binding.namespace !== namespace || !Number.isSafeInteger(binding.ownerPid) || binding.ownerPid <= 0 || typeof binding.marker !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(binding.marker)) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
106
+ if ([binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary].some(value => !value || typeof value.path !== "string" || !path.isAbsolute(value.path) || typeof value.dev !== "string" || !/^\d+$/.test(value.dev) || typeof value.ino !== "string" || !/^[1-9]\d*$/.test(value.ino))) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
107
+ if (!sameIdentity(binding.taskRoot, task) || !sameIdentity(binding.nativeRoot, native)) throw Error("MANAGED_FIXTURE_AUTHORITY_CHANGED");
108
+ const expectedParent = path.join(native.path, "llr14-native-fixtures", ...namespaceParts(namespace));
109
+ if (!binding.attempt || path.dirname(binding.attempt.path) !== expectedParent || path.basename(binding.attempt.path) !== 'attempt-slot') throw Error("MANAGED_FIXTURE_ATTEMPT_OUTSIDE_AUTHORITY");
110
+ if (!binding.evidence || (!beneath(task.path, binding.evidence.path) && binding.evidence.path !== binding.attempt.path)) throw Error("MANAGED_FIXTURE_EVIDENCE_OUTSIDE_AUTHORITY");
111
+ if (!binding.temporary || binding.temporary.path !== path.join(binding.attempt.path, "temporary")) throw Error("MANAGED_FIXTURE_TEMPORARY_OUTSIDE_ATTEMPT");
112
+ for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) verifyIdentity(value);
113
+ privateDirectory(binding.attempt.path);
114
+ privateDirectory(binding.temporary.path);
115
+ const marker = path.join(binding.attempt.path, markerName);
116
+ if (!binding.ownership || binding.ownership.path !== marker) throw Error("INVALID_MANAGED_FIXTURE_BINDING");
117
+ const stored = readMetadata(marker, binding.ownership);
118
+ if (JSON.stringify(stored.value) !== JSON.stringify(markerBody(binding))) throw Error("MANAGED_FIXTURE_MARKER_BINDING_CHANGED");
119
+ for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) verifyIdentity(value);
120
+ }
121
+
122
+ // The injected roots come from the resource owner. Routing grants no capacity,
123
+ // service permission or closure proof, and never falls back when a root is bad.
124
+ export function resolveManagedFixtureEvidenceBase(legacyBase, namespace, environment = process.env) {
125
+ if (environment.LLR14_EVIDENCE_ROOT === undefined) return legacyBase;
126
+ const task = identity(environment.LLR14_EVIDENCE_ROOT);
127
+ const parts = namespaceParts(namespace);
128
+ let current = task.path;
129
+ for (const part of parts) {
130
+ current = path.join(current, part);
131
+ let stat;
132
+ try { stat = fs.lstatSync(current, { bigint: true }); }
133
+ catch (error) { if (error.code !== "ENOENT") throw error; break; }
134
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("MANAGED_FIXTURE_REQUIRES_REAL_DIRECTORIES");
135
+ absoluteDirectory(current);
136
+ }
137
+ verifyIdentity(task);
138
+ return path.join(task.path, ...parts);
139
+ }
140
+
141
+ export function assertManagedFixtureAuthority(environment = process.env) {
142
+ if (environment.LLR14_EVIDENCE_ROOT === undefined) throw Error('MANAGED_FIXTURE_AUTHORITY_REQUIRED');
143
+ const task = identity(environment.LLR14_EVIDENCE_ROOT);
144
+ const native = identity(environment.TEMP), alternate = identity(environment.TMP);
145
+ if (!sameIdentity(native, alternate) || (environment.TMPDIR !== undefined && !sameIdentity(native, identity(environment.TMPDIR))) || (environment.LLR14_NATIVE_FIXTURE_BASE !== undefined && !sameIdentity(native, identity(environment.LLR14_NATIVE_FIXTURE_BASE)))) throw Error("MANAGED_FIXTURE_TEMP_AUTHORITY_MISMATCH");
146
+ if (native.path === task.path || beneath(native.path, task.path) || beneath(task.path, native.path)) throw Error("MANAGED_FIXTURE_AUTHORITY_ROOTS_OVERLAP");
147
+ return { task, native };
148
+ }
149
+
150
+ export function createManagedRetainedFixture({ root, evidence, namespace, environment = process.env }) {
151
+ if (typeof root !== "string" || !path.isAbsolute(root)) throw Error("MANAGED_FIXTURE_ROOT_REQUIRED");
152
+ if (environment.LLR14_EVIDENCE_ROOT === undefined) return undefined;
153
+ const parts = namespaceParts(namespace), { task, native } = assertManagedFixtureAuthority(environment);
154
+ const requestedEvidence = identity(evidence);
155
+ if (!beneath(task.path, requestedEvidence.path)) throw Error("MANAGED_FIXTURE_EVIDENCE_OUTSIDE_AUTHORITY");
156
+ const parent = ensureChildDirectories(native.path, ["llr14-native-fixtures", ...parts]);
157
+ verifyIdentity(task); verifyIdentity(native); verifyIdentity(requestedEvidence);
158
+ const lifecycle = createTemporaryScope({ root, scope: parent, label: 'attempt', maximumBytes: 1024 ** 3, requiresClosureProof: true });
159
+ const directory = lifecycle.directory;
160
+ try {
161
+ privateDirectory(directory);
162
+ const temporary = path.join(directory, "temporary");
163
+ fs.mkdirSync(temporary, { mode: 0o700 });
164
+ privateDirectory(temporary);
165
+ const body = { version: 1, namespace, ownerPid: process.pid, marker: crypto.randomUUID(), taskRoot: task, nativeRoot: native, attempt: identity(directory), evidence: requestedEvidence, temporary: identity(temporary) };
166
+ const marker = path.join(directory, markerName);
167
+ fs.writeFileSync(marker, JSON.stringify(body) + "\n", { mode: 0o600, flag: "wx" });
168
+ const ownership = readMetadata(marker).identity;
169
+ const binding = Object.freeze({ ...body, ownership: Object.freeze(ownership) });
170
+ for (const value of [binding.taskRoot, binding.nativeRoot, binding.attempt, binding.evidence, binding.temporary]) Object.freeze(value);
171
+ const verify = () => verifyBinding(binding, namespace, identity(task.path), identity(native.path));
172
+ verify();
173
+ let finalized;
174
+ return Object.freeze({
175
+ directory, temporary, evidence: binding.evidence.path, managed: true, binding, verify,
176
+ checkBudget: lifecycle.checkBudget,
177
+ beginLaunch: lifecycle.beginLaunch,
178
+ trackPid: lifecycle.trackPid,
179
+ finalize({ status, closed }) {
180
+ if (finalized) return finalized;
181
+ verify();
182
+ const receipt = path.join(binding.evidence.path, receiptName);
183
+ const value = { schemaVersion: 2, at: new Date().toISOString(), namespace, ownerPid: binding.ownerPid, directory, temporary, evidence: binding.evidence.path, ownershipSha256: binding.ownership.sha256, ownershipVerified: true, status, retained: false, copied: false, removed: false };
184
+ fs.writeFileSync(receipt, JSON.stringify(value) + "\n", { mode: 0o600, flag: 'wx' });
185
+ const receiptIdentity = readMetadata(receipt).identity;
186
+ try { lifecycle.finish({ status, closed }); value.removed = true; }
187
+ finally { readMetadata(receipt, receiptIdentity); fs.writeFileSync(receipt, JSON.stringify(value) + "\n", { mode: 0o600 }); }
188
+ finalized = Object.freeze(value);
189
+ return finalized;
190
+ },
191
+ });
192
+ } catch (error) {
193
+ try { lifecycle.finish({ status: 'initialization-failed', closed: true }); }
194
+ catch (cleanupError) { error.cleanupError = cleanupError; }
195
+ throw error;
196
+ }
197
+ }
198
+
199
+ export function validateManagedFixtureEvidence({ evidence, legacyBase, namespace, binding, environment = process.env }) {
200
+ if (binding === undefined) {
201
+ if (environment.LLR14_EVIDENCE_ROOT !== undefined) throw Error("MANAGED_FIXTURE_BINDING_REQUIRED");
202
+ if (typeof evidence !== "string" || !beneath(fs.realpathSync(legacyBase), fs.realpathSync(evidence))) throw Error("Unapproved service fixture");
203
+ return;
204
+ }
205
+ if (environment.LLR14_EVIDENCE_ROOT === undefined || environment.LLR14_NATIVE_FIXTURE_BASE === undefined) throw Error("MANAGED_FIXTURE_STABLE_AUTHORITY_REQUIRED");
206
+ const task = identity(environment.LLR14_EVIDENCE_ROOT), native = identity(environment.LLR14_NATIVE_FIXTURE_BASE);
207
+ verifyBinding(binding, namespace, task, native);
208
+ if (typeof evidence !== "string" || evidence !== binding.evidence.path || !sameIdentity(binding.evidence, identity(evidence))) throw Error("MANAGED_FIXTURE_EVIDENCE_BINDING_CHANGED");
209
+ }