@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.
Files changed (156) hide show
  1. package/CHANGELOG.md +322 -0
  2. package/README.md +205 -31
  3. package/dist/adapt-BdQ9R7Iw.mjs +97 -0
  4. package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
  5. package/dist/adapt-CCSKGjVH.js +107 -0
  6. package/dist/api-client-JHOrRUA_.d.mts +222 -0
  7. package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
  8. package/dist/api-client-JHOrRUA_.d.ts +222 -0
  9. package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
  10. package/dist/api-client.d.mts +2 -213
  11. package/dist/api-client.d.ts +2 -213
  12. package/dist/api-client.js +221 -206
  13. package/dist/api-client.mjs +222 -202
  14. package/dist/api-client.mjs.map +1 -0
  15. package/dist/api-middleware-BWjokNis.d.mts +131 -0
  16. package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
  17. package/dist/api-middleware-Bf3xmM9W.js +391 -0
  18. package/dist/api-middleware-C-ngFX_8.mjs +387 -0
  19. package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
  20. package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
  21. package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
  22. package/dist/api-middleware.d.mts +2 -166
  23. package/dist/api-middleware.d.ts +2 -166
  24. package/dist/api-middleware.js +3 -526
  25. package/dist/api-middleware.mjs +2 -521
  26. package/dist/cedar-wasm.d.mts +20 -0
  27. package/dist/cedar-wasm.d.mts.map +1 -0
  28. package/dist/cedar-wasm.d.ts +19 -0
  29. package/dist/cedar-wasm.d.ts.map +1 -0
  30. package/dist/cedar-wasm.js +24 -0
  31. package/dist/cedar-wasm.mjs +23 -0
  32. package/dist/cedar-wasm.mjs.map +1 -0
  33. package/dist/config-CPP1RV0f.d.mts +291 -0
  34. package/dist/config-CPP1RV0f.d.mts.map +1 -0
  35. package/dist/config-DVgOFxJs.d.ts +291 -0
  36. package/dist/config-DVgOFxJs.d.ts.map +1 -0
  37. package/dist/engine-wasm.d.mts +20 -0
  38. package/dist/engine-wasm.d.mts.map +1 -0
  39. package/dist/engine-wasm.d.ts +19 -0
  40. package/dist/engine-wasm.d.ts.map +1 -0
  41. package/dist/engine-wasm.js +24 -0
  42. package/dist/engine-wasm.mjs +23 -0
  43. package/dist/engine-wasm.mjs.map +1 -0
  44. package/dist/index-edge.d.mts +8 -0
  45. package/dist/index-edge.d.ts +8 -0
  46. package/dist/index-edge.js +14 -0
  47. package/dist/index-edge.mjs +7 -0
  48. package/dist/index.d.mts +8 -17
  49. package/dist/index.d.ts +8 -17
  50. package/dist/index.js +36 -1275
  51. package/dist/index.mjs +29 -1234
  52. package/dist/index.mjs.map +1 -0
  53. package/dist/middleware-bundler.d.mts +6 -12
  54. package/dist/middleware-bundler.d.mts.map +1 -0
  55. package/dist/middleware-bundler.d.ts +6 -12
  56. package/dist/middleware-bundler.d.ts.map +1 -0
  57. package/dist/middleware-bundler.js +12 -350
  58. package/dist/middleware-bundler.mjs +11 -347
  59. package/dist/middleware-bundler.mjs.map +1 -0
  60. package/dist/middleware-core-B0jf5_Hm.mjs +264 -0
  61. package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
  62. package/dist/middleware-core-Bol44X9C.d.ts +17 -0
  63. package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
  64. package/dist/middleware-core-CMc-2QkU.js +274 -0
  65. package/dist/middleware-core-DycsbHUd.d.mts +17 -0
  66. package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
  67. package/dist/middleware-edge.d.mts +16 -14
  68. package/dist/middleware-edge.d.mts.map +1 -0
  69. package/dist/middleware-edge.d.ts +16 -14
  70. package/dist/middleware-edge.d.ts.map +1 -0
  71. package/dist/middleware-edge.js +94 -355
  72. package/dist/middleware-edge.mjs +90 -347
  73. package/dist/middleware-edge.mjs.map +1 -0
  74. package/dist/middleware-node-context-591KsiYg.js +39 -0
  75. package/dist/middleware-node-context-D_ZyUEcA.mjs +35 -0
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
  77. package/dist/middleware-node.d.mts +10 -25
  78. package/dist/middleware-node.d.mts.map +1 -0
  79. package/dist/middleware-node.d.ts +10 -25
  80. package/dist/middleware-node.d.ts.map +1 -0
  81. package/dist/middleware-node.js +21 -351
  82. package/dist/middleware-node.mjs +19 -347
  83. package/dist/middleware-node.mjs.map +1 -0
  84. package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
  85. package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
  86. package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
  87. package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
  88. package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
  89. package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
  90. package/dist/posture-outcome-DddsJtL8.js +25 -0
  91. package/dist/public-api-CYsHrTQI.d.ts +5 -0
  92. package/dist/public-api-DkG7pRE0.d.mts +5 -0
  93. package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
  94. package/dist/utils-Cnwg0VrY.mjs +88 -0
  95. package/dist/utils-Cnwg0VrY.mjs.map +1 -0
  96. package/dist/utils-dyFxqlFI.js +104 -0
  97. package/package.json +31 -66
  98. package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
  99. package/bin/setup-edge-wasm.js +0 -513
  100. package/dist/adapt.d.mts +0 -39
  101. package/dist/adapt.d.ts +0 -39
  102. package/dist/adapt.js +0 -59
  103. package/dist/adapt.mjs +0 -57
  104. package/dist/composed-policy.d.mts +0 -115
  105. package/dist/composed-policy.d.ts +0 -115
  106. package/dist/composed-policy.js +0 -103
  107. package/dist/composed-policy.mjs +0 -97
  108. package/dist/config-CleTeeoW.d.mts +0 -233
  109. package/dist/config-XMOIkxFN.d.ts +0 -233
  110. package/dist/create-middleware.d.mts +0 -22
  111. package/dist/create-middleware.d.ts +0 -22
  112. package/dist/create-middleware.js +0 -34
  113. package/dist/create-middleware.mjs +0 -31
  114. package/dist/edge/index.d.mts +0 -112
  115. package/dist/edge/index.d.ts +0 -112
  116. package/dist/edge/index.js +0 -277
  117. package/dist/edge/index.mjs +0 -275
  118. package/dist/edge-runtime-loader.d.mts +0 -77
  119. package/dist/edge-runtime-loader.d.ts +0 -77
  120. package/dist/edge-runtime-loader.js +0 -242
  121. package/dist/edge-runtime-loader.mjs +0 -235
  122. package/dist/edge-wasm-middleware.d.mts +0 -62
  123. package/dist/edge-wasm-middleware.d.ts +0 -62
  124. package/dist/edge-wasm-middleware.js +0 -26
  125. package/dist/edge-wasm-middleware.mjs +0 -22
  126. package/dist/middleware.d.mts +0 -45
  127. package/dist/middleware.d.ts +0 -45
  128. package/dist/middleware.js +0 -19
  129. package/dist/middleware.mjs +0 -15
  130. package/dist/nodejs-wasm-loader.d.mts +0 -41
  131. package/dist/nodejs-wasm-loader.d.ts +0 -41
  132. package/dist/nodejs-wasm-loader.js +0 -36
  133. package/dist/nodejs-wasm-loader.mjs +0 -30
  134. package/dist/policy.d.mts +0 -162
  135. package/dist/policy.d.ts +0 -162
  136. package/dist/policy.js +0 -198
  137. package/dist/policy.mjs +0 -174
  138. package/dist/session-tracker.d.mts +0 -55
  139. package/dist/session-tracker.d.ts +0 -55
  140. package/dist/session-tracker.js +0 -172
  141. package/dist/session-tracker.mjs +0 -169
  142. package/dist/translate.d.mts +0 -63
  143. package/dist/translate.d.ts +0 -63
  144. package/dist/translate.js +0 -44
  145. package/dist/translate.mjs +0 -42
  146. package/dist/types-Chgi5TFC.d.mts +0 -105
  147. package/dist/types-Chgi5TFC.d.ts +0 -105
  148. package/dist/wasm-setup.d.mts +0 -46
  149. package/dist/wasm-setup.d.ts +0 -46
  150. package/dist/wasm-setup.js +0 -122
  151. package/dist/wasm-setup.mjs +0 -118
  152. package/wasm/agentshield_wasm.d.ts +0 -479
  153. package/wasm/agentshield_wasm.js +0 -1536
  154. package/wasm/agentshield_wasm_bg.wasm +0 -0
  155. package/wasm/package.json +0 -30
  156. package/wasm.d.ts +0 -21
