@kya-os/checkpoint-nextjs 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +322 -0
- package/README.md +205 -31
- package/dist/adapt-BdQ9R7Iw.mjs +97 -0
- package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
- package/dist/adapt-CCSKGjVH.js +107 -0
- package/dist/api-client-JHOrRUA_.d.mts +222 -0
- package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
- package/dist/api-client-JHOrRUA_.d.ts +222 -0
- package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
- package/dist/api-client.d.mts +2 -213
- package/dist/api-client.d.ts +2 -213
- package/dist/api-client.js +221 -206
- package/dist/api-client.mjs +222 -202
- package/dist/api-client.mjs.map +1 -0
- package/dist/api-middleware-BWjokNis.d.mts +131 -0
- package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
- package/dist/api-middleware-Bf3xmM9W.js +391 -0
- package/dist/api-middleware-C-ngFX_8.mjs +387 -0
- package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
- package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
- package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
- package/dist/api-middleware.d.mts +2 -166
- package/dist/api-middleware.d.ts +2 -166
- package/dist/api-middleware.js +3 -526
- package/dist/api-middleware.mjs +2 -521
- package/dist/cedar-wasm.d.mts +20 -0
- package/dist/cedar-wasm.d.mts.map +1 -0
- package/dist/cedar-wasm.d.ts +19 -0
- package/dist/cedar-wasm.d.ts.map +1 -0
- package/dist/cedar-wasm.js +24 -0
- package/dist/cedar-wasm.mjs +23 -0
- package/dist/cedar-wasm.mjs.map +1 -0
- package/dist/config-CPP1RV0f.d.mts +291 -0
- package/dist/config-CPP1RV0f.d.mts.map +1 -0
- package/dist/config-DVgOFxJs.d.ts +291 -0
- package/dist/config-DVgOFxJs.d.ts.map +1 -0
- package/dist/engine-wasm.d.mts +20 -0
- package/dist/engine-wasm.d.mts.map +1 -0
- package/dist/engine-wasm.d.ts +19 -0
- package/dist/engine-wasm.d.ts.map +1 -0
- package/dist/engine-wasm.js +24 -0
- package/dist/engine-wasm.mjs +23 -0
- package/dist/engine-wasm.mjs.map +1 -0
- package/dist/index-edge.d.mts +8 -0
- package/dist/index-edge.d.ts +8 -0
- package/dist/index-edge.js +14 -0
- package/dist/index-edge.mjs +7 -0
- package/dist/index.d.mts +8 -17
- package/dist/index.d.ts +8 -17
- package/dist/index.js +36 -1275
- package/dist/index.mjs +29 -1234
- package/dist/index.mjs.map +1 -0
- package/dist/middleware-bundler.d.mts +6 -12
- package/dist/middleware-bundler.d.mts.map +1 -0
- package/dist/middleware-bundler.d.ts +6 -12
- package/dist/middleware-bundler.d.ts.map +1 -0
- package/dist/middleware-bundler.js +12 -350
- package/dist/middleware-bundler.mjs +11 -347
- package/dist/middleware-bundler.mjs.map +1 -0
- package/dist/middleware-core-B0jf5_Hm.mjs +264 -0
- package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
- package/dist/middleware-core-Bol44X9C.d.ts +17 -0
- package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
- package/dist/middleware-core-CMc-2QkU.js +274 -0
- package/dist/middleware-core-DycsbHUd.d.mts +17 -0
- package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
- package/dist/middleware-edge.d.mts +16 -14
- package/dist/middleware-edge.d.mts.map +1 -0
- package/dist/middleware-edge.d.ts +16 -14
- package/dist/middleware-edge.d.ts.map +1 -0
- package/dist/middleware-edge.js +94 -355
- package/dist/middleware-edge.mjs +90 -347
- package/dist/middleware-edge.mjs.map +1 -0
- package/dist/middleware-node-context-591KsiYg.js +39 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs +35 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
- package/dist/middleware-node.d.mts +10 -25
- package/dist/middleware-node.d.mts.map +1 -0
- package/dist/middleware-node.d.ts +10 -25
- package/dist/middleware-node.d.ts.map +1 -0
- package/dist/middleware-node.js +21 -351
- package/dist/middleware-node.mjs +19 -347
- package/dist/middleware-node.mjs.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
- package/dist/posture-outcome-DddsJtL8.js +25 -0
- package/dist/public-api-CYsHrTQI.d.ts +5 -0
- package/dist/public-api-DkG7pRE0.d.mts +5 -0
- package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
- package/dist/utils-Cnwg0VrY.mjs +88 -0
- package/dist/utils-Cnwg0VrY.mjs.map +1 -0
- package/dist/utils-dyFxqlFI.js +104 -0
- package/package.json +31 -66
- package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
- package/bin/setup-edge-wasm.js +0 -513
- package/dist/adapt.d.mts +0 -39
- package/dist/adapt.d.ts +0 -39
- package/dist/adapt.js +0 -59
- package/dist/adapt.mjs +0 -57
- package/dist/composed-policy.d.mts +0 -115
- package/dist/composed-policy.d.ts +0 -115
- package/dist/composed-policy.js +0 -103
- package/dist/composed-policy.mjs +0 -97
- package/dist/config-CleTeeoW.d.mts +0 -233
- package/dist/config-XMOIkxFN.d.ts +0 -233
- package/dist/create-middleware.d.mts +0 -22
- package/dist/create-middleware.d.ts +0 -22
- package/dist/create-middleware.js +0 -34
- package/dist/create-middleware.mjs +0 -31
- package/dist/edge/index.d.mts +0 -112
- package/dist/edge/index.d.ts +0 -112
- package/dist/edge/index.js +0 -277
- package/dist/edge/index.mjs +0 -275
- package/dist/edge-runtime-loader.d.mts +0 -77
- package/dist/edge-runtime-loader.d.ts +0 -77
- package/dist/edge-runtime-loader.js +0 -242
- package/dist/edge-runtime-loader.mjs +0 -235
- package/dist/edge-wasm-middleware.d.mts +0 -62
- package/dist/edge-wasm-middleware.d.ts +0 -62
- package/dist/edge-wasm-middleware.js +0 -26
- package/dist/edge-wasm-middleware.mjs +0 -22
- package/dist/middleware.d.mts +0 -45
- package/dist/middleware.d.ts +0 -45
- package/dist/middleware.js +0 -19
- package/dist/middleware.mjs +0 -15
- package/dist/nodejs-wasm-loader.d.mts +0 -41
- package/dist/nodejs-wasm-loader.d.ts +0 -41
- package/dist/nodejs-wasm-loader.js +0 -36
- package/dist/nodejs-wasm-loader.mjs +0 -30
- package/dist/policy.d.mts +0 -162
- package/dist/policy.d.ts +0 -162
- package/dist/policy.js +0 -198
- package/dist/policy.mjs +0 -174
- package/dist/session-tracker.d.mts +0 -55
- package/dist/session-tracker.d.ts +0 -55
- package/dist/session-tracker.js +0 -172
- package/dist/session-tracker.mjs +0 -169
- package/dist/translate.d.mts +0 -63
- package/dist/translate.d.ts +0 -63
- package/dist/translate.js +0 -44
- package/dist/translate.mjs +0 -42
- package/dist/types-Chgi5TFC.d.mts +0 -105
- package/dist/types-Chgi5TFC.d.ts +0 -105
- package/dist/wasm-setup.d.mts +0 -46
- package/dist/wasm-setup.d.ts +0 -46
- package/dist/wasm-setup.js +0 -122
- package/dist/wasm-setup.mjs +0 -118
- package/wasm/agentshield_wasm.d.ts +0 -479
- package/wasm/agentshield_wasm.js +0 -1536
- package/wasm/agentshield_wasm_bg.wasm +0 -0
- package/wasm/package.json +0 -30
- package/wasm.d.ts +0 -21
package/dist/api-client.mjs
CHANGED
|
@@ -1,213 +1,233 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { n as relayHeaders } from "./utils-Cnwg0VrY.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/api-client.ts
|
|
4
|
+
const DEFAULT_BASE_URL = "https://kya.vouched.id";
|
|
5
|
+
const EDGE_DETECT_URL = "https://detect.checkpoint-gateway.ai";
|
|
6
|
+
const DEFAULT_TIMEOUT = 5e3;
|
|
7
|
+
/**
|
|
8
|
+
* Checkpoint API Client
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* const client = new CheckpointApiClient({
|
|
13
|
+
* apiKey: process.env.CHECKPOINT_API_KEY!,
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* const result = await client.enforce({
|
|
17
|
+
* headers: Object.fromEntries(request.headers),
|
|
18
|
+
* path: request.nextUrl.pathname,
|
|
19
|
+
* method: request.method,
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* if (result.decision.action === 'block') {
|
|
23
|
+
* return new Response('Access denied', { status: 403 });
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
5
27
|
var CheckpointApiClient = class {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
clearTimeout(timeoutId);
|
|
160
|
-
throw error;
|
|
161
|
-
}
|
|
162
|
-
} catch (error) {
|
|
163
|
-
if (this.debug) {
|
|
164
|
-
console.error("[Checkpoint] Log detection failed:", error);
|
|
165
|
-
}
|
|
166
|
-
throw error;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
28
|
+
apiKey;
|
|
29
|
+
baseUrl;
|
|
30
|
+
useEdge;
|
|
31
|
+
timeout;
|
|
32
|
+
debug;
|
|
33
|
+
constructor(config) {
|
|
34
|
+
if (!config.apiKey) throw new Error("Checkpoint API key is required");
|
|
35
|
+
this.apiKey = config.apiKey;
|
|
36
|
+
this.useEdge = config.useEdge !== false;
|
|
37
|
+
this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);
|
|
38
|
+
this.timeout = config.timeout || DEFAULT_TIMEOUT;
|
|
39
|
+
this.debug = config.debug || false;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Call the enforce API to check if a request should be allowed
|
|
43
|
+
*/
|
|
44
|
+
async enforce(input) {
|
|
45
|
+
const startTime = Date.now();
|
|
46
|
+
try {
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
49
|
+
try {
|
|
50
|
+
const endpoint = this.useEdge ? `${this.baseUrl}/__detect/enforce` : `${this.baseUrl}/api/v1/enforce`;
|
|
51
|
+
const response = await fetch(endpoint, {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers: {
|
|
54
|
+
"Content-Type": "application/json",
|
|
55
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
56
|
+
"X-Request-ID": input.requestId || crypto.randomUUID()
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
...input,
|
|
60
|
+
headers: input.headers && relayHeaders(input.headers)
|
|
61
|
+
}),
|
|
62
|
+
signal: controller.signal
|
|
63
|
+
});
|
|
64
|
+
clearTimeout(timeoutId);
|
|
65
|
+
const data = await response.json();
|
|
66
|
+
if (this.debug) console.log("[Checkpoint] Enforce response:", {
|
|
67
|
+
status: response.status,
|
|
68
|
+
action: data.data?.decision.action,
|
|
69
|
+
processingTimeMs: Date.now() - startTime
|
|
70
|
+
});
|
|
71
|
+
if (!response.ok) return {
|
|
72
|
+
success: false,
|
|
73
|
+
error: {
|
|
74
|
+
code: `HTTP_${response.status}`,
|
|
75
|
+
message: data.error?.message || `HTTP error: ${response.status}`
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
return data;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
clearTimeout(timeoutId);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
85
|
+
if (this.debug) console.warn("[Checkpoint] Request timed out");
|
|
86
|
+
return {
|
|
87
|
+
success: false,
|
|
88
|
+
error: {
|
|
89
|
+
code: "TIMEOUT",
|
|
90
|
+
message: `Request timed out after ${this.timeout}ms`
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
if (this.debug) console.error("[Checkpoint] Request failed:", error);
|
|
95
|
+
return {
|
|
96
|
+
success: false,
|
|
97
|
+
error: {
|
|
98
|
+
code: "NETWORK_ERROR",
|
|
99
|
+
message: error instanceof Error ? error.message : "Network request failed"
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Quick check - returns just the action without full response parsing
|
|
106
|
+
* Useful for very fast middleware that just needs allow/block. On an API
|
|
107
|
+
* error the action is `block` (fail-closed) with `error` set.
|
|
108
|
+
*/
|
|
109
|
+
async quickCheck(input) {
|
|
110
|
+
const result = await this.enforce(input);
|
|
111
|
+
if (!result.success || !result.data) return {
|
|
112
|
+
action: "block",
|
|
113
|
+
error: result.error?.message
|
|
114
|
+
};
|
|
115
|
+
return { action: result.data.decision.action };
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Check if this client is using edge detection (Gateway Worker)
|
|
119
|
+
*/
|
|
120
|
+
isUsingEdge() {
|
|
121
|
+
return this.useEdge;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Log a detection result to the Checkpoint database.
|
|
125
|
+
* Use after Gateway Worker detection to persist results.
|
|
126
|
+
* Fire-and-forget - returns immediately without waiting for DB write.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* // After receiving Gateway response
|
|
131
|
+
* if (client.isUsingEdge() && response.data?.detection) {
|
|
132
|
+
* client.logDetection({
|
|
133
|
+
* detection: response.data.detection,
|
|
134
|
+
* context: { userAgent, ipAddress, path, url, method }
|
|
135
|
+
* }).catch(err => console.error('Log failed:', err));
|
|
136
|
+
* }
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
async logDetection(input) {
|
|
140
|
+
const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
|
|
141
|
+
try {
|
|
142
|
+
const controller = new AbortController();
|
|
143
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
144
|
+
try {
|
|
145
|
+
const response = await fetch(logEndpoint, {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers: {
|
|
148
|
+
"Content-Type": "application/json",
|
|
149
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
150
|
+
},
|
|
151
|
+
body: JSON.stringify({
|
|
152
|
+
detection: {
|
|
153
|
+
isAgent: input.detection.isAgent,
|
|
154
|
+
confidence: input.detection.confidence,
|
|
155
|
+
agentName: input.detection.agentName,
|
|
156
|
+
agentType: input.detection.agentType,
|
|
157
|
+
detectionClass: input.detection.detectionClass,
|
|
158
|
+
verificationMethod: input.detection.verificationMethod,
|
|
159
|
+
reasons: input.detection.reasons,
|
|
160
|
+
detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
|
|
161
|
+
},
|
|
162
|
+
context: input.context,
|
|
163
|
+
source: input.source || "gateway",
|
|
164
|
+
enforcement: input.enforcement,
|
|
165
|
+
engine: input.engine,
|
|
166
|
+
sdk: input.sdk
|
|
167
|
+
}),
|
|
168
|
+
signal: controller.signal
|
|
169
|
+
});
|
|
170
|
+
clearTimeout(timeoutId);
|
|
171
|
+
if (!response.ok && this.debug) console.warn("[Checkpoint] Log detection returned non-2xx:", response.status);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
clearTimeout(timeoutId);
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (this.debug) console.error("[Checkpoint] Log detection failed:", error);
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
169
181
|
};
|
|
170
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Create a cached client instance for a resolved configuration.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```typescript
|
|
187
|
+
* // In middleware.ts
|
|
188
|
+
* import { getCheckpointApiClient } from '@kya-os/checkpoint-nextjs';
|
|
189
|
+
*
|
|
190
|
+
* const client = getCheckpointApiClient();
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
const clientInstances = /* @__PURE__ */ new Map();
|
|
171
194
|
function resolveClientConfig(config) {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
// Default to edge detection unless explicitly disabled
|
|
182
|
-
useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
|
|
183
|
-
timeout: config?.timeout,
|
|
184
|
-
debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
|
|
185
|
-
};
|
|
195
|
+
const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;
|
|
196
|
+
if (!apiKey) throw new Error("Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config.");
|
|
197
|
+
return {
|
|
198
|
+
apiKey,
|
|
199
|
+
baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,
|
|
200
|
+
useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
|
|
201
|
+
timeout: config?.timeout,
|
|
202
|
+
debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
|
|
203
|
+
};
|
|
186
204
|
}
|
|
187
205
|
function clientCacheKey(config) {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
206
|
+
return JSON.stringify([
|
|
207
|
+
config.apiKey,
|
|
208
|
+
config.baseUrl ?? "",
|
|
209
|
+
config.useEdge,
|
|
210
|
+
config.timeout ?? DEFAULT_TIMEOUT,
|
|
211
|
+
config.debug
|
|
212
|
+
]);
|
|
195
213
|
}
|
|
196
214
|
function getCheckpointApiClient(config) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
215
|
+
const resolvedConfig = resolveClientConfig(config);
|
|
216
|
+
const key = clientCacheKey(resolvedConfig);
|
|
217
|
+
let clientInstance = clientInstances.get(key);
|
|
218
|
+
if (!clientInstance) {
|
|
219
|
+
clientInstance = new CheckpointApiClient(resolvedConfig);
|
|
220
|
+
clientInstances.set(key, clientInstance);
|
|
221
|
+
}
|
|
222
|
+
return clientInstance;
|
|
205
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Reset the singleton client (useful for testing)
|
|
226
|
+
*/
|
|
206
227
|
function resetCheckpointApiClient() {
|
|
207
|
-
|
|
228
|
+
clientInstances.clear();
|
|
208
229
|
}
|
|
209
|
-
var AgentShieldClient = CheckpointApiClient;
|
|
210
|
-
var getAgentShieldClient = getCheckpointApiClient;
|
|
211
|
-
var resetAgentShieldClient = resetCheckpointApiClient;
|
|
212
230
|
|
|
213
|
-
|
|
231
|
+
//#endregion
|
|
232
|
+
export { CheckpointApiClient, getCheckpointApiClient, resetCheckpointApiClient };
|
|
233
|
+
//# sourceMappingURL=api-client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client.mjs","names":[],"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * Checkpoint API Client\n *\n * Lightweight client for calling the Checkpoint enforce API from middleware.\n * Designed for Edge Runtime compatibility (no Node.js-specific APIs).\n */\n\nimport type { DetectionDetail, EnforcementAction, EngineInfo } from '@kya-os/checkpoint-shared';\nimport { relayHeaders } from './utils';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * API client configuration\n */\nexport interface CheckpointApiClientConfig {\n /** API key for authentication */\n apiKey: string;\n /** API base URL (defaults to production) */\n baseUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * @default true\n */\n useEdge?: boolean;\n /** Request timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Enforcement action — re-exported from `@kya-os/checkpoint-shared`\n * so consumers of this package can keep importing it from the same\n * place. The canonical 6-value union is defined in\n * `packages/checkpoint-shared/src/policy/constants.ts`. `'instruct'`\n * tells the middleware to emit a 401 with a KYA-OS Link header\n * pointing the agent at a connect/consent URL.\n */\nexport type { EnforcementAction };\n\n/**\n * Enforcement decision from the API\n */\nexport interface EnforcementDecision {\n action: EnforcementAction;\n reason: string;\n isAgent: boolean;\n confidence: number;\n agentName?: string;\n agentType?: string;\n redirectUrl?: string;\n message?: string;\n metadata?: {\n policyVersion?: string;\n signatureVerified?: boolean;\n denyListMatch?: {\n clientDid?: string;\n agentDid?: string;\n clientName?: string;\n reason?: string;\n };\n rateLimit?: {\n limit?: number;\n retryAfterSeconds?: number;\n wouldBlock?: boolean;\n skipped?: 'no_client_ip';\n };\n };\n}\n\n/**\n * Detection detail (optional in response)\n */\nexport type ApiDetectionDetail = Omit<\n DetectionDetail,\n 'detectionClass' | 'verificationMethod' | 'reasons' | 'signals' | 'timestamp'\n> & {\n agentName?: string;\n /** Detection class: 'human', 'ai_agent', 'bot', 'incomplete_data' */\n detectionClass?: string;\n verificationMethod?: string;\n reasons?: string[];\n signals?: DetectionDetail['signals'];\n timestamp?: DetectionDetail['timestamp'];\n /** Detection engine used: 'wasm' or 'javascript-fallback' */\n detectionMethod?: string;\n detectionBasis?: string;\n /**\n * Ordered `detection/*` reason codes (KYA-1107 signal exposure; carried\n * on every enforce detection payload alongside the populated `signals`\n * list). Deliberately `string[]` rather than\n * the registry union so an older SDK build tolerates codes added\n * server-side later; the registry lives in\n * `@kya-os/checkpoint-shared` (`DETECTION_REASON_CODES`).\n */\n reasonCodes?: string[];\n};\n\n/**\n * Enforce API response\n */\nexport interface EnforceResponse {\n success: boolean;\n data?: {\n decision: EnforcementDecision;\n processingTimeMs: number;\n requestId: string;\n detection?: ApiDetectionDetail;\n /**\n * Self-identification of the engine that ran the detection (the gateway\n * worker's `checkpoint-worker-wasm`). Absent when the gateway could not\n * compute it.\n */\n engine?: EngineInfo;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\n/**\n * Request input for enforce API\n */\nexport interface EnforceInput {\n /** HTTP headers from the incoming request */\n headers?: Record<string, string>;\n /** User-Agent header */\n userAgent?: string;\n /** Client IP address */\n ipAddress?: string;\n /** Request path */\n path?: string;\n /** Request URL */\n url?: string;\n /** HTTP method */\n method?: string;\n /** Request ID for tracing */\n requestId?: string;\n /** Options */\n options?: {\n /** Include full detection result */\n includeDetectionResult?: boolean;\n /** Cache TTL override */\n cacheTTL?: number;\n };\n}\n\n/**\n * Input for logging a detection result\n */\nexport interface LogDetectionInput {\n /** Detection result from Gateway */\n detection: ApiDetectionDetail;\n /** Request context */\n context: {\n userAgent?: string;\n ipAddress?: string;\n path?: string;\n url?: string;\n method?: string;\n };\n /** Source of the detection */\n source?: 'gateway' | 'middleware';\n /** The enforcement decision the caller received and acted on. */\n enforcement?: { action: EnforcementAction };\n /** Self-identification of the engine that produced the detection. */\n engine?: EngineInfo;\n /** Self-identification of the reporting SDK: package, version and Next.js runtime. */\n sdk?: { name: string; version: string; runtime: 'node' | 'edge' };\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\nconst DEFAULT_BASE_URL = 'https://kya.vouched.id';\nconst EDGE_DETECT_URL = 'https://detect.checkpoint-gateway.ai';\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * Checkpoint API Client\n *\n * @example\n * ```typescript\n * const client = new CheckpointApiClient({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * });\n *\n * const result = await client.enforce({\n * headers: Object.fromEntries(request.headers),\n * path: request.nextUrl.pathname,\n * method: request.method,\n * });\n *\n * if (result.decision.action === 'block') {\n * return new Response('Access denied', { status: 403 });\n * }\n * ```\n */\nexport class CheckpointApiClient {\n private apiKey: string;\n private baseUrl: string;\n private useEdge: boolean;\n private timeout: number;\n private debug: boolean;\n\n constructor(config: CheckpointApiClientConfig) {\n if (!config.apiKey) {\n throw new Error('Checkpoint API key is required');\n }\n\n this.apiKey = config.apiKey;\n // Default to edge detection for better coverage (detects non-JS clients)\n this.useEdge = config.useEdge !== false; // true by default\n this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n }\n\n /**\n * Call the enforce API to check if a request should be allowed\n */\n async enforce(input: EnforceInput): Promise<EnforceResponse> {\n const startTime = Date.now();\n\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Use edge endpoint or Vercel API based on configuration\n const endpoint = this.useEdge\n ? `${this.baseUrl}/__detect/enforce`\n : `${this.baseUrl}/api/v1/enforce`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Request-ID': input.requestId || crypto.randomUUID(),\n },\n body: JSON.stringify({\n ...input,\n headers: input.headers && relayHeaders(input.headers),\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const data = (await response.json()) as EnforceResponse;\n\n if (this.debug) {\n console.log('[Checkpoint] Enforce response:', {\n status: response.status,\n action: data.data?.decision.action,\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Handle non-2xx responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n code: `HTTP_${response.status}`,\n message: data.error?.message || `HTTP error: ${response.status}`,\n },\n };\n }\n\n return data;\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError') {\n if (this.debug) {\n console.warn('[Checkpoint] Request timed out');\n }\n return {\n success: false,\n error: {\n code: 'TIMEOUT',\n message: `Request timed out after ${this.timeout}ms`,\n },\n };\n }\n\n // Handle network errors\n if (this.debug) {\n console.error('[Checkpoint] Request failed:', error);\n }\n\n return {\n success: false,\n error: {\n code: 'NETWORK_ERROR',\n message: error instanceof Error ? error.message : 'Network request failed',\n },\n };\n }\n }\n\n /**\n * Quick check - returns just the action without full response parsing\n * Useful for very fast middleware that just needs allow/block. On an API\n * error the action is `block` (fail-closed) with `error` set.\n */\n async quickCheck(input: EnforceInput): Promise<{\n action: EnforcementAction;\n error?: string;\n }> {\n const result = await this.enforce(input);\n\n if (!result.success || !result.data) {\n return {\n action: 'block',\n error: result.error?.message,\n };\n }\n\n return {\n action: result.data.decision.action,\n };\n }\n\n /**\n * Check if this client is using edge detection (Gateway Worker)\n */\n isUsingEdge(): boolean {\n return this.useEdge;\n }\n\n /**\n * Log a detection result to the Checkpoint database.\n * Use after Gateway Worker detection to persist results.\n * Fire-and-forget - returns immediately without waiting for DB write.\n *\n * @example\n * ```typescript\n * // After receiving Gateway response\n * if (client.isUsingEdge() && response.data?.detection) {\n * client.logDetection({\n * detection: response.data.detection,\n * context: { userAgent, ipAddress, path, url, method }\n * }).catch(err => console.error('Log failed:', err));\n * }\n * ```\n */\n async logDetection(input: LogDetectionInput): Promise<void> {\n // Don't await - fire and forget\n // Use the base URL (not edge) for logging since this goes to the main API\n const logEndpoint = this.useEdge\n ? `${DEFAULT_BASE_URL}/api/v1/log-detection`\n : `${this.baseUrl}/api/v1/log-detection`;\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(logEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n detection: {\n isAgent: input.detection.isAgent,\n confidence: input.detection.confidence,\n agentName: input.detection.agentName,\n agentType: input.detection.agentType,\n detectionClass: input.detection.detectionClass,\n verificationMethod: input.detection.verificationMethod,\n reasons: input.detection.reasons,\n detectionBasis:\n typeof input.detection.detectionBasis === 'string'\n ? input.detection.detectionBasis\n : undefined,\n },\n context: input.context,\n source: input.source || 'gateway',\n // Optional blocks; JSON.stringify drops the ones left undefined, so\n // a caller that sends none posts the same body as before.\n enforcement: input.enforcement,\n engine: input.engine,\n sdk: input.sdk,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok && this.debug) {\n console.warn('[Checkpoint] Log detection returned non-2xx:', response.status);\n }\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Silently fail for fire-and-forget, but log in debug mode\n if (this.debug) {\n console.error('[Checkpoint] Log detection failed:', error);\n }\n // Re-throw so caller can catch if needed\n throw error;\n }\n }\n}\n\n/**\n * Create a cached client instance for a resolved configuration.\n *\n * @example\n * ```typescript\n * // In middleware.ts\n * import { getCheckpointApiClient } from '@kya-os/checkpoint-nextjs';\n *\n * const client = getCheckpointApiClient();\n * ```\n */\nconst clientInstances = new Map<string, CheckpointApiClient>();\n\nfunction resolveClientConfig(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClientConfig {\n const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n return {\n apiKey,\n baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,\n // Default to edge detection unless explicitly disabled\n useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== 'false',\n timeout: config?.timeout,\n debug: config?.debug || process.env.CHECKPOINT_DEBUG === 'true',\n };\n}\n\nfunction clientCacheKey(config: CheckpointApiClientConfig): string {\n return JSON.stringify([\n config.apiKey,\n config.baseUrl ?? '',\n config.useEdge,\n config.timeout ?? DEFAULT_TIMEOUT,\n config.debug,\n ]);\n}\n\nexport function getCheckpointApiClient(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClient {\n const resolvedConfig = resolveClientConfig(config);\n const key = clientCacheKey(resolvedConfig);\n let clientInstance = clientInstances.get(key);\n\n if (!clientInstance) {\n clientInstance = new CheckpointApiClient(resolvedConfig);\n clientInstances.set(key, clientInstance);\n }\n\n return clientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing)\n */\nexport function resetCheckpointApiClient(): void {\n clientInstances.clear();\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { s as EnforcementDecision } from "./api-client-JHOrRUA_.mjs";
|
|
2
|
+
import { ChallengeEnvelopeMode } from "@kya-os/checkpoint-shared/host-adapter";
|
|
3
|
+
import { NextRequest, NextResponse } from "next/server.js";
|
|
4
|
+
import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared/client-ip";
|
|
5
|
+
//#region src/api-middleware.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Middleware configuration
|
|
8
|
+
*/
|
|
9
|
+
interface CheckpointApiMiddlewareConfig {
|
|
10
|
+
/** Explicit deployment/proxy trust profile for client-IP resolution. */
|
|
11
|
+
clientIpPolicy?: ClientIpTrustPolicy;
|
|
12
|
+
/** API key (or use CHECKPOINT_API_KEY env var) */
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Gateway base URL. Override for staging or self-hosted deployments.
|
|
16
|
+
* With `useEdge: false` the default becomes `https://kya.vouched.id`.
|
|
17
|
+
*
|
|
18
|
+
* @default 'https://detect.checkpoint-gateway.ai'
|
|
19
|
+
*/
|
|
20
|
+
apiUrl?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.
|
|
23
|
+
* Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)
|
|
24
|
+
* that the pixel cannot detect since they don't execute JavaScript.
|
|
25
|
+
* Set to false to use the Vercel API instead.
|
|
26
|
+
* @default true
|
|
27
|
+
*/
|
|
28
|
+
useEdge?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Request timeout in milliseconds for the gateway call.
|
|
31
|
+
*
|
|
32
|
+
* @default 5000
|
|
33
|
+
*/
|
|
34
|
+
timeout?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Action to take when an agent should be blocked
|
|
37
|
+
* - 'block': Return 403 response
|
|
38
|
+
* - 'redirect': Redirect to redirectUrl
|
|
39
|
+
* - 'challenge': Show a challenge page (future)
|
|
40
|
+
* Default: uses policy from dashboard
|
|
41
|
+
*/
|
|
42
|
+
onBlock?: 'block' | 'redirect' | 'challenge';
|
|
43
|
+
/**
|
|
44
|
+
* URL to redirect to when blocking (if onBlock is 'redirect')
|
|
45
|
+
* Default: uses redirectUrl from dashboard policy
|
|
46
|
+
*/
|
|
47
|
+
redirectUrl?: string;
|
|
48
|
+
/**
|
|
49
|
+
* How the middleware handles a `redirect` / `instruct` action.
|
|
50
|
+
*
|
|
51
|
+
* - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON
|
|
52
|
+
* body pointing the agent at the redirect URL. LLMs surface the URL as a
|
|
53
|
+
* clickable link for the user. Matches the Cloudflare Gateway contract.
|
|
54
|
+
* - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM
|
|
55
|
+
* fetchers won't follow the redirect, so this is only useful when your
|
|
56
|
+
* traffic is real browsers.
|
|
57
|
+
*
|
|
58
|
+
* @default 'instruct'
|
|
59
|
+
*/
|
|
60
|
+
redirectMode?: 'instruct' | 'http';
|
|
61
|
+
/**
|
|
62
|
+
* Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).
|
|
63
|
+
* `negotiated` serves a body-readable HTTP 200 instruct response to
|
|
64
|
+
* cooperative agents (so fetchers that drop 4xx bodies can read it),
|
|
65
|
+
* keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).
|
|
66
|
+
* A cooperative-UX bridge, NOT an access control.
|
|
67
|
+
*
|
|
68
|
+
* @default 'negotiated'
|
|
69
|
+
*/
|
|
70
|
+
delegationChallengeMode?: ChallengeEnvelopeMode;
|
|
71
|
+
/**
|
|
72
|
+
* Customize the blocked response's status, message, and extra headers.
|
|
73
|
+
*
|
|
74
|
+
* @default { status: 403, message: 'Access denied' }
|
|
75
|
+
*/
|
|
76
|
+
blockedResponse?: {
|
|
77
|
+
status?: number;
|
|
78
|
+
message?: string;
|
|
79
|
+
headers?: Record<string, string>;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Paths to skip (in addition to dashboard policy)
|
|
83
|
+
* Supports glob patterns: '/api/*', '/_next/*'
|
|
84
|
+
*/
|
|
85
|
+
skipPaths?: string[];
|
|
86
|
+
/**
|
|
87
|
+
* Only enforce on these paths (overrides dashboard policy)
|
|
88
|
+
*/
|
|
89
|
+
includePaths?: string[];
|
|
90
|
+
/**
|
|
91
|
+
* Callback when an agent is detected
|
|
92
|
+
*/
|
|
93
|
+
onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Callback to customize the blocked response
|
|
96
|
+
*/
|
|
97
|
+
customBlockedResponse?: (request: NextRequest, decision: EnforcementDecision) => NextResponse | Promise<NextResponse>;
|
|
98
|
+
/**
|
|
99
|
+
* Whether to fail open (allow) on API errors. Must be explicitly `true`;
|
|
100
|
+
* the default is fail-closed (503 with `Retry-After`). A request that
|
|
101
|
+
* presented a credential (bearer or KYA delegation headers) is answered 503
|
|
102
|
+
* on an API error even when this is `true`.
|
|
103
|
+
*
|
|
104
|
+
* @default false
|
|
105
|
+
*/
|
|
106
|
+
failOpen?: boolean;
|
|
107
|
+
/**
|
|
108
|
+
* Log detection decisions and errors to the console.
|
|
109
|
+
*
|
|
110
|
+
* @default false
|
|
111
|
+
*/
|
|
112
|
+
debug?: boolean;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Create Checkpoint middleware with API-based detection
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```typescript
|
|
119
|
+
* // middleware.ts
|
|
120
|
+
* import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
|
|
121
|
+
*
|
|
122
|
+
* export default withCheckpointApi({
|
|
123
|
+
* onBlock: 'block',
|
|
124
|
+
* skipPaths: ['/api/health'],
|
|
125
|
+
* });
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
declare function withCheckpointApi(config?: CheckpointApiMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
|
|
129
|
+
//#endregion
|
|
130
|
+
export { withCheckpointApi as n, CheckpointApiMiddlewareConfig as t };
|
|
131
|
+
//# sourceMappingURL=api-middleware-BWjokNis.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-middleware-BWjokNis.d.mts","names":[],"sources":["../src/api-middleware.ts"],"mappings":";;;;;;;;UA4EiB;;EAEf,iBAAiB;;EAEjB;;;;;;;EAOA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA,0BAA0B;;;;;;EAO1B;IACE;IACA;IACA,UAAU;;;;;;EAOZ;;;;EAKA;;;;EAKA,mBAAmB,SAAS,aAAa,UAAU,+BAA+B;;;;EAKlF,yBACE,SAAS,aACT,UAAU,wBACP,eAAe,QAAQ;;;;;;;;;EAU5B;;;;;;EAOA;;;;;;;;;;;;;;;;iBA2Mc,kBAAkB,SAAQ,iCA6CP,SAAS,gBAAc,QAAQ"}
|