@kya-os/checkpoint-nextjs 1.11.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 (78) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +16 -8
  3. package/dist/{adapt-BdQ9R7Iw.mjs → adapt-BvqYgrAk.mjs} +2 -2
  4. package/dist/{adapt-BdQ9R7Iw.mjs.map → adapt-BvqYgrAk.mjs.map} +1 -1
  5. package/dist/{adapt-CCSKGjVH.js → adapt-DUEIfZnx.js} +1 -1
  6. package/dist/{api-middleware-BWjokNis.d.mts → api-middleware-BtsYJU5u.d.mts} +2 -2
  7. package/dist/{api-middleware-BWjokNis.d.mts.map → api-middleware-BtsYJU5u.d.mts.map} +1 -1
  8. package/dist/{api-middleware-C-ngFX_8.mjs → api-middleware-DvmkJ_Li.mjs} +4 -4
  9. package/dist/{api-middleware-C-ngFX_8.mjs.map → api-middleware-DvmkJ_Li.mjs.map} +1 -1
  10. package/dist/{api-middleware-Bf3xmM9W.js → api-middleware-beNlXd5P.js} +3 -3
  11. package/dist/api-middleware.d.mts +1 -1
  12. package/dist/api-middleware.js +1 -1
  13. package/dist/api-middleware.mjs +1 -1
  14. package/dist/cedar-wasm.d.mts +1 -1
  15. package/dist/cedar-wasm.d.ts +1 -1
  16. package/dist/cedar-wasm.js +1 -1
  17. package/dist/cedar-wasm.mjs +1 -1
  18. package/dist/cedar-wasm.mjs.map +1 -1
  19. package/dist/config-D7h2w_it.d.mts +89 -0
  20. package/dist/config-D7h2w_it.d.mts.map +1 -0
  21. package/dist/config-DkXvl4nH.d.ts +89 -0
  22. package/dist/config-DkXvl4nH.d.ts.map +1 -0
  23. package/dist/engine-wasm.d.mts +1 -1
  24. package/dist/engine-wasm.d.ts +1 -1
  25. package/dist/engine-wasm.js +1 -1
  26. package/dist/engine-wasm.mjs +1 -1
  27. package/dist/engine-wasm.mjs.map +1 -1
  28. package/dist/index-edge.d.mts +4 -4
  29. package/dist/index-edge.d.ts +3 -3
  30. package/dist/index-edge.js +2 -2
  31. package/dist/index-edge.mjs +2 -2
  32. package/dist/index.d.mts +4 -4
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +2 -2
  35. package/dist/index.mjs +2 -2
  36. package/dist/middleware-bundler.d.mts +1 -1
  37. package/dist/middleware-bundler.d.ts +1 -1
  38. package/dist/middleware-bundler.js +3 -3
  39. package/dist/middleware-bundler.mjs +3 -3
  40. package/dist/middleware-bundler.mjs.map +1 -1
  41. package/dist/middleware-core-B1GuspOY.js +169 -0
  42. package/dist/{middleware-core-Bol44X9C.d.ts → middleware-core-BmW2kH8J.d.ts} +4 -7
  43. package/dist/middleware-core-BmW2kH8J.d.ts.map +1 -0
  44. package/dist/{middleware-core-DycsbHUd.d.mts → middleware-core-CnPUoD2v.d.mts} +4 -7
  45. package/dist/middleware-core-CnPUoD2v.d.mts.map +1 -0
  46. package/dist/middleware-core-WZeMSRqx.mjs +159 -0
  47. package/dist/middleware-core-WZeMSRqx.mjs.map +1 -0
  48. package/dist/middleware-edge.d.mts +1 -1
  49. package/dist/middleware-edge.d.mts.map +1 -1
  50. package/dist/middleware-edge.d.ts +1 -1
  51. package/dist/middleware-edge.d.ts.map +1 -1
  52. package/dist/middleware-edge.js +21 -35
  53. package/dist/middleware-edge.mjs +21 -35
  54. package/dist/middleware-edge.mjs.map +1 -1
  55. package/dist/middleware-node-context-BvqrL2Ra.mjs +16 -0
  56. package/dist/middleware-node-context-BvqrL2Ra.mjs.map +1 -0
  57. package/dist/middleware-node-context-TRMTgp3y.js +20 -0
  58. package/dist/middleware-node.d.mts +2 -2
  59. package/dist/middleware-node.d.ts +2 -2
  60. package/dist/middleware-node.js +3 -3
  61. package/dist/middleware-node.mjs +3 -3
  62. package/dist/middleware-node.mjs.map +1 -1
  63. package/dist/{public-api-CYsHrTQI.d.ts → public-api-Cw7Zj290.d.ts} +2 -2
  64. package/dist/public-api-DgCw1uo6.d.mts +5 -0
  65. package/package.json +3 -3
  66. package/dist/config-CPP1RV0f.d.mts +0 -291
  67. package/dist/config-CPP1RV0f.d.mts.map +0 -1
  68. package/dist/config-DVgOFxJs.d.ts +0 -291
  69. package/dist/config-DVgOFxJs.d.ts.map +0 -1
  70. package/dist/middleware-core-B0jf5_Hm.mjs +0 -264
  71. package/dist/middleware-core-B0jf5_Hm.mjs.map +0 -1
  72. package/dist/middleware-core-Bol44X9C.d.ts.map +0 -1
  73. package/dist/middleware-core-CMc-2QkU.js +0 -274
  74. package/dist/middleware-core-DycsbHUd.d.mts.map +0 -1
  75. package/dist/middleware-node-context-591KsiYg.js +0 -39
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs +0 -35
  77. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +0 -1
  78. package/dist/public-api-DkG7pRE0.d.mts +0 -5
