@kya-os/agentshield-nextjs 0.3.3 → 0.3.5

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 (110) hide show
  1. package/README.md +21 -369
  2. package/index.js +9 -0
  3. package/package.json +7 -141
  4. package/EDGE_RUNTIME_WASM_SETUP.md +0 -348
  5. package/bin/setup-edge-wasm.js +0 -525
  6. package/dist/.tsbuildinfo +0 -1
  7. package/dist/api-client.d.mts +0 -196
  8. package/dist/api-client.d.ts +0 -196
  9. package/dist/api-client.js +0 -200
  10. package/dist/api-client.js.map +0 -1
  11. package/dist/api-client.mjs +0 -196
  12. package/dist/api-client.mjs.map +0 -1
  13. package/dist/api-middleware.d.mts +0 -140
  14. package/dist/api-middleware.d.ts +0 -140
  15. package/dist/api-middleware.js +0 -511
  16. package/dist/api-middleware.js.map +0 -1
  17. package/dist/api-middleware.mjs +0 -508
  18. package/dist/api-middleware.mjs.map +0 -1
  19. package/dist/create-middleware.d.mts +0 -17
  20. package/dist/create-middleware.d.ts +0 -17
  21. package/dist/create-middleware.js +0 -1381
  22. package/dist/create-middleware.js.map +0 -1
  23. package/dist/create-middleware.mjs +0 -1358
  24. package/dist/create-middleware.mjs.map +0 -1
  25. package/dist/edge/index.d.mts +0 -110
  26. package/dist/edge/index.d.ts +0 -110
  27. package/dist/edge/index.js +0 -277
  28. package/dist/edge/index.js.map +0 -1
  29. package/dist/edge/index.mjs +0 -275
  30. package/dist/edge/index.mjs.map +0 -1
  31. package/dist/edge-detector-wrapper.d.mts +0 -34
  32. package/dist/edge-detector-wrapper.d.ts +0 -34
  33. package/dist/edge-detector-wrapper.js +0 -596
  34. package/dist/edge-detector-wrapper.js.map +0 -1
  35. package/dist/edge-detector-wrapper.mjs +0 -574
  36. package/dist/edge-detector-wrapper.mjs.map +0 -1
  37. package/dist/edge-runtime-loader.d.mts +0 -50
  38. package/dist/edge-runtime-loader.d.ts +0 -50
  39. package/dist/edge-runtime-loader.js +0 -204
  40. package/dist/edge-runtime-loader.js.map +0 -1
  41. package/dist/edge-runtime-loader.mjs +0 -201
  42. package/dist/edge-runtime-loader.mjs.map +0 -1
  43. package/dist/edge-wasm-middleware.d.mts +0 -68
  44. package/dist/edge-wasm-middleware.d.ts +0 -68
  45. package/dist/edge-wasm-middleware.js +0 -318
  46. package/dist/edge-wasm-middleware.js.map +0 -1
  47. package/dist/edge-wasm-middleware.mjs +0 -315
  48. package/dist/edge-wasm-middleware.mjs.map +0 -1
  49. package/dist/enhanced-middleware.d.mts +0 -153
  50. package/dist/enhanced-middleware.d.ts +0 -153
  51. package/dist/enhanced-middleware.js +0 -1082
  52. package/dist/enhanced-middleware.js.map +0 -1
  53. package/dist/enhanced-middleware.mjs +0 -1080
  54. package/dist/enhanced-middleware.mjs.map +0 -1
  55. package/dist/index.d.mts +0 -24
  56. package/dist/index.d.ts +0 -24
  57. package/dist/index.js +0 -2717
  58. package/dist/index.js.map +0 -1
  59. package/dist/index.mjs +0 -2662
  60. package/dist/index.mjs.map +0 -1
  61. package/dist/middleware.d.mts +0 -21
  62. package/dist/middleware.d.ts +0 -21
  63. package/dist/middleware.js +0 -1362
  64. package/dist/middleware.js.map +0 -1
  65. package/dist/middleware.mjs +0 -1339
  66. package/dist/middleware.mjs.map +0 -1
  67. package/dist/nodejs-wasm-loader.d.mts +0 -25
  68. package/dist/nodejs-wasm-loader.d.ts +0 -25
  69. package/dist/nodejs-wasm-loader.js +0 -78
  70. package/dist/nodejs-wasm-loader.js.map +0 -1
  71. package/dist/nodejs-wasm-loader.mjs +0 -68
  72. package/dist/nodejs-wasm-loader.mjs.map +0 -1
  73. package/dist/policy.d.mts +0 -162
  74. package/dist/policy.d.ts +0 -162
  75. package/dist/policy.js +0 -189
  76. package/dist/policy.js.map +0 -1
  77. package/dist/policy.mjs +0 -165
  78. package/dist/policy.mjs.map +0 -1
  79. package/dist/session-tracker.d.mts +0 -55
  80. package/dist/session-tracker.d.ts +0 -55
  81. package/dist/session-tracker.js +0 -170
  82. package/dist/session-tracker.js.map +0 -1
  83. package/dist/session-tracker.mjs +0 -167
  84. package/dist/session-tracker.mjs.map +0 -1
  85. package/dist/signature-verifier.d.mts +0 -33
  86. package/dist/signature-verifier.d.ts +0 -33
  87. package/dist/signature-verifier.js +0 -386
  88. package/dist/signature-verifier.js.map +0 -1
  89. package/dist/signature-verifier.mjs +0 -362
  90. package/dist/signature-verifier.mjs.map +0 -1
  91. package/dist/types-DVmy9NE3.d.mts +0 -105
  92. package/dist/types-DVmy9NE3.d.ts +0 -105
  93. package/dist/wasm-middleware.d.mts +0 -63
  94. package/dist/wasm-middleware.d.ts +0 -63
  95. package/dist/wasm-middleware.js +0 -98
  96. package/dist/wasm-middleware.js.map +0 -1
  97. package/dist/wasm-middleware.mjs +0 -95
  98. package/dist/wasm-middleware.mjs.map +0 -1
  99. package/dist/wasm-setup.d.mts +0 -46
  100. package/dist/wasm-setup.d.ts +0 -46
  101. package/dist/wasm-setup.js +0 -157
  102. package/dist/wasm-setup.js.map +0 -1
  103. package/dist/wasm-setup.mjs +0 -148
  104. package/dist/wasm-setup.mjs.map +0 -1
  105. package/templates/middleware-wasm-100.ts +0 -151
  106. package/wasm/agentshield_wasm.d.ts +0 -479
  107. package/wasm/agentshield_wasm.js +0 -1536
  108. package/wasm/agentshield_wasm_bg.wasm +0 -0
  109. package/wasm/package.json +0 -30
  110. package/wasm.d.ts +0 -21
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/agentshield-shared';
3
- export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, PolicyConfig, PolicyEvaluationContext, PolicyEvaluationResult, createEvaluationContext, evaluatePolicy } from '@kya-os/agentshield-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/agentshield-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/agentshield-shared';
3
- export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, PolicyConfig, PolicyEvaluationContext, PolicyEvaluationResult, createEvaluationContext, evaluatePolicy } from '@kya-os/agentshield-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/agentshield-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,189 +0,0 @@
1
- 'use strict';
2
-
3
- var server = require('next/server');
4
- var agentshieldShared = require('@kya-os/agentshield-shared');
5
-
6
- // src/policy.ts
7
- function createContextFromDetection(detection, request) {
8
- return agentshieldShared.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
- signatureVerified: detection.verificationMethod === "signature",
17
- isAuthenticated: false,
18
- // TODO: integrate with auth
19
- userAgent: request.headers.get("user-agent") || void 0
20
- });
21
- }
22
- function evaluatePolicyForDetection(detection, request, policy) {
23
- const context = createContextFromDetection(detection, request);
24
- return agentshieldShared.evaluatePolicy(policy, context);
25
- }
26
- function buildBlockedResponse(decision, config) {
27
- const status = config.blockedResponse?.status ?? 403;
28
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
29
- const response = server.NextResponse.json(
30
- {
31
- error: message,
32
- code: "POLICY_BLOCKED",
33
- reason: decision.reason,
34
- ruleId: decision.ruleId,
35
- matchType: decision.matchType
36
- },
37
- { status }
38
- );
39
- if (config.blockedResponse?.headers) {
40
- for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
41
- response.headers.set(key, value);
42
- }
43
- }
44
- response.headers.set("KYA-Action", decision.action);
45
- response.headers.set("KYA-Reason", decision.reason);
46
- response.headers.set("KYA-Match-Type", decision.matchType);
47
- return response;
48
- }
49
- function buildRedirectResponse(request, decision, config, detection) {
50
- const redirectUrl = decision.redirectUrl || config.redirectUrl || "/blocked";
51
- const url = new URL(redirectUrl, request.url);
52
- url.searchParams.set("reason", decision.reason);
53
- if (decision.ruleId) {
54
- url.searchParams.set("ruleId", decision.ruleId);
55
- }
56
- const agentName = detection?.detectedAgent?.name;
57
- if (agentName && !url.searchParams.has("agent")) {
58
- url.searchParams.set("agent", agentName.toLowerCase());
59
- }
60
- return server.NextResponse.redirect(url);
61
- }
62
- function buildChallengeResponse(request, decision, config, detection) {
63
- return buildRedirectResponse(request, decision, config, detection);
64
- }
65
- async function handlePolicyDecision(request, decision, config, detection) {
66
- switch (decision.action) {
67
- case agentshieldShared.ENFORCEMENT_ACTIONS.BLOCK:
68
- if (config.customBlockedResponse) {
69
- return await config.customBlockedResponse(request, decision);
70
- }
71
- return buildBlockedResponse(decision, config);
72
- case agentshieldShared.ENFORCEMENT_ACTIONS.REDIRECT:
73
- return buildRedirectResponse(request, decision, config, detection);
74
- case agentshieldShared.ENFORCEMENT_ACTIONS.CHALLENGE:
75
- return buildChallengeResponse(request, decision, config, detection);
76
- case agentshieldShared.ENFORCEMENT_ACTIONS.LOG:
77
- console.log("[AgentShield] Policy decision (log):", {
78
- path: request.nextUrl.pathname,
79
- action: decision.action,
80
- reason: decision.reason,
81
- matchType: decision.matchType,
82
- ruleId: decision.ruleId
83
- });
84
- return null;
85
- // Continue to allow
86
- case agentshieldShared.ENFORCEMENT_ACTIONS.ALLOW:
87
- default:
88
- return null;
89
- }
90
- }
91
- var fetcherCache = /* @__PURE__ */ new Map();
92
- function getFetcherCacheKey(config) {
93
- return `${config.apiUrl ?? "default"}:${config.apiKey ?? ""}:${config.cacheTtlSeconds ?? "default"}`;
94
- }
95
- function getPolicyFetcher(config) {
96
- if (!config) {
97
- throw new Error("fetchPolicy config required");
98
- }
99
- const cacheKey = getFetcherCacheKey(config);
100
- let fetcher = fetcherCache.get(cacheKey);
101
- if (!fetcher) {
102
- const fetcherConfig = {
103
- apiBaseUrl: config.apiUrl || "https://kya.vouched.id",
104
- apiKey: config.apiKey,
105
- cacheTtlSeconds: config.cacheTtlSeconds
106
- };
107
- fetcher = agentshieldShared.createPolicyFetcher(fetcherConfig);
108
- fetcherCache.set(cacheKey, fetcher);
109
- }
110
- return fetcher;
111
- }
112
- async function getPolicy(config) {
113
- if (config.policy) {
114
- return agentshieldShared.PolicyConfigSchema.parse({ ...agentshieldShared.DEFAULT_POLICY, ...config.policy });
115
- }
116
- if (config.fetchPolicy) {
117
- try {
118
- const fetcher = getPolicyFetcher(config.fetchPolicy);
119
- return await fetcher.getPolicy(config.fetchPolicy.projectId);
120
- } catch (error) {
121
- if (config.debug) {
122
- console.warn("[AgentShield] Policy fetch failed, using fallback:", error);
123
- }
124
- return agentshieldShared.PolicyConfigSchema.parse({
125
- ...agentshieldShared.DEFAULT_POLICY,
126
- ...config.fallbackPolicy || {}
127
- });
128
- }
129
- }
130
- return agentshieldShared.PolicyConfigSchema.parse(agentshieldShared.DEFAULT_POLICY);
131
- }
132
- async function applyPolicy(request, detection, config) {
133
- try {
134
- const path = request.nextUrl.pathname;
135
- if (config.skipPaths?.some((pattern) => agentshieldShared.matchPath(path, pattern))) {
136
- return null;
137
- }
138
- if (config.includePaths && config.includePaths.length > 0) {
139
- if (!config.includePaths.some((pattern) => agentshieldShared.matchPath(path, pattern))) {
140
- return null;
141
- }
142
- }
143
- const policy = await getPolicy(config);
144
- const context = createContextFromDetection(detection, request);
145
- const decision = agentshieldShared.evaluatePolicy(policy, context);
146
- if (config.onPolicyDecision) {
147
- await config.onPolicyDecision(request, decision, context);
148
- }
149
- return await handlePolicyDecision(request, decision, config, detection);
150
- } catch (error) {
151
- if (config.debug) {
152
- console.error("[AgentShield] Policy evaluation error:", error);
153
- }
154
- if (config.failOpen !== false) {
155
- return null;
156
- }
157
- return server.NextResponse.json(
158
- { error: "Security check failed", code: "POLICY_ERROR" },
159
- { status: 503 }
160
- );
161
- }
162
- }
163
-
164
- Object.defineProperty(exports, "DEFAULT_POLICY", {
165
- enumerable: true,
166
- get: function () { return agentshieldShared.DEFAULT_POLICY; }
167
- });
168
- Object.defineProperty(exports, "ENFORCEMENT_ACTIONS", {
169
- enumerable: true,
170
- get: function () { return agentshieldShared.ENFORCEMENT_ACTIONS; }
171
- });
172
- Object.defineProperty(exports, "createEvaluationContext", {
173
- enumerable: true,
174
- get: function () { return agentshieldShared.createEvaluationContext; }
175
- });
176
- Object.defineProperty(exports, "evaluatePolicy", {
177
- enumerable: true,
178
- get: function () { return agentshieldShared.evaluatePolicy; }
179
- });
180
- exports.applyPolicy = applyPolicy;
181
- exports.buildBlockedResponse = buildBlockedResponse;
182
- exports.buildChallengeResponse = buildChallengeResponse;
183
- exports.buildRedirectResponse = buildRedirectResponse;
184
- exports.createContextFromDetection = createContextFromDetection;
185
- exports.evaluatePolicyForDetection = evaluatePolicyForDetection;
186
- exports.getPolicy = getPolicy;
187
- exports.handlePolicyDecision = handlePolicyDecision;
188
- //# sourceMappingURL=policy.js.map
189
- //# sourceMappingURL=policy.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/policy.ts"],"names":["createEvaluationContext","evaluatePolicy","NextResponse","ENFORCEMENT_ACTIONS","createPolicyFetcher","PolicyConfigSchema","DEFAULT_POLICY","matchPath"],"mappings":";;;;;;AAwJO,SAAS,0BAAA,CACd,WACA,OAAA,EACyB;AACzB,EAAA,OAAOA,yCAAA,CAAwB;AAAA,IAC7B,SAAA,EAAW,UAAU,aAAA,EAAe,IAAA;AAAA,IACpC,SAAA,EAAW,UAAU,aAAA,EAAe,IAAA;AAAA,IACpC,WAAA,EAAa,UAAU,aAAA,EAAe,MAAA;AAAA,IACtC,YAAY,SAAA,CAAU,UAAA;AAAA,IACtB,WAAW,SAAA,CAAU,SAAA;AAAA,IACrB,IAAA,EAAM,QAAQ,OAAA,CAAQ,QAAA;AAAA,IACtB,QAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,iBAAA,EAAmB,UAAU,kBAAA,KAAuB,WAAA;AAAA,IACpD,eAAA,EAAiB,KAAA;AAAA;AAAA,IACjB,SAAA,EAAW,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,YAAY,CAAA,IAAK;AAAA,GACjD,CAAA;AACH;AAKO,SAAS,0BAAA,CACd,SAAA,EACA,OAAA,EACA,MAAA,EACwB;AACxB,EAAA,MAAM,OAAA,GAAU,0BAAA,CAA2B,SAAA,EAAW,OAAO,CAAA;AAC7D,EAAA,OAAO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K,CAAC,YAAYA,2BAAA,CAAU,IAAA,EAAM,OAAO,CAAC,CAAA,EAAG;AACpE,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AAGA,IAAA,MAAM,MAAA,GAAS,MAAM,SAAA,CAAU,MAAM,CAAA;AAGrC,IAAA,MAAM,OAAA,GAAU,0BAAA,CAA2B,SAAA,EAAW,OAAO,CAAA;AAC7D,IAAA,MAAM,QAAA,GAAWN,gCAAA,CAAe,MAAA,EAAQ,OAAO,CAAA;AAG/C,IAAA,IAAI,OAAO,gBAAA,EAAkB;AAC3B,MAAA,MAAM,MAAA,CAAO,gBAAA,CAAiB,OAAA,EAAS,QAAA,EAAU,OAAO,CAAA;AAAA,IAC1D;AAGA,IAAA,OAAO,MAAM,oBAAA,CAAqB,OAAA,EAAS,QAAA,EAAU,QAAQ,SAAS,CAAA;AAAA,EACxE,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,OAAO,KAAA,EAAO;AAChB,MAAA,OAAA,CAAQ,KAAA,CAAM,0CAA0C,KAAK,CAAA;AAAA,IAC/D;AAEA,IAAA,IAAI,MAAA,CAAO,aAAa,KAAA,EAAO;AAC7B,MAAA,OAAO,IAAA;AAAA,IACT;AAGA,IAAA,OAAOC,mBAAA,CAAa,IAAA;AAAA,MAClB,EAAE,KAAA,EAAO,uBAAA,EAAyB,IAAA,EAAM,cAAA,EAAe;AAAA,MACvD,EAAE,QAAQ,GAAA;AAAI,KAChB;AAAA,EACF;AACF","file":"policy.js","sourcesContent":["/**\n * Policy Integration for agentshield-nextjs\n *\n * This module provides policy evaluation support for the Next.js middleware.\n * It can use:\n * - Local policy configuration (static)\n * - Fetched policy from AgentShield API (dynamic with caching)\n * - Fallback/default policies\n *\n * @example\n * ```typescript\n * import { createPolicyMiddleware } from '@kya-os/agentshield-nextjs/policy';\n *\n * export default createPolicyMiddleware({\n * policy: {\n * enabled: true,\n * defaultAction: 'allow',\n * thresholds: { confidenceThreshold: 80, confidenceAction: 'block' },\n * allowList: [{ clientName: 'ChatGPT' }],\n * },\n * });\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server';\nimport {\n evaluatePolicy,\n createEvaluationContext,\n createPolicyFetcher,\n matchPath,\n PolicyFetcher,\n PolicyConfigSchema,\n ENFORCEMENT_ACTIONS,\n DEFAULT_POLICY,\n type PolicyConfig,\n type PolicyEvaluationContext,\n type PolicyEvaluationResult,\n type PolicyFetcherConfig,\n type DetectionResult,\n} from '@kya-os/agentshield-shared';\n\n// Re-export shared policy types for convenience\nexport {\n evaluatePolicy,\n createEvaluationContext,\n type PolicyConfig,\n type PolicyEvaluationContext,\n type PolicyEvaluationResult,\n ENFORCEMENT_ACTIONS,\n DEFAULT_POLICY,\n} from '@kya-os/agentshield-shared';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Policy middleware configuration\n */\nexport interface PolicyMiddlewareConfig {\n /**\n * Local policy configuration (static)\n * If provided, this policy is used instead of fetching from API\n */\n policy?: Partial<PolicyConfig>;\n\n /**\n * Fetch policy from AgentShield API\n * Requires projectId and optionally an apiKey\n */\n fetchPolicy?: {\n /** Project ID to fetch policy for */\n projectId: string;\n /** API base URL (defaults to production) */\n apiUrl?: string;\n /** API key for authentication */\n apiKey?: string;\n /** Cache TTL in seconds (default: 300) */\n cacheTtlSeconds?: number;\n };\n\n /**\n * Fallback policy to use when fetch fails\n * Defaults to DEFAULT_POLICY (allow all)\n */\n fallbackPolicy?: Partial<PolicyConfig>;\n\n /**\n * Custom blocked response\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Default redirect URL for redirect actions\n */\n redirectUrl?: string;\n\n /**\n * Callback when policy decision is made\n */\n onPolicyDecision?: (\n request: NextRequest,\n decision: PolicyEvaluationResult,\n context: PolicyEvaluationContext\n ) => void | Promise<void>;\n\n /**\n * Custom response builder for blocked requests\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: PolicyEvaluationResult\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on policy evaluation errors\n * Default: true (recommended for production)\n */\n failOpen?: boolean;\n\n /**\n * Enable debug logging\n */\n debug?: boolean;\n}\n\n/**\n * Combined middleware configuration with policy support\n */\nexport interface NextJSPolicyMiddlewareConfig extends PolicyMiddlewareConfig {\n /**\n * Paths to skip (in addition to policy excludedPaths)\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides policy includedPaths)\n */\n includePaths?: string[];\n}\n\n// ============================================================================\n// Policy Evaluation Helper\n// ============================================================================\n\n/**\n * Create policy evaluation context from detection result and request\n */\nexport function createContextFromDetection(\n detection: DetectionResult,\n request: NextRequest\n): PolicyEvaluationContext {\n return createEvaluationContext({\n agentType: detection.detectedAgent?.type,\n agentName: detection.detectedAgent?.name,\n agentVendor: detection.detectedAgent?.vendor,\n confidence: detection.confidence,\n riskLevel: detection.riskLevel,\n path: request.nextUrl.pathname,\n method: request.method,\n signatureVerified: detection.verificationMethod === 'signature',\n isAuthenticated: false, // TODO: integrate with auth\n userAgent: request.headers.get('user-agent') || undefined,\n });\n}\n\n/**\n * Evaluate policy for a detection result\n */\nexport function evaluatePolicyForDetection(\n detection: DetectionResult,\n request: NextRequest,\n policy: PolicyConfig\n): PolicyEvaluationResult {\n const context = createContextFromDetection(detection, request);\n return evaluatePolicy(policy, context);\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response based on policy decision\n */\nexport function buildBlockedResponse(\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const response = NextResponse.json(\n {\n error: message,\n code: 'POLICY_BLOCKED',\n reason: decision.reason,\n ruleId: decision.ruleId,\n matchType: decision.matchType,\n },\n { status }\n );\n\n // Add custom headers\n if (config.blockedResponse?.headers) {\n for (const [key, value] of Object.entries(config.blockedResponse.headers)) {\n response.headers.set(key, value);\n }\n }\n\n // Add AgentShield headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n response.headers.set('KYA-Match-Type', decision.matchType);\n\n return response;\n}\n\n/**\n * Build redirect response based on policy decision\n */\nexport function buildRedirectResponse(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): NextResponse {\n const redirectUrl = decision.redirectUrl || config.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with policy info\n url.searchParams.set('reason', decision.reason);\n if (decision.ruleId) {\n url.searchParams.set('ruleId', decision.ruleId);\n }\n const agentName = detection?.detectedAgent?.name;\n if (agentName && !url.searchParams.has('agent')) {\n url.searchParams.set('agent', agentName.toLowerCase());\n }\n\n return NextResponse.redirect(url);\n}\n\n/**\n * Build challenge response (placeholder - future implementation)\n */\nexport function buildChallengeResponse(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): NextResponse {\n // For now, treat challenge as redirect\n // Future: implement CAPTCHA, proof-of-work, etc.\n return buildRedirectResponse(request, decision, config, detection);\n}\n\n// ============================================================================\n// Policy Handler\n// ============================================================================\n\n/**\n * Handle policy decision and return appropriate response\n */\nexport async function handlePolicyDecision(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): Promise<NextResponse | null> {\n switch (decision.action) {\n case ENFORCEMENT_ACTIONS.BLOCK:\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n return buildBlockedResponse(decision, config);\n\n case ENFORCEMENT_ACTIONS.REDIRECT:\n return buildRedirectResponse(request, decision, config, detection);\n\n case ENFORCEMENT_ACTIONS.CHALLENGE:\n return buildChallengeResponse(request, decision, config, detection);\n\n case ENFORCEMENT_ACTIONS.LOG:\n // LOG action always logs - that's its purpose\n // (debug flag controls verbose debugging output, not LOG action behavior)\n console.log('[AgentShield] Policy decision (log):', {\n path: request.nextUrl.pathname,\n action: decision.action,\n reason: decision.reason,\n matchType: decision.matchType,\n ruleId: decision.ruleId,\n });\n return null; // Continue to allow\n\n case ENFORCEMENT_ACTIONS.ALLOW:\n default:\n return null; // Continue\n }\n}\n\n// ============================================================================\n// Policy Fetcher Integration\n// ============================================================================\n\n// Cache fetchers by config to avoid recreating them, but also support\n// different configurations (different apiUrl, apiKey, etc.)\nconst fetcherCache = new Map<string, PolicyFetcher>();\n\n/**\n * Generate a cache key for fetcher config.\n * Uses ?? to distinguish between explicit 0 and undefined values.\n */\nfunction getFetcherCacheKey(config: NonNullable<PolicyMiddlewareConfig['fetchPolicy']>): string {\n return `${config.apiUrl ?? 'default'}:${config.apiKey ?? ''}:${config.cacheTtlSeconds ?? 'default'}`;\n}\n\n/**\n * Get or create policy fetcher for the given config\n */\nfunction getPolicyFetcher(config: PolicyMiddlewareConfig['fetchPolicy']): PolicyFetcher {\n if (!config) {\n throw new Error('fetchPolicy config required');\n }\n\n const cacheKey = getFetcherCacheKey(config);\n let fetcher = fetcherCache.get(cacheKey);\n\n if (!fetcher) {\n const fetcherConfig: PolicyFetcherConfig = {\n apiBaseUrl: config.apiUrl || 'https://kya.vouched.id',\n apiKey: config.apiKey,\n cacheTtlSeconds: config.cacheTtlSeconds,\n };\n fetcher = createPolicyFetcher(fetcherConfig);\n fetcherCache.set(cacheKey, fetcher);\n }\n\n return fetcher;\n}\n\n/**\n * Get policy (local, fetched, or fallback)\n */\nexport async function getPolicy(config: PolicyMiddlewareConfig): Promise<PolicyConfig> {\n // Use local policy if provided\n if (config.policy) {\n return PolicyConfigSchema.parse({ ...DEFAULT_POLICY, ...config.policy });\n }\n\n // Fetch from API if configured\n if (config.fetchPolicy) {\n try {\n const fetcher = getPolicyFetcher(config.fetchPolicy);\n return await fetcher.getPolicy(config.fetchPolicy.projectId);\n } catch (error) {\n if (config.debug) {\n console.warn('[AgentShield] Policy fetch failed, using fallback:', error);\n }\n // Return fallback policy\n return PolicyConfigSchema.parse({\n ...DEFAULT_POLICY,\n ...(config.fallbackPolicy || {}),\n });\n }\n }\n\n // No policy configured - return default (allow all)\n return PolicyConfigSchema.parse(DEFAULT_POLICY);\n}\n\n// ============================================================================\n// Standalone Policy Middleware\n// ============================================================================\n\n/**\n * Apply policy to a detection result\n *\n * This function can be used standalone to evaluate policy after detection.\n * Supports extended config with skipPaths and includePaths for path-based filtering.\n *\n * @example\n * ```typescript\n * const result = await detector.analyze(context);\n * const response = await applyPolicy(request, result, {\n * policy: { thresholds: { confidenceThreshold: 80 } },\n * skipPaths: ['/health', '/api/public/*'],\n * includePaths: ['/api/*'],\n * });\n *\n * if (response) {\n * return response; // Policy blocked the request\n * }\n * ```\n */\nexport async function applyPolicy(\n request: NextRequest,\n detection: DetectionResult,\n config: NextJSPolicyMiddlewareConfig\n): Promise<NextResponse | null> {\n try {\n const path = request.nextUrl.pathname;\n\n // Check skipPaths - if path matches any skip pattern, allow through\n if (config.skipPaths?.some((pattern) => matchPath(path, pattern))) {\n return null; // Skip policy enforcement for this path\n }\n\n // Check includePaths - if defined, path must match at least one pattern\n if (config.includePaths && config.includePaths.length > 0) {\n if (!config.includePaths.some((pattern) => matchPath(path, pattern))) {\n return null; // Path not in included paths, skip policy enforcement\n }\n }\n\n // Get policy\n const policy = await getPolicy(config);\n\n // Create context and evaluate\n const context = createContextFromDetection(detection, request);\n const decision = evaluatePolicy(policy, context);\n\n // Call decision callback if provided\n if (config.onPolicyDecision) {\n await config.onPolicyDecision(request, decision, context);\n }\n\n // Handle decision — pass detection through so redirect can append ?agent=\n return await handlePolicyDecision(request, decision, config, detection);\n } catch (error) {\n if (config.debug) {\n console.error('[AgentShield] Policy evaluation error:', error);\n }\n\n if (config.failOpen !== false) {\n return null; // Allow on error\n }\n\n // Fail closed\n return NextResponse.json(\n { error: 'Security check failed', code: 'POLICY_ERROR' },\n { status: 503 }\n );\n }\n}\n"]}