@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/middleware-node.mjs
CHANGED
|
@@ -1,352 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { applyBrowserPosture, applyBrowserIntegrityStepUp, validateBrowserIntegrityChallenge, makeComposedPolicyCache, isCredentialVerificationBlock, evaluateComposedPolicy, verifyResultToAuthorizeInput } from '@kya-os/checkpoint-wasm-runtime/composed-policy';
|
|
4
|
-
import { makeSystemClock, makePolicyEvaluator, makeReputationOracle, makeStatusListCache, makeDidResolver } from '@kya-os/checkpoint-wasm-runtime/adapters';
|
|
5
|
-
import { makeDetectionReporter } from '@kya-os/checkpoint-wasm-runtime/reporter';
|
|
6
|
-
import { selectBodyReadable200, resolveChallengeContext, PolicyFetcher, requestCarriesDelegationProof, resolveClientIp, acceptsHtml, encodeVerdictCookie, classifyResponseShape, BLOCKED_PATH, VERDICT_COOKIE_NAME } from '@kya-os/checkpoint-shared';
|
|
7
|
-
import { NextResponse } from 'next/server';
|
|
1
|
+
import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-B0jf5_Hm.mjs";
|
|
2
|
+
import { t as buildComposedContext } from "./middleware-node-context-D_ZyUEcA.mjs";
|
|
8
3
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
case "pass-through": {
|
|
16
|
-
const res = NextResponse.next();
|
|
17
|
-
applyHeaders(res, rendered);
|
|
18
|
-
setVerdictCookie(res, verdictCookie);
|
|
19
|
-
return res;
|
|
20
|
-
}
|
|
21
|
-
case "redirect": {
|
|
22
|
-
const target = new URL(rendered.headers.Location);
|
|
23
|
-
const res = NextResponse.redirect(target);
|
|
24
|
-
applyHeaders(res, rendered);
|
|
25
|
-
setVerdictCookie(res, verdictCookie);
|
|
26
|
-
return res;
|
|
27
|
-
}
|
|
28
|
-
case "html-block": {
|
|
29
|
-
const blockedUrl = new URL(BLOCKED_PATH, req.url);
|
|
30
|
-
const res = NextResponse.rewrite(blockedUrl, { status: 200 });
|
|
31
|
-
applyHeaders(res, rendered);
|
|
32
|
-
setVerdictCookie(res, verdictCookie);
|
|
33
|
-
return res;
|
|
34
|
-
}
|
|
35
|
-
case "json-block": {
|
|
36
|
-
const body = rendered.body ?? {};
|
|
37
|
-
const res = NextResponse.json(body, { status: rendered.status });
|
|
38
|
-
applyHeaders(res, rendered);
|
|
39
|
-
setVerdictCookie(res, verdictCookie);
|
|
40
|
-
return res;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
function setVerdictCookie(res, value) {
|
|
45
|
-
res.cookies.set({
|
|
46
|
-
name: VERDICT_COOKIE_NAME,
|
|
47
|
-
value,
|
|
48
|
-
path: "/",
|
|
49
|
-
sameSite: "lax",
|
|
50
|
-
httpOnly: false
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
function applyHeaders(res, rendered) {
|
|
54
|
-
for (const [key, value] of Object.entries(rendered.headers)) {
|
|
55
|
-
res.headers.set(key, value);
|
|
56
|
-
}
|
|
57
|
-
for (const [key, value] of rendered.headerEntries ?? []) {
|
|
58
|
-
res.headers.append(key, value);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
var DEFAULT_DASHBOARD_URL = "https://kya.vouched.id";
|
|
62
|
-
var NOOP_LOGGER = {
|
|
63
|
-
shadowDivergence: () => {
|
|
64
|
-
},
|
|
65
|
-
evaluationError: () => {
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
function makeComposedPolicyContext(opts) {
|
|
69
|
-
const { projectId, fetcher } = opts;
|
|
70
|
-
const cache = makeComposedPolicyCache({ compile: opts.compile, cacheMax: opts.cacheMax });
|
|
71
|
-
const logger = opts.logger ?? NOOP_LOGGER;
|
|
72
|
-
return {
|
|
73
|
-
async apply(result, path) {
|
|
74
|
-
const structured = { decision: result.decision, acted: false };
|
|
75
|
-
if (isCredentialVerificationBlock(result.decision)) return structured;
|
|
76
|
-
const policy = await fetcher.getPolicy(projectId);
|
|
77
|
-
const outcome = await evaluateComposedPolicy({
|
|
78
|
-
cache,
|
|
79
|
-
projectId,
|
|
80
|
-
flags: {
|
|
81
|
-
policyLanguage: policy.policyLanguage,
|
|
82
|
-
policySourceText: policy.policySourceText,
|
|
83
|
-
engineEnforcementEnabled: policy.engineEnforcementEnabled,
|
|
84
|
-
enabled: policy.enabled
|
|
85
|
-
},
|
|
86
|
-
authorizeInput: verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),
|
|
87
|
-
baselineDecisionKind: result.decision.kind
|
|
88
|
-
});
|
|
89
|
-
if ((outcome.status === "acting" || outcome.status === "shadow") && outcome.diverged) {
|
|
90
|
-
logger.shadowDivergence({
|
|
91
|
-
projectId,
|
|
92
|
-
path,
|
|
93
|
-
engineDecision: outcome.engineDecision.kind,
|
|
94
|
-
structuredDecision: result.decision.kind,
|
|
95
|
-
detectionClass: result.detectionDetail.detectionClass.type,
|
|
96
|
-
verificationMethod: result.detectionDetail.verificationMethod,
|
|
97
|
-
confidence: result.detectionDetail.confidence,
|
|
98
|
-
agentName: result.detectionDetail.detectedAgent?.name
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
if (outcome.status === "error") {
|
|
102
|
-
logger.evaluationError(projectId, outcome.error);
|
|
103
|
-
return structured;
|
|
104
|
-
}
|
|
105
|
-
if (outcome.status === "acting") {
|
|
106
|
-
return {
|
|
107
|
-
decision: outcome.engineDecision,
|
|
108
|
-
acted: true,
|
|
109
|
-
// Echo the SSOT revision pin with the decision it produced (#3246
|
|
110
|
-
// PR5). Conditional spread: absent upstream stays absent here.
|
|
111
|
-
...policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
return structured;
|
|
115
|
-
},
|
|
116
|
-
async trustedDelegationRoots() {
|
|
117
|
-
const policy = await fetcher.getPolicy(projectId);
|
|
118
|
-
return policy.trustedDelegationRoots ?? [];
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
async function resolveTrustedDelegationRootsForRequest(resolver, headers) {
|
|
123
|
-
if (!resolver) return void 0;
|
|
124
|
-
if (!requestCarriesDelegationProof(headers)) return void 0;
|
|
125
|
-
const roots = await resolver();
|
|
126
|
-
return roots.length > 0 ? roots : void 0;
|
|
127
|
-
}
|
|
128
|
-
async function applyComposedPolicy(context, result, path) {
|
|
129
|
-
if (!context) return;
|
|
130
|
-
try {
|
|
131
|
-
const outcome = await context.apply(result, path);
|
|
132
|
-
if (outcome.acted) {
|
|
133
|
-
result.decision = outcome.decision;
|
|
134
|
-
if (outcome.composedBlobHash) {
|
|
135
|
-
result.composedBlobHash = outcome.composedBlobHash;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
} catch {
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
var consoleComposedPolicyLogger = {
|
|
142
|
-
shadowDivergence(info) {
|
|
143
|
-
console.warn("[checkpoint/composed-policy] shadow-divergence", info);
|
|
144
|
-
},
|
|
145
|
-
evaluationError(projectId, error) {
|
|
146
|
-
console.error(
|
|
147
|
-
`[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`,
|
|
148
|
-
error
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
};
|
|
152
|
-
async function nextRequestToHttpLike(req, opts = {}) {
|
|
153
|
-
const url = new URL(req.url);
|
|
154
|
-
const body = await tryDrainJsonBody(req, opts);
|
|
155
|
-
return {
|
|
156
|
-
method: req.method,
|
|
157
|
-
// Path + query only — orchestrator's URL parsing expects no scheme/host.
|
|
158
|
-
url: url.pathname + url.search,
|
|
159
|
-
headers: headersToRecord(req.headers),
|
|
160
|
-
body,
|
|
161
|
-
remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
async function tryDrainJsonBody(req, opts) {
|
|
165
|
-
if (opts.drainJsonBody === false) return null;
|
|
166
|
-
const contentType = req.headers.get("content-type") ?? "";
|
|
167
|
-
if (!contentType.toLowerCase().includes("application/json")) return null;
|
|
168
|
-
try {
|
|
169
|
-
return await req.clone().text();
|
|
170
|
-
} catch {
|
|
171
|
-
return null;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
function headersToRecord(headers) {
|
|
175
|
-
const out = {};
|
|
176
|
-
headers.forEach((value, key) => {
|
|
177
|
-
out[key.toLowerCase()] = value;
|
|
178
|
-
});
|
|
179
|
-
return out;
|
|
180
|
-
}
|
|
181
|
-
function extractRemoteAddress(req, policy) {
|
|
182
|
-
const maybeIp = req.ip;
|
|
183
|
-
return resolveClientIp({
|
|
184
|
-
headers: req.headers,
|
|
185
|
-
frameworkAddress: maybeIp,
|
|
186
|
-
policy
|
|
187
|
-
}).ip ?? void 0;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// src/middleware-core.ts
|
|
191
|
-
function makeNextMiddleware(verifyRequest2, renderDecisionAsResponse2, config, host) {
|
|
192
|
-
if (config.browserPosture) validateBrowserPostureConfig(config.browserPosture, config.projectId);
|
|
193
|
-
if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) {
|
|
194
|
-
throw new Error(
|
|
195
|
-
"browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)"
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
const opts = buildVerifyOpts(config);
|
|
199
|
-
const reporter = buildReporter(config, host.runtime);
|
|
200
|
-
const composed = host.buildComposedContext(config);
|
|
201
|
-
const trustedRootsResolver = buildTrustedRootsResolver(config, composed);
|
|
202
|
-
const translateOpts = {
|
|
203
|
-
drainJsonBody: config.drainJsonBody,
|
|
204
|
-
clientIpPolicy: config.clientIpPolicy
|
|
205
|
-
};
|
|
206
|
-
return async function checkpointMiddleware(req, event) {
|
|
207
|
-
const httpLike = await nextRequestToHttpLike(req, translateOpts);
|
|
208
|
-
const trustedDelegationRoots = await resolveTrustedDelegationRootsForRequest(
|
|
209
|
-
trustedRootsResolver,
|
|
210
|
-
req.headers
|
|
211
|
-
);
|
|
212
|
-
const result = await verifyRequest2(
|
|
213
|
-
httpLike,
|
|
214
|
-
trustedDelegationRoots ? { ...opts, trustedDelegationRoots } : opts
|
|
215
|
-
);
|
|
216
|
-
await applyBrowserPosture(
|
|
217
|
-
result,
|
|
218
|
-
req.headers.get("cookie"),
|
|
219
|
-
config.browserPosture,
|
|
220
|
-
config.projectId
|
|
221
|
-
);
|
|
222
|
-
await applyComposedPolicy(composed, result, req.nextUrl.pathname);
|
|
223
|
-
applyBrowserIntegrityStepUp(result, config.browserPosture, req.nextUrl.pathname);
|
|
224
|
-
if (reporter) {
|
|
225
|
-
const reportPromise = reporter(
|
|
226
|
-
result,
|
|
227
|
-
extractReporterContext(req, config.clientIpPolicy ?? { platform: "direct" })
|
|
228
|
-
);
|
|
229
|
-
if (event) {
|
|
230
|
-
event.waitUntil(reportPromise);
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
await dispatchOnResult(config, result, req);
|
|
234
|
-
const bodyReadable200 = selectBodyReadable200(
|
|
235
|
-
config.delegationChallengeMode ?? "negotiated",
|
|
236
|
-
req.headers,
|
|
237
|
-
result.detectionDetail.detectionClass,
|
|
238
|
-
result.detectionDetail.isAgent
|
|
239
|
-
);
|
|
240
|
-
const challengeContextRequested = result.enforcementMode === "enforce" && result.decision.kind === "Challenge" && config.resolveDelegationChallenge !== void 0;
|
|
241
|
-
const delegationChallenge = challengeContextRequested ? await resolveChallengeContext(
|
|
242
|
-
config.resolveDelegationChallenge,
|
|
243
|
-
{ result, request: req },
|
|
244
|
-
{
|
|
245
|
-
timeoutMs: config.delegationChallengeTimeoutMs,
|
|
246
|
-
onFailure: config.onDelegationChallengeFailure
|
|
247
|
-
}
|
|
248
|
-
) : void 0;
|
|
249
|
-
const rendered = renderDecisionAsResponse2(result, {
|
|
250
|
-
bodyReadable200,
|
|
251
|
-
delegationChallenge: validateBrowserIntegrityChallenge(result, delegationChallenge),
|
|
252
|
-
challengeContextRequested
|
|
253
|
-
});
|
|
254
|
-
return adaptToNextResponse(rendered, req);
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
var SDK_NAME = "@kya-os/checkpoint-nextjs";
|
|
258
|
-
var VERSION = "1.9.0";
|
|
259
|
-
function buildReporter(config, runtime = "node") {
|
|
260
|
-
if (!config.apiKey) return null;
|
|
261
|
-
return makeDetectionReporter({
|
|
262
|
-
apiKey: config.apiKey,
|
|
263
|
-
baseUrl: config.baseUrl,
|
|
264
|
-
debug: config.debug,
|
|
265
|
-
// Self-identify (incl. node-vs-edge) so the dashboard can version-gate
|
|
266
|
-
// enforcement. Next.js EDGE composed enforcement is opt-in (needs
|
|
267
|
-
// `cedarWasmModule`), so the dashboard shows it as opt-in, never "Enforcing".
|
|
268
|
-
sdk: { name: SDK_NAME, version: VERSION, runtime }
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
function buildTrustedRootsResolver(config, composed) {
|
|
272
|
-
if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots);
|
|
273
|
-
if (composed?.trustedDelegationRoots) {
|
|
274
|
-
return () => composed.trustedDelegationRoots();
|
|
275
|
-
}
|
|
276
|
-
if (!config.projectId) return null;
|
|
277
|
-
const fetcher = new PolicyFetcher({
|
|
278
|
-
apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
|
|
279
|
-
apiKey: config.apiKey,
|
|
280
|
-
cacheTtlSeconds: config.policyCacheTtlSeconds
|
|
281
|
-
});
|
|
282
|
-
const projectId = config.projectId;
|
|
283
|
-
return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
|
|
284
|
-
}
|
|
285
|
-
function extractReporterContext(req, policy) {
|
|
286
|
-
const resolution = resolveClientIp({
|
|
287
|
-
headers: req.headers,
|
|
288
|
-
frameworkAddress: req.ip,
|
|
289
|
-
policy
|
|
290
|
-
});
|
|
291
|
-
return {
|
|
292
|
-
userAgent: req.headers.get("user-agent") ?? void 0,
|
|
293
|
-
ipAddress: resolution.ip ?? void 0,
|
|
294
|
-
path: req.nextUrl.pathname,
|
|
295
|
-
url: req.nextUrl.href,
|
|
296
|
-
method: req.method
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
function buildVerifyOpts(config) {
|
|
300
|
-
const overrides = config.adapters ?? {};
|
|
301
|
-
return {
|
|
302
|
-
didResolver: overrides.didResolver ?? makeDidResolver(),
|
|
303
|
-
statusListCache: overrides.statusListCache ?? makeStatusListCache(),
|
|
304
|
-
reputationOracle: overrides.reputationOracle ?? makeReputationOracle({ argusUrl: config.argusUrl }),
|
|
305
|
-
policyEvaluator: overrides.policyEvaluator ?? makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
|
|
306
|
-
clock: makeSystemClock(),
|
|
307
|
-
tenantHost: config.tenantHost,
|
|
308
|
-
resourceOrgDid: config.resourceOrgDid,
|
|
309
|
-
trustedDelegationRoots: config.trustedDelegationRoots,
|
|
310
|
-
enforcementMode: config.enforcementMode ?? "enforce",
|
|
311
|
-
reputationBaseline: config.reputationBaseline,
|
|
312
|
-
argusUrl: config.argusUrl,
|
|
313
|
-
legacyEnvelopeFallback: config.legacyEnvelopeFallback ?? false,
|
|
314
|
-
engineConfig: config.engineConfig
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
async function dispatchOnResult(config, result, req) {
|
|
318
|
-
if (!config.onResult) return;
|
|
319
|
-
try {
|
|
320
|
-
await config.onResult(result, req);
|
|
321
|
-
} catch {
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
function buildComposedContext(config) {
|
|
325
|
-
if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
|
|
326
|
-
if (!config.projectId) return null;
|
|
327
|
-
return makeComposedPolicyContext({
|
|
328
|
-
projectId: config.projectId,
|
|
329
|
-
fetcher: new PolicyFetcher({
|
|
330
|
-
apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
|
|
331
|
-
apiKey: config.apiKey,
|
|
332
|
-
cacheTtlSeconds: config.policyCacheTtlSeconds
|
|
333
|
-
}),
|
|
334
|
-
// Load the Node policy compiler only on first use. This module is imported
|
|
335
|
-
// exclusively by the Node and bundler hosts, never by the Edge pipeline.
|
|
336
|
-
compile: async (_language, source) => {
|
|
337
|
-
const { createPolicyEvaluator } = await import('@kya-os/checkpoint-wasm-runtime/policy');
|
|
338
|
-
return createPolicyEvaluator(source);
|
|
339
|
-
},
|
|
340
|
-
logger: config.debug ? consoleComposedPolicyLogger : void 0
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// src/middleware-node.ts
|
|
4
|
+
//#region src/middleware-node.ts
|
|
5
|
+
/**
|
|
6
|
+
* `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
|
|
7
|
+
* or not. The engine's Node build loads its `.wasm` through `new URL(...,
|
|
8
|
+
* import.meta.url)`, which bundlers follow and copy.
|
|
9
|
+
*/
|
|
345
10
|
function withCheckpoint(config) {
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
11
|
+
return makeNextMiddleware(config, {
|
|
12
|
+
runtime: "node",
|
|
13
|
+
loadEngine: async () => {
|
|
14
|
+
const orchestrator = await import("@kya-os/checkpoint-wasm-runtime/orchestrator/node");
|
|
15
|
+
await orchestrator.initEngine();
|
|
16
|
+
return orchestrator;
|
|
17
|
+
},
|
|
18
|
+
buildComposedContext
|
|
19
|
+
});
|
|
350
20
|
}
|
|
351
21
|
|
|
22
|
+
//#endregion
|
|
352
23
|
export { VERSION, withCheckpoint };
|
|
24
|
+
//# sourceMappingURL=middleware-node.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-node.mjs","names":[],"sources":["../src/middleware-node.ts"],"sourcesContent":["import { makeNextMiddleware } from './middleware-core';\nimport { buildComposedContext } from './middleware-node-context';\nimport type { CheckpointConfig } from './config';\nexport type { CheckpointConfig } from './config';\n\n/**\n * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)\n * or not. The engine's Node build loads its `.wasm` through `new URL(...,\n * import.meta.url)`, which bundlers follow and copy.\n */\nexport function withCheckpoint(config: CheckpointConfig) {\n return makeNextMiddleware(config, {\n runtime: 'node',\n // Pinned to the Node build whatever conditions a bundler resolves with.\n // Importing it does not read the `.wasm`; `initEngine` does, so a missing\n // or unreadable engine fails here, where it is logged and answered 503,\n // and the next request retries, instead of failing this module.\n loadEngine: async () => {\n const orchestrator = await import('@kya-os/checkpoint-wasm-runtime/orchestrator/node');\n await orchestrator.initEngine();\n return orchestrator;\n },\n buildComposedContext,\n });\n}\n\nexport { VERSION } from './middleware-core';\n"],"mappings":";;;;;;;;;AAUA,SAAgB,eAAe,QAA0B;CACvD,OAAO,mBAAmB,QAAQ;EAChC,SAAS;EAKT,YAAY,YAAY;GACtB,MAAM,eAAe,MAAM,OAAO;GAClC,MAAM,aAAa,WAAW;GAC9B,OAAO;EACT;EACA;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
|
|
2
|
+
import { PostureHandlerView } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
3
|
+
//#region src/posture-outcome.d.ts
|
|
4
|
+
type CheckpointPostureOutcome = PostureHandlerView;
|
|
5
|
+
interface CheckpointPostureOptions {
|
|
6
|
+
browserPosture: BrowserPostureConfig;
|
|
7
|
+
projectId: string;
|
|
8
|
+
}
|
|
9
|
+
declare function getCheckpointPostureOutcome(input: Request | Headers | {
|
|
10
|
+
headers: Headers;
|
|
11
|
+
}, options: CheckpointPostureOptions): Promise<CheckpointPostureOutcome>;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { CheckpointPostureOutcome as n, getCheckpointPostureOutcome as r, CheckpointPostureOptions as t };
|
|
14
|
+
//# sourceMappingURL=posture-outcome-Ccujx_9V.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"posture-outcome-Ccujx_9V.d.mts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAWY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBASoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
|
|
2
|
+
import { PostureHandlerView } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
3
|
+
//#region src/posture-outcome.d.ts
|
|
4
|
+
type CheckpointPostureOutcome = PostureHandlerView;
|
|
5
|
+
interface CheckpointPostureOptions {
|
|
6
|
+
browserPosture: BrowserPostureConfig;
|
|
7
|
+
projectId: string;
|
|
8
|
+
}
|
|
9
|
+
declare function getCheckpointPostureOutcome(input: Request | Headers | {
|
|
10
|
+
headers: Headers;
|
|
11
|
+
}, options: CheckpointPostureOptions): Promise<CheckpointPostureOutcome>;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { CheckpointPostureOutcome as n, getCheckpointPostureOutcome as r, CheckpointPostureOptions as t };
|
|
14
|
+
//# sourceMappingURL=posture-outcome-Ccujx_9V.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"posture-outcome-Ccujx_9V.d.ts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAWY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBASoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { postureOutcomeFromRequest, postureRequestFromHeaders, validateBrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
|
|
2
|
+
import { postureOutcomeView } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
|
|
3
|
+
|
|
4
|
+
//#region src/posture-outcome.ts
|
|
5
|
+
function hasGet(input) {
|
|
6
|
+
return typeof input.get === "function";
|
|
7
|
+
}
|
|
8
|
+
const validatedProjects = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
async function getCheckpointPostureOutcome(input, options) {
|
|
10
|
+
if (!options.browserPosture) throw new Error("getCheckpointPostureOutcome requires the browserPosture config");
|
|
11
|
+
if (validatedProjects.get(options.browserPosture) !== options.projectId) {
|
|
12
|
+
validateBrowserPostureConfig(options.browserPosture, options.projectId);
|
|
13
|
+
validatedProjects.set(options.browserPosture, options.projectId);
|
|
14
|
+
}
|
|
15
|
+
const headers = hasGet(input) ? input : input.headers;
|
|
16
|
+
return postureOutcomeView(await postureOutcomeFromRequest(postureRequestFromHeaders((name) => headers.get(name)), options.browserPosture, options.projectId));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
//#endregion
|
|
20
|
+
export { getCheckpointPostureOutcome as t };
|
|
21
|
+
//# sourceMappingURL=posture-outcome-DQ4fdMfq.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"posture-outcome-DQ4fdMfq.mjs","names":[],"sources":["../src/posture-outcome.ts"],"sourcesContent":["import {\n postureOutcomeFromRequest,\n postureRequestFromHeaders,\n validateBrowserPostureConfig,\n type BrowserPostureConfig,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport {\n postureOutcomeView,\n type PostureHandlerView,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\n\nexport type CheckpointPostureOutcome = PostureHandlerView;\n\nexport interface CheckpointPostureOptions {\n browserPosture: BrowserPostureConfig;\n projectId: string;\n}\n\nfunction hasGet(input: Request | Headers | { headers: Headers }): input is Headers {\n return typeof (input as Headers).get === 'function';\n}\n\nconst validatedProjects = new WeakMap<BrowserPostureConfig, string>();\n\nexport async function getCheckpointPostureOutcome(\n input: Request | Headers | { headers: Headers },\n options: CheckpointPostureOptions\n): Promise<CheckpointPostureOutcome> {\n if (!options.browserPosture) {\n throw new Error('getCheckpointPostureOutcome requires the browserPosture config');\n }\n if (validatedProjects.get(options.browserPosture) !== options.projectId) {\n validateBrowserPostureConfig(options.browserPosture, options.projectId);\n validatedProjects.set(options.browserPosture, options.projectId);\n }\n const headers = hasGet(input) ? input : input.headers;\n return postureOutcomeView(\n await postureOutcomeFromRequest(\n postureRequestFromHeaders((name) => headers.get(name)),\n options.browserPosture,\n options.projectId\n )\n );\n}\n"],"mappings":";;;;AAkBA,SAAS,OAAO,OAAmE;CACjF,OAAO,OAAQ,MAAkB,QAAQ;AAC3C;AAEA,MAAM,oCAAoB,IAAI,QAAsC;AAEpE,eAAsB,4BACpB,OACA,SACmC;CACnC,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,gEAAgE;CAElF,IAAI,kBAAkB,IAAI,QAAQ,cAAc,MAAM,QAAQ,WAAW;EACvE,6BAA6B,QAAQ,gBAAgB,QAAQ,SAAS;EACtE,kBAAkB,IAAI,QAAQ,gBAAgB,QAAQ,SAAS;CACjE;CACA,MAAM,UAAU,OAAO,KAAK,IAAI,QAAQ,MAAM;CAC9C,OAAO,mBACL,MAAM,0BACJ,2BAA2B,SAAS,QAAQ,IAAI,IAAI,CAAC,GACrD,QAAQ,gBACR,QAAQ,SACV,CACF;AACF"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
let _kya_os_checkpoint_shared_browser_posture = require("@kya-os/checkpoint-shared/browser-posture");
|
|
2
|
+
let _kya_os_checkpoint_wasm_runtime_composed_policy = require("@kya-os/checkpoint-wasm-runtime/composed-policy");
|
|
3
|
+
|
|
4
|
+
//#region src/posture-outcome.ts
|
|
5
|
+
function hasGet(input) {
|
|
6
|
+
return typeof input.get === "function";
|
|
7
|
+
}
|
|
8
|
+
const validatedProjects = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
async function getCheckpointPostureOutcome(input, options) {
|
|
10
|
+
if (!options.browserPosture) throw new Error("getCheckpointPostureOutcome requires the browserPosture config");
|
|
11
|
+
if (validatedProjects.get(options.browserPosture) !== options.projectId) {
|
|
12
|
+
(0, _kya_os_checkpoint_shared_browser_posture.validateBrowserPostureConfig)(options.browserPosture, options.projectId);
|
|
13
|
+
validatedProjects.set(options.browserPosture, options.projectId);
|
|
14
|
+
}
|
|
15
|
+
const headers = hasGet(input) ? input : input.headers;
|
|
16
|
+
return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.postureOutcomeView)(await (0, _kya_os_checkpoint_shared_browser_posture.postureOutcomeFromRequest)((0, _kya_os_checkpoint_shared_browser_posture.postureRequestFromHeaders)((name) => headers.get(name)), options.browserPosture, options.projectId));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
//#endregion
|
|
20
|
+
Object.defineProperty(exports, 'getCheckpointPostureOutcome', {
|
|
21
|
+
enumerable: true,
|
|
22
|
+
get: function () {
|
|
23
|
+
return getCheckpointPostureOutcome;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: ((k) => from[k]).bind(null, key),
|
|
15
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
23
|
+
value: mod,
|
|
24
|
+
enumerable: true
|
|
25
|
+
}) : target, mod));
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
Object.defineProperty(exports, '__toESM', {
|
|
29
|
+
enumerable: true,
|
|
30
|
+
get: function () {
|
|
31
|
+
return __toESM;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { resolveObservedClientAddress } from "@kya-os/checkpoint-shared/client-ip";
|
|
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
|
+
* Forwarded values require an authenticated deployment boundary. NextRequest
|
|
8
|
+
* exposes no socket peer, so arbitrary proxy profiles remain unavailable.
|
|
9
|
+
*
|
|
10
|
+
* @param request - The NextRequest object
|
|
11
|
+
* @returns The client IP address or undefined if not available
|
|
12
|
+
*/
|
|
13
|
+
function getClientIp(request, policy = { platform: "direct" }) {
|
|
14
|
+
const frameworkAddress = request.ip;
|
|
15
|
+
const onVercel = typeof process !== "undefined" && process.env?.VERCEL === "1";
|
|
16
|
+
const effectivePolicy = policy.platform === "vercel" && !onVercel ? { platform: "direct" } : policy;
|
|
17
|
+
const resolution = resolveObservedClientAddress({
|
|
18
|
+
headers: request.headers,
|
|
19
|
+
frameworkAddress,
|
|
20
|
+
vercelRuntime: onVercel,
|
|
21
|
+
policy: effectivePolicy
|
|
22
|
+
});
|
|
23
|
+
return resolution.trusted ? resolution.ip : void 0;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Safely extract the hostname from a URL string.
|
|
27
|
+
* Returns a friendly fallback when parsing fails so UX copy doesn't leak
|
|
28
|
+
* "undefined" or similar to end users.
|
|
29
|
+
*/
|
|
30
|
+
function safeHostname(url) {
|
|
31
|
+
try {
|
|
32
|
+
return new URL(url).hostname;
|
|
33
|
+
} catch {
|
|
34
|
+
return "this site";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const DROPPED_HEADERS = [
|
|
38
|
+
"cookie",
|
|
39
|
+
"authorization",
|
|
40
|
+
"proxy-authorization",
|
|
41
|
+
"x-api-key",
|
|
42
|
+
"x-vercel-protection-bypass",
|
|
43
|
+
"cf-access-jwt-assertion",
|
|
44
|
+
"cf-access-client-secret"
|
|
45
|
+
];
|
|
46
|
+
const CREDENTIAL_HEADER = /^(?!kya-|x-bot-token$)(?:.*-)?(?:authorization|auth|token|secret|password|api-?key|apikey|subscription-key|credential)s?(?:-.*)?$/;
|
|
47
|
+
const BEACON_COOKIE = "_as_beacon_session=";
|
|
48
|
+
const DELEGATION_BEARER = /^bearer\s+[\w-]+\.([\w-]+)\.[\w-]+$/i;
|
|
49
|
+
function isRecord(value) {
|
|
50
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
51
|
+
}
|
|
52
|
+
function hasDelegationType(type) {
|
|
53
|
+
return Array.isArray(type) && type.includes("DelegationCredential");
|
|
54
|
+
}
|
|
55
|
+
function isDelegationBearer(authorization) {
|
|
56
|
+
for (const candidate of (authorization ?? "").split(",")) {
|
|
57
|
+
const match = DELEGATION_BEARER.exec(candidate.trim());
|
|
58
|
+
if (!match) continue;
|
|
59
|
+
if (match[1].length > 16384) return true;
|
|
60
|
+
let claims;
|
|
61
|
+
try {
|
|
62
|
+
claims = JSON.parse(atob(match[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
63
|
+
} catch {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!isRecord(claims)) continue;
|
|
67
|
+
if (hasDelegationType(claims.type)) return true;
|
|
68
|
+
const vc = claims.vc;
|
|
69
|
+
if (!isRecord(vc)) continue;
|
|
70
|
+
if (hasDelegationType(vc.type)) return true;
|
|
71
|
+
const subject = vc.credentialSubject;
|
|
72
|
+
if (isRecord(subject) && isRecord(subject.delegation)) return true;
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
function relayHeaders(input) {
|
|
77
|
+
const headers = new Headers(input);
|
|
78
|
+
const relayed = Object.fromEntries([...headers].filter(([name]) => !DROPPED_HEADERS.includes(name) && !CREDENTIAL_HEADER.test(name)));
|
|
79
|
+
const beacon = (headers.get("cookie") ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(BEACON_COOKIE));
|
|
80
|
+
if (beacon.length) relayed.cookie = beacon.join("; ");
|
|
81
|
+
const authorization = headers.get("authorization");
|
|
82
|
+
if (isDelegationBearer(authorization)) relayed.authorization = authorization;
|
|
83
|
+
return relayed;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
//#endregion
|
|
87
|
+
export { relayHeaders as n, safeHostname as r, getClientIp as t };
|
|
88
|
+
//# sourceMappingURL=utils-Cnwg0VrY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-Cnwg0VrY.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Utility functions for @kya-os/checkpoint-nextjs\n */\n\nimport type { NextRequest } from 'next/server.js';\nimport {\n resolveObservedClientAddress,\n type ClientIpTrustPolicy,\n} from '@kya-os/checkpoint-shared/client-ip';\n\n/**\n * Extract client IP address from a NextRequest.\n * In Next.js 15+, the `ip` property was removed from NextRequest.\n * Forwarded values require an authenticated deployment boundary. NextRequest\n * exposes no socket peer, so arbitrary proxy profiles remain unavailable.\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 const onVercel = typeof process !== 'undefined' && process.env?.VERCEL === '1';\n const effectivePolicy: ClientIpTrustPolicy =\n policy.platform === 'vercel' && !onVercel ? { platform: 'direct' } : policy;\n const resolution = resolveObservedClientAddress({\n headers: request.headers,\n frameworkAddress,\n vercelRuntime: onVercel,\n policy: effectivePolicy,\n });\n return resolution.trusted ? resolution.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\nconst DROPPED_HEADERS = [\n 'cookie',\n 'authorization',\n 'proxy-authorization',\n 'x-api-key',\n 'x-vercel-protection-bypass',\n 'cf-access-jwt-assertion',\n 'cf-access-client-secret',\n];\nconst CREDENTIAL_HEADER =\n /^(?!kya-|x-bot-token$)(?:.*-)?(?:authorization|auth|token|secret|password|api-?key|apikey|subscription-key|credential)s?(?:-.*)?$/;\nconst BEACON_COOKIE = '_as_beacon_session=';\nconst DELEGATION_BEARER = /^bearer\\s+[\\w-]+\\.([\\w-]+)\\.[\\w-]+$/i;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasDelegationType(type: unknown): boolean {\n return Array.isArray(type) && type.includes('DelegationCredential');\n}\n\nfunction isDelegationBearer(authorization: string | null): authorization is string {\n for (const candidate of (authorization ?? '').split(',')) {\n const match = DELEGATION_BEARER.exec(candidate.trim());\n if (!match) continue;\n\n // Match the engine's conservative routing: oversized compact bearers must\n // reach it so it can fail closed without decoding an untrusted payload.\n if (match[1].length > 16 * 1024) return true;\n\n let claims: unknown;\n try {\n claims = JSON.parse(atob(match[1].replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n continue;\n }\n if (!isRecord(claims)) continue;\n if (hasDelegationType(claims.type)) return true;\n const vc = claims.vc;\n if (!isRecord(vc)) continue;\n if (hasDelegationType(vc.type)) return true;\n const subject = vc.credentialSubject;\n if (isRecord(subject) && isRecord(subject.delegation)) return true;\n }\n return false;\n}\n\nexport function relayHeaders(input: Record<string, string>): Record<string, string> {\n const headers = new Headers(input);\n const relayed = Object.fromEntries(\n [...headers].filter(\n ([name]) => !DROPPED_HEADERS.includes(name) && !CREDENTIAL_HEADER.test(name)\n )\n );\n const beacon = (headers.get('cookie') ?? '')\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.startsWith(BEACON_COOKIE));\n if (beacon.length) relayed.cookie = beacon.join('; ');\n const authorization = headers.get('authorization');\n if (isDelegationBearer(authorization)) relayed.authorization = authorization;\n return relayed;\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,YACd,SACA,SAA8B,EAAE,UAAU,SAAS,GAC/B;CACpB,MAAM,mBAAoB,QAAuC;CACjE,MAAM,WAAW,OAAO,YAAY,eAAe,QAAQ,KAAK,WAAW;CAC3E,MAAM,kBACJ,OAAO,aAAa,YAAY,CAAC,WAAW,EAAE,UAAU,SAAS,IAAI;CACvE,MAAM,aAAa,6BAA6B;EAC9C,SAAS,QAAQ;EACjB;EACA,eAAe;EACf,QAAQ;CACV,CAAC;CACD,OAAO,WAAW,UAAU,WAAW,KAAK;AAC9C;;;;;;AAOA,SAAgB,aAAa,KAAqB;CAChD,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,oBACJ;AACF,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAE1B,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,kBAAkB,MAAwB;CACjD,OAAO,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,sBAAsB;AACpE;AAEA,SAAS,mBAAmB,eAAuD;CACjF,KAAK,MAAM,cAAc,iBAAiB,GAAE,CAAE,MAAM,GAAG,GAAG;EACxD,MAAM,QAAQ,kBAAkB,KAAK,UAAU,KAAK,CAAC;EACrD,IAAI,CAAC,OAAO;EAIZ,IAAI,MAAM,EAAE,CAAC,SAAS,OAAW,OAAO;EAExC,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,MAAM,KAAK,MAAM,EAAE,CAAC,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,CAAC,CAAC;EAC1E,QAAQ;GACN;EACF;EACA,IAAI,CAAC,SAAS,MAAM,GAAG;EACvB,IAAI,kBAAkB,OAAO,IAAI,GAAG,OAAO;EAC3C,MAAM,KAAK,OAAO;EAClB,IAAI,CAAC,SAAS,EAAE,GAAG;EACnB,IAAI,kBAAkB,GAAG,IAAI,GAAG,OAAO;EACvC,MAAM,UAAU,GAAG;EACnB,IAAI,SAAS,OAAO,KAAK,SAAS,QAAQ,UAAU,GAAG,OAAO;CAChE;CACA,OAAO;AACT;AAEA,SAAgB,aAAa,OAAuD;CAClF,MAAM,UAAU,IAAI,QAAQ,KAAK;CACjC,MAAM,UAAU,OAAO,YACrB,CAAC,GAAG,OAAO,CAAC,CAAC,QACV,CAAC,UAAU,CAAC,gBAAgB,SAAS,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,CAC7E,CACF;CACA,MAAM,UAAU,QAAQ,IAAI,QAAQ,KAAK,GAAE,CACxC,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,CAC1B,QAAQ,SAAS,KAAK,WAAW,aAAa,CAAC;CAClD,IAAI,OAAO,QAAQ,QAAQ,SAAS,OAAO,KAAK,IAAI;CACpD,MAAM,gBAAgB,QAAQ,IAAI,eAAe;CACjD,IAAI,mBAAmB,aAAa,GAAG,QAAQ,gBAAgB;CAC/D,OAAO;AACT"}
|