@@ -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,4 +1,4 @@
1
- import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-CPP1RV0f.mjs";
1
+ import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-D7h2w_it.mjs";
2
2
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.mjs";
3
3
  import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
4
4
  import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
@@ -1 +1 @@
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
+ {"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,4 +1,4 @@
1
- import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-DVgOFxJs.js";
1
+ import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-DkXvl4nH.js";
2
2
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.js";
3
3
  import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
4
4
  import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
@@ -1 +1 @@
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
+ {"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,8 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-CMc-2QkU.js');
2
+ const require_middleware_core = require('./middleware-core-B1GuspOY.js');
3
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");
6
4
  let _kya_os_checkpoint_wasm_runtime_orchestrator_edge = require("@kya-os/checkpoint-wasm-runtime/orchestrator/edge");
7
5
  let _kya_os_checkpoint_wasm_runtime_policy_edge = require("@kya-os/checkpoint-wasm-runtime/policy-edge");
8
6
 
@@ -22,7 +20,7 @@ function withCheckpoint(config) {
22
20
  renderDecisionAsResponse: _kya_os_checkpoint_wasm_runtime_orchestrator_edge.renderDecisionAsResponse
23
21
  };
24
22
  },
25
- buildComposedContext,
23
+ policyCompiler: edgePolicyCompiler,
26
24
  start: checkModules
27
25
  });
28
26
  }
@@ -50,45 +48,33 @@ var CedarWasmModuleMissingError = class extends Error {
50
48
  }
51
49
  };
52
50
  /**
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.
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.
60
58
  *
61
- * Without it a project's policy is still fetched and is never skipped: its
59
+ * Without it a project's policy is still fetched and is never skipped: the
62
60
  * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar
63
61
  * policy is unaffected, a policy in shadow mode keeps the structured decision,
64
62
  * and an enforcing policy answers 503, as any composed-policy fault does.
65
63
  */
