@kya-os/checkpoint-nextjs 1.10.0 → 1.12.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 (214) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +217 -35
  3. package/dist/{adapt.mjs → adapt-BvqYgrAk.mjs} +15 -4
  4. package/dist/adapt-BvqYgrAk.mjs.map +1 -0
  5. package/dist/{adapt.js → adapt-DUEIfZnx.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-BtsYJU5u.d.mts +131 -0
  16. package/dist/api-middleware-BtsYJU5u.d.mts.map +1 -0
  17. package/dist/{api-middleware-CMDRoQik.mjs → api-middleware-DvmkJ_Li.mjs} +68 -38
  18. package/dist/api-middleware-DvmkJ_Li.mjs.map +1 -0
  19. package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
  20. package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
  21. package/dist/{api-middleware-CDSh3TSE.js → api-middleware-beNlXd5P.js} +75 -63
  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-D7h2w_it.d.mts +89 -0
  34. package/dist/config-D7h2w_it.d.mts.map +1 -0
  35. package/dist/config-DkXvl4nH.d.ts +89 -0
  36. package/dist/config-DkXvl4nH.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 +5 -5
  58. package/dist/middleware-bundler.mjs +5 -5
  59. package/dist/middleware-bundler.mjs.map +1 -1
  60. package/dist/middleware-core-B1GuspOY.js +169 -0
  61. package/dist/middleware-core-BmW2kH8J.d.ts +14 -0
  62. package/dist/middleware-core-BmW2kH8J.d.ts.map +1 -0
  63. package/dist/middleware-core-CnPUoD2v.d.mts +14 -0
  64. package/dist/middleware-core-CnPUoD2v.d.mts.map +1 -0
  65. package/dist/middleware-core-WZeMSRqx.mjs +159 -0
  66. package/dist/middleware-core-WZeMSRqx.mjs.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 +68 -29
  72. package/dist/middleware-edge.mjs +68 -31
  73. package/dist/middleware-edge.mjs.map +1 -1
  74. package/dist/middleware-node-context-BvqrL2Ra.mjs +16 -0
  75. package/dist/middleware-node-context-BvqrL2Ra.mjs.map +1 -0
  76. package/dist/middleware-node-context-TRMTgp3y.js +20 -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 +14 -6
  82. package/dist/middleware-node.mjs +14 -6
  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-Cw7Zj290.d.ts +5 -0
  92. package/dist/public-api-DgCw1uo6.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 +0 -255
  120. package/dist/config-CbAg2mze.d.ts.map +0 -1
  121. package/dist/config-Doe0Tn53.d.mts +0 -255
  122. package/dist/config-Doe0Tn53.d.mts.map +0 -1
  123. package/dist/create-middleware.d.mts +0 -11
  124. package/dist/create-middleware.d.mts.map +0 -1
  125. package/dist/create-middleware.d.ts +0 -11
  126. package/dist/create-middleware.d.ts.map +0 -1
  127. package/dist/create-middleware.js +0 -39
  128. package/dist/create-middleware.mjs +0 -38
  129. package/dist/create-middleware.mjs.map +0 -1
  130. package/dist/edge/index.d.mts +0 -88
  131. package/dist/edge/index.d.mts.map +0 -1
  132. package/dist/edge/index.d.ts +0 -88
  133. package/dist/edge/index.d.ts.map +0 -1
  134. package/dist/edge/index.js +0 -362
  135. package/dist/edge/index.mjs +0 -362
  136. package/dist/edge/index.mjs.map +0 -1
  137. package/dist/edge-runtime-loader.d.mts +0 -49
  138. package/dist/edge-runtime-loader.d.mts.map +0 -1
  139. package/dist/edge-runtime-loader.d.ts +0 -49
  140. package/dist/edge-runtime-loader.d.ts.map +0 -1
  141. package/dist/edge-runtime-loader.js +0 -297
  142. package/dist/edge-runtime-loader.mjs +0 -292
  143. package/dist/edge-runtime-loader.mjs.map +0 -1
  144. package/dist/edge-wasm-middleware.d.mts +0 -43
  145. package/dist/edge-wasm-middleware.d.mts.map +0 -1
  146. package/dist/edge-wasm-middleware.d.ts +0 -43
  147. package/dist/edge-wasm-middleware.d.ts.map +0 -1
  148. package/dist/edge-wasm-middleware.js +0 -37
  149. package/dist/edge-wasm-middleware.mjs +0 -35
  150. package/dist/edge-wasm-middleware.mjs.map +0 -1
  151. package/dist/middleware-core-BYQP9FND.mjs +0 -165
  152. package/dist/middleware-core-BYQP9FND.mjs.map +0 -1
  153. package/dist/middleware-core-D6TijE6P.js +0 -175
  154. package/dist/middleware-node-CE4GevYs.d.ts +0 -20
  155. package/dist/middleware-node-CE4GevYs.d.ts.map +0 -1
  156. package/dist/middleware-node-DtyOuPta.d.mts +0 -20
  157. package/dist/middleware-node-DtyOuPta.d.mts.map +0 -1
  158. package/dist/middleware-node-context-BqPbf-fI.mjs +0 -34
  159. package/dist/middleware-node-context-BqPbf-fI.mjs.map +0 -1
  160. package/dist/middleware-node-context-rgnc7UNR.js +0 -38
  161. package/dist/middleware.d.mts +0 -25
  162. package/dist/middleware.d.mts.map +0 -1
  163. package/dist/middleware.d.ts +0 -25
  164. package/dist/middleware.d.ts.map +0 -1
  165. package/dist/middleware.js +0 -53
  166. package/dist/middleware.mjs +0 -51
  167. package/dist/middleware.mjs.map +0 -1
  168. package/dist/nodejs-wasm-loader.d.mts +0 -42
  169. package/dist/nodejs-wasm-loader.d.mts.map +0 -1
  170. package/dist/nodejs-wasm-loader.d.ts +0 -42
  171. package/dist/nodejs-wasm-loader.d.ts.map +0 -1
  172. package/dist/nodejs-wasm-loader.js +0 -70
  173. package/dist/nodejs-wasm-loader.mjs +0 -66
  174. package/dist/nodejs-wasm-loader.mjs.map +0 -1
  175. package/dist/policy.d.mts +0 -138
  176. package/dist/policy.d.mts.map +0 -1
  177. package/dist/policy.d.ts +0 -138
  178. package/dist/policy.d.ts.map +0 -1
  179. package/dist/policy.js +0 -236
  180. package/dist/policy.mjs +0 -205
  181. package/dist/policy.mjs.map +0 -1
  182. package/dist/session-tracker.d.mts +0 -50
  183. package/dist/session-tracker.d.mts.map +0 -1
  184. package/dist/session-tracker.d.ts +0 -50
  185. package/dist/session-tracker.d.ts.map +0 -1
  186. package/dist/session-tracker.js +0 -148
  187. package/dist/session-tracker.mjs +0 -147
  188. package/dist/session-tracker.mjs.map +0 -1
  189. package/dist/translate.d.mts +0 -48
  190. package/dist/translate.d.mts.map +0 -1
  191. package/dist/translate.d.ts +0 -48
  192. package/dist/translate.d.ts.map +0 -1
  193. package/dist/translate.js +0 -79
  194. package/dist/translate.mjs +0 -79
  195. package/dist/translate.mjs.map +0 -1
  196. package/dist/types-C0SkqLMM.d.mts +0 -102
  197. package/dist/types-C0SkqLMM.d.mts.map +0 -1
  198. package/dist/types-C7DNSCTO.d.ts +0 -102
  199. package/dist/types-C7DNSCTO.d.ts.map +0 -1
  200. package/dist/utils-Cj4XNhIY.mjs +0 -35
  201. package/dist/utils-Cj4XNhIY.mjs.map +0 -1
  202. package/dist/utils-DAisnYnI.js +0 -45
  203. package/dist/wasm-setup.d.mts +0 -47
  204. package/dist/wasm-setup.d.mts.map +0 -1
  205. package/dist/wasm-setup.d.ts +0 -47
  206. package/dist/wasm-setup.d.ts.map +0 -1
  207. package/dist/wasm-setup.js +0 -91
  208. package/dist/wasm-setup.mjs +0 -95
  209. package/dist/wasm-setup.mjs.map +0 -1
  210. package/wasm/agentshield_wasm.d.ts +0 -479
  211. package/wasm/agentshield_wasm.js +0 -1536
  212. package/wasm/agentshield_wasm_bg.wasm +0 -0
  213. package/wasm/package.json +0 -30
  214. package/wasm.d.ts +0 -21
@@ -0,0 +1,169 @@
1
+ const require_adapt = require('./adapt-DUEIfZnx.js');
2
+ const require_utils = require('./utils-dyFxqlFI.js');
3
+ let _kya_os_checkpoint_wasm_runtime_pipeline = require("@kya-os/checkpoint-wasm-runtime/pipeline");
4
+ let _vercel_functions = require("@vercel/functions");
5
+
6
+ //#region src/translate.ts
7
+ /**
8
+ * Translate a Next.js `NextRequest` into the orchestrator's
9
+ * `IncomingHttpLike` shape.
10
+ *
11
+ * When `opts.drainJsonBody !== false` and the request is JSON, the
12
+ * translator clones the request and reads the body into a string so
13
+ * the orchestrator's `buildAgentRequest` can extract a
14
+ * `_meta.proof.jws` envelope. The original `req.body` stream is
15
+ * preserved for downstream handlers via `req.clone()`.
16
+ *
17
+ * When the body can't be read (drain disabled, non-JSON, or a stream
18
+ * error) we pass `body: null` and the orchestrator routes to
19
+ * PlainHttp — same behavior as the pre-1.1.0 default.
20
+ */
21
+ async function nextRequestToHttpLike(req, opts = {}) {
22
+ const url = new URL(req.url);
23
+ const body = await tryDrainJsonBody(req, opts);
24
+ return {
25
+ method: req.method,
26
+ url: url.pathname + url.search,
27
+ headers: headersToRecord(req.headers),
28
+ body,
29
+ remoteAddress: require_utils.getClientIp(req, opts.clientIpPolicy)
30
+ };
31
+ }
32
+ /**
33
+ * Read the request body as a UTF-8 string when JSON and the caller
34
+ * has opted in (default). Returns `null` on any failure — the
35
+ * orchestrator handles `null` as "no body present" (→ PlainHttp).
36
+ *
37
+ * Clone-first means the original `req.body` ReadableStream stays
38
+ * unconsumed and downstream handlers can re-read it. Without the
39
+ * clone, calling `req.text()` in middleware would block any route
40
+ * handler that needs the body.
41
+ */
42
+ async function tryDrainJsonBody(req, opts) {
43
+ if (opts.drainJsonBody === false) return null;
44
+ if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
45
+ try {
46
+ return await req.clone().text();
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ /**
52
+ * Convert a `Headers` instance into a lowercase-keyed plain object.
53
+ * HTTP header names are case-insensitive (RFC 9110 § 5.1); the
54
+ * orchestrator does case-sensitive lookups, so we normalise to
55
+ * lowercase here. Multi-value headers (Set-Cookie, Accept) are
56
+ * surfaced as their `Headers.get()` view — a single string with
57
+ * comma-joined values, matching what other host adapters produce.
58
+ */
59
+ function headersToRecord(headers) {
60
+ const out = {};
61
+ headers.forEach((value, key) => {
62
+ out[key.toLowerCase()] = value;
63
+ });
64
+ return out;
65
+ }
66
+
67
+ //#endregion
68
+ //#region src/middleware-core.ts
69
+ /**
70
+ * The Next.js side of the shared request pipeline
71
+ * (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts
72
+ * inject their engine and Cedar compiler; runtime-specific WASM initialization
73
+ * stays in each host entry. Public withCheckpoint exports live there too.
74
+ */
75
+ /** npm package name this SDK self-reports to the detection reporter. */
76
+ const SDK_NAME = "@kya-os/checkpoint-nextjs";
77
+ /**
78
+ * Installed SDK version, self-reported to the detection reporter so the
79
+ * dashboard can version-gate "composed policy enforces here". MUST equal
80
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
81
+ * drifted). Re-exported as `VERSION` from the package index.
82
+ */
83
+ const VERSION = "1.12.0";
84
+ /**
85
+ * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
86
+ * suitable for `export default withCheckpoint({...})` in `middleware.ts`.
87
+ *
88
+ * Every verification decision flows through the Rust `kya-os-engine`
89
+ * via WASM. The TS layer translates request shape, runs the shared
90
+ * pipeline, and translates the verdict to `NextResponse`. No
91
+ * verification logic lives in this file.
92
+ *
93
+ * It never throws. An error in the configuration or in loading the engine
94
+ * would otherwise fail the middleware module, and a Next.js middleware that
95
+ * fails to load can let requests through unchecked. Every such error is
96
+ * answered 503 instead (fail closed) and logged.
97
+ */
98
+ function makeNextMiddleware(config, host) {
99
+ try {
100
+ return makeMiddleware(config, host);
101
+ } catch (error) {
102
+ return async function misconfiguredCheckpointMiddleware() {
103
+ console.error("[checkpoint] withCheckpoint is misconfigured; responding 503:", error);
104
+ return require_adapt.failClosedResponse();
105
+ };
106
+ }
107
+ }
108
+ function makeMiddleware(config, host) {
109
+ const pipeline = (0, _kya_os_checkpoint_wasm_runtime_pipeline.makeCheckpointPipeline)(config, {
110
+ sdk: {
111
+ name: SDK_NAME,
112
+ version: VERSION,
113
+ runtime: host.runtime
114
+ },
115
+ loadEngine: host.loadEngine,
116
+ policyCompiler: host.policyCompiler,
117
+ start: host.start
118
+ });
119
+ const translateOpts = {
120
+ drainJsonBody: config.drainJsonBody,
121
+ clientIpPolicy: config.clientIpPolicy
122
+ };
123
+ return async function checkpointMiddleware(req, event) {
124
+ const waitUntil = event ? (promise) => event.waitUntil(promise) : _vercel_functions.waitUntil;
125
+ try {
126
+ const { rendered } = await pipeline({
127
+ request: req,
128
+ translate: () => nextRequestToHttpLike(req, translateOpts),
129
+ headers: req.headers,
130
+ path: req.nextUrl.pathname,
131
+ clientIp: () => require_utils.getClientIp(req, config.clientIpPolicy),
132
+ reportContext: () => extractReporterContext(req, config.clientIpPolicy),
133
+ waitUntil
134
+ });
135
+ return require_adapt.adaptToNextResponse(rendered, req);
136
+ } catch (err) {
137
+ (0, _kya_os_checkpoint_wasm_runtime_pipeline.logPipelineFailure)(err, config.debug);
138
+ return require_adapt.failClosedResponse();
139
+ }
140
+ };
141
+ }
142
+ /**
143
+ * Pull the request context the dashboard's `/api/v1/log-detection`
144
+ * endpoint expects out of a `NextRequest`. Works under both Node and
145
+ * Edge runtimes — no runtime-specific APIs.
146
+ */
147
+ function extractReporterContext(req, policy) {
148
+ return {
149
+ userAgent: req.headers.get("user-agent") ?? void 0,
150
+ ipAddress: require_utils.getClientIp(req, policy),
151
+ path: req.nextUrl.pathname,
152
+ url: req.nextUrl.href,
153
+ method: req.method
154
+ };
155
+ }
156
+
157
+ //#endregion
158
+ Object.defineProperty(exports, 'VERSION', {
159
+ enumerable: true,
160
+ get: function () {
161
+ return VERSION;
162
+ }
163
+ });
164
+ Object.defineProperty(exports, 'makeNextMiddleware', {
165
+ enumerable: true,
166
+ get: function () {
167
+ return makeNextMiddleware;
168
+ }
169
+ });
@@ -0,0 +1,14 @@
1
+ import "./config-DkXvl4nH.js";
2
+ import { NextRequest, NextResponse } from "next/server.js";
3
+ import "@kya-os/checkpoint-wasm-runtime/pipeline";
4
+ //#region src/middleware-core.d.ts
5
+ /**
6
+ * Installed SDK version, self-reported to the detection reporter so the
7
+ * dashboard can version-gate "composed policy enforces here". MUST equal
8
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
9
+ * drifted). Re-exported as `VERSION` from the package index.
10
+ */
11
+ declare const VERSION = "1.12.0";
12
+ //#endregion
13
+ export { VERSION as t };
14
+ //# sourceMappingURL=middleware-core-BmW2kH8J.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-BmW2kH8J.d.ts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -0,0 +1,14 @@
1
+ import "./config-D7h2w_it.mjs";
2
+ import "@kya-os/checkpoint-wasm-runtime/pipeline";
3
+ import { NextRequest, NextResponse } from "next/server.js";
4
+ //#region src/middleware-core.d.ts
5
+ /**
6
+ * Installed SDK version, self-reported to the detection reporter so the
7
+ * dashboard can version-gate "composed policy enforces here". MUST equal
8
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
9
+ * drifted). Re-exported as `VERSION` from the package index.
10
+ */
11
+ declare const VERSION = "1.12.0";
12
+ //#endregion
13
+ export { VERSION as t };
14
+ //# sourceMappingURL=middleware-core-CnPUoD2v.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-CnPUoD2v.d.mts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -0,0 +1,159 @@
1
+ import { n as failClosedResponse, t as adaptToNextResponse } from "./adapt-BvqYgrAk.mjs";
2
+ import { t as getClientIp } from "./utils-Cnwg0VrY.mjs";
3
+ import { logPipelineFailure, makeCheckpointPipeline } from "@kya-os/checkpoint-wasm-runtime/pipeline";
4
+ import { waitUntil } from "@vercel/functions";
5
+
6
+ //#region src/translate.ts
7
+ /**
8
+ * Translate a Next.js `NextRequest` into the orchestrator's
9
+ * `IncomingHttpLike` shape.
10
+ *
11
+ * When `opts.drainJsonBody !== false` and the request is JSON, the
12
+ * translator clones the request and reads the body into a string so
13
+ * the orchestrator's `buildAgentRequest` can extract a
14
+ * `_meta.proof.jws` envelope. The original `req.body` stream is
15
+ * preserved for downstream handlers via `req.clone()`.
16
+ *
17
+ * When the body can't be read (drain disabled, non-JSON, or a stream
18
+ * error) we pass `body: null` and the orchestrator routes to
19
+ * PlainHttp — same behavior as the pre-1.1.0 default.
20
+ */
21
+ async function nextRequestToHttpLike(req, opts = {}) {
22
+ const url = new URL(req.url);
23
+ const body = await tryDrainJsonBody(req, opts);
24
+ return {
25
+ method: req.method,
26
+ url: url.pathname + url.search,
27
+ headers: headersToRecord(req.headers),
28
+ body,
29
+ remoteAddress: getClientIp(req, opts.clientIpPolicy)
30
+ };
31
+ }
32
+ /**
33
+ * Read the request body as a UTF-8 string when JSON and the caller
34
+ * has opted in (default). Returns `null` on any failure — the
35
+ * orchestrator handles `null` as "no body present" (→ PlainHttp).
36
+ *
37
+ * Clone-first means the original `req.body` ReadableStream stays
38
+ * unconsumed and downstream handlers can re-read it. Without the
39
+ * clone, calling `req.text()` in middleware would block any route
40
+ * handler that needs the body.
41
+ */
42
+ async function tryDrainJsonBody(req, opts) {
43
+ if (opts.drainJsonBody === false) return null;
44
+ if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
45
+ try {
46
+ return await req.clone().text();
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ /**
52
+ * Convert a `Headers` instance into a lowercase-keyed plain object.
53
+ * HTTP header names are case-insensitive (RFC 9110 § 5.1); the
54
+ * orchestrator does case-sensitive lookups, so we normalise to
55
+ * lowercase here. Multi-value headers (Set-Cookie, Accept) are
56
+ * surfaced as their `Headers.get()` view — a single string with
57
+ * comma-joined values, matching what other host adapters produce.
58
+ */
59
+ function headersToRecord(headers) {
60
+ const out = {};
61
+ headers.forEach((value, key) => {
62
+ out[key.toLowerCase()] = value;
63
+ });
64
+ return out;
65
+ }
66
+
67
+ //#endregion
68
+ //#region src/middleware-core.ts
69
+ /**
70
+ * The Next.js side of the shared request pipeline
71
+ * (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts
72
+ * inject their engine and Cedar compiler; runtime-specific WASM initialization
73
+ * stays in each host entry. Public withCheckpoint exports live there too.
74
+ */
75
+ /** npm package name this SDK self-reports to the detection reporter. */
76
+ const SDK_NAME = "@kya-os/checkpoint-nextjs";
77
+ /**
78
+ * Installed SDK version, self-reported to the detection reporter so the
79
+ * dashboard can version-gate "composed policy enforces here". MUST equal
80
+ * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
81
+ * drifted). Re-exported as `VERSION` from the package index.
82
+ */
83
+ const VERSION = "1.12.0";
84
+ /**
85
+ * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
86
+ * suitable for `export default withCheckpoint({...})` in `middleware.ts`.
87
+ *
88
+ * Every verification decision flows through the Rust `kya-os-engine`
89
+ * via WASM. The TS layer translates request shape, runs the shared
90
+ * pipeline, and translates the verdict to `NextResponse`. No
91
+ * verification logic lives in this file.
92
+ *
93
+ * It never throws. An error in the configuration or in loading the engine
94
+ * would otherwise fail the middleware module, and a Next.js middleware that
95
+ * fails to load can let requests through unchecked. Every such error is
96
+ * answered 503 instead (fail closed) and logged.
97
+ */
98
+ function makeNextMiddleware(config, host) {
99
+ try {
100
+ return makeMiddleware(config, host);
101
+ } catch (error) {
102
+ return async function misconfiguredCheckpointMiddleware() {
103
+ console.error("[checkpoint] withCheckpoint is misconfigured; responding 503:", error);
104
+ return failClosedResponse();
105
+ };
106
+ }
107
+ }
108
+ function makeMiddleware(config, host) {
109
+ const pipeline = makeCheckpointPipeline(config, {
110
+ sdk: {
111
+ name: SDK_NAME,
112
+ version: VERSION,
113
+ runtime: host.runtime
114
+ },
115
+ loadEngine: host.loadEngine,
116
+ policyCompiler: host.policyCompiler,
117
+ start: host.start
118
+ });
119
+ const translateOpts = {
120
+ drainJsonBody: config.drainJsonBody,
121
+ clientIpPolicy: config.clientIpPolicy
122
+ };
123
+ return async function checkpointMiddleware(req, event) {
124
+ const waitUntil$1 = event ? (promise) => event.waitUntil(promise) : waitUntil;
125
+ try {
126
+ const { rendered } = await pipeline({
127
+ request: req,
128
+ translate: () => nextRequestToHttpLike(req, translateOpts),
129
+ headers: req.headers,
130
+ path: req.nextUrl.pathname,
131
+ clientIp: () => getClientIp(req, config.clientIpPolicy),
132
+ reportContext: () => extractReporterContext(req, config.clientIpPolicy),
133
+ waitUntil: waitUntil$1
134
+ });
135
+ return adaptToNextResponse(rendered, req);
136
+ } catch (err) {
137
+ logPipelineFailure(err, config.debug);
138
+ return failClosedResponse();
139
+ }
140
+ };
141
+ }
142
+ /**
143
+ * Pull the request context the dashboard's `/api/v1/log-detection`
144
+ * endpoint expects out of a `NextRequest`. Works under both Node and
145
+ * Edge runtimes — no runtime-specific APIs.
146
+ */
147
+ function extractReporterContext(req, policy) {
148
+ return {
149
+ userAgent: req.headers.get("user-agent") ?? void 0,
150
+ ipAddress: getClientIp(req, policy),
151
+ path: req.nextUrl.pathname,
152
+ url: req.nextUrl.href,
153
+ method: req.method
154
+ };
155
+ }
156
+
157
+ //#endregion
158
+ export { makeNextMiddleware as n, VERSION as t };
159
+ //# sourceMappingURL=middleware-core-WZeMSRqx.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-WZeMSRqx.mjs","names":["waitUntil","vercelWaitUntil"],"sources":["../src/translate.ts","../src/middleware-core.ts"],"sourcesContent":["/**\n * D.2 — `NextRequest` → `IncomingHttpLike` translator.\n *\n * The host wrapper's *only* job on the inbound path: take Next.js's\n * native request shape and produce the transport-agnostic\n * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification\n * logic, zero adapter calls, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. Next.js\n * `NextRequest` is the same shape in both runtimes — `req.headers` is\n * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is\n * a getter (only present in some deployment surfaces; forwarding headers\n * are considered only when the caller selects a matching trust policy).\n */\n\nimport type { NextRequest } from 'next/server.js';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\nimport { getClientIp } from './utils';\n\n/**\n * Options controlling translator side effects.\n *\n * `drainJsonBody` (default `true`) controls whether the translator\n * reads the request body so the orchestrator can extract a KYA-OS\n * envelope from `_meta.proof.jws` (the canonical spec-form transport).\n *\n * Trade-off — body draining consumes the request stream. We use\n * `req.clone().text()` so the original `req.body` stream is preserved\n * for downstream Next.js handlers. Cloning has memory overhead\n * proportional to the body size; for large request bodies (>1 MB) or\n * streaming-sensitive routes, set `drainJsonBody: false` and verify\n * envelopes via the `KYA-Delegation` header transport instead (the\n * legacy form, requires `legacyEnvelopeFallback: true` on\n * `withCheckpoint`).\n */\nexport interface NextRequestToHttpLikeOpts {\n /**\n * Read the request body when `content-type` is `application/json` so\n * the orchestrator can extract a KYA-OS envelope from\n * `_meta.proof.jws`. Default `true`. Set `false` for streaming\n * middlewares that can't tolerate the clone/read overhead.\n */\n drainJsonBody?: boolean;\n /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */\n clientIpPolicy?: ClientIpTrustPolicy;\n}\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * When `opts.drainJsonBody !== false` and the request is JSON, the\n * translator clones the request and reads the body into a string so\n * the orchestrator's `buildAgentRequest` can extract a\n * `_meta.proof.jws` envelope. The original `req.body` stream is\n * preserved for downstream handlers via `req.clone()`.\n *\n * When the body can't be read (drain disabled, non-JSON, or a stream\n * error) we pass `body: null` and the orchestrator routes to\n * PlainHttp — same behavior as the pre-1.1.0 default.\n */\nexport async function nextRequestToHttpLike(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<IncomingHttpLike> {\n const url = new URL(req.url);\n const body = await tryDrainJsonBody(req, opts);\n return {\n method: req.method,\n // Path + query only — orchestrator's URL parsing expects no scheme/host.\n url: url.pathname + url.search,\n headers: headersToRecord(req.headers),\n body,\n remoteAddress: getClientIp(req, opts.clientIpPolicy),\n };\n}\n\n/**\n * Read the request body as a UTF-8 string when JSON and the caller\n * has opted in (default). Returns `null` on any failure — the\n * orchestrator handles `null` as \"no body present\" (→ PlainHttp).\n *\n * Clone-first means the original `req.body` ReadableStream stays\n * unconsumed and downstream handlers can re-read it. Without the\n * clone, calling `req.text()` in middleware would block any route\n * handler that needs the body.\n */\nasync function tryDrainJsonBody(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts\n): Promise<string | null> {\n if (opts.drainJsonBody === false) return null;\n const contentType = req.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().includes('application/json')) return null;\n try {\n return await req.clone().text();\n } catch {\n // Body unreadable (stream errored, content-length mismatch, etc.).\n // Falling through to null routes the request as PlainHttp —\n // identical behavior to the pre-1.1.0 default.\n return null;\n }\n}\n\n/**\n * Convert a `Headers` instance into a lowercase-keyed plain object.\n * HTTP header names are case-insensitive (RFC 9110 § 5.1); the\n * orchestrator does case-sensitive lookups, so we normalise to\n * lowercase here. Multi-value headers (Set-Cookie, Accept) are\n * surfaced as their `Headers.get()` view — a single string with\n * comma-joined values, matching what other host adapters produce.\n */\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value;\n });\n return out;\n}\n","/**\n * The Next.js side of the shared request pipeline\n * (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts\n * inject their engine and Cedar compiler; runtime-specific WASM initialization\n * stays in each host entry. Public withCheckpoint exports live there too.\n */\n\nimport {\n logPipelineFailure,\n makeCheckpointPipeline,\n type PipelineEngine,\n type PolicyCompile,\n} from '@kya-os/checkpoint-wasm-runtime/pipeline';\nimport type { ReporterContext } from '@kya-os/checkpoint-wasm-runtime/reporter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\nimport { type NextFetchEvent, type NextRequest, type NextResponse } from 'next/server.js';\n\nimport { waitUntil as vercelWaitUntil } from '@vercel/functions';\n\nimport { adaptToNextResponse, failClosedResponse } from './adapt';\nimport type { CheckpointConfig } from './config';\nimport { nextRequestToHttpLike } from './translate';\nimport { getClientIp } from './utils';\n\n// `CheckpointConfig` lives in `./config`; the public import paths (`.`,\n// `/node`, `/edge`) stay stable via this re-export.\nexport type { CheckpointConfig } from './config';\n\n/** The engine a host runs: one `./orchestrator` build of wasm-runtime. */\nexport type EngineEntry = PipelineEngine;\n\nexport interface NextMiddlewareHost {\n runtime: 'node' | 'edge';\n /**\n * Loads the engine. Hosts import it lazily, so a failure to load the engine\n * (a missing or unreadable `.wasm`) rejects here, inside the request\n * pipeline, and is answered 503 instead of failing the middleware module.\n */\n loadEngine: () => Promise<EngineEntry>;\n /** The Cedar compiler this runtime can load, for the project's composed policy. */\n policyCompiler: (config: CheckpointConfig) => PolicyCompile;\n /** Host-specific setup, run once with the rest; it may throw. */\n start?: (config: CheckpointConfig) => void;\n}\n\ntype CheckpointMiddleware = (\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n) => Promise<NextResponse>;\n\n/** npm package name this SDK self-reports to the detection reporter. */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * Installed SDK version, self-reported to the detection reporter so the\n * dashboard can version-gate \"composed policy enforces here\". MUST equal\n * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had\n * drifted). Re-exported as `VERSION` from the package index.\n */\nexport const VERSION = '1.12.0';\n\n/**\n * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`\n * suitable for `export default withCheckpoint({...})` in `middleware.ts`.\n *\n * Every verification decision flows through the Rust `kya-os-engine`\n * via WASM. The TS layer translates request shape, runs the shared\n * pipeline, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n *\n * It never throws. An error in the configuration or in loading the engine\n * would otherwise fail the middleware module, and a Next.js middleware that\n * fails to load can let requests through unchecked. Every such error is\n * answered 503 instead (fail closed) and logged.\n */\nexport function makeNextMiddleware(\n config: CheckpointConfig,\n host: NextMiddlewareHost\n): CheckpointMiddleware {\n try {\n return makeMiddleware(config, host);\n } catch (error) {\n return async function misconfiguredCheckpointMiddleware() {\n console.error('[checkpoint] withCheckpoint is misconfigured; responding 503:', error);\n return failClosedResponse();\n };\n }\n}\n\nfunction makeMiddleware(config: CheckpointConfig, host: NextMiddlewareHost): CheckpointMiddleware {\n const pipeline = makeCheckpointPipeline<NextRequest, CheckpointConfig>(config, {\n // Self-identify (incl. node-vs-edge) so the dashboard can version-gate\n // enforcement. Next.js EDGE composed enforcement is opt-in (needs a Cedar\n // module), so the dashboard shows it as opt-in, never \"Enforcing\".\n sdk: { name: SDK_NAME, version: VERSION, runtime: host.runtime },\n loadEngine: host.loadEngine,\n policyCompiler: host.policyCompiler,\n start: host.start,\n });\n const translateOpts = {\n drainJsonBody: config.drainJsonBody,\n clientIpPolicy: config.clientIpPolicy,\n };\n return async function checkpointMiddleware(\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n ): Promise<NextResponse> {\n // Work that outlives the response (the engine's vendor key feed round, the\n // detection report) must be registered, or Vercel and Workers cancel it\n // once the response is sent. Next.js passes the event to middleware; a\n // wrapper that drops it falls back to Vercel's request context.\n const waitUntil = event\n ? (promise: Promise<unknown>) => event.waitUntil(promise)\n : vercelWaitUntil;\n try {\n const { rendered } = await pipeline({\n request: req,\n translate: () => nextRequestToHttpLike(req, translateOpts),\n headers: req.headers,\n // The query-free path verification saw.\n path: req.nextUrl.pathname,\n clientIp: () => getClientIp(req, config.clientIpPolicy),\n reportContext: () => extractReporterContext(req, config.clientIpPolicy),\n waitUntil,\n });\n return adaptToNextResponse(rendered, req);\n } catch (err) {\n logPipelineFailure(err, config.debug);\n return failClosedResponse();\n }\n };\n}\n\n/**\n * Pull the request context the dashboard's `/api/v1/log-detection`\n * endpoint expects out of a `NextRequest`. Works under both Node and\n * Edge runtimes — no runtime-specific APIs.\n */\nfunction extractReporterContext(\n req: NextRequest,\n policy: ClientIpTrustPolicy | undefined\n): ReporterContext {\n return {\n userAgent: req.headers.get('user-agent') ?? undefined,\n ipAddress: getClientIp(req, policy),\n path: req.nextUrl.pathname,\n url: req.nextUrl.href,\n method: req.method,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,eAAsB,sBACpB,KACA,OAAkC,CAAC,GACR;CAC3B,MAAM,MAAM,IAAI,IAAI,IAAI,GAAG;CAC3B,MAAM,OAAO,MAAM,iBAAiB,KAAK,IAAI;CAC7C,OAAO;EACL,QAAQ,IAAI;EAEZ,KAAK,IAAI,WAAW,IAAI;EACxB,SAAS,gBAAgB,IAAI,OAAO;EACpC;EACA,eAAe,YAAY,KAAK,KAAK,cAAc;CACrD;AACF;;;;;;;;;;;AAYA,eAAe,iBACb,KACA,MACwB;CACxB,IAAI,KAAK,kBAAkB,OAAO,OAAO;CAEzC,IAAI,EADgB,IAAI,QAAQ,IAAI,cAAc,KAAK,GACvC,CAAC,YAAY,CAAC,CAAC,SAAS,kBAAkB,GAAG,OAAO;CACpE,IAAI;EACF,OAAO,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;CAChC,QAAQ;EAIN,OAAO;CACT;AACF;;;;;;;;;AAUA,SAAS,gBAAgB,SAA0C;CACjE,MAAM,MAA8B,CAAC;CACrC,QAAQ,SAAS,OAAO,QAAQ;EAC9B,IAAI,IAAI,YAAY,KAAK;CAC3B,CAAC;CACD,OAAO;AACT;;;;;;;;;;;ACrEA,MAAM,WAAW;;;;;;;AAQjB,MAAa,UAAU;;;;;;;;;;;;;;;AAgBvB,SAAgB,mBACd,QACA,MACsB;CACtB,IAAI;EACF,OAAO,eAAe,QAAQ,IAAI;CACpC,SAAS,OAAO;EACd,OAAO,eAAe,oCAAoC;GACxD,QAAQ,MAAM,iEAAiE,KAAK;GACpF,OAAO,mBAAmB;EAC5B;CACF;AACF;AAEA,SAAS,eAAe,QAA0B,MAAgD;CAChG,MAAM,WAAW,uBAAsD,QAAQ;EAI7E,KAAK;GAAE,MAAM;GAAU,SAAS;GAAS,SAAS,KAAK;EAAQ;EAC/D,YAAY,KAAK;EACjB,gBAAgB,KAAK;EACrB,OAAO,KAAK;CACd,CAAC;CACD,MAAM,gBAAgB;EACpB,eAAe,OAAO;EACtB,gBAAgB,OAAO;CACzB;CACA,OAAO,eAAe,qBACpB,KACA,OACuB;EAKvB,MAAMA,cAAY,SACb,YAA8B,MAAM,UAAU,OAAO,IACtDC;EACJ,IAAI;GACF,MAAM,EAAE,aAAa,MAAM,SAAS;IAClC,SAAS;IACT,iBAAiB,sBAAsB,KAAK,aAAa;IACzD,SAAS,IAAI;IAEb,MAAM,IAAI,QAAQ;IAClB,gBAAgB,YAAY,KAAK,OAAO,cAAc;IACtD,qBAAqB,uBAAuB,KAAK,OAAO,cAAc;IACtE;GACF,CAAC;GACD,OAAO,oBAAoB,UAAU,GAAG;EAC1C,SAAS,KAAK;GACZ,mBAAmB,KAAK,OAAO,KAAK;GACpC,OAAO,mBAAmB;EAC5B;CACF;AACF;;;;;;AAOA,SAAS,uBACP,KACA,QACiB;CACjB,OAAO;EACL,WAAW,IAAI,QAAQ,IAAI,YAAY,KAAK;EAC5C,WAAW,YAAY,KAAK,MAAM;EAClC,MAAM,IAAI,QAAQ;EAClB,KAAK,IAAI,QAAQ;EACjB,QAAQ,IAAI;CACd;AACF"}
@@ -1,8 +1,16 @@
1
- import { t as CheckpointConfig } from "./config-Doe0Tn53.mjs";
1
+ import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-D7h2w_it.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":";;;;;wBAyBgB,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-DkXvl4nH.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":";;;;;wBAyBgB,eAAe,QAAQ,wBAAoB,2BAAA,aAAA,QAAA,2BAAA,iCAAA,8BAAA;;;;;qBAwD9C,oCAAoC;EACnC,YAAA"}
@@ -1,46 +1,85 @@
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-B1GuspOY.js');
3
+ const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
5
4
  let _kya_os_checkpoint_wasm_runtime_orchestrator_edge = require("@kya-os/checkpoint-wasm-runtime/orchestrator/edge");
6
5
  let _kya_os_checkpoint_wasm_runtime_policy_edge = require("@kya-os/checkpoint-wasm-runtime/policy-edge");
7
6
 
8
7
  //#region src/middleware-edge.ts
9
- /** Edge host: eagerly initialize its engine and opt into Cedar only when wired. */
8
+ /**
9
+ * Edge host: the engine runs on the module the host passes. The Cedar build
10
+ * (`./cedar-wasm`) is the engine plus Cedar, so passed as `engineWasmModule`
11
+ * (or alone as `cedarWasmModule`) one instance serves detection and policy.
12
+ */
10
13
  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, {
14
+ return require_middleware_core.makeNextMiddleware(config, {
13
15
  runtime: "edge",
14
- buildComposedContext
16
+ loadEngine: async () => {
17
+ await (0, _kya_os_checkpoint_wasm_runtime_orchestrator_edge.initEngineEdge)(engineModule(config));
18
+ return {
19
+ verifyRequest: _kya_os_checkpoint_wasm_runtime_orchestrator_edge.verifyRequestEdge,
20
+ renderDecisionAsResponse: _kya_os_checkpoint_wasm_runtime_orchestrator_edge.renderDecisionAsResponse
21
+ };
22
+ },
23
+ policyCompiler: edgePolicyCompiler,
24
+ start: checkModules
15
25
  });
16
26
  }
27
+ /** The module the engine runs on: `engineWasmModule`, else the Cedar build. */
28
+ function engineModule(config) {
29
+ return config.engineWasmModule ?? config.cedarWasmModule;
30
+ }
31
+ /** The Cedar build, whichever field it was passed in. */
32
+ function cedarModule(config) {
33
+ if (config.cedarWasmModule) return config.cedarWasmModule;
34
+ return (0, _kya_os_checkpoint_wasm_runtime_policy_edge.isCedarModule)(config.engineWasmModule) ? config.engineWasmModule : void 0;
35
+ }
36
+ function checkModules(config) {
37
+ 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");
38
+ 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.");
39
+ }
17
40
  /**
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).
41
+ * A project has a Cedar policy, but this Edge middleware has no Cedar module to
42
+ * evaluate it with.
26
43
  */
27
- function buildComposedContext(config) {
28
- 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",
35
- apiKey: config.apiKey,
36
- cacheTtlSeconds: config.policyCacheTtlSeconds
37
- }),
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
40
- });
44
+ var CedarWasmModuleMissingError = class extends Error {
45
+ constructor(projectId) {
46
+ 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.`);
47
+ this.name = "CedarWasmModuleMissingError";
48
+ }
49
+ };
50
+ /**
51
+ * The EDGE-runtime Cedar compiler for the project's composed policy. The Cedar
52
+ * build is opt-in on the Edge runtime (it is larger than the engine-only
53
+ * build), so Edge bundles that never evaluate Cedar don't carry it. When the
54
+ * host passes it, as `engineWasmModule` or `cedarWasmModule`, it is registered
55
+ * via `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's
56
+ * own instance when the engine runs on it, and the async `evaluatePolicy`
57
+ * compiler is used.
58
+ *
59
+ * Without it a project's policy is still fetched and is never skipped: the
60
+ * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar
61
+ * policy is unaffected, a policy in shadow mode keeps the structured decision,
62
+ * and an enforcing policy answers 503, as any composed-policy fault does.
63
+ */
64
+ function edgePolicyCompiler(config) {
65
+ const projectId = config.projectId ?? "";
66
+ const cedarWasmModule = cedarModule(config);
67
+ if (cedarWasmModule) (0, _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge)(cedarWasmModule);
68
+ let reportedMissingModule = false;
69
+ return async (language, source) => {
70
+ if (cedarWasmModule) return (0, _kya_os_checkpoint_wasm_runtime_policy_edge.evaluatePolicy)(language, source);
71
+ const error = new CedarWasmModuleMissingError(projectId);
72
+ if (!reportedMissingModule) {
73
+ reportedMissingModule = true;
74
+ console.error(`[checkpoint] ${error.message}`);
75
+ }
76
+ throw error;
77
+ };
41
78
  }
42
79
 
43
80
  //#endregion
81
+ exports.CedarWasmModuleMissingError = CedarWasmModuleMissingError;
82
+ exports.getCheckpointPostureOutcome = require_posture_outcome.getCheckpointPostureOutcome;
44
83
  exports.initEngineEdge = _kya_os_checkpoint_wasm_runtime_orchestrator_edge.initEngineEdge;
45
84
  exports.initPolicyEvaluatorEdge = _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge;
46
85
  exports.withCheckpoint = withCheckpoint;