@kya-os/checkpoint-nextjs 1.10.0 → 1.11.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 (210) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/README.md +205 -31
  3. package/dist/{adapt.mjs → adapt-BdQ9R7Iw.mjs} +15 -4
  4. package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
  5. package/dist/{adapt.js → adapt-CCSKGjVH.js} +34 -13
  6. package/dist/api-client-JHOrRUA_.d.mts +222 -0
  7. package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
  8. package/dist/api-client-JHOrRUA_.d.ts +222 -0
  9. package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
  10. package/dist/api-client.d.mts +2 -204
  11. package/dist/api-client.d.ts +2 -204
  12. package/dist/api-client.js +19 -18
  13. package/dist/api-client.mjs +20 -16
  14. package/dist/api-client.mjs.map +1 -1
  15. package/dist/api-middleware-BWjokNis.d.mts +131 -0
  16. package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
  17. package/dist/{api-middleware-CDSh3TSE.js → api-middleware-Bf3xmM9W.js} +75 -63
  18. package/dist/{api-middleware-CMDRoQik.mjs → api-middleware-C-ngFX_8.mjs} +68 -38
  19. package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
  20. package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
  21. package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
  22. package/dist/api-middleware.d.mts +2 -152
  23. package/dist/api-middleware.d.ts +2 -152
  24. package/dist/api-middleware.js +1 -5
  25. package/dist/api-middleware.mjs +2 -3
  26. package/dist/cedar-wasm.d.mts +20 -0
  27. package/dist/cedar-wasm.d.mts.map +1 -0
  28. package/dist/cedar-wasm.d.ts +19 -0
  29. package/dist/cedar-wasm.d.ts.map +1 -0
  30. package/dist/cedar-wasm.js +24 -0
  31. package/dist/cedar-wasm.mjs +23 -0
  32. package/dist/cedar-wasm.mjs.map +1 -0
  33. package/dist/{config-Doe0Tn53.d.mts → config-CPP1RV0f.d.mts} +65 -29
  34. package/dist/config-CPP1RV0f.d.mts.map +1 -0
  35. package/dist/{config-CbAg2mze.d.ts → config-DVgOFxJs.d.ts} +66 -30
  36. package/dist/config-DVgOFxJs.d.ts.map +1 -0
  37. package/dist/engine-wasm.d.mts +20 -0
  38. package/dist/engine-wasm.d.mts.map +1 -0
  39. package/dist/engine-wasm.d.ts +19 -0
  40. package/dist/engine-wasm.d.ts.map +1 -0
  41. package/dist/engine-wasm.js +24 -0
  42. package/dist/engine-wasm.mjs +23 -0
  43. package/dist/engine-wasm.mjs.map +1 -0
  44. package/dist/index-edge.d.mts +8 -0
  45. package/dist/index-edge.d.ts +8 -0
  46. package/dist/index-edge.js +14 -0
  47. package/dist/index-edge.mjs +7 -0
  48. package/dist/index.d.mts +8 -10
  49. package/dist/index.d.ts +8 -10
  50. package/dist/index.js +20 -49
  51. package/dist/index.mjs +21 -8
  52. package/dist/index.mjs.map +1 -1
  53. package/dist/middleware-bundler.d.mts +1 -1
  54. package/dist/middleware-bundler.d.mts.map +1 -1
  55. package/dist/middleware-bundler.d.ts +1 -1
  56. package/dist/middleware-bundler.d.ts.map +1 -1
  57. package/dist/middleware-bundler.js +4 -4
  58. package/dist/middleware-bundler.mjs +4 -4
  59. package/dist/middleware-bundler.mjs.map +1 -1
  60. package/dist/middleware-core-B0jf5_Hm.mjs +264 -0
  61. package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
  62. package/dist/middleware-core-Bol44X9C.d.ts +17 -0
  63. package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
  64. package/dist/middleware-core-CMc-2QkU.js +274 -0
  65. package/dist/middleware-core-DycsbHUd.d.mts +17 -0
  66. package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
  67. package/dist/middleware-edge.d.mts +11 -3
  68. package/dist/middleware-edge.d.mts.map +1 -1
  69. package/dist/middleware-edge.d.ts +11 -3
  70. package/dist/middleware-edge.d.ts.map +1 -1
  71. package/dist/middleware-edge.js +77 -24
  72. package/dist/middleware-edge.mjs +74 -23
  73. package/dist/middleware-edge.mjs.map +1 -1
  74. package/dist/{middleware-node-context-rgnc7UNR.js → middleware-node-context-591KsiYg.js} +8 -7
  75. package/dist/{middleware-node-context-BqPbf-fI.mjs → middleware-node-context-D_ZyUEcA.mjs} +6 -5
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
  77. package/dist/middleware-node.d.mts +12 -3
  78. package/dist/middleware-node.d.mts.map +1 -0
  79. package/dist/middleware-node.d.ts +12 -3
  80. package/dist/middleware-node.d.ts.map +1 -0
  81. package/dist/middleware-node.js +13 -5
  82. package/dist/middleware-node.mjs +13 -5
  83. package/dist/middleware-node.mjs.map +1 -1
  84. package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
  85. package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
  86. package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
  87. package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
  88. package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
  89. package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
  90. package/dist/posture-outcome-DddsJtL8.js +25 -0
  91. package/dist/public-api-CYsHrTQI.d.ts +5 -0
  92. package/dist/public-api-DkG7pRE0.d.mts +5 -0
  93. package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
  94. package/dist/utils-Cnwg0VrY.mjs +88 -0
  95. package/dist/utils-Cnwg0VrY.mjs.map +1 -0
  96. package/dist/utils-dyFxqlFI.js +104 -0
  97. package/package.json +27 -62
  98. package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
  99. package/bin/setup-edge-wasm.js +0 -513
  100. package/dist/adapt.d.mts +0 -11
  101. package/dist/adapt.d.mts.map +0 -1
  102. package/dist/adapt.d.ts +0 -11
  103. package/dist/adapt.d.ts.map +0 -1
  104. package/dist/adapt.mjs.map +0 -1
  105. package/dist/api-client.d.mts.map +0 -1
  106. package/dist/api-client.d.ts.map +0 -1
  107. package/dist/api-middleware-CMDRoQik.mjs.map +0 -1
  108. package/dist/api-middleware.d.mts.map +0 -1
  109. package/dist/api-middleware.d.ts.map +0 -1
  110. package/dist/composed-policy-BCaNiVHv.d.mts +0 -98
  111. package/dist/composed-policy-BCaNiVHv.d.mts.map +0 -1
  112. package/dist/composed-policy-zzJYNFTb.d.ts +0 -98
  113. package/dist/composed-policy-zzJYNFTb.d.ts.map +0 -1
  114. package/dist/composed-policy.d.mts +0 -2
  115. package/dist/composed-policy.d.ts +0 -2
  116. package/dist/composed-policy.js +0 -136
  117. package/dist/composed-policy.mjs +0 -132
  118. package/dist/composed-policy.mjs.map +0 -1
  119. package/dist/config-CbAg2mze.d.ts.map +0 -1
  120. package/dist/config-Doe0Tn53.d.mts.map +0 -1
  121. package/dist/create-middleware.d.mts +0 -11
  122. package/dist/create-middleware.d.mts.map +0 -1
  123. package/dist/create-middleware.d.ts +0 -11
  124. package/dist/create-middleware.d.ts.map +0 -1
  125. package/dist/create-middleware.js +0 -39
  126. package/dist/create-middleware.mjs +0 -38
  127. package/dist/create-middleware.mjs.map +0 -1
  128. package/dist/edge/index.d.mts +0 -88
  129. package/dist/edge/index.d.mts.map +0 -1
  130. package/dist/edge/index.d.ts +0 -88
  131. package/dist/edge/index.d.ts.map +0 -1
  132. package/dist/edge/index.js +0 -362
  133. package/dist/edge/index.mjs +0 -362
  134. package/dist/edge/index.mjs.map +0 -1
  135. package/dist/edge-runtime-loader.d.mts +0 -49
  136. package/dist/edge-runtime-loader.d.mts.map +0 -1
  137. package/dist/edge-runtime-loader.d.ts +0 -49
  138. package/dist/edge-runtime-loader.d.ts.map +0 -1
  139. package/dist/edge-runtime-loader.js +0 -297
  140. package/dist/edge-runtime-loader.mjs +0 -292
  141. package/dist/edge-runtime-loader.mjs.map +0 -1
  142. package/dist/edge-wasm-middleware.d.mts +0 -43
  143. package/dist/edge-wasm-middleware.d.mts.map +0 -1
  144. package/dist/edge-wasm-middleware.d.ts +0 -43
  145. package/dist/edge-wasm-middleware.d.ts.map +0 -1
  146. package/dist/edge-wasm-middleware.js +0 -37
  147. package/dist/edge-wasm-middleware.mjs +0 -35
  148. package/dist/edge-wasm-middleware.mjs.map +0 -1
  149. package/dist/middleware-core-BYQP9FND.mjs +0 -165
  150. package/dist/middleware-core-BYQP9FND.mjs.map +0 -1
  151. package/dist/middleware-core-D6TijE6P.js +0 -175
  152. package/dist/middleware-node-CE4GevYs.d.ts +0 -20
  153. package/dist/middleware-node-CE4GevYs.d.ts.map +0 -1
  154. package/dist/middleware-node-DtyOuPta.d.mts +0 -20
  155. package/dist/middleware-node-DtyOuPta.d.mts.map +0 -1
  156. package/dist/middleware-node-context-BqPbf-fI.mjs.map +0 -1
  157. package/dist/middleware.d.mts +0 -25
  158. package/dist/middleware.d.mts.map +0 -1
  159. package/dist/middleware.d.ts +0 -25
  160. package/dist/middleware.d.ts.map +0 -1
  161. package/dist/middleware.js +0 -53
  162. package/dist/middleware.mjs +0 -51
  163. package/dist/middleware.mjs.map +0 -1
  164. package/dist/nodejs-wasm-loader.d.mts +0 -42
  165. package/dist/nodejs-wasm-loader.d.mts.map +0 -1
  166. package/dist/nodejs-wasm-loader.d.ts +0 -42
  167. package/dist/nodejs-wasm-loader.d.ts.map +0 -1
  168. package/dist/nodejs-wasm-loader.js +0 -70
  169. package/dist/nodejs-wasm-loader.mjs +0 -66
  170. package/dist/nodejs-wasm-loader.mjs.map +0 -1
  171. package/dist/policy.d.mts +0 -138
  172. package/dist/policy.d.mts.map +0 -1
  173. package/dist/policy.d.ts +0 -138
  174. package/dist/policy.d.ts.map +0 -1
  175. package/dist/policy.js +0 -236
  176. package/dist/policy.mjs +0 -205
  177. package/dist/policy.mjs.map +0 -1
  178. package/dist/session-tracker.d.mts +0 -50
  179. package/dist/session-tracker.d.mts.map +0 -1
  180. package/dist/session-tracker.d.ts +0 -50
  181. package/dist/session-tracker.d.ts.map +0 -1
  182. package/dist/session-tracker.js +0 -148
  183. package/dist/session-tracker.mjs +0 -147
  184. package/dist/session-tracker.mjs.map +0 -1
  185. package/dist/translate.d.mts +0 -48
  186. package/dist/translate.d.mts.map +0 -1
  187. package/dist/translate.d.ts +0 -48
  188. package/dist/translate.d.ts.map +0 -1
  189. package/dist/translate.js +0 -79
  190. package/dist/translate.mjs +0 -79
  191. package/dist/translate.mjs.map +0 -1
  192. package/dist/types-C0SkqLMM.d.mts +0 -102
  193. package/dist/types-C0SkqLMM.d.mts.map +0 -1
  194. package/dist/types-C7DNSCTO.d.ts +0 -102
  195. package/dist/types-C7DNSCTO.d.ts.map +0 -1
  196. package/dist/utils-Cj4XNhIY.mjs +0 -35
  197. package/dist/utils-Cj4XNhIY.mjs.map +0 -1
  198. package/dist/utils-DAisnYnI.js +0 -45
  199. package/dist/wasm-setup.d.mts +0 -47
  200. package/dist/wasm-setup.d.mts.map +0 -1
  201. package/dist/wasm-setup.d.ts +0 -47
  202. package/dist/wasm-setup.d.ts.map +0 -1
  203. package/dist/wasm-setup.js +0 -91
  204. package/dist/wasm-setup.mjs +0 -95
  205. package/dist/wasm-setup.mjs.map +0 -1
  206. package/wasm/agentshield_wasm.d.ts +0 -479
  207. package/wasm/agentshield_wasm.js +0 -1536
  208. package/wasm/agentshield_wasm_bg.wasm +0 -0
  209. package/wasm/package.json +0 -30
  210. package/wasm.d.ts +0 -21
