@kya-os/checkpoint-nextjs 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +322 -0
- package/README.md +205 -31
- package/dist/adapt-BdQ9R7Iw.mjs +97 -0
- package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
- package/dist/adapt-CCSKGjVH.js +107 -0
- package/dist/api-client-JHOrRUA_.d.mts +222 -0
- package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
- package/dist/api-client-JHOrRUA_.d.ts +222 -0
- package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
- package/dist/api-client.d.mts +2 -213
- package/dist/api-client.d.ts +2 -213
- package/dist/api-client.js +221 -206
- package/dist/api-client.mjs +222 -202
- package/dist/api-client.mjs.map +1 -0
- package/dist/api-middleware-BWjokNis.d.mts +131 -0
- package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
- package/dist/api-middleware-Bf3xmM9W.js +391 -0
- package/dist/api-middleware-C-ngFX_8.mjs +387 -0
- package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
- package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
- package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
- package/dist/api-middleware.d.mts +2 -166
- package/dist/api-middleware.d.ts +2 -166
- package/dist/api-middleware.js +3 -526
- package/dist/api-middleware.mjs +2 -521
- package/dist/cedar-wasm.d.mts +20 -0
- package/dist/cedar-wasm.d.mts.map +1 -0
- package/dist/cedar-wasm.d.ts +19 -0
- package/dist/cedar-wasm.d.ts.map +1 -0
- package/dist/cedar-wasm.js +24 -0
- package/dist/cedar-wasm.mjs +23 -0
- package/dist/cedar-wasm.mjs.map +1 -0
- package/dist/config-CPP1RV0f.d.mts +291 -0
- package/dist/config-CPP1RV0f.d.mts.map +1 -0
- package/dist/config-DVgOFxJs.d.ts +291 -0
- package/dist/config-DVgOFxJs.d.ts.map +1 -0
- package/dist/engine-wasm.d.mts +20 -0
- package/dist/engine-wasm.d.mts.map +1 -0
- package/dist/engine-wasm.d.ts +19 -0
- package/dist/engine-wasm.d.ts.map +1 -0
- package/dist/engine-wasm.js +24 -0
- package/dist/engine-wasm.mjs +23 -0
- package/dist/engine-wasm.mjs.map +1 -0
- package/dist/index-edge.d.mts +8 -0
- package/dist/index-edge.d.ts +8 -0
- package/dist/index-edge.js +14 -0
- package/dist/index-edge.mjs +7 -0
- package/dist/index.d.mts +8 -17
- package/dist/index.d.ts +8 -17
- package/dist/index.js +36 -1275
- package/dist/index.mjs +29 -1234
- package/dist/index.mjs.map +1 -0
- package/dist/middleware-bundler.d.mts +6 -12
- package/dist/middleware-bundler.d.mts.map +1 -0
- package/dist/middleware-bundler.d.ts +6 -12
- package/dist/middleware-bundler.d.ts.map +1 -0
- package/dist/middleware-bundler.js +12 -350
- package/dist/middleware-bundler.mjs +11 -347
- package/dist/middleware-bundler.mjs.map +1 -0
- package/dist/middleware-core-B0jf5_Hm.mjs +264 -0
- package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
- package/dist/middleware-core-Bol44X9C.d.ts +17 -0
- package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
- package/dist/middleware-core-CMc-2QkU.js +274 -0
- package/dist/middleware-core-DycsbHUd.d.mts +17 -0
- package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
- package/dist/middleware-edge.d.mts +16 -14
- package/dist/middleware-edge.d.mts.map +1 -0
- package/dist/middleware-edge.d.ts +16 -14
- package/dist/middleware-edge.d.ts.map +1 -0
- package/dist/middleware-edge.js +94 -355
- package/dist/middleware-edge.mjs +90 -347
- package/dist/middleware-edge.mjs.map +1 -0
- package/dist/middleware-node-context-591KsiYg.js +39 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs +35 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
- package/dist/middleware-node.d.mts +10 -25
- package/dist/middleware-node.d.mts.map +1 -0
- package/dist/middleware-node.d.ts +10 -25
- package/dist/middleware-node.d.ts.map +1 -0
- package/dist/middleware-node.js +21 -351
- package/dist/middleware-node.mjs +19 -347
- package/dist/middleware-node.mjs.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
- package/dist/posture-outcome-DddsJtL8.js +25 -0
- package/dist/public-api-CYsHrTQI.d.ts +5 -0
- package/dist/public-api-DkG7pRE0.d.mts +5 -0
- package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
- package/dist/utils-Cnwg0VrY.mjs +88 -0
- package/dist/utils-Cnwg0VrY.mjs.map +1 -0
- package/dist/utils-dyFxqlFI.js +104 -0
- package/package.json +31 -66
- package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
- package/bin/setup-edge-wasm.js +0 -513
- package/dist/adapt.d.mts +0 -39
- package/dist/adapt.d.ts +0 -39
- package/dist/adapt.js +0 -59
- package/dist/adapt.mjs +0 -57
- package/dist/composed-policy.d.mts +0 -115
- package/dist/composed-policy.d.ts +0 -115
- package/dist/composed-policy.js +0 -103
- package/dist/composed-policy.mjs +0 -97
- package/dist/config-CleTeeoW.d.mts +0 -233
- package/dist/config-XMOIkxFN.d.ts +0 -233
- package/dist/create-middleware.d.mts +0 -22
- package/dist/create-middleware.d.ts +0 -22
- package/dist/create-middleware.js +0 -34
- package/dist/create-middleware.mjs +0 -31
- package/dist/edge/index.d.mts +0 -112
- package/dist/edge/index.d.ts +0 -112
- package/dist/edge/index.js +0 -277
- package/dist/edge/index.mjs +0 -275
- package/dist/edge-runtime-loader.d.mts +0 -77
- package/dist/edge-runtime-loader.d.ts +0 -77
- package/dist/edge-runtime-loader.js +0 -242
- package/dist/edge-runtime-loader.mjs +0 -235
- package/dist/edge-wasm-middleware.d.mts +0 -62
- package/dist/edge-wasm-middleware.d.ts +0 -62
- package/dist/edge-wasm-middleware.js +0 -26
- package/dist/edge-wasm-middleware.mjs +0 -22
- package/dist/middleware.d.mts +0 -45
- package/dist/middleware.d.ts +0 -45
- package/dist/middleware.js +0 -19
- package/dist/middleware.mjs +0 -15
- package/dist/nodejs-wasm-loader.d.mts +0 -41
- package/dist/nodejs-wasm-loader.d.ts +0 -41
- package/dist/nodejs-wasm-loader.js +0 -36
- package/dist/nodejs-wasm-loader.mjs +0 -30
- package/dist/policy.d.mts +0 -162
- package/dist/policy.d.ts +0 -162
- package/dist/policy.js +0 -198
- package/dist/policy.mjs +0 -174
- package/dist/session-tracker.d.mts +0 -55
- package/dist/session-tracker.d.ts +0 -55
- package/dist/session-tracker.js +0 -172
- package/dist/session-tracker.mjs +0 -169
- package/dist/translate.d.mts +0 -63
- package/dist/translate.d.ts +0 -63
- package/dist/translate.js +0 -44
- package/dist/translate.mjs +0 -42
- package/dist/types-Chgi5TFC.d.mts +0 -105
- package/dist/types-Chgi5TFC.d.ts +0 -105
- package/dist/wasm-setup.d.mts +0 -46
- package/dist/wasm-setup.d.ts +0 -46
- package/dist/wasm-setup.js +0 -122
- package/dist/wasm-setup.mjs +0 -118
- package/wasm/agentshield_wasm.d.ts +0 -479
- package/wasm/agentshield_wasm.js +0 -1536
- package/wasm/agentshield_wasm_bg.wasm +0 -0
- package/wasm/package.json +0 -30
- package/wasm.d.ts +0 -21
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-core-B0jf5_Hm.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 * Shared Next.js request pipeline. Node, bundler and Edge hosts inject their\n * engine and policy-context factories; runtime-specific WASM initialization\n * stays in each host entry. Public withCheckpoint exports live there too.\n */\n\nimport {\n postureRequestFromHeaders,\n validateBrowserPostureConfig,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport {\n applyBrowserPosture,\n applyBrowserIntegrityStepUp,\n applyComposedPolicy,\n applyRequestClaim,\n createLocalRequestClaimStore,\n createPlatformRequestClaimStore,\n isConsentRemediableBlock,\n resolveTrustedDelegationRootsForRequest,\n validateBrowserIntegrityChallenge,\n DEFAULT_DASHBOARD_URL,\n type ComposedPolicyContext,\n type TrustedDelegationRootsResolver,\n type RequestClaimStore,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\n\nimport { type NextFetchEvent, type NextRequest, type NextResponse } from 'next/server.js';\n\nimport type {\n renderDecisionAsResponse as RenderDecision,\n IncomingHttpLike,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport type { VerifyRequestEdgeOpts } from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';\nimport { makeEngineDefaults } from '@kya-os/checkpoint-wasm-runtime/adapters';\nimport {\n makeDetectionReporter,\n type DetectionReporter,\n type ReporterContext,\n} from '@kya-os/checkpoint-wasm-runtime/reporter';\nimport type { VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\nimport { PolicyFetcher } from '@kya-os/checkpoint-shared/policy/fetcher';\nimport {\n resolveChallengeContext,\n selectBodyReadable200,\n} from '@kya-os/checkpoint-shared/host-adapter';\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` (a 190-line documented contract); the\n// public import paths (`.`, `/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 interface EngineEntry {\n // Typed with the Edge options, which add `waitUntil`; the Node and bundler\n // builds take the same call and ignore it.\n verifyRequest: (req: IncomingHttpLike, opts: VerifyRequestEdgeOpts) => Promise<VerifyResult>;\n renderDecisionAsResponse: typeof RenderDecision;\n}\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 buildComposedContext: (config: CheckpointConfig) => ComposedPolicyContext | null;\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/**\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, calls\n * `verifyRequest`, 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 */\nlet warnedLocalClaimStore = false;\n\n/**\n * Where accepted signed requests are claimed: the caller's store, else the\n * dashboard's shared ledger when the project is configured, else this\n * process (or isolate), with a one-time warning that several instances need\n * a shared store.\n */\nfunction buildRequestClaimStore(config: CheckpointConfig): RequestClaimStore {\n if (config.requestClaimStore) return config.requestClaimStore;\n if (config.apiKey && config.projectId) {\n return createPlatformRequestClaimStore({\n baseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,\n apiKey: config.apiKey,\n });\n }\n if (!warnedLocalClaimStore) {\n warnedLocalClaimStore = true;\n console.warn(\n '[checkpoint] signed requests are claimed in this process only; a deployment with several instances needs apiKey and projectId, or a shared requestClaimStore'\n );\n }\n return createLocalRequestClaimStore();\n}\n\nexport function makeNextMiddleware(\n config: CheckpointConfig,\n host: NextMiddlewareHost\n): CheckpointMiddleware {\n try {\n return makePipeline(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 makePipeline(config: CheckpointConfig, host: NextMiddlewareHost): CheckpointMiddleware {\n if (config.browserPosture) validateBrowserPostureConfig(config.browserPosture, config.projectId);\n if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) {\n throw new Error(\n 'browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)'\n );\n }\n host.start?.(config);\n const engine = memoizeEngine(host.loadEngine);\n // Start loading now; a failure is answered by the first request that needs it.\n engine().catch(() => undefined);\n const opts = buildVerifyOpts(config);\n const reporter = buildReporter(config, host.runtime);\n // Null deliberately disables composed policy on Edge without a Cedar module;\n // it must never fall back to a Node policy compiler.\n const composed = host.buildComposedContext(config);\n const requestClaimStore = buildRequestClaimStore(config);\n const trustedRootsResolver = buildTrustedRootsResolver(config, composed);\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 { verifyRequest, renderDecisionAsResponse } = await engine().catch((error) => {\n console.error('[checkpoint] kya-os-engine failed to load; responding 503:', error);\n throw error;\n });\n const httpLike = await nextRequestToHttpLike(req, translateOpts);\n // P2 / DR-1: on a credential-bearing request, pin the engine's L2 delegation chains\n // to the org's trusted roots (resolved from the same cached policy payload).\n // Omitted on the hot path → opts unchanged (byte-identical to pre-P2).\n const trustedDelegationRoots = await resolveTrustedDelegationRootsForRequest(\n trustedRootsResolver,\n req.headers\n );\n const result = await verifyRequest(httpLike, {\n ...opts,\n ...(trustedDelegationRoots ? { trustedDelegationRoots } : {}),\n waitUntil,\n });\n // Composed (kya-os-engine) policy seam — swaps result.decision in place when\n // the project's deployed Cedar bundle acts. MUST run BEFORE the reporter so\n // the dashboard records the enforced decision (parity with Express + the\n // shadow→enforce telemetry). `req.nextUrl.pathname` is the query-free path\n // verification saw. A fault on an enforcing project throws → 503.\n await applyBrowserPosture(\n result,\n postureRequestFromHeaders((name) => req.headers.get(name)),\n config.browserPosture,\n config.projectId\n );\n await applyComposedPolicy(composed, result, req.nextUrl.pathname);\n applyBrowserIntegrityStepUp(result, config.browserPosture, req.nextUrl.pathname);\n // The final decision is known: claim an accepted signed request before\n // anything acts on it, so it is used once.\n await applyRequestClaim(result, requestClaimStore, {\n sourceIp: getClientIp(req, config.clientIpPolicy) ?? undefined,\n });\n if (reporter) {\n waitUntil(reporter(result, extractReporterContext(req, config.clientIpPolicy)));\n }\n await dispatchOnResult(config, result, req);\n // Dual envelope: body-readable 200 step-up for cooperative agents under\n // negotiated mode; else the spec 401/422. Shared selector (drift-proof).\n const bodyReadable200 = selectBodyReadable200(\n config.delegationChallengeMode ?? 'negotiated',\n req.headers,\n result.detectionDetail.detectionClass,\n result.detectionDetail.isAgent\n );\n const challengeContextRequested =\n result.enforcementMode === 'enforce' &&\n (result.decision.kind === 'Challenge' || isConsentRemediableBlock(result)) &&\n config.resolveDelegationChallenge !== undefined;\n const delegationChallenge = challengeContextRequested\n ? await resolveChallengeContext(\n config.resolveDelegationChallenge,\n { result, request: req },\n {\n timeoutMs: config.delegationChallengeTimeoutMs,\n onFailure: config.onDelegationChallengeFailure,\n }\n )\n : undefined;\n const rendered = renderDecisionAsResponse(result, {\n bodyReadable200,\n delegationChallenge: validateBrowserIntegrityChallenge(result, delegationChallenge),\n challengeContextRequested,\n });\n return adaptToNextResponse(rendered, req);\n } catch (err) {\n if (config.debug) {\n console.error('[checkpoint] verification pipeline failed; responding 503:', err);\n }\n return failClosedResponse();\n }\n };\n}\n\n/** Load the engine once; a failed load is retried by the next request. */\nfunction memoizeEngine(load: () => Promise<EngineEntry>): () => Promise<EngineEntry> {\n let loading: Promise<EngineEntry> | undefined;\n return () =>\n (loading ??= load().catch((error: unknown) => {\n loading = undefined;\n throw error;\n }));\n}\n\n/**\n * Build a fire-and-forget detection reporter from the host config. Returns\n * `null` when `apiKey` is not set — that case is the documented opt-out\n * (engine still runs locally, dashboard just sees no detections).\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.11.0';\n\nfunction buildReporter(\n config: CheckpointConfig,\n runtime: 'node' | 'edge' = 'node'\n): DetectionReporter | null {\n if (!config.apiKey) return null;\n return makeDetectionReporter({\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n debug: config.debug,\n // Self-identify (incl. node-vs-edge) so the dashboard can version-gate\n // enforcement. Next.js EDGE composed enforcement is opt-in (needs\n // `cedarWasmModule`), so the dashboard shows it as opt-in, never \"Enforcing\".\n sdk: { name: SDK_NAME, version: VERSION, runtime },\n });\n}\n\n/**\n * Build the per-factory trusted-delegation-roots resolver (P2 / DR-1). Root\n * pinning is a security concern INDEPENDENT of composed Cedar enforcement, so it\n * must resolve wherever a `projectId` exists — including Edge setups that never\n * wire `cedarWasmModule` (where `buildComposedContext` returns null). Prefers the\n * composed context's accessor (reuses its cached fetcher / honors an injected\n * enforcer); otherwise falls back to a `projectId`-only policy fetch. Returns\n * `null` when no source is configured (no roots → the engine rejects delegation).\n * An origin outage rejects with `PolicyUnavailableError`, which the middleware\n * answers as a retryable 503.\n */\nfunction buildTrustedRootsResolver(\n config: CheckpointConfig,\n composed: ComposedPolicyContext | null\n): TrustedDelegationRootsResolver | null {\n if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots!);\n if (composed?.trustedDelegationRoots) {\n return () => composed.trustedDelegationRoots!();\n }\n if (!config.projectId) return null;\n const 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 const projectId = config.projectId;\n return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];\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: import('@kya-os/checkpoint-shared').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\n/** The engine's default options for this config; per-request fields go on top. */\nfunction buildVerifyOpts(config: CheckpointConfig) {\n return makeEngineDefaults(config);\n}\n\nasync function dispatchOnResult(\n config: CheckpointConfig,\n result: VerifyResult,\n req: NextRequest\n): Promise<void> {\n if (!config.onResult) return;\n try {\n await config.onResult(result, req);\n } catch {\n // Swallow — onResult is observability, not verdict-critical.\n // Verdict already computed; let the response proceed.\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;C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M,QAAQ,UAAU,SAAS,EAAC,CAAE,0BAA0B,CAAC;AACrF;;;;;;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;;AAGA,SAAS,gBAAgB,QAA0B;CACjD,OAAO,mBAAmB,MAAM;AAClC;AAEA,eAAe,iBACb,QACA,QACA,KACe;CACf,IAAI,CAAC,OAAO,UAAU;CACtB,IAAI;EACF,MAAM,OAAO,SAAS,QAAQ,GAAG;CACnC,QAAQ,CAGR;AACF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import "./config-DVgOFxJs.js";
|
|
2
|
+
import { NextRequest, NextResponse } from "next/server.js";
|
|
3
|
+
import "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
|
|
4
|
+
import { ComposedPolicyContext } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
5
|
+
import { VerifyResult } from "@kya-os/checkpoint-wasm-runtime/engine";
|
|
6
|
+
import "@kya-os/checkpoint-wasm-runtime/orchestrator";
|
|
7
|
+
//#region src/middleware-core.d.ts
|
|
8
|
+
/**
|
|
9
|
+
* Installed SDK version, self-reported to the detection reporter so the
|
|
10
|
+
* dashboard can version-gate "composed policy enforces here". MUST equal
|
|
11
|
+
* `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
|
|
12
|
+
* drifted). Re-exported as `VERSION` from the package index.
|
|
13
|
+
*/
|
|
14
|
+
declare const VERSION = "1.11.0";
|
|
15
|
+
//#endregion
|
|
16
|
+
export { VERSION as t };
|
|
17
|
+
//# sourceMappingURL=middleware-core-Bol44X9C.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-core-Bol44X9C.d.ts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;;;;cA8Qa"}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
const require_adapt = require('./adapt-CCSKGjVH.js');
|
|
2
|
+
const require_utils = require('./utils-dyFxqlFI.js');
|
|
3
|
+
let _kya_os_checkpoint_shared_browser_posture = require("@kya-os/checkpoint-shared/browser-posture");
|
|
4
|
+
let _kya_os_checkpoint_wasm_runtime_composed_policy = require("@kya-os/checkpoint-wasm-runtime/composed-policy");
|
|
5
|
+
let _kya_os_checkpoint_wasm_runtime_adapters = require("@kya-os/checkpoint-wasm-runtime/adapters");
|
|
6
|
+
let _kya_os_checkpoint_wasm_runtime_reporter = require("@kya-os/checkpoint-wasm-runtime/reporter");
|
|
7
|
+
let _kya_os_checkpoint_shared_policy_fetcher = require("@kya-os/checkpoint-shared/policy/fetcher");
|
|
8
|
+
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
9
|
+
let _vercel_functions = require("@vercel/functions");
|
|
10
|
+
|
|
11
|
+
//#region src/translate.ts
|
|
12
|
+
/**
|
|
13
|
+
* Translate a Next.js `NextRequest` into the orchestrator's
|
|
14
|
+
* `IncomingHttpLike` shape.
|
|
15
|
+
*
|
|
16
|
+
* When `opts.drainJsonBody !== false` and the request is JSON, the
|
|
17
|
+
* translator clones the request and reads the body into a string so
|
|
18
|
+
* the orchestrator's `buildAgentRequest` can extract a
|
|
19
|
+
* `_meta.proof.jws` envelope. The original `req.body` stream is
|
|
20
|
+
* preserved for downstream handlers via `req.clone()`.
|
|
21
|
+
*
|
|
22
|
+
* When the body can't be read (drain disabled, non-JSON, or a stream
|
|
23
|
+
* error) we pass `body: null` and the orchestrator routes to
|
|
24
|
+
* PlainHttp — same behavior as the pre-1.1.0 default.
|
|
25
|
+
*/
|
|
26
|
+
async function nextRequestToHttpLike(req, opts = {}) {
|
|
27
|
+
const url = new URL(req.url);
|
|
28
|
+
const body = await tryDrainJsonBody(req, opts);
|
|
29
|
+
return {
|
|
30
|
+
method: req.method,
|
|
31
|
+
url: url.pathname + url.search,
|
|
32
|
+
headers: headersToRecord(req.headers),
|
|
33
|
+
body,
|
|
34
|
+
remoteAddress: require_utils.getClientIp(req, opts.clientIpPolicy)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Read the request body as a UTF-8 string when JSON and the caller
|
|
39
|
+
* has opted in (default). Returns `null` on any failure — the
|
|
40
|
+
* orchestrator handles `null` as "no body present" (→ PlainHttp).
|
|
41
|
+
*
|
|
42
|
+
* Clone-first means the original `req.body` ReadableStream stays
|
|
43
|
+
* unconsumed and downstream handlers can re-read it. Without the
|
|
44
|
+
* clone, calling `req.text()` in middleware would block any route
|
|
45
|
+
* handler that needs the body.
|
|
46
|
+
*/
|
|
47
|
+
async function tryDrainJsonBody(req, opts) {
|
|
48
|
+
if (opts.drainJsonBody === false) return null;
|
|
49
|
+
if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
|
|
50
|
+
try {
|
|
51
|
+
return await req.clone().text();
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Convert a `Headers` instance into a lowercase-keyed plain object.
|
|
58
|
+
* HTTP header names are case-insensitive (RFC 9110 § 5.1); the
|
|
59
|
+
* orchestrator does case-sensitive lookups, so we normalise to
|
|
60
|
+
* lowercase here. Multi-value headers (Set-Cookie, Accept) are
|
|
61
|
+
* surfaced as their `Headers.get()` view — a single string with
|
|
62
|
+
* comma-joined values, matching what other host adapters produce.
|
|
63
|
+
*/
|
|
64
|
+
function headersToRecord(headers) {
|
|
65
|
+
const out = {};
|
|
66
|
+
headers.forEach((value, key) => {
|
|
67
|
+
out[key.toLowerCase()] = value;
|
|
68
|
+
});
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/middleware-core.ts
|
|
74
|
+
/**
|
|
75
|
+
* Shared Next.js request pipeline. Node, bundler and Edge hosts inject their
|
|
76
|
+
* engine and policy-context factories; runtime-specific WASM initialization
|
|
77
|
+
* stays in each host entry. Public withCheckpoint exports live there too.
|
|
78
|
+
*/
|
|
79
|
+
/**
|
|
80
|
+
* Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
|
|
81
|
+
* suitable for `export default withCheckpoint({...})` in `middleware.ts`.
|
|
82
|
+
*
|
|
83
|
+
* Every verification decision flows through the Rust `kya-os-engine`
|
|
84
|
+
* via WASM. The TS layer translates request shape, calls
|
|
85
|
+
* `verifyRequest`, and translates the verdict to `NextResponse`. No
|
|
86
|
+
* verification logic lives in this file.
|
|
87
|
+
*
|
|
88
|
+
* It never throws. An error in the configuration or in loading the engine
|
|
89
|
+
* would otherwise fail the middleware module, and a Next.js middleware that
|
|
90
|
+
* fails to load can let requests through unchecked. Every such error is
|
|
91
|
+
* answered 503 instead (fail closed) and logged.
|
|
92
|
+
*/
|
|
93
|
+
let warnedLocalClaimStore = false;
|
|
94
|
+
/**
|
|
95
|
+
* Where accepted signed requests are claimed: the caller's store, else the
|
|
96
|
+
* dashboard's shared ledger when the project is configured, else this
|
|
97
|
+
* process (or isolate), with a one-time warning that several instances need
|
|
98
|
+
* a shared store.
|
|
99
|
+
*/
|
|
100
|
+
function buildRequestClaimStore(config) {
|
|
101
|
+
if (config.requestClaimStore) return config.requestClaimStore;
|
|
102
|
+
if (config.apiKey && config.projectId) return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.createPlatformRequestClaimStore)({
|
|
103
|
+
baseUrl: config.dashboardUrl ?? config.baseUrl ?? _kya_os_checkpoint_wasm_runtime_composed_policy.DEFAULT_DASHBOARD_URL,
|
|
104
|
+
apiKey: config.apiKey
|
|
105
|
+
});
|
|
106
|
+
if (!warnedLocalClaimStore) {
|
|
107
|
+
warnedLocalClaimStore = true;
|
|
108
|
+
console.warn("[checkpoint] signed requests are claimed in this process only; a deployment with several instances needs apiKey and projectId, or a shared requestClaimStore");
|
|
109
|
+
}
|
|
110
|
+
return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.createLocalRequestClaimStore)();
|
|
111
|
+
}
|
|
112
|
+
function makeNextMiddleware(config, host) {
|
|
113
|
+
try {
|
|
114
|
+
return makePipeline(config, host);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
return async function misconfiguredCheckpointMiddleware() {
|
|
117
|
+
console.error("[checkpoint] withCheckpoint is misconfigured; responding 503:", error);
|
|
118
|
+
return require_adapt.failClosedResponse();
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function makePipeline(config, host) {
|
|
123
|
+
if (config.browserPosture) (0, _kya_os_checkpoint_shared_browser_posture.validateBrowserPostureConfig)(config.browserPosture, config.projectId);
|
|
124
|
+
if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) throw new Error("browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)");
|
|
125
|
+
host.start?.(config);
|
|
126
|
+
const engine = memoizeEngine(host.loadEngine);
|
|
127
|
+
engine().catch(() => void 0);
|
|
128
|
+
const opts = buildVerifyOpts(config);
|
|
129
|
+
const reporter = buildReporter(config, host.runtime);
|
|
130
|
+
const composed = host.buildComposedContext(config);
|
|
131
|
+
const requestClaimStore = buildRequestClaimStore(config);
|
|
132
|
+
const trustedRootsResolver = buildTrustedRootsResolver(config, composed);
|
|
133
|
+
const translateOpts = {
|
|
134
|
+
drainJsonBody: config.drainJsonBody,
|
|
135
|
+
clientIpPolicy: config.clientIpPolicy
|
|
136
|
+
};
|
|
137
|
+
return async function checkpointMiddleware(req, event) {
|
|
138
|
+
const waitUntil = event ? (promise) => event.waitUntil(promise) : _vercel_functions.waitUntil;
|
|
139
|
+
try {
|
|
140
|
+
const { verifyRequest, renderDecisionAsResponse } = await engine().catch((error) => {
|
|
141
|
+
console.error("[checkpoint] kya-os-engine failed to load; responding 503:", error);
|
|
142
|
+
throw error;
|
|
143
|
+
});
|
|
144
|
+
const httpLike = await nextRequestToHttpLike(req, translateOpts);
|
|
145
|
+
const trustedDelegationRoots = await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.resolveTrustedDelegationRootsForRequest)(trustedRootsResolver, req.headers);
|
|
146
|
+
const result = await verifyRequest(httpLike, {
|
|
147
|
+
...opts,
|
|
148
|
+
...trustedDelegationRoots ? { trustedDelegationRoots } : {},
|
|
149
|
+
waitUntil
|
|
150
|
+
});
|
|
151
|
+
await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyBrowserPosture)(result, (0, _kya_os_checkpoint_shared_browser_posture.postureRequestFromHeaders)((name) => req.headers.get(name)), config.browserPosture, config.projectId);
|
|
152
|
+
await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyComposedPolicy)(composed, result, req.nextUrl.pathname);
|
|
153
|
+
(0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyBrowserIntegrityStepUp)(result, config.browserPosture, req.nextUrl.pathname);
|
|
154
|
+
await (0, _kya_os_checkpoint_wasm_runtime_composed_policy.applyRequestClaim)(result, requestClaimStore, { sourceIp: require_utils.getClientIp(req, config.clientIpPolicy) ?? void 0 });
|
|
155
|
+
if (reporter) waitUntil(reporter(result, extractReporterContext(req, config.clientIpPolicy)));
|
|
156
|
+
await dispatchOnResult(config, result, req);
|
|
157
|
+
const bodyReadable200 = (0, _kya_os_checkpoint_shared_host_adapter.selectBodyReadable200)(config.delegationChallengeMode ?? "negotiated", req.headers, result.detectionDetail.detectionClass, result.detectionDetail.isAgent);
|
|
158
|
+
const challengeContextRequested = result.enforcementMode === "enforce" && (result.decision.kind === "Challenge" || (0, _kya_os_checkpoint_wasm_runtime_composed_policy.isConsentRemediableBlock)(result)) && config.resolveDelegationChallenge !== void 0;
|
|
159
|
+
const delegationChallenge = challengeContextRequested ? await (0, _kya_os_checkpoint_shared_host_adapter.resolveChallengeContext)(config.resolveDelegationChallenge, {
|
|
160
|
+
result,
|
|
161
|
+
request: req
|
|
162
|
+
}, {
|
|
163
|
+
timeoutMs: config.delegationChallengeTimeoutMs,
|
|
164
|
+
onFailure: config.onDelegationChallengeFailure
|
|
165
|
+
}) : void 0;
|
|
166
|
+
const rendered = renderDecisionAsResponse(result, {
|
|
167
|
+
bodyReadable200,
|
|
168
|
+
delegationChallenge: (0, _kya_os_checkpoint_wasm_runtime_composed_policy.validateBrowserIntegrityChallenge)(result, delegationChallenge),
|
|
169
|
+
challengeContextRequested
|
|
170
|
+
});
|
|
171
|
+
return require_adapt.adaptToNextResponse(rendered, req);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (config.debug) console.error("[checkpoint] verification pipeline failed; responding 503:", err);
|
|
174
|
+
return require_adapt.failClosedResponse();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/** Load the engine once; a failed load is retried by the next request. */
|
|
179
|
+
function memoizeEngine(load) {
|
|
180
|
+
let loading;
|
|
181
|
+
return () => loading ??= load().catch((error) => {
|
|
182
|
+
loading = void 0;
|
|
183
|
+
throw error;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Build a fire-and-forget detection reporter from the host config. Returns
|
|
188
|
+
* `null` when `apiKey` is not set — that case is the documented opt-out
|
|
189
|
+
* (engine still runs locally, dashboard just sees no detections).
|
|
190
|
+
*/
|
|
191
|
+
/** npm package name this SDK self-reports to the detection reporter. */
|
|
192
|
+
const SDK_NAME = "@kya-os/checkpoint-nextjs";
|
|
193
|
+
/**
|
|
194
|
+
* Installed SDK version, self-reported to the detection reporter so the
|
|
195
|
+
* dashboard can version-gate "composed policy enforces here". MUST equal
|
|
196
|
+
* `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
|
|
197
|
+
* drifted). Re-exported as `VERSION` from the package index.
|
|
198
|
+
*/
|
|
199
|
+
const VERSION = "1.11.0";
|
|
200
|
+
function buildReporter(config, runtime = "node") {
|
|
201
|
+
if (!config.apiKey) return null;
|
|
202
|
+
return (0, _kya_os_checkpoint_wasm_runtime_reporter.makeDetectionReporter)({
|
|
203
|
+
apiKey: config.apiKey,
|
|
204
|
+
baseUrl: config.baseUrl,
|
|
205
|
+
debug: config.debug,
|
|
206
|
+
sdk: {
|
|
207
|
+
name: SDK_NAME,
|
|
208
|
+
version: VERSION,
|
|
209
|
+
runtime
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Build the per-factory trusted-delegation-roots resolver (P2 / DR-1). Root
|
|
215
|
+
* pinning is a security concern INDEPENDENT of composed Cedar enforcement, so it
|
|
216
|
+
* must resolve wherever a `projectId` exists — including Edge setups that never
|
|
217
|
+
* wire `cedarWasmModule` (where `buildComposedContext` returns null). Prefers the
|
|
218
|
+
* composed context's accessor (reuses its cached fetcher / honors an injected
|
|
219
|
+
* enforcer); otherwise falls back to a `projectId`-only policy fetch. Returns
|
|
220
|
+
* `null` when no source is configured (no roots → the engine rejects delegation).
|
|
221
|
+
* An origin outage rejects with `PolicyUnavailableError`, which the middleware
|
|
222
|
+
* answers as a retryable 503.
|
|
223
|
+
*/
|
|
224
|
+
function buildTrustedRootsResolver(config, composed) {
|
|
225
|
+
if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots);
|
|
226
|
+
if (composed?.trustedDelegationRoots) return () => composed.trustedDelegationRoots();
|
|
227
|
+
if (!config.projectId) return null;
|
|
228
|
+
const fetcher = new _kya_os_checkpoint_shared_policy_fetcher.PolicyFetcher({
|
|
229
|
+
apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? _kya_os_checkpoint_wasm_runtime_composed_policy.DEFAULT_DASHBOARD_URL,
|
|
230
|
+
apiKey: config.apiKey,
|
|
231
|
+
cacheTtlSeconds: config.policyCacheTtlSeconds,
|
|
232
|
+
throwOnUnavailable: true
|
|
233
|
+
});
|
|
234
|
+
const projectId = config.projectId;
|
|
235
|
+
return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Pull the request context the dashboard's `/api/v1/log-detection`
|
|
239
|
+
* endpoint expects out of a `NextRequest`. Works under both Node and
|
|
240
|
+
* Edge runtimes — no runtime-specific APIs.
|
|
241
|
+
*/
|
|
242
|
+
function extractReporterContext(req, policy) {
|
|
243
|
+
return {
|
|
244
|
+
userAgent: req.headers.get("user-agent") ?? void 0,
|
|
245
|
+
ipAddress: require_utils.getClientIp(req, policy),
|
|
246
|
+
path: req.nextUrl.pathname,
|
|
247
|
+
url: req.nextUrl.href,
|
|
248
|
+
method: req.method
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/** The engine's default options for this config; per-request fields go on top. */
|
|
252
|
+
function buildVerifyOpts(config) {
|
|
253
|
+
return (0, _kya_os_checkpoint_wasm_runtime_adapters.makeEngineDefaults)(config);
|
|
254
|
+
}
|
|
255
|
+
async function dispatchOnResult(config, result, req) {
|
|
256
|
+
if (!config.onResult) return;
|
|
257
|
+
try {
|
|
258
|
+
await config.onResult(result, req);
|
|
259
|
+
} catch {}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
//#endregion
|
|
263
|
+
Object.defineProperty(exports, 'VERSION', {
|
|
264
|
+
enumerable: true,
|
|
265
|
+
get: function () {
|
|
266
|
+
return VERSION;
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
Object.defineProperty(exports, 'makeNextMiddleware', {
|
|
270
|
+
enumerable: true,
|
|
271
|
+
get: function () {
|
|
272
|
+
return makeNextMiddleware;
|
|
273
|
+
}
|
|
274
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import "./config-CPP1RV0f.mjs";
|
|
2
|
+
import { ComposedPolicyContext } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
3
|
+
import { NextRequest, NextResponse } from "next/server.js";
|
|
4
|
+
import "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
|
|
5
|
+
import { VerifyResult } from "@kya-os/checkpoint-wasm-runtime/engine";
|
|
6
|
+
import "@kya-os/checkpoint-wasm-runtime/orchestrator";
|
|
7
|
+
//#region src/middleware-core.d.ts
|
|
8
|
+
/**
|
|
9
|
+
* Installed SDK version, self-reported to the detection reporter so the
|
|
10
|
+
* dashboard can version-gate "composed policy enforces here". MUST equal
|
|
11
|
+
* `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
|
|
12
|
+
* drifted). Re-exported as `VERSION` from the package index.
|
|
13
|
+
*/
|
|
14
|
+
declare const VERSION = "1.11.0";
|
|
15
|
+
//#endregion
|
|
16
|
+
export { VERSION as t };
|
|
17
|
+
//# sourceMappingURL=middleware-core-DycsbHUd.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-core-DycsbHUd.d.mts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;;;;cA8Qa"}
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-CPP1RV0f.mjs";
|
|
2
|
+
import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.mjs";
|
|
3
|
+
import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
|
|
4
|
+
import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
|
|
5
|
+
//#region src/middleware-edge.d.ts
|
|
6
|
+
export declare function withCheckpoint(config: CheckpointEdgeConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
|
|
7
|
+
/**
|
|
8
|
+
* A project has a Cedar policy, but this Edge middleware has no Cedar module to
|
|
9
|
+
* evaluate it with.
|
|
10
|
+
*/
|
|
11
|
+
export declare class CedarWasmModuleMissingError extends Error {
|
|
12
|
+
constructor(projectId: string);
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { type CheckpointConfig, type CheckpointEdgeConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, getCheckpointPostureOutcome, initEngineEdge, initPolicyEvaluatorEdge };
|
|
16
|
+
//# sourceMappingURL=middleware-edge.d.mts.map
|
|
@@ -0,0 +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,14 +1,16 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
import { n as CheckpointEdgeConfig, t as CheckpointConfig } from "./config-DVgOFxJs.js";
|
|
2
|
+
import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.js";
|
|
3
|
+
import { initEngineEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
|
|
4
|
+
import { initPolicyEvaluatorEdge } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
|
|
5
|
+
//#region src/middleware-edge.d.ts
|
|
6
|
+
export declare function withCheckpoint(config: CheckpointEdgeConfig): (req: import("next/server").NextRequest, event?: Pick<import("next/server").NextFetchEvent, "waitUntil">) => Promise<import("next/server").NextResponse>;
|
|
7
|
+
/**
|
|
8
|
+
* A project has a Cedar policy, but this Edge middleware has no Cedar module to
|
|
9
|
+
* evaluate it with.
|
|
10
|
+
*/
|
|
11
|
+
export declare class CedarWasmModuleMissingError extends Error {
|
|
12
|
+
constructor(projectId: string);
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { type CheckpointConfig, type CheckpointEdgeConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, getCheckpointPostureOutcome, initEngineEdge, initPolicyEvaluatorEdge };
|
|
16
|
+
//# sourceMappingURL=middleware-edge.d.ts.map
|
|
@@ -0,0 +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"}
|