@kya-os/checkpoint-nextjs 1.7.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/EDGE_RUNTIME_WASM_SETUP.md +11 -11
  3. package/README.md +144 -251
  4. package/bin/setup-edge-wasm.js +9 -1
  5. package/dist/adapt.d.mts +6 -34
  6. package/dist/adapt.d.mts.map +1 -0
  7. package/dist/adapt.d.ts +6 -34
  8. package/dist/adapt.d.ts.map +1 -0
  9. package/dist/adapt.js +79 -49
  10. package/dist/adapt.mjs +78 -46
  11. package/dist/adapt.mjs.map +1 -0
  12. package/dist/api-client.d.mts +150 -150
  13. package/dist/api-client.d.mts.map +1 -0
  14. package/dist/api-client.d.ts +150 -150
  15. package/dist/api-client.d.ts.map +1 -0
  16. package/dist/api-client.js +218 -204
  17. package/dist/api-client.mjs +217 -201
  18. package/dist/api-client.mjs.map +1 -0
  19. package/dist/api-middleware-CDSh3TSE.js +379 -0
  20. package/dist/api-middleware-CMDRoQik.mjs +357 -0
  21. package/dist/api-middleware-CMDRoQik.mjs.map +1 -0
  22. package/dist/api-middleware.d.mts +117 -129
  23. package/dist/api-middleware.d.mts.map +1 -0
  24. package/dist/api-middleware.d.ts +117 -129
  25. package/dist/api-middleware.d.ts.map +1 -0
  26. package/dist/api-middleware.js +8 -540
  27. package/dist/api-middleware.mjs +3 -534
  28. package/dist/composed-policy-BCaNiVHv.d.mts +98 -0
  29. package/dist/composed-policy-BCaNiVHv.d.mts.map +1 -0
  30. package/dist/composed-policy-zzJYNFTb.d.ts +98 -0
  31. package/dist/composed-policy-zzJYNFTb.d.ts.map +1 -0
  32. package/dist/composed-policy.d.mts +2 -115
  33. package/dist/composed-policy.d.ts +2 -115
  34. package/dist/composed-policy.js +122 -88
  35. package/dist/composed-policy.mjs +121 -85
  36. package/dist/composed-policy.mjs.map +1 -0
  37. package/dist/config-CbAg2mze.d.ts +255 -0
  38. package/dist/config-CbAg2mze.d.ts.map +1 -0
  39. package/dist/config-Doe0Tn53.d.mts +255 -0
  40. package/dist/config-Doe0Tn53.d.mts.map +1 -0
  41. package/dist/create-middleware.d.mts +7 -18
  42. package/dist/create-middleware.d.mts.map +1 -0
  43. package/dist/create-middleware.d.ts +7 -18
  44. package/dist/create-middleware.d.ts.map +1 -0
  45. package/dist/create-middleware.js +36 -31
  46. package/dist/create-middleware.mjs +35 -28
  47. package/dist/create-middleware.mjs.map +1 -0
  48. package/dist/edge/index.d.mts +64 -86
  49. package/dist/edge/index.d.mts.map +1 -0
  50. package/dist/edge/index.d.ts +64 -86
  51. package/dist/edge/index.d.ts.map +1 -0
  52. package/dist/edge/index.js +349 -275
  53. package/dist/edge/index.mjs +348 -272
  54. package/dist/edge/index.mjs.map +1 -0
  55. package/dist/edge-runtime-loader.d.mts +37 -63
  56. package/dist/edge-runtime-loader.d.mts.map +1 -0
  57. package/dist/edge-runtime-loader.d.ts +37 -63
  58. package/dist/edge-runtime-loader.d.ts.map +1 -0
  59. package/dist/edge-runtime-loader.js +268 -225
  60. package/dist/edge-runtime-loader.mjs +267 -222
  61. package/dist/edge-runtime-loader.mjs.map +1 -0
  62. package/dist/edge-wasm-middleware.d.mts +27 -46
  63. package/dist/edge-wasm-middleware.d.mts.map +1 -0
  64. package/dist/edge-wasm-middleware.d.ts +27 -46
  65. package/dist/edge-wasm-middleware.d.ts.map +1 -0
  66. package/dist/edge-wasm-middleware.js +26 -15
  67. package/dist/edge-wasm-middleware.mjs +25 -12
  68. package/dist/edge-wasm-middleware.mjs.map +1 -0
  69. package/dist/index.d.mts +10 -17
  70. package/dist/index.d.ts +10 -17
  71. package/dist/index.js +55 -1224
  72. package/dist/index.mjs +16 -1193
  73. package/dist/index.mjs.map +1 -0
  74. package/dist/middleware-bundler.d.mts +7 -0
  75. package/dist/middleware-bundler.d.mts.map +1 -0
  76. package/dist/middleware-bundler.d.ts +7 -0
  77. package/dist/middleware-bundler.d.ts.map +1 -0
  78. package/dist/middleware-bundler.js +16 -0
  79. package/dist/middleware-bundler.mjs +16 -0
  80. package/dist/middleware-bundler.mjs.map +1 -0
  81. package/dist/middleware-core-BYQP9FND.mjs +165 -0
  82. package/dist/middleware-core-BYQP9FND.mjs.map +1 -0
  83. package/dist/middleware-core-D6TijE6P.js +175 -0
  84. package/dist/middleware-edge.d.mts +8 -50
  85. package/dist/middleware-edge.d.mts.map +1 -0
  86. package/dist/middleware-edge.d.ts +8 -50
  87. package/dist/middleware-edge.d.ts.map +1 -0
  88. package/dist/middleware-edge.js +41 -307
  89. package/dist/middleware-edge.mjs +39 -299
  90. package/dist/middleware-edge.mjs.map +1 -0
  91. package/dist/middleware-node-CE4GevYs.d.ts +20 -0
  92. package/dist/middleware-node-CE4GevYs.d.ts.map +1 -0
  93. package/dist/middleware-node-DtyOuPta.d.mts +20 -0
  94. package/dist/middleware-node-DtyOuPta.d.mts.map +1 -0
  95. package/dist/middleware-node-context-BqPbf-fI.mjs +34 -0
  96. package/dist/middleware-node-context-BqPbf-fI.mjs.map +1 -0
  97. package/dist/middleware-node-context-rgnc7UNR.js +38 -0
  98. package/dist/middleware-node.d.mts +3 -63
  99. package/dist/middleware-node.d.ts +3 -63
  100. package/dist/middleware-node.js +13 -308
  101. package/dist/middleware-node.mjs +12 -301
  102. package/dist/middleware-node.mjs.map +1 -0
  103. package/dist/middleware.d.mts +8 -28
  104. package/dist/middleware.d.mts.map +1 -0
  105. package/dist/middleware.d.ts +8 -28
  106. package/dist/middleware.d.ts.map +1 -0
  107. package/dist/middleware.js +43 -9
  108. package/dist/middleware.mjs +42 -6
  109. package/dist/middleware.mjs.map +1 -0
  110. package/dist/nodejs-wasm-loader.d.mts +8 -7
  111. package/dist/nodejs-wasm-loader.d.mts.map +1 -0
  112. package/dist/nodejs-wasm-loader.d.ts +8 -7
  113. package/dist/nodejs-wasm-loader.d.ts.map +1 -0
  114. package/dist/nodejs-wasm-loader.js +53 -19
  115. package/dist/nodejs-wasm-loader.mjs +52 -16
  116. package/dist/nodejs-wasm-loader.mjs.map +1 -0
  117. package/dist/policy.d.mts +86 -110
  118. package/dist/policy.d.mts.map +1 -0
  119. package/dist/policy.d.ts +86 -110
  120. package/dist/policy.d.ts.map +1 -0
  121. package/dist/policy.js +203 -160
  122. package/dist/policy.mjs +183 -147
  123. package/dist/policy.mjs.map +1 -0
  124. package/dist/session-tracker.d.mts +42 -47
  125. package/dist/session-tracker.d.mts.map +1 -0
  126. package/dist/session-tracker.d.ts +42 -47
  127. package/dist/session-tracker.d.ts.map +1 -0
  128. package/dist/session-tracker.js +141 -163
  129. package/dist/session-tracker.mjs +140 -160
  130. package/dist/session-tracker.mjs.map +1 -0
  131. package/dist/translate.d.mts +18 -30
  132. package/dist/translate.d.mts.map +1 -0
  133. package/dist/translate.d.ts +18 -30
  134. package/dist/translate.d.ts.map +1 -0
  135. package/dist/translate.js +70 -34
  136. package/dist/translate.mjs +70 -32
  137. package/dist/translate.mjs.map +1 -0
  138. package/dist/types-C0SkqLMM.d.mts +102 -0
  139. package/dist/types-C0SkqLMM.d.mts.map +1 -0
  140. package/dist/types-C7DNSCTO.d.ts +102 -0
  141. package/dist/types-C7DNSCTO.d.ts.map +1 -0
  142. package/dist/utils-Cj4XNhIY.mjs +35 -0
  143. package/dist/utils-Cj4XNhIY.mjs.map +1 -0
  144. package/dist/utils-DAisnYnI.js +45 -0
  145. package/dist/wasm-setup.d.mts +6 -5
  146. package/dist/wasm-setup.d.mts.map +1 -0
  147. package/dist/wasm-setup.d.ts +6 -5
  148. package/dist/wasm-setup.d.ts.map +1 -0
  149. package/dist/wasm-setup.js +82 -113
  150. package/dist/wasm-setup.mjs +85 -108
  151. package/dist/wasm-setup.mjs.map +1 -0
  152. package/package.json +22 -15
  153. package/dist/config-DAwIA4DB.d.mts +0 -214
  154. package/dist/config-DyU4l5er.d.ts +0 -214
  155. package/dist/types-D9RQvPNy.d.mts +0 -105
  156. package/dist/types-D9RQvPNy.d.ts +0 -105