@@ -0,0 +1,274 @@
1
+ const require_adapt = require('./adapt-CCSKGjVH.js');
2
+ const require_utils = require('./utils-dyFxqlFI.js');
3
+ let _kya_os_checkpoint_shared_browser_posture = require("@kya-os/checkpoint-shared/browser-posture");
4
+ let _kya_os_checkpoint_wasm_runtime_composed_policy = require("@kya-os/checkpoint-wasm-runtime/composed-policy");
5
+ let _kya_os_checkpoint_wasm_runtime_adapters = require("@kya-os/checkpoint-wasm-runtime/adapters");
6
+ let _kya_os_checkpoint_wasm_runtime_reporter = require("@kya-os/checkpoint-wasm-runtime/reporter");
7
+ let _kya_os_checkpoint_shared_policy_fetcher = require("@kya-os/checkpoint-shared/policy/fetcher");
8
+ let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
9
+ let _vercel_functions = require("@vercel/functions");
10
+
11
+ //#region src/translate.ts
12
+ /**
13
+ * Translate a Next.js `NextRequest` into the orchestrator's
14
+ * `IncomingHttpLike` shape.
15
+ *
16
+ * When `opts.drainJsonBody !== false` and the request is JSON, the
17
+ * translator clones the request and reads the body into a string so
18
+ * the orchestrator's `buildAgentRequest` can extract a
19
+ * `_meta.proof.jws` envelope. The original `req.body` stream is
20
+ * preserved for downstream handlers via `req.clone()`.
21
+ *
22
+ * When the body can't be read (drain disabled, non-JSON, or a stream
23
+ * error) we pass `body: null` and the orchestrator routes to
24
+ * PlainHttp — same behavior as the pre-1.1.0 default.
25
+ */
26
+ async function nextRequestToHttpLike(req, opts = {}) {
27
+ const url = new URL(req.url);
28
+ const body = await tryDrainJsonBody(req, opts);
29
+ return {
30
+ method: req.method,
31
+ url: url.pathname + url.search,
32
+ headers: headersToRecord(req.headers),
33
+ body,
34
+ remoteAddress: require_utils.getClientIp(req, opts.clientIpPolicy)
35
+ };
36
+ }
37
+ /**
38
+ * Read the request body as a UTF-8 string when JSON and the caller
39
+ * has opted in (default). Returns `null` on any failure — the
40
+ * orchestrator handles `null` as "no body present" (→ PlainHttp).
41
+ *
42
+ * Clone-first means the original `req.body` ReadableStream stays
43
+ * unconsumed and downstream handlers can re-read it. Without the
44
+ * clone, calling `req.text()` in middleware would block any route
45
+ * handler that needs the body.
46
+ */
47
+ async function tryDrainJsonBody(req, opts) {
48
+ if (opts.drainJsonBody === false) return null;
49
+ if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
50
+ try {
51
+ return await req.clone().text();
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+ /**
57
+ * Convert a `Headers` instance into a lowercase-keyed plain object.
58
+ * HTTP header names are case-insensitive (RFC 9110 § 5.1); the
59
+ * orchestrator does case-sensitive lookups, so we normalise to
60
+ * lowercase here. Multi-value headers (Set-Cookie, Accept) are
61
+ * surfaced as their `Headers.get()` view — a single string with
62
+ * comma-joined values, matching what other host adapters produce.
63
+ */
64
+ function headersToRecord(headers) {
65
+ const out = {};
66
+ headers.forEach((value, key) => {
67
+ out[key.toLowerCase()] = value;
68
+ });
69
+ return out;
70
+ }
71
+
72
+ //#endregion
73
+ //#region src/middleware-core.ts
74
+ /**
75
+ * Shared Next.js request pipeline. Node, bundler and Edge hosts inject their
76
+ * engine and policy-context factories; runtime-specific WASM initialization
77
+ * stays in each host entry. Public withCheckpoint exports live there too.
78
+ */
79
+ /**
80
+ * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
81
+ * suitable for `export default withCheckpoint({...})` in `middleware.ts`.
82
+ *
83
+ * Every verification decision flows through the Rust `kya-os-engine`
84
+ * via WASM. The TS layer translates request shape, calls
85
+ * `verifyRequest`, and translates the verdict to `NextResponse`. No
86
+ * verification logic lives in this file.
87
+ *
88
+ * It never throws. An error in the configuration or in loading the engine
89
+ * would otherwise fail the middleware module, and a Next.js middleware that
90
+ * fails to load can let requests through unchecked. Every such error is
91
+ * answered 503 instead (fail closed) and logged.
92
+ */
93
+ let warnedLocalClaimStore = false;
94
+ /**
95
+ * Where accepted signed requests are claimed: the caller's store, else the
96
+ * dashboard's shared ledger when the project is configured, else this
97
+ * process (or isolate), with a one-time warning that several instances need
98
+ * a shared store.
99
+ */
100
+ function buildRequestClaimStore(config) {
101
+ if (config.requestClaimStore) return config.requestClaimStore;
102
+ if (config.apiKey && config.projectId) return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.createPlatformRequestClaimStore)({
103
+ baseUrl: config.dashboardUrl ?? config.baseUrl ?? _kya_os_checkpoint_wasm_runtime_composed_policy.DEFAULT_DASHBOARD_URL,
104
+ apiKey: config.apiKey
105
+ });
106
+ if (!warnedLocalClaimStore) {
107
+ warnedLocalClaimStore = true;
108
+ console.warn("[checkpoint] signed requests are claimed in this process only; a deployment with several instances needs apiKey and projectId, or a shared requestClaimStore");
109
+ }
110
+ return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.createLocalRequestClaimStore)();
111
+ }
112
+ function makeNextMiddleware(config, host) {
113
+ try {
114
+ return makePipeline(config, host);
115
+ } catch (error) {
116
+ return async function misconfiguredCheckpointMiddleware() {
117
+ console.error("[checkpoint] withCheckpoint is misconfigured; responding 503:", error);
118
+ return require_adapt.failClosedResponse();
119
+ };
120
+ }
121
+ }
122
+ function makePipeline(config, host) {
123
+ if (config.browserPosture) (0, _kya_os_checkpoint_shared_browser_posture.validateBrowserPostureConfig)(config.browserPosture, config.projectId);
124
+ if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) throw new Error("browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)");
125
+ host.start?.(config);
126
+ const engine = memoizeEngine(host.loadEngine);
127
+ engine().catch(() => void 0);
128
+ const opts = buildVerifyOpts(config);
129
+ const reporter = buildReporter(config, host.runtime);
130
+ const composed = host.buildComposedContext(config);
131
+ const requestClaimStore = buildRequestClaimStore(config);
132
+ const trustedRootsResolver = buildTrustedRootsResolver(config, composed);
133
+ const translateOpts = {
134
+ drainJsonBody: config.drainJsonBody,
135
+ clientIpPolicy: config.clientIpPolicy
136
+ };
137
+ return async function checkpointMiddleware(req, event) {
138
+ const waitUntil = event ? (promise) => event.waitUntil(promise) : _vercel_functions.waitUntil;
139
+ try {
140
+ const { verifyRequest, renderDecisionAsResponse } = await engine().catch((error) => {
141
+ console.error("[checkpoint] kya-os-engine failed to load; responding 503:", error);
142
+ throw error;
143
+ });
144
+ const httpLike = await nextRequestToHttpLike(req, translateOpts);
145
+ const trustedDelegationRoots = await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.resolveTrustedDelegationRootsForRequest)(trustedRootsResolver, req.headers);
146
+ const result = await verifyRequest(httpLike, {
147
+ ...opts,
148
+ ...trustedDelegationRoots ? { trustedDelegationRoots } : {},
149
+ waitUntil
150
+ });
151
+ await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyBrowserPosture)(result, (0, _kya_os_checkpoint_shared_browser_posture.postureRequestFromHeaders)((name) => req.headers.get(name)), config.browserPosture, config.projectId);
152
+ await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyComposedPolicy)(composed, result, req.nextUrl.pathname);
153
+ (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyBrowserIntegrityStepUp)(result, config.browserPosture, req.nextUrl.pathname);
154
+ await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyRequestClaim)(result, requestClaimStore, { sourceIp: require_utils.getClientIp(req, config.clientIpPolicy) ?? void 0 });
155
+ if (reporter) waitUntil(reporter(result, extractReporterContext(req, config.clientIpPolicy)));
156
+ await dispatchOnResult(config, result, req);
157
+ const bodyReadable200 = (0, _kya_os_checkpoint_shared_host_adapter.selectBodyReadable200)(config.delegationChallengeMode ?? "negotiated", req.headers, result.detectionDetail.detectionClass, result.detectionDetail.isAgent);
158
+ const challengeContextRequested = result.enforcementMode === "enforce" && (result.decision.kind === "Challenge" || (0, _kya_os_checkpoint_wasm_runtime_composed_policy.isConsentRemediableBlock)(result)) && config.resolveDelegationChallenge !== void 0;
159
+ const delegationChallenge = challengeContextRequested ? await (0, _kya_os_checkpoint_shared_host_adapter.resolveChallengeContext)(config.resolveDelegationChallenge, {
160
+ result,
161
+ request: req
162
+ }, {
163
+ timeoutMs: config.delegationChallengeTimeoutMs,
164
+ onFailure: config.onDelegationChallengeFailure
165
+ }) : void 0;
166
+ const rendered = renderDecisionAsResponse(result, {
167
+ bodyReadable200,
168
+ delegationChallenge: (0, _kya_os_checkpoint_wasm_runtime_composed_policy.validateBrowserIntegrityChallenge)(result, delegationChallenge),
169
+ challengeContextRequested
170
+ });
171
+ return require_adapt.adaptToNextResponse(rendered, req);
172
+ } catch (err) {
173
+ if (config.debug) console.error("[checkpoint] verification pipeline failed; responding 503:", err);
174
+ return require_adapt.failClosedResponse();
175
+ }
176
+ };
177
+ }
178
+ /** Load the engine once; a failed load is retried by the next request. */
179
+ function memoizeEngine(load) {
180
+ let loading;
181
+ return () => loading ??= load().catch((error) => {
182
+ loading = void 0;
183
+ throw error;
184
+ });
185
+ }
186
+ /**
187
+ * Build a fire-and-forget detection reporter from the host config. Returns
188
+ * `null` when `apiKey` is not set — that case is the documented opt-out
189
+ * (engine still runs locally, dashboard just sees no detections).
190
+ */
191
+ /** npm package name this SDK self-reports to the detection reporter. */
192
+ const SDK_NAME = "@kya-os/checkpoint-nextjs";
193
+ /**
194
+ * Installed SDK version, self-reported to the detection reporter so the
195
+ * dashboard can version-gate "composed policy enforces here". MUST equal
196
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
197
+ * drifted). Re-exported as `VERSION` from the package index.
198
+ */
199
+ const VERSION = "1.11.0";
200
+ function buildReporter(config, runtime = "node") {
201
+ if (!config.apiKey) return null;
202
+ return (0, _kya_os_checkpoint_wasm_runtime_reporter.makeDetectionReporter)({
203
+ apiKey: config.apiKey,
204
+ baseUrl: config.baseUrl,
205
+ debug: config.debug,
206
+ sdk: {
207
+ name: SDK_NAME,
208
+ version: VERSION,
209
+ runtime
210
+ }
211
+ });
212
+ }
213
+ /**
214
+ * Build the per-factory trusted-delegation-roots resolver (P2 / DR-1). Root
215
+ * pinning is a security concern INDEPENDENT of composed Cedar enforcement, so it
216
+ * must resolve wherever a `projectId` exists — including Edge setups that never
217
+ * wire `cedarWasmModule` (where `buildComposedContext` returns null). Prefers the
218
+ * composed context's accessor (reuses its cached fetcher / honors an injected
219
+ * enforcer); otherwise falls back to a `projectId`-only policy fetch. Returns
220
+ * `null` when no source is configured (no roots → the engine rejects delegation).
221
+ * An origin outage rejects with `PolicyUnavailableError`, which the middleware
222
+ * answers as a retryable 503.
223
+ */
224
+ function buildTrustedRootsResolver(config, composed) {
225
+ if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots);
226
+ if (composed?.trustedDelegationRoots) return () => composed.trustedDelegationRoots();
227
+ if (!config.projectId) return null;
228
+ const fetcher = new _kya_os_checkpoint_shared_policy_fetcher.PolicyFetcher({
229
+ apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? _kya_os_checkpoint_wasm_runtime_composed_policy.DEFAULT_DASHBOARD_URL,
230
+ apiKey: config.apiKey,
231
+ cacheTtlSeconds: config.policyCacheTtlSeconds,
232
+ throwOnUnavailable: true
233
+ });
234
+ const projectId = config.projectId;
235
+ return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
236
+ }
237
+ /**
238
+ * Pull the request context the dashboard's `/api/v1/log-detection`
239
+ * endpoint expects out of a `NextRequest`. Works under both Node and
240
+ * Edge runtimes — no runtime-specific APIs.
241
+ */
242
+ function extractReporterContext(req, policy) {
243
+ return {
244
+ userAgent: req.headers.get("user-agent") ?? void 0,
245
+ ipAddress: require_utils.getClientIp(req, policy),
246
+ path: req.nextUrl.pathname,
247
+ url: req.nextUrl.href,
248
+ method: req.method
249
+ };
250
+ }
251
+ /** The engine's default options for this config; per-request fields go on top. */
252
+ function buildVerifyOpts(config) {
253
+ return (0, _kya_os_checkpoint_wasm_runtime_adapters.makeEngineDefaults)(config);
254
+ }
255
+ async function dispatchOnResult(config, result, req) {
256
+ if (!config.onResult) return;
257
+ try {
258
+ await config.onResult(result, req);
259
+ } catch {}
260
+ }
261
+
262
+ //#endregion
263
+ Object.defineProperty(exports, 'VERSION', {
264
+ enumerable: true,
265
+ get: function () {
266
+ return VERSION;
267
+ }
268
+ });
269
+ Object.defineProperty(exports, 'makeNextMiddleware', {
270
+ enumerable: true,
271
+ get: function () {
272
+ return makeNextMiddleware;
273
+ }
274
+ });
@@ -0,0 +1,17 @@
1
+ import "./config-CPP1RV0f.mjs";
2
+ import { ComposedPolicyContext } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
3
+ import { NextRequest, NextResponse } from "next/server.js";
4
+ import "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
5
+ import { VerifyResult } from "@kya-os/checkpoint-wasm-runtime/engine";
6
+ import "@kya-os/checkpoint-wasm-runtime/orchestrator";
7
+ //#region src/middleware-core.d.ts
8
+ /**
9
+ * Installed SDK version, self-reported to the detection reporter so the
10
+ * dashboard can version-gate "composed policy enforces here". MUST equal
11
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
12
+ * drifted). Re-exported as `VERSION` from the package index.
13
+ */
14
+ declare const VERSION = "1.11.0";
15
+ //#endregion
16
+ export { VERSION as t };
17
+ //# sourceMappingURL=middleware-core-DycsbHUd.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-DycsbHUd.d.mts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;;;;cA8Qa"}
@@ -1,8 +1,16 @@
1
- import { t as CheckpointConfig } from "./config-Doe0Tn53.mjs";
1
+ import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-CPP1RV0f.mjs";
2
+ import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.mjs";
2
3
  import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
