@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,1034 @@
1
+ import { createPublicKey, verify, createHash } from 'node:crypto';
2
+
3
+ const RELEASE_MANIFEST_OBJECT_TYPE = "aops-release-closure-manifest";
4
+ const RELEASE_MANIFEST_CANONICALIZATION = "RFC8785-JCS-v1";
5
+ const RELEASE_MANIFEST_PURPOSE = "urn:aops:artifact-installer:v1";
6
+ const RELEASE_MANIFEST_CRITICAL_FIELDS = Object.freeze([
7
+ "objectType",
8
+ "payloadCanonicalization",
9
+ "schemaVersion"
10
+ ]);
11
+ const SHA256 = /^sha256:[a-f0-9]{64}$/;
12
+ const SHA512_INTEGRITY = /^sha512-[A-Za-z0-9+/]{86}==$/;
13
+ const RELEASE_KID = /^release\/[A-Za-z0-9._~-]{1,160}$/;
14
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
15
+ const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
16
+ const SOURCE_COMMIT = /^[a-f0-9]{40,64}$/;
17
+ const NAMESPACE = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)+$/;
18
+ const COMMERCIAL_LAUNCH_ROLES = Object.freeze([
19
+ "runtime-node",
20
+ "cli",
21
+ "server",
22
+ "cockpit"
23
+ ]);
24
+ const verifiedReleaseManifests = /* @__PURE__ */ new WeakSet();
25
+ class CommercialArtifactError extends Error {
26
+ stage;
27
+ decision;
28
+ reason;
29
+ constructor(stage, reason, decision = "deny") {
30
+ super(`${stage}:${reason}`);
31
+ this.name = "CommercialArtifactError";
32
+ this.stage = stage;
33
+ this.reason = reason;
34
+ this.decision = decision;
35
+ }
36
+ }
37
+ function fail$3(stage, reason) {
38
+ throw new CommercialArtifactError(stage, reason);
39
+ }
40
+ function isRecord$1(value) {
41
+ return value !== null && typeof value === "object" && !Array.isArray(value);
42
+ }
43
+ function canonicalCommercialJson(value) {
44
+ if (value === null || typeof value === "boolean" || typeof value === "string")
45
+ return JSON.stringify(value);
46
+ if (typeof value === "number") {
47
+ if (!Number.isFinite(value))
48
+ fail$3("manifest-schema", "non_finite_number");
49
+ return JSON.stringify(value);
50
+ }
51
+ if (Array.isArray(value))
52
+ return `[${value.map((entry) => canonicalCommercialJson(entry)).join(",")}]`;
53
+ if (!isRecord$1(value))
54
+ fail$3("manifest-schema", "non_json_value");
55
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalCommercialJson(value[key])}`).join(",")}}`;
56
+ }
57
+ function sha256Commercial(value) {
58
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
59
+ }
60
+ function runtimeVersionTuple(value) {
61
+ const match = /^([0-9]+)\.([0-9]+)\.([0-9]+)$/.exec(value);
62
+ if (!match)
63
+ fail$3("artifact-preflight", "bundled_runtime_version_invalid");
64
+ const tuple = match.slice(1).map(Number);
65
+ if (tuple.some((part) => !Number.isSafeInteger(part) || part < 0)) {
66
+ fail$3("artifact-preflight", "bundled_runtime_version_invalid");
67
+ }
68
+ return tuple;
69
+ }
70
+ function compareRuntimeVersions(left, right) {
71
+ for (let index = 0; index < left.length; index += 1) {
72
+ if (left[index] !== right[index])
73
+ return left[index] < right[index] ? -1 : 1;
74
+ }
75
+ return 0;
76
+ }
77
+ function assertCommercialRuntimeCompatible(version, supportedRange) {
78
+ const current = runtimeVersionTuple(version);
79
+ const clauses = supportedRange.trim().split(/\s+/);
80
+ const compatible = clauses.length > 0 && clauses.every((clause) => {
81
+ const match = /^(>=|>|<=|<|=)?([0-9]+\.[0-9]+\.[0-9]+)$/.exec(clause);
82
+ if (!match)
83
+ return false;
84
+ const comparison = compareRuntimeVersions(current, runtimeVersionTuple(match[2]));
85
+ if (match[1] === ">=")
86
+ return comparison >= 0;
87
+ if (match[1] === ">")
88
+ return comparison > 0;
89
+ if (match[1] === "<=")
90
+ return comparison <= 0;
91
+ if (match[1] === "<")
92
+ return comparison < 0;
93
+ return comparison === 0;
94
+ });
95
+ if (!compatible)
96
+ fail$3("artifact-preflight", "bundled_runtime_incompatible");
97
+ }
98
+ function exactObject(value, keys, reason) {
99
+ if (!isRecord$1(value))
100
+ fail$3("manifest-schema", reason);
101
+ const actual = Object.keys(value).sort();
102
+ const expected = [...keys].sort();
103
+ if (canonicalCommercialJson(actual) !== canonicalCommercialJson(expected))
104
+ fail$3("manifest-schema", reason);
105
+ }
106
+ function requiredString(record, key, reason) {
107
+ const value = record[key];
108
+ if (typeof value !== "string" || !value || value !== value.trim() || value.length > 1024) {
109
+ fail$3("manifest-schema", reason);
110
+ }
111
+ if (/[\u0000-\u001f\u007f]/.test(value))
112
+ fail$3("manifest-schema", reason);
113
+ return value;
114
+ }
115
+ function digest(record, key, reason) {
116
+ const value = requiredString(record, key, reason);
117
+ if (!SHA256.test(value))
118
+ fail$3("manifest-schema", reason);
119
+ return value;
120
+ }
121
+ function timestamp(record, key, reason) {
122
+ const value = requiredString(record, key, reason);
123
+ const millis = Date.parse(value);
124
+ if (!Number.isFinite(millis) || new Date(millis).toISOString() !== value)
125
+ fail$3("manifest-schema", reason);
126
+ return value;
127
+ }
128
+ function sortedUniqueStrings(record, key, reason, options = {}) {
129
+ const value = record[key];
130
+ if (!Array.isArray(value) || !options.allowEmpty && value.length === 0)
131
+ fail$3("manifest-schema", reason);
132
+ const strings = value.map((entry) => {
133
+ if (typeof entry !== "string" || !entry || entry !== entry.trim() || entry.length > 1024) {
134
+ fail$3("manifest-schema", reason);
135
+ }
136
+ if (options.validate && !options.validate(entry))
137
+ fail$3("manifest-schema", reason);
138
+ return entry;
139
+ });
140
+ const expected = [...new Set(strings)].sort();
141
+ if (canonicalCommercialJson(strings) !== canonicalCommercialJson(expected))
142
+ fail$3("manifest-schema", reason);
143
+ return Object.freeze(strings);
144
+ }
145
+ function safeEntrypoint(value) {
146
+ if (pathLikeAbsolute(value) || value.includes("\\") || value.includes("\0"))
147
+ return false;
148
+ const separator = value.indexOf(":");
149
+ if (separator < 1)
150
+ return false;
151
+ const packageName = value.slice(0, separator);
152
+ const relative = value.slice(separator + 1);
153
+ return PACKAGE_NAME.test(packageName) && relative.length > 0 && relative.split("/").every((segment) => segment && segment !== "." && segment !== "..");
154
+ }
155
+ function safePackageRelativeEntrypoint(value) {
156
+ return value.length > 0 && value.length <= 4096 && !pathLikeAbsolute(value) && !value.includes("\\") && !value.includes("\0") && value.split("/").every((segment) => segment && segment !== "." && segment !== "..");
157
+ }
158
+ function validRuntimeRange(value) {
159
+ const clauses = value.trim().split(/\s+/);
160
+ return clauses.length > 0 && clauses.every((clause) => /^(?:>=|>|<=|<|=)?[0-9]+\.[0-9]+\.[0-9]+$/.test(clause));
161
+ }
162
+ function pathLikeAbsolute(value) {
163
+ return value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
164
+ }
165
+ function assertNoLocalMaterial(value, reason) {
166
+ if (pathLikeAbsolute(value) || /(?:localhost|127\.0\.0\.1|password|token|secret)=/i.test(value)) {
167
+ fail$3("manifest-schema", reason);
168
+ }
169
+ }
170
+ function parseClosure(value) {
171
+ if (!Array.isArray(value) || value.length === 0)
172
+ fail$3("manifest-schema", "closure_invalid");
173
+ const rows = value.map((candidate) => {
174
+ exactObject(candidate, [
175
+ "packageName",
176
+ "version",
177
+ "artifactSha256",
178
+ "packageIntegrity",
179
+ "filesDigest",
180
+ "launchRole",
181
+ "launchEntrypoint",
182
+ "runtimeRange"
183
+ ], "closure_entry_invalid");
184
+ const packageName = requiredString(candidate, "packageName", "closure_package_invalid");
185
+ const version = requiredString(candidate, "version", "closure_version_invalid");
186
+ const packageIntegrity = requiredString(candidate, "packageIntegrity", "closure_integrity_invalid");
187
+ if (!PACKAGE_NAME.test(packageName))
188
+ fail$3("manifest-schema", "closure_package_invalid");
189
+ if (!VERSION.test(version))
190
+ fail$3("manifest-schema", "closure_version_invalid");
191
+ if (!SHA512_INTEGRITY.test(packageIntegrity))
192
+ fail$3("manifest-schema", "closure_integrity_invalid");
193
+ const launchRole = candidate.launchRole;
194
+ if (launchRole !== null && !COMMERCIAL_LAUNCH_ROLES.includes(launchRole)) {
195
+ fail$3("manifest-schema", "closure_launch_role_invalid");
196
+ }
197
+ const launchEntrypoint = candidate.launchEntrypoint;
198
+ const runtimeRange = candidate.runtimeRange;
199
+ if (launchRole === null) {
200
+ if (launchEntrypoint !== null || runtimeRange !== null) {
201
+ fail$3("manifest-schema", "closure_launch_binding_invalid");
202
+ }
203
+ } else {
204
+ if (typeof launchEntrypoint !== "string" || !safePackageRelativeEntrypoint(launchEntrypoint)) {
205
+ fail$3("manifest-schema", "closure_launch_entrypoint_invalid");
206
+ }
207
+ if (launchRole === "runtime-node") {
208
+ if (runtimeRange !== null)
209
+ fail$3("manifest-schema", "closure_runtime_range_invalid");
210
+ } else if (typeof runtimeRange !== "string" || !validRuntimeRange(runtimeRange)) {
211
+ fail$3("manifest-schema", "closure_runtime_range_invalid");
212
+ }
213
+ }
214
+ return Object.freeze({
215
+ packageName,
216
+ version,
217
+ artifactSha256: digest(candidate, "artifactSha256", "closure_artifact_digest_invalid"),
218
+ packageIntegrity,
219
+ filesDigest: digest(candidate, "filesDigest", "closure_files_digest_invalid"),
220
+ launchRole,
221
+ launchEntrypoint,
222
+ runtimeRange
223
+ });
224
+ });
225
+ const identities = rows.map((row) => `${row.packageName}@${row.version}`);
226
+ if (canonicalCommercialJson(identities) !== canonicalCommercialJson([...new Set(identities)].sort())) {
227
+ fail$3("manifest-schema", "closure_order_invalid");
228
+ }
229
+ const roles = rows.filter((row) => row.launchRole !== null).map((row) => row.launchRole);
230
+ if (roles.filter((role) => role === "runtime-node").length !== 1) {
231
+ fail$3("manifest-schema", "closure_runtime_role_invalid");
232
+ }
233
+ if (new Set(roles).size !== roles.length)
234
+ fail$3("manifest-schema", "closure_launch_role_duplicate");
235
+ return Object.freeze(rows);
236
+ }
237
+ function parseRelease(value) {
238
+ exactObject(value, ["packageName", "version", "releaseId", "sourceRepositoryId", "sourceCommit", "sourceTag"], "release_invalid");
239
+ const packageName = requiredString(value, "packageName", "release_package_invalid");
240
+ const version = requiredString(value, "version", "release_version_invalid");
241
+ const sourceRepositoryId = requiredString(value, "sourceRepositoryId", "release_repository_invalid");
242
+ const sourceCommit = requiredString(value, "sourceCommit", "release_commit_invalid");
243
+ const sourceTag = requiredString(value, "sourceTag", "release_tag_invalid");
244
+ if (!PACKAGE_NAME.test(packageName))
245
+ fail$3("manifest-schema", "release_package_invalid");
246
+ if (!VERSION.test(version))
247
+ fail$3("manifest-schema", "release_version_invalid");
248
+ if (!SOURCE_COMMIT.test(sourceCommit))
249
+ fail$3("manifest-schema", "release_commit_invalid");
250
+ assertNoLocalMaterial(sourceRepositoryId, "release_repository_invalid");
251
+ assertNoLocalMaterial(sourceTag, "release_tag_invalid");
252
+ return Object.freeze({
253
+ packageName,
254
+ version,
255
+ releaseId: requiredString(value, "releaseId", "release_id_invalid"),
256
+ sourceRepositoryId,
257
+ sourceCommit,
258
+ sourceTag
259
+ });
260
+ }
261
+ function parseMigrationCapsules(value) {
262
+ if (!Array.isArray(value))
263
+ fail$3("manifest-schema", "migration_capsules_invalid");
264
+ const rows = value.map((candidate) => {
265
+ exactObject(candidate, ["capsuleId", "version", "digest", "semanticContractDigest", "readbackPolicy", "rollbackPolicy"], "migration_capsule_invalid");
266
+ const version = requiredString(candidate, "version", "migration_capsule_version_invalid");
267
+ if (!VERSION.test(version))
268
+ fail$3("manifest-schema", "migration_capsule_version_invalid");
269
+ return Object.freeze({
270
+ capsuleId: requiredString(candidate, "capsuleId", "migration_capsule_id_invalid"),
271
+ version,
272
+ digest: digest(candidate, "digest", "migration_capsule_digest_invalid"),
273
+ semanticContractDigest: digest(candidate, "semanticContractDigest", "migration_semantic_digest_invalid"),
274
+ readbackPolicy: requiredString(candidate, "readbackPolicy", "migration_readback_policy_invalid"),
275
+ rollbackPolicy: requiredString(candidate, "rollbackPolicy", "migration_rollback_policy_invalid")
276
+ });
277
+ });
278
+ const identities = rows.map((row) => `${row.capsuleId}@${row.version}`);
279
+ if (canonicalCommercialJson(identities) !== canonicalCommercialJson([...new Set(identities)].sort())) {
280
+ fail$3("manifest-schema", "migration_capsule_order_invalid");
281
+ }
282
+ return Object.freeze(rows);
283
+ }
284
+ function parseReleaseClosureManifest(value, options = {}) {
285
+ exactObject(value, [
286
+ "manifestId",
287
+ "publisherId",
288
+ "issuedAt",
289
+ "notBefore",
290
+ "notAfter",
291
+ "release",
292
+ "closure",
293
+ "closureDigest",
294
+ "packlistDigest",
295
+ "sbom",
296
+ "entrypoints",
297
+ "dcm",
298
+ "hostAbi",
299
+ "migrationCapsules",
300
+ "degradedOperationIds",
301
+ "extensions"
302
+ ], "release_manifest_invalid");
303
+ const issuedAt = timestamp(value, "issuedAt", "issued_at_invalid");
304
+ const notBefore = timestamp(value, "notBefore", "not_before_invalid");
305
+ const notAfter = timestamp(value, "notAfter", "not_after_invalid");
306
+ if (!(Date.parse(notBefore) <= Date.parse(issuedAt) && Date.parse(issuedAt) < Date.parse(notAfter))) {
307
+ fail$3("manifest-schema", "manifest_time_order_invalid");
308
+ }
309
+ const release = parseRelease(value.release);
310
+ const closure = parseClosure(value.closure);
311
+ if (!closure.some((row) => row.packageName === release.packageName && row.version === release.version)) {
312
+ fail$3("manifest-schema", "release_missing_from_closure");
313
+ }
314
+ const closureDigest = digest(value, "closureDigest", "closure_digest_invalid");
315
+ if (sha256Commercial(canonicalCommercialJson(closure)) !== closureDigest) {
316
+ fail$3("manifest-closure", "closure_digest_mismatch");
317
+ }
318
+ exactObject(value.sbom, ["format", "digest"], "sbom_invalid");
319
+ const sbom = Object.freeze({
320
+ format: requiredString(value.sbom, "format", "sbom_format_invalid"),
321
+ digest: digest(value.sbom, "digest", "sbom_digest_invalid")
322
+ });
323
+ exactObject(value.entrypoints, ["plugin", "dcmProviders", "manifestProviders", "resources"], "entrypoints_invalid");
324
+ const plugin = requiredString(value.entrypoints, "plugin", "plugin_entrypoint_invalid");
325
+ if (!safeEntrypoint(plugin))
326
+ fail$3("manifest-schema", "plugin_entrypoint_invalid");
327
+ const entrypoints = Object.freeze({
328
+ plugin,
329
+ dcmProviders: sortedUniqueStrings(value.entrypoints, "dcmProviders", "dcm_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint }),
330
+ manifestProviders: sortedUniqueStrings(value.entrypoints, "manifestProviders", "manifest_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint }),
331
+ resources: sortedUniqueStrings(value.entrypoints, "resources", "resource_entrypoints_invalid", { allowEmpty: true, validate: safeEntrypoint })
332
+ });
333
+ exactObject(value.dcm, ["digest", "operationCatalogDigest"], "dcm_invalid");
334
+ const dcm = Object.freeze({
335
+ digest: digest(value.dcm, "digest", "dcm_digest_invalid"),
336
+ operationCatalogDigest: digest(value.dcm, "operationCatalogDigest", "operation_catalog_digest_invalid")
337
+ });
338
+ exactObject(value.hostAbi, ["protocolVersion", "supportedRange"], "host_abi_invalid");
339
+ const hostAbi = Object.freeze({
340
+ protocolVersion: requiredString(value.hostAbi, "protocolVersion", "host_abi_protocol_invalid"),
341
+ supportedRange: requiredString(value.hostAbi, "supportedRange", "host_abi_range_invalid")
342
+ });
343
+ const degradedOperationIds = sortedUniqueStrings(value, "degradedOperationIds", "degraded_operations_invalid", { allowEmpty: true });
344
+ if (options.knownOperationIds) {
345
+ for (const operationId of degradedOperationIds) {
346
+ if (!options.knownOperationIds.has(operationId))
347
+ fail$3("manifest-schema", "unknown_degraded_operation");
348
+ }
349
+ }
350
+ if (!isRecord$1(value.extensions))
351
+ fail$3("manifest-schema", "extensions_invalid");
352
+ for (const [namespace, extension] of Object.entries(value.extensions)) {
353
+ if (!NAMESPACE.test(namespace) || !isRecord$1(extension))
354
+ fail$3("manifest-schema", "extension_invalid");
355
+ canonicalCommercialJson(extension);
356
+ }
357
+ return Object.freeze({
358
+ manifestId: requiredString(value, "manifestId", "manifest_id_invalid"),
359
+ publisherId: requiredString(value, "publisherId", "publisher_id_invalid"),
360
+ issuedAt,
361
+ notBefore,
362
+ notAfter,
363
+ release,
364
+ closure,
365
+ closureDigest,
366
+ packlistDigest: digest(value, "packlistDigest", "packlist_digest_invalid"),
367
+ sbom,
368
+ entrypoints,
369
+ dcm,
370
+ hostAbi,
371
+ migrationCapsules: parseMigrationCapsules(value.migrationCapsules),
372
+ degradedOperationIds,
373
+ extensions: Object.freeze({ ...value.extensions })
374
+ });
375
+ }
376
+ function signatureInput(envelope) {
377
+ return canonicalCommercialJson(envelope);
378
+ }
379
+ function createReleaseManifestSigningInput(envelope) {
380
+ return Buffer.from(signatureInput(envelope), "utf8");
381
+ }
382
+ function parseReleaseManifestEnvelope(value, options = {}) {
383
+ exactObject(value, ["schemaVersion", "objectType", "payloadCanonicalization", "payloadDigest", "signingHeader", "signature", "payload"], "manifest_envelope_invalid");
384
+ if (value.schemaVersion !== 2)
385
+ fail$3("manifest-schema", "unsupported_schema_version");
386
+ if (value.objectType !== RELEASE_MANIFEST_OBJECT_TYPE)
387
+ fail$3("manifest-schema", "object_type_mismatch");
388
+ if (value.payloadCanonicalization !== RELEASE_MANIFEST_CANONICALIZATION) {
389
+ fail$3("manifest-schema", "canonicalization_unsupported");
390
+ }
391
+ exactObject(value.signingHeader, ["purpose", "alg", "kid", "crit"], "signing_header_invalid");
392
+ if (value.signingHeader.purpose !== RELEASE_MANIFEST_PURPOSE)
393
+ fail$3("manifest-signature", "key_purpose_mismatch");
394
+ if (value.signingHeader.alg !== "EdDSA")
395
+ fail$3("manifest-signature", "algorithm_not_allowed");
396
+ const kid = requiredString(value.signingHeader, "kid", "signing_kid_invalid");
397
+ if (!RELEASE_KID.test(kid))
398
+ fail$3("manifest-signature", "key_purpose_mismatch");
399
+ const crit = sortedUniqueStrings(value.signingHeader, "crit", "critical_fields_invalid", { allowEmpty: true });
400
+ if (canonicalCommercialJson(crit) !== canonicalCommercialJson(RELEASE_MANIFEST_CRITICAL_FIELDS)) {
401
+ fail$3("manifest-signature", "unknown_critical_field");
402
+ }
403
+ const signature = requiredString(value, "signature", "signature_invalid");
404
+ if (!/^[A-Za-z0-9_-]{86}$/.test(signature))
405
+ fail$3("manifest-signature", "signature_invalid");
406
+ const payload = parseReleaseClosureManifest(value.payload, options);
407
+ const payloadDigest = digest(value, "payloadDigest", "payload_digest_invalid");
408
+ if (sha256Commercial(canonicalCommercialJson(payload)) !== payloadDigest) {
409
+ fail$3("manifest-digest", "payload_digest_mismatch");
410
+ }
411
+ return Object.freeze({
412
+ schemaVersion: 2,
413
+ objectType: RELEASE_MANIFEST_OBJECT_TYPE,
414
+ payloadCanonicalization: RELEASE_MANIFEST_CANONICALIZATION,
415
+ payloadDigest,
416
+ signingHeader: Object.freeze({
417
+ purpose: RELEASE_MANIFEST_PURPOSE,
418
+ alg: "EdDSA",
419
+ kid,
420
+ crit
421
+ }),
422
+ signature,
423
+ payload
424
+ });
425
+ }
426
+ function decodeBase64Url(value) {
427
+ try {
428
+ return Buffer.from(value, "base64url");
429
+ } catch {
430
+ fail$3("manifest-signature", "signature_invalid");
431
+ }
432
+ }
433
+ function verifyReleaseManifestEnvelope(value, options) {
434
+ const envelope = parseReleaseManifestEnvelope(value, { knownOperationIds: options.knownOperationIds });
435
+ const duplicateKids = options.trustKeys.filter((key) => key.kid === envelope.signingHeader.kid);
436
+ if (duplicateKids.length !== 1)
437
+ fail$3("manifest-signature", duplicateKids.length ? "duplicate_trust_key" : "unknown_signing_key");
438
+ const trustKey = duplicateKids[0];
439
+ if (trustKey.purpose !== RELEASE_MANIFEST_PURPOSE || trustKey.alg !== "EdDSA" || !RELEASE_KID.test(trustKey.kid)) {
440
+ fail$3("manifest-signature", "key_purpose_mismatch");
441
+ }
442
+ const now = options.now ?? /* @__PURE__ */ new Date();
443
+ const nowMillis = now.getTime();
444
+ if (!Number.isFinite(nowMillis))
445
+ fail$3("manifest-validity", "clock_invalid");
446
+ if (trustKey.status !== void 0 && !["active", "verify-only", "retired", "revoked"].includes(trustKey.status))
447
+ fail$3("manifest-signature", "release_key_status_invalid");
448
+ if (trustKey.status === "retired" || trustKey.status === "revoked") {
449
+ fail$3("manifest-signature", "release_key_not_accepted");
450
+ }
451
+ const keyNotBefore = trustKey.notBefore === void 0 ? null : Date.parse(trustKey.notBefore);
452
+ const keyNotAfter = trustKey.notAfter === void 0 ? null : Date.parse(trustKey.notAfter);
453
+ if (keyNotBefore !== null && !Number.isFinite(keyNotBefore) || keyNotAfter !== null && !Number.isFinite(keyNotAfter) || keyNotBefore !== null && keyNotAfter !== null && keyNotBefore >= keyNotAfter)
454
+ fail$3("manifest-signature", "release_key_time_invalid");
455
+ if (keyNotBefore !== null && nowMillis < keyNotBefore) {
456
+ fail$3("manifest-signature", "release_key_not_yet_valid");
457
+ }
458
+ if (keyNotAfter !== null && nowMillis >= keyNotAfter) {
459
+ fail$3("manifest-signature", "release_key_expired");
460
+ }
461
+ let publicKey;
462
+ try {
463
+ publicKey = createPublicKey(trustKey.publicKeyPem);
464
+ } catch {
465
+ fail$3("manifest-signature", "trust_key_invalid");
466
+ }
467
+ if (publicKey.asymmetricKeyType !== "ed25519")
468
+ fail$3("manifest-signature", "algorithm_not_allowed");
469
+ const unsigned = {
470
+ schemaVersion: envelope.schemaVersion,
471
+ objectType: envelope.objectType,
472
+ payloadCanonicalization: envelope.payloadCanonicalization,
473
+ payloadDigest: envelope.payloadDigest,
474
+ signingHeader: envelope.signingHeader,
475
+ payload: envelope.payload
476
+ };
477
+ if (!verify(null, createReleaseManifestSigningInput(unsigned), publicKey, decodeBase64Url(envelope.signature))) {
478
+ fail$3("manifest-signature", "bad_signature");
479
+ }
480
+ if (nowMillis < Date.parse(envelope.payload.notBefore))
481
+ fail$3("manifest-validity", "manifest_not_yet_valid");
482
+ if (nowMillis >= Date.parse(envelope.payload.notAfter))
483
+ fail$3("manifest-validity", "manifest_expired");
484
+ const verified = Object.freeze({
485
+ envelope,
486
+ manifestDigest: sha256Commercial(canonicalCommercialJson(envelope)),
487
+ payloadDigest: envelope.payloadDigest,
488
+ verifiedAt: now.toISOString(),
489
+ signerKid: envelope.signingHeader.kid
490
+ });
491
+ verifiedReleaseManifests.add(verified);
492
+ return verified;
493
+ }
494
+ const verifiedRevocationSnapshots = /* @__PURE__ */ new WeakSet();
495
+ function fail$2(stage, reason) {
496
+ throw new CommercialArtifactError(stage, reason);
497
+ }
498
+ function text$1(value, maximum = 512) {
499
+ if (typeof value !== "string" || value !== value.trim() || value.length === 0 || value.length > maximum || /[\u0000-\u001f\u007f]/u.test(value))
500
+ fail$2("revocation-snapshot-schema", "revocation_snapshot_schema_invalid");
501
+ return value;
502
+ }
503
+ function assertVerifiedRevocationSnapshot(value) {
504
+ if (!verifiedRevocationSnapshots.has(value)) {
505
+ fail$2("revocation-snapshot-authority", "unverified_revocation_snapshot_identity");
506
+ }
507
+ }
508
+ function assertRevocationSnapshotCovers(input) {
509
+ assertVerifiedRevocationSnapshot(input.snapshot);
510
+ const claims = input.snapshot.claims;
511
+ if (claims.iss !== input.issuer) {
512
+ fail$2("revocation-snapshot-coverage", "revocation_snapshot_issuer_invalid");
513
+ }
514
+ if (claims.tenantId !== input.tenantId) {
515
+ fail$2("revocation-snapshot-coverage", "revocation_snapshot_tenant_not_covered");
516
+ }
517
+ if (claims.coverage.kind === "installation" && claims.coverage.installationId !== input.installationId || claims.coverage.kind === "product" && !claims.coverage.productIds.includes(input.productId))
518
+ fail$2("revocation-snapshot-coverage", "revocation_snapshot_scope_not_covered");
519
+ }
520
+ function evaluateRevocationSnapshotLease(input) {
521
+ assertVerifiedRevocationSnapshot(input.snapshot);
522
+ const leaseId = text$1(input.leaseId, 200);
523
+ const common = {
524
+ snapshotOrdinal: input.snapshot.claims.snapshotOrdinal,
525
+ revocationEpoch: input.snapshot.claims.revocationEpoch
526
+ };
527
+ if (input.snapshot.claims.revokedLeaseIds.includes(leaseId)) {
528
+ return Object.freeze({ status: "revoked", ...common });
529
+ }
530
+ if (input.snapshot.mode === "retained-deny-only") {
531
+ return Object.freeze({
532
+ status: "unknown",
533
+ reason: "snapshot_expired",
534
+ ...common
535
+ });
536
+ }
537
+ return Object.freeze({ status: "not-revoked", ...common });
538
+ }
539
+ const ENTITLEMENT_LEASE_ALGORITHM = "EdDSA";
540
+ const ENTITLEMENT_LEASE_TYPE = "aops-entitlement-lease+jwt";
541
+ const ENTITLEMENT_LEASE_PURPOSE = "urn:aops:commercial-admission:v1";
542
+ const ENTITLEMENT_LEASE_SCHEMA_VERSION = 1;
543
+ const ENTITLEMENT_LEASE_BOUND_SCHEMA_VERSION = 2;
544
+ const OFFLINE_LEASE_MAX_FULL_WINDOW_SECONDS = 90 * 24 * 60 * 60;
545
+ const OFFLINE_LEASE_MAX_DEGRADED_WINDOW_SECONDS = 14 * 24 * 60 * 60;
546
+ const UNSIGNED_REVOCATION_LIST_REFUSAL = Object.freeze({
547
+ stage: "lease-revocation-migration",
548
+ reason: "unsigned_revocation_list_refused",
549
+ decision: "quarantine",
550
+ nextAction: "Import and verify a South-signed revocation snapshot; do not retain derived revoked ID lists."
551
+ });
552
+ const MAX_LEASE_BYTES = 32 * 1024;
553
+ const CLOCK_SKEW_SECONDS = 30;
554
+ const SHA256_HEX = /^[a-f0-9]{64}$/;
555
+ const LEASE_KID = /^lease\/[A-Za-z0-9._:/-]+$/;
556
+ const verifiedEntitlementLeases = /* @__PURE__ */ new WeakSet();
557
+ const COMMON_CLAIM_KEYS = Object.freeze([
558
+ "aud",
559
+ "domainConstraints",
560
+ "entitlementEpoch",
561
+ "exp",
562
+ "featureIds",
563
+ "fullUntil",
564
+ "iat",
565
+ "installationId",
566
+ "iss",
567
+ "jti",
568
+ "leaseMode",
569
+ "nbf",
570
+ "productIds",
571
+ "refreshAfter",
572
+ "releaseConstraint",
573
+ "revocationEpoch",
574
+ "schemaVersion",
575
+ "skuId",
576
+ "subscriptionId",
577
+ "tenantId"
578
+ ]);
579
+ const CLAIM_KEYS_V1 = COMMON_CLAIM_KEYS;
580
+ const CLAIM_KEYS_V2 = Object.freeze([
581
+ ...COMMON_CLAIM_KEYS,
582
+ "activationBinding",
583
+ "installationKeyThumbprint"
584
+ ]);
585
+ function fail$1(stage, reason) {
586
+ throw new CommercialArtifactError(stage, reason);
587
+ }
588
+ function isRecord(value) {
589
+ return value !== null && typeof value === "object" && !Array.isArray(value);
590
+ }
591
+ function exactKeys(value, expected, stage) {
592
+ const actual = Object.keys(value).sort();
593
+ const sortedExpected = [...expected].sort();
594
+ if (actual.length !== sortedExpected.length || actual.some((key, index) => key !== sortedExpected[index]))
595
+ fail$1(stage, "lease_schema_invalid");
596
+ }
597
+ function text(value, maximum = 512) {
598
+ if (typeof value !== "string" || value !== value.trim() || value.length === 0 || value.length > maximum)
599
+ fail$1("lease-schema", "lease_schema_invalid");
600
+ return value;
601
+ }
602
+ function integer(value) {
603
+ if (!Number.isSafeInteger(value))
604
+ fail$1("lease-schema", "lease_schema_invalid");
605
+ return value;
606
+ }
607
+ function sortedTexts(value, maximum = 200) {
608
+ if (!Array.isArray(value) || value.length > 512)
609
+ fail$1("lease-schema", "lease_schema_invalid");
610
+ const result = value.map((entry) => text(entry, maximum));
611
+ const sorted = [...result].sort();
612
+ if (new Set(result).size !== result.length || result.some((entry, index) => entry !== sorted[index]))
613
+ fail$1("lease-schema", "lease_schema_invalid");
614
+ return Object.freeze(result);
615
+ }
616
+ function sortedDigests(value) {
617
+ const digests = sortedTexts(value, 64);
618
+ if (digests.some((digest2) => !SHA256_HEX.test(digest2))) {
619
+ fail$1("lease-schema", "lease_schema_invalid");
620
+ }
621
+ return digests;
622
+ }
623
+ function normalizeDigest(value) {
624
+ const digest2 = value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
625
+ if (!SHA256_HEX.test(digest2))
626
+ fail$1("lease-coverage", "release_digest_invalid");
627
+ return digest2;
628
+ }
629
+ function releaseConstraint(value) {
630
+ if (!isRecord(value))
631
+ fail$1("lease-schema", "lease_schema_invalid");
632
+ exactKeys(value, ["manifestDigests", "closureDigests", "versionRange"], "lease-schema");
633
+ const manifestDigests = sortedDigests(value.manifestDigests);
634
+ const closureDigests = sortedDigests(value.closureDigests);
635
+ const versionRange = value.versionRange === null ? null : text(value.versionRange);
636
+ if (manifestDigests.length === 0 && closureDigests.length === 0 && versionRange === null) {
637
+ fail$1("lease-schema", "lease_release_constraint_empty");
638
+ }
639
+ return Object.freeze({ manifestDigests, closureDigests, versionRange });
640
+ }
641
+ function sha256(value) {
642
+ const digest2 = text(value, 64);
643
+ if (!SHA256_HEX.test(digest2))
644
+ fail$1("lease-schema", "lease_schema_invalid");
645
+ return digest2;
646
+ }
647
+ function activationBinding(value, leaseMode) {
648
+ if (!isRecord(value))
649
+ fail$1("lease-schema", "lease_schema_invalid");
650
+ exactKeys(value, ["challengeDigest", "kind"], "lease-schema");
651
+ if (value.kind !== "online" && value.kind !== "offline-challenge") {
652
+ fail$1("lease-schema", "lease_schema_invalid");
653
+ }
654
+ const challengeDigest = value.challengeDigest === null ? null : sha256(value.challengeDigest);
655
+ if (leaseMode === "online" && (value.kind !== "online" || challengeDigest !== null) || leaseMode === "offline" && (value.kind !== "offline-challenge" || challengeDigest === null))
656
+ fail$1("lease-schema", "lease_activation_binding_invalid");
657
+ return Object.freeze({ kind: value.kind, challengeDigest });
658
+ }
659
+ function decodeSegment(segment) {
660
+ if (!/^[A-Za-z0-9_-]+$/.test(segment))
661
+ fail$1("lease-schema", "lease_compact_invalid");
662
+ const decoded = Buffer.from(segment, "base64url");
663
+ if (decoded.toString("base64url") !== segment)
664
+ fail$1("lease-schema", "lease_compact_invalid");
665
+ return decoded;
666
+ }
667
+ function decodeJson(segment) {
668
+ try {
669
+ const value = JSON.parse(decodeSegment(segment).toString("utf8"));
670
+ if (!isRecord(value))
671
+ fail$1("lease-schema", "lease_schema_invalid");
672
+ return value;
673
+ } catch (error) {
674
+ if (error instanceof CommercialArtifactError)
675
+ throw error;
676
+ fail$1("lease-schema", "lease_json_invalid");
677
+ }
678
+ }
679
+ function normalizeEntitlementLeaseClaims(value) {
680
+ if (!isRecord(value))
681
+ fail$1("lease-schema", "lease_schema_invalid");
682
+ const schemaVersion = integer(value.schemaVersion);
683
+ if (schemaVersion !== ENTITLEMENT_LEASE_SCHEMA_VERSION && schemaVersion !== ENTITLEMENT_LEASE_BOUND_SCHEMA_VERSION) {
684
+ fail$1("lease-schema", "lease_schema_version_unsupported");
685
+ }
686
+ exactKeys(value, schemaVersion === ENTITLEMENT_LEASE_SCHEMA_VERSION ? CLAIM_KEYS_V1 : CLAIM_KEYS_V2, "lease-schema");
687
+ const aud = text(value.aud);
688
+ if (aud !== ENTITLEMENT_LEASE_PURPOSE)
689
+ fail$1("lease-schema", "lease_audience_invalid");
690
+ const leaseMode = value.leaseMode;
691
+ if (leaseMode !== "online" && leaseMode !== "offline") {
692
+ fail$1("lease-schema", "lease_mode_invalid");
693
+ }
694
+ const common = {
695
+ iss: text(value.iss),
696
+ aud: ENTITLEMENT_LEASE_PURPOSE,
697
+ jti: text(value.jti, 200),
698
+ tenantId: text(value.tenantId, 200),
699
+ subscriptionId: text(value.subscriptionId, 200),
700
+ installationId: text(value.installationId, 200),
701
+ productIds: sortedTexts(value.productIds),
702
+ skuId: text(value.skuId, 200),
703
+ featureIds: sortedTexts(value.featureIds),
704
+ domainConstraints: sortedTexts(value.domainConstraints),
705
+ releaseConstraint: releaseConstraint(value.releaseConstraint),
706
+ leaseMode,
707
+ entitlementEpoch: integer(value.entitlementEpoch),
708
+ revocationEpoch: integer(value.revocationEpoch),
709
+ iat: integer(value.iat),
710
+ nbf: integer(value.nbf),
711
+ refreshAfter: integer(value.refreshAfter),
712
+ fullUntil: integer(value.fullUntil),
713
+ exp: integer(value.exp)
714
+ };
715
+ const claims = schemaVersion === ENTITLEMENT_LEASE_SCHEMA_VERSION ? Object.freeze({ schemaVersion: 1, ...common }) : Object.freeze({
716
+ schemaVersion: 2,
717
+ ...common,
718
+ installationKeyThumbprint: sha256(value.installationKeyThumbprint),
719
+ activationBinding: activationBinding(value.activationBinding, leaseMode)
720
+ });
721
+ if (claims.productIds.length === 0 || claims.entitlementEpoch < 1 || claims.revocationEpoch < 0 || claims.nbf < claims.iat - CLOCK_SKEW_SECONDS || claims.refreshAfter < claims.nbf || claims.fullUntil < claims.refreshAfter || claims.exp < claims.fullUntil)
722
+ fail$1("lease-schema", "lease_time_or_epoch_invalid");
723
+ if (claims.leaseMode === "offline" && (claims.fullUntil - claims.nbf > OFFLINE_LEASE_MAX_FULL_WINDOW_SECONDS || claims.exp - claims.fullUntil > OFFLINE_LEASE_MAX_DEGRADED_WINDOW_SECONDS))
724
+ fail$1("lease-schema", "offline_lease_window_exceeded");
725
+ return claims;
726
+ }
727
+ function assertTrustKey(key, nowMs) {
728
+ if (key.alg !== ENTITLEMENT_LEASE_ALGORITHM || key.purpose !== ENTITLEMENT_LEASE_PURPOSE || !LEASE_KID.test(key.kid))
729
+ fail$1("lease-signature", "lease_key_purpose_mismatch");
730
+ if (key.status !== void 0 && !["active", "verify-only", "retired", "revoked"].includes(key.status))
731
+ fail$1("lease-signature", "lease_key_status_invalid");
732
+ if (key.status === "revoked" || key.status === "retired") {
733
+ fail$1("lease-signature", "lease_key_not_accepted");
734
+ }
735
+ const notBefore = key.notBefore === void 0 ? null : Date.parse(key.notBefore);
736
+ const notAfter = key.notAfter === void 0 ? null : Date.parse(key.notAfter);
737
+ if (notBefore !== null && !Number.isFinite(notBefore) || notAfter !== null && !Number.isFinite(notAfter) || notBefore !== null && notAfter !== null && notBefore >= notAfter)
738
+ fail$1("lease-signature", "lease_key_time_invalid");
739
+ if (notBefore !== null && nowMs < notBefore) {
740
+ fail$1("lease-signature", "lease_key_not_yet_valid");
741
+ }
742
+ if (notAfter !== null && nowMs >= notAfter) {
743
+ fail$1("lease-signature", "lease_key_expired");
744
+ }
745
+ }
746
+ function verifyEntitlementLease(input) {
747
+ if (Object.prototype.hasOwnProperty.call(input, "revokedLeaseIds") && input.revokedLeaseIds !== void 0) {
748
+ throw new CommercialArtifactError(UNSIGNED_REVOCATION_LIST_REFUSAL.stage, UNSIGNED_REVOCATION_LIST_REFUSAL.reason, UNSIGNED_REVOCATION_LIST_REFUSAL.decision);
749
+ }
750
+ if (typeof input.token !== "string" || input.token.length < 16 || Buffer.byteLength(input.token, "utf8") > MAX_LEASE_BYTES)
751
+ fail$1("lease-schema", "lease_compact_invalid");
752
+ const parts = input.token.split(".");
753
+ if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
754
+ fail$1("lease-schema", "lease_compact_invalid");
755
+ }
756
+ const header = decodeJson(parts[0]);
757
+ exactKeys(header, ["alg", "kid", "typ"], "lease-schema");
758
+ if (header.alg !== ENTITLEMENT_LEASE_ALGORITHM)
759
+ fail$1("lease-signature", "lease_algorithm_invalid");
760
+ if (header.typ !== ENTITLEMENT_LEASE_TYPE)
761
+ fail$1("lease-signature", "lease_type_invalid");
762
+ const kid = text(header.kid, 200);
763
+ if (!LEASE_KID.test(kid))
764
+ fail$1("lease-signature", "lease_key_purpose_mismatch");
765
+ const key = input.trustKeys.find((candidate) => candidate.kid === kid);
766
+ if (!key)
767
+ fail$1("lease-signature", "lease_key_unknown");
768
+ const now = input.now ?? /* @__PURE__ */ new Date();
769
+ const nowMs = now.getTime();
770
+ const nowSeconds = Math.floor(nowMs / 1e3);
771
+ if (!Number.isSafeInteger(nowSeconds))
772
+ fail$1("lease-validity", "clock_invalid");
773
+ assertTrustKey(key, nowMs);
774
+ let publicKey;
775
+ try {
776
+ publicKey = createPublicKey(key.publicKeyPem);
777
+ if (publicKey.asymmetricKeyType !== "ed25519")
778
+ fail$1("lease-signature", "lease_key_type_invalid");
779
+ } catch (error) {
780
+ if (error instanceof CommercialArtifactError)
781
+ throw error;
782
+ fail$1("lease-signature", "lease_key_invalid");
783
+ }
784
+ let signature;
785
+ try {
786
+ signature = decodeSegment(parts[2]);
787
+ } catch {
788
+ fail$1("lease-signature", "bad_signature");
789
+ }
790
+ if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`, "ascii"), publicKey, signature)) {
791
+ fail$1("lease-signature", "bad_signature");
792
+ }
793
+ const claims = normalizeEntitlementLeaseClaims(decodeJson(parts[1]));
794
+ if (claims.iss !== input.issuer)
795
+ fail$1("lease-validity", "lease_issuer_invalid");
796
+ if (nowSeconds + CLOCK_SKEW_SECONDS < claims.nbf)
797
+ fail$1("lease-validity", "lease_not_yet_valid");
798
+ if (nowSeconds >= claims.exp)
799
+ fail$1("lease-validity", "lease_expired");
800
+ const expected = input.expected;
801
+ if (input.revocationSnapshot) {
802
+ assertVerifiedRevocationSnapshot(input.revocationSnapshot);
803
+ assertRevocationSnapshotCovers({
804
+ snapshot: input.revocationSnapshot,
805
+ issuer: input.issuer,
806
+ tenantId: claims.tenantId,
807
+ installationId: claims.installationId,
808
+ productId: expected.productId
809
+ });
810
+ const disposition = evaluateRevocationSnapshotLease({
811
+ snapshot: input.revocationSnapshot,
812
+ leaseId: claims.jti
813
+ });
814
+ if (disposition.status === "revoked") {
815
+ fail$1("lease-validity", "lease_revoked");
816
+ }
817
+ if (disposition.status === "unknown") {
818
+ fail$1("lease-validity", "revocation_status_unknown");
819
+ }
820
+ }
821
+ if (claims.tenantId !== expected.tenantId)
822
+ fail$1("lease-coverage", "tenant_not_covered");
823
+ if (claims.installationId !== expected.installationId) {
824
+ fail$1("lease-coverage", "installation_not_covered");
825
+ }
826
+ if (!claims.productIds.includes(expected.productId))
827
+ fail$1("lease-coverage", "product_not_covered");
828
+ if (expected.featureIds?.some((feature) => !claims.featureIds.includes(feature))) {
829
+ fail$1("lease-coverage", "feature_not_covered");
830
+ }
831
+ if (expected.domain && !claims.domainConstraints.includes(expected.domain)) {
832
+ fail$1("lease-coverage", "domain_not_covered");
833
+ }
834
+ if (!claims.releaseConstraint.manifestDigests.includes(normalizeDigest(expected.manifestDigest)) || !claims.releaseConstraint.closureDigests.includes(normalizeDigest(expected.closureDigest)))
835
+ fail$1("lease-coverage", "release_not_covered");
836
+ if (expected.entitlementEpoch !== void 0 && claims.entitlementEpoch !== expected.entitlementEpoch) {
837
+ fail$1("lease-epoch", "entitlement_epoch_stale");
838
+ }
839
+ if (expected.minimumRevocationEpoch !== void 0 && claims.revocationEpoch < expected.minimumRevocationEpoch)
840
+ fail$1("lease-epoch", "revocation_epoch_stale");
841
+ if (expected.leaseMode !== void 0 && claims.leaseMode !== expected.leaseMode) {
842
+ fail$1("lease-coverage", "lease_mode_mismatch");
843
+ }
844
+ if (claims.leaseMode === "offline" && claims.schemaVersion !== 2) {
845
+ fail$1("lease-coverage", "offline_lease_binding_required");
846
+ }
847
+ if (claims.leaseMode === "offline" && (expected.installationKeyThumbprint === void 0 || expected.activationChallengeDigest === void 0))
848
+ fail$1("lease-coverage", "offline_lease_binding_context_required");
849
+ if (expected.installationKeyThumbprint !== void 0) {
850
+ if (claims.schemaVersion !== 2 || claims.installationKeyThumbprint !== normalizeDigest(expected.installationKeyThumbprint))
851
+ fail$1("lease-coverage", "installation_key_not_bound");
852
+ }
853
+ if (expected.activationChallengeDigest !== void 0) {
854
+ if (claims.schemaVersion !== 2 || claims.activationBinding.kind !== "offline-challenge" || claims.activationBinding.challengeDigest !== normalizeDigest(expected.activationChallengeDigest))
855
+ fail$1("lease-coverage", "activation_challenge_not_bound");
856
+ }
857
+ const verified = Object.freeze({
858
+ claims,
859
+ keyId: kid,
860
+ mode: nowSeconds < claims.fullUntil ? "full" : "degraded",
861
+ refreshDue: nowSeconds >= claims.refreshAfter,
862
+ verifiedAt: now.toISOString()
863
+ });
864
+ verifiedEntitlementLeases.add(verified);
865
+ return verified;
866
+ }
867
+ const DOMAIN_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/;
868
+ const OPERATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;
869
+ function fail(stage, reason) {
870
+ throw new CommercialArtifactError(stage, reason);
871
+ }
872
+ function sortedUnique(values, reason) {
873
+ const sorted = [...values].sort();
874
+ if (new Set(values).size !== values.length || values.some((value, index) => value !== sorted[index])) {
875
+ fail("admission", reason);
876
+ }
877
+ return Object.freeze(sorted);
878
+ }
879
+ function canonicalUnique(values, reason) {
880
+ if (new Set(values).size !== values.length)
881
+ fail("admission", reason);
882
+ return Object.freeze([...values].sort());
883
+ }
884
+ function normalizedDomain(value) {
885
+ const domain = value.trim().toLowerCase();
886
+ if (!DOMAIN_ID.test(domain))
887
+ fail("admission", "domain_invalid");
888
+ return domain;
889
+ }
890
+ function assertOperation(operation) {
891
+ if (!OPERATION_ID.test(operation.operationId))
892
+ fail("admission", "operation_id_invalid");
893
+ const features = operation.requiredFeatureIds ?? [];
894
+ sortedUnique(features, "operation_feature_ids_not_canonical");
895
+ if (!["none", "db", "fs", "network", "mixed"].includes(operation.sideEffect)) {
896
+ fail("admission", "operation_side_effect_invalid");
897
+ }
898
+ }
899
+ function degradedBaselineEligible(operation) {
900
+ return operation.sideEffect === "none" && operation.safety?.destructive !== true && operation.safety?.confirmationRequired !== true && operation.safety?.applyRequired !== true;
901
+ }
902
+ function assertEvidence(input) {
903
+ const payload = input.manifest.envelope.payload;
904
+ const claims = input.lease.claims;
905
+ if (input.receipt.manifestDigest !== input.manifest.manifestDigest || input.receipt.closureDigest !== payload.closureDigest || input.receipt.releaseId !== payload.release.releaseId || input.receipt.installationId !== claims.installationId)
906
+ fail("admission", "verified_chain_mismatch");
907
+ const manifestDigest = input.manifest.manifestDigest.replace(/^sha256:/, "");
908
+ const closureDigest = input.receipt.closureDigest.replace(/^sha256:/, "");
909
+ if (!claims.productIds.includes(input.productId) || !claims.domainConstraints.includes(input.domain) || !claims.releaseConstraint.manifestDigests.includes(manifestDigest) || !claims.releaseConstraint.closureDigests.includes(closureDigest))
910
+ fail("admission", "lease_projection_mismatch");
911
+ }
912
+ function commercialDecision(input) {
913
+ const domain = normalizedDomain(input.domain);
914
+ assertEvidence({ ...input, domain });
915
+ const operations = [...input.operations].sort((left, right) => left.operationId < right.operationId ? -1 : left.operationId > right.operationId ? 1 : 0);
916
+ if (new Set(operations.map((operation) => operation.operationId)).size !== operations.length)
917
+ fail("admission", "operation_id_duplicate");
918
+ for (const operation of operations)
919
+ assertOperation(operation);
920
+ const covered = operations.filter((operation) => (operation.requiredFeatureIds ?? []).every((feature) => input.lease.claims.featureIds.includes(feature)));
921
+ const manifestDegraded = new Set(input.manifest.envelope.payload.degradedOperationIds);
922
+ const degraded = covered.filter((operation) => degradedBaselineEligible(operation) && manifestDegraded.has(operation.operationId));
923
+ const allowed = input.lease.mode === "full" ? covered : degraded;
924
+ return Object.freeze({
925
+ domain,
926
+ plane: "commercial",
927
+ state: input.lease.mode,
928
+ reason: "verified_chain",
929
+ allowedOperationIds: new Set(allowed.map((operation) => operation.operationId)),
930
+ degradedOperationIds: new Set(degraded.map((operation) => operation.operationId)),
931
+ productId: input.productId,
932
+ manifestDigest: input.manifest.manifestDigest,
933
+ closureDigest: input.receipt.closureDigest,
934
+ receiptId: input.receipt.receiptId,
935
+ leaseId: input.lease.claims.jti,
936
+ entitlementEpoch: input.lease.claims.entitlementEpoch,
937
+ revocationEpoch: input.lease.claims.revocationEpoch,
938
+ refreshAfter: input.lease.claims.refreshAfter,
939
+ fullUntil: input.lease.claims.fullUntil,
940
+ expiresAt: input.lease.claims.exp,
941
+ migrationEligible: input.lease.mode === "full"
942
+ });
943
+ }
944
+ function buildAdmittedDomainSnapshot(input) {
945
+ if (!Number.isSafeInteger(input.generation) || input.generation < 1) {
946
+ fail("admission", "snapshot_generation_invalid");
947
+ }
948
+ const createdAt = (input.now ?? /* @__PURE__ */ new Date()).toISOString();
949
+ const domains = /* @__PURE__ */ new Map();
950
+ const freeDomains = canonicalUnique(input.freeDomains.map(normalizedDomain), "free_domain_set_not_canonical");
951
+ for (const domain of freeDomains) {
952
+ domains.set(domain, Object.freeze({
953
+ domain,
954
+ plane: "community",
955
+ state: "free",
956
+ reason: "community_builtin",
957
+ allowedOperationIds: null,
958
+ degradedOperationIds: null,
959
+ productId: null,
960
+ manifestDigest: null,
961
+ closureDigest: null,
962
+ receiptId: null,
963
+ leaseId: null,
964
+ entitlementEpoch: null,
965
+ revocationEpoch: null,
966
+ refreshAfter: null,
967
+ fullUntil: null,
968
+ expiresAt: null,
969
+ migrationEligible: true
970
+ }));
971
+ }
972
+ const commercial = [...input.commercialDomains ?? []].sort((left, right) => left.domain < right.domain ? -1 : left.domain > right.domain ? 1 : 0);
973
+ for (const candidate of commercial) {
974
+ const decision = commercialDecision(candidate);
975
+ if (domains.has(decision.domain))
976
+ fail("admission", "domain_authority_collision");
977
+ domains.set(decision.domain, decision);
978
+ }
979
+ const orderedDomains = Object.freeze([...domains.values()]);
980
+ return Object.freeze({
981
+ schemaVersion: 1,
982
+ objectType: "aops-admitted-domain-snapshot-v1",
983
+ generation: input.generation,
984
+ createdAt,
985
+ domains,
986
+ orderedDomains
987
+ });
988
+ }
989
+ function checkDomainAdmission(snapshot, domainInput, operationId, now = /* @__PURE__ */ new Date()) {
990
+ const domain = normalizedDomain(domainInput);
991
+ const decision = snapshot.domains.get(domain);
992
+ if (!decision)
993
+ return Object.freeze({ allowed: false, domain, reason: "domain_not_admitted" });
994
+ if (decision.expiresAt !== null && Math.floor(now.getTime() / 1e3) >= decision.expiresAt)
995
+ return Object.freeze({ allowed: false, domain, reason: "lease_expired" });
996
+ const nowSeconds = Math.floor(now.getTime() / 1e3);
997
+ const effectiveDecision = decision.state === "full" && decision.fullUntil !== null && nowSeconds >= decision.fullUntil ? Object.freeze({
998
+ ...decision,
999
+ state: "degraded",
1000
+ allowedOperationIds: decision.degradedOperationIds,
1001
+ migrationEligible: false
1002
+ }) : decision;
1003
+ if (operationId !== void 0 && effectiveDecision.allowedOperationIds !== null && !effectiveDecision.allowedOperationIds.has(operationId))
1004
+ return Object.freeze({ allowed: false, domain, reason: "operation_not_admitted" });
1005
+ return Object.freeze({ allowed: true, decision: effectiveDecision });
1006
+ }
1007
+ class AdmissionDecisionCache {
1008
+ #snapshot;
1009
+ #lastSeenMs;
1010
+ constructor(initial) {
1011
+ this.#snapshot = initial;
1012
+ this.#lastSeenMs = Date.parse(initial.createdAt);
1013
+ if (!Number.isFinite(this.#lastSeenMs))
1014
+ fail("admission", "snapshot_time_invalid");
1015
+ }
1016
+ read() {
1017
+ return this.#snapshot;
1018
+ }
1019
+ replace(next) {
1020
+ if (next.generation <= this.#snapshot.generation) {
1021
+ fail("admission", "snapshot_generation_not_monotonic");
1022
+ }
1023
+ this.#snapshot = next;
1024
+ }
1025
+ check(domain, operationId, now) {
1026
+ const observedMs = (now ?? /* @__PURE__ */ new Date()).getTime();
1027
+ if (!Number.isFinite(observedMs))
1028
+ fail("admission", "clock_invalid");
1029
+ this.#lastSeenMs = Math.max(this.#lastSeenMs, observedMs);
1030
+ return checkDomainAdmission(this.#snapshot, domain, operationId, new Date(this.#lastSeenMs));
1031
+ }
1032
+ }
1033
+
1034
+ export { AdmissionDecisionCache as A, CommercialArtifactError as C, ENTITLEMENT_LEASE_PURPOSE as E, RELEASE_MANIFEST_PURPOSE as R, verifyReleaseManifestEnvelope as a, buildAdmittedDomainSnapshot as b, canonicalCommercialJson as c, ENTITLEMENT_LEASE_ALGORITHM as d, assertCommercialRuntimeCompatible as e, sha256Commercial as s, verifyEntitlementLease as v };