@@ -1,30 +0,0 @@
1
- // src/nodejs-wasm-loader.ts
2
- var MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy detection class they fed was removed in AgentDetector-Deletion-2. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
3
- var _nodejsWasmWarned = false;
4
- function warnNodejsWasmDeprecated() {
5
- if (_nodejsWasmWarned) return;
6
- _nodejsWasmWarned = true;
7
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") return;
8
- console.warn(`[Checkpoint] ${MIGRATION_ERROR}`);
9
- }
10
- function __resetNodejsWasmWarningForTests() {
11
- _nodejsWasmWarned = false;
12
- }
13
- async function loadWasmNodejs() {
14
- warnNodejsWasmDeprecated();
15
- throw new Error(MIGRATION_ERROR);
16
- }
17
- function isNodejsRuntime() {
18
- warnNodejsWasmDeprecated();
19
- throw new Error(MIGRATION_ERROR);
20
- }
21
- function getWasmModule() {
22
- warnNodejsWasmDeprecated();
23
- throw new Error(MIGRATION_ERROR);
24
- }
25
- function isWasmInitialized() {
26
- warnNodejsWasmDeprecated();
27
- throw new Error(MIGRATION_ERROR);
28
- }
29
-
30
- export { __resetNodejsWasmWarningForTests, getWasmModule, isNodejsRuntime, isWasmInitialized, loadWasmNodejs };
package/dist/policy.d.mts DELETED
@@ -1,162 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { PolicyConfig, PolicyEvaluationResult, PolicyEvaluationContext, DetectionResult } from '@kya-os/checkpoint-shared';
3
- export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, PolicyConfig, PolicyEvaluationContext, PolicyEvaluationResult, createEvaluationContext, evaluatePolicy } from '@kya-os/checkpoint-shared';
4
-
5
- /**
6
- * Policy Integration for agentshield-nextjs
7
- *
8
- * This module provides policy evaluation support for the Next.js middleware.
9
- * It can use:
10
- * - Local policy configuration (static)
11
- * - Fetched policy from AgentShield API (dynamic with caching)
12
- * - Fallback/default policies
13
- *
14
- * @example
15
- * ```typescript
16
- * import { createPolicyMiddleware } from '@kya-os/checkpoint-nextjs/policy';
17
- *
18
- * export default createPolicyMiddleware({
19
- * policy: {
20
- * enabled: true,
21
- * defaultAction: 'allow',
22
- * thresholds: { confidenceThreshold: 80, confidenceAction: 'block' },
23
- * allowList: [{ clientName: 'ChatGPT' }],
24
- * },
25
- * });
26
- * ```
27
- */
28
-
29
- /**
30
- * Policy middleware configuration
31
- */
32
- interface PolicyMiddlewareConfig {
33
- /**
34
- * Local policy configuration (static)
35
- * If provided, this policy is used instead of fetching from API
36
- */
37
- policy?: Partial<PolicyConfig>;
38
- /**
39
- * Fetch policy from AgentShield API
40
- * Requires projectId and optionally an apiKey
41
- */
42
- fetchPolicy?: {
43
- /** Project ID to fetch policy for */
44
- projectId: string;
45
- /** API base URL (defaults to production) */
46
- apiUrl?: string;
47
- /** API key for authentication */
48
- apiKey?: string;
49
- /** Cache TTL in seconds (default: 300) */
50
- cacheTtlSeconds?: number;
51
- };
52
- /**
53
- * Fallback policy to use when fetch fails
54
- * Defaults to DEFAULT_POLICY (allow all)
55
- */
56
- fallbackPolicy?: Partial<PolicyConfig>;
57
- /**
58
- * Custom blocked response
59
- */
60
- blockedResponse?: {
61
- status?: number;
62
- message?: string;
63
- headers?: Record<string, string>;
64
- };
65
- /**
66
- * Default redirect URL for redirect actions
67
- */
68
- redirectUrl?: string;
69
- /**
70
- * Callback when policy decision is made
71
- */
72
- onPolicyDecision?: (request: NextRequest, decision: PolicyEvaluationResult, context: PolicyEvaluationContext) => void | Promise<void>;
73
- /**
74
- * Custom response builder for blocked requests
75
- */
76
- customBlockedResponse?: (request: NextRequest, decision: PolicyEvaluationResult) => NextResponse | Promise<NextResponse>;
77
- /**
78
- * Whether to fail open (allow) on policy evaluation errors
79
- * Default: true (recommended for production)
80
- */
81
- failOpen?: boolean;
82
- /**
83
- * Enable debug logging
84
- */
85
- debug?: boolean;
86
- }
87
- /**
88
- * Combined middleware configuration with policy support
89
- */
90
- interface NextJSPolicyMiddlewareConfig extends PolicyMiddlewareConfig {
91
- /**
92
- * Paths to skip (in addition to policy excludedPaths)
93
- */
94
- skipPaths?: string[];
95
- /**
96
- * Only enforce on these paths (overrides policy includedPaths)
97
- */
98
- includePaths?: string[];
99
- }
100
- /**
101
- * Create policy evaluation context from detection result and request
102
- */
103
- declare function createContextFromDetection(detection: DetectionResult, request: NextRequest): PolicyEvaluationContext;
104
- /**
105
- * Evaluate policy for a detection result
106
- */
107
- declare function evaluatePolicyForDetection(detection: DetectionResult, request: NextRequest, policy: PolicyConfig): PolicyEvaluationResult;
108
- /**
109
- * Build blocked response based on policy decision
110
- */
111
- declare function buildBlockedResponse(decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig): NextResponse;
112
- /**
113
- * Build redirect response based on policy decision
114
- */
115
- declare function buildRedirectResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
116
- detectedAgent?: {
117
- name?: string;
118
- };
119
- }): NextResponse;
120
- /**
121
- * Build challenge response (placeholder - future implementation)
122
- */
123
- declare function buildChallengeResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
124
- detectedAgent?: {
125
- name?: string;
126
- };
127
- }): NextResponse;
128
- /**
129
- * Handle policy decision and return appropriate response
130
- */
131
- declare function handlePolicyDecision(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
132
- detectedAgent?: {
133
- name?: string;
134
- };
135
- }): Promise<NextResponse | null>;
136
- /**
137
- * Get policy (local, fetched, or fallback)
138
- */
139
- declare function getPolicy(config: PolicyMiddlewareConfig): Promise<PolicyConfig>;
140
- /**
141
- * Apply policy to a detection result
142
- *
143
- * This function can be used standalone to evaluate policy after detection.
144
- * Supports extended config with skipPaths and includePaths for path-based filtering.
145
- *
146
- * @example
147
- * ```typescript
148
- * const result = await detector.analyze(context);
149
- * const response = await applyPolicy(request, result, {
150
- * policy: { thresholds: { confidenceThreshold: 80 } },
151
- * skipPaths: ['/health', '/api/public/*'],
152
- * includePaths: ['/api/*'],
153
- * });
154
- *
155
- * if (response) {
156
- * return response; // Policy blocked the request
157
- * }
158
- * ```
159
- */
160
- declare function applyPolicy(request: NextRequest, detection: DetectionResult, config: NextJSPolicyMiddlewareConfig): Promise<NextResponse | null>;
161
-
162
- export { type NextJSPolicyMiddlewareConfig, type PolicyMiddlewareConfig, applyPolicy, buildBlockedResponse, buildChallengeResponse, buildRedirectResponse, createContextFromDetection, evaluatePolicyForDetection, getPolicy, handlePolicyDecision };
package/dist/policy.d.ts DELETED
@@ -1,162 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { PolicyConfig, PolicyEvaluationResult, PolicyEvaluationContext, DetectionResult } from '@kya-os/checkpoint-shared';
3
- export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, PolicyConfig, PolicyEvaluationContext, PolicyEvaluationResult, createEvaluationContext, evaluatePolicy } from '@kya-os/checkpoint-shared';
4
-
5
- /**
6
- * Policy Integration for agentshield-nextjs
7
- *
8
- * This module provides policy evaluation support for the Next.js middleware.
9
- * It can use:
10
- * - Local policy configuration (static)
11
- * - Fetched policy from AgentShield API (dynamic with caching)
12
- * - Fallback/default policies
13
- *
14
- * @example
15
- * ```typescript
16
- * import { createPolicyMiddleware } from '@kya-os/checkpoint-nextjs/policy';
17
- *
18
- * export default createPolicyMiddleware({
19
- * policy: {
20
- * enabled: true,
21
- * defaultAction: 'allow',
22
- * thresholds: { confidenceThreshold: 80, confidenceAction: 'block' },
23
- * allowList: [{ clientName: 'ChatGPT' }],
24
- * },
25
- * });
26
- * ```
27
- */
28
-
29
- /**
30
- * Policy middleware configuration
31
- */
32
- interface PolicyMiddlewareConfig {
33
- /**
34
- * Local policy configuration (static)
35
- * If provided, this policy is used instead of fetching from API
36
- */
37
- policy?: Partial<PolicyConfig>;
38
- /**
39
- * Fetch policy from AgentShield API
40
- * Requires projectId and optionally an apiKey
41
- */
42
- fetchPolicy?: {
43
- /** Project ID to fetch policy for */
44
- projectId: string;
45
- /** API base URL (defaults to production) */
46
- apiUrl?: string;
47
- /** API key for authentication */
48
- apiKey?: string;
49
- /** Cache TTL in seconds (default: 300) */
50
- cacheTtlSeconds?: number;
51
- };
52
- /**
53
- * Fallback policy to use when fetch fails
54
- * Defaults to DEFAULT_POLICY (allow all)
55
- */
56
- fallbackPolicy?: Partial<PolicyConfig>;
57
- /**
58
- * Custom blocked response
59
- */
60
- blockedResponse?: {
61
- status?: number;
62
- message?: string;
63
- headers?: Record<string, string>;
64
- };
65
- /**
66
- * Default redirect URL for redirect actions
67
- */
68
- redirectUrl?: string;
69
- /**
70
- * Callback when policy decision is made
71
- */
72
- onPolicyDecision?: (request: NextRequest, decision: PolicyEvaluationResult, context: PolicyEvaluationContext) => void | Promise<void>;
73
- /**
74
- * Custom response builder for blocked requests
75
- */
76
- customBlockedResponse?: (request: NextRequest, decision: PolicyEvaluationResult) => NextResponse | Promise<NextResponse>;
77
- /**
78
- * Whether to fail open (allow) on policy evaluation errors
79
- * Default: true (recommended for production)
80
- */
81
- failOpen?: boolean;
82
- /**
83
- * Enable debug logging
84
- */
85
- debug?: boolean;
86
- }
87
- /**
88
- * Combined middleware configuration with policy support
89
- */
90
- interface NextJSPolicyMiddlewareConfig extends PolicyMiddlewareConfig {
91
- /**
92
- * Paths to skip (in addition to policy excludedPaths)
93
- */
94
- skipPaths?: string[];
95
- /**
96
- * Only enforce on these paths (overrides policy includedPaths)
97
- */
98
- includePaths?: string[];
99
- }
100
- /**
101
- * Create policy evaluation context from detection result and request
102
- */
103
- declare function createContextFromDetection(detection: DetectionResult, request: NextRequest): PolicyEvaluationContext;
104
- /**
105
- * Evaluate policy for a detection result
106
- */
107
- declare function evaluatePolicyForDetection(detection: DetectionResult, request: NextRequest, policy: PolicyConfig): PolicyEvaluationResult;
108
- /**
109
- * Build blocked response based on policy decision
110
- */
111
- declare function buildBlockedResponse(decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig): NextResponse;
112
- /**
113
- * Build redirect response based on policy decision
114
- */
115
- declare function buildRedirectResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
116
- detectedAgent?: {
117
- name?: string;
118
- };
119
- }): NextResponse;
120
- /**
121
- * Build challenge response (placeholder - future implementation)
122
- */
123
- declare function buildChallengeResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
124
- detectedAgent?: {
125
- name?: string;
126
- };
127
- }): NextResponse;
128
- /**
129
- * Handle policy decision and return appropriate response
130
- */
131
- declare function handlePolicyDecision(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
132
- detectedAgent?: {
133
- name?: string;
134
- };
135
- }): Promise<NextResponse | null>;
136
- /**
137
- * Get policy (local, fetched, or fallback)
138
- */
139
- declare function getPolicy(config: PolicyMiddlewareConfig): Promise<PolicyConfig>;
140
- /**
141
- * Apply policy to a detection result
142
- *
143
- * This function can be used standalone to evaluate policy after detection.
144
- * Supports extended config with skipPaths and includePaths for path-based filtering.
145
- *
146
- * @example
147
- * ```typescript
148
- * const result = await detector.analyze(context);
149
- * const response = await applyPolicy(request, result, {
150
- * policy: { thresholds: { confidenceThreshold: 80 } },
151
- * skipPaths: ['/health', '/api/public/*'],
152
- * includePaths: ['/api/*'],
153
- * });
154
- *
155
- * if (response) {
156
- * return response; // Policy blocked the request
157
- * }
158
- * ```
159
- */
160
- declare function applyPolicy(request: NextRequest, detection: DetectionResult, config: NextJSPolicyMiddlewareConfig): Promise<NextResponse | null>;
161
-
162
- export { type NextJSPolicyMiddlewareConfig, type PolicyMiddlewareConfig, applyPolicy, buildBlockedResponse, buildChallengeResponse, buildRedirectResponse, createContextFromDetection, evaluatePolicyForDetection, getPolicy, handlePolicyDecision };
package/dist/policy.js DELETED
@@ -1,198 +0,0 @@
1
- 'use strict';
2
-
3
- var server = require('next/server');
4
- var checkpointShared = require('@kya-os/checkpoint-shared');
5
-
6
- // src/policy.ts
7
- function createContextFromDetection(detection, request) {
8
- return checkpointShared.createEvaluationContext({
9
- agentType: detection.detectedAgent?.type,
10
- agentName: detection.detectedAgent?.name,
11
- agentVendor: detection.detectedAgent?.vendor,
12
- confidence: detection.confidence,
13
- riskLevel: detection.riskLevel,
14
- path: request.nextUrl.pathname,
15
- method: request.method,
16
- // Cryptographic-signature methods only, mirroring the composed-policy
17
- // VERIFIED_VERIFICATION_METHODS allowlist (checkpoint-wasm-runtime):
18
- // 'signature' (bare RFC 9421 keyid) and 'tier1_rfc9421' (RFC 9421 vendor-key
19
- // / Web Bot Auth, #4804) are the same crypto class; kya-http/kya-http-delegated
20
- // are the draft-kya-http-02 §4.3 request-signature methods.
21
- signatureVerified: detection.verificationMethod === "signature" || detection.verificationMethod === "tier1_rfc9421" || detection.verificationMethod === "kya-http" || detection.verificationMethod === "kya-http-delegated",
22
- isAuthenticated: false,
23
- // TODO: integrate with auth
24
- userAgent: request.headers.get("user-agent") || void 0
25
- });
26
- }
27
- function evaluatePolicyForDetection(detection, request, policy) {
28
- const context = createContextFromDetection(detection, request);
29
- return checkpointShared.evaluatePolicy(policy, context);
30
- }
31
- function buildBlockedResponse(decision, config) {
32
- const status = config.blockedResponse?.status ?? 403;
33
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
34
- const response = server.NextResponse.json(
35
- {
36
- error: message,
37
- code: "POLICY_BLOCKED",
38
- reason: decision.reason,
39
- ruleId: decision.ruleId,
40
- matchType: decision.matchType
41
- },
42
- { status }
43
- );
44
- if (config.blockedResponse?.headers) {
45
- for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
46
- response.headers.set(key, value);
47
- }
48
- }
49
- response.headers.set("KYA-Action", decision.action);
50
- response.headers.set("KYA-Reason", decision.reason);
51
- response.headers.set("KYA-Match-Type", decision.matchType);
52
- return response;
53
- }
54
- function buildRedirectResponse(request, decision, config, detection) {
55
- const redirectUrl = decision.redirectUrl || config.redirectUrl || "/blocked";
56
- const url = new URL(redirectUrl, request.url);
57
- url.searchParams.set("reason", decision.reason);
58
- if (decision.ruleId) {
59
- url.searchParams.set("ruleId", decision.ruleId);
60
- }
61
- const agentName = detection?.detectedAgent?.name;
62
- if (agentName && !url.searchParams.has("agent")) {
63
- url.searchParams.set("agent", agentName.toLowerCase());
64
- }
65
- return server.NextResponse.redirect(url);
66
- }
67
- function buildChallengeResponse(request, decision, config, detection) {
68
- return buildRedirectResponse(request, decision, config, detection);
69
- }
70
- async function handlePolicyDecision(request, decision, config, detection) {
71
- switch (decision.action) {
72
- case checkpointShared.ENFORCEMENT_ACTIONS.BLOCK:
73
- if (config.customBlockedResponse) {
74
- return await config.customBlockedResponse(request, decision);
75
- }
76
- return buildBlockedResponse(decision, config);
77
- case checkpointShared.ENFORCEMENT_ACTIONS.REDIRECT:
78
- return buildRedirectResponse(request, decision, config, detection);
79
- case checkpointShared.ENFORCEMENT_ACTIONS.CHALLENGE:
80
- return buildChallengeResponse(request, decision, config, detection);
81
- case checkpointShared.ENFORCEMENT_ACTIONS.LOG:
82
- console.log("[Checkpoint] Policy decision (log):", {
83
- path: request.nextUrl.pathname,
84
- action: decision.action,
85
- reason: decision.reason,
86
- matchType: decision.matchType,
87
- ruleId: decision.ruleId
88
- });
89
- return null;
90
- // Continue to allow
91
- case checkpointShared.ENFORCEMENT_ACTIONS.ALLOW:
92
- default:
93
- return null;
94
- }
95
- }
96
- var fetcherCache = /* @__PURE__ */ new Map();
97
- function getFetcherCacheKey(config) {
98
- return `${config.apiUrl ?? "default"}:${config.apiKey ?? ""}:${config.cacheTtlSeconds ?? "default"}`;
99
- }
100
- function getPolicyFetcher(config) {
101
- if (!config) {
102
- throw new Error("fetchPolicy config required");
103
- }
104
- const cacheKey = getFetcherCacheKey(config);
105
- let fetcher = fetcherCache.get(cacheKey);
106
- if (!fetcher) {
107
- const fetcherConfig = {
108
- apiBaseUrl: config.apiUrl || "https://kya.vouched.id",
109
- apiKey: config.apiKey,
110
- cacheTtlSeconds: config.cacheTtlSeconds
111
- };
112
- fetcher = checkpointShared.createPolicyFetcher(fetcherConfig);
113
- fetcherCache.set(cacheKey, fetcher);
114
- }
115
- return fetcher;
116
- }
117
- async function getPolicy(config) {
118
- if (config.policy) {
119
- return checkpointShared.PolicyConfigSchema.parse({ ...checkpointShared.DEFAULT_POLICY, ...config.policy });
120
- }
121
- if (config.fetchPolicy) {
122
- try {
123
- const fetcher = getPolicyFetcher(config.fetchPolicy);
124
- return await fetcher.getPolicy(config.fetchPolicy.projectId);
125
- } catch (error) {
126
- if (config.debug) {
127
- console.warn("[Checkpoint] Policy fetch failed, using fallback:", error);
128
- }
129
- return checkpointShared.PolicyConfigSchema.parse({
130
- ...checkpointShared.DEFAULT_POLICY,
131
- ...config.fallbackPolicy || {}
132
- });
133
- }
134
- }
135
- return checkpointShared.PolicyConfigSchema.parse(checkpointShared.DEFAULT_POLICY);
136
- }
137
- async function applyPolicy(request, detection, config) {
138
- try {
139
- const path = request.nextUrl.pathname;
140
- if (config.skipPaths?.some((pattern) => checkpointShared.matchPath(path, pattern))) {
141
- return null;
142
- }
143
- if (config.includePaths && config.includePaths.length > 0) {
144
- if (!config.includePaths.some((pattern) => checkpointShared.matchPath(path, pattern))) {
145
- return null;
146
- }
147
- }
148
- const policy = await getPolicy(config);
149
- const context = createContextFromDetection(detection, request);
150
- const decision = checkpointShared.evaluatePolicy(policy, context);
151
- if (config.onPolicyDecision) {
152
- try {
153
- await config.onPolicyDecision(request, decision, context);
154
- } catch (error) {
155
- if (config.debug) {
156
- console.error("[Checkpoint] onPolicyDecision callback failed:", error);
157
- }
158
- }
159
- }
160
- return await handlePolicyDecision(request, decision, config, detection);
161
- } catch (error) {
162
- if (config.debug) {
163
- console.error("[Checkpoint] Policy evaluation error:", error);
164
- }
165
- if (config.failOpen !== false) {
166
- return null;
167
- }
168
- return server.NextResponse.json(
169
- { error: "Security check failed", code: "POLICY_ERROR" },
170
- { status: 503 }
171
- );
172
- }
173
- }
174
-
175
- Object.defineProperty(exports, "DEFAULT_POLICY", {
176
- enumerable: true,
177
- get: function () { return checkpointShared.DEFAULT_POLICY; }
178
- });
179
- Object.defineProperty(exports, "ENFORCEMENT_ACTIONS", {
180
- enumerable: true,
181
- get: function () { return checkpointShared.ENFORCEMENT_ACTIONS; }
182
- });
183
- Object.defineProperty(exports, "createEvaluationContext", {
184
- enumerable: true,
185
- get: function () { return checkpointShared.createEvaluationContext; }
186
- });
187
- Object.defineProperty(exports, "evaluatePolicy", {
188
- enumerable: true,
189
- get: function () { return checkpointShared.evaluatePolicy; }
190
- });
191
- exports.applyPolicy = applyPolicy;
192
- exports.buildBlockedResponse = buildBlockedResponse;
193
- exports.buildChallengeResponse = buildChallengeResponse;
194
- exports.buildRedirectResponse = buildRedirectResponse;
195
- exports.createContextFromDetection = createContextFromDetection;
196
- exports.evaluatePolicyForDetection = evaluatePolicyForDetection;
197
- exports.getPolicy = getPolicy;
198
- exports.handlePolicyDecision = handlePolicyDecision;