@kya-os/checkpoint-nextjs 1.10.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 (210) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/README.md +205 -31
  3. package/dist/{adapt.mjs → adapt-BdQ9R7Iw.mjs} +15 -4
  4. package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
  5. package/dist/{adapt.js → adapt-CCSKGjVH.js} +34 -13
  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 -204
  11. package/dist/api-client.d.ts +2 -204
  12. package/dist/api-client.js +19 -18
  13. package/dist/api-client.mjs +20 -16
  14. package/dist/api-client.mjs.map +1 -1
  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-CDSh3TSE.js → api-middleware-Bf3xmM9W.js} +75 -63
  18. package/dist/{api-middleware-CMDRoQik.mjs → api-middleware-C-ngFX_8.mjs} +68 -38
  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 -152
  23. package/dist/api-middleware.d.ts +2 -152
  24. package/dist/api-middleware.js +1 -5
  25. package/dist/api-middleware.mjs +2 -3
  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-Doe0Tn53.d.mts → config-CPP1RV0f.d.mts} +65 -29
  34. package/dist/config-CPP1RV0f.d.mts.map +1 -0
  35. package/dist/{config-CbAg2mze.d.ts → config-DVgOFxJs.d.ts} +66 -30
  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 -10
  49. package/dist/index.d.ts +8 -10
  50. package/dist/index.js +20 -49
  51. package/dist/index.mjs +21 -8
  52. package/dist/index.mjs.map +1 -1
  53. package/dist/middleware-bundler.d.mts +1 -1
  54. package/dist/middleware-bundler.d.mts.map +1 -1
  55. package/dist/middleware-bundler.d.ts +1 -1
  56. package/dist/middleware-bundler.d.ts.map +1 -1
  57. package/dist/middleware-bundler.js +4 -4
  58. package/dist/middleware-bundler.mjs +4 -4
  59. package/dist/middleware-bundler.mjs.map +1 -1
  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 +11 -3
  68. package/dist/middleware-edge.d.mts.map +1 -1
  69. package/dist/middleware-edge.d.ts +11 -3
  70. package/dist/middleware-edge.d.ts.map +1 -1
  71. package/dist/middleware-edge.js +77 -24
  72. package/dist/middleware-edge.mjs +74 -23
  73. package/dist/middleware-edge.mjs.map +1 -1
  74. package/dist/{middleware-node-context-rgnc7UNR.js → middleware-node-context-591KsiYg.js} +8 -7
  75. package/dist/{middleware-node-context-BqPbf-fI.mjs → middleware-node-context-D_ZyUEcA.mjs} +6 -5
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
  77. package/dist/middleware-node.d.mts +12 -3
  78. package/dist/middleware-node.d.mts.map +1 -0
  79. package/dist/middleware-node.d.ts +12 -3
  80. package/dist/middleware-node.d.ts.map +1 -0
  81. package/dist/middleware-node.js +13 -5
  82. package/dist/middleware-node.mjs +13 -5
  83. package/dist/middleware-node.mjs.map +1 -1
  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 +27 -62
  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 -11
  101. package/dist/adapt.d.mts.map +0 -1
  102. package/dist/adapt.d.ts +0 -11
  103. package/dist/adapt.d.ts.map +0 -1
  104. package/dist/adapt.mjs.map +0 -1
  105. package/dist/api-client.d.mts.map +0 -1
  106. package/dist/api-client.d.ts.map +0 -1
  107. package/dist/api-middleware-CMDRoQik.mjs.map +0 -1
  108. package/dist/api-middleware.d.mts.map +0 -1
  109. package/dist/api-middleware.d.ts.map +0 -1
  110. package/dist/composed-policy-BCaNiVHv.d.mts +0 -98
  111. package/dist/composed-policy-BCaNiVHv.d.mts.map +0 -1
  112. package/dist/composed-policy-zzJYNFTb.d.ts +0 -98
  113. package/dist/composed-policy-zzJYNFTb.d.ts.map +0 -1
  114. package/dist/composed-policy.d.mts +0 -2
  115. package/dist/composed-policy.d.ts +0 -2
  116. package/dist/composed-policy.js +0 -136
  117. package/dist/composed-policy.mjs +0 -132
  118. package/dist/composed-policy.mjs.map +0 -1
  119. package/dist/config-CbAg2mze.d.ts.map +0 -1
  120. package/dist/config-Doe0Tn53.d.mts.map +0 -1
  121. package/dist/create-middleware.d.mts +0 -11
  122. package/dist/create-middleware.d.mts.map +0 -1
  123. package/dist/create-middleware.d.ts +0 -11
  124. package/dist/create-middleware.d.ts.map +0 -1
  125. package/dist/create-middleware.js +0 -39
  126. package/dist/create-middleware.mjs +0 -38
  127. package/dist/create-middleware.mjs.map +0 -1
  128. package/dist/edge/index.d.mts +0 -88
  129. package/dist/edge/index.d.mts.map +0 -1
  130. package/dist/edge/index.d.ts +0 -88
  131. package/dist/edge/index.d.ts.map +0 -1
  132. package/dist/edge/index.js +0 -362
  133. package/dist/edge/index.mjs +0 -362
  134. package/dist/edge/index.mjs.map +0 -1
  135. package/dist/edge-runtime-loader.d.mts +0 -49
  136. package/dist/edge-runtime-loader.d.mts.map +0 -1
  137. package/dist/edge-runtime-loader.d.ts +0 -49
  138. package/dist/edge-runtime-loader.d.ts.map +0 -1
  139. package/dist/edge-runtime-loader.js +0 -297
  140. package/dist/edge-runtime-loader.mjs +0 -292
  141. package/dist/edge-runtime-loader.mjs.map +0 -1
  142. package/dist/edge-wasm-middleware.d.mts +0 -43
  143. package/dist/edge-wasm-middleware.d.mts.map +0 -1
  144. package/dist/edge-wasm-middleware.d.ts +0 -43
  145. package/dist/edge-wasm-middleware.d.ts.map +0 -1
  146. package/dist/edge-wasm-middleware.js +0 -37
  147. package/dist/edge-wasm-middleware.mjs +0 -35
  148. package/dist/edge-wasm-middleware.mjs.map +0 -1
  149. package/dist/middleware-core-BYQP9FND.mjs +0 -165
  150. package/dist/middleware-core-BYQP9FND.mjs.map +0 -1
  151. package/dist/middleware-core-D6TijE6P.js +0 -175
  152. package/dist/middleware-node-CE4GevYs.d.ts +0 -20
  153. package/dist/middleware-node-CE4GevYs.d.ts.map +0 -1
  154. package/dist/middleware-node-DtyOuPta.d.mts +0 -20
  155. package/dist/middleware-node-DtyOuPta.d.mts.map +0 -1
  156. package/dist/middleware-node-context-BqPbf-fI.mjs.map +0 -1
  157. package/dist/middleware.d.mts +0 -25
  158. package/dist/middleware.d.mts.map +0 -1
  159. package/dist/middleware.d.ts +0 -25
  160. package/dist/middleware.d.ts.map +0 -1
  161. package/dist/middleware.js +0 -53
  162. package/dist/middleware.mjs +0 -51
  163. package/dist/middleware.mjs.map +0 -1
  164. package/dist/nodejs-wasm-loader.d.mts +0 -42
  165. package/dist/nodejs-wasm-loader.d.mts.map +0 -1
  166. package/dist/nodejs-wasm-loader.d.ts +0 -42
  167. package/dist/nodejs-wasm-loader.d.ts.map +0 -1
  168. package/dist/nodejs-wasm-loader.js +0 -70
  169. package/dist/nodejs-wasm-loader.mjs +0 -66
  170. package/dist/nodejs-wasm-loader.mjs.map +0 -1
  171. package/dist/policy.d.mts +0 -138
  172. package/dist/policy.d.mts.map +0 -1
  173. package/dist/policy.d.ts +0 -138
  174. package/dist/policy.d.ts.map +0 -1
  175. package/dist/policy.js +0 -236
  176. package/dist/policy.mjs +0 -205
  177. package/dist/policy.mjs.map +0 -1
  178. package/dist/session-tracker.d.mts +0 -50
  179. package/dist/session-tracker.d.mts.map +0 -1
  180. package/dist/session-tracker.d.ts +0 -50
  181. package/dist/session-tracker.d.ts.map +0 -1
  182. package/dist/session-tracker.js +0 -148
  183. package/dist/session-tracker.mjs +0 -147
  184. package/dist/session-tracker.mjs.map +0 -1
  185. package/dist/translate.d.mts +0 -48
  186. package/dist/translate.d.mts.map +0 -1
  187. package/dist/translate.d.ts +0 -48
  188. package/dist/translate.d.ts.map +0 -1
  189. package/dist/translate.js +0 -79
  190. package/dist/translate.mjs +0 -79
  191. package/dist/translate.mjs.map +0 -1
  192. package/dist/types-C0SkqLMM.d.mts +0 -102
  193. package/dist/types-C0SkqLMM.d.mts.map +0 -1
  194. package/dist/types-C7DNSCTO.d.ts +0 -102
  195. package/dist/types-C7DNSCTO.d.ts.map +0 -1
  196. package/dist/utils-Cj4XNhIY.mjs +0 -35
  197. package/dist/utils-Cj4XNhIY.mjs.map +0 -1
  198. package/dist/utils-DAisnYnI.js +0 -45
  199. package/dist/wasm-setup.d.mts +0 -47
  200. package/dist/wasm-setup.d.mts.map +0 -1
  201. package/dist/wasm-setup.d.ts +0 -47
  202. package/dist/wasm-setup.d.ts.map +0 -1
  203. package/dist/wasm-setup.js +0 -91
  204. package/dist/wasm-setup.mjs +0 -95
  205. package/dist/wasm-setup.mjs.map +0 -1
  206. package/wasm/agentshield_wasm.d.ts +0 -479
  207. package/wasm/agentshield_wasm.js +0 -1536
  208. package/wasm/agentshield_wasm_bg.wasm +0 -0
  209. package/wasm/package.json +0 -30
  210. package/wasm.d.ts +0 -21
