@aopslabs/aops-server 0.2.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 (150) hide show
  1. package/LICENSE +19 -0
  2. package/NOTICE +7 -0
  3. package/README.md +28 -0
  4. package/THIRD_PARTY_NOTICES +13409 -0
  5. package/THIRD_PARTY_NOTICES.inventory.json +2768 -0
  6. package/build/client/_app/immutable/chunks/2_TffmqH.js +1 -0
  7. package/build/client/_app/immutable/chunks/3DOfIKW0.js +1 -0
  8. package/build/client/_app/immutable/chunks/B2EkC-sy.js +1 -0
  9. package/build/client/_app/immutable/chunks/BlANKL2r.js +1 -0
  10. package/build/client/_app/immutable/chunks/CMkIcmi1.js +2 -0
  11. package/build/client/_app/immutable/chunks/rqnVXeyB.js +1 -0
  12. package/build/client/_app/immutable/chunks/wbPk3Yxo.js +81 -0
  13. package/build/client/_app/immutable/entry/app.a0iGCm6X.js +2 -0
  14. package/build/client/_app/immutable/entry/start.Df7u6fQ1.js +1 -0
  15. package/build/client/_app/immutable/nodes/0.BYBfjxZ5.js +1 -0
  16. package/build/client/_app/immutable/nodes/1.BtbjYUHR.js +1 -0
  17. package/build/client/_app/version.json +1 -0
  18. package/build/env.js +69 -0
  19. package/build/handler.js +15 -0
  20. package/build/index.js +138 -0
  21. package/build/server/chunks/0-RfB6m2nq.js +6 -0
  22. package/build/server/chunks/1-UJuUicIe.js +8 -0
  23. package/build/server/chunks/_server.ts-6bdzoHJH.js +83 -0
  24. package/build/server/chunks/_server.ts-AwMeEYiZ.js +9 -0
  25. package/build/server/chunks/_server.ts-B9gjXi95.js +260 -0
  26. package/build/server/chunks/_server.ts-BX4X0tW0.js +16 -0
  27. package/build/server/chunks/_server.ts-BkxSxdd0.js +172 -0
  28. package/build/server/chunks/_server.ts-Bly8fCZa.js +90 -0
  29. package/build/server/chunks/_server.ts-Bz-Erv-1.js +43 -0
  30. package/build/server/chunks/_server.ts-CRKd0KAC.js +43 -0
  31. package/build/server/chunks/_server.ts-CjzSQgpk.js +95 -0
  32. package/build/server/chunks/_server.ts-Cv-yaXZI.js +6 -0
  33. package/build/server/chunks/_server.ts-DQWRrk5C.js +14 -0
  34. package/build/server/chunks/_server.ts-DQzYSH_C.js +125 -0
  35. package/build/server/chunks/_server.ts-DaIr3NkR.js +10 -0
  36. package/build/server/chunks/_server.ts-DbdAfdYo.js +8 -0
  37. package/build/server/chunks/_server.ts-De9ZrSV0.js +84 -0
  38. package/build/server/chunks/_server.ts-DsTeOL2P.js +17 -0
  39. package/build/server/chunks/_server.ts-N61POKjl.js +84 -0
  40. package/build/server/chunks/_server.ts-Ua5Ieisy.js +37 -0
  41. package/build/server/chunks/_server.ts-XmKDT59M.js +37 -0
  42. package/build/server/chunks/_server.ts-o9pJceJP.js +54 -0
  43. package/build/server/chunks/_server.ts-u2UWBqNN.js +276 -0
  44. package/build/server/chunks/admission-snapshot-C2wGfTWE.js +1034 -0
  45. package/build/server/chunks/agent-gateway-runtime-C7Kvvy0H.js +2614 -0
  46. package/build/server/chunks/aops-runtime-config-CHpDUCdE.js +185 -0
  47. package/build/server/chunks/auth-provider-C07OUlnz.js +18 -0
  48. package/build/server/chunks/canonical-text-order-DbXJJnFD.js +5 -0
  49. package/build/server/chunks/commercial-admission-loader-V_vXHdVa.js +2077 -0
  50. package/build/server/chunks/discovery-BvDEgiqC.js +897 -0
  51. package/build/server/chunks/error.svelte-B9R6O_Hn.js +44 -0
  52. package/build/server/chunks/handler-DurXhqww.js +1472 -0
  53. package/build/server/chunks/hooks.server-DYGrWbgh.js +62 -0
  54. package/build/server/chunks/index.js-BQnOaW3H.js +11573 -0
  55. package/build/server/chunks/manifest.js-CCJDdahY.js +180 -0
  56. package/build/server/chunks/plugin-error-normalize-DNeRsopQ.js +309 -0
  57. package/build/server/chunks/project-alias-BdnRxWft.js +28 -0
  58. package/build/server/chunks/registry-DO8ob5o1.js +660 -0
  59. package/build/server/chunks/request-base-url-zKJpVUv5.js +35 -0
  60. package/build/server/chunks/request-context-9wzBoKrz.js +421 -0
  61. package/build/server/chunks/xf-result-BRDjvftr.js +16 -0
  62. package/build/shims.js +32 -0
  63. package/cockpit/.vite/manifest.json +198 -0
  64. package/cockpit/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  65. package/cockpit/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  66. package/cockpit/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  67. package/cockpit/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  68. package/cockpit/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  69. package/cockpit/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  70. package/cockpit/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  71. package/cockpit/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  72. package/cockpit/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  73. package/cockpit/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  74. package/cockpit/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  75. package/cockpit/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  76. package/cockpit/assets/index-CkhZWZ2f.js +18 -0
  77. package/cockpit/assets/index-TSfC5rf2.css +1 -0
  78. package/cockpit/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  79. package/cockpit/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  80. package/cockpit/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  81. package/cockpit/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  82. package/cockpit/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  83. package/cockpit/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  84. package/cockpit/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  85. package/cockpit/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  86. package/cockpit/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  87. package/cockpit/assets/outfit-latin-400-normal-BGsTXAXT.woff2 +0 -0
  88. package/cockpit/assets/outfit-latin-400-normal-DMwTpYkH.woff +0 -0
  89. package/cockpit/assets/outfit-latin-600-normal-B7SfZ07L.woff2 +0 -0
  90. package/cockpit/assets/outfit-latin-600-normal-BEfTtDA7.woff +0 -0
  91. package/cockpit/assets/outfit-latin-ext-400-normal-5tcqmc2S.woff2 +0 -0
  92. package/cockpit/assets/outfit-latin-ext-400-normal-DHm7mdGe.woff +0 -0
  93. package/cockpit/assets/outfit-latin-ext-600-normal-B85nYjL1.woff2 +0 -0
  94. package/cockpit/assets/outfit-latin-ext-600-normal-CWJcPgd7.woff +0 -0
  95. package/cockpit/assets/unbounded-cyrillic-600-normal-B-s5c2Kn.woff +0 -0
  96. package/cockpit/assets/unbounded-cyrillic-600-normal-DW6uzIMB.woff2 +0 -0
  97. package/cockpit/assets/unbounded-latin-600-normal-BPdB_PEv.woff +0 -0
  98. package/cockpit/assets/unbounded-latin-600-normal-oRSANpZr.woff2 +0 -0
  99. package/cockpit/assets/unbounded-latin-ext-600-normal-0iZLtTDV.woff2 +0 -0
  100. package/cockpit/assets/unbounded-latin-ext-600-normal-ClMPf-bu.woff +0 -0
  101. package/cockpit/assets/unbounded-vietnamese-600-normal-BzfrgZ_C.woff +0 -0
  102. package/cockpit/assets/unbounded-vietnamese-600-normal-Cx2bTSHN.woff2 +0 -0
  103. package/cockpit/community.module-inventory.json +2439 -0
  104. package/cockpit/index.html +14 -0
  105. package/community-postgres.json +13 -0
  106. package/migrations/agentspace/0000_thin_carlie_cooper.sql +764 -0
  107. package/migrations/agentspace/meta/_journal.json +13 -0
  108. package/migrations/chatv3/0000_dry_ego.sql +218 -0
  109. package/migrations/chatv3/0001_nosy_obadiah_stane.sql +35 -0
  110. package/migrations/chatv3/0002_narrow_darkhawk.sql +4 -0
  111. package/migrations/chatv3/0003_damp_zarek.sql +2 -0
  112. package/migrations/chatv3/0004_nervous_martin_li.sql +60 -0
  113. package/migrations/chatv3/0005_chatv3_server_encrypted_mode.sql +1 -0
  114. package/migrations/chatv3/0006_chatv3_database_server_keyring.sql +21 -0
  115. package/migrations/chatv3/meta/_journal.json +55 -0
  116. package/migrations/docman/0000_curvy_valeria_richards.sql +257 -0
  117. package/migrations/docman/0001_massive_risque.sql +2 -0
  118. package/migrations/docman/0002_simple_logan.sql +50 -0
  119. package/migrations/docman/0003_quick_index.sql +45 -0
  120. package/migrations/docman/0004_known_summary.sql +9 -0
  121. package/migrations/docman/0005_vector_signal.sql +9 -0
  122. package/migrations/docman/0006_document_version_current_invariant.sql +15 -0
  123. package/migrations/docman/meta/_journal.json +55 -0
  124. package/migrations/projectman/0000_smooth_klaw.sql +257 -0
  125. package/migrations/projectman/0001_worthless_zodiak.sql +9 -0
  126. package/migrations/projectman/0002_board_rename.sql +108 -0
  127. package/migrations/projectman/0003_review_request.sql +62 -0
  128. package/migrations/projectman/0004_review_request_idempotency.sql +3 -0
  129. package/migrations/projectman/0005_allow_multi_sprint_per_task.sql +1 -0
  130. package/migrations/projectman/meta/_journal.json +48 -0
  131. package/migrations/sys/0000_loose_praxagora.sql +31 -0
  132. package/migrations/sys/0001_awesome_ronan.sql +2 -0
  133. package/migrations/sys/0002_steady_maximus.sql +2 -0
  134. package/migrations/sys/0003_escalating_rate_limiter.sql +2 -0
  135. package/migrations/sys/0004_rate_limiter_timestamptz.sql +22 -0
  136. package/migrations/sys/0005_sys_counters.sql +21 -0
  137. package/migrations/sys/meta/_journal.json +48 -0
  138. package/npm-shrinkwrap.json +5069 -0
  139. package/package.json +88 -0
  140. package/runtime/agentspace-host-adapter.mjs +64 -0
  141. package/runtime/agentspace-tooling.mjs +389 -0
  142. package/runtime/commercial-integrity-worker.mjs +1643 -0
  143. package/runtime/docman-host-adapter.mjs +177 -0
  144. package/runtime/docman-policy.mjs +450 -0
  145. package/runtime/docman-tooling.mjs +20 -0
  146. package/runtime/projectman-host-adapter.mjs +597 -0
  147. package/runtime/scope-context.mjs +99 -0
  148. package/runtime-closure.package.json +376 -0
  149. package/scripts/community-host.mjs +919 -0
  150. package/scripts/community-migration-policy-package-v1.json +11854 -0