@@ -1,96 +1,132 @@
1
- import { makeComposedPolicyCache, evaluateComposedPolicy, verifyResultToAuthorizeInput } from '@kya-os/checkpoint-wasm-runtime/composed-policy';
2
- import { requestCarriesDelegationProof } from '@kya-os/checkpoint-shared';
1
+ import { evaluateComposedPolicy, isCredentialVerificationBlock, makeComposedPolicyCache, verifyResultToAuthorizeInput } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
2
+ import { requestCarriesDelegationProof } from "@kya-os/checkpoint-shared";
3
3
 
4
- // src/composed-policy.ts
5
- var DEFAULT_DASHBOARD_URL = "https://kya.vouched.id";
6
- var NOOP_LOGGER = {
7
- shadowDivergence: () => {
8
- },
9
- evaluationError: () => {
10
- }
4
+ //#region src/composed-policy.ts
5
+ /**
6
+ * Composed-policy (kya-os-engine) wiring for the Next.js middleware.
7
+ *
8
+ * A THIN layer on top of the shared core
9
+ * (`@kya-os/checkpoint-wasm-runtime/composed-policy`): the core owns all the
10
+ * logic (empty-Cedar deny-all guard, compile-once LRU cache, act-gate,
11
+ * divergence, and the `verifyResultToAuthorizeInput` parity projection), so this
12
+ * module only fetches the project's `PolicyConfig`, drives the core once per
13
+ * request, maps the tagged outcome to a decision-swap signal, and logs
14
+ * (debug-gated). Runtime-neutral — the caller injects the compiler:
15
+ * - Node: `(language, source) => createPolicyEvaluator(source)` (`./policy`)
16
+ * - Edge: `(language, source) => evaluatePolicy(language, source)` (`./policy-edge`)
17
+ *
18
+ * This is the SDK sibling of `@kya-os/checkpoint-express`'s composed-policy
19
+ * wiring; both consume the same core so the DNS Gateway, Express, and Next.js
20
+ * produce the same decision for the same composed Cedar bundle.
21
+ */
22
+ /** Dashboard the composed-policy fetch defaults to when no base URL is set. */
23
+ const DEFAULT_DASHBOARD_URL = "https://kya.vouched.id";
24
+ const NOOP_LOGGER = {
25
+ shadowDivergence: () => {},
26
+ evaluationError: () => {}
11
27
  };
12
28
  function makeComposedPolicyContext(opts) {
13
- const { projectId, fetcher } = opts;
14
- const cache = makeComposedPolicyCache({ compile: opts.compile, cacheMax: opts.cacheMax });
15
- const logger = opts.logger ?? NOOP_LOGGER;
16
- return {
17
- async apply(result, path) {
18
- const structured = { decision: result.decision, acted: false };
19
- const policy = await fetcher.getPolicy(projectId);
20
- const outcome = await evaluateComposedPolicy({
21
- cache,
22
- projectId,
23
- flags: {
24
- policyLanguage: policy.policyLanguage,
25
- policySourceText: policy.policySourceText,
26
- engineEnforcementEnabled: policy.engineEnforcementEnabled,
27
- enabled: policy.enabled
28
- },
29
- authorizeInput: verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),
30
- baselineDecisionKind: result.decision.kind
31
- });
32
- if ((outcome.status === "acting" || outcome.status === "shadow") && outcome.diverged) {
33
- logger.shadowDivergence({
34
- projectId,
35
- path,
36
- engineDecision: outcome.engineDecision.kind,
37
- structuredDecision: result.decision.kind,
38
- detectionClass: result.detectionDetail.detectionClass.type,
39
- verificationMethod: result.detectionDetail.verificationMethod,
40
- confidence: result.detectionDetail.confidence,
41
- agentName: result.detectionDetail.detectedAgent?.name
42
- });
43
- }
44
- if (outcome.status === "error") {
45
- logger.evaluationError(projectId, outcome.error);
46
- return structured;
47
- }
48
- if (outcome.status === "acting") {
49
- return {
50
- decision: outcome.engineDecision,
51
- acted: true,
52
- // Echo the SSOT revision pin with the decision it produced (#3246
53
- // PR5). Conditional spread: absent upstream stays absent here.
54
- ...policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}
55
- };
56
- }
57
- return structured;
58
- },
59
- async trustedDelegationRoots() {
60
- const policy = await fetcher.getPolicy(projectId);
61
- return policy.trustedDelegationRoots ?? [];
62
- }
63
- };
29
+ const { projectId, fetcher } = opts;
30
+ const cache = makeComposedPolicyCache({
31
+ compile: opts.compile,
32
+ cacheMax: opts.cacheMax
33
+ });
34
+ const logger = opts.logger ?? NOOP_LOGGER;
35
+ return {
36
+ async apply(result, path) {
37
+ const structured = {
38
+ decision: result.decision,
39
+ acted: false
40
+ };
41
+ if (isCredentialVerificationBlock(result.decision)) return structured;
42
+ const policy = await fetcher.getPolicy(projectId);
43
+ const outcome = await evaluateComposedPolicy({
44
+ cache,
45
+ projectId,
46
+ flags: {
47
+ policyLanguage: policy.policyLanguage,
48
+ policySourceText: policy.policySourceText,
49
+ engineEnforcementEnabled: policy.engineEnforcementEnabled,
50
+ enabled: policy.enabled
51
+ },
52
+ authorizeInput: verifyResultToAuthorizeInput(result, {
53
+ tenantId: projectId,
54
+ path
55
+ }),
56
+ baselineDecisionKind: result.decision.kind
57
+ });
58
+ if ((outcome.status === "acting" || outcome.status === "shadow") && outcome.diverged) logger.shadowDivergence({
59
+ projectId,
60
+ path,
61
+ engineDecision: outcome.engineDecision.kind,
62
+ structuredDecision: result.decision.kind,
63
+ detectionClass: result.detectionDetail.detectionClass.type,
64
+ verificationMethod: result.detectionDetail.verificationMethod,
65
+ confidence: result.detectionDetail.confidence,
66
+ agentName: result.detectionDetail.detectedAgent?.name
67
+ });
68
+ if (outcome.status === "error") {
69
+ logger.evaluationError(projectId, outcome.error);
70
+ return structured;
71
+ }
72
+ if (outcome.status === "acting") return {
73
+ decision: outcome.engineDecision,
74
+ acted: true,
75
+ ...policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}
76
+ };
77
+ return structured;
78
+ },
79
+ async trustedDelegationRoots() {
80
+ return (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
81
+ }
82
+ };
64
83
  }