@@ -1,148 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- let _kya_os_checkpoint_shared = require("@kya-os/checkpoint-shared");
3
-
4
- //#region src/session-tracker.ts
5
- var EdgeSessionTracker = class {
6
- config;
7
- constructor(config) {
8
- this.config = {
9
- enabled: config.enabled,
10
- cookieName: config.cookieName || "__agentshield_session",
11
- cookieMaxAge: config.cookieMaxAge || 3600,
12
- encryptionKey: config.encryptionKey || process.env.CHECKPOINT_SECRET || "agentshield-default-key"
13
- };
14
- }
15
- /**
16
- * Track a new AI agent session
17
- */
18
- async track(_request, response, result) {
19
- try {
20
- const detectedName = result.detectedAgent?.name;
21
- const isEnforceable = result.isAgent || result.isAiCrawler || (0, _kya_os_checkpoint_shared.isKnownAiCrawler)(detectedName);
22
- if (!this.config.enabled || !isEnforceable) return response;
23
- const sessionData = {
24
- id: crypto.randomUUID(),
25
- agent: result.detectedAgent?.name || "unknown",
26
- confidence: result.confidence,
27
- detectedAt: Date.now(),
28
- expires: Date.now() + this.config.cookieMaxAge * 1e3
29
- };
30
- const encrypted = await this.encrypt(JSON.stringify(sessionData));
31
- response.cookies.set(this.config.cookieName, encrypted, {
32
- httpOnly: true,
33
- secure: process.env.NODE_ENV === "production",
34
- sameSite: "lax",
35
- maxAge: this.config.cookieMaxAge,
36
- path: "/"
37
- });
38
- return response;
39
- } catch (error) {
40
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to track session:", error);
41
- return response;
42
- }
43
- }
44
- /**
45
- * Check for existing AI agent session
46
- */
47
- async check(request) {
48
- try {
49
- if (!this.config.enabled) return null;
50
- const cookie = request.cookies.get(this.config.cookieName);
51
- if (!cookie?.value) return null;
52
- const decrypted = await this.decrypt(cookie.value);
53
- const session = JSON.parse(decrypted);
54
- if (session.expires < Date.now()) return null;
55
- return session;
56
- } catch (error) {
57
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to check session:", error);
58
- return null;
59
- }
60
- }
61
- /**
62
- * Clear an existing session
63
- */
64
- clear(response) {
65
- try {
66
- response.cookies.delete(this.config.cookieName);
67
- } catch (error) {
68
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to clear session:", error);
69
- }
70
- return response;
71
- }
72
- /**
73
- * Simple encryption using Web Crypto API (Edge-compatible)
74
- */
75
- async encrypt(data) {
76
- try {
77
- const key = this.config.encryptionKey;
78
- const encoded = new TextEncoder().encode(data);
79
- const obfuscated = new Uint8Array(encoded.length);
80
- for (let i = 0; i < encoded.length; i++) obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);
81
- return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(""));
82
- } catch (error) {
83
- return btoa(data);
84
- }
85
- }
86
- /**
87
- * Simple decryption (Edge-compatible)
88
- */
89
- async decrypt(data) {
90
- try {
91
- const key = this.config.encryptionKey;
92
- const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
93
- const deobfuscated = new Uint8Array(decoded.length);
94
- for (let i = 0; i < decoded.length; i++) deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);
95
- return new TextDecoder().decode(deobfuscated);
96
- } catch (error) {
97
- return atob(data);
98
- }
99
- }
100
- };
101
- /**
102
- * Stateless session checker for non-Next.js environments (Express, etc.)
103
- * Uses a combination of headers to identify continued sessions
104
- */
105
- var StatelessSessionChecker = class {
106
- static check(headers) {
107
- try {
108
- const agent = headers["kya-session-agent"];
109
- const confidence = headers["kya-session-confidence"];
110
- const sessionId = headers["kya-session-id"];
111
- if (agent && confidence && sessionId) return {
112
- id: sessionId,
113
- agent,
114
- confidence: parseFloat(confidence),
115
- detectedAt: Date.now(),
116
- expires: Date.now() + 36e5
117
- };
118
- const cookieHeader = headers["cookie"];
119
- if (cookieHeader && cookieHeader.includes("__agentshield_session=")) {
120
- const match = cookieHeader.match(/__agentshield_session=([^;]+)/);
121
- if (match && match[1]) try {
122
- const decoded = atob(match[1]);
123
- return JSON.parse(decoded);
124
- } catch {}
125
- }
126
- return null;
127
- } catch {
128
- return null;
129
- }
130
- }
131
- static setHeaders(response, session) {
132
- try {
133
- if (response.setHeader) {
134
- response.setHeader("KYA-Session-Agent", session.agent);
135
- response.setHeader("KYA-Session-Confidence", session.confidence.toString());
136
- response.setHeader("KYA-Session-Id", session.id);
137
- } else if (response.headers && response.headers.set) {
138
- response.headers.set("kya-session-agent", session.agent);
139
- response.headers.set("kya-session-confidence", session.confidence.toString());
140
- response.headers.set("kya-session-id", session.id);
141
- }
142
- } catch {}
143
- }
144
- };
145
-
146
- //#endregion
147
- exports.EdgeSessionTracker = EdgeSessionTracker;
148
- exports.StatelessSessionChecker = StatelessSessionChecker;
@@ -1,147 +0,0 @@
1
- import { isKnownAiCrawler } from "@kya-os/checkpoint-shared";
2
-
3
- //#region src/session-tracker.ts
4
- var EdgeSessionTracker = class {
5
- config;
6
- constructor(config) {
7
- this.config = {
8
- enabled: config.enabled,
9
- cookieName: config.cookieName || "__agentshield_session",
10
- cookieMaxAge: config.cookieMaxAge || 3600,
11
- encryptionKey: config.encryptionKey || process.env.CHECKPOINT_SECRET || "agentshield-default-key"
12
- };
13
- }
14
- /**
15
- * Track a new AI agent session
16
- */
17
- async track(_request, response, result) {
18
- try {
19
- const detectedName = result.detectedAgent?.name;
20
- const isEnforceable = result.isAgent || result.isAiCrawler || isKnownAiCrawler(detectedName);
21
- if (!this.config.enabled || !isEnforceable) return response;
22
- const sessionData = {
23
- id: crypto.randomUUID(),
24
- agent: result.detectedAgent?.name || "unknown",
25
- confidence: result.confidence,
26
- detectedAt: Date.now(),
27
- expires: Date.now() + this.config.cookieMaxAge * 1e3
28
- };
29
- const encrypted = await this.encrypt(JSON.stringify(sessionData));
30
- response.cookies.set(this.config.cookieName, encrypted, {
31
- httpOnly: true,
32
- secure: process.env.NODE_ENV === "production",
33
- sameSite: "lax",
34
- maxAge: this.config.cookieMaxAge,
35
- path: "/"
36
- });
37
- return response;
38
- } catch (error) {
39
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to track session:", error);
40
- return response;
41
- }
42
- }
43
- /**
44
- * Check for existing AI agent session
45
- */
46
- async check(request) {
47
- try {
48
- if (!this.config.enabled) return null;
49
- const cookie = request.cookies.get(this.config.cookieName);
50
- if (!cookie?.value) return null;
51
- const decrypted = await this.decrypt(cookie.value);
52
- const session = JSON.parse(decrypted);
53
- if (session.expires < Date.now()) return null;
54
- return session;
55
- } catch (error) {
56
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to check session:", error);
57
- return null;
58
- }
59
- }
60
- /**
61
- * Clear an existing session
62
- */
63
- clear(response) {
64
- try {
65
- response.cookies.delete(this.config.cookieName);
66
- } catch (error) {
67
- if (process.env.DEBUG_AGENTSHIELD) console.warn("AgentShield: Failed to clear session:", error);
68
- }
69
- return response;
70
- }
71
- /**
72
- * Simple encryption using Web Crypto API (Edge-compatible)
73
- */
74
- async encrypt(data) {
75
- try {
76
- const key = this.config.encryptionKey;
77
- const encoded = new TextEncoder().encode(data);
78
- const obfuscated = new Uint8Array(encoded.length);
79
- for (let i = 0; i < encoded.length; i++) obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);
80
- return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(""));
81
- } catch (error) {
82
- return btoa(data);
83
- }
84
- }
85
- /**
86
- * Simple decryption (Edge-compatible)
87
- */
88
- async decrypt(data) {
89
- try {
90
- const key = this.config.encryptionKey;
91
- const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
92
- const deobfuscated = new Uint8Array(decoded.length);
93
- for (let i = 0; i < decoded.length; i++) deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);
94
- return new TextDecoder().decode(deobfuscated);
95
- } catch (error) {
96
- return atob(data);
97
- }
98
- }
99
- };
100
- /**
101
- * Stateless session checker for non-Next.js environments (Express, etc.)
102
- * Uses a combination of headers to identify continued sessions
103
- */
104
- var StatelessSessionChecker = class {
105
- static check(headers) {
106
- try {
107
- const agent = headers["kya-session-agent"];
108
- const confidence = headers["kya-session-confidence"];
109
- const sessionId = headers["kya-session-id"];
110
- if (agent && confidence && sessionId) return {
111
- id: sessionId,
112
- agent,
113
- confidence: parseFloat(confidence),
114
- detectedAt: Date.now(),
115
- expires: Date.now() + 36e5
116
- };
117
- const cookieHeader = headers["cookie"];
118
- if (cookieHeader && cookieHeader.includes("__agentshield_session=")) {
119
- const match = cookieHeader.match(/__agentshield_session=([^;]+)/);
120
- if (match && match[1]) try {
121
- const decoded = atob(match[1]);
122
- return JSON.parse(decoded);
123
- } catch {}
124
- }
125
- return null;
126
- } catch {
127
- return null;
128
- }
129
- }
130
- static setHeaders(response, session) {
131
- try {
132
- if (response.setHeader) {
133
- response.setHeader("KYA-Session-Agent", session.agent);
134
- response.setHeader("KYA-Session-Confidence", session.confidence.toString());
135
- response.setHeader("KYA-Session-Id", session.id);
136
- } else if (response.headers && response.headers.set) {
137
- response.headers.set("kya-session-agent", session.agent);
138
- response.headers.set("kya-session-confidence", session.confidence.toString());
139
- response.headers.set("kya-session-id", session.id);
140
- }
141
- } catch {}
142
- }
143
- };
144
-
145
- //#endregion
146
- export { EdgeSessionTracker, StatelessSessionChecker };
147
- //# sourceMappingURL=session-tracker.mjs.map
@@ -1 +0,0 @@
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":";;;AAwBA,IAAa,qBAAb,MAAgC;CAC9B,AAAiB;CAEjB,YAAY,QAA+B;EACzC,KAAK,SAAS;GACZ,SAAS,OAAO;GAChB,YAAY,OAAO,cAAc;GACjC,cAAc,OAAO,gBAAgB;GACrC,eACE,OAAO,iBAAiB,QAAQ,IAAI,qBAAqB;EAC7D;CACF;;;;CAKA,MAAM,MACJ,UACA,UACA,QACuB;EACvB,IAAI;GAOF,MAAM,eAAe,OAAO,eAAe;GAC3C,MAAM,gBAAgB,OAAO,WAAW,OAAO,eAAe,iBAAiB,YAAY;GAC3F,IAAI,CAAC,KAAK,OAAO,WAAW,CAAC,eAC3B,OAAO;GAGT,MAAM,cAA2B;IAC/B,IAAI,OAAO,WAAW;IACtB,OAAO,OAAO,eAAe,QAAQ;IACrC,YAAY,OAAO;IACnB,YAAY,KAAK,IAAI;IACrB,SAAS,KAAK,IAAI,IAAI,KAAK,OAAO,eAAe;GACnD;GAGA,MAAM,YAAY,MAAM,KAAK,QAAQ,KAAK,UAAU,WAAW,CAAC;GAGhE,SAAS,QAAQ,IAAI,KAAK,OAAO,YAAY,WAAW;IACtD,UAAU;IACV,QAAQ,QAAQ,IAAI,aAAa;IACjC,UAAU;IACV,QAAQ,KAAK,OAAO;IACpB,MAAM;GACR,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GAEd,IAAI,QAAQ,IAAI,mBACd,QAAQ,KAAK,yCAAyC,KAAK;GAE7D,OAAO;EACT;CACF;;;;CAKA,MAAM,MAAM,SAAmD;EAC7D,IAAI;GACF,IAAI,CAAC,KAAK,OAAO,SACf,OAAO;GAGT,MAAM,SAAS,QAAQ,QAAQ,IAAI,KAAK,OAAO,UAAU;GACzD,IAAI,CAAC,QAAQ,OACX,OAAO;GAIT,MAAM,YAAY,MAAM,KAAK,QAAQ,OAAO,KAAK;GACjD,MAAM,UAAuB,KAAK,MAAM,SAAS;GAGjD,IAAI,QAAQ,UAAU,KAAK,IAAI,GAC7B,OAAO;GAGT,OAAO;EACT,SAAS,OAAO;GAEd,IAAI,QAAQ,IAAI,mBACd,QAAQ,KAAK,yCAAyC,KAAK;GAE7D,OAAO;EACT;CACF;;;;CAKA,MAAM,UAAsC;EAC1C,IAAI;GACF,SAAS,QAAQ,OAAO,KAAK,OAAO,UAAU;EAChD,SAAS,OAAO;GAEd,IAAI,QAAQ,IAAI,mBACd,QAAQ,KAAK,yCAAyC,KAAK;EAE/D;EACA,OAAO;CACT;;;;CAKA,MAAc,QAAQ,MAA+B;EACnD,IAAI;GAGF,MAAM,MAAM,KAAK,OAAO;GACxB,MAAM,UAAU,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;GAG7C,MAAM,aAAa,IAAI,WAAW,QAAQ,MAAM;GAChD,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,WAAW,MAAM,QAAQ,MAAM,KAAK,IAAI,WAAW,IAAI,IAAI,MAAM;GAInE,OAAO,KAAK,MAAM,KAAK,aAAa,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;EAClF,SAAS,OAAO;GAEd,OAAO,KAAK,IAAI;EAClB;CACF;;;;CAKA,MAAc,QAAQ,MAA+B;EACnD,IAAI;GACF,MAAM,MAAM,KAAK,OAAO;GACxB,MAAM,UAAU,WAAW,KAAK,KAAK,IAAI,IAAI,MAAM,EAAE,WAAW,CAAC,CAAC;GAGlE,MAAM,eAAe,IAAI,WAAW,QAAQ,MAAM;GAClD,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,aAAa,MAAM,QAAQ,MAAM,KAAK,IAAI,WAAW,IAAI,IAAI,MAAM;GAGrE,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,YAAY;EAC9C,SAAS,OAAO;GAEd,OAAO,KAAK,IAAI;EAClB;CACF;AACF;;;;;AAMA,IAAa,0BAAb,MAAqC;CACnC,OAAO,MAAM,SAAqD;EAChE,IAAI;GAEF,MAAM,QAAQ,QAAQ;GACtB,MAAM,aAAa,QAAQ;GAC3B,MAAM,YAAY,QAAQ;GAE1B,IAAI,SAAS,cAAc,WACzB,OAAO;IACL,IAAI;IACJ;IACA,YAAY,WAAW,UAAU;IACjC,YAAY,KAAK,IAAI;IACrB,SAAS,KAAK,IAAI,IAAI;GACxB;GAIF,MAAM,eAAe,QAAQ;GAC7B,IAAI,gBAAgB,aAAa,SAAS,wBAAwB,GAAG;IAEnE,MAAM,QAAQ,aAAa,MAAM,+BAA+B;IAChE,IAAI,SAAS,MAAM,IACjB,IAAI;KACF,MAAM,UAAU,KAAK,MAAM,EAAE;KAC7B,OAAO,KAAK,MAAM,OAAO;IAC3B,QAAQ,CAER;GAEJ;GAEA,OAAO;EACT,QAAQ;GACN,OAAO;EACT;CACF;CAIA,OAAO,WAAW,UAAe,SAA4B;EAC3D,IAAI;GAEF,IAAI,SAAS,WAAW;IACtB,SAAS,UAAU,qBAAqB,QAAQ,KAAK;IACrD,SAAS,UAAU,0BAA0B,QAAQ,WAAW,SAAS,CAAC;IAC1E,SAAS,UAAU,kBAAkB,QAAQ,EAAE;GACjD,OAAO,IAAI,SAAS,WAAW,SAAS,QAAQ,KAAK;IACnD,SAAS,QAAQ,IAAI,qBAAqB,QAAQ,KAAK;IACvD,SAAS,QAAQ,IAAI,0BAA0B,QAAQ,WAAW,SAAS,CAAC;IAC5E,SAAS,QAAQ,IAAI,kBAAkB,QAAQ,EAAE;GACnD;EACF,QAAQ,CAER;CACF;AACF"}
@@ -1,48 +0,0 @@
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
5
- /**
6
- * Options controlling translator side effects.
7
- *
8
- * `drainJsonBody` (default `true`) controls whether the translator
9
- * reads the request body so the orchestrator can extract a KYA-OS
10
- * envelope from `_meta.proof.jws` (the canonical spec-form transport).
11
- *
12
- * Trade-off — body draining consumes the request stream. We use
13
- * `req.clone().text()` so the original `req.body` stream is preserved
14
- * for downstream Next.js handlers. Cloning has memory overhead
15
- * proportional to the body size; for large request bodies (>1 MB) or
16
- * streaming-sensitive routes, set `drainJsonBody: false` and verify
17
- * envelopes via the `KYA-Delegation` header transport instead (the
18
- * legacy form, requires `legacyEnvelopeFallback: true` on
19
- * `withCheckpoint`).
20
- */
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;
31
- }
32
- /**
33
- * Translate a Next.js `NextRequest` into the orchestrator's
34
- * `IncomingHttpLike` shape.
35
- *
36
- * When `opts.drainJsonBody !== false` and the request is JSON, the
37
- * translator clones the request and reads the body into a string so
38
- * the orchestrator's `buildAgentRequest` can extract a
39
- * `_meta.proof.jws` envelope. The original `req.body` stream is
40
- * preserved for downstream handlers via `req.clone()`.
41
- *
42
- * When the body can't be read (drain disabled, non-JSON, or a stream
43
- * error) we pass `body: null` and the orchestrator routes to
44
- * PlainHttp — same behavior as the pre-1.1.0 default.
45
- */
46
- export declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
47
- //#endregion
48
- //# sourceMappingURL=translate.d.mts.map
@@ -1 +0,0 @@
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,48 +0,0 @@
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
5
- /**
6
- * Options controlling translator side effects.
7
- *
8
- * `drainJsonBody` (default `true`) controls whether the translator
9
- * reads the request body so the orchestrator can extract a KYA-OS
10
- * envelope from `_meta.proof.jws` (the canonical spec-form transport).
11
- *
12
- * Trade-off — body draining consumes the request stream. We use
13
- * `req.clone().text()` so the original `req.body` stream is preserved
14
- * for downstream Next.js handlers. Cloning has memory overhead
15
- * proportional to the body size; for large request bodies (>1 MB) or
16
- * streaming-sensitive routes, set `drainJsonBody: false` and verify
17
- * envelopes via the `KYA-Delegation` header transport instead (the
18
- * legacy form, requires `legacyEnvelopeFallback: true` on
19
- * `withCheckpoint`).
20
- */
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;
31
- }
32
- /**
33
- * Translate a Next.js `NextRequest` into the orchestrator's
34
- * `IncomingHttpLike` shape.
35
- *
36
- * When `opts.drainJsonBody !== false` and the request is JSON, the
37
- * translator clones the request and reads the body into a string so
38
- * the orchestrator's `buildAgentRequest` can extract a
39
- * `_meta.proof.jws` envelope. The original `req.body` stream is
40
- * preserved for downstream handlers via `req.clone()`.
41
- *
42
- * When the body can't be read (drain disabled, non-JSON, or a stream
43
- * error) we pass `body: null` and the orchestrator routes to
44
- * PlainHttp — same behavior as the pre-1.1.0 default.
45
- */
46
- export declare function nextRequestToHttpLike(req: NextRequest, opts?: NextRequestToHttpLikeOpts): Promise<IncomingHttpLike>;
47
- //#endregion
48
- //# sourceMappingURL=translate.d.ts.map
@@ -1 +0,0 @@
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 DELETED
@@ -1,79 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- let _kya_os_checkpoint_shared = require("@kya-os/checkpoint-shared");
3
-
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
- */
19
- async function nextRequestToHttpLike(req, opts = {}) {
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
- };
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
- */
40
- async function tryDrainJsonBody(req, opts) {
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
- }
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
- */
57
- function headersToRecord(headers) {
58
- const out = {};
59
- headers.forEach((value, key) => {
60
- out[key.toLowerCase()] = value;
61
- });
62
- return out;
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
- */
69
- function extractRemoteAddress(req, policy) {
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;
76
- }
77
-
78
- //#endregion
79
- exports.nextRequestToHttpLike = nextRequestToHttpLike;
@@ -1,79 +0,0 @@
1
- import { resolveClientIp } from "@kya-os/checkpoint-shared";
2
-
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
- */
18
- async function nextRequestToHttpLike(req, opts = {}) {
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
- };
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
- */
39
- async function tryDrainJsonBody(req, opts) {
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
- }
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
- */
56
- function headersToRecord(headers) {
57
- const out = {};
58
- headers.forEach((value, key) => {
59
- out[key.toLowerCase()] = value;
60
- });
61
- return out;
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
- */
68
- function extractRemoteAddress(req, policy) {
69
- const maybeIp = req.ip;
70
- return resolveClientIp({
71
- headers: req.headers,
72
- frameworkAddress: maybeIp,
73
- policy
74
- }).ip ?? void 0;
75
- }
76
-
77
- //#endregion
78
- export { nextRequestToHttpLike };
79
- //# sourceMappingURL=translate.mjs.map
@@ -1 +0,0 @@
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"}