3
4
  import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
4
5
  //#region src/middleware-edge.d.ts
5
- export declare function withCheckpoint(config: CheckpointConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
6
+ export declare function withCheckpoint(config: CheckpointEdgeConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
7
+ /**
8
+ * A project has a Cedar policy, but this Edge middleware has no Cedar module to
9
+ * evaluate it with.
10
+ */
11
+ export declare class CedarWasmModuleMissingError extends Error {
12
+ constructor(projectId: string);
13
+ }
6
14
  //#endregion
7
- export { type CheckpointConfig, initEngineEdge, initPolicyEvaluatorEdge };
15
+ export { type CheckpointConfig, type CheckpointEdgeConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, getCheckpointPostureOutcome, initEngineEdge, initPolicyEvaluatorEdge };
8
16
  //# sourceMappingURL=middleware-edge.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-edge.d.mts","names":[],"sources":["../src/middleware-edge.ts"],"mappings":";;;;wBAqBgB,eAAe,QAAQ,oBAAgB,2BAAA,aAAA,QAAA,2BAAA,iCAAA,8BAAA"}
1
+ {"version":3,"file":"middleware-edge.d.mts","names":[],"sources":["../src/middleware-edge.ts"],"mappings":";;;;;wBA+BgB,eAAe,QAAQ,wBAAoB,2BAAA,aAAA,QAAA,2BAAA,iCAAA,8BAAA;;;;;qBAwD9C,oCAAoC;EACnC,YAAA"}
@@ -1,8 +1,16 @@
1
- import { t as CheckpointConfig } from "./config-CbAg2mze.js";
1
+ import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-DVgOFxJs.js";
2
+ import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.js";
2
3
  import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
3
4
  import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
4
5
  //#region src/middleware-edge.d.ts
5
- export declare function withCheckpoint(config: CheckpointConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
6
+ export declare function withCheckpoint(config: CheckpointEdgeConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
7
+ /**
8
+ * A project has a Cedar policy, but this Edge middleware has no Cedar module to
9
+ * evaluate it with.
10
+ */
11
+ export declare class CedarWasmModuleMissingError extends Error {
12
+ constructor(projectId: string);
13
+ }
6
14
  //#endregion
7
- export { type CheckpointConfig, initEngineEdge, initPolicyEvaluatorEdge };
15
+ export { type CheckpointConfig, type CheckpointEdgeConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, getCheckpointPostureOutcome, initEngineEdge, initPolicyEvaluatorEdge };
8
16
  //# sourceMappingURL=middleware-edge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-edge.d.ts","names":[],"sources":["../src/middleware-edge.ts"],"mappings":";;;;wBAqBgB,eAAe,QAAQ,oBAAgB,2BAAA,aAAA,QAAA,2BAAA,iCAAA,8BAAA"}
1
+ {"version":3,"file":"middleware-edge.d.ts","names":[],"sources":["../src/middleware-edge.ts"],"mappings":";;;;;wBA+BgB,eAAe,QAAQ,wBAAoB,2BAAA,aAAA,QAAA,2BAAA,iCAAA,8BAAA;;;;;qBAwD9C,oCAAoC;EACnC,YAAA"}
@@ -1,46 +1,99 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_composed_policy = require('./composed-policy.js');
3
- const require_middleware_core = require('./middleware-core-D6TijE6P.js');
4
- let _kya_os_checkpoint_shared = require("@kya-os/checkpoint-shared");
2
+ const require_middleware_core = require('./middleware-core-CMc-2QkU.js');
3
+ const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
4
+ let _kya_os_checkpoint_wasm_runtime_composed_policy = require("@kya-os/checkpoint-wasm-runtime/composed-policy");
5
+ let _kya_os_checkpoint_shared_policy_fetcher = require("@kya-os/checkpoint-shared/policy/fetcher");
5
6
  let _kya_os_checkpoint_wasm_runtime_orchestrator_edge = require("@kya-os/checkpoint-wasm-runtime/orchestrator/edge");
6
7
  let _kya_os_checkpoint_wasm_runtime_policy_edge = require("@kya-os/checkpoint-wasm-runtime/policy-edge");
7
8
 
8
9
  //#region src/middleware-edge.ts
9
- /** Edge host: eagerly initialize its engine and opt into Cedar only when wired. */
10
+ /**
11
+ * Edge host: the engine runs on the module the host passes. The Cedar build
12
+ * (`./cedar-wasm`) is the engine plus Cedar, so passed as `engineWasmModule`
13
+ * (or alone as `cedarWasmModule`) one instance serves detection and policy.
14
+ */
10
15
  function withCheckpoint(config) {
11
- (0, _kya_os_checkpoint_wasm_runtime_orchestrator_edge.initEngineEdge)();
12
- return require_middleware_core.makeNextMiddleware(_kya_os_checkpoint_wasm_runtime_orchestrator_edge.verifyRequestEdge, _kya_os_checkpoint_wasm_runtime_orchestrator_edge.renderDecisionAsResponse, config, {
16
+ return require_middleware_core.makeNextMiddleware(config, {
13
17
  runtime: "edge",
14
- buildComposedContext
18
+ loadEngine: async () => {
19
+ await (0, _kya_os_checkpoint_wasm_runtime_orchestrator_edge.initEngineEdge)(engineModule(config));
20
+ return {
21
+ verifyRequest: _kya_os_checkpoint_wasm_runtime_orchestrator_edge.verifyRequestEdge,
22
+ renderDecisionAsResponse: _kya_os_checkpoint_wasm_runtime_orchestrator_edge.renderDecisionAsResponse
23
+ };
24
+ },
25
+ buildComposedContext,
26
+ start: checkModules
15
27
  });
16
28
  }
29
+ /** The module the engine runs on: `engineWasmModule`, else the Cedar build. */
30
+ function engineModule(config) {
31
+ return config.engineWasmModule ?? config.cedarWasmModule;
32
+ }
33
+ /** The Cedar build, whichever field it was passed in. */
34
+ function cedarModule(config) {
35
+ if (config.cedarWasmModule) return config.cedarWasmModule;
36
+ return (0, _kya_os_checkpoint_wasm_runtime_policy_edge.isCedarModule)(config.engineWasmModule) ? config.engineWasmModule : void 0;
37
+ }
38
+ function checkModules(config) {
39
+ if (!engineModule(config)) throw new Error("withCheckpoint on the Edge runtime needs engineWasmModule: import it from '@kya-os/checkpoint-nextjs/engine-wasm' (detection), or from '@kya-os/checkpoint-nextjs/cedar-wasm' (detection and Cedar policy), and pass it in the config");
40
+ if (config.debug && config.engineWasmModule && config.cedarWasmModule && !(0, _kya_os_checkpoint_wasm_runtime_policy_edge.isCedarModule)(config.engineWasmModule)) console.warn("[checkpoint] engineWasmModule and cedarWasmModule are two different builds, so the Edge bundle carries the engine twice. The Cedar build is the engine too: pass '@kya-os/checkpoint-nextjs/cedar-wasm' as engineWasmModule alone to run detection and Cedar on one module.");
41
+ }
42
+ /**
43
+ * A project has a Cedar policy, but this Edge middleware has no Cedar module to
44
+ * evaluate it with.
45
+ */
46
+ var CedarWasmModuleMissingError = class extends Error {
47
+ constructor(projectId) {
48
+ super(`Project ${projectId} has a Cedar policy, but withCheckpoint on the Edge runtime has no Cedar module to evaluate it: import it from '@kya-os/checkpoint-nextjs/cedar-wasm' and pass it as engineWasmModule, in place of the engine-only build, so one module runs detection and Cedar. Requests are answered 503 while the policy is enforcing.`);
49
+ this.name = "CedarWasmModuleMissingError";
50
+ }
51
+ };
17
52
  /**
18
- * Build the EDGE-runtime composed-policy context. Unlike Node, edge composed
19
- * enforcement is CONSUMER-OPT-IN: it requires `cedarWasmModule` to be wired so
20
- * the ~2 MB cedar binary is never forced into every consumer's Edge Middleware
21
- * bundle, and so the unproven `new URL('…cedar…')` fallback fetch is never
22
- * reached. Without it the seam stays inert — edge behaves exactly as 1.4.0.
23
- * When wired, the cedar-web module is registered once via
24
- * `initPolicyEvaluatorEdge`, and the async `evaluatePolicy` compiler is injected
25
- * into the shared core (its single-flight cache absorbs the async compile).
53
+ * Build the EDGE-runtime composed-policy context. The Cedar build is opt-in on
54
+ * the Edge runtime (it is larger than the engine-only build), so Edge bundles
55
+ * that never evaluate Cedar don't carry it. When the host passes it, as
56
+ * `engineWasmModule` or `cedarWasmModule`, it is registered via
57
+ * `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's own
58
+ * instance when the engine runs on it, and the async `evaluatePolicy` compiler
59
+ * is injected into the shared core.
60
+ *
61
+ * Without it a project's policy is still fetched and is never skipped: its
62
+ * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar
63
+ * policy is unaffected, a policy in shadow mode keeps the structured decision,
64
+ * and an enforcing policy answers 503, as any composed-policy fault does.
26
65
  */
27
66
  function buildComposedContext(config) {
28
67
  if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
29
- if (!config.projectId || !config.cedarWasmModule) return null;
30
- (0, _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge)(config.cedarWasmModule);
31
- return require_composed_policy.makeComposedPolicyContext({
32
- projectId: config.projectId,
33
- fetcher: new _kya_os_checkpoint_shared.PolicyFetcher({
34
- apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? "https://kya.vouched.id",
68
+ if (!config.projectId) return null;
69
+ const projectId = config.projectId;
70
+ const cedarWasmModule = cedarModule(config);
71
+ if (cedarWasmModule) (0, _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge)(cedarWasmModule);
72
+ let reportedMissingModule = false;
73
+ return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.makeComposedPolicyContext)({
74
+ projectId,
75
+ fetcher: new _kya_os_checkpoint_shared_policy_fetcher.PolicyFetcher({
76
+ apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? _kya_os_checkpoint_wasm_runtime_composed_policy.DEFAULT_DASHBOARD_URL,
35
77
  apiKey: config.apiKey,
36
- cacheTtlSeconds: config.policyCacheTtlSeconds
78
+ cacheTtlSeconds: config.policyCacheTtlSeconds,
79
+ throwOnUnavailable: true
37
80
  }),
38
- compile: (language, source) => (0, _kya_os_checkpoint_wasm_runtime_policy_edge.evaluatePolicy)(language, source),
39
- logger: config.debug ? require_composed_policy.consoleComposedPolicyLogger : void 0
81
+ compile: async (language, source) => {
82
+ if (cedarWasmModule) return (0, _kya_os_checkpoint_wasm_runtime_policy_edge.evaluatePolicy)(language, source);
83
+ const error = new CedarWasmModuleMissingError(projectId);
84
+ if (!reportedMissingModule) {
85
+ reportedMissingModule = true;
86
+ console.error(`[checkpoint] ${error.message}`);
87
+ }
88
+ throw error;
89
+ },
90
+ logger: config.debug ? _kya_os_checkpoint_wasm_runtime_composed_policy.consoleComposedPolicyLogger : void 0
40
91
  });
41
92
  }
42
93
 
43
94
  //#endregion
95
+ exports.CedarWasmModuleMissingError = CedarWasmModuleMissingError;
96
+ exports.getCheckpointPostureOutcome = require_posture_outcome.getCheckpointPostureOutcome;
44
97
  exports.initEngineEdge = _kya_os_checkpoint_wasm_runtime_orchestrator_edge.initEngineEdge;
45
98
  exports.initPolicyEvaluatorEdge = _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge;
46
99
  exports.withCheckpoint = withCheckpoint;
@@ -1,44 +1,95 @@
1
- import { DEFAULT_DASHBOARD_URL, consoleComposedPolicyLogger, makeComposedPolicyContext } from "./composed-policy.mjs";
2
- import { n as makeNextMiddleware } from "./middleware-core-BYQP9FND.mjs";
3
- import { PolicyFetcher } from "@kya-os/checkpoint-shared";
1
+ import { n as makeNextMiddleware } from "./middleware-core-B0jf5_Hm.mjs";
2
+ import { t as getCheckpointPostureOutcome } from "./posture-outcome-DQ4fdMfq.mjs";
3
+ import { DEFAULT_DASHBOARD_URL, consoleComposedPolicyLogger, makeComposedPolicyContext } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
4
+ import { PolicyFetcher } from "@kya-os/checkpoint-shared/policy/fetcher";
4
5
  import { initEngineEdge, renderDecisionAsResponse, verifyRequestEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
5
- import { evaluatePolicy as evaluatePolicy$1, initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
6
+ import { evaluatePolicy, initPolicyEvaluatorEdge, isCedarModule } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
6
7
 
7
8
  //#region src/middleware-edge.ts
8
- /** Edge host: eagerly initialize its engine and opt into Cedar only when wired. */
9
+ /**
10
+ * Edge host: the engine runs on the module the host passes. The Cedar build
11
+ * (`./cedar-wasm`) is the engine plus Cedar, so passed as `engineWasmModule`
12
+ * (or alone as `cedarWasmModule`) one instance serves detection and policy.
13
+ */
9
14
  function withCheckpoint(config) {
10
- initEngineEdge();
11
- return makeNextMiddleware(verifyRequestEdge, renderDecisionAsResponse, config, {
15
+ return makeNextMiddleware(config, {
12
16
  runtime: "edge",
13
- buildComposedContext
17
+ loadEngine: async () => {
18
+ await initEngineEdge(engineModule(config));
19
+ return {
20
+ verifyRequest: verifyRequestEdge,
21
+ renderDecisionAsResponse
22
+ };
23
+ },
24
+ buildComposedContext,
25
+ start: checkModules
14
26
  });
15
27
  }
28
+ /** The module the engine runs on: `engineWasmModule`, else the Cedar build. */
29
+ function engineModule(config) {
30
+ return config.engineWasmModule ?? config.cedarWasmModule;
31
+ }
32
+ /** The Cedar build, whichever field it was passed in. */
33
+ function cedarModule(config) {
34
+ if (config.cedarWasmModule) return config.cedarWasmModule;
35
+ return isCedarModule(config.engineWasmModule) ? config.engineWasmModule : void 0;
36
+ }
37
+ function checkModules(config) {
38
+ if (!engineModule(config)) throw new Error("withCheckpoint on the Edge runtime needs engineWasmModule: import it from '@kya-os/checkpoint-nextjs/engine-wasm' (detection), or from '@kya-os/checkpoint-nextjs/cedar-wasm' (detection and Cedar policy), and pass it in the config");
39
+ if (config.debug && config.engineWasmModule && config.cedarWasmModule && !isCedarModule(config.engineWasmModule)) console.warn("[checkpoint] engineWasmModule and cedarWasmModule are two different builds, so the Edge bundle carries the engine twice. The Cedar build is the engine too: pass '@kya-os/checkpoint-nextjs/cedar-wasm' as engineWasmModule alone to run detection and Cedar on one module.");
40
+ }
41
+ /**
42
+ * A project has a Cedar policy, but this Edge middleware has no Cedar module to
43
+ * evaluate it with.
44
+ */
45
+ var CedarWasmModuleMissingError = class extends Error {
46
+ constructor(projectId) {
47
+ super(`Project ${projectId} has a Cedar policy, but withCheckpoint on the Edge runtime has no Cedar module to evaluate it: import it from '@kya-os/checkpoint-nextjs/cedar-wasm' and pass it as engineWasmModule, in place of the engine-only build, so one module runs detection and Cedar. Requests are answered 503 while the policy is enforcing.`);
48
+ this.name = "CedarWasmModuleMissingError";
49
+ }
50
+ };
16
51
  /**
17
- * Build the EDGE-runtime composed-policy context. Unlike Node, edge composed
18
- * enforcement is CONSUMER-OPT-IN: it requires `cedarWasmModule` to be wired so
19
- * the ~2 MB cedar binary is never forced into every consumer's Edge Middleware
20
- * bundle, and so the unproven `new URL('…cedar…')` fallback fetch is never
21
- * reached. Without it the seam stays inert — edge behaves exactly as 1.4.0.
22
- * When wired, the cedar-web module is registered once via
23
- * `initPolicyEvaluatorEdge`, and the async `evaluatePolicy` compiler is injected
24
- * into the shared core (its single-flight cache absorbs the async compile).
52
+ * Build the EDGE-runtime composed-policy context. The Cedar build is opt-in on
53
+ * the Edge runtime (it is larger than the engine-only build), so Edge bundles
54
+ * that never evaluate Cedar don't carry it. When the host passes it, as
55
+ * `engineWasmModule` or `cedarWasmModule`, it is registered via
56
+ * `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's own
57
+ * instance when the engine runs on it, and the async `evaluatePolicy` compiler
58
+ * is injected into the shared core.
59
+ *
60
+ * Without it a project's policy is still fetched and is never skipped: its
61
+ * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar
62
+ * policy is unaffected, a policy in shadow mode keeps the structured decision,
63
+ * and an enforcing policy answers 503, as any composed-policy fault does.
25
64
  */
26
65
  function buildComposedContext(config) {
27
66
  if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
28
- if (!config.projectId || !config.cedarWasmModule) return null;
29
- initPolicyEvaluatorEdge(config.cedarWasmModule);
67
+ if (!config.projectId) return null;
68
+ const projectId = config.projectId;
69
+ const cedarWasmModule = cedarModule(config);
70
+ if (cedarWasmModule) initPolicyEvaluatorEdge(cedarWasmModule);
71
+ let reportedMissingModule = false;
30
72
  return makeComposedPolicyContext({
31
- projectId: config.projectId,
73
+ projectId,
32
74
  fetcher: new PolicyFetcher({
33
- apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? "https://kya.vouched.id",
75
+ apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
34
76
  apiKey: config.apiKey,
35
- cacheTtlSeconds: config.policyCacheTtlSeconds
77
+ cacheTtlSeconds: config.policyCacheTtlSeconds,
78
+ throwOnUnavailable: true
36
79
  }),
37
- compile: (language, source) => evaluatePolicy$1(language, source),
80
+ compile: async (language, source) => {
81
+ if (cedarWasmModule) return evaluatePolicy(language, source);
82
+ const error = new CedarWasmModuleMissingError(projectId);
83
+ if (!reportedMissingModule) {
84
+ reportedMissingModule = true;
85
+ console.error(`[checkpoint] ${error.message}`);
86
+ }
87
+ throw error;
88
+ },
38
89
  logger: config.debug ? consoleComposedPolicyLogger : void 0
39
90
  });
40
91
  }
41
92
 
42
93
  //#endregion
43
- export { initEngineEdge, initPolicyEvaluatorEdge, withCheckpoint };
94
+ export { CedarWasmModuleMissingError, getCheckpointPostureOutcome, initEngineEdge, initPolicyEvaluatorEdge, withCheckpoint };
44
95
  //# sourceMappingURL=middleware-edge.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-edge.mjs","names":["evaluatePolicy"],"sources":["../src/middleware-edge.ts"],"sourcesContent":["/** Edge host: eagerly initialize its engine and opt into Cedar only when wired. */\nimport {\n initEngineEdge,\n renderDecisionAsResponse,\n verifyRequestEdge,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';\nimport {\n evaluatePolicy,\n initPolicyEvaluatorEdge,\n} from '@kya-os/checkpoint-wasm-runtime/policy-edge';\nimport { PolicyFetcher } from '@kya-os/checkpoint-shared';\nimport {\n makeComposedPolicyContext,\n consoleComposedPolicyLogger,\n DEFAULT_DASHBOARD_URL,\n type ComposedPolicyContext,\n} from './composed-policy';\nimport { makeNextMiddleware } from './middleware-core';\nimport type { CheckpointConfig } from './config';\nexport type { CheckpointConfig } from './config';\n\nexport function withCheckpoint(config: CheckpointConfig) {\n // The first request awaits this same idempotent initialization promise.\n void initEngineEdge();\n return makeNextMiddleware(verifyRequestEdge, renderDecisionAsResponse, config, {\n runtime: 'edge',\n buildComposedContext,\n });\n}\n\n/**\n * Build the EDGE-runtime composed-policy context. Unlike Node, edge composed\n * enforcement is CONSUMER-OPT-IN: it requires `cedarWasmModule` to be wired so\n * the ~2 MB cedar binary is never forced into every consumer's Edge Middleware\n * bundle, and so the unproven `new URL('…cedar…')` fallback fetch is never\n * reached. Without it the seam stays inert — edge behaves exactly as 1.4.0.\n * When wired, the cedar-web module is registered once via\n * `initPolicyEvaluatorEdge`, and the async `evaluatePolicy` compiler is injected\n * into the shared core (its single-flight cache absorbs the async compile).\n */\nfunction buildComposedContext(config: CheckpointConfig): ComposedPolicyContext | null {\n if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;\n if (!config.projectId || !config.cedarWasmModule) return null;\n initPolicyEvaluatorEdge(config.cedarWasmModule);\n return makeComposedPolicyContext({\n projectId: config.projectId,\n fetcher: new PolicyFetcher({\n apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,\n apiKey: config.apiKey,\n cacheTtlSeconds: config.policyCacheTtlSeconds,\n }),\n compile: (language, source) => evaluatePolicy(language, source),\n logger: config.debug ? consoleComposedPolicyLogger : undefined,\n });\n}\n\n// Allow hosts to initialize their WASM modules explicitly at startup.\nexport { initEngineEdge, initPolicyEvaluatorEdge };\n"],"mappings":";;;;;;;;AAqBA,SAAgB,eAAe,QAA0B;CAEvD,AAAK,eAAe;CACpB,OAAO,mBAAmB,mBAAmB,0BAA0B,QAAQ;EAC7E,SAAS;EACT;CACF,CAAC;AACH;;;;;;;;;;;AAYA,SAAS,qBAAqB,QAAwD;CACpF,IAAI,OAAO,wBAAwB,OAAO,OAAO;CACjD,IAAI,CAAC,OAAO,aAAa,CAAC,OAAO,iBAAiB,OAAO;CACzD,wBAAwB,OAAO,eAAe;CAC9C,OAAO,0BAA0B;EAC/B,WAAW,OAAO;EAClB,SAAS,IAAI,cAAc;GACzB,YAAY,OAAO,gBAAgB,OAAO;GAC1C,QAAQ,OAAO;GACf,iBAAiB,OAAO;EAC1B,CAAC;EACD,UAAU,UAAU,WAAWA,iBAAe,UAAU,MAAM;EAC9D,QAAQ,OAAO,QAAQ,8BAA8B;CACvD,CAAC;AACH"}
1
+ {"version":3,"file":"middleware-edge.mjs","names":[],"sources":["../src/middleware-edge.ts"],"sourcesContent":["/**\n * Edge host: the engine runs on the module the host passes. The Cedar build\n * (`./cedar-wasm`) is the engine plus Cedar, so passed as `engineWasmModule`\n * (or alone as `cedarWasmModule`) one instance serves detection and policy.\n */\nimport {\n initEngineEdge,\n renderDecisionAsResponse,\n verifyRequestEdge,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';\nimport {\n evaluatePolicy,\n initPolicyEvaluatorEdge,\n isCedarModule,\n} from '@kya-os/checkpoint-wasm-runtime/policy-edge';\nimport { PolicyFetcher } from '@kya-os/checkpoint-shared/policy/fetcher';\nimport {\n makeComposedPolicyContext,\n consoleComposedPolicyLogger,\n DEFAULT_DASHBOARD_URL,\n type ComposedPolicyContext,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\nimport { makeNextMiddleware } from './middleware-core';\nimport type { CheckpointConfig, CheckpointEdgeConfig } from './config';\nexport type { CheckpointConfig, CheckpointEdgeConfig } from './config';\nexport {\n getCheckpointPostureOutcome,\n type CheckpointPostureOptions,\n type CheckpointPostureOutcome,\n} from './posture-outcome';\n\nexport function withCheckpoint(config: CheckpointEdgeConfig) {\n return makeNextMiddleware(config, {\n runtime: 'edge',\n // Every attempt passes the module: after a failed init wasm-runtime\n // forgets the module it was given, and an init without one tries to\n // compile bytes, which the Edge runtime cannot do. A failed load is\n // retried by the next request; once loaded, this resolves at once.\n loadEngine: async () => {\n await initEngineEdge(engineModule(config));\n return { verifyRequest: verifyRequestEdge, renderDecisionAsResponse };\n },\n buildComposedContext,\n start: checkModules,\n });\n}\n\n/** The module the engine runs on: `engineWasmModule`, else the Cedar build. */\nfunction engineModule(config: CheckpointConfig): WebAssembly.Module | undefined {\n return config.engineWasmModule ?? config.cedarWasmModule;\n}\n\n/** The Cedar build, whichever field it was passed in. */\nfunction cedarModule(config: CheckpointConfig): WebAssembly.Module | undefined {\n if (config.cedarWasmModule) return config.cedarWasmModule;\n return isCedarModule(config.engineWasmModule) ? config.engineWasmModule : undefined;\n}\n\nfunction checkModules(config: CheckpointConfig): void {\n // `config` is typed, but the `.` entry's types are the Node build's, where\n // both modules are optional, so check here.\n if (!engineModule(config)) {\n throw new Error(\n 'withCheckpoint on the Edge runtime needs engineWasmModule: import it from ' +\n \"'@kya-os/checkpoint-nextjs/engine-wasm' (detection), or from \" +\n \"'@kya-os/checkpoint-nextjs/cedar-wasm' (detection and Cedar policy), and pass it in the config\"\n );\n }\n if (\n config.debug &&\n config.engineWasmModule &&\n config.cedarWasmModule &&\n !isCedarModule(config.engineWasmModule)\n ) {\n console.warn(\n '[checkpoint] engineWasmModule and cedarWasmModule are two different builds, so the Edge ' +\n 'bundle carries the engine twice. The Cedar build is the engine too: pass ' +\n \"'@kya-os/checkpoint-nextjs/cedar-wasm' as engineWasmModule alone to run detection and \" +\n 'Cedar on one module.'\n );\n }\n}\n\n/**\n * A project has a Cedar policy, but this Edge middleware has no Cedar module to\n * evaluate it with.\n */\nexport class CedarWasmModuleMissingError extends Error {\n constructor(projectId: string) {\n super(\n `Project ${projectId} has a Cedar policy, but withCheckpoint on the Edge runtime has no ` +\n \"Cedar module to evaluate it: import it from '@kya-os/checkpoint-nextjs/cedar-wasm' and \" +\n 'pass it as engineWasmModule, in place of the engine-only build, so one module runs ' +\n 'detection and Cedar. Requests are answered 503 while the policy is enforcing.'\n );\n this.name = 'CedarWasmModuleMissingError';\n }\n}\n\n/**\n * Build the EDGE-runtime composed-policy context. The Cedar build is opt-in on\n * the Edge runtime (it is larger than the engine-only build), so Edge bundles\n * that never evaluate Cedar don't carry it. When the host passes it, as\n * `engineWasmModule` or `cedarWasmModule`, it is registered via\n * `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's own\n * instance when the engine runs on it, and the async `evaluatePolicy` compiler\n * is injected into the shared core.\n *\n * Without it a project's policy is still fetched and is never skipped: its\n * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar\n * policy is unaffected, a policy in shadow mode keeps the structured decision,\n * and an enforcing policy answers 503, as any composed-policy fault does.\n */\nfunction buildComposedContext(config: CheckpointConfig): ComposedPolicyContext | null {\n if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;\n if (!config.projectId) return null;\n const projectId = config.projectId;\n const cedarWasmModule = cedarModule(config);\n if (cedarWasmModule) initPolicyEvaluatorEdge(cedarWasmModule);\n let reportedMissingModule = false;\n return makeComposedPolicyContext({\n projectId,\n fetcher: new PolicyFetcher({\n apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,\n apiKey: config.apiKey,\n cacheTtlSeconds: config.policyCacheTtlSeconds,\n throwOnUnavailable: true,\n }),\n compile: async (language, source) => {\n if (cedarWasmModule) return evaluatePolicy(language, source);\n const error = new CedarWasmModuleMissingError(projectId);\n if (!reportedMissingModule) {\n reportedMissingModule = true;\n console.error(`[checkpoint] ${error.message}`);\n }\n throw error;\n },\n logger: config.debug ? consoleComposedPolicyLogger : undefined,\n });\n}\n\n// Allow hosts to initialize their WASM modules explicitly at startup.\nexport { initEngineEdge, initPolicyEvaluatorEdge };\n"],"mappings":";;;;;;;;;;;;;AA+BA,SAAgB,eAAe,QAA8B;CAC3D,OAAO,mBAAmB,QAAQ;EAChC,SAAS;EAKT,YAAY,YAAY;GACtB,MAAM,eAAe,aAAa,MAAM,CAAC;GACzC,OAAO;IAAE,eAAe;IAAmB;GAAyB;EACtE;EACA;EACA,OAAO;CACT,CAAC;AACH;;AAGA,SAAS,aAAa,QAA0D;CAC9E,OAAO,OAAO,oBAAoB,OAAO;AAC3C;;AAGA,SAAS,YAAY,QAA0D;CAC7E,IAAI,OAAO,iBAAiB,OAAO,OAAO;CAC1C,OAAO,cAAc,OAAO,gBAAgB,IAAI,OAAO,mBAAmB;AAC5E;AAEA,SAAS,aAAa,QAAgC;CAGpD,IAAI,CAAC,aAAa,MAAM,GACtB,MAAM,IAAI,MACR,uOAGF;CAEF,IACE,OAAO,SACP,OAAO,oBACP,OAAO,mBACP,CAAC,cAAc,OAAO,gBAAgB,GAEtC,QAAQ,KACN,6QAIF;AAEJ;;;;;AAMA,IAAa,8BAAb,cAAiD,MAAM;CACrD,YAAY,WAAmB;EAC7B,MACE,WAAW,UAAU,2TAIvB;EACA,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,qBAAqB,QAAwD;CACpF,IAAI,OAAO,wBAAwB,OAAO,OAAO;CACjD,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,MAAM,YAAY,OAAO;CACzB,MAAM,kBAAkB,YAAY,MAAM;CAC1C,IAAI,iBAAiB,wBAAwB,eAAe;CAC5D,IAAI,wBAAwB;CAC5B,OAAO,0BAA0B;EAC/B;EACA,SAAS,IAAI,cAAc;GACzB,YAAY,OAAO,gBAAgB,OAAO,WAAW;GACrD,QAAQ,OAAO;GACf,iBAAiB,OAAO;GACxB,oBAAoB;EACtB,CAAC;EACD,SAAS,OAAO,UAAU,WAAW;GACnC,IAAI,iBAAiB,OAAO,eAAe,UAAU,MAAM;GAC3D,MAAM,QAAQ,IAAI,4BAA4B,SAAS;GACvD,IAAI,CAAC,uBAAuB;IAC1B,wBAAwB;IACxB,QAAQ,MAAM,gBAAgB,MAAM,SAAS;GAC/C;GACA,MAAM;EACR;EACA,QAAQ,OAAO,QAAQ,8BAA8B;CACvD,CAAC;AACH"}