84
+ /**
85
+ * Resolve the org trusted-delegation roots to inject into the engine for THIS
86
+ * request (P2 / DR-1). Returns `undefined` — leaving `VerifyRequestOpts`
87
+ * byte-identical to pre-P2 — unless (a) a resolver is configured and (b) the
88
+ * request actually carries a delegation-proof header (so the human /
89
+ * no-delegation hot path never pays the early policy fetch). Shared by the Node
90
+ * and Edge middleware entries.
91
+ */
65
92
  async function resolveTrustedDelegationRootsForRequest(resolver, headers) {
66
- if (!resolver) return void 0;
67
- if (!requestCarriesDelegationProof(headers)) return void 0;
68
- const roots = await resolver();
69
- return roots.length > 0 ? roots : void 0;
93
+ if (!resolver) return void 0;
94
+ if (!requestCarriesDelegationProof(headers)) return void 0;
95
+ const roots = await resolver();
96
+ return roots.length > 0 ? roots : void 0;
70
97
  }
98
+ /**
99
+ * The per-request seam shared by both middleware entries. Evaluates the composed
100
+ * policy and swaps `result.decision` IN PLACE when the engine acts — so the
101
+ * swap happens BEFORE the detection reporter fires and before
102
+ * `renderDecisionAsResponse`, exactly like the Express runtime (the reporter
103
+ * records the enforced decision). Fail-OPEN: any fault keeps the structured
104
+ * decision; a policy fault never breaks the response.
105
+ */
71
106
  async function applyComposedPolicy(context, result, path) {
72
- if (!context) return;
73
- try {
74
- const outcome = await context.apply(result, path);
75
- if (outcome.acted) {
76
- result.decision = outcome.decision;
77
- if (outcome.composedBlobHash) {
78
- result.composedBlobHash = outcome.composedBlobHash;
79
- }
80
- }
81
- } catch {
82
- }
107
+ if (!context) return;
108
+ try {
109
+ const outcome = await context.apply(result, path);
110
+ if (outcome.acted) {
111
+ result.decision = outcome.decision;
112
+ if (outcome.composedBlobHash) result.composedBlobHash = outcome.composedBlobHash;
113
+ }
114
+ } catch {}
83
115
  }