66
- function buildComposedContext(config) {
67
- if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
68
- if (!config.projectId) return null;
69
- const projectId = config.projectId;
64
+ function edgePolicyCompiler(config) {
65
+ const projectId = config.projectId ?? "";
70
66
  const cedarWasmModule = cedarModule(config);
71
67
  if (cedarWasmModule) (0, _kya_os_checkpoint_wasm_runtime_policy_edge.initPolicyEvaluatorEdge)(cedarWasmModule);
72
68
  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,
77
- apiKey: config.apiKey,
78
- cacheTtlSeconds: config.policyCacheTtlSeconds,
79
- throwOnUnavailable: true
80
- }),
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
91
- });
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
+ };
92
78
  }
93
79
 
94
80
  //#endregion
@@ -1,7 +1,5 @@
1
- import { n as makeNextMiddleware } from "./middleware-core-B0jf5_Hm.mjs";
1
+ import { n as makeNextMiddleware } from "./middleware-core-WZeMSRqx.mjs";
2
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";
5
3
  import { initEngineEdge, renderDecisionAsResponse, verifyRequestEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
6
4
  import { evaluatePolicy, initPolicyEvaluatorEdge, isCedarModule } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
7
5
 
@@ -21,7 +19,7 @@ function withCheckpoint(config) {
21
19
  renderDecisionAsResponse
22
20
  };
23
21
  },
24
- buildComposedContext,
22
+ policyCompiler: edgePolicyCompiler,
25
23
  start: checkModules
26
24
  });
27
25
  }
@@ -49,45 +47,33 @@ var CedarWasmModuleMissingError = class extends Error {
49
47
  }
50
48
  };
51
49
  /**
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.
50
+ * The EDGE-runtime Cedar compiler for the project's composed policy. The Cedar
51
+ * build is opt-in on the Edge runtime (it is larger than the engine-only
52
+ * build), so Edge bundles that never evaluate Cedar don't carry it. When the
53
+ * host passes it, as `engineWasmModule` or `cedarWasmModule`, it is registered
54
+ * via `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's
55
+ * own instance when the engine runs on it, and the async `evaluatePolicy`
56
+ * compiler is used.
59
57
  *
60
- * Without it a project's policy is still fetched and is never skipped: its
58
+ * Without it a project's policy is still fetched and is never skipped: the
61
59
  * compiler throws `CedarWasmModuleMissingError`, so a project with no Cedar
62
60
  * policy is unaffected, a policy in shadow mode keeps the structured decision,
63
61
  * and an enforcing policy answers 503, as any composed-policy fault does.
64
62
  */
65
- function buildComposedContext(config) {
66
- if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
67
- if (!config.projectId) return null;
68
- const projectId = config.projectId;
63
+ function edgePolicyCompiler(config) {
64
+ const projectId = config.projectId ?? "";
69
65
  const cedarWasmModule = cedarModule(config);
70
66
  if (cedarWasmModule) initPolicyEvaluatorEdge(cedarWasmModule);
71
67
  let reportedMissingModule = false;
72
- return makeComposedPolicyContext({
73
- projectId,
74
- fetcher: new PolicyFetcher({
75
- apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
76
- apiKey: config.apiKey,
77
- cacheTtlSeconds: config.policyCacheTtlSeconds,
78
- throwOnUnavailable: true
79
- }),
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
- },
89
- logger: config.debug ? consoleComposedPolicyLogger : void 0
90
- });
68
+ return async (language, source) => {
69
+ if (cedarWasmModule) return evaluatePolicy(language, source);
70
+ const error = new CedarWasmModuleMissingError(projectId);
71
+ if (!reportedMissingModule) {
72
+ reportedMissingModule = true;
73
+ console.error(`[checkpoint] ${error.message}`);
74
+ }
75
+ throw error;
76
+ };
91
77
  }
92
78
 
93
79
  //#endregion
