@kya-os/checkpoint-nextjs 1.7.1 → 1.9.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 +30 -0
- package/EDGE_RUNTIME_WASM_SETUP.md +11 -11
- package/README.md +144 -251
- package/bin/setup-edge-wasm.js +9 -1
- package/dist/adapt.js +9 -6
- package/dist/adapt.mjs +9 -6
- package/dist/api-client.d.mts +9 -0
- package/dist/api-client.d.ts +9 -0
- package/dist/api-middleware.d.mts +5 -3
- package/dist/api-middleware.d.ts +5 -3
- package/dist/api-middleware.js +19 -32
- package/dist/api-middleware.mjs +20 -33
- package/dist/composed-policy.js +1 -0
- package/dist/composed-policy.mjs +2 -1
- package/dist/{config-DAwIA4DB.d.mts → config-CleTeeoW.d.mts} +32 -13
- package/dist/{config-DyU4l5er.d.ts → config-XMOIkxFN.d.ts} +32 -13
- package/dist/create-middleware.d.mts +1 -1
- package/dist/create-middleware.d.ts +1 -1
- package/dist/edge/index.d.mts +3 -1
- package/dist/edge/index.d.ts +3 -1
- package/dist/edge/index.js +5 -16
- package/dist/edge/index.mjs +5 -16
- package/dist/edge-runtime-loader.d.mts +3 -1
- package/dist/edge-runtime-loader.d.ts +3 -1
- package/dist/edge-runtime-loader.js +4 -16
- package/dist/edge-runtime-loader.mjs +5 -17
- package/dist/edge-wasm-middleware.d.mts +1 -1
- package/dist/edge-wasm-middleware.d.ts +1 -1
- package/dist/edge-wasm-middleware.js +1 -1
- package/dist/edge-wasm-middleware.mjs +1 -1
- package/dist/index.d.mts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +126 -85
- package/dist/index.mjs +128 -87
- package/dist/middleware-bundler.d.mts +13 -0
- package/dist/middleware-bundler.d.ts +13 -0
- package/dist/middleware-bundler.js +354 -0
- package/dist/middleware-bundler.mjs +352 -0
- package/dist/middleware-edge.d.mts +4 -40
- package/dist/middleware-edge.d.ts +4 -40
- package/dist/middleware-edge.js +148 -100
- package/dist/middleware-edge.mjs +151 -103
- package/dist/middleware-node.d.mts +15 -51
- package/dist/middleware-node.d.ts +15 -51
- package/dist/middleware-node.js +99 -56
- package/dist/middleware-node.mjs +102 -55
- package/dist/middleware.d.mts +1 -1
- package/dist/middleware.d.ts +1 -1
- package/dist/policy.js +6 -1
- package/dist/policy.mjs +6 -1
- package/dist/session-tracker.js +2 -0
- package/dist/session-tracker.mjs +2 -0
- package/dist/translate.d.mts +7 -4
- package/dist/translate.d.ts +7 -4
- package/dist/translate.js +9 -8
- package/dist/translate.mjs +9 -8
- package/dist/{types-D9RQvPNy.d.mts → types-Chgi5TFC.d.mts} +2 -2
- package/dist/{types-D9RQvPNy.d.ts → types-Chgi5TFC.d.ts} +2 -2
- package/package.json +17 -10
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var bundler = require('@kya-os/checkpoint-wasm-runtime/orchestrator/bundler');
|
|
4
|
+
var browserPosture = require('@kya-os/checkpoint-shared/browser-posture');
|
|
5
|
+
var composedPolicy = require('@kya-os/checkpoint-wasm-runtime/composed-policy');
|
|
6
|
+
var adapters = require('@kya-os/checkpoint-wasm-runtime/adapters');
|
|
7
|
+
var reporter = require('@kya-os/checkpoint-wasm-runtime/reporter');
|
|
8
|
+
var checkpointShared = require('@kya-os/checkpoint-shared');
|
|
9
|
+
var server = require('next/server');
|
|
10
|
+
|
|
11
|
+
// src/middleware-bundler.ts
|
|
12
|
+
function adaptToNextResponse(rendered, req) {
|
|
13
|
+
const clientAcceptsHtml = checkpointShared.acceptsHtml(req.headers);
|
|
14
|
+
const verdictCookie = checkpointShared.encodeVerdictCookie(rendered);
|
|
15
|
+
const shape = checkpointShared.classifyResponseShape(rendered, clientAcceptsHtml);
|
|
16
|
+
switch (shape) {
|
|
17
|
+
case "pass-through": {
|
|
18
|
+
const res = server.NextResponse.next();
|
|
19
|
+
applyHeaders(res, rendered);
|
|
20
|
+
setVerdictCookie(res, verdictCookie);
|
|
21
|
+
return res;
|
|
22
|
+
}
|
|
23
|
+
case "redirect": {
|
|
24
|
+
const target = new URL(rendered.headers.Location);
|
|
25
|
+
const res = server.NextResponse.redirect(target);
|
|
26
|
+
applyHeaders(res, rendered);
|
|
27
|
+
setVerdictCookie(res, verdictCookie);
|
|
28
|
+
return res;
|
|
29
|
+
}
|
|
30
|
+
case "html-block": {
|
|
31
|
+
const blockedUrl = new URL(checkpointShared.BLOCKED_PATH, req.url);
|
|
32
|
+
const res = server.NextResponse.rewrite(blockedUrl, { status: 200 });
|
|
33
|
+
applyHeaders(res, rendered);
|
|
34
|
+
setVerdictCookie(res, verdictCookie);
|
|
35
|
+
return res;
|
|
36
|
+
}
|
|
37
|
+
case "json-block": {
|
|
38
|
+
const body = rendered.body ?? {};
|
|
39
|
+
const res = server.NextResponse.json(body, { status: rendered.status });
|
|
40
|
+
applyHeaders(res, rendered);
|
|
41
|
+
setVerdictCookie(res, verdictCookie);
|
|
42
|
+
return res;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function setVerdictCookie(res, value) {
|
|
47
|
+
res.cookies.set({
|
|
48
|
+
name: checkpointShared.VERDICT_COOKIE_NAME,
|
|
49
|
+
value,
|
|
50
|
+
path: "/",
|
|
51
|
+
sameSite: "lax",
|
|
52
|
+
httpOnly: false
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function applyHeaders(res, rendered) {
|
|
56
|
+
for (const [key, value] of Object.entries(rendered.headers)) {
|
|
57
|
+
res.headers.set(key, value);
|
|
58
|
+
}
|
|
59
|
+
for (const [key, value] of rendered.headerEntries ?? []) {
|
|
60
|
+
res.headers.append(key, value);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
var DEFAULT_DASHBOARD_URL = "https://kya.vouched.id";
|
|
64
|
+
var NOOP_LOGGER = {
|
|
65
|
+
shadowDivergence: () => {
|
|
66
|
+
},
|
|
67
|
+
evaluationError: () => {
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
function makeComposedPolicyContext(opts) {
|
|
71
|
+
const { projectId, fetcher } = opts;
|
|
72
|
+
const cache = composedPolicy.makeComposedPolicyCache({ compile: opts.compile, cacheMax: opts.cacheMax });
|
|
73
|
+
const logger = opts.logger ?? NOOP_LOGGER;
|
|
74
|
+
return {
|
|
75
|
+
async apply(result, path) {
|
|
76
|
+
const structured = { decision: result.decision, acted: false };
|
|
77
|
+
if (composedPolicy.isCredentialVerificationBlock(result.decision)) return structured;
|
|
78
|
+
const policy = await fetcher.getPolicy(projectId);
|
|
79
|
+
const outcome = await composedPolicy.evaluateComposedPolicy({
|
|
80
|
+
cache,
|
|
81
|
+
projectId,
|
|
82
|
+
flags: {
|
|
83
|
+
policyLanguage: policy.policyLanguage,
|
|
84
|
+
policySourceText: policy.policySourceText,
|
|
85
|
+
engineEnforcementEnabled: policy.engineEnforcementEnabled,
|
|
86
|
+
enabled: policy.enabled
|
|
87
|
+
},
|
|
88
|
+
authorizeInput: composedPolicy.verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),
|
|
89
|
+
baselineDecisionKind: result.decision.kind
|
|
90
|
+
});
|
|
91
|
+
if ((outcome.status === "acting" || outcome.status === "shadow") && outcome.diverged) {
|
|
92
|
+
logger.shadowDivergence({
|
|
93
|
+
projectId,
|
|
94
|
+
path,
|
|
95
|
+
engineDecision: outcome.engineDecision.kind,
|
|
96
|
+
structuredDecision: result.decision.kind,
|
|
97
|
+
detectionClass: result.detectionDetail.detectionClass.type,
|
|
98
|
+
verificationMethod: result.detectionDetail.verificationMethod,
|
|
99
|
+
confidence: result.detectionDetail.confidence,
|
|
100
|
+
agentName: result.detectionDetail.detectedAgent?.name
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
if (outcome.status === "error") {
|
|
104
|
+
logger.evaluationError(projectId, outcome.error);
|
|
105
|
+
return structured;
|
|
106
|
+
}
|
|
107
|
+
if (outcome.status === "acting") {
|
|
108
|
+
return {
|
|
109
|
+
decision: outcome.engineDecision,
|
|
110
|
+
acted: true,
|
|
111
|
+
// Echo the SSOT revision pin with the decision it produced (#3246
|
|
112
|
+
// PR5). Conditional spread: absent upstream stays absent here.
|
|
113
|
+
...policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return structured;
|
|
117
|
+
},
|
|
118
|
+
async trustedDelegationRoots() {
|
|
119
|
+
const policy = await fetcher.getPolicy(projectId);
|
|
120
|
+
return policy.trustedDelegationRoots ?? [];
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
async function resolveTrustedDelegationRootsForRequest(resolver, headers) {
|
|
125
|
+
if (!resolver) return void 0;
|
|
126
|
+
if (!checkpointShared.requestCarriesDelegationProof(headers)) return void 0;
|
|
127
|
+
const roots = await resolver();
|
|
128
|
+
return roots.length > 0 ? roots : void 0;
|
|
129
|
+
}
|
|
130
|
+
async function applyComposedPolicy(context, result, path) {
|
|
131
|
+
if (!context) return;
|
|
132
|
+
try {
|
|
133
|
+
const outcome = await context.apply(result, path);
|
|
134
|
+
if (outcome.acted) {
|
|
135
|
+
result.decision = outcome.decision;
|
|
136
|
+
if (outcome.composedBlobHash) {
|
|
137
|
+
result.composedBlobHash = outcome.composedBlobHash;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
var consoleComposedPolicyLogger = {
|
|
144
|
+
shadowDivergence(info) {
|
|
145
|
+
console.warn("[checkpoint/composed-policy] shadow-divergence", info);
|
|
146
|
+
},
|
|
147
|
+
evaluationError(projectId, error) {
|
|
148
|
+
console.error(
|
|
149
|
+
`[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`,
|
|
150
|
+
error
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
async function nextRequestToHttpLike(req, opts = {}) {
|
|
155
|
+
const url = new URL(req.url);
|
|
156
|
+
const body = await tryDrainJsonBody(req, opts);
|
|
157
|
+
return {
|
|
158
|
+
method: req.method,
|
|
159
|
+
// Path + query only — orchestrator's URL parsing expects no scheme/host.
|
|
160
|
+
url: url.pathname + url.search,
|
|
161
|
+
headers: headersToRecord(req.headers),
|
|
162
|
+
body,
|
|
163
|
+
remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
async function tryDrainJsonBody(req, opts) {
|
|
167
|
+
if (opts.drainJsonBody === false) return null;
|
|
168
|
+
const contentType = req.headers.get("content-type") ?? "";
|
|
169
|
+
if (!contentType.toLowerCase().includes("application/json")) return null;
|
|
170
|
+
try {
|
|
171
|
+
return await req.clone().text();
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function headersToRecord(headers) {
|
|
177
|
+
const out = {};
|
|
178
|
+
headers.forEach((value, key) => {
|
|
179
|
+
out[key.toLowerCase()] = value;
|
|
180
|
+
});
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
function extractRemoteAddress(req, policy) {
|
|
184
|
+
const maybeIp = req.ip;
|
|
185
|
+
return checkpointShared.resolveClientIp({
|
|
186
|
+
headers: req.headers,
|
|
187
|
+
frameworkAddress: maybeIp,
|
|
188
|
+
policy
|
|
189
|
+
}).ip ?? void 0;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/middleware-core.ts
|
|
193
|
+
function makeNextMiddleware(verifyRequest2, renderDecisionAsResponse2, config, host) {
|
|
194
|
+
if (config.browserPosture) browserPosture.validateBrowserPostureConfig(config.browserPosture, config.projectId);
|
|
195
|
+
if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) {
|
|
196
|
+
throw new Error(
|
|
197
|
+
"browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)"
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const opts = buildVerifyOpts(config);
|
|
201
|
+
const reporter = buildReporter(config, host.runtime);
|
|
202
|
+
const composed = host.buildComposedContext(config);
|
|
203
|
+
const trustedRootsResolver = buildTrustedRootsResolver(config, composed);
|
|
204
|
+
const translateOpts = {
|
|
205
|
+
drainJsonBody: config.drainJsonBody,
|
|
206
|
+
clientIpPolicy: config.clientIpPolicy
|
|
207
|
+
};
|
|
208
|
+
return async function checkpointMiddleware(req, event) {
|
|
209
|
+
const httpLike = await nextRequestToHttpLike(req, translateOpts);
|
|
210
|
+
const trustedDelegationRoots = await resolveTrustedDelegationRootsForRequest(
|
|
211
|
+
trustedRootsResolver,
|
|
212
|
+
req.headers
|
|
213
|
+
);
|
|
214
|
+
const result = await verifyRequest2(
|
|
215
|
+
httpLike,
|
|
216
|
+
trustedDelegationRoots ? { ...opts, trustedDelegationRoots } : opts
|
|
217
|
+
);
|
|
218
|
+
await composedPolicy.applyBrowserPosture(
|
|
219
|
+
result,
|
|
220
|
+
req.headers.get("cookie"),
|
|
221
|
+
config.browserPosture,
|
|
222
|
+
config.projectId
|
|
223
|
+
);
|
|
224
|
+
await applyComposedPolicy(composed, result, req.nextUrl.pathname);
|
|
225
|
+
composedPolicy.applyBrowserIntegrityStepUp(result, config.browserPosture, req.nextUrl.pathname);
|
|
226
|
+
if (reporter) {
|
|
227
|
+
const reportPromise = reporter(
|
|
228
|
+
result,
|
|
229
|
+
extractReporterContext(req, config.clientIpPolicy ?? { platform: "direct" })
|
|
230
|
+
);
|
|
231
|
+
if (event) {
|
|
232
|
+
event.waitUntil(reportPromise);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
await dispatchOnResult(config, result, req);
|
|
236
|
+
const bodyReadable200 = checkpointShared.selectBodyReadable200(
|
|
237
|
+
config.delegationChallengeMode ?? "negotiated",
|
|
238
|
+
req.headers,
|
|
239
|
+
result.detectionDetail.detectionClass,
|
|
240
|
+
result.detectionDetail.isAgent
|
|
241
|
+
);
|
|
242
|
+
const challengeContextRequested = result.enforcementMode === "enforce" && result.decision.kind === "Challenge" && config.resolveDelegationChallenge !== void 0;
|
|
243
|
+
const delegationChallenge = challengeContextRequested ? await checkpointShared.resolveChallengeContext(
|
|
244
|
+
config.resolveDelegationChallenge,
|
|
245
|
+
{ result, request: req },
|
|
246
|
+
{
|
|
247
|
+
timeoutMs: config.delegationChallengeTimeoutMs,
|
|
248
|
+
onFailure: config.onDelegationChallengeFailure
|
|
249
|
+
}
|
|
250
|
+
) : void 0;
|
|
251
|
+
const rendered = renderDecisionAsResponse2(result, {
|
|
252
|
+
bodyReadable200,
|
|
253
|
+
delegationChallenge: composedPolicy.validateBrowserIntegrityChallenge(result, delegationChallenge),
|
|
254
|
+
challengeContextRequested
|
|
255
|
+
});
|
|
256
|
+
return adaptToNextResponse(rendered, req);
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
var SDK_NAME = "@kya-os/checkpoint-nextjs";
|
|
260
|
+
var VERSION = "1.9.0";
|
|
261
|
+
function buildReporter(config, runtime = "node") {
|
|
262
|
+
if (!config.apiKey) return null;
|
|
263
|
+
return reporter.makeDetectionReporter({
|
|
264
|
+
apiKey: config.apiKey,
|
|
265
|
+
baseUrl: config.baseUrl,
|
|
266
|
+
debug: config.debug,
|
|
267
|
+
// Self-identify (incl. node-vs-edge) so the dashboard can version-gate
|
|
268
|
+
// enforcement. Next.js EDGE composed enforcement is opt-in (needs
|
|
269
|
+
// `cedarWasmModule`), so the dashboard shows it as opt-in, never "Enforcing".
|
|
270
|
+
sdk: { name: SDK_NAME, version: VERSION, runtime }
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
function buildTrustedRootsResolver(config, composed) {
|
|
274
|
+
if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots);
|
|
275
|
+
if (composed?.trustedDelegationRoots) {
|
|
276
|
+
return () => composed.trustedDelegationRoots();
|
|
277
|
+
}
|
|
278
|
+
if (!config.projectId) return null;
|
|
279
|
+
const fetcher = new checkpointShared.PolicyFetcher({
|
|
280
|
+
apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
|
|
281
|
+
apiKey: config.apiKey,
|
|
282
|
+
cacheTtlSeconds: config.policyCacheTtlSeconds
|
|
283
|
+
});
|
|
284
|
+
const projectId = config.projectId;
|
|
285
|
+
return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
|
|
286
|
+
}
|
|
287
|
+
function extractReporterContext(req, policy) {
|
|
288
|
+
const resolution = checkpointShared.resolveClientIp({
|
|
289
|
+
headers: req.headers,
|
|
290
|
+
frameworkAddress: req.ip,
|
|
291
|
+
policy
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
userAgent: req.headers.get("user-agent") ?? void 0,
|
|
295
|
+
ipAddress: resolution.ip ?? void 0,
|
|
296
|
+
path: req.nextUrl.pathname,
|
|
297
|
+
url: req.nextUrl.href,
|
|
298
|
+
method: req.method
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
function buildVerifyOpts(config) {
|
|
302
|
+
const overrides = config.adapters ?? {};
|
|
303
|
+
return {
|
|
304
|
+
didResolver: overrides.didResolver ?? adapters.makeDidResolver(),
|
|
305
|
+
statusListCache: overrides.statusListCache ?? adapters.makeStatusListCache(),
|
|
306
|
+
reputationOracle: overrides.reputationOracle ?? adapters.makeReputationOracle({ argusUrl: config.argusUrl }),
|
|
307
|
+
policyEvaluator: overrides.policyEvaluator ?? adapters.makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
|
|
308
|
+
clock: adapters.makeSystemClock(),
|
|
309
|
+
tenantHost: config.tenantHost,
|
|
310
|
+
resourceOrgDid: config.resourceOrgDid,
|
|
311
|
+
trustedDelegationRoots: config.trustedDelegationRoots,
|
|
312
|
+
enforcementMode: config.enforcementMode ?? "enforce",
|
|
313
|
+
reputationBaseline: config.reputationBaseline,
|
|
314
|
+
argusUrl: config.argusUrl,
|
|
315
|
+
legacyEnvelopeFallback: config.legacyEnvelopeFallback ?? false,
|
|
316
|
+
engineConfig: config.engineConfig
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
async function dispatchOnResult(config, result, req) {
|
|
320
|
+
if (!config.onResult) return;
|
|
321
|
+
try {
|
|
322
|
+
await config.onResult(result, req);
|
|
323
|
+
} catch {
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function buildComposedContext(config) {
|
|
327
|
+
if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
|
|
328
|
+
if (!config.projectId) return null;
|
|
329
|
+
return makeComposedPolicyContext({
|
|
330
|
+
projectId: config.projectId,
|
|
331
|
+
fetcher: new checkpointShared.PolicyFetcher({
|
|
332
|
+
apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
|
|
333
|
+
apiKey: config.apiKey,
|
|
334
|
+
cacheTtlSeconds: config.policyCacheTtlSeconds
|
|
335
|
+
}),
|
|
336
|
+
// Load the Node policy compiler only on first use. This module is imported
|
|
337
|
+
// exclusively by the Node and bundler hosts, never by the Edge pipeline.
|
|
338
|
+
compile: async (_language, source) => {
|
|
339
|
+
const { createPolicyEvaluator } = await import('@kya-os/checkpoint-wasm-runtime/policy');
|
|
340
|
+
return createPolicyEvaluator(source);
|
|
341
|
+
},
|
|
342
|
+
logger: config.debug ? consoleComposedPolicyLogger : void 0
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// src/middleware-bundler.ts
|
|
347
|
+
function withCheckpoint(config) {
|
|
348
|
+
return makeNextMiddleware(bundler.verifyRequest, bundler.renderDecisionAsResponse, config, {
|
|
349
|
+
runtime: "node",
|
|
350
|
+
buildComposedContext
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
exports.withCheckpoint = withCheckpoint;
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { renderDecisionAsResponse, verifyRequest } from '@kya-os/checkpoint-wasm-runtime/orchestrator/bundler';
|
|
2
|
+
import { validateBrowserPostureConfig } from '@kya-os/checkpoint-shared/browser-posture';
|
|
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';
|
|
8
|
+
|
|
9
|
+
// src/middleware-bundler.ts
|
|
10
|
+
function adaptToNextResponse(rendered, req) {
|
|
11
|
+
const clientAcceptsHtml = acceptsHtml(req.headers);
|
|
12
|
+
const verdictCookie = encodeVerdictCookie(rendered);
|
|
13
|
+
const shape = classifyResponseShape(rendered, clientAcceptsHtml);
|
|
14
|
+
switch (shape) {
|
|
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-bundler.ts
|
|
345
|
+
function withCheckpoint(config) {
|
|
346
|
+
return makeNextMiddleware(verifyRequest, renderDecisionAsResponse, config, {
|
|
347
|
+
runtime: "node",
|
|
348
|
+
buildComposedContext
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export { withCheckpoint };
|