@kya-os/checkpoint-nextjs 1.11.0 → 1.13.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.
- package/CHANGELOG.md +38 -0
- package/README.md +16 -8
- package/dist/{adapt-BdQ9R7Iw.mjs → adapt-BGEyLf44.mjs} +13 -3
- package/dist/adapt-BGEyLf44.mjs.map +1 -0
- package/dist/{adapt-CCSKGjVH.js → adapt-D2-OBY9M.js} +17 -1
- package/dist/{api-middleware-BWjokNis.d.mts → api-middleware-BtsYJU5u.d.mts} +2 -2
- package/dist/{api-middleware-BWjokNis.d.mts.map → api-middleware-BtsYJU5u.d.mts.map} +1 -1
- package/dist/{api-middleware-C-ngFX_8.mjs → api-middleware-DcUgTDv5.mjs} +4 -4
- package/dist/{api-middleware-C-ngFX_8.mjs.map → api-middleware-DcUgTDv5.mjs.map} +1 -1
- package/dist/{api-middleware-Bf3xmM9W.js → api-middleware-LhLqOapx.js} +3 -3
- package/dist/api-middleware.d.mts +1 -1
- package/dist/api-middleware.js +1 -1
- package/dist/api-middleware.mjs +1 -1
- package/dist/cedar-wasm.d.mts +1 -1
- package/dist/cedar-wasm.d.ts +1 -1
- package/dist/cedar-wasm.js +1 -1
- package/dist/cedar-wasm.mjs +1 -1
- package/dist/cedar-wasm.mjs.map +1 -1
- package/dist/config-CXS_-rRv.d.ts +95 -0
- package/dist/config-CXS_-rRv.d.ts.map +1 -0
- package/dist/config-DQ-VuHlJ.d.mts +95 -0
- package/dist/config-DQ-VuHlJ.d.mts.map +1 -0
- package/dist/engine-wasm.d.mts +1 -1
- package/dist/engine-wasm.d.ts +1 -1
- package/dist/engine-wasm.js +1 -1
- package/dist/engine-wasm.mjs +1 -1
- package/dist/engine-wasm.mjs.map +1 -1
- package/dist/index-edge.d.mts +4 -4
- package/dist/index-edge.d.ts +3 -3
- package/dist/index-edge.js +2 -2
- package/dist/index-edge.mjs +2 -2
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/middleware-bundler.d.mts +1 -1
- package/dist/middleware-bundler.d.ts +1 -1
- package/dist/middleware-bundler.js +3 -3
- package/dist/middleware-bundler.mjs +3 -3
- package/dist/middleware-bundler.mjs.map +1 -1
- package/dist/middleware-core-0s8y7UNN.js +203 -0
- package/dist/{middleware-core-Bol44X9C.d.ts → middleware-core-Cxb9Jh0a.d.mts} +4 -7
- package/dist/middleware-core-Cxb9Jh0a.d.mts.map +1 -0
- package/dist/middleware-core-DN_FLlaV.mjs +193 -0
- package/dist/middleware-core-DN_FLlaV.mjs.map +1 -0
- package/dist/{middleware-core-DycsbHUd.d.mts → middleware-core-DaNMjsib.d.ts} +4 -7
- package/dist/middleware-core-DaNMjsib.d.ts.map +1 -0
- package/dist/middleware-edge.d.mts +1 -1
- package/dist/middleware-edge.d.mts.map +1 -1
- package/dist/middleware-edge.d.ts +1 -1
- package/dist/middleware-edge.d.ts.map +1 -1
- package/dist/middleware-edge.js +21 -35
- package/dist/middleware-edge.mjs +21 -35
- package/dist/middleware-edge.mjs.map +1 -1
- package/dist/middleware-node-context-BvqrL2Ra.mjs +16 -0
- package/dist/middleware-node-context-BvqrL2Ra.mjs.map +1 -0
- package/dist/middleware-node-context-TRMTgp3y.js +20 -0
- package/dist/middleware-node.d.mts +2 -2
- package/dist/middleware-node.d.ts +2 -2
- package/dist/middleware-node.js +3 -3
- package/dist/middleware-node.mjs +3 -3
- package/dist/middleware-node.mjs.map +1 -1
- package/dist/public-api-BZ5Ahk6X.d.mts +5 -0
- package/dist/{public-api-CYsHrTQI.d.ts → public-api-DnTh8YEz.d.ts} +2 -2
- package/package.json +3 -3
- package/dist/adapt-BdQ9R7Iw.mjs.map +0 -1
- package/dist/config-CPP1RV0f.d.mts +0 -291
- package/dist/config-CPP1RV0f.d.mts.map +0 -1
- package/dist/config-DVgOFxJs.d.ts +0 -291
- package/dist/config-DVgOFxJs.d.ts.map +0 -1
- package/dist/middleware-core-B0jf5_Hm.mjs +0 -264
- package/dist/middleware-core-B0jf5_Hm.mjs.map +0 -1
- package/dist/middleware-core-Bol44X9C.d.ts.map +0 -1
- package/dist/middleware-core-CMc-2QkU.js +0 -274
- package/dist/middleware-core-DycsbHUd.d.mts.map +0 -1
- package/dist/middleware-node-context-591KsiYg.js +0 -39
- package/dist/middleware-node-context-D_ZyUEcA.mjs +0 -35
- package/dist/middleware-node-context-D_ZyUEcA.mjs.map +0 -1
- package/dist/public-api-DkG7pRE0.d.mts +0 -5
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { n as failClosedResponse, r as signedBodyTooLargeResponse, t as adaptToNextResponse } from "./adapt-BGEyLf44.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
|
+
import { KYA_SIGNED_BODY_MAX_BYTES, readBodyBounded, requestPresentsKyaSignature } from "@kya-os/checkpoint-shared/kya-http";
|
|
6
|
+
|
|
7
|
+
//#region src/translate.ts
|
|
8
|
+
/**
|
|
9
|
+
* Translate a Next.js `NextRequest` into the orchestrator's
|
|
10
|
+
* `IncomingHttpLike` shape.
|
|
11
|
+
*
|
|
12
|
+
* When `opts.drainJsonBody !== false` the translator reads a clone of
|
|
13
|
+
* the request body: JSON as a string so `buildAgentRequest` can extract
|
|
14
|
+
* a `_meta.proof.jws` envelope, and the body of a kya-http/2 signed
|
|
15
|
+
* request as its exact bytes (`rawBody`) for the `Content-Digest` check.
|
|
16
|
+
* The original `req.body` stream is preserved for downstream handlers.
|
|
17
|
+
*
|
|
18
|
+
* When the body can't be read (drain disabled, non-JSON unsigned, or a
|
|
19
|
+
* stream error) we pass `body: null` and the orchestrator routes to
|
|
20
|
+
* PlainHttp — same behavior as the pre-1.1.0 default. A kya-http/2
|
|
21
|
+
* request whose `Content-Length` or `Transfer-Encoding` declares a body
|
|
22
|
+
* the engine never received is refused by the orchestrator.
|
|
23
|
+
*/
|
|
24
|
+
async function translateNextRequest(req, opts = {}) {
|
|
25
|
+
const url = new URL(req.url);
|
|
26
|
+
const { body, rawBody, signedBodyTooLarge } = await tryDrainBody(req, opts);
|
|
27
|
+
return {
|
|
28
|
+
httpLike: {
|
|
29
|
+
method: req.method,
|
|
30
|
+
url: url.pathname + url.search,
|
|
31
|
+
headers: headersToRecord(req.headers),
|
|
32
|
+
body,
|
|
33
|
+
...rawBody ? { rawBody } : {},
|
|
34
|
+
remoteAddress: getClientIp(req, opts.clientIpPolicy)
|
|
35
|
+
},
|
|
36
|
+
signedBodyTooLarge
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Read the request body when the caller has opted in (default). Returns
|
|
41
|
+
* `body: null` on any failure — the orchestrator handles `null` as "no
|
|
42
|
+
* body present" (→ PlainHttp).
|
|
43
|
+
*
|
|
44
|
+
* Clone-first means the original `req.body` ReadableStream stays
|
|
45
|
+
* unconsumed and downstream handlers can re-read it. Without the
|
|
46
|
+
* clone, calling `req.text()` in middleware would block any route
|
|
47
|
+
* handler that needs the body.
|
|
48
|
+
*/
|
|
49
|
+
async function tryDrainBody(req, opts) {
|
|
50
|
+
if (opts.drainJsonBody === false) return {
|
|
51
|
+
body: null,
|
|
52
|
+
signedBodyTooLarge: false
|
|
53
|
+
};
|
|
54
|
+
const isJson = (req.headers.get("content-type") ?? "").toLowerCase().includes("application/json");
|
|
55
|
+
if (requestPresentsKyaSignature(req.headers)) {
|
|
56
|
+
const read = await readBodyBounded(req, KYA_SIGNED_BODY_MAX_BYTES);
|
|
57
|
+
if ("failure" in read) return {
|
|
58
|
+
body: null,
|
|
59
|
+
signedBodyTooLarge: read.failure === "too-large"
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
body: isJson ? new TextDecoder().decode(read.bytes) : null,
|
|
63
|
+
rawBody: read.bytes,
|
|
64
|
+
signedBodyTooLarge: false
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (!isJson) return {
|
|
68
|
+
body: null,
|
|
69
|
+
signedBodyTooLarge: false
|
|
70
|
+
};
|
|
71
|
+
try {
|
|
72
|
+
return {
|
|
73
|
+
body: await req.clone().text(),
|
|
74
|
+
signedBodyTooLarge: false
|
|
75
|
+
};
|
|
76
|
+
} catch {
|
|
77
|
+
return {
|
|
78
|
+
body: null,
|
|
79
|
+
signedBodyTooLarge: false
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Convert a `Headers` instance into a lowercase-keyed plain object.
|
|
85
|
+
* HTTP header names are case-insensitive (RFC 9110 § 5.1); the
|
|
86
|
+
* orchestrator does case-sensitive lookups, so we normalise to
|
|
87
|
+
* lowercase here. Multi-value headers (Set-Cookie, Accept) are
|
|
88
|
+
* surfaced as their `Headers.get()` view — a single string with
|
|
89
|
+
* comma-joined values, matching what other host adapters produce.
|
|
90
|
+
*/
|
|
91
|
+
function headersToRecord(headers) {
|
|
92
|
+
const out = {};
|
|
93
|
+
headers.forEach((value, key) => {
|
|
94
|
+
out[key.toLowerCase()] = value;
|
|
95
|
+
});
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/middleware-core.ts
|
|
101
|
+
/**
|
|
102
|
+
* The Next.js side of the shared request pipeline
|
|
103
|
+
* (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts
|
|
104
|
+
* inject their engine and Cedar compiler; runtime-specific WASM initialization
|
|
105
|
+
* stays in each host entry. Public withCheckpoint exports live there too.
|
|
106
|
+
*/
|
|
107
|
+
/** npm package name this SDK self-reports to the detection reporter. */
|
|
108
|
+
const SDK_NAME = "@kya-os/checkpoint-nextjs";
|
|
109
|
+
/**
|
|
110
|
+
* Installed SDK version, self-reported to the detection reporter so the
|
|
111
|
+
* dashboard can version-gate "composed policy enforces here". MUST equal
|
|
112
|
+
* `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
|
|
113
|
+
* drifted). Re-exported as `VERSION` from the package index.
|
|
114
|
+
*/
|
|
115
|
+
const VERSION = "1.13.0";
|
|
116
|
+
/**
|
|
117
|
+
* Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
|
|
118
|
+
* suitable for `export default withCheckpoint({...})` in `middleware.ts`.
|
|
119
|
+
*
|
|
120
|
+
* Every verification decision flows through the Rust `kya-os-engine`
|
|
121
|
+
* via WASM. The TS layer translates request shape, runs the shared
|
|
122
|
+
* pipeline, and translates the verdict to `NextResponse`. No
|
|
123
|
+
* verification logic lives in this file.
|
|
124
|
+
*
|
|
125
|
+
* It never throws. An error in the configuration or in loading the engine
|
|
126
|
+
* would otherwise fail the middleware module, and a Next.js middleware that
|
|
127
|
+
* fails to load can let requests through unchecked. Every such error is
|
|
128
|
+
* answered 503 instead (fail closed) and logged.
|
|
129
|
+
*/
|
|
130
|
+
function makeNextMiddleware(config, host) {
|
|
131
|
+
try {
|
|
132
|
+
return makeMiddleware(config, host);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return async function misconfiguredCheckpointMiddleware() {
|
|
135
|
+
console.error("[checkpoint] withCheckpoint is misconfigured; responding 503:", error);
|
|
136
|
+
return failClosedResponse();
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function makeMiddleware(config, host) {
|
|
141
|
+
const pipeline = makeCheckpointPipeline(config, {
|
|
142
|
+
sdk: {
|
|
143
|
+
name: SDK_NAME,
|
|
144
|
+
version: VERSION,
|
|
145
|
+
runtime: host.runtime
|
|
146
|
+
},
|
|
147
|
+
loadEngine: host.loadEngine,
|
|
148
|
+
policyCompiler: host.policyCompiler,
|
|
149
|
+
start: host.start
|
|
150
|
+
});
|
|
151
|
+
const translateOpts = {
|
|
152
|
+
drainJsonBody: config.drainJsonBody,
|
|
153
|
+
clientIpPolicy: config.clientIpPolicy
|
|
154
|
+
};
|
|
155
|
+
return async function checkpointMiddleware(req, event) {
|
|
156
|
+
const waitUntil$1 = event ? (promise) => event.waitUntil(promise) : waitUntil;
|
|
157
|
+
try {
|
|
158
|
+
const { httpLike, signedBodyTooLarge } = await translateNextRequest(req, translateOpts);
|
|
159
|
+
if (signedBodyTooLarge && config.enforcementMode !== "observe") return signedBodyTooLargeResponse();
|
|
160
|
+
const { rendered } = await pipeline({
|
|
161
|
+
request: req,
|
|
162
|
+
translate: () => httpLike,
|
|
163
|
+
headers: req.headers,
|
|
164
|
+
path: req.nextUrl.pathname,
|
|
165
|
+
clientIp: () => getClientIp(req, config.clientIpPolicy),
|
|
166
|
+
reportContext: () => extractReporterContext(req, config.clientIpPolicy),
|
|
167
|
+
waitUntil: waitUntil$1
|
|
168
|
+
});
|
|
169
|
+
return adaptToNextResponse(rendered, req);
|
|
170
|
+
} catch (err) {
|
|
171
|
+
logPipelineFailure(err, config.debug);
|
|
172
|
+
return failClosedResponse();
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Pull the request context the dashboard's `/api/v1/log-detection`
|
|
178
|
+
* endpoint expects out of a `NextRequest`. Works under both Node and
|
|
179
|
+
* Edge runtimes — no runtime-specific APIs.
|
|
180
|
+
*/
|
|
181
|
+
function extractReporterContext(req, policy) {
|
|
182
|
+
return {
|
|
183
|
+
userAgent: req.headers.get("user-agent") ?? void 0,
|
|
184
|
+
ipAddress: getClientIp(req, policy),
|
|
185
|
+
path: req.nextUrl.pathname,
|
|
186
|
+
url: req.nextUrl.href,
|
|
187
|
+
method: req.method
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
//#endregion
|
|
192
|
+
export { makeNextMiddleware as n, VERSION as t };
|
|
193
|
+
//# sourceMappingURL=middleware-core-DN_FLlaV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-core-DN_FLlaV.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';\nimport {\n KYA_SIGNED_BODY_MAX_BYTES,\n readBodyBounded,\n requestPresentsKyaSignature,\n} from '@kya-os/checkpoint-shared/kya-http';\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: JSON bodies so the orchestrator can extract a\n * KYA-OS envelope from `_meta.proof.jws` (the canonical spec-form\n * transport), and the exact bytes of a kya-http/2 signed request so the\n * KYA HTTP Binding can check its `Content-Digest`.\n *\n * Trade-off — body draining consumes the request stream. We read a\n * `req.clone()` so the original `req.body` stream is preserved for\n * 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`). With draining off, a kya-http/2 request whose\n * `Content-Length` or `Transfer-Encoding` declares a body is refused,\n * because the body cannot be bound to its signature.\n */\nexport interface NextRequestToHttpLikeOpts {\n /**\n * Read the request body when `content-type` is `application/json` or the\n * request carries a kya-http/2 signature. Default `true`. Set `false`\n * for streaming 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/** {@link translateNextRequest}'s result. */\nexport interface TranslatedNextRequest {\n httpLike: IncomingHttpLike;\n /** A kya-http/2 signed body over 1 MiB: the middleware answers 413 (enforce mode). */\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * When `opts.drainJsonBody !== false` the translator reads a clone of\n * the request body: JSON as a string so `buildAgentRequest` can extract\n * a `_meta.proof.jws` envelope, and the body of a kya-http/2 signed\n * request as its exact bytes (`rawBody`) for the `Content-Digest` check.\n * The original `req.body` stream is preserved for downstream handlers.\n *\n * When the body can't be read (drain disabled, non-JSON unsigned, or a\n * stream error) we pass `body: null` and the orchestrator routes to\n * PlainHttp — same behavior as the pre-1.1.0 default. A kya-http/2\n * request whose `Content-Length` or `Transfer-Encoding` declares a body\n * the engine never received is refused by the orchestrator.\n */\nexport async function translateNextRequest(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<TranslatedNextRequest> {\n const url = new URL(req.url);\n const { body, rawBody, signedBodyTooLarge } = await tryDrainBody(req, opts);\n return {\n httpLike: {\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 ...(rawBody ? { rawBody } : {}),\n remoteAddress: getClientIp(req, opts.clientIpPolicy),\n },\n signedBodyTooLarge,\n };\n}\n\n/** {@link translateNextRequest} without the over-cap signal. */\nexport async function nextRequestToHttpLike(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<IncomingHttpLike> {\n return (await translateNextRequest(req, opts)).httpLike;\n}\n\ninterface DrainedBody {\n body: string | null;\n rawBody?: Uint8Array;\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Read the request body when the caller has opted in (default). Returns\n * `body: null` on any failure — the orchestrator handles `null` as \"no\n * 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 tryDrainBody(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts\n): Promise<DrainedBody> {\n if (opts.drainJsonBody === false) return { body: null, signedBodyTooLarge: false };\n const contentType = req.headers.get('content-type') ?? '';\n const isJson = contentType.toLowerCase().includes('application/json');\n // Any content type: a kya-http/2 signature binds the body bytes, not a\n // parsed form of them. Gated on a `kya` signature member so ordinary\n // uploads and vendor signatures are never buffered here. A signed body\n // the bounded read could not take is withheld entirely, JSON included:\n // falling through to the unbounded text read below would hand the engine\n // the body anyway.\n if (requestPresentsKyaSignature(req.headers)) {\n const read = await readBodyBounded(req, KYA_SIGNED_BODY_MAX_BYTES);\n if ('failure' in read) {\n return { body: null, signedBodyTooLarge: read.failure === 'too-large' };\n }\n return {\n body: isJson ? new TextDecoder().decode(read.bytes) : null,\n rawBody: read.bytes,\n signedBodyTooLarge: false,\n };\n }\n if (!isJson) return { body: null, signedBodyTooLarge: false };\n try {\n return { body: await req.clone().text(), signedBodyTooLarge: false };\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 { body: null, signedBodyTooLarge: false };\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, signedBodyTooLargeResponse } from './adapt';\nimport type { CheckpointConfig } from './config';\nimport { translateNextRequest } 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.13.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 // A kya-http/2 signed body is read here, before the shared pipeline: over\n // the cap it is answered 413 and never verified in part, as the .NET\n // adapters do. Observe mode passes everything through: the request goes\n // on to verification without its bytes, the orchestrator refuses it\n // there, and observe reports that as the would-have-been Block.\n const { httpLike, signedBodyTooLarge } = await translateNextRequest(req, translateOpts);\n if (signedBodyTooLarge && config.enforcementMode !== 'observe') {\n return signedBodyTooLargeResponse();\n }\n const { rendered } = await pipeline({\n request: req,\n translate: () => httpLike,\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":";;;;;;;;;;;;;;;;;;;;;;;AAiFA,eAAsB,qBACpB,KACA,OAAkC,CAAC,GACH;CAChC,MAAM,MAAM,IAAI,IAAI,IAAI,GAAG;CAC3B,MAAM,EAAE,MAAM,SAAS,uBAAuB,MAAM,aAAa,KAAK,IAAI;CAC1E,OAAO;EACL,UAAU;GACR,QAAQ,IAAI;GAEZ,KAAK,IAAI,WAAW,IAAI;GACxB,SAAS,gBAAgB,IAAI,OAAO;GACpC;GACA,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;GAC7B,eAAe,YAAY,KAAK,KAAK,cAAc;EACrD;EACA;CACF;AACF;;;;;;;;;;;AA0BA,eAAe,aACb,KACA,MACsB;CACtB,IAAI,KAAK,kBAAkB,OAAO,OAAO;EAAE,MAAM;EAAM,oBAAoB;CAAM;CAEjF,MAAM,UADc,IAAI,QAAQ,IAAI,cAAc,KAAK,GAC7B,CAAC,YAAY,CAAC,CAAC,SAAS,kBAAkB;CAOpE,IAAI,4BAA4B,IAAI,OAAO,GAAG;EAC5C,MAAM,OAAO,MAAM,gBAAgB,KAAK,yBAAyB;EACjE,IAAI,aAAa,MACf,OAAO;GAAE,MAAM;GAAM,oBAAoB,KAAK,YAAY;EAAY;EAExE,OAAO;GACL,MAAM,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,KAAK,IAAI;GACtD,SAAS,KAAK;GACd,oBAAoB;EACtB;CACF;CACA,IAAI,CAAC,QAAQ,OAAO;EAAE,MAAM;EAAM,oBAAoB;CAAM;CAC5D,IAAI;EACF,OAAO;GAAE,MAAM,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;GAAG,oBAAoB;EAAM;CACrE,QAAQ;EAIN,OAAO;GAAE,MAAM;GAAM,oBAAoB;EAAM;CACjD;AACF;;;;;;;;;AAUA,SAAS,gBAAgB,SAA0C;CACjE,MAAM,MAA8B,CAAC;CACrC,QAAQ,SAAS,OAAO,QAAQ;EAC9B,IAAI,IAAI,YAAY,KAAK;CAC3B,CAAC;CACD,OAAO;AACT;;;;;;;;;;;AC1HA,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;GAMF,MAAM,EAAE,UAAU,uBAAuB,MAAM,qBAAqB,KAAK,aAAa;GACtF,IAAI,sBAAsB,OAAO,oBAAoB,WACnD,OAAO,2BAA2B;GAEpC,MAAM,EAAE,aAAa,MAAM,SAAS;IAClC,SAAS;IACT,iBAAiB;IACjB,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,9 +1,6 @@
|
|
|
1
|
-
import "./config-
|
|
2
|
-
import { ComposedPolicyContext } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
1
|
+
import "./config-CXS_-rRv.js";
|
|
3
2
|
import { NextRequest, NextResponse } from "next/server.js";
|
|
4
|
-
import "@kya-os/checkpoint-wasm-runtime/
|
|
5
|
-
import { VerifyResult } from "@kya-os/checkpoint-wasm-runtime/engine";
|
|
6
|
-
import "@kya-os/checkpoint-wasm-runtime/orchestrator";
|
|
3
|
+
import "@kya-os/checkpoint-wasm-runtime/pipeline";
|
|
7
4
|
//#region src/middleware-core.d.ts
|
|
8
5
|
/**
|
|
9
6
|
* Installed SDK version, self-reported to the detection reporter so the
|
|
@@ -11,7 +8,7 @@ import "@kya-os/checkpoint-wasm-runtime/orchestrator";
|
|
|
11
8
|
* `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
|
|
12
9
|
* drifted). Re-exported as `VERSION` from the package index.
|
|
13
10
|
*/
|
|
14
|
-
declare const VERSION = "1.
|
|
11
|
+
declare const VERSION = "1.13.0";
|
|
15
12
|
//#endregion
|
|
16
13
|
export { VERSION as t };
|
|
17
|
-
//# sourceMappingURL=middleware-core-
|
|
14
|
+
//# sourceMappingURL=middleware-core-DaNMjsib.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-core-DaNMjsib.d.ts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-
|
|
1
|
+
import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-DQ-VuHlJ.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":";;;;;
|
|
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-
|
|
1
|
+
import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-CXS_-rRv.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":";;;;;
|
|
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"}
|
package/dist/middleware-edge.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_middleware_core = require('./middleware-core-
|
|
2
|
+
const require_middleware_core = require('./middleware-core-0s8y7UNN.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
|
-
|
|
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
|
-
*
|
|
54
|
-
* the Edge runtime (it is larger than the engine-only
|
|
55
|
-
* that never evaluate Cedar don't carry it. When the
|
|
56
|
-
* `engineWasmModule` or `cedarWasmModule`, it is registered
|
|
57
|
-
* `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's
|
|
58
|
-
* instance when the engine runs on it, and the async `evaluatePolicy`
|
|
59
|
-
* is
|
|
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:
|
|
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
|
|
67
|
-
|
|
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 (
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
package/dist/middleware-edge.mjs
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { n as makeNextMiddleware } from "./middleware-core-
|
|
1
|
+
import { n as makeNextMiddleware } from "./middleware-core-DN_FLlaV.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
|
-
|
|
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
|
-
*
|
|
53
|
-
* the Edge runtime (it is larger than the engine-only
|
|
54
|
-
* that never evaluate Cedar don't carry it. When the
|
|
55
|
-
* `engineWasmModule` or `cedarWasmModule`, it is registered
|
|
56
|
-
* `initPolicyEvaluatorEdge`, wasm-runtime evaluates policy on the engine's
|
|
57
|
-
* instance when the engine runs on it, and the async `evaluatePolicy`
|
|
58
|
-
* is
|
|
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:
|
|
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
|
|
66
|
-
|
|
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
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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 {
|
|
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-
|
|
2
|
-
import { t as VERSION } from "./middleware-core-
|
|
1
|
+
import { t as CheckpointConfig } from "./config-DQ-VuHlJ.mjs";
|
|
2
|
+
import { t as VERSION } from "./middleware-core-Cxb9Jh0a.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-
|
|
2
|
-
import { t as VERSION } from "./middleware-core-
|
|
1
|
+
import { t as CheckpointConfig } from "./config-CXS_-rRv.js";
|
|
2
|
+
import { t as VERSION } from "./middleware-core-DaNMjsib.js";
|
|
3
3
|
//#region src/middleware-node.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
|
package/dist/middleware-node.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_middleware_core = require('./middleware-core-
|
|
3
|
-
const require_middleware_node_context = require('./middleware-node-context-
|
|
2
|
+
const require_middleware_core = require('./middleware-core-0s8y7UNN.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
|
-
|
|
19
|
+
policyCompiler: require_middleware_node_context.nodePolicyCompiler
|
|
20
20
|
});
|
|
21
21
|
}
|
|
22
22
|
|
package/dist/middleware-node.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-
|
|
2
|
-
import { t as
|
|
1
|
+
import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-DN_FLlaV.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
|
-
|
|
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 {
|
|
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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kya-os/checkpoint-nextjs",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.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-
|
|
107
|
-
"@kya-os/checkpoint-
|
|
106
|
+
"@kya-os/checkpoint-shared": "^1.10.0",
|
|
107
|
+
"@kya-os/checkpoint-wasm-runtime": "^1.15.0"
|
|
108
108
|
},
|
|
109
109
|
"scripts": {
|
|
110
110
|
"build": "tsdown",
|