@@ -1 +1 @@
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"}
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 type { PolicyCompile } from '@kya-os/checkpoint-wasm-runtime/pipeline';\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 policyCompiler: edgePolicyCompiler,\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 * The EDGE-runtime Cedar compiler for the project's composed policy. The Cedar\n * build is opt-in on the Edge runtime (it is larger than the engine-only\n * build), so Edge bundles that never evaluate Cedar don't carry it. When the\n * host passes it, as `engineWasmModule` or `cedarWasmModule`, it is registered\n * via `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's\n * own instance when the engine runs on it, and the async `evaluatePolicy`\n * compiler is used.\n *\n * Without it a project's policy is still fetched and is never skipped: the\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 edgePolicyCompiler(config: CheckpointConfig): PolicyCompile {\n const projectId = config.projectId ?? '';\n const cedarWasmModule = cedarModule(config);\n if (cedarWasmModule) initPolicyEvaluatorEdge(cedarWasmModule);\n let reportedMissingModule = false;\n return 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}\n\n// Allow hosts to initialize their WASM modules explicitly at startup.\nexport { initEngineEdge, initPolicyEvaluatorEdge };\n"],"mappings":";;;;;;;;;;;AAyBA,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,gBAAgB;EAChB,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,mBAAmB,QAAyC;CACnE,MAAM,YAAY,OAAO,aAAa;CACtC,MAAM,kBAAkB,YAAY,MAAM;CAC1C,IAAI,iBAAiB,wBAAwB,eAAe;CAC5D,IAAI,wBAAwB;CAC5B,OAAO,OAAO,UAAU,WAAW;EACjC,IAAI,iBAAiB,OAAO,eAAe,UAAU,MAAM;EAC3D,MAAM,QAAQ,IAAI,4BAA4B,SAAS;EACvD,IAAI,CAAC,uBAAuB;GAC1B,wBAAwB;GACxB,QAAQ,MAAM,gBAAgB,MAAM,SAAS;EAC/C;EACA,MAAM;CACR;AACF"}
@@ -0,0 +1,16 @@
1
+ //#region src/middleware-node-context.ts
2
+ /**
3
+ * The Node-runtime Cedar compiler for the project's composed policy: the SYNC
4
+ * `createPolicyEvaluator`, whose cedar-nodejs glue loads lazily on first use
5
+ * (no init handshake, never bundled into the edge build).
6
+ */
7
+ function nodePolicyCompiler() {
8
+ return async (_language, source) => {
9
+ const { createPolicyEvaluator } = await import("@kya-os/checkpoint-wasm-runtime/policy");
10
+ return createPolicyEvaluator(source);
11
+ };
12
+ }
13
+
14
+ //#endregion
15
+ export { nodePolicyCompiler as t };
16
+ //# sourceMappingURL=middleware-node-context-BvqrL2Ra.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-node-context-BvqrL2Ra.mjs","names":[],"sources":["../src/middleware-node-context.ts"],"sourcesContent":["import type { PolicyCompile } from '@kya-os/checkpoint-wasm-runtime/pipeline';\n\n/**\n * The Node-runtime Cedar compiler for the project's composed policy: the SYNC\n * `createPolicyEvaluator`, whose cedar-nodejs glue loads lazily on first use\n * (no init handshake, never bundled into the edge build).\n */\nexport function nodePolicyCompiler(): PolicyCompile {\n // Load the Node policy compiler only on first use. This module is imported\n // exclusively by the Node and bundler hosts, never by the Edge pipeline.\n return async (_language, source) => {\n const { createPolicyEvaluator } = await import('@kya-os/checkpoint-wasm-runtime/policy');\n return createPolicyEvaluator(source);\n };\n}\n"],"mappings":";;;;;;AAOA,SAAgB,qBAAoC;CAGlD,OAAO,OAAO,WAAW,WAAW;EAClC,MAAM,EAAE,0BAA0B,MAAM,OAAO;EAC/C,OAAO,sBAAsB,MAAM;CACrC;AACF"}
@@ -0,0 +1,20 @@
1
+ //#region src/middleware-node-context.ts
2
+ /**
3
+ * The Node-runtime Cedar compiler for the project's composed policy: the SYNC
4
+ * `createPolicyEvaluator`, whose cedar-nodejs glue loads lazily on first use
5
+ * (no init handshake, never bundled into the edge build).
6
+ */
7
+ function nodePolicyCompiler() {
8
+ return async (_language, source) => {
9
+ const { createPolicyEvaluator } = await import("@kya-os/checkpoint-wasm-runtime/policy");
10
+ return createPolicyEvaluator(source);
11
+ };
12
+ }
13
+
14
+ //#endregion
15
+ Object.defineProperty(exports, 'nodePolicyCompiler', {
16
+ enumerable: true,
17
+ get: function () {
18
+ return nodePolicyCompiler;
19
+ }
20
+ });
@@ -1,5 +1,5 @@
1
- import { t as CheckpointConfig } from "./config-CPP1RV0f.mjs";
2
- import { t as VERSION } from "./middleware-core-DycsbHUd.mjs";
1
+ import { t as CheckpointConfig } from "./config-D7h2w_it.mjs";
2
+ import { t as VERSION } from "./middleware-core-CnPUoD2v.mjs";
3
3
  //#region src/middleware-node.d.ts
4
4
  /**
5
5
  * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
@@ -1,5 +1,5 @@
1
- import { t as CheckpointConfig } from "./config-DVgOFxJs.js";
2
- import { t as VERSION } from "./middleware-core-Bol44X9C.js";
1
+ import { t as CheckpointConfig } from "./config-DkXvl4nH.js";
2
+ import { t as VERSION } from "./middleware-core-BmW2kH8J.js";
3
3
  //#region src/middleware-node.d.ts
4
4
  /**
5
5
  * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-CMc-2QkU.js');
3
- const require_middleware_node_context = require('./middleware-node-context-591KsiYg.js');
2
+ const require_middleware_core = require('./middleware-core-B1GuspOY.js');
3
+ const require_middleware_node_context = require('./middleware-node-context-TRMTgp3y.js');
4
4
 
5
5
  //#region src/middleware-node.ts
6
6
  /**
@@ -16,7 +16,7 @@ function withCheckpoint(config) {
16
16
  await orchestrator.initEngine();
17
17
  return orchestrator;
18
18
  },
19
- buildComposedContext: require_middleware_node_context.buildComposedContext
19
+ policyCompiler: require_middleware_node_context.nodePolicyCompiler
20
20
  });
21
21
  }
22
22
 
@@ -1,5 +1,5 @@
1
- import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-B0jf5_Hm.mjs";
2
- import { t as buildComposedContext } from "./middleware-node-context-D_ZyUEcA.mjs";
1
+ import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-WZeMSRqx.mjs";
2
+ import { t as nodePolicyCompiler } from "./middleware-node-context-BvqrL2Ra.mjs";
3
3
 
4
4
  //#region src/middleware-node.ts
5
5
  /**
@@ -15,7 +15,7 @@ function withCheckpoint(config) {
15
15
  await orchestrator.initEngine();
16
16
  return orchestrator;
17
17
  },
18
- buildComposedContext
18
+ policyCompiler: nodePolicyCompiler
19
19
  });
20
20
  }
21
21
 
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-node.mjs","names":[],"sources":["../src/middleware-node.ts"],"sourcesContent":["import { makeNextMiddleware } from './middleware-core';\nimport { buildComposedContext } from './middleware-node-context';\nimport type { CheckpointConfig } from './config';\nexport type { CheckpointConfig } from './config';\n\n/**\n * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)\n * or not. The engine's Node build loads its `.wasm` through `new URL(...,\n * import.meta.url)`, which bundlers follow and copy.\n */\nexport function withCheckpoint(config: CheckpointConfig) {\n return makeNextMiddleware(config, {\n runtime: 'node',\n // Pinned to the Node build whatever conditions a bundler resolves with.\n // Importing it does not read the `.wasm`; `initEngine` does, so a missing\n // or unreadable engine fails here, where it is logged and answered 503,\n // and the next request retries, instead of failing this module.\n loadEngine: async () => {\n const orchestrator = await import('@kya-os/checkpoint-wasm-runtime/orchestrator/node');\n await orchestrator.initEngine();\n return orchestrator;\n },\n buildComposedContext,\n });\n}\n\nexport { VERSION } from './middleware-core';\n"],"mappings":";;;;;;;;;AAUA,SAAgB,eAAe,QAA0B;CACvD,OAAO,mBAAmB,QAAQ;EAChC,SAAS;EAKT,YAAY,YAAY;GACtB,MAAM,eAAe,MAAM,OAAO;GAClC,MAAM,aAAa,WAAW;GAC9B,OAAO;EACT;EACA;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"middleware-node.mjs","names":[],"sources":["../src/middleware-node.ts"],"sourcesContent":["import { makeNextMiddleware } from './middleware-core';\nimport { nodePolicyCompiler } from './middleware-node-context';\nimport type { CheckpointConfig } from './config';\nexport type { CheckpointConfig } from './config';\n\n/**\n * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)\n * or not. The engine's Node build loads its `.wasm` through `new URL(...,\n * import.meta.url)`, which bundlers follow and copy.\n */\nexport function withCheckpoint(config: CheckpointConfig) {\n return makeNextMiddleware(config, {\n runtime: 'node',\n // Pinned to the Node build whatever conditions a bundler resolves with.\n // Importing it does not read the `.wasm`; `initEngine` does, so a missing\n // or unreadable engine fails here, where it is logged and answered 503,\n // and the next request retries, instead of failing this module.\n loadEngine: async () => {\n const orchestrator = await import('@kya-os/checkpoint-wasm-runtime/orchestrator/node');\n await orchestrator.initEngine();\n return orchestrator;\n },\n policyCompiler: nodePolicyCompiler,\n });\n}\n\nexport { VERSION } from './middleware-core';\n"],"mappings":";;;;;;;;;AAUA,SAAgB,eAAe,QAA0B;CACvD,OAAO,mBAAmB,QAAQ;EAChC,SAAS;EAKT,YAAY,YAAY;GACtB,MAAM,eAAe,MAAM,OAAO;GAClC,MAAM,aAAa,WAAW;GAC9B,OAAO;EACT;EACA,gBAAgB;CAClB,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  import "./api-client-JHOrRUA_.js";
2
2
  import "./api-middleware-DyLDqOYF.js";
3
- import "./config-DVgOFxJs.js";
3
+ import "./config-DkXvl4nH.js";
4
4
  import "./posture-outcome-Ccujx_9V.js";
5
- import "./middleware-core-Bol44X9C.js";
5
+ import "./middleware-core-BmW2kH8J.js";
@@ -0,0 +1,5 @@
1
+ import "./api-client-JHOrRUA_.mjs";
2
+ import "./api-middleware-BtsYJU5u.mjs";
3
+ import "./config-D7h2w_it.mjs";
4
+ import "./posture-outcome-Ccujx_9V.mjs";
5
+ import "./middleware-core-CnPUoD2v.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/checkpoint-nextjs",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "Checkpoint Next.js middleware: AI agent detection and verification through kya-os-engine",
5
5
  "keywords": [
6
6
  "nextjs",
@@ -103,8 +103,8 @@
103
103
  "sideEffects": false,
104
104
  "dependencies": {
105
105
  "@vercel/functions": "^3.9.3",
106
- "@kya-os/checkpoint-wasm-runtime": "^1.12.0",
107
- "@kya-os/checkpoint-shared": "^1.8.0"
106
+ "@kya-os/checkpoint-shared": "^1.9.0",
107
+ "@kya-os/checkpoint-wasm-runtime": "^1.14.0"
108
108
  },
109
109
  "scripts": {
110
110
  "build": "tsdown",