@@ -0,0 +1,1643 @@
1
+ import { workerData, parentPort } from "node:worker_threads";
2
+ import { createPublicKey, verify, createHash, createHmac, timingSafeEqual, randomUUID, randomBytes } from "node:crypto";
3
+ import { existsSync, rmSync, mkdirSync, lstatSync, realpathSync, readFileSync, statSync, writeFileSync, renameSync, chmodSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { gunzipSync } from "node:zlib";
6
+ function compareCanonicalText(left, right) {
7
+ return left < right ? -1 : left > right ? 1 : 0;
8
+ }
9
+ const RELEASE_MANIFEST_OBJECT_TYPE = "aops-release-closure-manifest";
10
+ const RELEASE_MANIFEST_CANONICALIZATION = "RFC8785-JCS-v1";
11
+ const RELEASE_MANIFEST_PURPOSE = "urn:aops:artifact-installer:v1";
12
+ const RELEASE_MANIFEST_CRITICAL_FIELDS = Object.freeze([
13
+ "objectType",
14
+ "payloadCanonicalization",
15
+ "schemaVersion"
16
+ ]);
17
+ const SHA256$1 = /^sha256:[a-f0-9]{64}$/;
18
+ const SHA512_INTEGRITY = /^sha512-[A-Za-z0-9+/]{86}==$/;
19
+ const RELEASE_KID = /^release\/[A-Za-z0-9._~-]{1,160}$/;
20
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
21
+ const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
22
+ const SOURCE_COMMIT = /^[a-f0-9]{40,64}$/;
23
+ const NAMESPACE = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)+$/;
24
+ const COMMERCIAL_LAUNCH_ROLES = Object.freeze([
25
+ "runtime-node",
26
+ "cli",
27
+ "server",
28
+ "cockpit"
29
+ ]);
30
+ const verifiedReleaseManifests = /* @__PURE__ */ new WeakSet();
31
+ class CommercialArtifactError extends Error {
32
+ stage;
33
+ decision;
34
+ reason;
35
+ constructor(stage, reason, decision = "deny") {
36
+ super(`${stage}:${reason}`);
37
+ this.name = "CommercialArtifactError";
38
+ this.stage = stage;
39
+ this.reason = reason;
40
+ this.decision = decision;
41
+ }
42
+ }
43
+ function fail$1(stage, reason) {
44
+ throw new CommercialArtifactError(stage, reason);
45
+ }
46
+ function isRecord$1(value) {
47
+ return value !== null && typeof value === "object" && !Array.isArray(value);
48
+ }
49
+ function canonicalCommercialJson(value) {
50
+ if (value === null || typeof value === "boolean" || typeof value === "string")
51
+ return JSON.stringify(value);
52
+ if (typeof value === "number") {
53
+ if (!Number.isFinite(value))
54
+ fail$1("manifest-schema", "non_finite_number");
55
+ return JSON.stringify(value);
56
+ }
57
+ if (Array.isArray(value))
58
+ return `[${value.map((entry) => canonicalCommercialJson(entry)).join(",")}]`;
59
+ if (!isRecord$1(value))
60
+ fail$1("manifest-schema", "non_json_value");
61
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalCommercialJson(value[key])}`).join(",")}}`;
62
+ }
63
+ function sha256Commercial(value) {
64
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
65
+ }
66
+ function runtimeVersionTuple(value) {
67
+ const match = /^([0-9]+)\.([0-9]+)\.([0-9]+)$/.exec(value);
68
+ if (!match)
69
+ fail$1("artifact-preflight", "bundled_runtime_version_invalid");
70
+ const tuple = match.slice(1).map(Number);
71
+ if (tuple.some((part) => !Number.isSafeInteger(part) || part < 0)) {
72
+ fail$1("artifact-preflight", "bundled_runtime_version_invalid");
73
+ }
74
+ return tuple;
75
+ }
76
+ function compareRuntimeVersions(left, right) {
77
+ for (let index = 0; index < left.length; index += 1) {
78
+ if (left[index] !== right[index])
79
+ return left[index] < right[index] ? -1 : 1;
80
+ }
81
+ return 0;
82
+ }
83
+ function assertCommercialRuntimeCompatible(version, supportedRange) {
84
+ const current = runtimeVersionTuple(version);
85
+ const clauses = supportedRange.trim().split(/\s+/);
86
+ const compatible = clauses.length > 0 && clauses.every((clause) => {
87
+ const match = /^(>=|>|<=|<|=)?([0-9]+\.[0-9]+\.[0-9]+)$/.exec(clause);
88
+ if (!match)
89
+ return false;
90
+ const comparison = compareRuntimeVersions(current, runtimeVersionTuple(match[2]));
91
+ if (match[1] === ">=")
92
+ return comparison >= 0;
93
+ if (match[1] === ">")
94
+ return comparison > 0;
95
+ if (match[1] === "<=")
96
+ return comparison <= 0;
97
+ if (match[1] === "<")
98
+ return comparison < 0;
99
+ return comparison === 0;
100
+ });
101
+ if (!compatible)
102
+ fail$1("artifact-preflight", "bundled_runtime_incompatible");
103
+ }
104
+ function exactObject(value, keys, reason) {
105
+ if (!isRecord$1(value))
106
+ fail$1("manifest-schema", reason);
107
+ const actual = Object.keys(value).sort();
108
+ const expected = [...keys].sort();
109
+ if (canonicalCommercialJson(actual) !== canonicalCommercialJson(expected))
110
+ fail$1("manifest-schema", reason);
111
+ }
112
+ function requiredString(record, key, reason) {
113
+ const value = record[key];
114
+ if (typeof value !== "string" || !value || value !== value.trim() || value.length > 1024) {
115
+ fail$1("manifest-schema", reason);
116
+ }
117
+ if (/[\u0000-\u001f\u007f]/.test(value))
118
+ fail$1("manifest-schema", reason);
119
+ return value;
120
+ }
121
+ function digest(record, key, reason) {
122
+ const value = requiredString(record, key, reason);
123
+ if (!SHA256$1.test(value))
124
+ fail$1("manifest-schema", reason);
125
+ return value;
126
+ }
127
+ function timestamp(record, key, reason) {
128
+ const value = requiredString(record, key, reason);
129
+ const millis = Date.parse(value);
130
+ if (!Number.isFinite(millis) || new Date(millis).toISOString() !== value)
131
+ fail$1("manifest-schema", reason);
132
+ return value;
133
+ }
134
+ function sortedUniqueStrings(record, key, reason, options = {}) {
135
+ const value = record[key];
136
+ if (!Array.isArray(value) || !options.allowEmpty && value.length === 0)
137
+ fail$1("manifest-schema", reason);
138
+ const strings = value.map((entry) => {
139
+ if (typeof entry !== "string" || !entry || entry !== entry.trim() || entry.length > 1024) {
140
+ fail$1("manifest-schema", reason);
141
+ }
142
+ if (options.validate && !options.validate(entry))
143
+ fail$1("manifest-schema", reason);
144
+ return entry;
145
+ });
146
+ const expected = [...new Set(strings)].sort();
147
+ if (canonicalCommercialJson(strings) !== canonicalCommercialJson(expected))
148
+ fail$1("manifest-schema", reason);
149
+ return Object.freeze(strings);
150
+ }
151
+ function safeEntrypoint(value) {
152
+ if (pathLikeAbsolute(value) || value.includes("\\") || value.includes("\0"))
153
+ return false;
154
+ const separator = value.indexOf(":");
155
+ if (separator < 1)
156
+ return false;
157
+ const packageName = value.slice(0, separator);
158
+ const relative = value.slice(separator + 1);
159
+ return PACKAGE_NAME.test(packageName) && relative.length > 0 && relative.split("/").every((segment) => segment && segment !== "." && segment !== "..");
160
+ }
161
+ function safePackageRelativeEntrypoint(value) {
162
+ return value.length > 0 && value.length <= 4096 && !pathLikeAbsolute(value) && !value.includes("\\") && !value.includes("\0") && value.split("/").every((segment) => segment && segment !== "." && segment !== "..");
163
+ }
164
+ function validRuntimeRange(value) {
165
+ const clauses = value.trim().split(/\s+/);
166
+ return clauses.length > 0 && clauses.every((clause) => /^(?:>=|>|<=|<|=)?[0-9]+\.[0-9]+\.[0-9]+$/.test(clause));
167
+ }
168
+ function pathLikeAbsolute(value) {
169
+ return value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
170
+ }
171
+ function assertNoLocalMaterial(value, reason) {
172
+ if (pathLikeAbsolute(value) || /(?:localhost|127\.0\.0\.1|password|token|secret)=/i.test(value)) {
173
+ fail$1("manifest-schema", reason);
174
+ }
175
+ }
176
+ function parseClosure(value) {
177
+ if (!Array.isArray(value) || value.length === 0)
178
+ fail$1("manifest-schema", "closure_invalid");
179
+ const rows = value.map((candidate) => {
180
+ exactObject(candidate, [
181
+ "packageName",
182
+ "version",
183
+ "artifactSha256",
184
+ "packageIntegrity",
185
+ "filesDigest",
186
+ "launchRole",
187
+ "launchEntrypoint",
188
+ "runtimeRange"
189
+ ], "closure_entry_invalid");
190
+ const packageName = requiredString(candidate, "packageName", "closure_package_invalid");
191
+ const version = requiredString(candidate, "version", "closure_version_invalid");
192
+ const packageIntegrity = requiredString(candidate, "packageIntegrity", "closure_integrity_invalid");
193
+ if (!PACKAGE_NAME.test(packageName))
194
+ fail$1("manifest-schema", "closure_package_invalid");
195
+ if (!VERSION.test(version))
196
+ fail$1("manifest-schema", "closure_version_invalid");
197
+ if (!SHA512_INTEGRITY.test(packageIntegrity))
198
+ fail$1("manifest-schema", "closure_integrity_invalid");
199
+ const launchRole = candidate.launchRole;
200
+ if (launchRole !== null && !COMMERCIAL_LAUNCH_ROLES.includes(launchRole)) {
201
+ fail$1("manifest-schema", "closure_launch_role_invalid");
202
+ }
203
+ const launchEntrypoint = candidate.launchEntrypoint;
204
+ const runtimeRange = candidate.runtimeRange;
205
+ if (launchRole === null) {
206
+ if (launchEntrypoint !== null || runtimeRange !== null) {
207
+ fail$1("manifest-schema", "closure_launch_binding_invalid");
208
+ }
209
+ } else {
210
+ if (typeof launchEntrypoint !== "string" || !safePackageRelativeEntrypoint(launchEntrypoint)) {
211
+ fail$1("manifest-schema", "closure_launch_entrypoint_invalid");
212
+ }
213
+ if (launchRole === "runtime-node") {
214
+ if (runtimeRange !== null)
215
+ fail$1("manifest-schema", "closure_runtime_range_invalid");
216
+ } else if (typeof runtimeRange !== "string" || !validRuntimeRange(runtimeRange)) {
217
+ fail$1("manifest-schema", "closure_runtime_range_invalid");
218
+ }
219
+ }
220
+ return Object.freeze({
221
+ packageName,
222
+ version,
223
+ artifactSha256: digest(candidate, "artifactSha256", "closure_artifact_digest_invalid"),
224
+ packageIntegrity,
225
+ filesDigest: digest(candidate, "filesDigest", "closure_files_digest_invalid"),
226
+ launchRole,
227
+ launchEntrypoint,
228
+ runtimeRange
229
+ });
230
+ });
231
+ const identities = rows.map((row) => `${row.packageName}@${row.version}`);
232
+ if (canonicalCommercialJson(identities) !== canonicalCommercialJson([...new Set(identities)].sort())) {
233
+ fail$1("manifest-schema", "closure_order_invalid");
234
+ }
235
+ const roles = rows.filter((row) => row.launchRole !== null).map((row) => row.launchRole);
236
+ if (roles.filter((role) => role === "runtime-node").length !== 1) {
237
+ fail$1("manifest-schema", "closure_runtime_role_invalid");
238
+ }
239
+ if (new Set(roles).size !== roles.length)
240
+ fail$1("manifest-schema", "closure_launch_role_duplicate");
241
+ return Object.freeze(rows);
242
+ }
243
+ function parseRelease(value) {
244
+ exactObject(value, ["packageName", "version", "releaseId", "sourceRepositoryId", "sourceCommit", "sourceTag"], "release_invalid");
245
+ const packageName = requiredString(value, "packageName", "release_package_invalid");
246
+ const version = requiredString(value, "version", "release_version_invalid");
247
+ const sourceRepositoryId = requiredString(value, "sourceRepositoryId", "release_repository_invalid");
248
+ const sourceCommit = requiredString(value, "sourceCommit", "release_commit_invalid");
249
+ const sourceTag = requiredString(value, "sourceTag", "release_tag_invalid");
250
+ if (!PACKAGE_NAME.test(packageName))
251
+ fail$1("manifest-schema", "release_package_invalid");
252
+ if (!VERSION.test(version))
253
+ fail$1("manifest-schema", "release_version_invalid");
254
+ if (!SOURCE_COMMIT.test(sourceCommit))
255
+ fail$1("manifest-schema", "release_commit_invalid");
256
+ assertNoLocalMaterial(sourceRepositoryId, "release_repository_invalid");
257
+ assertNoLocalMaterial(sourceTag, "release_tag_invalid");
258
+ return Object.freeze({
259
+ packageName,
260
+ version,
261
+ releaseId: requiredString(value, "releaseId", "release_id_invalid"),
262
+ sourceRepositoryId,
263
+ sourceCommit,
264
+ sourceTag
265
+ });
266
+ }
267
+ function parseMigrationCapsules(value) {
268
+ if (!Array.isArray(value))
269
+ fail$1("manifest-schema", "migration_capsules_invalid");
270
+ const rows = value.map((candidate) => {
271
+ exactObject(candidate, ["capsuleId", "version", "digest", "semanticContractDigest", "readbackPolicy", "rollbackPolicy"], "migration_capsule_invalid");
272
+ const version = requiredString(candidate, "version", "migration_capsule_version_invalid");
273
+ if (!VERSION.test(version))
274
+ fail$1("manifest-schema", "migration_capsule_version_invalid");
275
+ return Object.freeze({
276
+ capsuleId: requiredString(candidate, "capsuleId", "migration_capsule_id_invalid"),
277
+ version,
278
+ digest: digest(candidate, "digest", "migration_capsule_digest_invalid"),
279
+ semanticContractDigest: digest(candidate, "semanticContractDigest", "migration_semantic_digest_invalid"),
280
+ readbackPolicy: requiredString(candidate, "readbackPolicy", "migration_readback_policy_invalid"),
281
+ rollbackPolicy: requiredString(candidate, "rollbackPolicy", "migration_rollback_policy_invalid")
282
+ });
283
+ });
284
+ const identities = rows.map((row) => `${row.capsuleId}@${row.version}`);
285
+ if (canonicalCommercialJson(identities) !== canonicalCommercialJson([...new Set(identities)].sort())) {
286
+ fail$1("manifest-schema", "migration_capsule_order_invalid");
287
+ }
288
+ return Object.freeze(rows);
289
+ }
290
+ function parseReleaseClosureManifest(value, options = {}) {
291
+ exactObject(value, [
292
+ "manifestId",
293
+ "publisherId",
294
+ "issuedAt",
295
+ "notBefore",
296
+ "notAfter",
297
+ "release",
298
+ "closure",
299
+ "closureDigest",
300
+ "packlistDigest",
301
+ "sbom",
302
+ "entrypoints",
303
+ "dcm",
304
+ "hostAbi",
305
+ "migrationCapsules",
306
+ "degradedOperationIds",
307
+ "extensions"
308
+ ], "release_manifest_invalid");
309
+ const issuedAt = timestamp(value, "issuedAt", "issued_at_invalid");
310
+ const notBefore = timestamp(value, "notBefore", "not_before_invalid");
311
+ const notAfter = timestamp(value, "notAfter", "not_after_invalid");
312
+ if (!(Date.parse(notBefore) <= Date.parse(issuedAt) && Date.parse(issuedAt) < Date.parse(notAfter))) {
313
+ fail$1("manifest-schema", "manifest_time_order_invalid");
314
+ }
315
+ const release = parseRelease(value.release);
316
+ const closure = parseClosure(value.closure);
317
+ if (!closure.some((row) => row.packageName === release.packageName && row.version === release.version)) {
318
+ fail$1("manifest-schema", "release_missing_from_closure");
319
+ }
320
+ const closureDigest = digest(value, "closureDigest", "closure_digest_invalid");
321
+ if (sha256Commercial(canonicalCommercialJson(closure)) !== closureDigest) {
322
+ fail$1("manifest-closure", "closure_digest_mismatch");
323
+ }
324
+ exactObject(value.sbom, ["format", "digest"], "sbom_invalid");
325
+ const sbom = Object.freeze({
326
+ format: requiredString(value.sbom, "format", "sbom_format_invalid"),
327
+ digest: digest(value.sbom, "digest", "sbom_digest_invalid")
328
+ });
329
+ exactObject(value.entrypoints, ["plugin", "dcmProviders", "manifestProviders", "resources"], "entrypoints_invalid");
330
+ const plugin = requiredString(value.entrypoints, "plugin", "plugin_entrypoint_invalid");
331
+ if (!safeEntrypoint(plugin))
332
+ fail$1("manifest-schema", "plugin_entrypoint_invalid");
333
+ const entrypoints = Object.freeze({
334
+ plugin,
335
+ dcmProviders: sortedUniqueStrings(value.entrypoints, "dcmProviders", "dcm_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint }),
336
+ manifestProviders: sortedUniqueStrings(value.entrypoints, "manifestProviders", "manifest_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint }),
337
+ resources: sortedUniqueStrings(value.entrypoints, "resources", "resource_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint })
338
+ });
339
+ exactObject(value.dcm, ["digest", "operationCatalogDigest"], "dcm_invalid");
340
+ const dcm = Object.freeze({
341
+ digest: digest(value.dcm, "digest", "dcm_digest_invalid"),
342
+ operationCatalogDigest: digest(value.dcm, "operationCatalogDigest", "operation_catalog_digest_invalid")
343
+ });
344
+ exactObject(value.hostAbi, ["protocolVersion", "supportedRange"], "host_abi_invalid");
345
+ const hostAbi = Object.freeze({
346
+ protocolVersion: requiredString(value.hostAbi, "protocolVersion", "host_abi_protocol_invalid"),
347
+ supportedRange: requiredString(value.hostAbi, "supportedRange", "host_abi_range_invalid")
348
+ });
349
+ const degradedOperationIds = sortedUniqueStrings(value, "degradedOperationIds", "degraded_operations_invalid", { allowEmpty: true });
350
+ if (options.knownOperationIds) {
351
+ for (const operationId of degradedOperationIds) {
352
+ if (!options.knownOperationIds.has(operationId))
353
+ fail$1("manifest-schema", "unknown_degraded_operation");
354
+ }
355
+ }
356
+ if (!isRecord$1(value.extensions))
357
+ fail$1("manifest-schema", "extensions_invalid");
358
+ for (const [namespace, extension] of Object.entries(value.extensions)) {
359
+ if (!NAMESPACE.test(namespace) || !isRecord$1(extension))
360
+ fail$1("manifest-schema", "extension_invalid");
361
+ canonicalCommercialJson(extension);
362
+ }
363
+ return Object.freeze({
364
+ manifestId: requiredString(value, "manifestId", "manifest_id_invalid"),
365
+ publisherId: requiredString(value, "publisherId", "publisher_id_invalid"),
366
+ issuedAt,
367
+ notBefore,
368
+ notAfter,
369
+ release,
370
+ closure,
371
+ closureDigest,
372
+ packlistDigest: digest(value, "packlistDigest", "packlist_digest_invalid"),
373
+ sbom,
374
+ entrypoints,
375
+ dcm,
376
+ hostAbi,
377
+ migrationCapsules: parseMigrationCapsules(value.migrationCapsules),
378
+ degradedOperationIds,
379
+ extensions: Object.freeze({ ...value.extensions })
380
+ });
381
+ }
382
+ function signatureInput(envelope) {
383
+ return canonicalCommercialJson(envelope);
384
+ }
385
+ function createReleaseManifestSigningInput(envelope) {
386
+ return Buffer.from(signatureInput(envelope), "utf8");
387
+ }
388
+ function parseReleaseManifestEnvelope(value, options = {}) {
389
+ exactObject(value, ["schemaVersion", "objectType", "payloadCanonicalization", "payloadDigest", "signingHeader", "signature", "payload"], "manifest_envelope_invalid");
390
+ if (value.schemaVersion !== 2)
391
+ fail$1("manifest-schema", "unsupported_schema_version");
392
+ if (value.objectType !== RELEASE_MANIFEST_OBJECT_TYPE)
393
+ fail$1("manifest-schema", "object_type_mismatch");
394
+ if (value.payloadCanonicalization !== RELEASE_MANIFEST_CANONICALIZATION) {
395
+ fail$1("manifest-schema", "canonicalization_unsupported");
396
+ }
397
+ exactObject(value.signingHeader, ["purpose", "alg", "kid", "crit"], "signing_header_invalid");
398
+ if (value.signingHeader.purpose !== RELEASE_MANIFEST_PURPOSE)
399
+ fail$1("manifest-signature", "key_purpose_mismatch");
400
+ if (value.signingHeader.alg !== "EdDSA")
401
+ fail$1("manifest-signature", "algorithm_not_allowed");
402
+ const kid = requiredString(value.signingHeader, "kid", "signing_kid_invalid");
403
+ if (!RELEASE_KID.test(kid))
404
+ fail$1("manifest-signature", "key_purpose_mismatch");
405
+ const crit = sortedUniqueStrings(value.signingHeader, "crit", "critical_fields_invalid", { allowEmpty: true });
406
+ if (canonicalCommercialJson(crit) !== canonicalCommercialJson(RELEASE_MANIFEST_CRITICAL_FIELDS)) {
407
+ fail$1("manifest-signature", "unknown_critical_field");
408
+ }
409
+ const signature = requiredString(value, "signature", "signature_invalid");
410
+ if (!/^[A-Za-z0-9_-]{86}$/.test(signature))
411
+ fail$1("manifest-signature", "signature_invalid");
412
+ const payload = parseReleaseClosureManifest(value.payload, options);
413
+ const payloadDigest = digest(value, "payloadDigest", "payload_digest_invalid");
414
+ if (sha256Commercial(canonicalCommercialJson(payload)) !== payloadDigest) {
415
+ fail$1("manifest-digest", "payload_digest_mismatch");
416
+ }
417
+ return Object.freeze({
418
+ schemaVersion: 2,
419
+ objectType: RELEASE_MANIFEST_OBJECT_TYPE,
420
+ payloadCanonicalization: RELEASE_MANIFEST_CANONICALIZATION,
421
+ payloadDigest,
422
+ signingHeader: Object.freeze({
423
+ purpose: RELEASE_MANIFEST_PURPOSE,
424
+ alg: "EdDSA",
425
+ kid,
426
+ crit
427
+ }),
428
+ signature,
429
+ payload
430
+ });
431
+ }
432
+ function decodeBase64Url(value) {
433
+ try {
434
+ return Buffer.from(value, "base64url");
435
+ } catch {
436
+ fail$1("manifest-signature", "signature_invalid");
437
+ }
438
+ }
439
+ function verifyReleaseManifestEnvelope(value, options) {
440
+ const envelope = parseReleaseManifestEnvelope(value, { knownOperationIds: options.knownOperationIds });
441
+ const duplicateKids = options.trustKeys.filter((key) => key.kid === envelope.signingHeader.kid);
442
+ if (duplicateKids.length !== 1)
443
+ fail$1("manifest-signature", duplicateKids.length ? "duplicate_trust_key" : "unknown_signing_key");
444
+ const trustKey = duplicateKids[0];
445
+ if (trustKey.purpose !== RELEASE_MANIFEST_PURPOSE || trustKey.alg !== "EdDSA" || !RELEASE_KID.test(trustKey.kid)) {
446
+ fail$1("manifest-signature", "key_purpose_mismatch");
447
+ }
448
+ const now = options.now ?? /* @__PURE__ */ new Date();
449
+ const nowMillis = now.getTime();
450
+ if (!Number.isFinite(nowMillis))
451
+ fail$1("manifest-validity", "clock_invalid");
452
+ if (trustKey.status !== void 0 && !["active", "verify-only", "retired", "revoked"].includes(trustKey.status))
453
+ fail$1("manifest-signature", "release_key_status_invalid");
454
+ if (trustKey.status === "retired" || trustKey.status === "revoked") {
455
+ fail$1("manifest-signature", "release_key_not_accepted");
456
+ }
457
+ const keyNotBefore = trustKey.notBefore === void 0 ? null : Date.parse(trustKey.notBefore);
458
+ const keyNotAfter = trustKey.notAfter === void 0 ? null : Date.parse(trustKey.notAfter);
459
+ if (keyNotBefore !== null && !Number.isFinite(keyNotBefore) || keyNotAfter !== null && !Number.isFinite(keyNotAfter) || keyNotBefore !== null && keyNotAfter !== null && keyNotBefore >= keyNotAfter)
460
+ fail$1("manifest-signature", "release_key_time_invalid");
461
+ if (keyNotBefore !== null && nowMillis < keyNotBefore) {
462
+ fail$1("manifest-signature", "release_key_not_yet_valid");
463
+ }
464
+ if (keyNotAfter !== null && nowMillis >= keyNotAfter) {
465
+ fail$1("manifest-signature", "release_key_expired");
466
+ }
467
+ let publicKey;
468
+ try {
469
+ publicKey = createPublicKey(trustKey.publicKeyPem);
470
+ } catch {
471
+ fail$1("manifest-signature", "trust_key_invalid");
472
+ }
473
+ if (publicKey.asymmetricKeyType !== "ed25519")
474
+ fail$1("manifest-signature", "algorithm_not_allowed");
475
+ const unsigned = {
476
+ schemaVersion: envelope.schemaVersion,
477
+ objectType: envelope.objectType,
478
+ payloadCanonicalization: envelope.payloadCanonicalization,
479
+ payloadDigest: envelope.payloadDigest,
480
+ signingHeader: envelope.signingHeader,
481
+ payload: envelope.payload
482
+ };
483
+ if (!verify(null, createReleaseManifestSigningInput(unsigned), publicKey, decodeBase64Url(envelope.signature))) {
484
+ fail$1("manifest-signature", "bad_signature");
485
+ }
486
+ if (nowMillis < Date.parse(envelope.payload.notBefore))
487
+ fail$1("manifest-validity", "manifest_not_yet_valid");
488
+ if (nowMillis >= Date.parse(envelope.payload.notAfter))
489
+ fail$1("manifest-validity", "manifest_expired");
490
+ const verified = Object.freeze({
491
+ envelope,
492
+ manifestDigest: sha256Commercial(canonicalCommercialJson(envelope)),
493
+ payloadDigest: envelope.payloadDigest,
494
+ verifiedAt: now.toISOString(),
495
+ signerKid: envelope.signingHeader.kid
496
+ });
497
+ verifiedReleaseManifests.add(verified);
498
+ return verified;
499
+ }
500
+ const COMMON_CLAIM_KEYS = Object.freeze([
501
+ "aud",
502
+ "domainConstraints",
503
+ "entitlementEpoch",
504
+ "exp",
505
+ "featureIds",
506
+ "fullUntil",
507
+ "iat",
508
+ "installationId",
509
+ "iss",
510
+ "jti",
511
+ "leaseMode",
512
+ "nbf",
513
+ "productIds",
514
+ "refreshAfter",
515
+ "releaseConstraint",
516
+ "revocationEpoch",
517
+ "schemaVersion",
518
+ "skuId",
519
+ "subscriptionId",
520
+ "tenantId"
521
+ ]);
522
+ Object.freeze([
523
+ ...COMMON_CLAIM_KEYS,
524
+ "activationBinding",
525
+ "installationKeyThumbprint"
526
+ ]);
527
+ const STORE_FORMAT_VERSION = 1;
528
+ const SHA256 = /^sha256:[a-f0-9]{64}$/;
529
+ const IDENTITY = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,255}$/;
530
+ const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
531
+ const MAX_ARCHIVE_FILES = 1e5;
532
+ const MAX_FILE_BYTES = 128 * 1024 * 1024;
533
+ function fail(stage, reason, decision = "deny") {
534
+ throw new CommercialArtifactError(stage, reason, decision);
535
+ }
536
+ function isRecord(value) {
537
+ return value !== null && typeof value === "object" && !Array.isArray(value);
538
+ }
539
+ function parseJsonFile(filePath, stage, reason) {
540
+ try {
541
+ return JSON.parse(readFileSync(filePath, "utf8"));
542
+ } catch {
543
+ fail(stage, reason);
544
+ }
545
+ }
546
+ function assertIdentity(value, reason) {
547
+ if (!IDENTITY.test(value))
548
+ fail("store-identity", reason);
549
+ }
550
+ function assertAbsoluteSafeRoot(rootPath, create) {
551
+ if (!path.isAbsolute(rootPath))
552
+ fail("store-path", "store_root_not_absolute");
553
+ const resolved = path.resolve(rootPath);
554
+ if (path.parse(resolved).root === resolved)
555
+ fail("store-path", "store_root_too_broad");
556
+ if (!existsSync(resolved)) {
557
+ fail("store-path", "store_root_missing");
558
+ mkdirSync(resolved, { recursive: true, mode: 448 });
559
+ }
560
+ const stat = lstatSync(resolved);
561
+ if (stat.isSymbolicLink() || !stat.isDirectory())
562
+ fail("store-path", "store_root_unsafe");
563
+ const real = realpathSync.native(resolved);
564
+ if (path.relative(resolved, real) !== "")
565
+ fail("store-path", "store_root_reparse_refused");
566
+ return real;
567
+ }
568
+ function safeChild(root, ...segments) {
569
+ for (const segment of segments) {
570
+ if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
571
+ fail("store-path", "unsafe_managed_segment");
572
+ }
573
+ }
574
+ const candidate = path.join(root, ...segments);
575
+ const relative = path.relative(root, candidate);
576
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative))
577
+ fail("store-path", "managed_path_escape");
578
+ return candidate;
579
+ }
580
+ function ensureManagedDirectory(root, ...segments) {
581
+ let cursor = root;
582
+ for (const segment of segments) {
583
+ cursor = safeChild(cursor, segment);
584
+ if (!existsSync(cursor))
585
+ mkdirSync(cursor, { mode: 448 });
586
+ const stat = lstatSync(cursor);
587
+ if (stat.isSymbolicLink() || !stat.isDirectory())
588
+ fail("store-path", "managed_directory_unsafe");
589
+ if (path.relative(cursor, realpathSync.native(cursor)) !== "")
590
+ fail("store-path", "managed_directory_reparse_refused");
591
+ }
592
+ return cursor;
593
+ }
594
+ function assertRegularFile(filePath, stage, reason) {
595
+ const stat = lstatSync(filePath);
596
+ if (stat.isSymbolicLink() || !stat.isFile())
597
+ fail(stage, reason);
598
+ return realpathSync.native(filePath);
599
+ }
600
+ function digestBytes(bytes) {
601
+ return sha256Commercial(bytes);
602
+ }
603
+ function integrityBytes(bytes) {
604
+ return `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
605
+ }
606
+ function atomicWrite(filePath, bytes, mode = 384) {
607
+ const parent = path.dirname(filePath);
608
+ const tempPath = path.join(parent, `.${path.basename(filePath)}.${randomUUID()}.tmp`);
609
+ writeFileSync(tempPath, bytes, { mode, flag: "wx" });
610
+ renameSync(tempPath, filePath);
611
+ try {
612
+ chmodSync(filePath, mode);
613
+ } catch {
614
+ }
615
+ }
616
+ function trimTarText(bytes) {
617
+ const nul = bytes.indexOf(0);
618
+ return bytes.subarray(0, nul === -1 ? bytes.length : nul).toString("utf8").trim();
619
+ }
620
+ function tarNumber(bytes, reason) {
621
+ if ((bytes[0] & 128) !== 0)
622
+ fail("archive-safety", reason);
623
+ const text = trimTarText(bytes).replace(/\0/g, "").trim();
624
+ if (!text)
625
+ return 0;
626
+ if (!/^[0-7]+$/.test(text))
627
+ fail("archive-safety", reason);
628
+ const value = Number.parseInt(text, 8);
629
+ if (!Number.isSafeInteger(value) || value < 0)
630
+ fail("archive-safety", reason);
631
+ return value;
632
+ }
633
+ function parsePax(bytes) {
634
+ const fields = {};
635
+ let offset = 0;
636
+ while (offset < bytes.length) {
637
+ const space = bytes.indexOf(32, offset);
638
+ if (space < 0)
639
+ fail("archive-safety", "pax_record_invalid");
640
+ const length = Number.parseInt(bytes.subarray(offset, space).toString("ascii"), 10);
641
+ if (!Number.isSafeInteger(length) || length <= 0 || offset + length > bytes.length) {
642
+ fail("archive-safety", "pax_record_invalid");
643
+ }
644
+ const record = bytes.subarray(space + 1, offset + length - 1).toString("utf8");
645
+ const equals = record.indexOf("=");
646
+ if (equals <= 0)
647
+ fail("archive-safety", "pax_record_invalid");
648
+ const key = record.slice(0, equals);
649
+ if (Object.hasOwn(fields, key))
650
+ fail("archive-safety", "pax_duplicate_field");
651
+ fields[key] = record.slice(equals + 1);
652
+ offset += length;
653
+ }
654
+ return fields;
655
+ }
656
+ function safeArchivePath(value) {
657
+ const normalized = value.replaceAll("\\", "/");
658
+ if (!normalized.startsWith("package/") || normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || normalized.length > 4096)
659
+ fail("archive-safety", "archive_path_invalid");
660
+ const relative = normalized.slice("package/".length);
661
+ if (!relative || relative.endsWith("/") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
662
+ fail("archive-safety", "archive_path_invalid");
663
+ }
664
+ return relative.normalize("NFC");
665
+ }
666
+ function inspectNpmTarball(bytes) {
667
+ if (bytes.byteLength <= 0 || bytes.byteLength > MAX_ARCHIVE_BYTES)
668
+ fail("archive-safety", "archive_size_invalid");
669
+ let tar;
670
+ try {
671
+ tar = gunzipSync(bytes, { maxOutputLength: MAX_ARCHIVE_BYTES });
672
+ } catch {
673
+ fail("archive-safety", "archive_gzip_invalid");
674
+ }
675
+ const rows = [];
676
+ const contents = /* @__PURE__ */ new Map();
677
+ let offset = 0;
678
+ let pax = {};
679
+ let longName = null;
680
+ while (offset + 512 <= tar.length) {
681
+ const header = tar.subarray(offset, offset + 512);
682
+ if (header.every((byte) => byte === 0))
683
+ break;
684
+ const storedChecksum = tarNumber(header.subarray(148, 156), "archive_checksum_invalid");
685
+ let checksum = 0;
686
+ for (let index = 0; index < 512; index += 1) {
687
+ checksum += index >= 148 && index < 156 ? 32 : header[index];
688
+ }
689
+ if (storedChecksum !== checksum)
690
+ fail("archive-safety", "archive_checksum_mismatch");
691
+ const baseName = trimTarText(header.subarray(0, 100));
692
+ const prefix = trimTarText(header.subarray(345, 500));
693
+ const headerName = prefix ? `${prefix}/${baseName}` : baseName;
694
+ const mode = tarNumber(header.subarray(100, 108), "archive_mode_invalid") & 511;
695
+ const headerSize = tarNumber(header.subarray(124, 136), "archive_entry_size_invalid");
696
+ if (headerSize > MAX_FILE_BYTES)
697
+ fail("archive-safety", "archive_entry_too_large");
698
+ const type = String.fromCharCode(header[156] || 0);
699
+ const contentOffset = offset + 512;
700
+ const contentEnd = contentOffset + headerSize;
701
+ if (contentEnd > tar.length)
702
+ fail("archive-safety", "archive_truncated");
703
+ const content = tar.subarray(contentOffset, contentEnd);
704
+ offset = contentOffset + Math.ceil(headerSize / 512) * 512;
705
+ if (type === "x" || type === "g") {
706
+ const next = parsePax(content);
707
+ const unsupported = Object.keys(next).filter((key) => !["path", "size", "mtime"].includes(key));
708
+ if (unsupported.some((key) => key === "linkpath"))
709
+ fail("archive-safety", "archive_link_refused");
710
+ pax = type === "g" ? { ...pax, ...next } : next;
711
+ continue;
712
+ }
713
+ if (type === "L") {
714
+ longName = trimTarText(content);
715
+ continue;
716
+ }
717
+ if (type === "5") {
718
+ pax = {};
719
+ longName = null;
720
+ continue;
721
+ }
722
+ if (type !== "\0" && type !== "0")
723
+ fail("archive-safety", "archive_special_entry_refused");
724
+ const entryName = pax.path ?? longName ?? headerName;
725
+ const declaredSize = pax.size === void 0 ? headerSize : Number.parseInt(pax.size, 10);
726
+ if (!Number.isSafeInteger(declaredSize) || declaredSize !== headerSize)
727
+ fail("archive-safety", "archive_entry_size_mismatch");
728
+ const relative = safeArchivePath(entryName);
729
+ if (contents.has(relative))
730
+ fail("archive-safety", "archive_duplicate_path");
731
+ const copy = Buffer.from(content);
732
+ contents.set(relative, copy);
733
+ rows.push(Object.freeze({
734
+ path: relative,
735
+ size: copy.byteLength,
736
+ mode,
737
+ sha256: digestBytes(copy)
738
+ }));
739
+ if (rows.length > MAX_ARCHIVE_FILES)
740
+ fail("archive-safety", "archive_file_limit_exceeded");
741
+ pax = {};
742
+ longName = null;
743
+ }
744
+ rows.sort((left, right) => compareCanonicalText(left.path, right.path));
745
+ const packageBytes = contents.get("package.json");
746
+ if (!packageBytes)
747
+ fail("archive-preflight", "package_json_missing");
748
+ let packageJson;
749
+ try {
750
+ packageJson = JSON.parse(packageBytes.toString("utf8"));
751
+ } catch {
752
+ fail("archive-preflight", "package_json_invalid");
753
+ }
754
+ if (!isRecord(packageJson) || typeof packageJson.name !== "string" || typeof packageJson.version !== "string") {
755
+ fail("archive-preflight", "package_identity_invalid");
756
+ }
757
+ const optionalPeerNames = /* @__PURE__ */ new Set();
758
+ if (packageJson.peerDependenciesMeta !== void 0) {
759
+ if (!isRecord(packageJson.peerDependenciesMeta)) {
760
+ fail("archive-preflight", "package_dependencies_invalid");
761
+ }
762
+ for (const [dependencyName, metadata] of Object.entries(packageJson.peerDependenciesMeta)) {
763
+ if (!isRecord(metadata) || typeof metadata.optional !== "boolean") {
764
+ fail("archive-preflight", "package_dependencies_invalid");
765
+ }
766
+ if (metadata.optional)
767
+ optionalPeerNames.add(dependencyName);
768
+ }
769
+ }
770
+ const runtimeDependencyNames = /* @__PURE__ */ new Set();
771
+ for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
772
+ const dependencies = packageJson[field];
773
+ if (dependencies === void 0)
774
+ continue;
775
+ if (!isRecord(dependencies))
776
+ fail("archive-preflight", "package_dependencies_invalid");
777
+ for (const [dependencyName, dependencyRange] of Object.entries(dependencies)) {
778
+ if (typeof dependencyRange !== "string" || !dependencyRange.trim()) {
779
+ fail("archive-preflight", "package_dependencies_invalid");
780
+ }
781
+ if (field !== "peerDependencies" || !optionalPeerNames.has(dependencyName)) {
782
+ runtimeDependencyNames.add(dependencyName);
783
+ }
784
+ }
785
+ }
786
+ return Object.freeze({
787
+ files: Object.freeze(rows),
788
+ contents,
789
+ filesDigest: sha256Commercial(canonicalCommercialJson(rows.map(({ path: filePath, size, sha256 }) => ({
790
+ path: filePath,
791
+ size,
792
+ sha256
793
+ })))),
794
+ packageName: packageJson.name,
795
+ version: packageJson.version,
796
+ runtimeDependencies: Object.freeze([...runtimeDependencyNames].sort(compareCanonicalText))
797
+ });
798
+ }
799
+ function readOnlyObjectPath(root, digest2) {
800
+ if (!SHA256.test(digest2))
801
+ fail("store-path", "object_digest_invalid");
802
+ return safeChild(root, "objects", "sha256", digest2.slice("sha256:".length));
803
+ }
804
+ function readOnlyTreePath(root, digest2) {
805
+ if (!SHA256.test(digest2))
806
+ fail("store-path", "tree_digest_invalid");
807
+ return safeChild(root, "trees", "sha256", digest2.slice("sha256:".length));
808
+ }
809
+ function verifyTree(root, archive) {
810
+ for (const row of archive.files) {
811
+ const segments = row.path.split("/");
812
+ let cursor = root;
813
+ for (const segment of segments) {
814
+ cursor = safeChild(cursor, segment);
815
+ const stat2 = lstatSync(cursor);
816
+ if (stat2.isSymbolicLink())
817
+ fail("cas-readback", "cas_tree_link_refused", "quarantine");
818
+ }
819
+ const stat = statSync(cursor);
820
+ if (!stat.isFile() || stat.size !== row.size || digestBytes(readFileSync(cursor)) !== row.sha256) {
821
+ fail("cas-readback", "cas_tree_digest_mismatch", "quarantine");
822
+ }
823
+ }
824
+ }
825
+ function resolveEntrypoint(entrypoint, artifacts, closureDigest) {
826
+ const separator = entrypoint.indexOf(":");
827
+ const packageName = entrypoint.slice(0, separator);
828
+ const relative = entrypoint.slice(separator + 1);
829
+ const artifact = artifacts.get(packageName);
830
+ if (!artifact)
831
+ fail("artifact-preflight", "entrypoint_package_missing");
832
+ if (!artifact.files.some((row) => row.path === relative))
833
+ fail("artifact-preflight", "entrypoint_file_missing");
834
+ return `runtimes/sha256/${closureDigest.slice("sha256:".length)}/node_modules/${packageName}/${relative}`;
835
+ }
836
+ function resolveLaunchClosure(manifest, artifacts) {
837
+ const roleRows = manifest.closure.filter((entry) => entry.launchRole !== null);
838
+ const runtime = roleRows.find((entry) => entry.launchRole === "runtime-node");
839
+ if (!runtime)
840
+ fail("artifact-preflight", "runtime_role_missing");
841
+ for (const entry of roleRows) {
842
+ const artifact = artifacts.get(entry.packageName);
843
+ if (!artifact)
844
+ fail("artifact-preflight", "launch_role_package_missing");
845
+ const file = artifact.files.find((candidate) => candidate.path === entry.launchEntrypoint);
846
+ if (!file)
847
+ fail("artifact-preflight", "launch_role_entrypoint_missing");
848
+ if (entry.launchRole !== "runtime-node") {
849
+ if (entry.runtimeRange === null)
850
+ fail("artifact-preflight", "launch_role_runtime_range_missing");
851
+ assertCommercialRuntimeCompatible(runtime.version, entry.runtimeRange);
852
+ }
853
+ }
854
+ const entries = roleRows.map((entry) => {
855
+ const artifact = artifacts.get(entry.packageName);
856
+ if (!artifact)
857
+ fail("artifact-preflight", "launch_role_package_missing");
858
+ const file = artifact.files.find((candidate) => candidate.path === entry.launchEntrypoint);
859
+ if (!file || entry.launchRole === null || entry.launchEntrypoint === null) {
860
+ fail("artifact-preflight", "launch_role_entrypoint_missing");
861
+ }
862
+ return Object.freeze({
863
+ role: entry.launchRole,
864
+ packageName: artifact.packageName,
865
+ packageVersion: artifact.version,
866
+ artifactDigest: artifact.digest,
867
+ entrypoint: entry.launchEntrypoint,
868
+ entrypointDigest: file.sha256,
869
+ runtimeRange: entry.runtimeRange,
870
+ resolvedPath: resolveEntrypoint(`${entry.packageName}:${entry.launchEntrypoint}`, artifacts, manifest.closureDigest)
871
+ });
872
+ }).sort((left, right) => compareCanonicalText(left.role, right.role));
873
+ return Object.freeze({
874
+ runtimeVersion: runtime.version,
875
+ entries: Object.freeze(entries)
876
+ });
877
+ }
878
+ function readOnlyRuntimeRootPath(root, closureDigest) {
879
+ if (!SHA256.test(closureDigest))
880
+ fail("store-path", "closure_digest_invalid");
881
+ return safeChild(root, "runtimes", "sha256", closureDigest.slice("sha256:".length));
882
+ }
883
+ function packageRuntimeRoot(nodeModulesRoot, packageName) {
884
+ const segments = packageName.split("/");
885
+ if (segments.length === 1)
886
+ return safeChild(nodeModulesRoot, segments[0]);
887
+ if (segments.length === 2 && segments[0].startsWith("@")) {
888
+ const scope = ensureManagedDirectory(nodeModulesRoot, segments[0]);
889
+ return safeChild(scope, segments[1]);
890
+ }
891
+ fail("artifact-preflight", "runtime_package_name_invalid");
892
+ }
893
+ function verifyRuntimeClosure(runtimeRoot, artifacts) {
894
+ const nodeModulesRoot = safeChild(runtimeRoot, "node_modules");
895
+ const nodeModulesStat = lstatSync(nodeModulesRoot);
896
+ if (nodeModulesStat.isSymbolicLink() || !nodeModulesStat.isDirectory()) {
897
+ fail("runtime-readback", "runtime_closure_unsafe", "quarantine");
898
+ }
899
+ for (const artifact of artifacts.values()) {
900
+ const packageRoot = packageRuntimeRoot(nodeModulesRoot, artifact.packageName);
901
+ for (const row of artifact.files) {
902
+ let cursor = packageRoot;
903
+ for (const segment of row.path.split("/")) {
904
+ cursor = safeChild(cursor, segment);
905
+ const stat2 = lstatSync(cursor);
906
+ if (stat2.isSymbolicLink())
907
+ fail("runtime-readback", "runtime_link_refused", "quarantine");
908
+ }
909
+ const stat = statSync(cursor);
910
+ if (!stat.isFile() || stat.size !== row.size || digestBytes(readFileSync(cursor)) !== row.sha256) {
911
+ fail("runtime-readback", "runtime_file_digest_mismatch", "quarantine");
912
+ }
913
+ }
914
+ }
915
+ }
916
+ function verifyRuntimeDependencyClosure(artifacts) {
917
+ for (const artifact of artifacts.values()) {
918
+ for (const dependencyName of artifact.runtimeDependencies) {
919
+ if (!artifacts.has(dependencyName)) {
920
+ fail("artifact-preflight", "runtime_dependency_outside_closure");
921
+ }
922
+ }
923
+ }
924
+ }
925
+ function statePath(root, name) {
926
+ return safeChild(ensureManagedDirectory(root, "state"), name);
927
+ }
928
+ function readOnlyStatePath(root, name) {
929
+ return safeChild(root, "state", name);
930
+ }
931
+ function assertStoreIdentity(root, expected, create = false) {
932
+ const filePath = create ? statePath(root, "store-identity.json") : readOnlyStatePath(root, "store-identity.json");
933
+ if (!existsSync(filePath)) {
934
+ if (!expected || !create)
935
+ fail("store-identity", "store_identity_missing", "quarantine");
936
+ const identity = Object.freeze({
937
+ schemaVersion: 1,
938
+ objectType: "aops-commercial-artifact-store-identity-v1",
939
+ storeFormatVersion: STORE_FORMAT_VERSION,
940
+ installationId: expected.installationId,
941
+ hostInstanceId: expected.hostInstanceId
942
+ });
943
+ atomicWrite(filePath, `${canonicalCommercialJson(identity)}
944
+ `);
945
+ }
946
+ const value = parseJsonFile(filePath, "store-identity", "store_identity_json_invalid");
947
+ if (!isRecord(value) || value.schemaVersion !== 1 || value.objectType !== "aops-commercial-artifact-store-identity-v1" || value.storeFormatVersion !== STORE_FORMAT_VERSION || typeof value.installationId !== "string" || typeof value.hostInstanceId !== "string")
948
+ fail("store-identity", "store_identity_schema_invalid", "quarantine");
949
+ if (expected && (value.installationId !== expected.installationId || value.hostInstanceId !== expected.hostInstanceId))
950
+ fail("store-identity", "store_identity_mismatch", "quarantine");
951
+ return value;
952
+ }
953
+ function readOnlyReceiptPath(root, receiptId) {
954
+ assertIdentity(receiptId, "receipt_id_invalid");
955
+ return safeChild(root, "receipts", `${receiptId}.json`);
956
+ }
957
+ function readOnlyManifestPath(root, digest2) {
958
+ if (!SHA256.test(digest2))
959
+ fail("store-path", "manifest_digest_invalid");
960
+ return safeChild(root, "manifests", `${digest2.slice("sha256:".length)}.json`);
961
+ }
962
+ function keyBytes(root, create) {
963
+ const keyPath = readOnlyStatePath(root, "receipt-hmac.key");
964
+ if (!existsSync(keyPath)) {
965
+ fail("receipt-integrity", "receipt_key_missing", "quarantine");
966
+ atomicWrite(keyPath, randomBytes(32), 384);
967
+ }
968
+ const key = readFileSync(assertRegularFile(keyPath, "receipt-integrity", "receipt_key_unsafe"));
969
+ if (key.byteLength !== 32)
970
+ fail("receipt-integrity", "receipt_key_invalid", "quarantine");
971
+ return key;
972
+ }
973
+ function readReceipt(root, receiptId) {
974
+ const value = parseJsonFile(readOnlyReceiptPath(root, receiptId), "receipt-readback", "receipt_json_invalid");
975
+ if (!isRecord(value) || !isRecord(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.receiptDigestOrMac !== "string") {
976
+ fail("receipt-readback", "receipt_schema_invalid", "quarantine");
977
+ }
978
+ if (value.schemaVersion !== 2 || value.objectType !== "aops-installation-receipt-v2") {
979
+ fail("receipt-readback", "receipt_schema_unsupported", "quarantine");
980
+ }
981
+ const { localIntegrity: _, ...unsigned } = value;
982
+ const expected = createHmac("sha256", keyBytes(root)).update(canonicalCommercialJson(unsigned)).digest();
983
+ const actualText = value.localIntegrity.receiptDigestOrMac;
984
+ if (!/^hmac-sha256:[a-f0-9]{64}$/.test(actualText))
985
+ fail("receipt-readback", "receipt_mac_invalid", "quarantine");
986
+ const actual = Buffer.from(actualText.slice("hmac-sha256:".length), "hex");
987
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
988
+ fail("receipt-readback", "receipt_mac_mismatch", "quarantine");
989
+ }
990
+ return value;
991
+ }
992
+ function readPointer(root, name) {
993
+ const filePath = readOnlyStatePath(root, name);
994
+ if (!existsSync(filePath))
995
+ return null;
996
+ const value = parseJsonFile(filePath, "activation-readback", "pointer_json_invalid");
997
+ if (!isRecord(value) || value.schemaVersion !== 1 || typeof value.receiptId !== "string" || typeof value.receiptMac !== "string" || !Number.isSafeInteger(value.generation))
998
+ fail("activation-readback", "pointer_schema_invalid", "quarantine");
999
+ const receipt = readReceipt(root, value.receiptId);
1000
+ if (receipt.localIntegrity.receiptDigestOrMac !== value.receiptMac || receipt.activation.generation !== value.generation)
1001
+ fail("activation-readback", "pointer_receipt_mismatch", "quarantine");
1002
+ return value;
1003
+ }
1004
+ function highWaterPath(root, packageName) {
1005
+ const identity = createHash("sha256").update(packageName, "utf8").digest("hex");
1006
+ return safeChild(ensureManagedDirectory(root, "high-water"), `${identity}.json`);
1007
+ }
1008
+ function highWaterMacInput(value) {
1009
+ return `aops-product-release-high-water-v1\0${canonicalCommercialJson(value)}`;
1010
+ }
1011
+ function verifyHighWaterState(root, packageName, value) {
1012
+ if (!isRecord(value) || canonicalCommercialJson(Object.keys(value).sort()) !== canonicalCommercialJson([
1013
+ "issuedAt",
1014
+ "localIntegrity",
1015
+ "manifestDigest",
1016
+ "objectType",
1017
+ "packageName",
1018
+ "schemaVersion",
1019
+ "versionOrdinal"
1020
+ ]) || value.schemaVersion !== 1 || value.objectType !== "aops-product-release-high-water-v1" || typeof value.packageName !== "string" || value.packageName.length < 1 || value.packageName.length > 512 || value.packageName !== packageName || typeof value.issuedAt !== "string" || !Number.isFinite(Date.parse(value.issuedAt)) || !Number.isSafeInteger(value.versionOrdinal) || Number(value.versionOrdinal) < 0 || typeof value.manifestDigest !== "string" || !SHA256.test(value.manifestDigest) || !isRecord(value.localIntegrity) || canonicalCommercialJson(Object.keys(value.localIntegrity).sort()) !== canonicalCommercialJson(["mac", "scheme"]) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.mac !== "string" || !/^hmac-sha256:[a-f0-9]{64}$/.test(value.localIntegrity.mac))
1021
+ fail("release-high-water", "high_water_schema_invalid", "quarantine");
1022
+ const { localIntegrity: _, ...unsigned } = value;
1023
+ const expected = createHmac("sha256", keyBytes(root)).update(highWaterMacInput(unsigned)).digest();
1024
+ const actual = Buffer.from(value.localIntegrity.mac.slice("hmac-sha256:".length), "hex");
1025
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
1026
+ fail("release-high-water", "high_water_mac_mismatch", "quarantine");
1027
+ }
1028
+ return value;
1029
+ }
1030
+ function readHighWater(root, packageName) {
1031
+ const filePath = highWaterPath(root, packageName);
1032
+ if (!existsSync(filePath))
1033
+ return null;
1034
+ const value = parseJsonFile(filePath, "release-high-water", "high_water_json_invalid");
1035
+ const verified = verifyHighWaterState(root, packageName, value);
1036
+ return Object.freeze({
1037
+ issuedAt: verified.issuedAt,
1038
+ versionOrdinal: verified.versionOrdinal,
1039
+ manifestDigest: verified.manifestDigest
1040
+ });
1041
+ }
1042
+ function assertRetainedHighWater(root, receipt) {
1043
+ const retained = readHighWater(root, receipt.packageName);
1044
+ if (!retained)
1045
+ fail("release-high-water", "high_water_missing", "quarantine");
1046
+ if (retained.versionOrdinal < receipt.releaseHighWater.versionOrdinal) {
1047
+ fail("release-high-water", "high_water_receipt_mismatch", "quarantine");
1048
+ }
1049
+ return retained;
1050
+ }
1051
+ function verifyStoredClosure(root, receipt, onVerified) {
1052
+ const startedAt = process.hrtime.bigint();
1053
+ const artifacts = /* @__PURE__ */ new Map();
1054
+ let casBytesRead = 0;
1055
+ let npmArtifactCount = 0;
1056
+ let archiveFileCount = 0;
1057
+ let archiveFileBytes = 0;
1058
+ for (const object of receipt.casObjects) {
1059
+ const filePath = readOnlyObjectPath(root, object.digest);
1060
+ const file = assertRegularFile(filePath, "cas-readback", "cas_object_missing");
1061
+ const bytes = readFileSync(file);
1062
+ casBytesRead += bytes.byteLength;
1063
+ if (bytes.byteLength !== object.size || digestBytes(bytes) !== object.digest) {
1064
+ fail("cas-readback", "cas_object_digest_mismatch", "quarantine");
1065
+ }
1066
+ if (object.role.startsWith("npm:")) {
1067
+ npmArtifactCount += 1;
1068
+ const packageName = object.role.slice("npm:".length);
1069
+ const archive = inspectNpmTarball(bytes);
1070
+ archiveFileCount += archive.files.length;
1071
+ archiveFileBytes += archive.files.reduce((total, row) => total + row.size, 0);
1072
+ if (archive.packageName !== packageName)
1073
+ fail("cas-readback", "cas_package_identity_mismatch", "quarantine");
1074
+ const tree = readOnlyTreePath(root, object.digest);
1075
+ if (!existsSync(tree))
1076
+ fail("cas-readback", "cas_tree_missing", "quarantine");
1077
+ const treeStat = lstatSync(tree);
1078
+ if (treeStat.isSymbolicLink() || !treeStat.isDirectory()) {
1079
+ fail("cas-readback", "cas_tree_unsafe", "quarantine");
1080
+ }
1081
+ verifyTree(tree, archive);
1082
+ artifacts.set(packageName, {
1083
+ packageName,
1084
+ version: archive.version,
1085
+ digest: object.digest,
1086
+ integrity: integrityBytes(bytes),
1087
+ filesDigest: archive.filesDigest,
1088
+ objectPath: file,
1089
+ treePath: tree,
1090
+ files: archive.files,
1091
+ runtimeDependencies: archive.runtimeDependencies
1092
+ });
1093
+ }
1094
+ }
1095
+ const runtimeRoot = readOnlyRuntimeRootPath(root, receipt.closureDigest);
1096
+ if (!existsSync(runtimeRoot))
1097
+ fail("runtime-readback", "runtime_closure_missing", "quarantine");
1098
+ verifyRuntimeClosure(runtimeRoot, artifacts);
1099
+ verifyRuntimeDependencyClosure(artifacts);
1100
+ onVerified?.(Object.freeze({
1101
+ elapsedMs: Number(process.hrtime.bigint() - startedAt) / 1e6,
1102
+ casObjectCount: receipt.casObjects.length,
1103
+ npmArtifactCount,
1104
+ tarballDecompressionCount: npmArtifactCount,
1105
+ archiveFileCount,
1106
+ casBytesRead,
1107
+ treeBytesRead: archiveFileBytes,
1108
+ runtimeBytesRead: archiveFileBytes,
1109
+ materializedBytesDerivedFromArchiveMetadata: true,
1110
+ materializedFilePasses: 2,
1111
+ totalFileReads: receipt.casObjects.length + archiveFileCount * 2,
1112
+ totalBytesRead: casBytesRead + archiveFileBytes * 2
1113
+ }));
1114
+ return artifacts;
1115
+ }
1116
+ const COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE = "aops-commercial-integrity-authority-v1";
1117
+ const COMMERCIAL_INTEGRITY_PENDING_PURPOSE = "aops-commercial-integrity-pending-v2";
1118
+ function commercialIntegrityRoot(stateRoot, create) {
1119
+ if (!path.isAbsolute(stateRoot))
1120
+ fail("commercial-integrity", "integrity_state_root_not_absolute");
1121
+ const resolved = path.resolve(stateRoot);
1122
+ if (!existsSync(resolved)) {
1123
+ return null;
1124
+ }
1125
+ const safeStateRoot = assertAbsoluteSafeRoot(resolved);
1126
+ {
1127
+ const candidate = path.join(safeStateRoot, "commercial-integrity");
1128
+ if (!existsSync(candidate))
1129
+ return null;
1130
+ }
1131
+ return ensureManagedDirectory(safeStateRoot, "commercial-integrity");
1132
+ }
1133
+ function commercialIntegrityKey(root, create) {
1134
+ const keyPath = safeChild(root, "authority-hmac.key");
1135
+ if (!existsSync(keyPath)) {
1136
+ return null;
1137
+ }
1138
+ const key = readFileSync(assertRegularFile(keyPath, "commercial-integrity", "integrity_key_unsafe"));
1139
+ if (key.byteLength !== 32)
1140
+ return null;
1141
+ return key;
1142
+ }
1143
+ function integrityMac(key, purpose, value) {
1144
+ return createHmac("sha256", key).update(`${purpose}\0${canonicalCommercialJson(value)}`).digest("hex");
1145
+ }
1146
+ function authorityUnsigned(value) {
1147
+ const { localIntegrity: _, ...unsigned } = value;
1148
+ return unsigned;
1149
+ }
1150
+ function pendingUnsigned(value) {
1151
+ const { localIntegrity: _, ...unsigned } = value;
1152
+ return unsigned;
1153
+ }
1154
+ function signCommercialIntegrityAuthority(key, value) {
1155
+ return Object.freeze({
1156
+ ...value,
1157
+ localIntegrity: Object.freeze({
1158
+ scheme: "hmac-sha256-v1",
1159
+ mac: integrityMac(key, COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE, value)
1160
+ })
1161
+ });
1162
+ }
1163
+ function parseOptionalJson(filePath) {
1164
+ if (!existsSync(filePath))
1165
+ return null;
1166
+ try {
1167
+ const file = assertRegularFile(filePath, "commercial-integrity", "integrity_record_unsafe");
1168
+ return JSON.parse(readFileSync(file, "utf8"));
1169
+ } catch (error) {
1170
+ if (error instanceof CommercialArtifactError)
1171
+ throw error;
1172
+ return null;
1173
+ }
1174
+ }
1175
+ function validIntegrityFile(value) {
1176
+ return isRecord(value) && typeof value.relativePath === "string" && value.relativePath.length > 0 && !value.relativePath.startsWith("/") && !value.relativePath.includes("\\") && !value.relativePath.split("/").some((segment) => !segment || segment === "." || segment === "..") && Number.isSafeInteger(value.size) && Number(value.size) >= 0 && typeof value.mtimeMs === "number" && Number.isFinite(value.mtimeMs) && typeof value.fileId === "string";
1177
+ }
1178
+ function validCriticalFile(value) {
1179
+ return isRecord(value) && typeof value.relativePath === "string" && SHA256.test(String(value.digest));
1180
+ }
1181
+ function authorityShape(value) {
1182
+ if (!isRecord(value) || value.schemaVersion !== 1 || value.objectType !== "aops-commercial-integrity-authority-v1" || typeof value.installationId !== "string" || typeof value.hostInstanceId !== "string" || typeof value.receiptId !== "string" || !SHA256.test(String(value.closureDigest)) || !Number.isSafeInteger(value.activationGeneration) || Number(value.activationGeneration) < 1 || typeof value.verifiedAt !== "string" || ![
1183
+ "install",
1184
+ "update",
1185
+ "rollback",
1186
+ "scheduled",
1187
+ "routine-size-drift-full-verify",
1188
+ "authority-reestablished"
1189
+ ].includes(String(value.verificationSource)) || typeof value.authorityReestablished !== "boolean" || typeof value.previousAnchorUnknown !== "boolean" || !Array.isArray(value.files) || !value.files.every(validIntegrityFile) || !validCriticalFile(value.dcm) || !validCriticalFile(value.operationCatalog) || !isRecord(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.mac !== "string")
1190
+ return false;
1191
+ let previous = "";
1192
+ for (const file of value.files) {
1193
+ if (file.relativePath <= previous)
1194
+ return false;
1195
+ previous = file.relativePath;
1196
+ }
1197
+ return true;
1198
+ }
1199
+ function pendingShape(value) {
1200
+ const hasNoLineage = isRecord(value) && value.planId === null && value.previousOperationReceiptId === null && value.previousPlanId === null;
1201
+ const hasExactLineage = isRecord(value) && SHA256.test(String(value.planId)) && typeof value.previousOperationReceiptId === "string" && value.previousOperationReceiptId.length > 0 && SHA256.test(String(value.previousPlanId));
1202
+ return isRecord(value) && value.schemaVersion === 2 && value.objectType === "aops-commercial-integrity-pending-v2" && ["install", "update", "rollback"].includes(String(value.operation)) && (hasNoLineage || hasExactLineage) && (value.operation === "install" ? hasNoLineage : true) && typeof value.installationId === "string" && typeof value.hostInstanceId === "string" && (value.priorReceiptId === null || typeof value.priorReceiptId === "string") && isRecord(value.target) && authorityShape({
1203
+ ...value.target,
1204
+ localIntegrity: { scheme: "hmac-sha256-v1", mac: "0".repeat(64) }
1205
+ }) && isRecord(value.localIntegrity) && value.localIntegrity.scheme === "hmac-sha256-v1" && typeof value.localIntegrity.mac === "string";
1206
+ }
1207
+ function verifyMacText(actualText, expectedText) {
1208
+ if (!/^[a-f0-9]{64}$/.test(actualText) || !/^[a-f0-9]{64}$/.test(expectedText))
1209
+ return false;
1210
+ const actual = Buffer.from(actualText, "hex");
1211
+ const expected = Buffer.from(expectedText, "hex");
1212
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
1213
+ }
1214
+ function readCommercialIntegrityAuthority(root, key) {
1215
+ const value = parseOptionalJson(safeChild(root, "authority.json"));
1216
+ if (value === null || !authorityShape(value))
1217
+ return null;
1218
+ const expected = integrityMac(key, COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE, authorityUnsigned(value));
1219
+ if (!verifyMacText(value.localIntegrity.mac, expected)) {
1220
+ fail("commercial-integrity", "integrity_authority_mac_mismatch", "quarantine");
1221
+ }
1222
+ return value;
1223
+ }
1224
+ function readCommercialIntegrityPending(root, key) {
1225
+ const value = parseOptionalJson(safeChild(root, "pending.json"));
1226
+ if (value === null)
1227
+ return null;
1228
+ if (!pendingShape(value))
1229
+ return "invalid";
1230
+ const expected = integrityMac(key, COMMERCIAL_INTEGRITY_PENDING_PURPOSE, pendingUnsigned(value));
1231
+ return verifyMacText(value.localIntegrity.mac, expected) ? value : "invalid";
1232
+ }
1233
+ function readCommercialIntegrityQuarantine(root, key) {
1234
+ const value = parseOptionalJson(safeChild(root, "quarantine.json"));
1235
+ if (value === null)
1236
+ return null;
1237
+ if (!isRecord(value) || value.schemaVersion !== 1 || value.objectType !== "aops-commercial-integrity-quarantine-v1" || typeof value.installationId !== "string" || typeof value.hostInstanceId !== "string" || typeof value.receiptId !== "string" || !SHA256.test(String(value.closureDigest)) || !Number.isSafeInteger(value.activationGeneration) || typeof value.detectedAt !== "string" || value.source !== "scheduled-verification" || typeof value.stage !== "string" || typeof value.reason !== "string" || !isRecord(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.mac !== "string")
1238
+ fail("commercial-integrity", "integrity_quarantine_record_invalid", "quarantine");
1239
+ const { localIntegrity: _, ...unsigned } = value;
1240
+ const expected = integrityMac(key, "aops-commercial-integrity-quarantine-v1", unsigned);
1241
+ if (!verifyMacText(value.localIntegrity.mac, expected)) {
1242
+ fail("commercial-integrity", "integrity_quarantine_mac_mismatch", "quarantine");
1243
+ }
1244
+ return value;
1245
+ }
1246
+ function persistScheduledIntegrityQuarantine(integrityRoot, key, receipt, error, now) {
1247
+ const unsigned = Object.freeze({
1248
+ schemaVersion: 1,
1249
+ objectType: "aops-commercial-integrity-quarantine-v1",
1250
+ installationId: receipt.installationId,
1251
+ hostInstanceId: receipt.hostInstanceId,
1252
+ receiptId: receipt.receiptId,
1253
+ closureDigest: receipt.closureDigest,
1254
+ activationGeneration: receipt.activation.generation,
1255
+ detectedAt: now.toISOString(),
1256
+ source: "scheduled-verification",
1257
+ stage: error instanceof CommercialArtifactError ? error.stage : "scheduled-verification",
1258
+ reason: error instanceof CommercialArtifactError ? error.reason : "scheduled_verification_failed"
1259
+ });
1260
+ const value = Object.freeze({
1261
+ ...unsigned,
1262
+ localIntegrity: Object.freeze({
1263
+ scheme: "hmac-sha256-v1",
1264
+ mac: integrityMac(key, "aops-commercial-integrity-quarantine-v1", unsigned)
1265
+ })
1266
+ });
1267
+ atomicWrite(safeChild(integrityRoot, "quarantine.json"), `${canonicalCommercialJson(value)}
1268
+ `);
1269
+ }
1270
+ function integrityRelativePath(storeRoot, filePath) {
1271
+ const relative = path.relative(storeRoot, filePath).split(path.sep).join("/");
1272
+ if (!relative || relative.startsWith("../") || path.isAbsolute(relative)) {
1273
+ fail("commercial-integrity", "integrity_snapshot_path_escape", "quarantine");
1274
+ }
1275
+ return relative;
1276
+ }
1277
+ function integrityStoredPath(storeRoot, relativePath) {
1278
+ let cursor = storeRoot;
1279
+ for (const segment of relativePath.split("/"))
1280
+ cursor = safeChild(cursor, segment);
1281
+ return cursor;
1282
+ }
1283
+ function integrityFileRecord(storeRoot, filePath) {
1284
+ const stat = lstatSync(filePath);
1285
+ if (stat.isSymbolicLink() || !stat.isFile()) {
1286
+ fail("commercial-integrity", "integrity_snapshot_file_unsafe", "quarantine");
1287
+ }
1288
+ return Object.freeze({
1289
+ relativePath: integrityRelativePath(storeRoot, filePath),
1290
+ size: stat.size,
1291
+ mtimeMs: stat.mtimeMs,
1292
+ fileId: `${stat.dev}:${stat.ino}`
1293
+ });
1294
+ }
1295
+ function runtimePackageReadOnlyRoot(nodeModulesRoot, packageName) {
1296
+ const segments = packageName.split("/");
1297
+ if (segments.length === 1)
1298
+ return safeChild(nodeModulesRoot, segments[0]);
1299
+ if (segments.length === 2 && segments[0].startsWith("@")) {
1300
+ return safeChild(nodeModulesRoot, segments[0], segments[1]);
1301
+ }
1302
+ fail("commercial-integrity", "integrity_package_name_invalid", "quarantine");
1303
+ }
1304
+ function buildCommercialIntegrityAuthority(storeRoot, receipt, artifacts, source, now, flags = {
1305
+ authorityReestablished: false,
1306
+ previousAnchorUnknown: false
1307
+ }) {
1308
+ const records = /* @__PURE__ */ new Map();
1309
+ const add = (filePath) => {
1310
+ const record = integrityFileRecord(storeRoot, filePath);
1311
+ const existing = records.get(record.relativePath);
1312
+ if (existing && existing.size !== record.size) {
1313
+ fail("commercial-integrity", "integrity_snapshot_duplicate_mismatch", "quarantine");
1314
+ }
1315
+ records.set(record.relativePath, record);
1316
+ };
1317
+ for (const object of receipt.casObjects)
1318
+ add(readOnlyObjectPath(storeRoot, object.digest));
1319
+ const runtimeRoot = readOnlyRuntimeRootPath(storeRoot, receipt.closureDigest);
1320
+ const nodeModulesRoot = safeChild(runtimeRoot, "node_modules");
1321
+ const critical = /* @__PURE__ */ new Map();
1322
+ for (const artifact of artifacts.values()) {
1323
+ const packageRoot = runtimePackageReadOnlyRoot(nodeModulesRoot, artifact.packageName);
1324
+ for (const row of artifact.files) {
1325
+ const treeFile = path.join(artifact.treePath, ...row.path.split("/"));
1326
+ const runtimeFile = path.join(packageRoot, ...row.path.split("/"));
1327
+ add(treeFile);
1328
+ add(runtimeFile);
1329
+ const candidates = critical.get(row.sha256) ?? [];
1330
+ candidates.push(integrityRelativePath(storeRoot, runtimeFile));
1331
+ critical.set(row.sha256, candidates);
1332
+ }
1333
+ }
1334
+ const criticalFile = (digest2, reason) => {
1335
+ const candidates = critical.get(digest2)?.sort();
1336
+ if (!candidates?.length)
1337
+ fail("commercial-integrity", reason, "quarantine");
1338
+ return Object.freeze({ relativePath: candidates[0], digest: digest2 });
1339
+ };
1340
+ return Object.freeze({
1341
+ schemaVersion: 1,
1342
+ objectType: "aops-commercial-integrity-authority-v1",
1343
+ installationId: receipt.installationId,
1344
+ hostInstanceId: receipt.hostInstanceId,
1345
+ receiptId: receipt.receiptId,
1346
+ closureDigest: receipt.closureDigest,
1347
+ activationGeneration: receipt.activation.generation,
1348
+ verifiedAt: now.toISOString(),
1349
+ verificationSource: source,
1350
+ authorityReestablished: flags.authorityReestablished,
1351
+ previousAnchorUnknown: flags.previousAnchorUnknown,
1352
+ files: Object.freeze([...records.values()].sort((left, right) => compareCanonicalText(left.relativePath, right.relativePath))),
1353
+ dcm: criticalFile(receipt.dcmDigest, "integrity_dcm_path_missing"),
1354
+ operationCatalog: criticalFile(receipt.operationCatalogDigest, "integrity_operation_catalog_path_missing")
1355
+ });
1356
+ }
1357
+ function persistCommercialIntegrityAuthority(integrityRoot, key, value) {
1358
+ const authority = signCommercialIntegrityAuthority(key, value);
1359
+ atomicWrite(safeChild(integrityRoot, "authority.json"), `${canonicalCommercialJson(authority)}
1360
+ `);
1361
+ return authority;
1362
+ }
1363
+ function verifyRoutineIntegrityFiles(storeRoot, authority) {
1364
+ let bytes = 0;
1365
+ let advisoryMtimeDriftCount = 0;
1366
+ let advisoryFileIdDriftCount = 0;
1367
+ for (const expected of authority.files) {
1368
+ const filePath = integrityStoredPath(storeRoot, expected.relativePath);
1369
+ if (!existsSync(filePath))
1370
+ return Object.freeze({
1371
+ matches: false,
1372
+ fileCount: authority.files.length,
1373
+ bytes,
1374
+ advisoryMtimeDriftCount,
1375
+ advisoryFileIdDriftCount
1376
+ });
1377
+ const stat = lstatSync(filePath);
1378
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size !== expected.size) {
1379
+ return Object.freeze({
1380
+ matches: false,
1381
+ fileCount: authority.files.length,
1382
+ bytes,
1383
+ advisoryMtimeDriftCount,
1384
+ advisoryFileIdDriftCount
1385
+ });
1386
+ }
1387
+ bytes += stat.size;
1388
+ if (stat.mtimeMs !== expected.mtimeMs)
1389
+ advisoryMtimeDriftCount += 1;
1390
+ if (`${stat.dev}:${stat.ino}` !== expected.fileId)
1391
+ advisoryFileIdDriftCount += 1;
1392
+ }
1393
+ return Object.freeze({
1394
+ matches: true,
1395
+ fileCount: authority.files.length,
1396
+ bytes,
1397
+ advisoryMtimeDriftCount,
1398
+ advisoryFileIdDriftCount
1399
+ });
1400
+ }
1401
+ function readCriticalIntegrityFile(storeRoot, critical) {
1402
+ const filePath = assertRegularFile(integrityStoredPath(storeRoot, critical.relativePath), "commercial-integrity", "integrity_critical_file_missing");
1403
+ const bytes = readFileSync(filePath);
1404
+ if (digestBytes(bytes) !== critical.digest) {
1405
+ fail("commercial-integrity", "integrity_critical_file_digest_mismatch", "quarantine");
1406
+ }
1407
+ return bytes;
1408
+ }
1409
+ function readClosureFileByDigest(root, receipt, digest2) {
1410
+ if (!SHA256.test(digest2))
1411
+ fail("closure-readback", "closure_file_digest_invalid");
1412
+ let matched = null;
1413
+ for (const object of receipt.casObjects) {
1414
+ if (!object.role.startsWith("npm:"))
1415
+ continue;
1416
+ const file = assertRegularFile(readOnlyObjectPath(root, object.digest), "cas-readback", "cas_object_missing");
1417
+ const bytes = readFileSync(file);
1418
+ if (bytes.byteLength !== object.size || digestBytes(bytes) !== object.digest) {
1419
+ fail("cas-readback", "cas_object_digest_mismatch", "quarantine");
1420
+ }
1421
+ const archive = inspectNpmTarball(bytes);
1422
+ for (const row of archive.files) {
1423
+ if (row.sha256 !== digest2)
1424
+ continue;
1425
+ const candidate = archive.contents.get(row.path);
1426
+ if (!candidate || digestBytes(candidate) !== digest2) {
1427
+ fail("closure-readback", "closure_file_digest_mismatch", "quarantine");
1428
+ }
1429
+ if (matched && !matched.equals(candidate)) {
1430
+ fail("closure-readback", "closure_file_digest_collision", "quarantine");
1431
+ }
1432
+ matched = Buffer.from(candidate);
1433
+ }
1434
+ }
1435
+ if (!matched)
1436
+ fail("closure-readback", "closure_file_missing", "quarantine");
1437
+ return matched;
1438
+ }
1439
+ function readStoredManifest(root, digest2) {
1440
+ const value = parseJsonFile(readOnlyManifestPath(root, digest2), "manifest-readback", "stored_manifest_invalid");
1441
+ return value;
1442
+ }
1443
+ function assertManifestReceiptBinding(receipt, manifest) {
1444
+ const payload = manifest.envelope.payload;
1445
+ if (manifest.manifestDigest !== receipt.manifestDigest || payload.release.releaseId !== receipt.releaseId || payload.release.packageName !== receipt.packageName || payload.release.version !== receipt.version || payload.closureDigest !== receipt.closureDigest || payload.packlistDigest !== receipt.packlistDigest || payload.dcm.digest !== receipt.dcmDigest || payload.dcm.operationCatalogDigest !== receipt.operationCatalogDigest)
1446
+ fail("manifest-readback", "manifest_receipt_mismatch", "quarantine");
1447
+ }
1448
+ function assertRoutineLaunchClosureBinding(root, receipt, payload) {
1449
+ const roleRows = payload.closure.filter((entry) => entry.launchRole !== null);
1450
+ const runtime = roleRows.find((entry) => entry.launchRole === "runtime-node");
1451
+ if (!runtime)
1452
+ fail("manifest-readback", "runtime_role_missing", "quarantine");
1453
+ if (receipt.launchClosure.runtimeVersion !== runtime.version || receipt.launchClosure.entries.length !== roleRows.length)
1454
+ fail("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1455
+ for (const row of roleRows) {
1456
+ const entry = receipt.launchClosure.entries.find((candidate) => candidate.role === row.launchRole);
1457
+ const expectedPath = row.launchEntrypoint === null ? null : `runtimes/sha256/${receipt.closureDigest.slice("sha256:".length)}/node_modules/${row.packageName}/${row.launchEntrypoint}`;
1458
+ if (!entry || entry.packageName !== row.packageName || entry.packageVersion !== row.version || entry.artifactDigest !== row.artifactSha256 || entry.entrypoint !== row.launchEntrypoint || entry.runtimeRange !== row.runtimeRange || entry.resolvedPath !== expectedPath)
1459
+ fail("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1460
+ const launchFile = assertRegularFile(integrityStoredPath(root, entry.resolvedPath), "manifest-readback", "launch_closure_file_missing");
1461
+ if (statSync(launchFile).size < 0) {
1462
+ fail("manifest-readback", "launch_closure_file_missing", "quarantine");
1463
+ }
1464
+ if (row.launchRole !== "runtime-node") {
1465
+ if (row.runtimeRange === null) {
1466
+ fail("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1467
+ }
1468
+ assertCommercialRuntimeCompatible(runtime.version, row.runtimeRange);
1469
+ }
1470
+ }
1471
+ }
1472
+ function assertAuthorityStoreBinding(authority, identity) {
1473
+ if (authority.installationId !== identity.installationId || authority.hostInstanceId !== identity.hostInstanceId)
1474
+ fail("commercial-integrity", "integrity_authority_store_identity_mismatch", "quarantine");
1475
+ }
1476
+ function readVerifiedActiveCommercialArtifact(options) {
1477
+ const root = assertAbsoluteSafeRoot(options.storeRoot);
1478
+ const identity = assertStoreIdentity(root, options.expectedIdentity);
1479
+ if (existsSync(readOnlyStatePath(root, "activation-journal.json"))) {
1480
+ fail("activation-readback", "activation_recovery_required", "quarantine");
1481
+ }
1482
+ const pointer = readPointer(root, "active.json");
1483
+ if (!pointer)
1484
+ return null;
1485
+ const receipt = readReceipt(root, pointer.receiptId);
1486
+ if (receipt.installationId !== identity.installationId || receipt.hostInstanceId !== identity.hostInstanceId)
1487
+ fail("store-identity", "receipt_store_identity_mismatch", "quarantine");
1488
+ assertRetainedHighWater(root, receipt);
1489
+ const mode = options.verificationMode ?? "full";
1490
+ const scheduledIntegrityRoot = mode === "scheduled" && options.integrityStateRoot ? commercialIntegrityRoot(options.integrityStateRoot) : null;
1491
+ const scheduledKey = scheduledIntegrityRoot ? commercialIntegrityKey(scheduledIntegrityRoot) : null;
1492
+ if (scheduledIntegrityRoot && scheduledKey && readCommercialIntegrityQuarantine(scheduledIntegrityRoot, scheduledKey))
1493
+ fail("commercial-integrity", "integrity_scheduled_quarantine_active", "quarantine");
1494
+ try {
1495
+ const manifest = verifyReleaseManifestEnvelope(readStoredManifest(root, receipt.manifestDigest), {
1496
+ trustKeys: options.trustKeys,
1497
+ now: options.now,
1498
+ knownOperationIds: options.knownOperationIds
1499
+ });
1500
+ assertManifestReceiptBinding(receipt, manifest);
1501
+ const payload = manifest.envelope.payload;
1502
+ let artifacts = null;
1503
+ let routineAuthority = null;
1504
+ let routineDecision = null;
1505
+ let routineFileCount = 0;
1506
+ let routineBytes = 0;
1507
+ let advisoryMtimeDriftCount = 0;
1508
+ let advisoryFileIdDriftCount = 0;
1509
+ const routineStartedAt = process.hrtime.bigint();
1510
+ const fullVerify = () => verifyStoredClosure(root, receipt, options.onClosureVerified);
1511
+ if (mode === "routine" && options.integrityStateRoot) {
1512
+ const integrityRoot = commercialIntegrityRoot(options.integrityStateRoot, false);
1513
+ const key = integrityRoot ? commercialIntegrityKey(integrityRoot, false) : null;
1514
+ const authority = integrityRoot && key ? readCommercialIntegrityAuthority(integrityRoot, key) : null;
1515
+ if (integrityRoot && key && readCommercialIntegrityQuarantine(integrityRoot, key)) {
1516
+ fail("commercial-integrity", "integrity_scheduled_quarantine_active", "quarantine");
1517
+ }
1518
+ if (!integrityRoot || !key || !authority) {
1519
+ artifacts = fullVerify();
1520
+ routineDecision = "full-fallback-authority-unavailable";
1521
+ } else {
1522
+ assertAuthorityStoreBinding(authority, identity);
1523
+ if (authority.activationGeneration > receipt.activation.generation) {
1524
+ fail("commercial-integrity", "integrity_authority_ahead", "quarantine");
1525
+ }
1526
+ if (authority.activationGeneration < receipt.activation.generation) {
1527
+ const pending = readCommercialIntegrityPending(integrityRoot, key);
1528
+ if (pending !== null && pending !== "invalid" && pending.installationId === identity.installationId && pending.hostInstanceId === identity.hostInstanceId && pending.target.receiptId === receipt.receiptId && pending.target.closureDigest === receipt.closureDigest && pending.target.activationGeneration === receipt.activation.generation) {
1529
+ artifacts = fullVerify();
1530
+ const healed = buildCommercialIntegrityAuthority(root, receipt, artifacts, pending.target.verificationSource, options.now ?? /* @__PURE__ */ new Date());
1531
+ routineAuthority = persistCommercialIntegrityAuthority(integrityRoot, key, healed);
1532
+ rmSync(safeChild(integrityRoot, "pending.json"), { force: true });
1533
+ routineDecision = "full-heal-forward";
1534
+ } else {
1535
+ artifacts = fullVerify();
1536
+ routineDecision = "full-fallback-authority-behind";
1537
+ }
1538
+ } else {
1539
+ if (authority.receiptId !== receipt.receiptId || authority.closureDigest !== receipt.closureDigest)
1540
+ fail("commercial-integrity", "integrity_authority_receipt_mismatch", "quarantine");
1541
+ const sweep = verifyRoutineIntegrityFiles(root, authority);
1542
+ routineFileCount = sweep.fileCount;
1543
+ routineBytes = sweep.bytes;
1544
+ advisoryMtimeDriftCount = sweep.advisoryMtimeDriftCount;
1545
+ advisoryFileIdDriftCount = sweep.advisoryFileIdDriftCount;
1546
+ if (!sweep.matches) {
1547
+ artifacts = fullVerify();
1548
+ const refreshed = buildCommercialIntegrityAuthority(root, receipt, artifacts, "routine-size-drift-full-verify", options.now ?? /* @__PURE__ */ new Date());
1549
+ routineAuthority = persistCommercialIntegrityAuthority(integrityRoot, key, refreshed);
1550
+ routineDecision = "full-fallback-size-drift";
1551
+ } else {
1552
+ routineAuthority = authority;
1553
+ routineDecision = "verified";
1554
+ }
1555
+ }
1556
+ }
1557
+ } else {
1558
+ artifacts = fullVerify();
1559
+ if (mode === "scheduled" && options.integrityStateRoot) {
1560
+ const integrityRoot = scheduledIntegrityRoot;
1561
+ const key = scheduledKey;
1562
+ const authority = integrityRoot && key ? readCommercialIntegrityAuthority(integrityRoot, key) : null;
1563
+ if (!integrityRoot || !key || !authority) {
1564
+ fail("commercial-integrity", "integrity_authority_reestablish_required", "quarantine");
1565
+ }
1566
+ assertAuthorityStoreBinding(authority, identity);
1567
+ if (authority.activationGeneration > receipt.activation.generation) {
1568
+ fail("commercial-integrity", "integrity_authority_ahead", "quarantine");
1569
+ }
1570
+ if (authority.activationGeneration < receipt.activation.generation) {
1571
+ fail("commercial-integrity", "integrity_authority_behind_reestablish_required", "quarantine");
1572
+ }
1573
+ if (authority.receiptId !== receipt.receiptId || authority.closureDigest !== receipt.closureDigest) {
1574
+ fail("commercial-integrity", "integrity_authority_receipt_mismatch", "quarantine");
1575
+ }
1576
+ persistCommercialIntegrityAuthority(integrityRoot, key, buildCommercialIntegrityAuthority(root, receipt, artifacts, "scheduled", options.now ?? /* @__PURE__ */ new Date()));
1577
+ }
1578
+ }
1579
+ if (artifacts) {
1580
+ const launchClosure = resolveLaunchClosure(payload, artifacts);
1581
+ if (canonicalCommercialJson(launchClosure) !== canonicalCommercialJson(receipt.launchClosure)) {
1582
+ fail("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1583
+ }
1584
+ } else {
1585
+ assertRoutineLaunchClosureBinding(root, receipt, payload);
1586
+ }
1587
+ const dcmBytes = routineAuthority ? readCriticalIntegrityFile(root, routineAuthority.dcm) : readClosureFileByDigest(root, receipt, receipt.dcmDigest);
1588
+ const operationCatalogBytes = routineAuthority ? readCriticalIntegrityFile(root, routineAuthority.operationCatalog) : readClosureFileByDigest(root, receipt, receipt.operationCatalogDigest);
1589
+ if (mode === "scheduled" && scheduledIntegrityRoot && scheduledKey) {
1590
+ rmSync(safeChild(scheduledIntegrityRoot, "quarantine.json"), { force: true });
1591
+ }
1592
+ if (routineDecision) {
1593
+ if (routineAuthority && routineFileCount === 0) {
1594
+ const sweep = verifyRoutineIntegrityFiles(root, routineAuthority);
1595
+ routineFileCount = sweep.fileCount;
1596
+ routineBytes = sweep.bytes;
1597
+ advisoryMtimeDriftCount = sweep.advisoryMtimeDriftCount;
1598
+ advisoryFileIdDriftCount = sweep.advisoryFileIdDriftCount;
1599
+ }
1600
+ options.onRoutineVerified?.(Object.freeze({
1601
+ elapsedMs: Number(process.hrtime.bigint() - routineStartedAt) / 1e6,
1602
+ authorityDecision: routineDecision,
1603
+ authoritativeFileCount: routineFileCount,
1604
+ authoritativeBytes: routineBytes,
1605
+ authoritativeBytesDerivedFromFileMetadata: true,
1606
+ advisoryMtimeDriftCount,
1607
+ advisoryFileIdDriftCount,
1608
+ fullVerificationPerformed: routineDecision !== "verified"
1609
+ }));
1610
+ }
1611
+ return Object.freeze({
1612
+ receipt,
1613
+ manifest,
1614
+ dcmBytes,
1615
+ operationCatalogBytes
1616
+ });
1617
+ } catch (error) {
1618
+ if (mode === "scheduled" && scheduledIntegrityRoot && scheduledKey) {
1619
+ persistScheduledIntegrityQuarantine(scheduledIntegrityRoot, scheduledKey, receipt, error, options.now ?? /* @__PURE__ */ new Date());
1620
+ }
1621
+ throw error;
1622
+ }
1623
+ }
1624
+ const port = parentPort;
1625
+ if (!port) throw new Error("commercial_integrity_worker_parent_port_missing");
1626
+ try {
1627
+ const data = workerData;
1628
+ const active = readVerifiedActiveCommercialArtifact({
1629
+ ...data.input,
1630
+ verificationMode: "scheduled",
1631
+ now: new Date(data.now)
1632
+ });
1633
+ if (!active) throw new Error("commercial_artifact_not_active");
1634
+ port.postMessage({ ok: true, receiptId: active.receipt.receiptId });
1635
+ } catch (error) {
1636
+ const candidate = error;
1637
+ port.postMessage({
1638
+ ok: false,
1639
+ stage: typeof candidate?.stage === "string" ? candidate.stage : "commercial-integrity-scheduler",
1640
+ decision: typeof candidate?.decision === "string" ? candidate.decision : "deny",
1641
+ reason: typeof candidate?.reason === "string" ? candidate.reason : typeof candidate?.message === "string" ? candidate.message : "scheduled_verification_failed"
1642
+ });
1643
+ }