84
- var consoleComposedPolicyLogger = {
85
- shadowDivergence(info) {
86
- console.warn("[checkpoint/composed-policy] shadow-divergence", info);
87
- },
88
- evaluationError(projectId, error) {
89
- console.error(
90
- `[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`,
91
- error
92
- );
93
- }
116
+ /**
117
+ * Debug logger mirroring the worker's `console.warn`/`console.error` shadow +
118
+ * fail-open telemetry. Wired by `withCheckpoint` only when `config.debug` is
119
+ * set, so the default SDK posture stays silent.
120
+ */
121
+ const consoleComposedPolicyLogger = {
122
+ shadowDivergence(info) {
123
+ console.warn("[checkpoint/composed-policy] shadow-divergence", info);
124
+ },
125
+ evaluationError(projectId, error) {
126
+ console.error(`[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`, error);
127
+ }
94
128
  };
95
129
 
130
+ //#endregion
96
131
  export { DEFAULT_DASHBOARD_URL, applyComposedPolicy, consoleComposedPolicyLogger, makeComposedPolicyContext, resolveTrustedDelegationRootsForRequest };
132
+ //# sourceMappingURL=composed-policy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composed-policy.mjs","names":[],"sources":["../src/composed-policy.ts"],"sourcesContent":["/**\n * Composed-policy (kya-os-engine) wiring for the Next.js middleware.\n *\n * A THIN layer on top of the shared core\n * (`@kya-os/checkpoint-wasm-runtime/composed-policy`): the core owns all the\n * logic (empty-Cedar deny-all guard, compile-once LRU cache, act-gate,\n * divergence, and the `verifyResultToAuthorizeInput` parity projection), so this\n * module only fetches the project's `PolicyConfig`, drives the core once per\n * request, maps the tagged outcome to a decision-swap signal, and logs\n * (debug-gated). Runtime-neutral — the caller injects the compiler:\n * - Node: `(language, source) => createPolicyEvaluator(source)` (`./policy`)\n * - Edge: `(language, source) => evaluatePolicy(language, source)` (`./policy-edge`)\n *\n * This is the SDK sibling of `@kya-os/checkpoint-express`'s composed-policy\n * wiring; both consume the same core so the DNS Gateway, Express, and Next.js\n * produce the same decision for the same composed Cedar bundle.\n */\n\nimport {\n evaluateComposedPolicy,\n isCredentialVerificationBlock,\n makeComposedPolicyCache,\n verifyResultToAuthorizeInput,\n type ComposedPolicyCompile,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\nimport type { Decision, VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\nimport { requestCarriesDelegationProof, type PolicyFetcher } from '@kya-os/checkpoint-shared';\n\n/** Dashboard the composed-policy fetch defaults to when no base URL is set. */\nexport const DEFAULT_DASHBOARD_URL = 'https://kya.vouched.id';\n\n/**\n * Telemetry sink. The shadow-divergence signal is the go/no-go instrument for\n * flipping a project to ENFORCE. Defaults to a no-op so the SDK never logs\n * unprompted — `withCheckpoint({ debug: true })` wires the console logger.\n */\nexport interface ComposedPolicyLogger {\n shadowDivergence(info: ShadowDivergenceInfo): void;\n evaluationError(projectId: string, error: unknown): void;\n}\n\nexport interface ShadowDivergenceInfo {\n projectId: string;\n path?: string;\n engineDecision: Decision['kind'];\n structuredDecision: Decision['kind'];\n detectionClass: string;\n verificationMethod?: string;\n confidence: number;\n agentName?: string;\n}\n\nconst NOOP_LOGGER: ComposedPolicyLogger = {\n shadowDivergence: () => {},\n evaluationError: () => {},\n};\n\n/** Result of one composed-policy evaluation: the decision to enforce + whether it replaced the baseline. */\nexport interface ComposedPolicyApplyResult {\n decision: Decision;\n acted: boolean;\n /**\n * SSOT-served revision pin (sha256 of the evaluated bundle, byte-identical\n * to `policy_revisions.composed_blob_hash`) — set ONLY when `acted`, echoed\n * from `PolicyConfig.policySourceHash` (#3246 PR5). Absent on structured\n * decisions and when the dashboard predates the field.\n */\n composedBlobHash?: string;\n}\n\nexport interface ComposedPolicyContext {\n /**\n * Evaluate the project's composed policy for one request. Reads\n * `result.decision` as the structured baseline for the divergence comparison;\n * the caller applies `acted ? decision` afterwards. Never throws.\n */\n apply(result: VerifyResult, path: string | undefined): Promise<ComposedPolicyApplyResult>;\n /**\n * Resolve the org's trusted Layer-2 delegation root DIDs from the project's\n * policy payload (P2 / DR-1). The middleware forwards these into the engine's\n * `ContextSpec.trustedDelegationRoots` on delegation requests. Optional so an\n * injected `composedPolicyEnforcer` (advanced/testing) need not implement it —\n * absence ⇒ no roots ⇒ the engine's open default. Never throws (a fetch fault\n * resolves to `[]`).\n */\n trustedDelegationRoots?(): Promise<string[]>;\n}\n\nexport interface MakeComposedPolicyContextOptions {\n projectId: string;\n /** Fetches the project's `PolicyConfig` (carries the composed-policy fields). */\n fetcher: PolicyFetcher;\n /** Target compiler — Node `createPolicyEvaluator`-backed or edge `evaluatePolicy`. */\n compile: ComposedPolicyCompile;\n logger?: ComposedPolicyLogger;\n cacheMax?: number;\n}\n\nexport function makeComposedPolicyContext(\n opts: MakeComposedPolicyContextOptions\n): ComposedPolicyContext {\n const { projectId, fetcher } = opts;\n const cache = makeComposedPolicyCache({ compile: opts.compile, cacheMax: opts.cacheMax });\n const logger = opts.logger ?? NOOP_LOGGER;\n\n return {\n async apply(result, path): Promise<ComposedPolicyApplyResult> {\n const structured: ComposedPolicyApplyResult = { decision: result.decision, acted: false };\n if (isCredentialVerificationBlock(result.decision)) return structured;\n\n // PolicyFetcher.getPolicy is itself fail-open (returns DEFAULT_POLICY on a\n // fetch/parse fault → no composed fields → the core's no-policy branch),\n // so this resolves to the structured decision on a dashboard outage.\n const policy = await fetcher.getPolicy(projectId);\n\n const outcome = await evaluateComposedPolicy({\n cache,\n projectId,\n flags: {\n policyLanguage: policy.policyLanguage,\n policySourceText: policy.policySourceText,\n engineEnforcementEnabled: policy.engineEnforcementEnabled,\n enabled: policy.enabled,\n },\n authorizeInput: verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),\n baselineDecisionKind: result.decision.kind,\n });\n\n // Divergence telemetry (acting OR shadow): the engine decided differently\n // than the structured baseline. `result.decision` is still the baseline\n // here — the caller swaps it only after this returns.\n if ((outcome.status === 'acting' || outcome.status === 'shadow') && outcome.diverged) {\n logger.shadowDivergence({\n projectId,\n path,\n engineDecision: outcome.engineDecision.kind,\n structuredDecision: result.decision.kind,\n detectionClass: result.detectionDetail.detectionClass.type,\n verificationMethod: result.detectionDetail.verificationMethod,\n confidence: result.detectionDetail.confidence,\n agentName: result.detectionDetail.detectedAgent?.name,\n });\n }\n\n if (outcome.status === 'error') {\n logger.evaluationError(projectId, outcome.error);\n return structured;\n }\n if (outcome.status === 'acting') {\n return {\n decision: outcome.engineDecision,\n acted: true,\n // Echo the SSOT revision pin with the decision it produced (#3246\n // PR5). Conditional spread: absent upstream stays absent here.\n ...(policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}),\n };\n }\n // 'shadow' | 'no-policy' → structured decision stands.\n return structured;\n },\n\n async trustedDelegationRoots(): Promise<string[]> {\n // Reuse the SAME (cached) PolicyFetcher the `apply` path uses, so the\n // early root-resolution and the later composed-policy fetch coalesce into\n // one network call. `getPolicy` is fail-open (DEFAULT_POLICY → no field),\n // so a dashboard outage resolves to `[]` (root pinning disabled).\n const policy = await fetcher.getPolicy(projectId);\n return policy.trustedDelegationRoots ?? [];\n },\n };\n}\n\n/**\n * Resolves the org's trusted delegation roots (empty when none). Built per\n * middleware factory from whatever source can supply them — the composed\n * context's accessor, or (when no context exists, e.g. Edge without\n * `cedarWasmModule`) a `projectId`-only policy fetch.\n */\nexport type TrustedDelegationRootsResolver = () => Promise<string[]>;\n\n/**\n * Resolve the org trusted-delegation roots to inject into the engine for THIS\n * request (P2 / DR-1). Returns `undefined` — leaving `VerifyRequestOpts`\n * byte-identical to pre-P2 — unless (a) a resolver is configured and (b) the\n * request actually carries a delegation-proof header (so the human /\n * no-delegation hot path never pays the early policy fetch). Shared by the Node\n * and Edge middleware entries.\n */\nexport async function resolveTrustedDelegationRootsForRequest(\n resolver: TrustedDelegationRootsResolver | null,\n headers: Headers\n): Promise<string[] | undefined> {\n if (!resolver) return undefined;\n if (!requestCarriesDelegationProof(headers)) return undefined;\n const roots = await resolver();\n return roots.length > 0 ? roots : undefined;\n}\n\n/**\n * The per-request seam shared by both middleware entries. Evaluates the composed\n * policy and swaps `result.decision` IN PLACE when the engine acts — so the\n * swap happens BEFORE the detection reporter fires and before\n * `renderDecisionAsResponse`, exactly like the Express runtime (the reporter\n * records the enforced decision). Fail-OPEN: any fault keeps the structured\n * decision; a policy fault never breaks the response.\n */\nexport async function applyComposedPolicy(\n context: ComposedPolicyContext | null,\n result: VerifyResult,\n path: string | undefined\n): Promise<void> {\n if (!context) return;\n try {\n const outcome = await context.apply(result, path);\n if (outcome.acted) {\n result.decision = outcome.decision;\n if (outcome.composedBlobHash) {\n result.composedBlobHash = outcome.composedBlobHash;\n }\n }\n } catch {\n // Defense-in-depth: the context catches engine/compile faults internally\n // (the core never throws), but an unexpected throw must still degrade to the\n // structured decision rather than reach the middleware's response path.\n }\n}\n\n/**\n * Debug logger mirroring the worker's `console.warn`/`console.error` shadow +\n * fail-open telemetry. Wired by `withCheckpoint` only when `config.debug` is\n * set, so the default SDK posture stays silent.\n */\nexport const consoleComposedPolicyLogger: ComposedPolicyLogger = {\n shadowDivergence(info) {\n // eslint-disable-next-line no-console -- debug-gated telemetry (see withCheckpoint)\n console.warn('[checkpoint/composed-policy] shadow-divergence', info);\n },\n evaluationError(projectId, error) {\n // eslint-disable-next-line no-console -- debug-gated telemetry (see withCheckpoint)\n console.error(\n `[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`,\n error\n );\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,wBAAwB;AAuBrC,MAAM,cAAoC;CACxC,wBAAwB,CAAC;CACzB,uBAAuB,CAAC;AAC1B;AA2CA,SAAgB,0BACd,MACuB;CACvB,MAAM,EAAE,WAAW,YAAY;CAC/B,MAAM,QAAQ,wBAAwB;EAAE,SAAS,KAAK;EAAS,UAAU,KAAK;CAAS,CAAC;CACxF,MAAM,SAAS,KAAK,UAAU;CAE9B,OAAO;EACL,MAAM,MAAM,QAAQ,MAA0C;GAC5D,MAAM,aAAwC;IAAE,UAAU,OAAO;IAAU,OAAO;GAAM;GACxF,IAAI,8BAA8B,OAAO,QAAQ,GAAG,OAAO;GAK3D,MAAM,SAAS,MAAM,QAAQ,UAAU,SAAS;GAEhD,MAAM,UAAU,MAAM,uBAAuB;IAC3C;IACA;IACA,OAAO;KACL,gBAAgB,OAAO;KACvB,kBAAkB,OAAO;KACzB,0BAA0B,OAAO;KACjC,SAAS,OAAO;IAClB;IACA,gBAAgB,6BAA6B,QAAQ;KAAE,UAAU;KAAW;IAAK,CAAC;IAClF,sBAAsB,OAAO,SAAS;GACxC,CAAC;GAKD,KAAK,QAAQ,WAAW,YAAY,QAAQ,WAAW,aAAa,QAAQ,UAC1E,OAAO,iBAAiB;IACtB;IACA;IACA,gBAAgB,QAAQ,eAAe;IACvC,oBAAoB,OAAO,SAAS;IACpC,gBAAgB,OAAO,gBAAgB,eAAe;IACtD,oBAAoB,OAAO,gBAAgB;IAC3C,YAAY,OAAO,gBAAgB;IACnC,WAAW,OAAO,gBAAgB,eAAe;GACnD,CAAC;GAGH,IAAI,QAAQ,WAAW,SAAS;IAC9B,OAAO,gBAAgB,WAAW,QAAQ,KAAK;IAC/C,OAAO;GACT;GACA,IAAI,QAAQ,WAAW,UACrB,OAAO;IACL,UAAU,QAAQ;IAClB,OAAO;IAGP,GAAI,OAAO,mBAAmB,EAAE,kBAAkB,OAAO,iBAAiB,IAAI,CAAC;GACjF;GAGF,OAAO;EACT;EAEA,MAAM,yBAA4C;GAMhD,QAAO,MADc,QAAQ,UAAU,SAAS,EACnC,CAAC,0BAA0B,CAAC;EAC3C;CACF;AACF;;;;;;;;;AAkBA,eAAsB,wCACpB,UACA,SAC+B;CAC/B,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,CAAC,8BAA8B,OAAO,GAAG,OAAO;CACpD,MAAM,QAAQ,MAAM,SAAS;CAC7B,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;;;AAUA,eAAsB,oBACpB,SACA,QACA,MACe;CACf,IAAI,CAAC,SAAS;CACd,IAAI;EACF,MAAM,UAAU,MAAM,QAAQ,MAAM,QAAQ,IAAI;EAChD,IAAI,QAAQ,OAAO;GACjB,OAAO,WAAW,QAAQ;GAC1B,IAAI,QAAQ,kBACV,OAAO,mBAAmB,QAAQ;EAEtC;CACF,QAAQ,CAIR;AACF;;;;;;AAOA,MAAa,8BAAoD;CAC/D,iBAAiB,MAAM;EAErB,QAAQ,KAAK,kDAAkD,IAAI;CACrE;CACA,gBAAgB,WAAW,OAAO;EAEhC,QAAQ,MACN,sDAAsD,UAAU,+BAChE,KACF;CACF;AACF"}
@@ -0,0 +1,255 @@
1
+ import { n as ComposedPolicyContext } from "./composed-policy-zzJYNFTb.js";
2
+ import { NextRequest } from "next/server";
3
+ import { ChallengeContextFailureEvent, ChallengeEnvelopeMode, ChallengeWireInput, ClientIpTrustPolicy } from "@kya-os/checkpoint-shared";
4
+ import { EnforcementMode, EngineConfig, VerifyResult } from "@kya-os/checkpoint-wasm-runtime/engine";
5
+ import { BrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
6
+ import { DidResolverAdapter, PolicyEvaluatorAdapter, ReputationOracleAdapter, StatusListCacheAdapter } from "@kya-os/checkpoint-wasm-runtime/adapters";
7
+ //#region src/config.d.ts
8
+ /**
9
+ * Configuration for `withCheckpoint`.
10
+ *
11
+ * The new minimal shape Phase D's middleware needs. Legacy
12
+ * `AgentShieldMiddlewareConfig` (from `./api-middleware`) remains
13
+ * exported during the deprecation window — see D.4 cutover.
14
+ */
15
+ interface CheckpointConfig {
16
+ /**
17
+ * Selects the infrastructure allowed to vouch for client IP headers.
18
+ * Defaults to direct peer/framework resolution; set `platform: 'vercel'`
19
+ * for Vercel-hosted requests or `platform: 'trusted-proxy'` with an
20
+ * explicit hop count for a configured proxy chain.
21
+ */
22
+ clientIpPolicy?: ClientIpTrustPolicy;
23
+ /**
24
+ * Tenant identifier — typically the customer's dashboard hostname
25
+ * (e.g. `acme.checkpoint.example`). The PolicyEvaluator uses this
26
+ * to look up tenant policy from the dashboard.
27
+ */
28
+ tenantHost: string;
29
+ /** Exact org DID used to verify the consent credential's audience. */
30
+ resourceOrgDid?: string;
31
+ /** Explicit trusted delegation issuers; otherwise resolved from project policy. */
32
+ trustedDelegationRoots?: string[];
33
+ /**
34
+ * `'enforce'` (default) blocks; `'observe'` passes everything
35
+ * through with `X-Checkpoint-Would-Have-Been` headers. Per Phase 0.2.
36
+ *
37
+ * @default 'enforce'
38
+ */
39
+ enforcementMode?: EnforcementMode;
40
+ /**
41
+ * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).
42
+ * `negotiated` serves a body-readable HTTP 200 step-up response to
43
+ * cooperative agents (fetchers that drop 4xx/5xx bodies), keeping the spec
44
+ * 401/422 for everyone else. Defaults to `negotiated` (#3530). A cooperative-UX
45
+ * bridge, NOT an access control.
46
+ *
47
+ * @default 'negotiated'
48
+ */
49
+ delegationChallengeMode?: ChallengeEnvelopeMode;
50
+ /**
51
+ * Resolve a policy `Challenge` into complete registered wire context.
52
+ * The callback performs any Authorization-Host registration asynchronously;
53
+ * the synchronous engine renderer never fabricates a sid, consent URI, or proof.
54
+ */
55
+ resolveDelegationChallenge?: (context: {
56
+ result: VerifyResult;
57
+ request: NextRequest;
58
+ }) => ChallengeWireInput | undefined | Promise<ChallengeWireInput | undefined>;
59
+ /**
60
+ * Registration/resolution budget in milliseconds.
61
+ *
62
+ * @default 3000
63
+ */
64
+ delegationChallengeTimeoutMs?: number;
65
+ /** Sanitized registration failure hook for metrics and operator warnings. */
66
+ onDelegationChallengeFailure?: (event: ChallengeContextFailureEvent) => void;
67
+ /**
68
+ * Argus reputation oracle base URL. Omit to use the trust-by-default
69
+ * baseline (reputation defaults to 1.0; orchestrator logs a one-shot
70
+ * warning at first request).
71
+ */
72
+ argusUrl?: string;
73
+ /**
74
+ * Dashboard base URL for the PolicyEvaluator to fetch tenant policy
75
+ * from. Omit to use the open-by-default tenant policy.
76
+ */
77
+ dashboardUrl?: string;
78
+ /**
79
+ * Returned to the PolicyEvaluator for anonymous requests (no agent
80
+ * DID). Trust-by-default. Engine scale is `0.0` to `1.0`.
81
+ *
82
+ * @default 1.0
83
+ */
84
+ reputationBaseline?: number;
85
+ /**
86
+ * Pre-built adapter instances. Production deployments use the
87
+ * factory-built defaults from `@kya-os/checkpoint-wasm-runtime/adapters`;
88
+ * tests use stubs. The factory composes any provided overrides over
89
+ * defaults — partial overrides are supported.
90
+ */
91
+ adapters?: Partial<{
92
+ didResolver: DidResolverAdapter;
93
+ statusListCache: StatusListCacheAdapter;
94
+ reputationOracle: ReputationOracleAdapter;
95
+ policyEvaluator: PolicyEvaluatorAdapter;
96
+ }>;
97
+ /**
98
+ * Optional callback for the post-verdict path — fires after every
99
+ * verification, regardless of permit/block, with the full
100
+ * `VerifyResult`. Use for logging, dashboards, telemetry. Errors
101
+ * thrown here are swallowed so user code can't break the middleware
102
+ * response.
103
+ */
104
+ onResult?: (result: VerifyResult, req: NextRequest) => void | Promise<void>;
105
+ /**
106
+ * Accept legacy `KYA-Delegation`-header envelope form alongside the
107
+ * canonical `_meta.proof.jws` body form. Default `false`.
108
+ *
109
+ * **When to enable** — customers whose agents pre-date Envelope-1
110
+ * (#2537) and ship KYA-OS proofs as `{protected,payload,signature}`
111
+ * JSON in a `KYA-Delegation` HTTP header. Post-Envelope-1 agents
112
+ * ship compact JWS in the request body's `_meta.proof.jws` field;
113
+ * those don't need this flag.
114
+ *
115
+ * Forwarded to the orchestrator's `VerifyRequestOpts.legacyEnvelopeFallback`.
116
+ * Both transports (header + body) are honored when this is `true`;
117
+ * the orchestrator's detection order is body first, then header
118
+ * (`packages/checkpoint-wasm-runtime/src/engine/orchestrator/build-agent-request.ts`).
119
+ *
120
+ * SDK-Envelope-Plumbing-1 (#2594). Added in `@kya-os/checkpoint-nextjs@1.1.0`.
121
+ *
122
+ * @default false
123
+ */
124
+ legacyEnvelopeFallback?: boolean;
125
+ /**
126
+ * Read the request body when `content-type` is `application/json` so
127
+ * the orchestrator can extract a KYA-OS envelope from
128
+ * `_meta.proof.jws`. Default `true`.
129
+ *
130
+ * **When to disable** — streaming middlewares that can't tolerate
131
+ * the `req.clone()` memory overhead (one full-body copy is buffered
132
+ * during the read). For those, set `false` and route KYA-OS
133
+ * envelopes through the `KYA-Delegation` header transport instead
134
+ * (requires `legacyEnvelopeFallback: true`).
135
+ *
136
+ * The clone preserves `req.body` for downstream handlers — disabling
137
+ * is a performance optimization, not a correctness fix.
138
+ *
139
+ * SDK-Envelope-Plumbing-1 (#2594). Added in `@kya-os/checkpoint-nextjs@1.1.0`.
140
+ *
141
+ * @default true
142
+ */
143
+ drainJsonBody?: boolean;
144
+ /**
145
+ * Engine-default behaviour knobs forwarded to every composed
146
+ * `ContextSpec`. Defaults to `{ tier3Action: 'monitor' }` —
147
+ * customer-onboarding-safe (tenant policy decides; engine doesn't
148
+ * short-circuit known-agent UAs with an engine-default Block).
149
+ *
150
+ * Opt into `{ tier3Action: 'block' }` when the host wants the
151
+ * calibrated engine-default block for KnownAiAgent / AiCrawler /
152
+ * HeadlessBrowser classifications BEFORE the tenant policy seam.
153
+ *
154
+ * Added in `@kya-os/checkpoint-nextjs@1.2.0` (Engine-Tier3-Monitor-
155
+ * Default, #2653 + this PR's plumbing follow-up).
156
+ *
157
+ * @default { tier3Action: 'monitor' }
158
+ */
159
+ engineConfig?: EngineConfig;
160
+ /**
161
+ * Project API key. Required for detections to land in the dashboard
162
+ * — the engine verifies in-process via WASM, but the resulting
163
+ * `VerifyResult` only reaches the dashboard's `detections` table
164
+ * when this reporter is configured. Without it the verdict path
165
+ * works locally but the onboarding "Verify connection" check fails
166
+ * forever because no rows are ever written.
167
+ *
168
+ * Resolve from `process.env.CHECKPOINT_API_KEY` in the host app.
169
+ *
170
+ * Added in `@kya-os/checkpoint-nextjs@1.4.0`
171
+ * (SDK-Detection-Reporter-1).
172
+ */
173
+ apiKey?: string;
174
+ /**
175
+ * Dashboard base URL. Override for staging or self-hosted dashboards.
176
+ *
177
+ * @default 'https://kya.vouched.id'
178
+ */
179
+ baseUrl?: string;
180
+ /**
181
+ * Surface reporter errors via `console.warn`. Defaults to `false`.
182
+ * The reporter is fire-and-forget; enable during development to
183
+ * confirm `apiKey` / `baseUrl` are routed correctly.
184
+ *
185
+ * Also wires the composed-policy shadow-divergence + fail-open
186
+ * telemetry to `console.warn`/`console.error` (otherwise silent).
187
+ *
188
+ * @default false
189
+ */
190
+ debug?: boolean;
191
+ /**
192
+ * Project id whose composed (/policy-compose) policy this middleware
193
+ * enforces. When set, the project's policy is fetched from the dashboard
194
+ * (`<dashboardUrl ?? baseUrl ?? default>/api/internal/policies/${projectId}`)
195
+ * and — if it carries a deployed Cedar bundle with `engineEnforcementEnabled`
196
+ * on — the kya-os-engine decision is enforced IN-PROCESS, byte-for-byte the
197
+ * same as the DNS Gateway. Omit to run detection + the structured policy only
198
+ * (fully back-compatible; purely additive).
199
+ *
200
+ * SHADOW-FIRST: with a deployed bundle but `engineEnforcementEnabled` off, the
201
+ * engine decision is computed + logged on divergence but does NOT act.
202
+ *
203
+ * **Node vs Edge:** composed enforcement is default-on under the Node runtime
204
+ * (`./node`). Under the Edge runtime (`./edge`) it additionally requires
205
+ * `cedarWasmModule` to be wired (see below) — otherwise the seam stays inert.
206
+ *
207
+ * Added in `@kya-os/checkpoint-nextjs@1.5.0` (@Policy middleware-Cedar, #3076).
208
+ */
209
+ projectId?: string;
210
+ /** Signed browser risk; configure explicit route scopes to enable consent step-up. */
211
+ browserPosture?: BrowserPostureConfig;
212
+ /**
213
+ * Policy-fetch cache TTL in seconds. Defaults to 300 (5 minutes). How long
214
+ * a fetched project policy is reused before the middleware refetches from
215
+ * the dashboard — i.e. the worst-case delay before a dashboard policy
216
+ * change takes effect on this host.
217
+ *
218
+ * `0` disables reuse entirely: every request fetches the policy (one
219
+ * origin round-trip per request). Use for demo/example sites where instant
220
+ * policy propagation matters more than latency; keep the default (or a
221
+ * small positive value like 5) for production and benchmark hosts.
222
+ *
223
+ * @default 300
224
+ */
225
+ policyCacheTtlSeconds?: number;
226
+ /**
227
+ * Advanced / testing: inject a pre-built composed-policy context instead of
228
+ * letting `withCheckpoint` construct one from `projectId` + `baseUrl` +
229
+ * `apiKey`. Mirrors the `adapters` injection philosophy — production omits
230
+ * this. When set, it takes precedence over `projectId`.
231
+ */
232
+ composedPolicyEnforcer?: ComposedPolicyContext;
233
+ /**
234
+ * EDGE runtime only. The cedar-web `WebAssembly.Module`, statically imported
235
+ * by the host so composed-policy Cedar can compile at the edge:
236
+ *
237
+ * ```ts
238
+ * import cedarWasmModule from
239
+ * '@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine_bg.wasm?module';
240
+ * export default withCheckpoint({ projectId, cedarWasmModule });
241
+ * ```
242
+ *
243
+ * The ~2 MB cedar binary is deliberately NOT bundled into the SDK — wiring it
244
+ * is the consumer's explicit opt-in for edge composed enforcement (requires
245
+ * `experiments.asyncWebAssembly` + a `.wasm` asset rule in `next.config`).
246
+ * Without it the Edge seam stays inert (behaves exactly as 1.4.0); the Node
247
+ * runtime ignores this field (it loads cedar via `createPolicyEvaluator`).
248
+ *
249
+ * Added in `@kya-os/checkpoint-nextjs@1.5.0` (@Policy middleware-Cedar, #3076).
250
+ */
251
+ cedarWasmModule?: WebAssembly.Module;
252
+ }
253
+ //#endregion
254
+ export { CheckpointConfig as t };
255
+ //# sourceMappingURL=config-CbAg2mze.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-CbAg2mze.d.ts","names":[],"sources":["../src/config.ts"],"mappings":";;;;;;;;;;;;;;UAuCiB;;;;;;;EAOf,iBAAiB;;;;;;EAMjB;;EAEA;;EAEA;;;;;;;EAQA,kBAAkB;;;;;;;;;;EAWlB,0BAA0B;;;;;;EAO1B,8BAA8B;IAC5B,QAAQ;IACR,SAAS;QACL,iCAAiC,QAAQ;;;;;;EAO/C;;EAGA,gCAAgC,OAAO;;;;;;EAOvC;;;;;EAMA;;;;;;;EAQA;;;;;;;EAQA,WAAW;IACT,aAAa;IACb,iBAAiB;IACjB,kBAAkB;IAClB,iBAAiB;;;;;;;;;EAUnB,YAAY,QAAQ,cAAc,KAAK,uBAAuB;;;;;;;;;;;;;;;;;;;;EAqB9D;;;;;;;;;;;;;;;;;;;EAoBA;;;;;;;;;;;;;;;;EAiBA,eAAe;;;;;;;;;;;;;;EAef;;;;;;EAOA;;;;;;;;;;;EAYA;;;;;;;;;;;;;;;;;;;EAoBA;;EAEA,iBAAiB;;;;;;;;;;;;;;EAejB;;;;;;;EAQA,yBAAyB;;;;;;;;;;;;;;;;;;;EAoBzB,kBAAkB,YAAY"}