@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,2077 @@
1
+ import { v as verifyEntitlementLease, b as buildAdmittedDomainSnapshot, R as RELEASE_MANIFEST_PURPOSE, a as verifyReleaseManifestEnvelope, c as canonicalCommercialJson, E as ENTITLEMENT_LEASE_PURPOSE, d as ENTITLEMENT_LEASE_ALGORITHM, C as CommercialArtifactError, e as assertCommercialRuntimeCompatible, s as sha256Commercial } from './admission-snapshot-C2wGfTWE.js';
2
+ import { randomBytes, randomUUID, createPrivateKey, sign, createPublicKey, verify, createHmac, timingSafeEqual, createHash } from 'node:crypto';
3
+ import { readFileSync, existsSync, rmSync, lstatSync, realpathSync, mkdirSync, statSync, writeFileSync, renameSync, chmodSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { gunzipSync } from 'node:zlib';
6
+ import { c as compareCanonicalText } from './canonical-text-order-DbXJJnFD.js';
7
+ import { homedir } from 'node:os';
8
+
9
+ const BASE64URL$1 = /^[A-Za-z0-9_-]+$/;
10
+ function fail$3(stage, reason) {
11
+ throw new CommercialArtifactError(stage, reason);
12
+ }
13
+ function isRecord$3(value) {
14
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15
+ }
16
+ function exactKeys$2(value, expected, stage) {
17
+ const actual = Object.keys(value).sort();
18
+ const sortedExpected = [...expected].sort();
19
+ if (actual.length !== sortedExpected.length || actual.some((key, index) => key !== sortedExpected[index]))
20
+ fail$3(stage, "offline_activation_schema_invalid");
21
+ }
22
+ function digest(value) {
23
+ return createHash("sha256").update(value, "utf8").digest("hex");
24
+ }
25
+ function publicJwk$1(value) {
26
+ if (!isRecord$3(value))
27
+ fail$3("offline-challenge-schema", "offline_activation_schema_invalid");
28
+ exactKeys$2(value, ["crv", "kty", "x"], "offline-challenge-schema");
29
+ if (value.kty !== "OKP" || value.crv !== "Ed25519" || typeof value.x !== "string" || !BASE64URL$1.test(value.x))
30
+ fail$3("offline-challenge-schema", "offline_activation_key_invalid");
31
+ try {
32
+ const key = createPublicKey({
33
+ key: { kty: "OKP", crv: "Ed25519", x: value.x },
34
+ format: "jwk"
35
+ });
36
+ if (key.asymmetricKeyType !== "ed25519") {
37
+ fail$3("offline-challenge-schema", "offline_activation_key_invalid");
38
+ }
39
+ } catch (error) {
40
+ if (error instanceof CommercialArtifactError)
41
+ throw error;
42
+ fail$3("offline-challenge-schema", "offline_activation_key_invalid");
43
+ }
44
+ return Object.freeze({ kty: "OKP", crv: "Ed25519", x: value.x });
45
+ }
46
+ function offlineActivationKeyThumbprint(jwk) {
47
+ const normalized = publicJwk$1(jwk);
48
+ return digest(JSON.stringify({ crv: normalized.crv, kty: normalized.kty, x: normalized.x }));
49
+ }
50
+ function installationPublicJwkFromPrivateKey(privateKeyPem) {
51
+ try {
52
+ const privateKey = createPrivateKey(privateKeyPem);
53
+ if (privateKey.asymmetricKeyType !== "ed25519") {
54
+ fail$3("offline-challenge-signature", "offline_activation_key_invalid");
55
+ }
56
+ return publicJwk$1(createPublicKey(privateKey).export({ format: "jwk" }));
57
+ } catch (error) {
58
+ if (error instanceof CommercialArtifactError)
59
+ throw error;
60
+ fail$3("offline-challenge-signature", "offline_activation_key_invalid");
61
+ }
62
+ }
63
+ class ManagedInstallationLayoutError extends Error {
64
+ code;
65
+ constructor(code) {
66
+ super(code);
67
+ this.name = "ManagedInstallationLayoutError";
68
+ this.code = code;
69
+ }
70
+ }
71
+ const verifiedLayouts = /* @__PURE__ */ new WeakSet();
72
+ function fail$2(code) {
73
+ throw new ManagedInstallationLayoutError(code);
74
+ }
75
+ function supportedPlatform(value) {
76
+ if (value === "win32" || value === "darwin" || value === "linux")
77
+ return value;
78
+ return fail$2("managed_layout_platform_unsupported");
79
+ }
80
+ function pathApi(platform) {
81
+ return platform === "win32" ? path.win32 : path.posix;
82
+ }
83
+ function absoluteBase(value, api, reason) {
84
+ if (typeof value !== "string" || !value || value.trim() !== value || !api.isAbsolute(value)) {
85
+ return fail$2(reason);
86
+ }
87
+ const normalized = api.resolve(api.normalize(value));
88
+ if (normalized === api.parse(normalized).root)
89
+ return fail$2(reason);
90
+ if (api === path.win32 && !/^[A-Za-z]:\\/.test(normalized))
91
+ return fail$2(reason);
92
+ return normalized;
93
+ }
94
+ function environmentBase(environment, key, fallback, api) {
95
+ return Object.prototype.hasOwnProperty.call(environment, key) ? absoluteBase(environment[key], api, `managed_layout_${key.toLowerCase()}_invalid`) : fallback;
96
+ }
97
+ function confined(root, candidate, api) {
98
+ const relative = api.relative(root, candidate);
99
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${api.sep}`) && !api.isAbsolute(relative);
100
+ }
101
+ function resolveManagedInstallationLayout(options = {}) {
102
+ const platform = supportedPlatform(options.platform ?? process.platform);
103
+ const api = pathApi(platform);
104
+ const environment = options.environment ?? process.env;
105
+ const home = absoluteBase(options.homeDirectory ?? homedir(), api, "managed_layout_home_invalid");
106
+ let dataRoot;
107
+ let stateBase;
108
+ let configBase;
109
+ let cacheBase;
110
+ let logsBase;
111
+ if (platform === "win32") {
112
+ const localAppData = environmentBase(environment, "LOCALAPPDATA", api.join(home, "AppData", "Local"), api);
113
+ dataRoot = api.join(localAppData, "AopsLab", "Aops");
114
+ stateBase = dataRoot;
115
+ configBase = dataRoot;
116
+ cacheBase = dataRoot;
117
+ logsBase = dataRoot;
118
+ } else if (platform === "darwin") {
119
+ dataRoot = api.join(home, "Library", "Application Support", "AopsLab", "Aops");
120
+ stateBase = dataRoot;
121
+ configBase = dataRoot;
122
+ cacheBase = api.join(home, "Library", "Caches", "AopsLab", "Aops");
123
+ logsBase = api.join(home, "Library", "Logs", "AopsLab", "Aops");
124
+ } else {
125
+ dataRoot = api.join(environmentBase(environment, "XDG_DATA_HOME", api.join(home, ".local", "share"), api), "aopslab", "aops");
126
+ stateBase = api.join(environmentBase(environment, "XDG_STATE_HOME", api.join(home, ".local", "state"), api), "aopslab", "aops");
127
+ configBase = api.join(environmentBase(environment, "XDG_CONFIG_HOME", api.join(home, ".config"), api), "aopslab", "aops");
128
+ cacheBase = api.join(environmentBase(environment, "XDG_CACHE_HOME", api.join(home, ".cache"), api), "aopslab", "aops");
129
+ logsBase = stateBase;
130
+ }
131
+ const instancesRoot = api.join(dataRoot, "instances");
132
+ const instanceRoot = api.join(instancesRoot, "default");
133
+ const stateRoot = platform === "win32" || platform === "darwin" ? api.join(instanceRoot, "state") : api.join(stateBase, "instances", "default");
134
+ const configRoot = platform === "win32" || platform === "darwin" ? api.join(instanceRoot, "config") : api.join(configBase, "instances", "default");
135
+ const cacheRoot = api.join(cacheBase, "instances", "default", "cache");
136
+ const logsRoot = platform === "win32" ? api.join(instanceRoot, "logs") : api.join(logsBase, "instances", "default", "logs");
137
+ const binding = Object.freeze({
138
+ schemaVersion: 1,
139
+ objectType: "aops-managed-installation-layout-binding-v1",
140
+ instanceId: "default",
141
+ platform,
142
+ source: "canonical-user",
143
+ dataRoot,
144
+ instancesRoot,
145
+ instanceRoot,
146
+ storeRoot: api.join(instanceRoot, "store"),
147
+ stagingRoot: api.join(instanceRoot, "staging"),
148
+ stateRoot,
149
+ configRoot,
150
+ cacheRoot,
151
+ logsRoot,
152
+ layoutManifestPath: api.join(stateRoot, "layout-manifest.json"),
153
+ currentReleasePointerPath: api.join(stateRoot, "current-release.json"),
154
+ installerLockPath: api.join(stateRoot, "installer.lock")
155
+ });
156
+ const managedChildren = [
157
+ binding.instancesRoot,
158
+ binding.instanceRoot,
159
+ binding.storeRoot,
160
+ binding.stagingRoot
161
+ ];
162
+ if (managedChildren.some((candidate) => !confined(binding.dataRoot, candidate, api))) {
163
+ return fail$2("managed_layout_data_escape");
164
+ }
165
+ for (const [root, candidates] of [
166
+ [stateRoot, [binding.layoutManifestPath, binding.currentReleasePointerPath, binding.installerLockPath]],
167
+ [configRoot, []],
168
+ [cacheRoot, []],
169
+ [logsRoot, []]
170
+ ]) {
171
+ if (!api.isAbsolute(root) || candidates.some((candidate) => !confined(root, candidate, api))) {
172
+ return fail$2("managed_layout_mutable_escape");
173
+ }
174
+ }
175
+ const layout = Object.freeze({
176
+ ...binding,
177
+ secretStorage: Object.freeze({
178
+ authority: "os-credential-store",
179
+ fileFallback: null
180
+ }),
181
+ runtime: Object.freeze({
182
+ immutableAuthority: "commercial-artifact-store",
183
+ activationAuthority: "store-active-receipt",
184
+ bundledNode: "verified-release-closure",
185
+ globalNodeNpmPnpm: "forbidden"
186
+ })
187
+ });
188
+ verifiedLayouts.add(layout);
189
+ return layout;
190
+ }
191
+ const STORE_FORMAT_VERSION = 1;
192
+ const SHA256 = /^sha256:[a-f0-9]{64}$/;
193
+ const IDENTITY = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,255}$/;
194
+ const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
195
+ const MAX_ARCHIVE_FILES = 1e5;
196
+ const MAX_FILE_BYTES = 128 * 1024 * 1024;
197
+ function fail$1(stage, reason, decision = "deny") {
198
+ throw new CommercialArtifactError(stage, reason, decision);
199
+ }
200
+ function isRecord$2(value) {
201
+ return value !== null && typeof value === "object" && !Array.isArray(value);
202
+ }
203
+ function parseJsonFile$1(filePath, stage, reason) {
204
+ try {
205
+ return JSON.parse(readFileSync(filePath, "utf8"));
206
+ } catch {
207
+ fail$1(stage, reason);
208
+ }
209
+ }
210
+ function assertIdentity(value, reason) {
211
+ if (!IDENTITY.test(value))
212
+ fail$1("store-identity", reason);
213
+ }
214
+ function assertAbsoluteSafeRoot(rootPath, create) {
215
+ if (!path.isAbsolute(rootPath))
216
+ fail$1("store-path", "store_root_not_absolute");
217
+ const resolved = path.resolve(rootPath);
218
+ if (path.parse(resolved).root === resolved)
219
+ fail$1("store-path", "store_root_too_broad");
220
+ if (!existsSync(resolved)) {
221
+ fail$1("store-path", "store_root_missing");
222
+ mkdirSync(resolved, { recursive: true, mode: 448 });
223
+ }
224
+ const stat = lstatSync(resolved);
225
+ if (stat.isSymbolicLink() || !stat.isDirectory())
226
+ fail$1("store-path", "store_root_unsafe");
227
+ const real = realpathSync.native(resolved);
228
+ if (path.relative(resolved, real) !== "")
229
+ fail$1("store-path", "store_root_reparse_refused");
230
+ return real;
231
+ }
232
+ function safeChild(root, ...segments) {
233
+ for (const segment of segments) {
234
+ if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
235
+ fail$1("store-path", "unsafe_managed_segment");
236
+ }
237
+ }
238
+ const candidate = path.join(root, ...segments);
239
+ const relative = path.relative(root, candidate);
240
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative))
241
+ fail$1("store-path", "managed_path_escape");
242
+ return candidate;
243
+ }
244
+ function ensureManagedDirectory(root, ...segments) {
245
+ let cursor = root;
246
+ for (const segment of segments) {
247
+ cursor = safeChild(cursor, segment);
248
+ if (!existsSync(cursor))
249
+ mkdirSync(cursor, { mode: 448 });
250
+ const stat = lstatSync(cursor);
251
+ if (stat.isSymbolicLink() || !stat.isDirectory())
252
+ fail$1("store-path", "managed_directory_unsafe");
253
+ if (path.relative(cursor, realpathSync.native(cursor)) !== "")
254
+ fail$1("store-path", "managed_directory_reparse_refused");
255
+ }
256
+ return cursor;
257
+ }
258
+ function assertRegularFile(filePath, stage, reason) {
259
+ const stat = lstatSync(filePath);
260
+ if (stat.isSymbolicLink() || !stat.isFile())
261
+ fail$1(stage, reason);
262
+ return realpathSync.native(filePath);
263
+ }
264
+ function digestBytes(bytes) {
265
+ return sha256Commercial(bytes);
266
+ }
267
+ function integrityBytes(bytes) {
268
+ return `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
269
+ }
270
+ function atomicWrite(filePath, bytes, mode = 384) {
271
+ const parent = path.dirname(filePath);
272
+ const tempPath = path.join(parent, `.${path.basename(filePath)}.${randomUUID()}.tmp`);
273
+ writeFileSync(tempPath, bytes, { mode, flag: "wx" });
274
+ renameSync(tempPath, filePath);
275
+ try {
276
+ chmodSync(filePath, mode);
277
+ } catch {
278
+ }
279
+ }
280
+ function trimTarText(bytes) {
281
+ const nul = bytes.indexOf(0);
282
+ return bytes.subarray(0, nul === -1 ? bytes.length : nul).toString("utf8").trim();
283
+ }
284
+ function tarNumber(bytes, reason) {
285
+ if ((bytes[0] & 128) !== 0)
286
+ fail$1("archive-safety", reason);
287
+ const text2 = trimTarText(bytes).replace(/\0/g, "").trim();
288
+ if (!text2)
289
+ return 0;
290
+ if (!/^[0-7]+$/.test(text2))
291
+ fail$1("archive-safety", reason);
292
+ const value = Number.parseInt(text2, 8);
293
+ if (!Number.isSafeInteger(value) || value < 0)
294
+ fail$1("archive-safety", reason);
295
+ return value;
296
+ }
297
+ function parsePax(bytes) {
298
+ const fields = {};
299
+ let offset = 0;
300
+ while (offset < bytes.length) {
301
+ const space = bytes.indexOf(32, offset);
302
+ if (space < 0)
303
+ fail$1("archive-safety", "pax_record_invalid");
304
+ const length = Number.parseInt(bytes.subarray(offset, space).toString("ascii"), 10);
305
+ if (!Number.isSafeInteger(length) || length <= 0 || offset + length > bytes.length) {
306
+ fail$1("archive-safety", "pax_record_invalid");
307
+ }
308
+ const record = bytes.subarray(space + 1, offset + length - 1).toString("utf8");
309
+ const equals = record.indexOf("=");
310
+ if (equals <= 0)
311
+ fail$1("archive-safety", "pax_record_invalid");
312
+ const key = record.slice(0, equals);
313
+ if (Object.hasOwn(fields, key))
314
+ fail$1("archive-safety", "pax_duplicate_field");
315
+ fields[key] = record.slice(equals + 1);
316
+ offset += length;
317
+ }
318
+ return fields;
319
+ }
320
+ function safeArchivePath(value) {
321
+ const normalized = value.replaceAll("\\", "/");
322
+ if (!normalized.startsWith("package/") || normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || normalized.length > 4096)
323
+ fail$1("archive-safety", "archive_path_invalid");
324
+ const relative = normalized.slice("package/".length);
325
+ if (!relative || relative.endsWith("/") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
326
+ fail$1("archive-safety", "archive_path_invalid");
327
+ }
328
+ return relative.normalize("NFC");
329
+ }
330
+ function inspectNpmTarball(bytes) {
331
+ if (bytes.byteLength <= 0 || bytes.byteLength > MAX_ARCHIVE_BYTES)
332
+ fail$1("archive-safety", "archive_size_invalid");
333
+ let tar;
334
+ try {
335
+ tar = gunzipSync(bytes, { maxOutputLength: MAX_ARCHIVE_BYTES });
336
+ } catch {
337
+ fail$1("archive-safety", "archive_gzip_invalid");
338
+ }
339
+ const rows = [];
340
+ const contents = /* @__PURE__ */ new Map();
341
+ let offset = 0;
342
+ let pax = {};
343
+ let longName = null;
344
+ while (offset + 512 <= tar.length) {
345
+ const header = tar.subarray(offset, offset + 512);
346
+ if (header.every((byte) => byte === 0))
347
+ break;
348
+ const storedChecksum = tarNumber(header.subarray(148, 156), "archive_checksum_invalid");
349
+ let checksum = 0;
350
+ for (let index = 0; index < 512; index += 1) {
351
+ checksum += index >= 148 && index < 156 ? 32 : header[index];
352
+ }
353
+ if (storedChecksum !== checksum)
354
+ fail$1("archive-safety", "archive_checksum_mismatch");
355
+ const baseName = trimTarText(header.subarray(0, 100));
356
+ const prefix = trimTarText(header.subarray(345, 500));
357
+ const headerName = prefix ? `${prefix}/${baseName}` : baseName;
358
+ const mode = tarNumber(header.subarray(100, 108), "archive_mode_invalid") & 511;
359
+ const headerSize = tarNumber(header.subarray(124, 136), "archive_entry_size_invalid");
360
+ if (headerSize > MAX_FILE_BYTES)
361
+ fail$1("archive-safety", "archive_entry_too_large");
362
+ const type = String.fromCharCode(header[156] || 0);
363
+ const contentOffset = offset + 512;
364
+ const contentEnd = contentOffset + headerSize;
365
+ if (contentEnd > tar.length)
366
+ fail$1("archive-safety", "archive_truncated");
367
+ const content = tar.subarray(contentOffset, contentEnd);
368
+ offset = contentOffset + Math.ceil(headerSize / 512) * 512;
369
+ if (type === "x" || type === "g") {
370
+ const next = parsePax(content);
371
+ const unsupported = Object.keys(next).filter((key) => !["path", "size", "mtime"].includes(key));
372
+ if (unsupported.some((key) => key === "linkpath"))
373
+ fail$1("archive-safety", "archive_link_refused");
374
+ pax = type === "g" ? { ...pax, ...next } : next;
375
+ continue;
376
+ }
377
+ if (type === "L") {
378
+ longName = trimTarText(content);
379
+ continue;
380
+ }
381
+ if (type === "5") {
382
+ pax = {};
383
+ longName = null;
384
+ continue;
385
+ }
386
+ if (type !== "\0" && type !== "0")
387
+ fail$1("archive-safety", "archive_special_entry_refused");
388
+ const entryName = pax.path ?? longName ?? headerName;
389
+ const declaredSize = pax.size === void 0 ? headerSize : Number.parseInt(pax.size, 10);
390
+ if (!Number.isSafeInteger(declaredSize) || declaredSize !== headerSize)
391
+ fail$1("archive-safety", "archive_entry_size_mismatch");
392
+ const relative = safeArchivePath(entryName);
393
+ if (contents.has(relative))
394
+ fail$1("archive-safety", "archive_duplicate_path");
395
+ const copy = Buffer.from(content);
396
+ contents.set(relative, copy);
397
+ rows.push(Object.freeze({
398
+ path: relative,
399
+ size: copy.byteLength,
400
+ mode,
401
+ sha256: digestBytes(copy)
402
+ }));
403
+ if (rows.length > MAX_ARCHIVE_FILES)
404
+ fail$1("archive-safety", "archive_file_limit_exceeded");
405
+ pax = {};
406
+ longName = null;
407
+ }
408
+ rows.sort((left, right) => compareCanonicalText(left.path, right.path));
409
+ const packageBytes = contents.get("package.json");
410
+ if (!packageBytes)
411
+ fail$1("archive-preflight", "package_json_missing");
412
+ let packageJson;
413
+ try {
414
+ packageJson = JSON.parse(packageBytes.toString("utf8"));
415
+ } catch {
416
+ fail$1("archive-preflight", "package_json_invalid");
417
+ }
418
+ if (!isRecord$2(packageJson) || typeof packageJson.name !== "string" || typeof packageJson.version !== "string") {
419
+ fail$1("archive-preflight", "package_identity_invalid");
420
+ }
421
+ const optionalPeerNames = /* @__PURE__ */ new Set();
422
+ if (packageJson.peerDependenciesMeta !== void 0) {
423
+ if (!isRecord$2(packageJson.peerDependenciesMeta)) {
424
+ fail$1("archive-preflight", "package_dependencies_invalid");
425
+ }
426
+ for (const [dependencyName, metadata] of Object.entries(packageJson.peerDependenciesMeta)) {
427
+ if (!isRecord$2(metadata) || typeof metadata.optional !== "boolean") {
428
+ fail$1("archive-preflight", "package_dependencies_invalid");
429
+ }
430
+ if (metadata.optional)
431
+ optionalPeerNames.add(dependencyName);
432
+ }
433
+ }
434
+ const runtimeDependencyNames = /* @__PURE__ */ new Set();
435
+ for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
436
+ const dependencies = packageJson[field];
437
+ if (dependencies === void 0)
438
+ continue;
439
+ if (!isRecord$2(dependencies))
440
+ fail$1("archive-preflight", "package_dependencies_invalid");
441
+ for (const [dependencyName, dependencyRange] of Object.entries(dependencies)) {
442
+ if (typeof dependencyRange !== "string" || !dependencyRange.trim()) {
443
+ fail$1("archive-preflight", "package_dependencies_invalid");
444
+ }
445
+ if (field !== "peerDependencies" || !optionalPeerNames.has(dependencyName)) {
446
+ runtimeDependencyNames.add(dependencyName);
447
+ }
448
+ }
449
+ }
450
+ return Object.freeze({
451
+ files: Object.freeze(rows),
452
+ contents,
453
+ filesDigest: sha256Commercial(canonicalCommercialJson(rows.map(({ path: filePath, size, sha256: sha2562 }) => ({
454
+ path: filePath,
455
+ size,
456
+ sha256: sha2562
457
+ })))),
458
+ packageName: packageJson.name,
459
+ version: packageJson.version,
460
+ runtimeDependencies: Object.freeze([...runtimeDependencyNames].sort(compareCanonicalText))
461
+ });
462
+ }
463
+ function readOnlyObjectPath(root, digest2) {
464
+ if (!SHA256.test(digest2))
465
+ fail$1("store-path", "object_digest_invalid");
466
+ return safeChild(root, "objects", "sha256", digest2.slice("sha256:".length));
467
+ }
468
+ function readOnlyTreePath(root, digest2) {
469
+ if (!SHA256.test(digest2))
470
+ fail$1("store-path", "tree_digest_invalid");
471
+ return safeChild(root, "trees", "sha256", digest2.slice("sha256:".length));
472
+ }
473
+ function verifyTree(root, archive) {
474
+ for (const row of archive.files) {
475
+ const segments = row.path.split("/");
476
+ let cursor = root;
477
+ for (const segment of segments) {
478
+ cursor = safeChild(cursor, segment);
479
+ const stat2 = lstatSync(cursor);
480
+ if (stat2.isSymbolicLink())
481
+ fail$1("cas-readback", "cas_tree_link_refused", "quarantine");
482
+ }
483
+ const stat = statSync(cursor);
484
+ if (!stat.isFile() || stat.size !== row.size || digestBytes(readFileSync(cursor)) !== row.sha256) {
485
+ fail$1("cas-readback", "cas_tree_digest_mismatch", "quarantine");
486
+ }
487
+ }
488
+ }
489
+ function resolveEntrypoint(entrypoint, artifacts, closureDigest) {
490
+ const separator = entrypoint.indexOf(":");
491
+ const packageName = entrypoint.slice(0, separator);
492
+ const relative = entrypoint.slice(separator + 1);
493
+ const artifact = artifacts.get(packageName);
494
+ if (!artifact)
495
+ fail$1("artifact-preflight", "entrypoint_package_missing");
496
+ if (!artifact.files.some((row) => row.path === relative))
497
+ fail$1("artifact-preflight", "entrypoint_file_missing");
498
+ return `runtimes/sha256/${closureDigest.slice("sha256:".length)}/node_modules/${packageName}/${relative}`;
499
+ }
500
+ function resolveLaunchClosure(manifest, artifacts) {
501
+ const roleRows = manifest.closure.filter((entry) => entry.launchRole !== null);
502
+ const runtime = roleRows.find((entry) => entry.launchRole === "runtime-node");
503
+ if (!runtime)
504
+ fail$1("artifact-preflight", "runtime_role_missing");
505
+ for (const entry of roleRows) {
506
+ const artifact = artifacts.get(entry.packageName);
507
+ if (!artifact)
508
+ fail$1("artifact-preflight", "launch_role_package_missing");
509
+ const file = artifact.files.find((candidate) => candidate.path === entry.launchEntrypoint);
510
+ if (!file)
511
+ fail$1("artifact-preflight", "launch_role_entrypoint_missing");
512
+ if (entry.launchRole !== "runtime-node") {
513
+ if (entry.runtimeRange === null)
514
+ fail$1("artifact-preflight", "launch_role_runtime_range_missing");
515
+ assertCommercialRuntimeCompatible(runtime.version, entry.runtimeRange);
516
+ }
517
+ }
518
+ const entries = roleRows.map((entry) => {
519
+ const artifact = artifacts.get(entry.packageName);
520
+ if (!artifact)
521
+ fail$1("artifact-preflight", "launch_role_package_missing");
522
+ const file = artifact.files.find((candidate) => candidate.path === entry.launchEntrypoint);
523
+ if (!file || entry.launchRole === null || entry.launchEntrypoint === null) {
524
+ fail$1("artifact-preflight", "launch_role_entrypoint_missing");
525
+ }
526
+ return Object.freeze({
527
+ role: entry.launchRole,
528
+ packageName: artifact.packageName,
529
+ packageVersion: artifact.version,
530
+ artifactDigest: artifact.digest,
531
+ entrypoint: entry.launchEntrypoint,
532
+ entrypointDigest: file.sha256,
533
+ runtimeRange: entry.runtimeRange,
534
+ resolvedPath: resolveEntrypoint(`${entry.packageName}:${entry.launchEntrypoint}`, artifacts, manifest.closureDigest)
535
+ });
536
+ }).sort((left, right) => compareCanonicalText(left.role, right.role));
537
+ return Object.freeze({
538
+ runtimeVersion: runtime.version,
539
+ entries: Object.freeze(entries)
540
+ });
541
+ }
542
+ function readOnlyRuntimeRootPath(root, closureDigest) {
543
+ if (!SHA256.test(closureDigest))
544
+ fail$1("store-path", "closure_digest_invalid");
545
+ return safeChild(root, "runtimes", "sha256", closureDigest.slice("sha256:".length));
546
+ }
547
+ function packageRuntimeRoot(nodeModulesRoot, packageName) {
548
+ const segments = packageName.split("/");
549
+ if (segments.length === 1)
550
+ return safeChild(nodeModulesRoot, segments[0]);
551
+ if (segments.length === 2 && segments[0].startsWith("@")) {
552
+ const scope = ensureManagedDirectory(nodeModulesRoot, segments[0]);
553
+ return safeChild(scope, segments[1]);
554
+ }
555
+ fail$1("artifact-preflight", "runtime_package_name_invalid");
556
+ }
557
+ function verifyRuntimeClosure(runtimeRoot, artifacts) {
558
+ const nodeModulesRoot = safeChild(runtimeRoot, "node_modules");
559
+ const nodeModulesStat = lstatSync(nodeModulesRoot);
560
+ if (nodeModulesStat.isSymbolicLink() || !nodeModulesStat.isDirectory()) {
561
+ fail$1("runtime-readback", "runtime_closure_unsafe", "quarantine");
562
+ }
563
+ for (const artifact of artifacts.values()) {
564
+ const packageRoot = packageRuntimeRoot(nodeModulesRoot, artifact.packageName);
565
+ for (const row of artifact.files) {
566
+ let cursor = packageRoot;
567
+ for (const segment of row.path.split("/")) {
568
+ cursor = safeChild(cursor, segment);
569
+ const stat2 = lstatSync(cursor);
570
+ if (stat2.isSymbolicLink())
571
+ fail$1("runtime-readback", "runtime_link_refused", "quarantine");
572
+ }
573
+ const stat = statSync(cursor);
574
+ if (!stat.isFile() || stat.size !== row.size || digestBytes(readFileSync(cursor)) !== row.sha256) {
575
+ fail$1("runtime-readback", "runtime_file_digest_mismatch", "quarantine");
576
+ }
577
+ }
578
+ }
579
+ }
580
+ function verifyRuntimeDependencyClosure(artifacts) {
581
+ for (const artifact of artifacts.values()) {
582
+ for (const dependencyName of artifact.runtimeDependencies) {
583
+ if (!artifacts.has(dependencyName)) {
584
+ fail$1("artifact-preflight", "runtime_dependency_outside_closure");
585
+ }
586
+ }
587
+ }
588
+ }
589
+ function statePath(root, name) {
590
+ return safeChild(ensureManagedDirectory(root, "state"), name);
591
+ }
592
+ function readOnlyStatePath(root, name) {
593
+ return safeChild(root, "state", name);
594
+ }
595
+ function assertStoreIdentity(root, expected, create = false) {
596
+ const filePath = create ? statePath(root, "store-identity.json") : readOnlyStatePath(root, "store-identity.json");
597
+ if (!existsSync(filePath)) {
598
+ if (!expected || !create)
599
+ fail$1("store-identity", "store_identity_missing", "quarantine");
600
+ const identity = Object.freeze({
601
+ schemaVersion: 1,
602
+ objectType: "aops-commercial-artifact-store-identity-v1",
603
+ storeFormatVersion: STORE_FORMAT_VERSION,
604
+ installationId: expected.installationId,
605
+ hostInstanceId: expected.hostInstanceId
606
+ });
607
+ atomicWrite(filePath, `${canonicalCommercialJson(identity)}
608
+ `);
609
+ }
610
+ const value = parseJsonFile$1(filePath, "store-identity", "store_identity_json_invalid");
611
+ if (!isRecord$2(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")
612
+ fail$1("store-identity", "store_identity_schema_invalid", "quarantine");
613
+ if (expected && (value.installationId !== expected.installationId || value.hostInstanceId !== expected.hostInstanceId))
614
+ fail$1("store-identity", "store_identity_mismatch", "quarantine");
615
+ return value;
616
+ }
617
+ function readOnlyReceiptPath(root, receiptId) {
618
+ assertIdentity(receiptId, "receipt_id_invalid");
619
+ return safeChild(root, "receipts", `${receiptId}.json`);
620
+ }
621
+ function readOnlyManifestPath(root, digest2) {
622
+ if (!SHA256.test(digest2))
623
+ fail$1("store-path", "manifest_digest_invalid");
624
+ return safeChild(root, "manifests", `${digest2.slice("sha256:".length)}.json`);
625
+ }
626
+ function keyBytes(root, create) {
627
+ const keyPath = readOnlyStatePath(root, "receipt-hmac.key");
628
+ if (!existsSync(keyPath)) {
629
+ fail$1("receipt-integrity", "receipt_key_missing", "quarantine");
630
+ atomicWrite(keyPath, randomBytes(32), 384);
631
+ }
632
+ const key = readFileSync(assertRegularFile(keyPath, "receipt-integrity", "receipt_key_unsafe"));
633
+ if (key.byteLength !== 32)
634
+ fail$1("receipt-integrity", "receipt_key_invalid", "quarantine");
635
+ return key;
636
+ }
637
+ function readReceipt(root, receiptId) {
638
+ const value = parseJsonFile$1(readOnlyReceiptPath(root, receiptId), "receipt-readback", "receipt_json_invalid");
639
+ if (!isRecord$2(value) || !isRecord$2(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.receiptDigestOrMac !== "string") {
640
+ fail$1("receipt-readback", "receipt_schema_invalid", "quarantine");
641
+ }
642
+ if (value.schemaVersion !== 2 || value.objectType !== "aops-installation-receipt-v2") {
643
+ fail$1("receipt-readback", "receipt_schema_unsupported", "quarantine");
644
+ }
645
+ const { localIntegrity: _, ...unsigned } = value;
646
+ const expected = createHmac("sha256", keyBytes(root)).update(canonicalCommercialJson(unsigned)).digest();
647
+ const actualText = value.localIntegrity.receiptDigestOrMac;
648
+ if (!/^hmac-sha256:[a-f0-9]{64}$/.test(actualText))
649
+ fail$1("receipt-readback", "receipt_mac_invalid", "quarantine");
650
+ const actual = Buffer.from(actualText.slice("hmac-sha256:".length), "hex");
651
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
652
+ fail$1("receipt-readback", "receipt_mac_mismatch", "quarantine");
653
+ }
654
+ return value;
655
+ }
656
+ function readPointer(root, name) {
657
+ const filePath = readOnlyStatePath(root, name);
658
+ if (!existsSync(filePath))
659
+ return null;
660
+ const value = parseJsonFile$1(filePath, "activation-readback", "pointer_json_invalid");
661
+ if (!isRecord$2(value) || value.schemaVersion !== 1 || typeof value.receiptId !== "string" || typeof value.receiptMac !== "string" || !Number.isSafeInteger(value.generation))
662
+ fail$1("activation-readback", "pointer_schema_invalid", "quarantine");
663
+ const receipt = readReceipt(root, value.receiptId);
664
+ if (receipt.localIntegrity.receiptDigestOrMac !== value.receiptMac || receipt.activation.generation !== value.generation)
665
+ fail$1("activation-readback", "pointer_receipt_mismatch", "quarantine");
666
+ return value;
667
+ }
668
+ function highWaterPath(root, packageName) {
669
+ const identity = createHash("sha256").update(packageName, "utf8").digest("hex");
670
+ return safeChild(ensureManagedDirectory(root, "high-water"), `${identity}.json`);
671
+ }
672
+ function highWaterMacInput(value) {
673
+ return `aops-product-release-high-water-v1\0${canonicalCommercialJson(value)}`;
674
+ }
675
+ function verifyHighWaterState(root, packageName, value) {
676
+ if (!isRecord$2(value) || canonicalCommercialJson(Object.keys(value).sort()) !== canonicalCommercialJson([
677
+ "issuedAt",
678
+ "localIntegrity",
679
+ "manifestDigest",
680
+ "objectType",
681
+ "packageName",
682
+ "schemaVersion",
683
+ "versionOrdinal"
684
+ ]) || 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$2(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))
685
+ fail$1("release-high-water", "high_water_schema_invalid", "quarantine");
686
+ const { localIntegrity: _, ...unsigned } = value;
687
+ const expected = createHmac("sha256", keyBytes(root)).update(highWaterMacInput(unsigned)).digest();
688
+ const actual = Buffer.from(value.localIntegrity.mac.slice("hmac-sha256:".length), "hex");
689
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
690
+ fail$1("release-high-water", "high_water_mac_mismatch", "quarantine");
691
+ }
692
+ return value;
693
+ }
694
+ function readHighWater(root, packageName) {
695
+ const filePath = highWaterPath(root, packageName);
696
+ if (!existsSync(filePath))
697
+ return null;
698
+ const value = parseJsonFile$1(filePath, "release-high-water", "high_water_json_invalid");
699
+ const verified = verifyHighWaterState(root, packageName, value);
700
+ return Object.freeze({
701
+ issuedAt: verified.issuedAt,
702
+ versionOrdinal: verified.versionOrdinal,
703
+ manifestDigest: verified.manifestDigest
704
+ });
705
+ }
706
+ function assertRetainedHighWater(root, receipt) {
707
+ const retained = readHighWater(root, receipt.packageName);
708
+ if (!retained)
709
+ fail$1("release-high-water", "high_water_missing", "quarantine");
710
+ if (retained.versionOrdinal < receipt.releaseHighWater.versionOrdinal) {
711
+ fail$1("release-high-water", "high_water_receipt_mismatch", "quarantine");
712
+ }
713
+ return retained;
714
+ }
715
+ function verifyStoredClosure(root, receipt, onVerified) {
716
+ const startedAt = process.hrtime.bigint();
717
+ const artifacts = /* @__PURE__ */ new Map();
718
+ let casBytesRead = 0;
719
+ let npmArtifactCount = 0;
720
+ let archiveFileCount = 0;
721
+ let archiveFileBytes = 0;
722
+ for (const object of receipt.casObjects) {
723
+ const filePath = readOnlyObjectPath(root, object.digest);
724
+ const file = assertRegularFile(filePath, "cas-readback", "cas_object_missing");
725
+ const bytes = readFileSync(file);
726
+ casBytesRead += bytes.byteLength;
727
+ if (bytes.byteLength !== object.size || digestBytes(bytes) !== object.digest) {
728
+ fail$1("cas-readback", "cas_object_digest_mismatch", "quarantine");
729
+ }
730
+ if (object.role.startsWith("npm:")) {
731
+ npmArtifactCount += 1;
732
+ const packageName = object.role.slice("npm:".length);
733
+ const archive = inspectNpmTarball(bytes);
734
+ archiveFileCount += archive.files.length;
735
+ archiveFileBytes += archive.files.reduce((total, row) => total + row.size, 0);
736
+ if (archive.packageName !== packageName)
737
+ fail$1("cas-readback", "cas_package_identity_mismatch", "quarantine");
738
+ const tree = readOnlyTreePath(root, object.digest);
739
+ if (!existsSync(tree))
740
+ fail$1("cas-readback", "cas_tree_missing", "quarantine");
741
+ const treeStat = lstatSync(tree);
742
+ if (treeStat.isSymbolicLink() || !treeStat.isDirectory()) {
743
+ fail$1("cas-readback", "cas_tree_unsafe", "quarantine");
744
+ }
745
+ verifyTree(tree, archive);
746
+ artifacts.set(packageName, {
747
+ packageName,
748
+ version: archive.version,
749
+ digest: object.digest,
750
+ integrity: integrityBytes(bytes),
751
+ filesDigest: archive.filesDigest,
752
+ objectPath: file,
753
+ treePath: tree,
754
+ files: archive.files,
755
+ runtimeDependencies: archive.runtimeDependencies
756
+ });
757
+ }
758
+ }
759
+ const runtimeRoot = readOnlyRuntimeRootPath(root, receipt.closureDigest);
760
+ if (!existsSync(runtimeRoot))
761
+ fail$1("runtime-readback", "runtime_closure_missing", "quarantine");
762
+ verifyRuntimeClosure(runtimeRoot, artifacts);
763
+ verifyRuntimeDependencyClosure(artifacts);
764
+ onVerified?.(Object.freeze({
765
+ elapsedMs: Number(process.hrtime.bigint() - startedAt) / 1e6,
766
+ casObjectCount: receipt.casObjects.length,
767
+ npmArtifactCount,
768
+ tarballDecompressionCount: npmArtifactCount,
769
+ archiveFileCount,
770
+ casBytesRead,
771
+ treeBytesRead: archiveFileBytes,
772
+ runtimeBytesRead: archiveFileBytes,
773
+ materializedBytesDerivedFromArchiveMetadata: true,
774
+ materializedFilePasses: 2,
775
+ totalFileReads: receipt.casObjects.length + archiveFileCount * 2,
776
+ totalBytesRead: casBytesRead + archiveFileBytes * 2
777
+ }));
778
+ return artifacts;
779
+ }
780
+ const COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE = "aops-commercial-integrity-authority-v1";
781
+ const COMMERCIAL_INTEGRITY_PENDING_PURPOSE = "aops-commercial-integrity-pending-v2";
782
+ function commercialIntegrityRoot(stateRoot, create) {
783
+ if (!path.isAbsolute(stateRoot))
784
+ fail$1("commercial-integrity", "integrity_state_root_not_absolute");
785
+ const resolved = path.resolve(stateRoot);
786
+ if (!existsSync(resolved)) {
787
+ return null;
788
+ }
789
+ const safeStateRoot = assertAbsoluteSafeRoot(resolved);
790
+ {
791
+ const candidate = path.join(safeStateRoot, "commercial-integrity");
792
+ if (!existsSync(candidate))
793
+ return null;
794
+ }
795
+ return ensureManagedDirectory(safeStateRoot, "commercial-integrity");
796
+ }
797
+ function commercialIntegrityKey(root, create) {
798
+ const keyPath = safeChild(root, "authority-hmac.key");
799
+ if (!existsSync(keyPath)) {
800
+ return null;
801
+ }
802
+ const key = readFileSync(assertRegularFile(keyPath, "commercial-integrity", "integrity_key_unsafe"));
803
+ if (key.byteLength !== 32)
804
+ return null;
805
+ return key;
806
+ }
807
+ function integrityMac(key, purpose, value) {
808
+ return createHmac("sha256", key).update(`${purpose}\0${canonicalCommercialJson(value)}`).digest("hex");
809
+ }
810
+ function authorityUnsigned(value) {
811
+ const { localIntegrity: _, ...unsigned } = value;
812
+ return unsigned;
813
+ }
814
+ function pendingUnsigned(value) {
815
+ const { localIntegrity: _, ...unsigned } = value;
816
+ return unsigned;
817
+ }
818
+ function signCommercialIntegrityAuthority(key, value) {
819
+ return Object.freeze({
820
+ ...value,
821
+ localIntegrity: Object.freeze({
822
+ scheme: "hmac-sha256-v1",
823
+ mac: integrityMac(key, COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE, value)
824
+ })
825
+ });
826
+ }
827
+ function parseOptionalJson(filePath) {
828
+ if (!existsSync(filePath))
829
+ return null;
830
+ try {
831
+ const file = assertRegularFile(filePath, "commercial-integrity", "integrity_record_unsafe");
832
+ return JSON.parse(readFileSync(file, "utf8"));
833
+ } catch (error) {
834
+ if (error instanceof CommercialArtifactError)
835
+ throw error;
836
+ return null;
837
+ }
838
+ }
839
+ function validIntegrityFile(value) {
840
+ return isRecord$2(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";
841
+ }
842
+ function validCriticalFile(value) {
843
+ return isRecord$2(value) && typeof value.relativePath === "string" && SHA256.test(String(value.digest));
844
+ }
845
+ function authorityShape(value) {
846
+ if (!isRecord$2(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" || ![
847
+ "install",
848
+ "update",
849
+ "rollback",
850
+ "scheduled",
851
+ "routine-size-drift-full-verify",
852
+ "authority-reestablished"
853
+ ].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$2(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.mac !== "string")
854
+ return false;
855
+ let previous = "";
856
+ for (const file of value.files) {
857
+ if (file.relativePath <= previous)
858
+ return false;
859
+ previous = file.relativePath;
860
+ }
861
+ return true;
862
+ }
863
+ function pendingShape(value) {
864
+ const hasNoLineage = isRecord$2(value) && value.planId === null && value.previousOperationReceiptId === null && value.previousPlanId === null;
865
+ const hasExactLineage = isRecord$2(value) && SHA256.test(String(value.planId)) && typeof value.previousOperationReceiptId === "string" && value.previousOperationReceiptId.length > 0 && SHA256.test(String(value.previousPlanId));
866
+ return isRecord$2(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$2(value.target) && authorityShape({
867
+ ...value.target,
868
+ localIntegrity: { scheme: "hmac-sha256-v1", mac: "0".repeat(64) }
869
+ }) && isRecord$2(value.localIntegrity) && value.localIntegrity.scheme === "hmac-sha256-v1" && typeof value.localIntegrity.mac === "string";
870
+ }
871
+ function verifyMacText(actualText, expectedText) {
872
+ if (!/^[a-f0-9]{64}$/.test(actualText) || !/^[a-f0-9]{64}$/.test(expectedText))
873
+ return false;
874
+ const actual = Buffer.from(actualText, "hex");
875
+ const expected = Buffer.from(expectedText, "hex");
876
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
877
+ }
878
+ function readCommercialIntegrityAuthority(root, key) {
879
+ const value = parseOptionalJson(safeChild(root, "authority.json"));
880
+ if (value === null || !authorityShape(value))
881
+ return null;
882
+ const expected = integrityMac(key, COMMERCIAL_INTEGRITY_AUTHORITY_PURPOSE, authorityUnsigned(value));
883
+ if (!verifyMacText(value.localIntegrity.mac, expected)) {
884
+ fail$1("commercial-integrity", "integrity_authority_mac_mismatch", "quarantine");
885
+ }
886
+ return value;
887
+ }
888
+ function readCommercialIntegrityPending(root, key) {
889
+ const value = parseOptionalJson(safeChild(root, "pending.json"));
890
+ if (value === null)
891
+ return null;
892
+ if (!pendingShape(value))
893
+ return "invalid";
894
+ const expected = integrityMac(key, COMMERCIAL_INTEGRITY_PENDING_PURPOSE, pendingUnsigned(value));
895
+ return verifyMacText(value.localIntegrity.mac, expected) ? value : "invalid";
896
+ }
897
+ function readCommercialIntegrityQuarantine(root, key) {
898
+ const value = parseOptionalJson(safeChild(root, "quarantine.json"));
899
+ if (value === null)
900
+ return null;
901
+ if (!isRecord$2(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$2(value.localIntegrity) || value.localIntegrity.scheme !== "hmac-sha256-v1" || typeof value.localIntegrity.mac !== "string")
902
+ fail$1("commercial-integrity", "integrity_quarantine_record_invalid", "quarantine");
903
+ const { localIntegrity: _, ...unsigned } = value;
904
+ const expected = integrityMac(key, "aops-commercial-integrity-quarantine-v1", unsigned);
905
+ if (!verifyMacText(value.localIntegrity.mac, expected)) {
906
+ fail$1("commercial-integrity", "integrity_quarantine_mac_mismatch", "quarantine");
907
+ }
908
+ return value;
909
+ }
910
+ function readCommercialIntegrityVerificationSchedule(integrityStateRoot, now = /* @__PURE__ */ new Date()) {
911
+ const integrityRoot = commercialIntegrityRoot(integrityStateRoot);
912
+ const key = integrityRoot ? commercialIntegrityKey(integrityRoot) : null;
913
+ if (!integrityRoot || !key) {
914
+ return Object.freeze({
915
+ state: "authority-unavailable",
916
+ verifiedAt: null,
917
+ dueAt: null,
918
+ minimumIntervalHours: 24
919
+ });
920
+ }
921
+ if (readCommercialIntegrityQuarantine(integrityRoot, key)) {
922
+ return Object.freeze({
923
+ state: "quarantined",
924
+ verifiedAt: null,
925
+ dueAt: null,
926
+ minimumIntervalHours: 24
927
+ });
928
+ }
929
+ const authority = readCommercialIntegrityAuthority(integrityRoot, key);
930
+ if (!authority) {
931
+ return Object.freeze({
932
+ state: "authority-unavailable",
933
+ verifiedAt: null,
934
+ dueAt: null,
935
+ minimumIntervalHours: 24
936
+ });
937
+ }
938
+ const verifiedAtMs = Date.parse(authority.verifiedAt);
939
+ if (!Number.isFinite(verifiedAtMs)) {
940
+ return Object.freeze({
941
+ state: "authority-unavailable",
942
+ verifiedAt: null,
943
+ dueAt: null,
944
+ minimumIntervalHours: 24
945
+ });
946
+ }
947
+ const dueAtMs = verifiedAtMs + 24 * 60 * 60 * 1e3;
948
+ if (verifiedAtMs > now.getTime()) {
949
+ return Object.freeze({
950
+ state: "due",
951
+ verifiedAt: new Date(verifiedAtMs).toISOString(),
952
+ dueAt: now.toISOString(),
953
+ minimumIntervalHours: 24
954
+ });
955
+ }
956
+ return Object.freeze({
957
+ state: now.getTime() >= dueAtMs ? "due" : "waiting",
958
+ verifiedAt: new Date(verifiedAtMs).toISOString(),
959
+ dueAt: new Date(dueAtMs).toISOString(),
960
+ minimumIntervalHours: 24
961
+ });
962
+ }
963
+ function persistScheduledIntegrityQuarantine(integrityRoot, key, receipt, error, now) {
964
+ const unsigned = Object.freeze({
965
+ schemaVersion: 1,
966
+ objectType: "aops-commercial-integrity-quarantine-v1",
967
+ installationId: receipt.installationId,
968
+ hostInstanceId: receipt.hostInstanceId,
969
+ receiptId: receipt.receiptId,
970
+ closureDigest: receipt.closureDigest,
971
+ activationGeneration: receipt.activation.generation,
972
+ detectedAt: now.toISOString(),
973
+ source: "scheduled-verification",
974
+ stage: error instanceof CommercialArtifactError ? error.stage : "scheduled-verification",
975
+ reason: error instanceof CommercialArtifactError ? error.reason : "scheduled_verification_failed"
976
+ });
977
+ const value = Object.freeze({
978
+ ...unsigned,
979
+ localIntegrity: Object.freeze({
980
+ scheme: "hmac-sha256-v1",
981
+ mac: integrityMac(key, "aops-commercial-integrity-quarantine-v1", unsigned)
982
+ })
983
+ });
984
+ atomicWrite(safeChild(integrityRoot, "quarantine.json"), `${canonicalCommercialJson(value)}
985
+ `);
986
+ }
987
+ function integrityRelativePath(storeRoot, filePath) {
988
+ const relative = path.relative(storeRoot, filePath).split(path.sep).join("/");
989
+ if (!relative || relative.startsWith("../") || path.isAbsolute(relative)) {
990
+ fail$1("commercial-integrity", "integrity_snapshot_path_escape", "quarantine");
991
+ }
992
+ return relative;
993
+ }
994
+ function integrityStoredPath(storeRoot, relativePath) {
995
+ let cursor = storeRoot;
996
+ for (const segment of relativePath.split("/"))
997
+ cursor = safeChild(cursor, segment);
998
+ return cursor;
999
+ }
1000
+ function integrityFileRecord(storeRoot, filePath) {
1001
+ const stat = lstatSync(filePath);
1002
+ if (stat.isSymbolicLink() || !stat.isFile()) {
1003
+ fail$1("commercial-integrity", "integrity_snapshot_file_unsafe", "quarantine");
1004
+ }
1005
+ return Object.freeze({
1006
+ relativePath: integrityRelativePath(storeRoot, filePath),
1007
+ size: stat.size,
1008
+ mtimeMs: stat.mtimeMs,
1009
+ fileId: `${stat.dev}:${stat.ino}`
1010
+ });
1011
+ }
1012
+ function runtimePackageReadOnlyRoot(nodeModulesRoot, packageName) {
1013
+ const segments = packageName.split("/");
1014
+ if (segments.length === 1)
1015
+ return safeChild(nodeModulesRoot, segments[0]);
1016
+ if (segments.length === 2 && segments[0].startsWith("@")) {
1017
+ return safeChild(nodeModulesRoot, segments[0], segments[1]);
1018
+ }
1019
+ fail$1("commercial-integrity", "integrity_package_name_invalid", "quarantine");
1020
+ }
1021
+ function buildCommercialIntegrityAuthority(storeRoot, receipt, artifacts, source, now, flags = {
1022
+ authorityReestablished: false,
1023
+ previousAnchorUnknown: false
1024
+ }) {
1025
+ const records = /* @__PURE__ */ new Map();
1026
+ const add = (filePath) => {
1027
+ const record = integrityFileRecord(storeRoot, filePath);
1028
+ const existing = records.get(record.relativePath);
1029
+ if (existing && existing.size !== record.size) {
1030
+ fail$1("commercial-integrity", "integrity_snapshot_duplicate_mismatch", "quarantine");
1031
+ }
1032
+ records.set(record.relativePath, record);
1033
+ };
1034
+ for (const object of receipt.casObjects)
1035
+ add(readOnlyObjectPath(storeRoot, object.digest));
1036
+ const runtimeRoot = readOnlyRuntimeRootPath(storeRoot, receipt.closureDigest);
1037
+ const nodeModulesRoot = safeChild(runtimeRoot, "node_modules");
1038
+ const critical = /* @__PURE__ */ new Map();
1039
+ for (const artifact of artifacts.values()) {
1040
+ const packageRoot = runtimePackageReadOnlyRoot(nodeModulesRoot, artifact.packageName);
1041
+ for (const row of artifact.files) {
1042
+ const treeFile = path.join(artifact.treePath, ...row.path.split("/"));
1043
+ const runtimeFile = path.join(packageRoot, ...row.path.split("/"));
1044
+ add(treeFile);
1045
+ add(runtimeFile);
1046
+ const candidates = critical.get(row.sha256) ?? [];
1047
+ candidates.push(integrityRelativePath(storeRoot, runtimeFile));
1048
+ critical.set(row.sha256, candidates);
1049
+ }
1050
+ }
1051
+ const criticalFile = (digest2, reason) => {
1052
+ const candidates = critical.get(digest2)?.sort();
1053
+ if (!candidates?.length)
1054
+ fail$1("commercial-integrity", reason, "quarantine");
1055
+ return Object.freeze({ relativePath: candidates[0], digest: digest2 });
1056
+ };
1057
+ return Object.freeze({
1058
+ schemaVersion: 1,
1059
+ objectType: "aops-commercial-integrity-authority-v1",
1060
+ installationId: receipt.installationId,
1061
+ hostInstanceId: receipt.hostInstanceId,
1062
+ receiptId: receipt.receiptId,
1063
+ closureDigest: receipt.closureDigest,
1064
+ activationGeneration: receipt.activation.generation,
1065
+ verifiedAt: now.toISOString(),
1066
+ verificationSource: source,
1067
+ authorityReestablished: flags.authorityReestablished,
1068
+ previousAnchorUnknown: flags.previousAnchorUnknown,
1069
+ files: Object.freeze([...records.values()].sort((left, right) => compareCanonicalText(left.relativePath, right.relativePath))),
1070
+ dcm: criticalFile(receipt.dcmDigest, "integrity_dcm_path_missing"),
1071
+ operationCatalog: criticalFile(receipt.operationCatalogDigest, "integrity_operation_catalog_path_missing")
1072
+ });
1073
+ }
1074
+ function persistCommercialIntegrityAuthority(integrityRoot, key, value) {
1075
+ const authority = signCommercialIntegrityAuthority(key, value);
1076
+ atomicWrite(safeChild(integrityRoot, "authority.json"), `${canonicalCommercialJson(authority)}
1077
+ `);
1078
+ return authority;
1079
+ }
1080
+ function verifyRoutineIntegrityFiles(storeRoot, authority) {
1081
+ let bytes = 0;
1082
+ let advisoryMtimeDriftCount = 0;
1083
+ let advisoryFileIdDriftCount = 0;
1084
+ for (const expected of authority.files) {
1085
+ const filePath = integrityStoredPath(storeRoot, expected.relativePath);
1086
+ if (!existsSync(filePath))
1087
+ return Object.freeze({
1088
+ matches: false,
1089
+ fileCount: authority.files.length,
1090
+ bytes,
1091
+ advisoryMtimeDriftCount,
1092
+ advisoryFileIdDriftCount
1093
+ });
1094
+ const stat = lstatSync(filePath);
1095
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size !== expected.size) {
1096
+ return Object.freeze({
1097
+ matches: false,
1098
+ fileCount: authority.files.length,
1099
+ bytes,
1100
+ advisoryMtimeDriftCount,
1101
+ advisoryFileIdDriftCount
1102
+ });
1103
+ }
1104
+ bytes += stat.size;
1105
+ if (stat.mtimeMs !== expected.mtimeMs)
1106
+ advisoryMtimeDriftCount += 1;
1107
+ if (`${stat.dev}:${stat.ino}` !== expected.fileId)
1108
+ advisoryFileIdDriftCount += 1;
1109
+ }
1110
+ return Object.freeze({
1111
+ matches: true,
1112
+ fileCount: authority.files.length,
1113
+ bytes,
1114
+ advisoryMtimeDriftCount,
1115
+ advisoryFileIdDriftCount
1116
+ });
1117
+ }
1118
+ function readCriticalIntegrityFile(storeRoot, critical) {
1119
+ const filePath = assertRegularFile(integrityStoredPath(storeRoot, critical.relativePath), "commercial-integrity", "integrity_critical_file_missing");
1120
+ const bytes = readFileSync(filePath);
1121
+ if (digestBytes(bytes) !== critical.digest) {
1122
+ fail$1("commercial-integrity", "integrity_critical_file_digest_mismatch", "quarantine");
1123
+ }
1124
+ return bytes;
1125
+ }
1126
+ function readClosureFileByDigest(root, receipt, digest2) {
1127
+ if (!SHA256.test(digest2))
1128
+ fail$1("closure-readback", "closure_file_digest_invalid");
1129
+ let matched = null;
1130
+ for (const object of receipt.casObjects) {
1131
+ if (!object.role.startsWith("npm:"))
1132
+ continue;
1133
+ const file = assertRegularFile(readOnlyObjectPath(root, object.digest), "cas-readback", "cas_object_missing");
1134
+ const bytes = readFileSync(file);
1135
+ if (bytes.byteLength !== object.size || digestBytes(bytes) !== object.digest) {
1136
+ fail$1("cas-readback", "cas_object_digest_mismatch", "quarantine");
1137
+ }
1138
+ const archive = inspectNpmTarball(bytes);
1139
+ for (const row of archive.files) {
1140
+ if (row.sha256 !== digest2)
1141
+ continue;
1142
+ const candidate = archive.contents.get(row.path);
1143
+ if (!candidate || digestBytes(candidate) !== digest2) {
1144
+ fail$1("closure-readback", "closure_file_digest_mismatch", "quarantine");
1145
+ }
1146
+ if (matched && !matched.equals(candidate)) {
1147
+ fail$1("closure-readback", "closure_file_digest_collision", "quarantine");
1148
+ }
1149
+ matched = Buffer.from(candidate);
1150
+ }
1151
+ }
1152
+ if (!matched)
1153
+ fail$1("closure-readback", "closure_file_missing", "quarantine");
1154
+ return matched;
1155
+ }
1156
+ function readStoredManifest(root, digest2) {
1157
+ const value = parseJsonFile$1(readOnlyManifestPath(root, digest2), "manifest-readback", "stored_manifest_invalid");
1158
+ return value;
1159
+ }
1160
+ function assertManifestReceiptBinding(receipt, manifest) {
1161
+ const payload = manifest.envelope.payload;
1162
+ 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)
1163
+ fail$1("manifest-readback", "manifest_receipt_mismatch", "quarantine");
1164
+ }
1165
+ function assertRoutineLaunchClosureBinding(root, receipt, payload) {
1166
+ const roleRows = payload.closure.filter((entry) => entry.launchRole !== null);
1167
+ const runtime = roleRows.find((entry) => entry.launchRole === "runtime-node");
1168
+ if (!runtime)
1169
+ fail$1("manifest-readback", "runtime_role_missing", "quarantine");
1170
+ if (receipt.launchClosure.runtimeVersion !== runtime.version || receipt.launchClosure.entries.length !== roleRows.length)
1171
+ fail$1("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1172
+ for (const row of roleRows) {
1173
+ const entry = receipt.launchClosure.entries.find((candidate) => candidate.role === row.launchRole);
1174
+ const expectedPath = row.launchEntrypoint === null ? null : `runtimes/sha256/${receipt.closureDigest.slice("sha256:".length)}/node_modules/${row.packageName}/${row.launchEntrypoint}`;
1175
+ 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)
1176
+ fail$1("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1177
+ const launchFile = assertRegularFile(integrityStoredPath(root, entry.resolvedPath), "manifest-readback", "launch_closure_file_missing");
1178
+ if (statSync(launchFile).size < 0) {
1179
+ fail$1("manifest-readback", "launch_closure_file_missing", "quarantine");
1180
+ }
1181
+ if (row.launchRole !== "runtime-node") {
1182
+ if (row.runtimeRange === null) {
1183
+ fail$1("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1184
+ }
1185
+ assertCommercialRuntimeCompatible(runtime.version, row.runtimeRange);
1186
+ }
1187
+ }
1188
+ }
1189
+ function assertAuthorityStoreBinding(authority, identity) {
1190
+ if (authority.installationId !== identity.installationId || authority.hostInstanceId !== identity.hostInstanceId)
1191
+ fail$1("commercial-integrity", "integrity_authority_store_identity_mismatch", "quarantine");
1192
+ }
1193
+ function readVerifiedActiveCommercialArtifact(options) {
1194
+ const root = assertAbsoluteSafeRoot(options.storeRoot);
1195
+ const identity = assertStoreIdentity(root, options.expectedIdentity);
1196
+ if (existsSync(readOnlyStatePath(root, "activation-journal.json"))) {
1197
+ fail$1("activation-readback", "activation_recovery_required", "quarantine");
1198
+ }
1199
+ const pointer = readPointer(root, "active.json");
1200
+ if (!pointer)
1201
+ return null;
1202
+ const receipt = readReceipt(root, pointer.receiptId);
1203
+ if (receipt.installationId !== identity.installationId || receipt.hostInstanceId !== identity.hostInstanceId)
1204
+ fail$1("store-identity", "receipt_store_identity_mismatch", "quarantine");
1205
+ assertRetainedHighWater(root, receipt);
1206
+ const mode = options.verificationMode ?? "full";
1207
+ const scheduledIntegrityRoot = mode === "scheduled" && options.integrityStateRoot ? commercialIntegrityRoot(options.integrityStateRoot) : null;
1208
+ const scheduledKey = scheduledIntegrityRoot ? commercialIntegrityKey(scheduledIntegrityRoot) : null;
1209
+ if (scheduledIntegrityRoot && scheduledKey && readCommercialIntegrityQuarantine(scheduledIntegrityRoot, scheduledKey))
1210
+ fail$1("commercial-integrity", "integrity_scheduled_quarantine_active", "quarantine");
1211
+ try {
1212
+ const manifest = verifyReleaseManifestEnvelope(readStoredManifest(root, receipt.manifestDigest), {
1213
+ trustKeys: options.trustKeys,
1214
+ now: options.now,
1215
+ knownOperationIds: options.knownOperationIds
1216
+ });
1217
+ assertManifestReceiptBinding(receipt, manifest);
1218
+ const payload = manifest.envelope.payload;
1219
+ let artifacts = null;
1220
+ let routineAuthority = null;
1221
+ let routineDecision = null;
1222
+ let routineFileCount = 0;
1223
+ let routineBytes = 0;
1224
+ let advisoryMtimeDriftCount = 0;
1225
+ let advisoryFileIdDriftCount = 0;
1226
+ const routineStartedAt = process.hrtime.bigint();
1227
+ const fullVerify = () => verifyStoredClosure(root, receipt, options.onClosureVerified);
1228
+ if (mode === "routine" && options.integrityStateRoot) {
1229
+ const integrityRoot = commercialIntegrityRoot(options.integrityStateRoot, false);
1230
+ const key = integrityRoot ? commercialIntegrityKey(integrityRoot, false) : null;
1231
+ const authority = integrityRoot && key ? readCommercialIntegrityAuthority(integrityRoot, key) : null;
1232
+ if (integrityRoot && key && readCommercialIntegrityQuarantine(integrityRoot, key)) {
1233
+ fail$1("commercial-integrity", "integrity_scheduled_quarantine_active", "quarantine");
1234
+ }
1235
+ if (!integrityRoot || !key || !authority) {
1236
+ artifacts = fullVerify();
1237
+ routineDecision = "full-fallback-authority-unavailable";
1238
+ } else {
1239
+ assertAuthorityStoreBinding(authority, identity);
1240
+ if (authority.activationGeneration > receipt.activation.generation) {
1241
+ fail$1("commercial-integrity", "integrity_authority_ahead", "quarantine");
1242
+ }
1243
+ if (authority.activationGeneration < receipt.activation.generation) {
1244
+ const pending = readCommercialIntegrityPending(integrityRoot, key);
1245
+ 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) {
1246
+ artifacts = fullVerify();
1247
+ const healed = buildCommercialIntegrityAuthority(root, receipt, artifacts, pending.target.verificationSource, options.now ?? /* @__PURE__ */ new Date());
1248
+ routineAuthority = persistCommercialIntegrityAuthority(integrityRoot, key, healed);
1249
+ rmSync(safeChild(integrityRoot, "pending.json"), { force: true });
1250
+ routineDecision = "full-heal-forward";
1251
+ } else {
1252
+ artifacts = fullVerify();
1253
+ routineDecision = "full-fallback-authority-behind";
1254
+ }
1255
+ } else {
1256
+ if (authority.receiptId !== receipt.receiptId || authority.closureDigest !== receipt.closureDigest)
1257
+ fail$1("commercial-integrity", "integrity_authority_receipt_mismatch", "quarantine");
1258
+ const sweep = verifyRoutineIntegrityFiles(root, authority);
1259
+ routineFileCount = sweep.fileCount;
1260
+ routineBytes = sweep.bytes;
1261
+ advisoryMtimeDriftCount = sweep.advisoryMtimeDriftCount;
1262
+ advisoryFileIdDriftCount = sweep.advisoryFileIdDriftCount;
1263
+ if (!sweep.matches) {
1264
+ artifacts = fullVerify();
1265
+ const refreshed = buildCommercialIntegrityAuthority(root, receipt, artifacts, "routine-size-drift-full-verify", options.now ?? /* @__PURE__ */ new Date());
1266
+ routineAuthority = persistCommercialIntegrityAuthority(integrityRoot, key, refreshed);
1267
+ routineDecision = "full-fallback-size-drift";
1268
+ } else {
1269
+ routineAuthority = authority;
1270
+ routineDecision = "verified";
1271
+ }
1272
+ }
1273
+ }
1274
+ } else {
1275
+ artifacts = fullVerify();
1276
+ if (mode === "scheduled" && options.integrityStateRoot) {
1277
+ const integrityRoot = scheduledIntegrityRoot;
1278
+ const key = scheduledKey;
1279
+ const authority = integrityRoot && key ? readCommercialIntegrityAuthority(integrityRoot, key) : null;
1280
+ if (!integrityRoot || !key || !authority) {
1281
+ fail$1("commercial-integrity", "integrity_authority_reestablish_required", "quarantine");
1282
+ }
1283
+ assertAuthorityStoreBinding(authority, identity);
1284
+ if (authority.activationGeneration > receipt.activation.generation) {
1285
+ fail$1("commercial-integrity", "integrity_authority_ahead", "quarantine");
1286
+ }
1287
+ if (authority.activationGeneration < receipt.activation.generation) {
1288
+ fail$1("commercial-integrity", "integrity_authority_behind_reestablish_required", "quarantine");
1289
+ }
1290
+ if (authority.receiptId !== receipt.receiptId || authority.closureDigest !== receipt.closureDigest) {
1291
+ fail$1("commercial-integrity", "integrity_authority_receipt_mismatch", "quarantine");
1292
+ }
1293
+ persistCommercialIntegrityAuthority(integrityRoot, key, buildCommercialIntegrityAuthority(root, receipt, artifacts, "scheduled", options.now ?? /* @__PURE__ */ new Date()));
1294
+ }
1295
+ }
1296
+ if (artifacts) {
1297
+ const launchClosure = resolveLaunchClosure(payload, artifacts);
1298
+ if (canonicalCommercialJson(launchClosure) !== canonicalCommercialJson(receipt.launchClosure)) {
1299
+ fail$1("manifest-readback", "launch_closure_receipt_mismatch", "quarantine");
1300
+ }
1301
+ } else {
1302
+ assertRoutineLaunchClosureBinding(root, receipt, payload);
1303
+ }
1304
+ const dcmBytes = routineAuthority ? readCriticalIntegrityFile(root, routineAuthority.dcm) : readClosureFileByDigest(root, receipt, receipt.dcmDigest);
1305
+ const operationCatalogBytes = routineAuthority ? readCriticalIntegrityFile(root, routineAuthority.operationCatalog) : readClosureFileByDigest(root, receipt, receipt.operationCatalogDigest);
1306
+ if (mode === "scheduled" && scheduledIntegrityRoot && scheduledKey) {
1307
+ rmSync(safeChild(scheduledIntegrityRoot, "quarantine.json"), { force: true });
1308
+ }
1309
+ if (routineDecision) {
1310
+ if (routineAuthority && routineFileCount === 0) {
1311
+ const sweep = verifyRoutineIntegrityFiles(root, routineAuthority);
1312
+ routineFileCount = sweep.fileCount;
1313
+ routineBytes = sweep.bytes;
1314
+ advisoryMtimeDriftCount = sweep.advisoryMtimeDriftCount;
1315
+ advisoryFileIdDriftCount = sweep.advisoryFileIdDriftCount;
1316
+ }
1317
+ options.onRoutineVerified?.(Object.freeze({
1318
+ elapsedMs: Number(process.hrtime.bigint() - routineStartedAt) / 1e6,
1319
+ authorityDecision: routineDecision,
1320
+ authoritativeFileCount: routineFileCount,
1321
+ authoritativeBytes: routineBytes,
1322
+ authoritativeBytesDerivedFromFileMetadata: true,
1323
+ advisoryMtimeDriftCount,
1324
+ advisoryFileIdDriftCount,
1325
+ fullVerificationPerformed: routineDecision !== "verified"
1326
+ }));
1327
+ }
1328
+ return Object.freeze({
1329
+ receipt,
1330
+ manifest,
1331
+ dcmBytes,
1332
+ operationCatalogBytes
1333
+ });
1334
+ } catch (error) {
1335
+ if (mode === "scheduled" && scheduledIntegrityRoot && scheduledKey) {
1336
+ persistScheduledIntegrityQuarantine(scheduledIntegrityRoot, scheduledKey, receipt, error, options.now ?? /* @__PURE__ */ new Date());
1337
+ }
1338
+ throw error;
1339
+ }
1340
+ }
1341
+ const INSTALLATION_POSSESSION_PROOF_ALGORITHM = "EdDSA";
1342
+ const INSTALLATION_POSSESSION_PROOF_TYPE = "aops-installation-possession-proof+jws";
1343
+ const INSTALLATION_POSSESSION_PROOF_PURPOSE = "urn:aops:installation-possession:v1";
1344
+ const INSTALLATION_POSSESSION_PROOF_SCHEMA_VERSION = 1;
1345
+ const MAX_INSTALLATION_POSSESSION_PROOF_LIFETIME_SECONDS = 5 * 60;
1346
+ const CLOCK_SKEW_SECONDS = 30;
1347
+ const MAX_PROOF_BYTES = 32 * 1024;
1348
+ const SHA256_HEX$1 = /^[a-f0-9]{64}$/;
1349
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1350
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
1351
+ const PAYLOAD_KEYS = Object.freeze([
1352
+ "activationChallengeDigest",
1353
+ "exp",
1354
+ "hostInstanceId",
1355
+ "iat",
1356
+ "installationId",
1357
+ "installationPublicKeyJwk",
1358
+ "leaseDigest",
1359
+ "nonce",
1360
+ "proofId",
1361
+ "purpose",
1362
+ "receiptBinding",
1363
+ "schemaVersion"
1364
+ ]);
1365
+ function fail(stage, reason) {
1366
+ throw new CommercialArtifactError(stage, reason);
1367
+ }
1368
+ function isRecord$1(value) {
1369
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1370
+ }
1371
+ function exactKeys$1(value, expected, stage) {
1372
+ const actual = Object.keys(value).sort();
1373
+ const sortedExpected = [...expected].sort();
1374
+ if (actual.length !== sortedExpected.length || actual.some((key, index) => key !== sortedExpected[index]))
1375
+ fail(stage, "installation_possession_schema_invalid");
1376
+ }
1377
+ function text$1(value, maximum = 512) {
1378
+ if (typeof value !== "string" || value !== value.trim() || value.length === 0 || value.length > maximum)
1379
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1380
+ return value;
1381
+ }
1382
+ function integer(value) {
1383
+ if (!Number.isSafeInteger(value)) {
1384
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1385
+ }
1386
+ return value;
1387
+ }
1388
+ function sha256$1(value) {
1389
+ const normalized = text$1(value, 64);
1390
+ if (!SHA256_HEX$1.test(normalized)) {
1391
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1392
+ }
1393
+ return normalized;
1394
+ }
1395
+ function hash(value) {
1396
+ return createHash("sha256").update(value, "utf8").digest("hex");
1397
+ }
1398
+ function normalizeNonce(value) {
1399
+ const normalized = text$1(value, 256);
1400
+ if (!BASE64URL.test(normalized)) {
1401
+ fail("installation-possession-schema", "installation_possession_nonce_invalid");
1402
+ }
1403
+ const bytes = Buffer.from(normalized, "base64url");
1404
+ if (bytes.length < 32 || bytes.length > 128 || bytes.toString("base64url") !== normalized)
1405
+ fail("installation-possession-schema", "installation_possession_nonce_invalid");
1406
+ return normalized;
1407
+ }
1408
+ function publicJwk(value) {
1409
+ if (!isRecord$1(value)) {
1410
+ fail("installation-possession-schema", "installation_possession_key_invalid");
1411
+ }
1412
+ exactKeys$1(value, ["crv", "kty", "x"], "installation-possession-schema");
1413
+ if (value.kty !== "OKP" || value.crv !== "Ed25519" || typeof value.x !== "string" || !BASE64URL.test(value.x))
1414
+ fail("installation-possession-schema", "installation_possession_key_invalid");
1415
+ const normalized = Object.freeze({
1416
+ kty: "OKP",
1417
+ crv: "Ed25519",
1418
+ x: value.x
1419
+ });
1420
+ try {
1421
+ const key = createPublicKey({ key: normalized, format: "jwk" });
1422
+ if (key.asymmetricKeyType !== "ed25519") {
1423
+ fail("installation-possession-schema", "installation_possession_key_invalid");
1424
+ }
1425
+ } catch (error) {
1426
+ if (error instanceof CommercialArtifactError)
1427
+ throw error;
1428
+ fail("installation-possession-schema", "installation_possession_key_invalid");
1429
+ }
1430
+ return normalized;
1431
+ }
1432
+ function receiptBinding(value) {
1433
+ if (!isRecord$1(value)) {
1434
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1435
+ }
1436
+ exactKeys$1(value, ["closureDigest", "manifestDigest", "receiptId", "releaseId"], "installation-possession-schema");
1437
+ return Object.freeze({
1438
+ receiptId: text$1(value.receiptId, 200),
1439
+ releaseId: text$1(value.releaseId),
1440
+ manifestDigest: sha256$1(value.manifestDigest),
1441
+ closureDigest: sha256$1(value.closureDigest)
1442
+ });
1443
+ }
1444
+ function normalizeInstallationPossessionProofPayload(value) {
1445
+ if (!isRecord$1(value)) {
1446
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1447
+ }
1448
+ exactKeys$1(value, PAYLOAD_KEYS, "installation-possession-schema");
1449
+ if (integer(value.schemaVersion) !== INSTALLATION_POSSESSION_PROOF_SCHEMA_VERSION || value.purpose !== INSTALLATION_POSSESSION_PROOF_PURPOSE)
1450
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1451
+ const proofId = text$1(value.proofId, 64).toLowerCase();
1452
+ if (!UUID.test(proofId)) {
1453
+ fail("installation-possession-schema", "installation_possession_schema_invalid");
1454
+ }
1455
+ const iat = integer(value.iat);
1456
+ const exp = integer(value.exp);
1457
+ if (iat < 0 || exp <= iat || exp - iat > MAX_INSTALLATION_POSSESSION_PROOF_LIFETIME_SECONDS)
1458
+ fail("installation-possession-schema", "installation_possession_window_invalid");
1459
+ return Object.freeze({
1460
+ schemaVersion: 1,
1461
+ purpose: INSTALLATION_POSSESSION_PROOF_PURPOSE,
1462
+ proofId,
1463
+ nonce: normalizeNonce(value.nonce),
1464
+ installationId: text$1(value.installationId, 200),
1465
+ hostInstanceId: text$1(value.hostInstanceId, 200),
1466
+ installationPublicKeyJwk: publicJwk(value.installationPublicKeyJwk),
1467
+ leaseDigest: sha256$1(value.leaseDigest),
1468
+ activationChallengeDigest: sha256$1(value.activationChallengeDigest),
1469
+ receiptBinding: receiptBinding(value.receiptBinding),
1470
+ iat,
1471
+ exp
1472
+ });
1473
+ }
1474
+ function encode(value) {
1475
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
1476
+ }
1477
+ function decodeSegment(segment, stage) {
1478
+ if (!BASE64URL.test(segment))
1479
+ fail(stage, "installation_possession_compact_invalid");
1480
+ const decoded = Buffer.from(segment, "base64url");
1481
+ if (decoded.toString("base64url") !== segment) {
1482
+ fail(stage, "installation_possession_compact_invalid");
1483
+ }
1484
+ return decoded;
1485
+ }
1486
+ function decodeJson(segment, stage) {
1487
+ try {
1488
+ const value = JSON.parse(decodeSegment(segment, stage).toString("utf8"));
1489
+ if (!isRecord$1(value))
1490
+ fail(stage, "installation_possession_schema_invalid");
1491
+ return value;
1492
+ } catch (error) {
1493
+ if (error instanceof CommercialArtifactError)
1494
+ throw error;
1495
+ fail(stage, "installation_possession_json_invalid");
1496
+ }
1497
+ }
1498
+ function createInstallationPossessionProof(input) {
1499
+ const installationPublicKeyJwk = installationPublicJwkFromPrivateKey(input.privateKeyPem);
1500
+ const payload = normalizeInstallationPossessionProofPayload({
1501
+ schemaVersion: 1,
1502
+ purpose: INSTALLATION_POSSESSION_PROOF_PURPOSE,
1503
+ proofId: input.proofId,
1504
+ nonce: input.nonce,
1505
+ installationId: input.installationId,
1506
+ hostInstanceId: input.hostInstanceId,
1507
+ installationPublicKeyJwk,
1508
+ leaseDigest: hash(input.leaseToken),
1509
+ activationChallengeDigest: input.activationChallengeDigest,
1510
+ receiptBinding: input.receiptBinding,
1511
+ iat: input.iat,
1512
+ exp: input.exp
1513
+ });
1514
+ const installationKeyThumbprint = offlineActivationKeyThumbprint(payload.installationPublicKeyJwk);
1515
+ const header = Object.freeze({
1516
+ alg: INSTALLATION_POSSESSION_PROOF_ALGORITHM,
1517
+ typ: INSTALLATION_POSSESSION_PROOF_TYPE,
1518
+ kid: `installation/${installationKeyThumbprint}`
1519
+ });
1520
+ const signingInput = `${encode(header)}.${encode(payload)}`;
1521
+ let signature;
1522
+ try {
1523
+ const privateKey = createPrivateKey(input.privateKeyPem);
1524
+ if (privateKey.asymmetricKeyType !== "ed25519") {
1525
+ fail("installation-possession-signature", "installation_possession_key_invalid");
1526
+ }
1527
+ signature = sign(null, Buffer.from(signingInput, "ascii"), privateKey);
1528
+ } catch (error) {
1529
+ if (error instanceof CommercialArtifactError)
1530
+ throw error;
1531
+ fail("installation-possession-signature", "installation_possession_signature_invalid");
1532
+ }
1533
+ const token = `${signingInput}.${signature.toString("base64url")}`;
1534
+ return Object.freeze({
1535
+ token,
1536
+ payload,
1537
+ proofDigest: hash(token),
1538
+ installationKeyThumbprint
1539
+ });
1540
+ }
1541
+ function verifyInstallationPossessionProof(input) {
1542
+ if (typeof input.token !== "string" || input.token.length < 16 || Buffer.byteLength(input.token, "utf8") > MAX_PROOF_BYTES)
1543
+ fail("installation-possession-schema", "installation_possession_compact_invalid");
1544
+ const parts = input.token.split(".");
1545
+ if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
1546
+ fail("installation-possession-schema", "installation_possession_compact_invalid");
1547
+ }
1548
+ const header = decodeJson(parts[0], "installation-possession-schema");
1549
+ exactKeys$1(header, ["alg", "kid", "typ"], "installation-possession-schema");
1550
+ if (header.alg !== INSTALLATION_POSSESSION_PROOF_ALGORITHM || header.typ !== INSTALLATION_POSSESSION_PROOF_TYPE) {
1551
+ fail("installation-possession-signature", "installation_possession_signature_context_invalid");
1552
+ }
1553
+ const payload = normalizeInstallationPossessionProofPayload(decodeJson(parts[1], "installation-possession-schema"));
1554
+ const installationKeyThumbprint = offlineActivationKeyThumbprint(payload.installationPublicKeyJwk);
1555
+ if (header.kid !== `installation/${installationKeyThumbprint}` || installationKeyThumbprint !== input.expected.installationKeyThumbprint)
1556
+ fail("installation-possession-coverage", "installation_key_not_bound");
1557
+ let signature;
1558
+ try {
1559
+ signature = decodeSegment(parts[2], "installation-possession-signature");
1560
+ } catch {
1561
+ fail("installation-possession-signature", "installation_possession_signature_invalid");
1562
+ }
1563
+ const key = createPublicKey({
1564
+ key: payload.installationPublicKeyJwk,
1565
+ format: "jwk"
1566
+ });
1567
+ if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`, "ascii"), key, signature)) {
1568
+ fail("installation-possession-signature", "installation_possession_signature_invalid");
1569
+ }
1570
+ const now = input.now ?? /* @__PURE__ */ new Date();
1571
+ const nowSeconds = Math.floor(now.getTime() / 1e3);
1572
+ if (!Number.isSafeInteger(nowSeconds)) {
1573
+ fail("installation-possession-validity", "clock_invalid");
1574
+ }
1575
+ if (nowSeconds + CLOCK_SKEW_SECONDS < payload.iat) {
1576
+ fail("installation-possession-validity", "installation_possession_not_yet_valid");
1577
+ }
1578
+ if (nowSeconds >= payload.exp) {
1579
+ fail("installation-possession-validity", "installation_possession_expired");
1580
+ }
1581
+ const expected = input.expected;
1582
+ if (payload.nonce !== normalizeNonce(expected.nonce)) {
1583
+ fail("installation-possession-coverage", "installation_possession_nonce_mismatch");
1584
+ }
1585
+ if (payload.installationId !== expected.installationId || payload.hostInstanceId !== expected.hostInstanceId)
1586
+ fail("installation-possession-coverage", "installation_identity_not_bound");
1587
+ if (payload.leaseDigest !== hash(expected.leaseToken)) {
1588
+ fail("installation-possession-coverage", "lease_not_bound");
1589
+ }
1590
+ if (payload.activationChallengeDigest !== expected.activationChallengeDigest) {
1591
+ fail("installation-possession-coverage", "activation_challenge_not_bound");
1592
+ }
1593
+ if (payload.receiptBinding.receiptId !== expected.receiptId || payload.receiptBinding.releaseId !== expected.releaseId || payload.receiptBinding.manifestDigest !== expected.manifestDigest || payload.receiptBinding.closureDigest !== expected.closureDigest)
1594
+ fail("installation-possession-coverage", "receipt_not_bound");
1595
+ return Object.freeze({
1596
+ token: input.token,
1597
+ payload,
1598
+ proofDigest: hash(input.token),
1599
+ installationKeyThumbprint,
1600
+ verifiedAt: now.toISOString()
1601
+ });
1602
+ }
1603
+ function commercialIntegrityReadOptions(storeRoot, requestedMode = "routine") {
1604
+ const layout = resolveManagedInstallationLayout();
1605
+ if (path.resolve(storeRoot) !== path.resolve(layout.storeRoot)) {
1606
+ if (requestedMode === "scheduled") {
1607
+ throw new Error("commercial_integrity_scheduler_requires_managed_store");
1608
+ }
1609
+ return Object.freeze({ verificationMode: "full" });
1610
+ }
1611
+ return Object.freeze({
1612
+ integrityStateRoot: layout.stateRoot,
1613
+ verificationMode: requestedMode
1614
+ });
1615
+ }
1616
+ const CONFIG_KEYS_V1 = Object.freeze([
1617
+ "domain",
1618
+ "entitlementEpoch",
1619
+ "extensionNamespace",
1620
+ "hostInstanceId",
1621
+ "installationId",
1622
+ "issuer",
1623
+ "leaseFile",
1624
+ "leaseMode",
1625
+ "leaseTrustBundle",
1626
+ "minimumRevocationEpoch",
1627
+ "objectType",
1628
+ "productId",
1629
+ "releaseTrustBundle",
1630
+ "schemaVersion",
1631
+ "storeRoot",
1632
+ "tenantId",
1633
+ "target"
1634
+ ]);
1635
+ const CONFIG_KEYS_V2 = Object.freeze([
1636
+ ...CONFIG_KEYS_V1,
1637
+ "activationChallengeDigest",
1638
+ "installationKeyThumbprint",
1639
+ "installationPrivateKeyFile"
1640
+ ]);
1641
+ const SHA256_HEX = /^[a-f0-9]{64}$/;
1642
+ function isRecord(value) {
1643
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1644
+ }
1645
+ function exactKeys(value, expected, reason) {
1646
+ const actual = Object.keys(value).sort();
1647
+ const sorted = [...expected].sort();
1648
+ if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) {
1649
+ throw new Error(reason);
1650
+ }
1651
+ }
1652
+ function text(value, reason) {
1653
+ if (typeof value !== "string" || value !== value.trim() || value.length === 0) {
1654
+ throw new Error(reason);
1655
+ }
1656
+ return value;
1657
+ }
1658
+ function nullableInteger(value, reason) {
1659
+ if (value === null) return null;
1660
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error(reason);
1661
+ return Number(value);
1662
+ }
1663
+ function sha256(value, reason) {
1664
+ const normalized = text(value, reason);
1665
+ if (!SHA256_HEX.test(normalized)) throw new Error(reason);
1666
+ return normalized;
1667
+ }
1668
+ function digestHex(value, reason) {
1669
+ const normalized = value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
1670
+ if (!SHA256_HEX.test(normalized)) throw new Error(reason);
1671
+ return normalized;
1672
+ }
1673
+ function safeRegularFile(filePath, reason) {
1674
+ if (!path.isAbsolute(filePath)) throw new Error(reason);
1675
+ try {
1676
+ const stat = lstatSync(filePath);
1677
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(reason);
1678
+ return realpathSync.native(filePath);
1679
+ } catch {
1680
+ throw new Error(reason);
1681
+ }
1682
+ }
1683
+ function verifyOfflineInstallationPossessionAtLoad(input) {
1684
+ const privateKeyPem = readFileSync(
1685
+ safeRegularFile(
1686
+ input.installationPrivateKeyFile,
1687
+ "commercial_installation_private_key_invalid"
1688
+ ),
1689
+ "utf8"
1690
+ );
1691
+ const nonce = randomBytes(32).toString("base64url");
1692
+ const iat = Math.floor(input.now.getTime() / 1e3);
1693
+ const manifestDigest = digestHex(
1694
+ input.receipt.manifestDigest,
1695
+ "commercial_installation_possession_invalid"
1696
+ );
1697
+ const closureDigest = digestHex(
1698
+ input.receipt.closureDigest,
1699
+ "commercial_installation_possession_invalid"
1700
+ );
1701
+ try {
1702
+ const proof = createInstallationPossessionProof({
1703
+ privateKeyPem,
1704
+ proofId: randomUUID(),
1705
+ nonce,
1706
+ installationId: input.installationId,
1707
+ hostInstanceId: input.hostInstanceId,
1708
+ leaseToken: input.leaseToken,
1709
+ activationChallengeDigest: input.activationChallengeDigest,
1710
+ receiptBinding: {
1711
+ receiptId: input.receipt.receiptId,
1712
+ releaseId: input.receipt.releaseId,
1713
+ manifestDigest,
1714
+ closureDigest
1715
+ },
1716
+ iat,
1717
+ exp: iat + 2 * 60
1718
+ });
1719
+ verifyInstallationPossessionProof({
1720
+ token: proof.token,
1721
+ now: input.now,
1722
+ expected: {
1723
+ nonce,
1724
+ installationId: input.installationId,
1725
+ hostInstanceId: input.hostInstanceId,
1726
+ installationKeyThumbprint: input.installationKeyThumbprint,
1727
+ leaseToken: input.leaseToken,
1728
+ activationChallengeDigest: input.activationChallengeDigest,
1729
+ receiptId: input.receipt.receiptId,
1730
+ releaseId: input.receipt.releaseId,
1731
+ manifestDigest,
1732
+ closureDigest
1733
+ }
1734
+ });
1735
+ } catch {
1736
+ throw new Error("commercial_installation_possession_invalid");
1737
+ }
1738
+ }
1739
+ function safeRuntimeEntrypoint(storeRoot, relativePath) {
1740
+ if (!path.isAbsolute(storeRoot) || path.isAbsolute(relativePath) || relativePath.split(/[\\/]/u).some((segment) => !segment || segment === "." || segment === "..")) throw new Error("commercial_runtime_entrypoint_invalid");
1741
+ const root = realpathSync.native(storeRoot);
1742
+ const candidate = path.resolve(root, relativePath);
1743
+ const relative = path.relative(root, candidate);
1744
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
1745
+ throw new Error("commercial_runtime_entrypoint_invalid");
1746
+ }
1747
+ const real = safeRegularFile(candidate, "commercial_runtime_entrypoint_invalid");
1748
+ const realRelative = path.relative(root, real);
1749
+ if (!realRelative || realRelative.startsWith("..") || path.isAbsolute(realRelative)) {
1750
+ throw new Error("commercial_runtime_entrypoint_invalid");
1751
+ }
1752
+ return real;
1753
+ }
1754
+ function parseJsonFile(filePath, reason) {
1755
+ try {
1756
+ return JSON.parse(readFileSync(safeRegularFile(filePath, reason), "utf8"));
1757
+ } catch (error) {
1758
+ if (error instanceof Error && error.message === reason) throw error;
1759
+ throw new Error(reason);
1760
+ }
1761
+ }
1762
+ function parseConfig(filePath) {
1763
+ const value = parseJsonFile(filePath, "commercial_admission_config_invalid");
1764
+ if (!isRecord(value)) throw new Error("commercial_admission_config_invalid");
1765
+ const schemaVersion = value.schemaVersion;
1766
+ if (schemaVersion !== 1 && schemaVersion !== 2 || value.objectType !== `aops-commercial-admission-config-v${schemaVersion}`) throw new Error("commercial_admission_config_invalid");
1767
+ exactKeys(
1768
+ value,
1769
+ schemaVersion === 1 ? CONFIG_KEYS_V1 : CONFIG_KEYS_V2,
1770
+ "commercial_admission_config_invalid"
1771
+ );
1772
+ const leaseMode = value.leaseMode;
1773
+ if (leaseMode !== null && leaseMode !== "online" && leaseMode !== "offline") {
1774
+ throw new Error("commercial_admission_config_invalid");
1775
+ }
1776
+ if (schemaVersion === 2 && leaseMode !== "offline") {
1777
+ throw new Error("commercial_admission_config_invalid");
1778
+ }
1779
+ return Object.freeze({
1780
+ schemaVersion,
1781
+ target: text(value.target, "commercial_admission_config_invalid"),
1782
+ storeRoot: text(value.storeRoot, "commercial_admission_config_invalid"),
1783
+ releaseTrustBundle: text(value.releaseTrustBundle, "commercial_admission_config_invalid"),
1784
+ leaseFile: text(value.leaseFile, "commercial_admission_config_invalid"),
1785
+ leaseTrustBundle: text(value.leaseTrustBundle, "commercial_admission_config_invalid"),
1786
+ issuer: text(value.issuer, "commercial_admission_config_invalid"),
1787
+ tenantId: text(value.tenantId, "commercial_admission_config_invalid"),
1788
+ installationId: text(value.installationId, "commercial_admission_config_invalid"),
1789
+ hostInstanceId: text(value.hostInstanceId, "commercial_admission_config_invalid"),
1790
+ productId: text(value.productId, "commercial_admission_config_invalid"),
1791
+ domain: text(value.domain, "commercial_admission_config_invalid").toLowerCase(),
1792
+ extensionNamespace: text(value.extensionNamespace, "commercial_admission_config_invalid"),
1793
+ entitlementEpoch: nullableInteger(value.entitlementEpoch, "commercial_admission_config_invalid"),
1794
+ minimumRevocationEpoch: nullableInteger(
1795
+ value.minimumRevocationEpoch,
1796
+ "commercial_admission_config_invalid"
1797
+ ),
1798
+ leaseMode,
1799
+ activationChallengeDigest: schemaVersion === 1 ? null : sha256(value.activationChallengeDigest, "commercial_admission_config_invalid"),
1800
+ installationKeyThumbprint: schemaVersion === 1 ? null : sha256(value.installationKeyThumbprint, "commercial_admission_config_invalid"),
1801
+ installationPrivateKeyFile: schemaVersion === 1 ? null : text(value.installationPrivateKeyFile, "commercial_admission_config_invalid")
1802
+ });
1803
+ }
1804
+ function parseReleaseTrustBundleFile(filePath) {
1805
+ const value = parseJsonFile(filePath, "release_trust_bundle_invalid");
1806
+ if (!isRecord(value)) throw new Error("release_trust_bundle_invalid");
1807
+ exactKeys(
1808
+ value,
1809
+ ["schemaVersion", "objectType", "purpose", "keys"],
1810
+ "release_trust_bundle_invalid"
1811
+ );
1812
+ if (value.schemaVersion !== 1 || value.objectType !== "aops-release-trust-bundle-v1" || value.purpose !== RELEASE_MANIFEST_PURPOSE || !Array.isArray(value.keys) || value.keys.length === 0) throw new Error("release_trust_bundle_invalid");
1813
+ const keys = value.keys.map((candidate) => {
1814
+ if (!isRecord(candidate)) throw new Error("release_trust_bundle_invalid");
1815
+ const actualKeys = Object.keys(candidate).sort();
1816
+ const legacyKeys = ["alg", "kid", "publicKeyPem", "purpose"];
1817
+ const rotatingKeys = [
1818
+ "alg",
1819
+ "kid",
1820
+ "notAfter",
1821
+ "notBefore",
1822
+ "publicKeyPem",
1823
+ "purpose",
1824
+ "status"
1825
+ ];
1826
+ const rotating = actualKeys.length === rotatingKeys.length && actualKeys.every((key, index) => key === rotatingKeys[index]);
1827
+ if (!rotating && (actualKeys.length !== legacyKeys.length || actualKeys.some((key, index) => key !== legacyKeys[index]))) throw new Error("release_trust_bundle_invalid");
1828
+ if (candidate.alg !== "EdDSA" || candidate.purpose !== RELEASE_MANIFEST_PURPOSE || typeof candidate.kid !== "string" || typeof candidate.publicKeyPem !== "string" || rotating && !["active", "verify-only", "retired", "revoked"].includes(
1829
+ String(candidate.status)
1830
+ ) || rotating && candidate.notBefore !== null && typeof candidate.notBefore !== "string" || rotating && candidate.notAfter !== null && typeof candidate.notAfter !== "string") throw new Error("release_trust_bundle_invalid");
1831
+ if (candidate.kid.toLowerCase().includes("test-ephemeral")) {
1832
+ throw new Error("release_trust_test_key_refused");
1833
+ }
1834
+ return Object.freeze({
1835
+ alg: "EdDSA",
1836
+ purpose: RELEASE_MANIFEST_PURPOSE,
1837
+ kid: candidate.kid,
1838
+ publicKeyPem: candidate.publicKeyPem,
1839
+ ...rotating ? {
1840
+ status: candidate.status,
1841
+ ...candidate.notBefore === null ? {} : { notBefore: candidate.notBefore },
1842
+ ...candidate.notAfter === null ? {} : { notAfter: candidate.notAfter }
1843
+ } : {}
1844
+ });
1845
+ });
1846
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length) {
1847
+ throw new Error("release_trust_bundle_invalid");
1848
+ }
1849
+ return Object.freeze(keys);
1850
+ }
1851
+ function parseLeaseTrustBundle(filePath) {
1852
+ const value = parseJsonFile(filePath, "lease_trust_bundle_invalid");
1853
+ if (!isRecord(value)) throw new Error("lease_trust_bundle_invalid");
1854
+ exactKeys(
1855
+ value,
1856
+ ["schemaVersion", "objectType", "purpose", "keys"],
1857
+ "lease_trust_bundle_invalid"
1858
+ );
1859
+ if (value.schemaVersion !== 1 || value.objectType !== "aops-entitlement-lease-trust-bundle-v1" || value.purpose !== ENTITLEMENT_LEASE_PURPOSE || !Array.isArray(value.keys) || value.keys.length === 0) throw new Error("lease_trust_bundle_invalid");
1860
+ const keys = value.keys.map((candidate) => {
1861
+ if (!isRecord(candidate)) throw new Error("lease_trust_bundle_invalid");
1862
+ exactKeys(
1863
+ candidate,
1864
+ ["alg", "kid", "notAfter", "notBefore", "publicKeyPem", "purpose", "status"],
1865
+ "lease_trust_bundle_invalid"
1866
+ );
1867
+ if (candidate.alg !== ENTITLEMENT_LEASE_ALGORITHM || candidate.purpose !== ENTITLEMENT_LEASE_PURPOSE || typeof candidate.kid !== "string" || typeof candidate.publicKeyPem !== "string" || candidate.status !== "active" && candidate.status !== "verify-only" || candidate.notBefore !== null && typeof candidate.notBefore !== "string" || candidate.notAfter !== null && typeof candidate.notAfter !== "string") throw new Error("lease_trust_bundle_invalid");
1868
+ return Object.freeze({
1869
+ alg: ENTITLEMENT_LEASE_ALGORITHM,
1870
+ purpose: ENTITLEMENT_LEASE_PURPOSE,
1871
+ kid: candidate.kid,
1872
+ publicKeyPem: candidate.publicKeyPem,
1873
+ status: candidate.status,
1874
+ ...candidate.notBefore === null ? {} : { notBefore: candidate.notBefore },
1875
+ ...candidate.notAfter === null ? {} : { notAfter: candidate.notAfter }
1876
+ });
1877
+ });
1878
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length) {
1879
+ throw new Error("lease_trust_bundle_invalid");
1880
+ }
1881
+ return Object.freeze(keys);
1882
+ }
1883
+ function parseOperations(dcmBytes, operationCatalogBytes, domain, extension) {
1884
+ let dcmValue;
1885
+ let catalogValue;
1886
+ try {
1887
+ dcmValue = JSON.parse(dcmBytes.toString("utf8"));
1888
+ catalogValue = JSON.parse(operationCatalogBytes.toString("utf8"));
1889
+ } catch {
1890
+ throw new Error("commercial_operation_contract_invalid");
1891
+ }
1892
+ if (!isRecord(dcmValue) || !isRecord(dcmValue.domain) || dcmValue.domain.id !== domain || !isRecord(dcmValue.capabilities) || !Array.isArray(dcmValue.capabilities.operations) || !Array.isArray(catalogValue) || !isRecord(extension)) throw new Error("commercial_operation_contract_invalid");
1893
+ const featureBindings = extension.operationFeatures;
1894
+ if (!Array.isArray(featureBindings)) throw new Error("commercial_operation_contract_invalid");
1895
+ const features = /* @__PURE__ */ new Map();
1896
+ let previousOperationId = "";
1897
+ for (const binding of featureBindings) {
1898
+ if (!isRecord(binding)) throw new Error("commercial_operation_contract_invalid");
1899
+ exactKeys(binding, ["operationId", "requiredFeatureIds"], "commercial_operation_contract_invalid");
1900
+ if (typeof binding.operationId !== "string" || !Array.isArray(binding.requiredFeatureIds)) {
1901
+ throw new Error("commercial_operation_contract_invalid");
1902
+ }
1903
+ const required = binding.requiredFeatureIds.map((entry) => text(entry, "commercial_operation_contract_invalid"));
1904
+ if (binding.operationId <= previousOperationId || required.length === 0 || new Set(required).size !== required.length || required.some((entry, index) => entry !== [...required].sort()[index])) throw new Error("commercial_operation_contract_invalid");
1905
+ previousOperationId = binding.operationId;
1906
+ features.set(binding.operationId, Object.freeze(required));
1907
+ }
1908
+ const catalog = /* @__PURE__ */ new Map();
1909
+ for (const operation of catalogValue) {
1910
+ if (!isRecord(operation) || typeof operation.operationId !== "string" || typeof operation.sideEffect !== "string" || catalog.has(operation.operationId)) throw new Error("commercial_operation_contract_invalid");
1911
+ catalog.set(operation.operationId, operation);
1912
+ }
1913
+ const policies = dcmValue.capabilities.operations.map((operation) => {
1914
+ if (!isRecord(operation) || typeof operation.operationId !== "string" || !["none", "db", "fs", "network", "mixed"].includes(String(operation.sideEffect)) || !features.has(operation.operationId)) throw new Error("commercial_operation_contract_invalid");
1915
+ const catalogOperation = catalog.get(operation.operationId);
1916
+ if (!catalogOperation || catalogOperation.sideEffect !== operation.sideEffect) {
1917
+ throw new Error("commercial_operation_contract_invalid");
1918
+ }
1919
+ return Object.freeze({
1920
+ operationId: operation.operationId,
1921
+ requiredFeatureIds: features.get(operation.operationId),
1922
+ sideEffect: operation.sideEffect,
1923
+ ...isRecord(operation.safety) ? {
1924
+ safety: Object.freeze({
1925
+ destructive: operation.safety.destructive === true,
1926
+ confirmationRequired: operation.safety.confirmationRequired === true,
1927
+ applyRequired: operation.safety.applyRequired === true
1928
+ })
1929
+ } : {}
1930
+ });
1931
+ });
1932
+ if (catalog.size !== policies.length || features.size !== policies.length) {
1933
+ throw new Error("commercial_operation_contract_invalid");
1934
+ }
1935
+ return Object.freeze(policies);
1936
+ }
1937
+ function loadCommercialAdmissionSnapshot(configFile, freeDomains, now = /* @__PURE__ */ new Date(), generation) {
1938
+ const config = parseConfig(configFile);
1939
+ const active = readVerifiedActiveCommercialArtifact({
1940
+ storeRoot: config.storeRoot,
1941
+ ...commercialIntegrityReadOptions(config.storeRoot),
1942
+ trustKeys: parseReleaseTrustBundleFile(config.releaseTrustBundle),
1943
+ now,
1944
+ expectedIdentity: {
1945
+ installationId: config.installationId,
1946
+ hostInstanceId: config.hostInstanceId
1947
+ }
1948
+ });
1949
+ if (!active) throw new Error("commercial_artifact_not_active");
1950
+ const extension = active.manifest.envelope.payload.extensions[config.extensionNamespace];
1951
+ if (!isRecord(extension) || extension.releaseTier !== "commercial" || !Array.isArray(extension.productIds) || !extension.productIds.includes(config.productId)) throw new Error("commercial_release_extension_invalid");
1952
+ const hostProjection = extension.hostProjection;
1953
+ if (!isRecord(hostProjection)) throw new Error("commercial_release_extension_invalid");
1954
+ exactKeys(
1955
+ hostProjection,
1956
+ ["manifestExport", "pluginFactory"],
1957
+ "commercial_release_extension_invalid"
1958
+ );
1959
+ const pluginFactory = text(
1960
+ hostProjection.pluginFactory,
1961
+ "commercial_release_extension_invalid"
1962
+ );
1963
+ const manifestExport = text(
1964
+ hostProjection.manifestExport,
1965
+ "commercial_release_extension_invalid"
1966
+ );
1967
+ const operations = parseOperations(
1968
+ active.dcmBytes,
1969
+ active.operationCatalogBytes,
1970
+ config.domain,
1971
+ extension
1972
+ );
1973
+ const token = readFileSync(safeRegularFile(config.leaseFile, "entitlement_lease_file_invalid"), "utf8").trim();
1974
+ const lease = verifyEntitlementLease({
1975
+ token,
1976
+ trustKeys: parseLeaseTrustBundle(config.leaseTrustBundle),
1977
+ issuer: config.issuer,
1978
+ now,
1979
+ expected: {
1980
+ tenantId: config.tenantId,
1981
+ installationId: config.installationId,
1982
+ productId: config.productId,
1983
+ domain: config.domain,
1984
+ manifestDigest: active.manifest.manifestDigest,
1985
+ closureDigest: active.receipt.closureDigest,
1986
+ ...config.entitlementEpoch === null ? {} : {
1987
+ entitlementEpoch: config.entitlementEpoch
1988
+ },
1989
+ ...config.minimumRevocationEpoch === null ? {} : {
1990
+ minimumRevocationEpoch: config.minimumRevocationEpoch
1991
+ },
1992
+ ...config.leaseMode === null ? {} : { leaseMode: config.leaseMode },
1993
+ ...config.installationKeyThumbprint === null ? {} : {
1994
+ installationKeyThumbprint: config.installationKeyThumbprint
1995
+ },
1996
+ ...config.activationChallengeDigest === null ? {} : {
1997
+ activationChallengeDigest: config.activationChallengeDigest
1998
+ }
1999
+ }
2000
+ });
2001
+ if (config.schemaVersion === 2) {
2002
+ if (lease.claims.schemaVersion !== 2 || config.installationPrivateKeyFile === null || config.installationKeyThumbprint === null || config.activationChallengeDigest === null) throw new Error("commercial_installation_possession_invalid");
2003
+ verifyOfflineInstallationPossessionAtLoad({
2004
+ installationPrivateKeyFile: config.installationPrivateKeyFile,
2005
+ installationKeyThumbprint: config.installationKeyThumbprint,
2006
+ activationChallengeDigest: config.activationChallengeDigest,
2007
+ installationId: config.installationId,
2008
+ hostInstanceId: config.hostInstanceId,
2009
+ leaseToken: token,
2010
+ receipt: {
2011
+ receiptId: active.receipt.receiptId,
2012
+ releaseId: active.receipt.releaseId,
2013
+ manifestDigest: active.receipt.manifestDigest,
2014
+ closureDigest: active.receipt.closureDigest
2015
+ },
2016
+ now
2017
+ });
2018
+ }
2019
+ const operationIds = new Set(operations.map((operation) => operation.operationId));
2020
+ if (active.manifest.envelope.payload.degradedOperationIds.some(
2021
+ (operationId) => !operationIds.has(operationId)
2022
+ )) throw new Error("commercial_operation_contract_invalid");
2023
+ const manifestEntrypoint = active.receipt.resolvedEntrypoints.manifestProviders[0] ?? active.receipt.resolvedEntrypoints.dcmProviders[0];
2024
+ if (!manifestEntrypoint) throw new Error("commercial_runtime_entrypoint_invalid");
2025
+ const snapshot = buildAdmittedDomainSnapshot({
2026
+ generation: generation ?? Math.max(2, active.receipt.activation.generation + 1),
2027
+ freeDomains,
2028
+ commercialDomains: [{
2029
+ domain: config.domain,
2030
+ productId: config.productId,
2031
+ receipt: active.receipt,
2032
+ manifest: active.manifest,
2033
+ lease,
2034
+ operations
2035
+ }],
2036
+ now
2037
+ });
2038
+ return Object.freeze({
2039
+ snapshot,
2040
+ runtime: Object.freeze({
2041
+ domain: config.domain,
2042
+ pluginModule: safeRuntimeEntrypoint(
2043
+ config.storeRoot,
2044
+ active.receipt.resolvedEntrypoints.plugin
2045
+ ),
2046
+ pluginFactory,
2047
+ manifestModule: safeRuntimeEntrypoint(config.storeRoot, manifestEntrypoint),
2048
+ manifestExport
2049
+ })
2050
+ });
2051
+ }
2052
+ function readCommercialAdmissionIntegritySchedule(configFile, now = /* @__PURE__ */ new Date()) {
2053
+ const config = parseConfig(configFile);
2054
+ const options = commercialIntegrityReadOptions(config.storeRoot, "scheduled");
2055
+ if (!options.integrityStateRoot) {
2056
+ throw new Error("commercial_integrity_scheduler_requires_managed_store");
2057
+ }
2058
+ return readCommercialIntegrityVerificationSchedule(options.integrityStateRoot, now);
2059
+ }
2060
+ function resolveCommercialIntegrityWorkerInput(configFile) {
2061
+ const config = parseConfig(configFile);
2062
+ const options = commercialIntegrityReadOptions(config.storeRoot, "scheduled");
2063
+ if (!options.integrityStateRoot) {
2064
+ throw new Error("commercial_integrity_scheduler_requires_managed_store");
2065
+ }
2066
+ return Object.freeze({
2067
+ storeRoot: config.storeRoot,
2068
+ integrityStateRoot: options.integrityStateRoot,
2069
+ trustKeys: parseReleaseTrustBundleFile(config.releaseTrustBundle),
2070
+ expectedIdentity: Object.freeze({
2071
+ installationId: config.installationId,
2072
+ hostInstanceId: config.hostInstanceId
2073
+ })
2074
+ });
2075
+ }
2076
+
2077
+ export { loadCommercialAdmissionSnapshot, parseReleaseTrustBundleFile, readCommercialAdmissionIntegritySchedule, resolveCommercialIntegrityWorkerInput, verifyOfflineInstallationPossessionAtLoad };