@kya-os/checkpoint-nextjs 1.9.0 → 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 (153) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/adapt.d.mts +6 -34
  3. package/dist/adapt.d.mts.map +1 -0
  4. package/dist/adapt.d.ts +6 -34
  5. package/dist/adapt.d.ts.map +1 -0
  6. package/dist/adapt.js +78 -51
  7. package/dist/adapt.mjs +77 -48
  8. package/dist/adapt.mjs.map +1 -0
  9. package/dist/api-client.d.mts +150 -159
  10. package/dist/api-client.d.mts.map +1 -0
  11. package/dist/api-client.d.ts +150 -159
  12. package/dist/api-client.d.ts.map +1 -0
  13. package/dist/api-client.js +218 -204
  14. package/dist/api-client.mjs +217 -201
  15. package/dist/api-client.mjs.map +1 -0
  16. package/dist/api-middleware-CDSh3TSE.js +379 -0
  17. package/dist/api-middleware-CMDRoQik.mjs +357 -0
  18. package/dist/api-middleware-CMDRoQik.mjs.map +1 -0
  19. package/dist/api-middleware.d.mts +117 -131
  20. package/dist/api-middleware.d.mts.map +1 -0
  21. package/dist/api-middleware.d.ts +117 -131
  22. package/dist/api-middleware.d.ts.map +1 -0
  23. package/dist/api-middleware.js +8 -527
  24. package/dist/api-middleware.mjs +3 -521
  25. package/dist/composed-policy-BCaNiVHv.d.mts +98 -0
  26. package/dist/composed-policy-BCaNiVHv.d.mts.map +1 -0
  27. package/dist/composed-policy-zzJYNFTb.d.ts +98 -0
  28. package/dist/composed-policy-zzJYNFTb.d.ts.map +1 -0
  29. package/dist/composed-policy.d.mts +2 -115
  30. package/dist/composed-policy.d.ts +2 -115
  31. package/dist/composed-policy.js +122 -89
  32. package/dist/composed-policy.mjs +121 -86
  33. package/dist/composed-policy.mjs.map +1 -0
  34. package/dist/config-CbAg2mze.d.ts +255 -0
  35. package/dist/config-CbAg2mze.d.ts.map +1 -0
  36. package/dist/config-Doe0Tn53.d.mts +255 -0
  37. package/dist/config-Doe0Tn53.d.mts.map +1 -0
  38. package/dist/create-middleware.d.mts +7 -18
  39. package/dist/create-middleware.d.mts.map +1 -0
  40. package/dist/create-middleware.d.ts +7 -18
  41. package/dist/create-middleware.d.ts.map +1 -0
  42. package/dist/create-middleware.js +36 -31
  43. package/dist/create-middleware.mjs +35 -28
  44. package/dist/create-middleware.mjs.map +1 -0
  45. package/dist/edge/index.d.mts +64 -88
  46. package/dist/edge/index.d.mts.map +1 -0
  47. package/dist/edge/index.d.ts +64 -88
  48. package/dist/edge/index.d.ts.map +1 -0
  49. package/dist/edge/index.js +349 -264
  50. package/dist/edge/index.mjs +348 -261
  51. package/dist/edge/index.mjs.map +1 -0
  52. package/dist/edge-runtime-loader.d.mts +37 -65
  53. package/dist/edge-runtime-loader.d.mts.map +1 -0
  54. package/dist/edge-runtime-loader.d.ts +37 -65
  55. package/dist/edge-runtime-loader.d.ts.map +1 -0
  56. package/dist/edge-runtime-loader.js +268 -213
  57. package/dist/edge-runtime-loader.mjs +267 -210
  58. package/dist/edge-runtime-loader.mjs.map +1 -0
  59. package/dist/edge-wasm-middleware.d.mts +27 -46
  60. package/dist/edge-wasm-middleware.d.mts.map +1 -0
  61. package/dist/edge-wasm-middleware.d.ts +27 -46
  62. package/dist/edge-wasm-middleware.d.ts.map +1 -0
  63. package/dist/edge-wasm-middleware.js +26 -15
  64. package/dist/edge-wasm-middleware.mjs +25 -12
  65. package/dist/edge-wasm-middleware.mjs.map +1 -0
  66. package/dist/index.d.mts +10 -17
  67. package/dist/index.d.ts +10 -17
  68. package/dist/index.js +55 -1265
  69. package/dist/index.mjs +16 -1234
  70. package/dist/index.mjs.map +1 -0
  71. package/dist/middleware-bundler.d.mts +6 -12
  72. package/dist/middleware-bundler.d.mts.map +1 -0
  73. package/dist/middleware-bundler.d.ts +6 -12
  74. package/dist/middleware-bundler.d.ts.map +1 -0
  75. package/dist/middleware-bundler.js +12 -350
  76. package/dist/middleware-bundler.mjs +11 -347
  77. package/dist/middleware-bundler.mjs.map +1 -0
  78. package/dist/middleware-core-BYQP9FND.mjs +165 -0
  79. package/dist/middleware-core-BYQP9FND.mjs.map +1 -0
  80. package/dist/middleware-core-D6TijE6P.js +175 -0
  81. package/dist/middleware-edge.d.mts +8 -14
  82. package/dist/middleware-edge.d.mts.map +1 -0
  83. package/dist/middleware-edge.d.ts +8 -14
  84. package/dist/middleware-edge.d.ts.map +1 -0
  85. package/dist/middleware-edge.js +41 -355
  86. package/dist/middleware-edge.mjs +39 -347
  87. package/dist/middleware-edge.mjs.map +1 -0
  88. package/dist/middleware-node-CE4GevYs.d.ts +20 -0
  89. package/dist/middleware-node-CE4GevYs.d.ts.map +1 -0
  90. package/dist/middleware-node-DtyOuPta.d.mts +20 -0
  91. package/dist/middleware-node-DtyOuPta.d.mts.map +1 -0
  92. package/dist/middleware-node-context-BqPbf-fI.mjs +34 -0
  93. package/dist/middleware-node-context-BqPbf-fI.mjs.map +1 -0
  94. package/dist/middleware-node-context-rgnc7UNR.js +38 -0
  95. package/dist/middleware-node.d.mts +3 -27
  96. package/dist/middleware-node.d.ts +3 -27
  97. package/dist/middleware-node.js +13 -351
  98. package/dist/middleware-node.mjs +11 -347
  99. package/dist/middleware-node.mjs.map +1 -0
  100. package/dist/middleware.d.mts +8 -28
  101. package/dist/middleware.d.mts.map +1 -0
  102. package/dist/middleware.d.ts +8 -28
  103. package/dist/middleware.d.ts.map +1 -0
  104. package/dist/middleware.js +43 -9
  105. package/dist/middleware.mjs +42 -6
  106. package/dist/middleware.mjs.map +1 -0
  107. package/dist/nodejs-wasm-loader.d.mts +8 -7
  108. package/dist/nodejs-wasm-loader.d.mts.map +1 -0
  109. package/dist/nodejs-wasm-loader.d.ts +8 -7
  110. package/dist/nodejs-wasm-loader.d.ts.map +1 -0
  111. package/dist/nodejs-wasm-loader.js +53 -19
  112. package/dist/nodejs-wasm-loader.mjs +52 -16
  113. package/dist/nodejs-wasm-loader.mjs.map +1 -0
  114. package/dist/policy.d.mts +86 -110
  115. package/dist/policy.d.mts.map +1 -0
  116. package/dist/policy.d.ts +86 -110
  117. package/dist/policy.d.ts.map +1 -0
  118. package/dist/policy.js +203 -165
  119. package/dist/policy.mjs +183 -152
  120. package/dist/policy.mjs.map +1 -0
  121. package/dist/session-tracker.d.mts +42 -47
  122. package/dist/session-tracker.d.mts.map +1 -0
  123. package/dist/session-tracker.d.ts +42 -47
  124. package/dist/session-tracker.d.ts.map +1 -0
  125. package/dist/session-tracker.js +141 -165
  126. package/dist/session-tracker.mjs +140 -162
  127. package/dist/session-tracker.mjs.map +1 -0
  128. package/dist/translate.d.mts +17 -32
  129. package/dist/translate.d.mts.map +1 -0
  130. package/dist/translate.d.ts +17 -32
  131. package/dist/translate.d.ts.map +1 -0
  132. package/dist/translate.js +69 -34
  133. package/dist/translate.mjs +68 -31
  134. package/dist/translate.mjs.map +1 -0
  135. package/dist/types-C0SkqLMM.d.mts +102 -0
  136. package/dist/types-C0SkqLMM.d.mts.map +1 -0
  137. package/dist/types-C7DNSCTO.d.ts +102 -0
  138. package/dist/types-C7DNSCTO.d.ts.map +1 -0
  139. package/dist/utils-Cj4XNhIY.mjs +35 -0
  140. package/dist/utils-Cj4XNhIY.mjs.map +1 -0
  141. package/dist/utils-DAisnYnI.js +45 -0
  142. package/dist/wasm-setup.d.mts +6 -5
  143. package/dist/wasm-setup.d.mts.map +1 -0
  144. package/dist/wasm-setup.d.ts +6 -5
  145. package/dist/wasm-setup.d.ts.map +1 -0
  146. package/dist/wasm-setup.js +82 -113
  147. package/dist/wasm-setup.mjs +85 -108
  148. package/dist/wasm-setup.mjs.map +1 -0
  149. package/package.json +8 -8
  150. package/dist/config-CleTeeoW.d.mts +0 -233
  151. package/dist/config-XMOIkxFN.d.ts +0 -233
  152. package/dist/types-Chgi5TFC.d.mts +0 -105
  153. package/dist/types-Chgi5TFC.d.ts +0 -105
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-tracker.mjs","names":[],"sources":["../src/session-tracker.ts"],"sourcesContent":["/**\n * Edge-compatible session tracking for AI agents\n * Uses cookie-based storage to work in Edge Runtime\n */\n\nimport type { NextRequest, NextResponse } from 'next/server';\nimport { isKnownAiCrawler } from '@kya-os/checkpoint-shared';\nimport type { DetectionDetail } from '@kya-os/checkpoint-shared';\n\nexport interface SessionData {\n id: string;\n agent: string;\n confidence: number;\n detectedAt: number;\n expires: number;\n}\n\nexport interface SessionTrackingConfig {\n enabled: boolean;\n cookieName?: string;\n cookieMaxAge?: number; // in seconds\n encryptionKey?: string;\n}\n\nexport class EdgeSessionTracker {\n private readonly config: Required<SessionTrackingConfig>;\n\n constructor(config: SessionTrackingConfig) {\n this.config = {\n enabled: config.enabled,\n cookieName: config.cookieName || '__agentshield_session',\n cookieMaxAge: config.cookieMaxAge || 3600, // 1 hour default\n encryptionKey:\n config.encryptionKey || process.env.CHECKPOINT_SECRET || 'agentshield-default-key',\n };\n }\n\n /**\n * Track a new AI agent session\n */\n async track(\n _request: NextRequest,\n response: NextResponse,\n result: DetectionDetail\n ): Promise<NextResponse> {\n try {\n // Three-signal predicate (restored from PR's narrowed\n // `!result.isAgent` check — cursor caught that crawlers arriving\n // with `isAgent: false` + `isAiCrawler: true` or only identifying\n // via known crawler name were silently dropped from tracking).\n // Mirrors the legacy `shouldEnforce()` predicate inline since\n // Phase-D.8b retires the shared helper.\n const detectedName = result.detectedAgent?.name;\n const isEnforceable = result.isAgent || result.isAiCrawler || isKnownAiCrawler(detectedName);\n if (!this.config.enabled || !isEnforceable) {\n return response;\n }\n\n const sessionData: SessionData = {\n id: crypto.randomUUID(),\n agent: result.detectedAgent?.name || 'unknown',\n confidence: result.confidence,\n detectedAt: Date.now(),\n expires: Date.now() + this.config.cookieMaxAge * 1000,\n };\n\n // Encrypt session data for security\n const encrypted = await this.encrypt(JSON.stringify(sessionData));\n\n // Set secure httpOnly cookie\n response.cookies.set(this.config.cookieName, encrypted, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n maxAge: this.config.cookieMaxAge,\n path: '/',\n });\n\n return response;\n } catch (error) {\n // Fail gracefully - log error but don't break request\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to track session:', error);\n }\n return response;\n }\n }\n\n /**\n * Check for existing AI agent session\n */\n async check(request: NextRequest): Promise<SessionData | null> {\n try {\n if (!this.config.enabled) {\n return null;\n }\n\n const cookie = request.cookies.get(this.config.cookieName);\n if (!cookie?.value) {\n return null;\n }\n\n // Decrypt and parse session data\n const decrypted = await this.decrypt(cookie.value);\n const session: SessionData = JSON.parse(decrypted);\n\n // Check if session is expired\n if (session.expires < Date.now()) {\n return null;\n }\n\n return session;\n } catch (error) {\n // Fail gracefully - invalid or corrupted session\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to check session:', error);\n }\n return null;\n }\n }\n\n /**\n * Clear an existing session\n */\n clear(response: NextResponse): NextResponse {\n try {\n response.cookies.delete(this.config.cookieName);\n } catch (error) {\n // Fail gracefully\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to clear session:', error);\n }\n }\n return response;\n }\n\n /**\n * Simple encryption using Web Crypto API (Edge-compatible)\n */\n private async encrypt(data: string): Promise<string> {\n try {\n // For Edge Runtime, use simple base64 encoding with obfuscation\n // In production, consider using Web Crypto API subtle.encrypt()\n const key = this.config.encryptionKey;\n const encoded = new TextEncoder().encode(data);\n\n // Simple XOR obfuscation\n const obfuscated = new Uint8Array(encoded.length);\n for (let i = 0; i < encoded.length; i++) {\n obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);\n }\n\n // Convert to base64\n return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(''));\n } catch (error) {\n // Fallback to simple base64 if encryption fails\n return btoa(data);\n }\n }\n\n /**\n * Simple decryption (Edge-compatible)\n */\n private async decrypt(data: string): Promise<string> {\n try {\n const key = this.config.encryptionKey;\n const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));\n\n // Reverse XOR obfuscation\n const deobfuscated = new Uint8Array(decoded.length);\n for (let i = 0; i < decoded.length; i++) {\n deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);\n }\n\n return new TextDecoder().decode(deobfuscated);\n } catch (error) {\n // Fallback to simple base64 if decryption fails\n return atob(data);\n }\n }\n}\n\n/**\n * Stateless session checker for non-Next.js environments (Express, etc.)\n * Uses a combination of headers to identify continued sessions\n */\nexport class StatelessSessionChecker {\n static check(headers: Record<string, string>): SessionData | null {\n try {\n // Check for session headers (set by previous response)\n const agent = headers['kya-session-agent'];\n const confidence = headers['kya-session-confidence'];\n const sessionId = headers['kya-session-id'];\n\n if (agent && confidence && sessionId) {\n return {\n id: sessionId,\n agent,\n confidence: parseFloat(confidence),\n detectedAt: Date.now(),\n expires: Date.now() + 3600000, // 1 hour\n };\n }\n\n // Check for cookie-based session (if cookies are parsed)\n const cookieHeader = headers['cookie'];\n if (cookieHeader && cookieHeader.includes('__agentshield_session=')) {\n // Simple cookie parsing\n const match = cookieHeader.match(/__agentshield_session=([^;]+)/);\n if (match && match[1]) {\n try {\n const decoded = atob(match[1]);\n return JSON.parse(decoded);\n } catch {\n // Invalid session data\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- published\n // signature; narrowing it is a breaking change, deferred to a major.\n static setHeaders(response: any, session: SessionData): void {\n try {\n // Set session headers for stateless tracking\n if (response.setHeader) {\n response.setHeader('KYA-Session-Agent', session.agent);\n response.setHeader('KYA-Session-Confidence', session.confidence.toString());\n response.setHeader('KYA-Session-Id', session.id);\n } else if (response.headers && response.headers.set) {\n response.headers.set('kya-session-agent', session.agent);\n response.headers.set('kya-session-confidence', session.confidence.toString());\n response.headers.set('kya-session-id', session.id);\n }\n } catch {\n // Fail gracefully\n }\n }\n}\n"],"mappings":"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"}
@@ -1,22 +1,7 @@
1
- import { NextRequest } from 'next/server';
2
- import { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';
3
- import { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';
4
-
5
- /**
6
- * D.2 — `NextRequest` → `IncomingHttpLike` translator.
7
- *
8
- * The host wrapper's *only* job on the inbound path: take Next.js's
9
- * native request shape and produce the transport-agnostic
10
- * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification
11
- * logic, zero adapter calls, zero engine I/O.
12
- *
13
- * Shared between the Node-runtime and Edge-runtime entries. Next.js
14
- * `NextRequest` is the same shape in both runtimes — `req.headers` is
15
- * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is
16
- * a getter (only present in some deployment surfaces; forwarding headers
17
- * are considered only when the caller selects a matching trust policy).
18
- */
19
-
1
+ import { IncomingHttpLike } from "@kya-os/checkpoint-wasm-runtime/orchestrator";
2
+ import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared";
3
+ import { NextRequest } from "next/server";
4
+ //#region src/translate.d.ts
20
5
  /**
21
6
  * Options controlling translator side effects.
22
7
  *
@@ -33,16 +18,16 @@ import { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';
33
18
  * legacy form, requires `legacyEnvelopeFallback: true` on
34
19
  * `withCheckpoint`).
35
20
  */
36
- interface NextRequestToHttpLikeOpts {
37
- /**
38
- * Read the request body when `content-type` is `application/json` so
39
- * the orchestrator can extract a KYA-OS envelope from
40
- * `_meta.proof.jws`. Default `true`. Set `false` for streaming
41
- * middlewares that can't tolerate the clone/read overhead.
42
- */
43
- drainJsonBody?: boolean;
44
- /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */
45
- clientIpPolicy?: ClientIpTrustPolicy;
21
+ export interface NextRequestToHttpLikeOpts {
22
+ /**
23
+ * Read the request body when `content-type` is `application/json` so
24
+ * the orchestrator can extract a KYA-OS envelope from
25
+ * `_meta.proof.jws`. Default `true`. Set `false` for streaming
26
+ * middlewares that can't tolerate the clone/read overhead.
27
+ */
28
+ drainJsonBody?: boolean;
29
+ /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */
30
+ clientIpPolicy?: ClientIpTrustPolicy;
46
31
  }
47
32
  /**
48
33
  * Translate a Next.js `NextRequest` into the orchestrator's
@@ -58,6 +43,6 @@ interface NextRequestToHttpLikeOpts {
58
43
  * error) we pass `body: null` and the orchestrator routes to
59
44
  * PlainHttp — same behavior as the pre-1.1.0 default.
60
45
  */
61
- declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
62
-
63
- export { type NextRequestToHttpLikeOpts, nextRequestToHttpLike };
46
+ export declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
47
+ //#endregion
48
+ //# sourceMappingURL=translate.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate.d.mts","names":[],"sources":["../src/translate.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBAoCiB;;;;;;;EAOf;;EAEA,iBAAiB;;;;;;;;;;;;;;;;wBAiBG,sBACpB,KAAK,aACL,OAAM,4BACL,QAAQ"}
@@ -1,22 +1,7 @@
1
- import { NextRequest } from 'next/server';
2
- import { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';
3
- import { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';
4
-
5
- /**
6
- * D.2 — `NextRequest` → `IncomingHttpLike` translator.
7
- *
8
- * The host wrapper's *only* job on the inbound path: take Next.js's
9
- * native request shape and produce the transport-agnostic
10
- * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification
11
- * logic, zero adapter calls, zero engine I/O.
12
- *
13
- * Shared between the Node-runtime and Edge-runtime entries. Next.js
14
- * `NextRequest` is the same shape in both runtimes — `req.headers` is
15
- * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is
16
- * a getter (only present in some deployment surfaces; forwarding headers
17
- * are considered only when the caller selects a matching trust policy).
18
- */
19
-
1
+ import { NextRequest } from "next/server";
2
+ import { IncomingHttpLike } from "@kya-os/checkpoint-wasm-runtime/orchestrator";
3
+ import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared";
4
+ //#region src/translate.d.ts
20
5
  /**
21
6
  * Options controlling translator side effects.
22
7
  *
@@ -33,16 +18,16 @@ import { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';
33
18
  * legacy form, requires `legacyEnvelopeFallback: true` on
34
19
  * `withCheckpoint`).
35
20
  */
36
- interface NextRequestToHttpLikeOpts {
37
- /**
38
- * Read the request body when `content-type` is `application/json` so
39
- * the orchestrator can extract a KYA-OS envelope from
40
- * `_meta.proof.jws`. Default `true`. Set `false` for streaming
41
- * middlewares that can't tolerate the clone/read overhead.
42
- */
43
- drainJsonBody?: boolean;
44
- /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */
45
- clientIpPolicy?: ClientIpTrustPolicy;
21
+ export interface NextRequestToHttpLikeOpts {
22
+ /**
23
+ * Read the request body when `content-type` is `application/json` so
24
+ * the orchestrator can extract a KYA-OS envelope from
25
+ * `_meta.proof.jws`. Default `true`. Set `false` for streaming
26
+ * middlewares that can't tolerate the clone/read overhead.
27
+ */
28
+ drainJsonBody?: boolean;
29
+ /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */
30
+ clientIpPolicy?: ClientIpTrustPolicy;
46
31
  }
47
32
  /**
48
33
  * Translate a Next.js `NextRequest` into the orchestrator's
@@ -58,6 +43,6 @@ interface NextRequestToHttpLikeOpts {
58
43
  * error) we pass `body: null` and the orchestrator routes to
59
44
  * PlainHttp — same behavior as the pre-1.1.0 default.
60
45
  */
61
- declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
62
-
63
- export { type NextRequestToHttpLikeOpts, nextRequestToHttpLike };
46
+ export declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
47
+ //#endregion
48
+ //# sourceMappingURL=translate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate.d.ts","names":[],"sources":["../src/translate.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBAoCiB;;;;;;;EAOf;;EAEA,iBAAiB;;;;;;;;;;;;;;;;wBAiBG,sBACpB,KAAK,aACL,OAAM,4BACL,QAAQ"}
package/dist/translate.js CHANGED
@@ -1,44 +1,79 @@
1
- 'use strict';
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _kya_os_checkpoint_shared = require("@kya-os/checkpoint-shared");
2
3
 
3
- var checkpointShared = require('@kya-os/checkpoint-shared');
4
-
5
- // src/translate.ts
4
+ //#region src/translate.ts
5
+ /**
6
+ * Translate a Next.js `NextRequest` into the orchestrator's
7
+ * `IncomingHttpLike` shape.
8
+ *
9
+ * When `opts.drainJsonBody !== false` and the request is JSON, the
10
+ * translator clones the request and reads the body into a string so
11
+ * the orchestrator's `buildAgentRequest` can extract a
12
+ * `_meta.proof.jws` envelope. The original `req.body` stream is
13
+ * preserved for downstream handlers via `req.clone()`.
14
+ *
15
+ * When the body can't be read (drain disabled, non-JSON, or a stream
16
+ * error) we pass `body: null` and the orchestrator routes to
17
+ * PlainHttp — same behavior as the pre-1.1.0 default.
18
+ */
6
19
  async function nextRequestToHttpLike(req, opts = {}) {
7
- const url = new URL(req.url);
8
- const body = await tryDrainJsonBody(req, opts);
9
- return {
10
- method: req.method,
11
- // Path + query only — orchestrator's URL parsing expects no scheme/host.
12
- url: url.pathname + url.search,
13
- headers: headersToRecord(req.headers),
14
- body,
15
- remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
16
- };
20
+ const url = new URL(req.url);
21
+ const body = await tryDrainJsonBody(req, opts);
22
+ return {
23
+ method: req.method,
24
+ url: url.pathname + url.search,
25
+ headers: headersToRecord(req.headers),
26
+ body,
27
+ remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
28
+ };
17
29
  }
30
+ /**
31
+ * Read the request body as a UTF-8 string when JSON and the caller
32
+ * has opted in (default). Returns `null` on any failure — the
33
+ * orchestrator handles `null` as "no body present" (→ PlainHttp).
34
+ *
35
+ * Clone-first means the original `req.body` ReadableStream stays
36
+ * unconsumed and downstream handlers can re-read it. Without the
37
+ * clone, calling `req.text()` in middleware would block any route
38
+ * handler that needs the body.
39
+ */
18
40
  async function tryDrainJsonBody(req, opts) {
19
- if (opts.drainJsonBody === false) return null;
20
- const contentType = req.headers.get("content-type") ?? "";
21
- if (!contentType.toLowerCase().includes("application/json")) return null;
22
- try {
23
- return await req.clone().text();
24
- } catch {
25
- return null;
26
- }
41
+ if (opts.drainJsonBody === false) return null;
42
+ if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
43
+ try {
44
+ return await req.clone().text();
45
+ } catch {
46
+ return null;
47
+ }
27
48
  }
49
+ /**
50
+ * Convert a `Headers` instance into a lowercase-keyed plain object.
51
+ * HTTP header names are case-insensitive (RFC 9110 § 5.1); the
52
+ * orchestrator does case-sensitive lookups, so we normalise to
53
+ * lowercase here. Multi-value headers (Set-Cookie, Accept) are
54
+ * surfaced as their `Headers.get()` view — a single string with
55
+ * comma-joined values, matching what other host adapters produce.
56
+ */
28
57
  function headersToRecord(headers) {
29
- const out = {};
30
- headers.forEach((value, key) => {
31
- out[key.toLowerCase()] = value;
32
- });
33
- return out;
58
+ const out = {};
59
+ headers.forEach((value, key) => {
60
+ out[key.toLowerCase()] = value;
61
+ });
62
+ return out;
34
63
  }
64
+ /**
65
+ * Pull the originating client IP through the caller-selected deployment
66
+ * trust policy. Forwarding headers are never trusted merely because they are
67
+ * present on the request.
68
+ */
35
69
  function extractRemoteAddress(req, policy) {
36
- const maybeIp = req.ip;
37
- return checkpointShared.resolveClientIp({
38
- headers: req.headers,
39
- frameworkAddress: maybeIp,
40
- policy
41
- }).ip ?? void 0;
70
+ const maybeIp = req.ip;
71
+ return (0, _kya_os_checkpoint_shared.resolveClientIp)({
72
+ headers: req.headers,
73
+ frameworkAddress: maybeIp,
74
+ policy
75
+ }).ip ?? void 0;
42
76
  }
43
77
 
44
- exports.nextRequestToHttpLike = nextRequestToHttpLike;
78
+ //#endregion
79
+ exports.nextRequestToHttpLike = nextRequestToHttpLike;
@@ -1,42 +1,79 @@
1
- import { resolveClientIp } from '@kya-os/checkpoint-shared';
1
+ import { resolveClientIp } from "@kya-os/checkpoint-shared";
2
2
 
3
- // src/translate.ts
3
+ //#region src/translate.ts
4
+ /**
5
+ * Translate a Next.js `NextRequest` into the orchestrator's
6
+ * `IncomingHttpLike` shape.
7
+ *
8
+ * When `opts.drainJsonBody !== false` and the request is JSON, the
9
+ * translator clones the request and reads the body into a string so
10
+ * the orchestrator's `buildAgentRequest` can extract a
11
+ * `_meta.proof.jws` envelope. The original `req.body` stream is
12
+ * preserved for downstream handlers via `req.clone()`.
13
+ *
14
+ * When the body can't be read (drain disabled, non-JSON, or a stream
15
+ * error) we pass `body: null` and the orchestrator routes to
16
+ * PlainHttp — same behavior as the pre-1.1.0 default.
17
+ */
4
18
  async function nextRequestToHttpLike(req, opts = {}) {
5
- const url = new URL(req.url);
6
- const body = await tryDrainJsonBody(req, opts);
7
- return {
8
- method: req.method,
9
- // Path + query only — orchestrator's URL parsing expects no scheme/host.
10
- url: url.pathname + url.search,
11
- headers: headersToRecord(req.headers),
12
- body,
13
- remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
14
- };
19
+ const url = new URL(req.url);
20
+ const body = await tryDrainJsonBody(req, opts);
21
+ return {
22
+ method: req.method,
23
+ url: url.pathname + url.search,
24
+ headers: headersToRecord(req.headers),
25
+ body,
26
+ remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
27
+ };
15
28
  }
29
+ /**
30
+ * Read the request body as a UTF-8 string when JSON and the caller
31
+ * has opted in (default). Returns `null` on any failure — the
32
+ * orchestrator handles `null` as "no body present" (→ PlainHttp).
33
+ *
34
+ * Clone-first means the original `req.body` ReadableStream stays
35
+ * unconsumed and downstream handlers can re-read it. Without the
36
+ * clone, calling `req.text()` in middleware would block any route
37
+ * handler that needs the body.
38
+ */
16
39
  async function tryDrainJsonBody(req, opts) {
17
- if (opts.drainJsonBody === false) return null;
18
- const contentType = req.headers.get("content-type") ?? "";
19
- if (!contentType.toLowerCase().includes("application/json")) return null;
20
- try {
21
- return await req.clone().text();
22
- } catch {
23
- return null;
24
- }
40
+ if (opts.drainJsonBody === false) return null;
41
+ if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) return null;
42
+ try {
43
+ return await req.clone().text();
44
+ } catch {
45
+ return null;
46
+ }
25
47
  }
48
+ /**
49
+ * Convert a `Headers` instance into a lowercase-keyed plain object.
50
+ * HTTP header names are case-insensitive (RFC 9110 § 5.1); the
51
+ * orchestrator does case-sensitive lookups, so we normalise to
52
+ * lowercase here. Multi-value headers (Set-Cookie, Accept) are
53
+ * surfaced as their `Headers.get()` view — a single string with
54
+ * comma-joined values, matching what other host adapters produce.
55
+ */
26
56
  function headersToRecord(headers) {
27
- const out = {};
28
- headers.forEach((value, key) => {
29
- out[key.toLowerCase()] = value;
30
- });
31
- return out;
57
+ const out = {};
58
+ headers.forEach((value, key) => {
59
+ out[key.toLowerCase()] = value;
60
+ });
61
+ return out;
32
62
  }
63
+ /**
64
+ * Pull the originating client IP through the caller-selected deployment
65
+ * trust policy. Forwarding headers are never trusted merely because they are
66
+ * present on the request.
67
+ */
33
68
  function extractRemoteAddress(req, policy) {
34
- const maybeIp = req.ip;
35
- return resolveClientIp({
36
- headers: req.headers,
37
- frameworkAddress: maybeIp,
38
- policy
39
- }).ip ?? void 0;
69
+ const maybeIp = req.ip;
70
+ return resolveClientIp({
71
+ headers: req.headers,
72
+ frameworkAddress: maybeIp,
73
+ policy
74
+ }).ip ?? void 0;
40
75
  }
41
76
 
77
+ //#endregion
42
78
  export { nextRequestToHttpLike };
79
+ //# sourceMappingURL=translate.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate.mjs","names":[],"sources":["../src/translate.ts"],"sourcesContent":["/**\n * D.2 — `NextRequest` → `IncomingHttpLike` translator.\n *\n * The host wrapper's *only* job on the inbound path: take Next.js's\n * native request shape and produce the transport-agnostic\n * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification\n * logic, zero adapter calls, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. Next.js\n * `NextRequest` is the same shape in both runtimes — `req.headers` is\n * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is\n * a getter (only present in some deployment surfaces; forwarding headers\n * are considered only when the caller selects a matching trust policy).\n */\n\nimport type { NextRequest } from 'next/server';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport { resolveClientIp, type ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\n/**\n * Options controlling translator side effects.\n *\n * `drainJsonBody` (default `true`) controls whether the translator\n * reads the request body so the orchestrator can extract a KYA-OS\n * envelope from `_meta.proof.jws` (the canonical spec-form transport).\n *\n * Trade-off — body draining consumes the request stream. We use\n * `req.clone().text()` so the original `req.body` stream is preserved\n * for downstream Next.js handlers. Cloning has memory overhead\n * proportional to the body size; for large request bodies (>1 MB) or\n * streaming-sensitive routes, set `drainJsonBody: false` and verify\n * envelopes via the `KYA-Delegation` header transport instead (the\n * legacy form, requires `legacyEnvelopeFallback: true` on\n * `withCheckpoint`).\n */\nexport interface NextRequestToHttpLikeOpts {\n /**\n * Read the request body when `content-type` is `application/json` so\n * the orchestrator can extract a KYA-OS envelope from\n * `_meta.proof.jws`. Default `true`. Set `false` for streaming\n * middlewares that can't tolerate the clone/read overhead.\n */\n drainJsonBody?: boolean;\n /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */\n clientIpPolicy?: ClientIpTrustPolicy;\n}\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * When `opts.drainJsonBody !== false` and the request is JSON, the\n * translator clones the request and reads the body into a string so\n * the orchestrator's `buildAgentRequest` can extract a\n * `_meta.proof.jws` envelope. The original `req.body` stream is\n * preserved for downstream handlers via `req.clone()`.\n *\n * When the body can't be read (drain disabled, non-JSON, or a stream\n * error) we pass `body: null` and the orchestrator routes to\n * PlainHttp — same behavior as the pre-1.1.0 default.\n */\nexport async function nextRequestToHttpLike(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<IncomingHttpLike> {\n const url = new URL(req.url);\n const body = await tryDrainJsonBody(req, opts);\n return {\n method: req.method,\n // Path + query only — orchestrator's URL parsing expects no scheme/host.\n url: url.pathname + url.search,\n headers: headersToRecord(req.headers),\n body,\n remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: 'direct' }),\n };\n}\n\n/**\n * Read the request body as a UTF-8 string when JSON and the caller\n * has opted in (default). Returns `null` on any failure — the\n * orchestrator handles `null` as \"no body present\" (→ PlainHttp).\n *\n * Clone-first means the original `req.body` ReadableStream stays\n * unconsumed and downstream handlers can re-read it. Without the\n * clone, calling `req.text()` in middleware would block any route\n * handler that needs the body.\n */\nasync function tryDrainJsonBody(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts\n): Promise<string | null> {\n if (opts.drainJsonBody === false) return null;\n const contentType = req.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().includes('application/json')) return null;\n try {\n return await req.clone().text();\n } catch {\n // Body unreadable (stream errored, content-length mismatch, etc.).\n // Falling through to null routes the request as PlainHttp —\n // identical behavior to the pre-1.1.0 default.\n return null;\n }\n}\n\n/**\n * Convert a `Headers` instance into a lowercase-keyed plain object.\n * HTTP header names are case-insensitive (RFC 9110 § 5.1); the\n * orchestrator does case-sensitive lookups, so we normalise to\n * lowercase here. Multi-value headers (Set-Cookie, Accept) are\n * surfaced as their `Headers.get()` view — a single string with\n * comma-joined values, matching what other host adapters produce.\n */\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value;\n });\n return out;\n}\n\n/**\n * Pull the originating client IP through the caller-selected deployment\n * trust policy. Forwarding headers are never trusted merely because they are\n * present on the request.\n */\nfunction extractRemoteAddress(req: NextRequest, policy: ClientIpTrustPolicy): string | undefined {\n const maybeIp = (req as unknown as { ip?: string }).ip;\n return (\n resolveClientIp({\n headers: req.headers,\n frameworkAddress: maybeIp,\n policy,\n }).ip ?? undefined\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8DA,eAAsB,sBACpB,KACA,OAAkC,CAAC,GACR;CAC3B,MAAM,MAAM,IAAI,IAAI,IAAI,GAAG;CAC3B,MAAM,OAAO,MAAM,iBAAiB,KAAK,IAAI;CAC7C,OAAO;EACL,QAAQ,IAAI;EAEZ,KAAK,IAAI,WAAW,IAAI;EACxB,SAAS,gBAAgB,IAAI,OAAO;EACpC;EACA,eAAe,qBAAqB,KAAK,KAAK,kBAAkB,EAAE,UAAU,SAAS,CAAC;CACxF;AACF;;;;;;;;;;;AAYA,eAAe,iBACb,KACA,MACwB;CACxB,IAAI,KAAK,kBAAkB,OAAO,OAAO;CAEzC,IAAI,EADgB,IAAI,QAAQ,IAAI,cAAc,KAAK,GACvC,CAAC,YAAY,CAAC,CAAC,SAAS,kBAAkB,GAAG,OAAO;CACpE,IAAI;EACF,OAAO,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;CAChC,QAAQ;EAIN,OAAO;CACT;AACF;;;;;;;;;AAUA,SAAS,gBAAgB,SAA0C;CACjE,MAAM,MAA8B,CAAC;CACrC,QAAQ,SAAS,OAAO,QAAQ;EAC9B,IAAI,IAAI,YAAY,KAAK;CAC3B,CAAC;CACD,OAAO;AACT;;;;;;AAOA,SAAS,qBAAqB,KAAkB,QAAiD;CAC/F,MAAM,UAAW,IAAmC;CACpD,OACE,gBAAgB;EACd,SAAS,IAAI;EACb,kBAAkB;EAClB;CACF,CAAC,CAAC,CAAC,MAAM;AAEb"}
@@ -0,0 +1,102 @@
1
+ import { AgentShieldConfig, DetectionResult } from "@kya-os/checkpoint-shared";
2
+ import { NextRequest, NextResponse } from "next/server";
3
+ import { CheckpointEvents } from "@kya-os/checkpoint";
4
+ //#region src/types.d.ts
5
+ /**
6
+ * Next.js middleware configuration
7
+ */
8
+ interface NextJSMiddlewareConfig extends Partial<AgentShieldConfig> {
9
+ /**
10
+ * Action to take when an agent is detected
11
+ */
12
+ onAgentDetected?: 'block' | 'redirect' | 'rewrite' | 'allow' | 'log';
13
+ /**
14
+ * Custom handler for agent detection
15
+ * @deprecated Use 'events' instead. Will be removed in v1.0.0
16
+ */
17
+ onDetection?: (req: NextRequest, result: DetectionResult) => NextResponse | Promise<NextResponse> | void | Promise<void>;
18
+ /**
19
+ * Event handlers for detection events
20
+ */
21
+ events?: Partial<CheckpointEvents>;
22
+ /**
23
+ * Path patterns to skip detection
24
+ */
25
+ skipPaths?: string[] | RegExp[];
26
+ /**
27
+ * Response when blocking agents
28
+ */
29
+ blockedResponse?: {
30
+ status: number;
31
+ message: string;
32
+ headers?: Record<string, string>;
33
+ };
34
+ /**
35
+ * Redirect URL when redirecting detected agents
36
+ */
37
+ redirectUrl?: string;
38
+ /**
39
+ * Rewrite URL when rewriting requests from detected agents
40
+ */
41
+ rewriteUrl?: string;
42
+ /**
43
+ * Confidence threshold for agent detection
44
+ */
45
+ confidenceThreshold?: number;
46
+ /**
47
+ * Enable WASM for enhanced detection
48
+ */
49
+ enableWasm?: boolean;
50
+ /**
51
+ * Session tracking configuration
52
+ */
53
+ sessionTracking?: {
54
+ /**
55
+ * Enable session tracking
56
+ */
57
+ enabled: boolean;
58
+ /**
59
+ * Cookie name for session storage
60
+ * Default: '__agentshield_session'
61
+ */
62
+ cookieName?: string;
63
+ /**
64
+ * Cookie max age in seconds
65
+ * Default: 3600 (1 hour)
66
+ */
67
+ cookieMaxAge?: number;
68
+ /**
69
+ * Encryption key for session data
70
+ * Default: Uses CHECKPOINT_SECRET env var or default key
71
+ */
72
+ encryptionKey?: string;
73
+ };
74
+ }
75
+ /**
76
+ * Extended NextRequest with AgentShield data
77
+ */
78
+ interface AgentShieldRequest extends NextRequest {
79
+ agentShield?: {
80
+ result?: DetectionResult;
81
+ skipped: boolean;
82
+ session?: {
83
+ id: string;
84
+ agent: string;
85
+ confidence: number;
86
+ detectedAt: number;
87
+ expires: number;
88
+ };
89
+ };
90
+ }
91
+ /**
92
+ * Detection context for hooks
93
+ */
94
+ interface DetectionContext {
95
+ result: DetectionResult;
96
+ request: NextRequest;
97
+ userAgent?: string;
98
+ ip?: string;
99
+ }
100
+ //#endregion
101
+ export { DetectionContext as n, NextJSMiddlewareConfig as r, AgentShieldRequest as t };
102
+ //# sourceMappingURL=types-C0SkqLMM.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-C0SkqLMM.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;UAWiB,+BAA+B,QAAQ;;;;EAItD;;;;;EAMA,eACE,KAAK,aACL,QAAQ,oBACL,eAAe,QAAQ,uBAAuB;;;;EAKnD,SAAS,QAAQ;;;;EAKjB,uBAAuB;;;;EAKvB;IACE;IACA;IACA,UAAU;;;;;EAMZ;;;;EAKA;;;;EAKA;;;;EAKA;;;;EAKA;;;;IAIE;;;;;IAMA;;;;;IAMA;;;;;IAMA;;;;;;UAOa,2BAA2B;EAC1C;IACE,SAAS;IACT;IACA;MACE;MACA;MACA;MACA;MACA;;;;;;;UAQW;EACf,QAAQ;EACR,SAAS;EACT;EACA"}
@@ -0,0 +1,102 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { AgentShieldConfig, DetectionResult } from "@kya-os/checkpoint-shared";
3
+ import { CheckpointEvents } from "@kya-os/checkpoint";
4
+ //#region src/types.d.ts
5
+ /**
6
+ * Next.js middleware configuration
7
+ */
8
+ interface NextJSMiddlewareConfig extends Partial<AgentShieldConfig> {
9
+ /**
10
+ * Action to take when an agent is detected
11
+ */
12
+ onAgentDetected?: 'block' | 'redirect' | 'rewrite' | 'allow' | 'log';
13
+ /**
14
+ * Custom handler for agent detection
15
+ * @deprecated Use 'events' instead. Will be removed in v1.0.0
16
+ */
17
+ onDetection?: (req: NextRequest, result: DetectionResult) => NextResponse | Promise<NextResponse> | void | Promise<void>;
18
+ /**
19
+ * Event handlers for detection events
20
+ */
21
+ events?: Partial<CheckpointEvents>;
22
+ /**
23
+ * Path patterns to skip detection
24
+ */
25
+ skipPaths?: string[] | RegExp[];
26
+ /**
27
+ * Response when blocking agents
28
+ */
29
+ blockedResponse?: {
30
+ status: number;
31
+ message: string;
32
+ headers?: Record<string, string>;
33
+ };
34
+ /**
35
+ * Redirect URL when redirecting detected agents
36
+ */
37
+ redirectUrl?: string;
38
+ /**
39
+ * Rewrite URL when rewriting requests from detected agents
40
+ */
41
+ rewriteUrl?: string;
42
+ /**
43
+ * Confidence threshold for agent detection
44
+ */
45
+ confidenceThreshold?: number;
46
+ /**
47
+ * Enable WASM for enhanced detection
48
+ */
49
+ enableWasm?: boolean;
50
+ /**
51
+ * Session tracking configuration
52
+ */
53
+ sessionTracking?: {
54
+ /**
55
+ * Enable session tracking
56
+ */
57
+ enabled: boolean;
58
+ /**
59
+ * Cookie name for session storage
60
+ * Default: '__agentshield_session'
61
+ */
62
+ cookieName?: string;
63
+ /**
64
+ * Cookie max age in seconds
65
+ * Default: 3600 (1 hour)
66
+ */
67
+ cookieMaxAge?: number;
68
+ /**
69
+ * Encryption key for session data
70
+ * Default: Uses CHECKPOINT_SECRET env var or default key
71
+ */
72
+ encryptionKey?: string;
73
+ };
74
+ }
75
+ /**
76
+ * Extended NextRequest with AgentShield data
77
+ */
78
+ interface AgentShieldRequest extends NextRequest {
79
+ agentShield?: {
80
+ result?: DetectionResult;
81
+ skipped: boolean;
82
+ session?: {
83
+ id: string;
84
+ agent: string;
85
+ confidence: number;
86
+ detectedAt: number;
87
+ expires: number;
88
+ };
89
+ };
90
+ }
91
+ /**
92
+ * Detection context for hooks
93
+ */
94
+ interface DetectionContext {
95
+ result: DetectionResult;
96
+ request: NextRequest;
97
+ userAgent?: string;
98
+ ip?: string;
99
+ }
100
+ //#endregion
101
+ export { DetectionContext as n, NextJSMiddlewareConfig as r, AgentShieldRequest as t };
102
+ //# sourceMappingURL=types-C7DNSCTO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-C7DNSCTO.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;UAWiB,+BAA+B,QAAQ;;;;EAItD;;;;;EAMA,eACE,KAAK,aACL,QAAQ,oBACL,eAAe,QAAQ,uBAAuB;;;;EAKnD,SAAS,QAAQ;;;;EAKjB,uBAAuB;;;;EAKvB;IACE;IACA;IACA,UAAU;;;;;EAMZ;;;;EAKA;;;;EAKA;;;;EAKA;;;;EAKA;;;;IAIE;;;;;IAMA;;;;;IAMA;;;;;IAMA;;;;;;UAOa,2BAA2B;EAC1C;IACE,SAAS;IACT;IACA;MACE;MACA;MACA;MACA;MACA;;;;;;;UAQW;EACf,QAAQ;EACR,SAAS;EACT;EACA"}
@@ -0,0 +1,35 @@
1
+ import { resolveClientIp } from "@kya-os/checkpoint-shared";
2
+
3
+ //#region src/utils.ts
4
+ /**
5
+ * Extract client IP address from a NextRequest.
6
+ * In Next.js 15+, the `ip` property was removed from NextRequest.
7
+ * This function uses headers to determine the client IP.
8
+ *
9
+ * @param request - The NextRequest object
10
+ * @returns The client IP address or undefined if not available
11
+ */
12
+ function getClientIp(request, policy = { platform: "direct" }) {
13
+ const frameworkAddress = request.ip;
14
+ return resolveClientIp({
15
+ headers: request.headers,
16
+ frameworkAddress,
17
+ policy
18
+ }).ip ?? void 0;
19
+ }
20
+ /**
21
+ * Safely extract the hostname from a URL string.
22
+ * Returns a friendly fallback when parsing fails so UX copy doesn't leak
23
+ * "undefined" or similar to end users.
24
+ */
25
+ function safeHostname(url) {
26
+ try {
27
+ return new URL(url).hostname;
28
+ } catch {
29
+ return "this site";
30
+ }
31
+ }
32
+
33
+ //#endregion
34
+ export { safeHostname as n, getClientIp as t };
35
+ //# sourceMappingURL=utils-Cj4XNhIY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-Cj4XNhIY.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Utility functions for agentshield-nextjs\n */\n\nimport type { NextRequest } from 'next/server';\nimport { resolveClientIp, type ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\n/**\n * Extract client IP address from a NextRequest.\n * In Next.js 15+, the `ip` property was removed from NextRequest.\n * This function uses headers to determine the client IP.\n *\n * @param request - The NextRequest object\n * @returns The client IP address or undefined if not available\n */\nexport function getClientIp(\n request: NextRequest,\n policy: ClientIpTrustPolicy = { platform: 'direct' }\n): string | undefined {\n const frameworkAddress = (request as unknown as { ip?: string }).ip;\n return resolveClientIp({ headers: request.headers, frameworkAddress, policy }).ip ?? undefined;\n}\n\n/**\n * Safely extract the hostname from a URL string.\n * Returns a friendly fallback when parsing fails so UX copy doesn't leak\n * \"undefined\" or similar to end users.\n */\nexport function safeHostname(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return 'this site';\n }\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,YACd,SACA,SAA8B,EAAE,UAAU,SAAS,GAC/B;CACpB,MAAM,mBAAoB,QAAuC;CACjE,OAAO,gBAAgB;EAAE,SAAS,QAAQ;EAAS;EAAkB;CAAO,CAAC,CAAC,CAAC,MAAM;AACvF;;;;;;AAOA,SAAgB,aAAa,KAAqB;CAChD,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF"}