@kya-os/checkpoint-shared 1.8.0 → 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 +37 -0
- package/dist/agent-catalog.d.mts +12 -0
- package/dist/agent-catalog.d.mts.map +1 -0
- package/dist/agent-catalog.d.ts +12 -0
- package/dist/agent-catalog.d.ts.map +1 -0
- package/dist/agent-catalog.js +105 -0
- package/dist/agent-catalog.mjs +105 -0
- package/dist/agent-catalog.mjs.map +1 -0
- package/dist/beacon-types/index.d.mts +18 -0
- package/dist/beacon-types/index.d.mts.map +1 -1
- package/dist/beacon-types/index.d.ts +18 -0
- package/dist/beacon-types/index.d.ts.map +1 -1
- package/dist/beacon-types/index.js +116 -12
- package/dist/beacon-types/index.mjs +105 -13
- package/dist/beacon-types/index.mjs.map +1 -1
- package/dist/browser-posture-5fPrsxx7.d.mts.map +1 -1
- package/dist/browser-posture-CCR1kh5e.d.ts.map +1 -1
- package/dist/browser-posture-cookie.js +1 -1
- package/dist/browser-posture-cookie.mjs +1 -1
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof-verifier-DvsOmFrM.js +202 -0
- package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +180 -0
- package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +1 -0
- package/dist/browser-posture-proof-verifier.d.mts +25 -0
- package/dist/browser-posture-proof-verifier.d.mts.map +1 -0
- package/dist/browser-posture-proof-verifier.d.ts +25 -0
- package/dist/browser-posture-proof-verifier.d.ts.map +1 -0
- package/dist/browser-posture-proof-verifier.js +7 -0
- package/dist/browser-posture-proof-verifier.mjs +3 -0
- package/dist/browser-posture-proof.d.mts +3 -18
- package/dist/browser-posture-proof.d.mts.map +1 -1
- package/dist/browser-posture-proof.d.ts +3 -18
- package/dist/browser-posture-proof.d.ts.map +1 -1
- package/dist/browser-posture-proof.js +6 -131
- package/dist/browser-posture-proof.mjs +1 -126
- package/dist/browser-posture-proof.mjs.map +1 -1
- package/dist/browser-posture.js +1 -1
- package/dist/browser-posture.mjs +1 -1
- package/dist/browser-posture.mjs.map +1 -1
- package/dist/browser.d.mts +0 -282
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.d.ts +0 -282
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/browser.mjs.map +1 -1
- package/dist/canonical-signer/index.mjs.map +1 -1
- package/dist/consent-handoff.d.mts +0 -3
- package/dist/consent-handoff.d.mts.map +1 -1
- package/dist/consent-handoff.d.ts +0 -3
- package/dist/consent-handoff.d.ts.map +1 -1
- package/dist/consent-handoff.mjs.map +1 -1
- package/dist/default-sign-in-host.d.mts +10 -0
- package/dist/default-sign-in-host.d.mts.map +1 -0
- package/dist/default-sign-in-host.d.ts +10 -0
- package/dist/default-sign-in-host.d.ts.map +1 -0
- package/dist/default-sign-in-host.js +72 -0
- package/dist/default-sign-in-host.mjs +66 -0
- package/dist/default-sign-in-host.mjs.map +1 -0
- package/dist/errors/index.d.mts +1 -0
- package/dist/errors/index.d.mts.map +1 -1
- package/dist/errors/index.d.ts +1 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +5 -2
- package/dist/errors/index.mjs +5 -2
- package/dist/errors/index.mjs.map +1 -1
- package/dist/{fetcher-CivUCbhL.d.ts → fetcher-C8qvwdnA.d.ts} +2 -2
- package/dist/{fetcher-CivUCbhL.d.ts.map → fetcher-C8qvwdnA.d.ts.map} +1 -1
- package/dist/{fetcher-cXQsbm6s.d.mts → fetcher-D2vjr7jB.d.mts} +2 -2
- package/dist/{fetcher-cXQsbm6s.d.mts.map → fetcher-D2vjr7jB.d.mts.map} +1 -1
- package/dist/gateway-client-ip.d.mts +0 -2
- package/dist/gateway-client-ip.d.mts.map +1 -1
- package/dist/gateway-client-ip.d.ts +0 -2
- package/dist/gateway-client-ip.d.ts.map +1 -1
- package/dist/gateway-client-ip.mjs.map +1 -1
- package/dist/host-adapter/index.d.mts +1 -1
- package/dist/host-adapter/index.d.ts +1 -1
- package/dist/host-adapter/index.js +1 -1
- package/dist/host-adapter/index.mjs +1 -1
- package/dist/{host-adapter-DHyISsIf.mjs → host-adapter-BKdQHwbi.mjs} +2 -2
- package/dist/{host-adapter-DHyISsIf.mjs.map → host-adapter-BKdQHwbi.mjs.map} +1 -1
- package/dist/{host-adapter-0F8EpbD6.js → host-adapter-bWftXA9T.js} +1 -1
- package/dist/{index-CXbOY7gB.d.ts → index-DnFsmr_o.d.ts} +3 -3
- package/dist/{index-CXbOY7gB.d.ts.map → index-DnFsmr_o.d.ts.map} +1 -1
- package/dist/{index-B3cHxr3O.d.mts → index-rvw5Bz-r.d.mts} +3 -3
- package/dist/{index-B3cHxr3O.d.mts.map → index-rvw5Bz-r.d.mts.map} +1 -1
- package/dist/index.d.mts +94 -449
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +94 -449
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25 -455
- package/dist/index.mjs +17 -422
- package/dist/index.mjs.map +1 -1
- package/dist/{kya-http-error-codes-UYb1zpGM.js → kya-http-error-codes-B4rUmUEI.js} +2 -0
- package/dist/{kya-http-error-codes-7ewV5RuK.d.ts → kya-http-error-codes-C14E4gi3.d.mts} +2 -1
- package/dist/kya-http-error-codes-C14E4gi3.d.mts.map +1 -0
- package/dist/{kya-http-error-codes-7ewV5RuK.d.mts → kya-http-error-codes-C14E4gi3.d.ts} +2 -1
- package/dist/kya-http-error-codes-C14E4gi3.d.ts.map +1 -0
- package/dist/{kya-http-error-codes-C2JiWPsi.mjs → kya-http-error-codes-DSBrxNry.mjs} +3 -1
- package/dist/kya-http-error-codes-DSBrxNry.mjs.map +1 -0
- package/dist/kya-http.d.mts +1 -1
- package/dist/kya-http.d.ts +1 -1
- package/dist/kya-http.js +1 -1
- package/dist/kya-http.mjs +1 -1
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
- package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
- package/dist/{patterns-B2r7M9wR.js → patterns-CiMpbdAF.js} +1 -1
- package/dist/{patterns-B7dQoeE3.mjs → patterns-D4OAsNQY.mjs} +2 -2
- package/dist/{patterns-B7dQoeE3.mjs.map → patterns-D4OAsNQY.mjs.map} +1 -1
- package/dist/patterns.js +1 -1
- package/dist/patterns.mjs +1 -1
- package/dist/policy/fetcher.d.mts +1 -1
- package/dist/policy/fetcher.d.ts +1 -1
- package/dist/policy/schemas.d.mts +1 -1
- package/dist/policy/schemas.d.ts +1 -1
- package/dist/{schemas-C_3C72SR.d.ts → schemas-CGKHzcMV.d.ts} +21 -21
- package/dist/{schemas-C_3C72SR.d.ts.map → schemas-CGKHzcMV.d.ts.map} +1 -1
- package/dist/{schemas-02CI7jgm.d.mts → schemas-m-GqyfyO.d.mts} +21 -21
- package/dist/{schemas-02CI7jgm.d.mts.map → schemas-m-GqyfyO.d.mts.map} +1 -1
- package/dist/tool-protection/index.d.mts +12 -0
- package/dist/tool-protection/index.d.mts.map +1 -1
- package/dist/tool-protection/index.d.ts +12 -0
- package/dist/tool-protection/index.d.ts.map +1 -1
- package/dist/tool-protection/index.js +46 -0
- package/dist/tool-protection/index.mjs +44 -1
- package/dist/tool-protection/index.mjs.map +1 -1
- package/fixtures/kya-http/error-codes.json +2 -1
- package/package.json +19 -3
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +0 -1
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +0 -1
- package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as PolicyConfig } from "./schemas-
|
|
1
|
+
import { D as PolicyConfig } from "./schemas-m-GqyfyO.mjs";
|
|
2
2
|
//#region src/policy/fetcher.d.ts
|
|
3
3
|
interface PolicyCacheAdapter {
|
|
4
4
|
get(key: string): Promise<string | null>;
|
|
@@ -41,4 +41,4 @@ declare class PolicyFetcher {
|
|
|
41
41
|
}
|
|
42
42
|
//#endregion
|
|
43
43
|
export { PolicyUnavailableError as a, PolicyFetcherConfig as i, PolicyCacheAdapter as n, isPolicyUnavailableError as o, PolicyFetcher as r, CachedPolicy as t };
|
|
44
|
-
//# sourceMappingURL=fetcher-
|
|
44
|
+
//# sourceMappingURL=fetcher-D2vjr7jB.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher-
|
|
1
|
+
{"version":3,"file":"fetcher-D2vjr7jB.d.mts","names":[],"sources":["../src/policy/fetcher.ts"],"mappings":";;UA0BiB;EACf,IAAI,cAAc;EAClB,IAAI,aAAa,eAAe,qBAAqB;EAErD,QAAQ,cAAc;;UAMP;EAEf;EAEA;EAEA;EAEA,eAAe;EAEf;EAEA;EAEA;EAEA,iBAAiB;;UAMF;EACf,QAAQ;EACR;EACA;EACA;;cA0BW,+BAA+B;WACjC;;;iBASK,yBAAyB;cAoE5B;UACH;UAIA;EAEI,YAAA,QAAQ;UAkBZ;UAWA;EAQF,UAAU,oBAAoB,QAAQ;UAuE9B;EA4Cd,oBAAoB;EAQd,gBAAgB,oBAAoB;EA0B1C;UASQ"}
|
|
@@ -31,7 +31,6 @@ export declare const GatewayClientIpPublicJwkSchema: ZodObject<{
|
|
|
31
31
|
x: ZodString;
|
|
32
32
|
y: ZodString;
|
|
33
33
|
}, $strip>;
|
|
34
|
-
export type GatewayClientIpPublicJwk = output<typeof GatewayClientIpPublicJwkSchema>;
|
|
35
34
|
export declare const GatewayClientIpPrivateJwkSchema: ZodObject<{
|
|
36
35
|
kty: ZodLiteral<"EC">;
|
|
37
36
|
crv: ZodLiteral<"P-256">;
|
|
@@ -42,7 +41,6 @@ export declare const GatewayClientIpPrivateJwkSchema: ZodObject<{
|
|
|
42
41
|
y: ZodString;
|
|
43
42
|
d: ZodString;
|
|
44
43
|
}, $strip>;
|
|
45
|
-
export type GatewayClientIpPrivateJwk = output<typeof GatewayClientIpPrivateJwkSchema>;
|
|
46
44
|
export declare function importGatewayClientIpSigningKey(jwk: JWK$1): Promise<KeyLike$1 | Uint8Array>;
|
|
47
45
|
export declare function signGatewayClientIp(privateKey: KeyLike$1 | Uint8Array, kid: string, input: GatewayClientIpInput, now?: number): Promise<string>;
|
|
48
46
|
export interface VerifyGatewayClientIpOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-client-ip.d.mts","names":[],"sources":["../src/gateway-client-ip.ts"],"mappings":";;;qBA2Ba;qBACA;qBACA;qBAYA;wBAaG,YAAY;qBAOf,6BAA2B;;;;;;;;GAQtC;YACU,wBAAwB,cAAe;iBAElC;EACf;EACA;EACA;EACA;;qBAIW,gCAA8B;;;;;;;;GAQzC;
|
|
1
|
+
{"version":3,"file":"gateway-client-ip.d.mts","names":[],"sources":["../src/gateway-client-ip.ts"],"mappings":";;;qBA2Ba;qBACA;qBACA;qBAYA;wBAaG,YAAY;qBAOf,6BAA2B;;;;;;;;GAQtC;YACU,wBAAwB,cAAe;iBAElC;EACf;EACA;EACA;EACA;;qBAIW,gCAA8B;;;;;;;;GAQzC;qBAGW,iCAA+B;;;;;;;;;GAE1C;wBAQoB,gCAAgC,KAAK,QAAM,QAAQ,YAAU;wBAU7D,oBACpB,YAAY,YAAU,YACtB,aACA,OAAO,sBACP,eACC;iBAkBc;EAEf;EAQA;EAYA;EACA;;wBAWoB,sBACpB,kCACA;EAAQ,MAAM;GACd,SAAS,+BACR,QAAQ"}
|
|
@@ -31,7 +31,6 @@ export declare const GatewayClientIpPublicJwkSchema: ZodObject<{
|
|
|
31
31
|
x: ZodString;
|
|
32
32
|
y: ZodString;
|
|
33
33
|
}, $strip>;
|
|
34
|
-
export type GatewayClientIpPublicJwk = output<typeof GatewayClientIpPublicJwkSchema>;
|
|
35
34
|
export declare const GatewayClientIpPrivateJwkSchema: ZodObject<{
|
|
36
35
|
kty: ZodLiteral<"EC">;
|
|
37
36
|
crv: ZodLiteral<"P-256">;
|
|
@@ -42,7 +41,6 @@ export declare const GatewayClientIpPrivateJwkSchema: ZodObject<{
|
|
|
42
41
|
y: ZodString;
|
|
43
42
|
d: ZodString;
|
|
44
43
|
}, $strip>;
|
|
45
|
-
export type GatewayClientIpPrivateJwk = output<typeof GatewayClientIpPrivateJwkSchema>;
|
|
46
44
|
export declare function importGatewayClientIpSigningKey(jwk: JWK$1): Promise<KeyLike$1 | Uint8Array>;
|
|
47
45
|
export declare function signGatewayClientIp(privateKey: KeyLike$1 | Uint8Array, kid: string, input: GatewayClientIpInput, now?: number): Promise<string>;
|
|
48
46
|
export interface VerifyGatewayClientIpOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-client-ip.d.ts","names":[],"sources":["../src/gateway-client-ip.ts"],"mappings":";;;qBA2Ba;qBACA;qBACA;qBAYA;wBAaG,YAAY;qBAOf,6BAA2B;;;;;;;;GAQtC;YACU,wBAAwB,cAAe;iBAElC;EACf;EACA;EACA;EACA;;qBAIW,gCAA8B;;;;;;;;GAQzC;
|
|
1
|
+
{"version":3,"file":"gateway-client-ip.d.ts","names":[],"sources":["../src/gateway-client-ip.ts"],"mappings":";;;qBA2Ba;qBACA;qBACA;qBAYA;wBAaG,YAAY;qBAOf,6BAA2B;;;;;;;;GAQtC;YACU,wBAAwB,cAAe;iBAElC;EACf;EACA;EACA;EACA;;qBAIW,gCAA8B;;;;;;;;GAQzC;qBAGW,iCAA+B;;;;;;;;;GAE1C;wBAQoB,gCAAgC,KAAK,QAAM,QAAQ,YAAU;wBAU7D,oBACpB,YAAY,YAAU,YACtB,aACA,OAAO,sBACP,eACC;iBAkBc;EAEf;EAQA;EAYA;EACA;;wBAWoB,sBACpB,kCACA;EAAQ,MAAM;GACd,SAAS,+BACR,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-client-ip.mjs","names":["z.object","z.literal","z.string","z.number"],"sources":["../src/gateway-client-ip.ts"],"sourcesContent":["import { SignJWT, createLocalJWKSet, importJWK, jwtVerify, type JWK, type KeyLike } from 'jose';\nimport { z } from 'zod';\nimport { parseIpv6 } from './utils/client-ip';\n\nexport type { JWK, KeyLike } from 'jose';\n\n/**\n * Signed client-identity token minted by the Checkpoint Cloudflare gateway\n * worker and verified by an origin-side Checkpoint SDK (KYA-1121 follow-up).\n *\n * The gateway already forwards the connecting IP as the plain `KYA-Client-IP`\n * / `X-Forwarded-For` headers (see `proxy.ts`), which every adapter behind a\n * KNOWN, trusted peer (Cloudflare's own published edge ranges) can trust.\n * Behind an additional untrusted hop - e.g. a PaaS's own reverse proxy\n * (Railway, Render, Fly) sitting between Cloudflare and the origin - the\n * origin's TCP peer is that PaaS's proxy, not Cloudflare, so the plain\n * header can never be trusted there: any caller reaching the PaaS's edge\n * directly could set it too. This ES256-signed JWS carries the SAME claim\n * with a signature only the gateway's private key can produce, so an origin\n * can trust it regardless of what sits between it and the gateway.\n *\n * One gateway-wide asymmetric key (not a per-project secret): the worker\n * holds the private JWK (`GATEWAY_CLIENT_IP_SIGNING_JWK`), the platform\n * publishes the public JWK at `/.well-known/jwks.json`\n * (`GATEWAY_CLIENT_IP_PUBLIC_JWK`). Rotation is by `kid`.\n */\n\nexport const GATEWAY_CLIENT_IP_TOKEN_HEADER = 'KYA-Client-IP-Token';\nexport const GATEWAY_CLIENT_IP_ISSUER = 'checkpoint:gateway-client-ip:v1';\nexport const GATEWAY_CLIENT_IP_TYPE = 'checkpoint-client-ip+jwt';\n/**\n * Token lifetime, seconds. A verifier MUST additionally bind `cid`/`host` to\n * the request it's verifying (see {@link VerifyGatewayClientIpOptions}) -\n * without that binding, a token captured on an untrusted hop within this\n * window is replayable onto a DIFFERENT request the gateway never actually\n * saw, and the `ip` it carries is not inert: it feeds the same IP-reputation\n * and vendor-cross-match signals as any other resolved client IP, which do\n * influence the engine's enforcement decision. Binding `cid` (unique per\n * request) is what keeps a captured token scoped to the one request the\n * gateway minted it for.\n */\nexport const GATEWAY_CLIENT_IP_TTL_SECONDS = 60;\n/** Clock-skew allowance applied to `exp` (via jose's `clockTolerance`) and independently to `iat` below. */\nconst CLOCK_SKEW_SECONDS = 30;\n\nfunction isIpv4Literal(value: string): boolean {\n const parts = value.split('.');\n return (\n parts.length === 4 &&\n parts.every((part) => /^(0|[1-9]\\d{0,2})$/.test(part) && Number(part) <= 255)\n );\n}\n\n/** True when `value` is a literal IPv4 or IPv6 address - never resolves a hostname. */\nexport function isIpLiteral(value: string): boolean {\n // parseIpv6 is exported by client-ip.ts specifically for reuse by callers\n // that need to validate/mask an address, not just resolve one - reused\n // here rather than a second hand-rolled IPv6 parser.\n return isIpv4Literal(value) || parseIpv6(value) !== null;\n}\n\nexport const GatewayClientIpClaimsSchema = z.object({\n iss: z.literal(GATEWAY_CLIENT_IP_ISSUER),\n aud: z.string().min(1),\n ip: z.string().refine(isIpLiteral, 'ip must be a literal IPv4 or IPv6 address'),\n cid: z.string().min(1),\n host: z.string().min(1),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive(),\n});\nexport type GatewayClientIpClaims = z.infer<typeof GatewayClientIpClaimsSchema>;\n\nexport interface GatewayClientIpInput {\n aud: string;\n ip: string;\n cid: string;\n host: string;\n}\n\n/** The gateway's own EC P-256 public key, as published in `/.well-known/jwks.json`. */\nexport const GatewayClientIpPublicJwkSchema = z.object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n alg: z.literal('ES256'),\n use: z.literal('sig'),\n kid: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n});\nexport type GatewayClientIpPublicJwk = z.infer<typeof GatewayClientIpPublicJwkSchema>;\n\n/** The private half the gateway worker holds (`GATEWAY_CLIENT_IP_SIGNING_JWK`). */\nexport const GatewayClientIpPrivateJwkSchema = GatewayClientIpPublicJwkSchema.extend({\n d: z.string().min(1),\n});\nexport type GatewayClientIpPrivateJwk = z.infer<typeof GatewayClientIpPrivateJwkSchema>;\n\n/**\n * Import a gateway client-ip JWK (private or public half) into a usable jose\n * key. Callers on a hot path - the gateway worker signs on every proxied\n * request - should import once per isolate and reuse the resulting key\n * rather than calling this per request.\n */\nexport async function importGatewayClientIpSigningKey(jwk: JWK): Promise<KeyLike | Uint8Array> {\n return importJWK(jwk, 'ES256');\n}\n\n/**\n * Mint a compact JWS carrying the gateway's client-identity claim.\n * `privateKey` must already be imported (see {@link importGatewayClientIpSigningKey}) -\n * this function never imports a key itself, so a cached key can be reused\n * across every signed request.\n */\nexport async function signGatewayClientIp(\n privateKey: KeyLike | Uint8Array,\n kid: string,\n input: GatewayClientIpInput,\n now: number = Math.floor(Date.now() / 1000)\n): Promise<string> {\n if (!kid || !input.aud || !input.cid || !input.host || !isIpLiteral(input.ip)) {\n throw new Error('Invalid gateway client-ip signing input');\n }\n const claims: GatewayClientIpClaims = {\n iss: GATEWAY_CLIENT_IP_ISSUER,\n aud: input.aud,\n ip: input.ip,\n cid: input.cid,\n host: input.host,\n iat: now,\n exp: now + GATEWAY_CLIENT_IP_TTL_SECONDS,\n };\n return new SignJWT(claims)\n .setProtectedHeader({ alg: 'ES256', typ: GATEWAY_CLIENT_IP_TYPE, kid })\n .sign(privateKey);\n}\n\nexport interface VerifyGatewayClientIpOptions {\n /** The project this token must be scoped to (`routingEntry.projectId` on the gateway side). */\n projectId: string;\n /**\n * The CURRENT request's own correlation id (the same value the gateway\n * forwards as `x-kya-correlation-id`) - must equal the token's `cid` claim.\n * This is the binding that makes replay impossible: without it, a token\n * captured on an untrusted hop verifies against ANY request presenting it\n * within the TTL, not just the one the gateway minted it for.\n */\n expectedCid: string;\n /**\n * The CURRENT request's own public hostname - must equal the token's\n * `host` claim. On the Java SDK's `RemoteIpResolver.gateway(options)`,\n * this is the host component of the gateway's `KYA-Original-Origin`\n * header, NOT `X-Forwarded-Host`: a PaaS's own reverse proxy in front of\n * the origin (Railway, Render, Fly) commonly rewrites the latter from its\n * own Host-header-based routing, which would make this binding never\n * match on exactly the topology it defends (Cursor Bugbot, high) - see\n * `proxy.ts`, which sets `KYA-Original-Origin` unconditionally on every\n * proxied request to the same `hostname` this token's `host` claim signs.\n */\n expectedHost: string;\n now?: number;\n}\n\n/**\n * Verify a gateway client-ip token against a JWKS document (as served by\n * `/.well-known/jwks.json`) and return its claims, or `null` on ANY failure\n * - malformed token, unknown `kid`, wrong `alg`, a tampered/expired/\n * mismatched claim, or a `cid`/`host` that doesn't match the request being\n * verified. Never throws: a missing or invalid token must change nothing\n * about the caller's IP resolution.\n */\nexport async function verifyGatewayClientIp(\n token: string | undefined | null,\n jwks: { keys: JWK[] },\n options: VerifyGatewayClientIpOptions\n): Promise<GatewayClientIpClaims | null> {\n if (!token || !options.projectId || !options.expectedCid || !options.expectedHost) return null;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n try {\n // Only EC/P-256 keys are ever candidates - the JWKS also carries the\n // unrelated OAuth Ed25519 (OKP) key, which must never be considered here.\n const ecKeys = jwks.keys.filter((key) => key.kty === 'EC' && key.crv === 'P-256');\n if (ecKeys.length === 0) return null;\n const getKey = createLocalJWKSet({ keys: ecKeys });\n const { payload } = await jwtVerify(token, getKey, {\n algorithms: ['ES256'],\n issuer: GATEWAY_CLIENT_IP_ISSUER,\n audience: options.projectId,\n typ: GATEWAY_CLIENT_IP_TYPE,\n currentDate: new Date(now * 1000),\n clockTolerance: CLOCK_SKEW_SECONDS,\n });\n const parsed = GatewayClientIpClaimsSchema.safeParse(payload);\n if (!parsed.success) return null;\n const claims = parsed.data;\n // Business-rule bounds jose has no concept of: the token's OWN declared\n // lifetime must never exceed the fixed TTL (even if a bug ever minted a\n // longer-lived but validly-signed token), iat must not be unreasonably\n // far in the future, and cid/host must bind this token to THIS request -\n // without that check a captured token replays onto any other request.\n if (\n claims.iat > now + CLOCK_SKEW_SECONDS ||\n claims.exp > claims.iat + GATEWAY_CLIENT_IP_TTL_SECONDS ||\n claims.cid !== options.expectedCid ||\n claims.host !== options.expectedHost\n ) {\n return null;\n }\n return claims;\n } catch {\n return null;\n }\n}\n"],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,OAAO;EAET,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"gateway-client-ip.mjs","names":["z.object","z.literal","z.string","z.number"],"sources":["../src/gateway-client-ip.ts"],"sourcesContent":["import { SignJWT, createLocalJWKSet, importJWK, jwtVerify, type JWK, type KeyLike } from 'jose';\nimport { z } from 'zod';\nimport { parseIpv6 } from './utils/client-ip';\n\nexport type { JWK, KeyLike } from 'jose';\n\n/**\n * Signed client-identity token minted by the Checkpoint Cloudflare gateway\n * worker and verified by an origin-side Checkpoint SDK (KYA-1121 follow-up).\n *\n * The gateway already forwards the connecting IP as the plain `KYA-Client-IP`\n * / `X-Forwarded-For` headers (see `proxy.ts`), which every adapter behind a\n * KNOWN, trusted peer (Cloudflare's own published edge ranges) can trust.\n * Behind an additional untrusted hop - e.g. a PaaS's own reverse proxy\n * (Railway, Render, Fly) sitting between Cloudflare and the origin - the\n * origin's TCP peer is that PaaS's proxy, not Cloudflare, so the plain\n * header can never be trusted there: any caller reaching the PaaS's edge\n * directly could set it too. This ES256-signed JWS carries the SAME claim\n * with a signature only the gateway's private key can produce, so an origin\n * can trust it regardless of what sits between it and the gateway.\n *\n * One gateway-wide asymmetric key (not a per-project secret): the worker\n * holds the private JWK (`GATEWAY_CLIENT_IP_SIGNING_JWK`), the platform\n * publishes the public JWK at `/.well-known/jwks.json`\n * (`GATEWAY_CLIENT_IP_PUBLIC_JWK`). Rotation is by `kid`.\n */\n\nexport const GATEWAY_CLIENT_IP_TOKEN_HEADER = 'KYA-Client-IP-Token';\nexport const GATEWAY_CLIENT_IP_ISSUER = 'checkpoint:gateway-client-ip:v1';\nexport const GATEWAY_CLIENT_IP_TYPE = 'checkpoint-client-ip+jwt';\n/**\n * Token lifetime, seconds. A verifier MUST additionally bind `cid`/`host` to\n * the request it's verifying (see {@link VerifyGatewayClientIpOptions}) -\n * without that binding, a token captured on an untrusted hop within this\n * window is replayable onto a DIFFERENT request the gateway never actually\n * saw, and the `ip` it carries is not inert: it feeds the same IP-reputation\n * and vendor-cross-match signals as any other resolved client IP, which do\n * influence the engine's enforcement decision. Binding `cid` (unique per\n * request) is what keeps a captured token scoped to the one request the\n * gateway minted it for.\n */\nexport const GATEWAY_CLIENT_IP_TTL_SECONDS = 60;\n/** Clock-skew allowance applied to `exp` (via jose's `clockTolerance`) and independently to `iat` below. */\nconst CLOCK_SKEW_SECONDS = 30;\n\nfunction isIpv4Literal(value: string): boolean {\n const parts = value.split('.');\n return (\n parts.length === 4 &&\n parts.every((part) => /^(0|[1-9]\\d{0,2})$/.test(part) && Number(part) <= 255)\n );\n}\n\n/** True when `value` is a literal IPv4 or IPv6 address - never resolves a hostname. */\nexport function isIpLiteral(value: string): boolean {\n // parseIpv6 is exported by client-ip.ts specifically for reuse by callers\n // that need to validate/mask an address, not just resolve one - reused\n // here rather than a second hand-rolled IPv6 parser.\n return isIpv4Literal(value) || parseIpv6(value) !== null;\n}\n\nexport const GatewayClientIpClaimsSchema = z.object({\n iss: z.literal(GATEWAY_CLIENT_IP_ISSUER),\n aud: z.string().min(1),\n ip: z.string().refine(isIpLiteral, 'ip must be a literal IPv4 or IPv6 address'),\n cid: z.string().min(1),\n host: z.string().min(1),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive(),\n});\nexport type GatewayClientIpClaims = z.infer<typeof GatewayClientIpClaimsSchema>;\n\nexport interface GatewayClientIpInput {\n aud: string;\n ip: string;\n cid: string;\n host: string;\n}\n\n/** The gateway's own EC P-256 public key, as published in `/.well-known/jwks.json`. */\nexport const GatewayClientIpPublicJwkSchema = z.object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n alg: z.literal('ES256'),\n use: z.literal('sig'),\n kid: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n});\n\n/** The private half the gateway worker holds (`GATEWAY_CLIENT_IP_SIGNING_JWK`). */\nexport const GatewayClientIpPrivateJwkSchema = GatewayClientIpPublicJwkSchema.extend({\n d: z.string().min(1),\n});\n\n/**\n * Import a gateway client-ip JWK (private or public half) into a usable jose\n * key. Callers on a hot path - the gateway worker signs on every proxied\n * request - should import once per isolate and reuse the resulting key\n * rather than calling this per request.\n */\nexport async function importGatewayClientIpSigningKey(jwk: JWK): Promise<KeyLike | Uint8Array> {\n return importJWK(jwk, 'ES256');\n}\n\n/**\n * Mint a compact JWS carrying the gateway's client-identity claim.\n * `privateKey` must already be imported (see {@link importGatewayClientIpSigningKey}) -\n * this function never imports a key itself, so a cached key can be reused\n * across every signed request.\n */\nexport async function signGatewayClientIp(\n privateKey: KeyLike | Uint8Array,\n kid: string,\n input: GatewayClientIpInput,\n now: number = Math.floor(Date.now() / 1000)\n): Promise<string> {\n if (!kid || !input.aud || !input.cid || !input.host || !isIpLiteral(input.ip)) {\n throw new Error('Invalid gateway client-ip signing input');\n }\n const claims: GatewayClientIpClaims = {\n iss: GATEWAY_CLIENT_IP_ISSUER,\n aud: input.aud,\n ip: input.ip,\n cid: input.cid,\n host: input.host,\n iat: now,\n exp: now + GATEWAY_CLIENT_IP_TTL_SECONDS,\n };\n return new SignJWT(claims)\n .setProtectedHeader({ alg: 'ES256', typ: GATEWAY_CLIENT_IP_TYPE, kid })\n .sign(privateKey);\n}\n\nexport interface VerifyGatewayClientIpOptions {\n /** The project this token must be scoped to (`routingEntry.projectId` on the gateway side). */\n projectId: string;\n /**\n * The CURRENT request's own correlation id (the same value the gateway\n * forwards as `x-kya-correlation-id`) - must equal the token's `cid` claim.\n * This is the binding that makes replay impossible: without it, a token\n * captured on an untrusted hop verifies against ANY request presenting it\n * within the TTL, not just the one the gateway minted it for.\n */\n expectedCid: string;\n /**\n * The CURRENT request's own public hostname - must equal the token's\n * `host` claim. On the Java SDK's `RemoteIpResolver.gateway(options)`,\n * this is the host component of the gateway's `KYA-Original-Origin`\n * header, NOT `X-Forwarded-Host`: a PaaS's own reverse proxy in front of\n * the origin (Railway, Render, Fly) commonly rewrites the latter from its\n * own Host-header-based routing, which would make this binding never\n * match on exactly the topology it defends (Cursor Bugbot, high) - see\n * `proxy.ts`, which sets `KYA-Original-Origin` unconditionally on every\n * proxied request to the same `hostname` this token's `host` claim signs.\n */\n expectedHost: string;\n now?: number;\n}\n\n/**\n * Verify a gateway client-ip token against a JWKS document (as served by\n * `/.well-known/jwks.json`) and return its claims, or `null` on ANY failure\n * - malformed token, unknown `kid`, wrong `alg`, a tampered/expired/\n * mismatched claim, or a `cid`/`host` that doesn't match the request being\n * verified. Never throws: a missing or invalid token must change nothing\n * about the caller's IP resolution.\n */\nexport async function verifyGatewayClientIp(\n token: string | undefined | null,\n jwks: { keys: JWK[] },\n options: VerifyGatewayClientIpOptions\n): Promise<GatewayClientIpClaims | null> {\n if (!token || !options.projectId || !options.expectedCid || !options.expectedHost) return null;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n try {\n // Only EC/P-256 keys are ever candidates - the JWKS also carries the\n // unrelated OAuth Ed25519 (OKP) key, which must never be considered here.\n const ecKeys = jwks.keys.filter((key) => key.kty === 'EC' && key.crv === 'P-256');\n if (ecKeys.length === 0) return null;\n const getKey = createLocalJWKSet({ keys: ecKeys });\n const { payload } = await jwtVerify(token, getKey, {\n algorithms: ['ES256'],\n issuer: GATEWAY_CLIENT_IP_ISSUER,\n audience: options.projectId,\n typ: GATEWAY_CLIENT_IP_TYPE,\n currentDate: new Date(now * 1000),\n clockTolerance: CLOCK_SKEW_SECONDS,\n });\n const parsed = GatewayClientIpClaimsSchema.safeParse(payload);\n if (!parsed.success) return null;\n const claims = parsed.data;\n // Business-rule bounds jose has no concept of: the token's OWN declared\n // lifetime must never exceed the fixed TTL (even if a bug ever minted a\n // longer-lived but validly-signed token), iat must not be unreasonably\n // far in the future, and cid/host must bind this token to THIS request -\n // without that check a captured token replays onto any other request.\n if (\n claims.iat > now + CLOCK_SKEW_SECONDS ||\n claims.exp > claims.iat + GATEWAY_CLIENT_IP_TTL_SECONDS ||\n claims.cid !== options.expectedCid ||\n claims.host !== options.expectedHost\n ) {\n return null;\n }\n return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,eACvB,OAAO,SAAS,QAAQ,cAExB,OAAO;EAET,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as ACCEPT_CHALLENGE_HEADER, B as VERDICT_COOKIE_NAME, C as buildDelegationBearerHeader, D as buildDelegationInstructions, E as buildDelegationChallengeHeader, F as BLOCKED_PATH, H as deriveVerdict, I as ResponseShape, L as classifyResponseShape, M as FetcherHeaderInput, N as selectBodyReadable200, O as deriveDelegationPickupUri, P as serveBodyReadable200, R as acceptsHtml, S as buildChallengeWire, T as buildDelegationChallengeEnvelope, U as encodeVerdictCookie, V as Verdict, _ as DelegationChallengeBody, a as ResolveBotSignalsInput, b as DelegationChallengeWireInput, c as ChallengeContextFailureEvent, d as resolveChallengeContext, f as ApprovalQuorumChallengeWireInput, g as ChallengeWireKind, h as ChallengeWireInput, i as CloudflareRequestCf, j as ChallengeEnvelopeMode, k as generateDelegationSid, l as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, m as ChallengeWireErrorCode, n as BotSignalsSource, o as resolveBotSignals, p as ChallengeWireError, r as BotSignalsTrustPolicy, s as ChallengeContextFailure, t as BotSignalsResolution, u as ResolveChallengeContextOptions, v as DelegationChallengeEnvelope, w as buildDelegationChallengeBody, x as HeaderEntry, y as DelegationChallengeEnvelopeMode, z as RenderedResponseLike } from "../index-
|
|
1
|
+
import { A as ACCEPT_CHALLENGE_HEADER, B as VERDICT_COOKIE_NAME, C as buildDelegationBearerHeader, D as buildDelegationInstructions, E as buildDelegationChallengeHeader, F as BLOCKED_PATH, H as deriveVerdict, I as ResponseShape, L as classifyResponseShape, M as FetcherHeaderInput, N as selectBodyReadable200, O as deriveDelegationPickupUri, P as serveBodyReadable200, R as acceptsHtml, S as buildChallengeWire, T as buildDelegationChallengeEnvelope, U as encodeVerdictCookie, V as Verdict, _ as DelegationChallengeBody, a as ResolveBotSignalsInput, b as DelegationChallengeWireInput, c as ChallengeContextFailureEvent, d as resolveChallengeContext, f as ApprovalQuorumChallengeWireInput, g as ChallengeWireKind, h as ChallengeWireInput, i as CloudflareRequestCf, j as ChallengeEnvelopeMode, k as generateDelegationSid, l as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, m as ChallengeWireErrorCode, n as BotSignalsSource, o as resolveBotSignals, p as ChallengeWireError, r as BotSignalsTrustPolicy, s as ChallengeContextFailure, t as BotSignalsResolution, u as ResolveChallengeContextOptions, v as DelegationChallengeEnvelope, w as buildDelegationChallengeBody, x as HeaderEntry, y as DelegationChallengeEnvelopeMode, z as RenderedResponseLike } from "../index-rvw5Bz-r.mjs";
|
|
2
2
|
export { ACCEPT_CHALLENGE_HEADER, type ApprovalQuorumChallengeWireInput, BLOCKED_PATH, type BotSignalsResolution, type BotSignalsSource, type BotSignalsTrustPolicy, type ChallengeContextFailure, type ChallengeContextFailureEvent, type ChallengeEnvelopeMode, ChallengeWireError, type ChallengeWireErrorCode, type ChallengeWireInput, type ChallengeWireKind, type CloudflareRequestCf, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, type DelegationChallengeBody, type DelegationChallengeEnvelope, type DelegationChallengeEnvelopeMode, type DelegationChallengeWireInput, type FetcherHeaderInput, type HeaderEntry, type RenderedResponseLike, type ResolveBotSignalsInput, type ResolveChallengeContextOptions, type ResponseShape, VERDICT_COOKIE_NAME, type Verdict, acceptsHtml, buildChallengeWire, buildDelegationBearerHeader, buildDelegationChallengeBody, buildDelegationChallengeEnvelope, buildDelegationChallengeHeader, buildDelegationInstructions, classifyResponseShape, deriveDelegationPickupUri, deriveVerdict, encodeVerdictCookie, generateDelegationSid, resolveBotSignals, resolveChallengeContext, selectBodyReadable200, serveBodyReadable200 };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as ACCEPT_CHALLENGE_HEADER, B as VERDICT_COOKIE_NAME, C as buildDelegationBearerHeader, D as buildDelegationInstructions, E as buildDelegationChallengeHeader, F as BLOCKED_PATH, H as deriveVerdict, I as ResponseShape, L as classifyResponseShape, M as FetcherHeaderInput, N as selectBodyReadable200, O as deriveDelegationPickupUri, P as serveBodyReadable200, R as acceptsHtml, S as buildChallengeWire, T as buildDelegationChallengeEnvelope, U as encodeVerdictCookie, V as Verdict, _ as DelegationChallengeBody, a as ResolveBotSignalsInput, b as DelegationChallengeWireInput, c as ChallengeContextFailureEvent, d as resolveChallengeContext, f as ApprovalQuorumChallengeWireInput, g as ChallengeWireKind, h as ChallengeWireInput, i as CloudflareRequestCf, j as ChallengeEnvelopeMode, k as generateDelegationSid, l as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, m as ChallengeWireErrorCode, n as BotSignalsSource, o as resolveBotSignals, p as ChallengeWireError, r as BotSignalsTrustPolicy, s as ChallengeContextFailure, t as BotSignalsResolution, u as ResolveChallengeContextOptions, v as DelegationChallengeEnvelope, w as buildDelegationChallengeBody, x as HeaderEntry, y as DelegationChallengeEnvelopeMode, z as RenderedResponseLike } from "../index-
|
|
1
|
+
import { A as ACCEPT_CHALLENGE_HEADER, B as VERDICT_COOKIE_NAME, C as buildDelegationBearerHeader, D as buildDelegationInstructions, E as buildDelegationChallengeHeader, F as BLOCKED_PATH, H as deriveVerdict, I as ResponseShape, L as classifyResponseShape, M as FetcherHeaderInput, N as selectBodyReadable200, O as deriveDelegationPickupUri, P as serveBodyReadable200, R as acceptsHtml, S as buildChallengeWire, T as buildDelegationChallengeEnvelope, U as encodeVerdictCookie, V as Verdict, _ as DelegationChallengeBody, a as ResolveBotSignalsInput, b as DelegationChallengeWireInput, c as ChallengeContextFailureEvent, d as resolveChallengeContext, f as ApprovalQuorumChallengeWireInput, g as ChallengeWireKind, h as ChallengeWireInput, i as CloudflareRequestCf, j as ChallengeEnvelopeMode, k as generateDelegationSid, l as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, m as ChallengeWireErrorCode, n as BotSignalsSource, o as resolveBotSignals, p as ChallengeWireError, r as BotSignalsTrustPolicy, s as ChallengeContextFailure, t as BotSignalsResolution, u as ResolveChallengeContextOptions, v as DelegationChallengeEnvelope, w as buildDelegationChallengeBody, x as HeaderEntry, y as DelegationChallengeEnvelopeMode, z as RenderedResponseLike } from "../index-DnFsmr_o.js";
|
|
2
2
|
export { ACCEPT_CHALLENGE_HEADER, type ApprovalQuorumChallengeWireInput, BLOCKED_PATH, type BotSignalsResolution, type BotSignalsSource, type BotSignalsTrustPolicy, type ChallengeContextFailure, type ChallengeContextFailureEvent, type ChallengeEnvelopeMode, ChallengeWireError, type ChallengeWireErrorCode, type ChallengeWireInput, type ChallengeWireKind, type CloudflareRequestCf, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, type DelegationChallengeBody, type DelegationChallengeEnvelope, type DelegationChallengeEnvelopeMode, type DelegationChallengeWireInput, type FetcherHeaderInput, type HeaderEntry, type RenderedResponseLike, type ResolveBotSignalsInput, type ResolveChallengeContextOptions, type ResponseShape, VERDICT_COOKIE_NAME, type Verdict, acceptsHtml, buildChallengeWire, buildDelegationBearerHeader, buildDelegationChallengeBody, buildDelegationChallengeEnvelope, buildDelegationChallengeHeader, buildDelegationInstructions, classifyResponseShape, deriveDelegationPickupUri, deriveVerdict, encodeVerdictCookie, generateDelegationSid, resolveBotSignals, resolveChallengeContext, selectBodyReadable200, serveBodyReadable200 };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_host_adapter = require('../host-adapter-
|
|
2
|
+
const require_host_adapter = require('../host-adapter-bWftXA9T.js');
|
|
3
3
|
|
|
4
4
|
exports.ACCEPT_CHALLENGE_HEADER = require_host_adapter.ACCEPT_CHALLENGE_HEADER;
|
|
5
5
|
exports.BLOCKED_PATH = require_host_adapter.BLOCKED_PATH;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { _ as acceptsHtml, a as buildDelegationBearerHeader, b as encodeVerdictCookie, c as buildDelegationChallengeHeader, d as generateDelegationSid, f as ACCEPT_CHALLENGE_HEADER, g as classifyResponseShape, h as BLOCKED_PATH, i as buildChallengeWire, l as buildDelegationInstructions, m as serveBodyReadable200, n as resolveChallengeContext, o as buildDelegationChallengeBody, p as selectBodyReadable200, r as ChallengeWireError, s as buildDelegationChallengeEnvelope, t as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, u as deriveDelegationPickupUri, v as VERDICT_COOKIE_NAME, x as resolveBotSignals, y as deriveVerdict } from "../host-adapter-
|
|
1
|
+
import { _ as acceptsHtml, a as buildDelegationBearerHeader, b as encodeVerdictCookie, c as buildDelegationChallengeHeader, d as generateDelegationSid, f as ACCEPT_CHALLENGE_HEADER, g as classifyResponseShape, h as BLOCKED_PATH, i as buildChallengeWire, l as buildDelegationInstructions, m as serveBodyReadable200, n as resolveChallengeContext, o as buildDelegationChallengeBody, p as selectBodyReadable200, r as ChallengeWireError, s as buildDelegationChallengeEnvelope, t as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, u as deriveDelegationPickupUri, v as VERDICT_COOKIE_NAME, x as resolveBotSignals, y as deriveVerdict } from "../host-adapter-BKdQHwbi.mjs";
|
|
2
2
|
|
|
3
3
|
export { ACCEPT_CHALLENGE_HEADER, BLOCKED_PATH, ChallengeWireError, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, VERDICT_COOKIE_NAME, acceptsHtml, buildChallengeWire, buildDelegationBearerHeader, buildDelegationChallengeBody, buildDelegationChallengeEnvelope, buildDelegationChallengeHeader, buildDelegationInstructions, classifyResponseShape, deriveDelegationPickupUri, deriveVerdict, encodeVerdictCookie, generateDelegationSid, resolveBotSignals, resolveChallengeContext, selectBodyReadable200, serveBodyReadable200 };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-
|
|
1
|
+
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-DSBrxNry.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/utils/detection-class.ts
|
|
4
4
|
/**
|
|
@@ -590,4 +590,4 @@ var ChallengeContextTimeoutError = class extends Error {
|
|
|
590
590
|
|
|
591
591
|
//#endregion
|
|
592
592
|
export { enumToDetectionClass as C, normalizeDetectionClassEnum as D, normalizeDetectionClass as E, detectionClassToEnum as S, migrateLegacyDetectionClass as T, acceptsHtml as _, buildDelegationBearerHeader as a, encodeVerdictCookie as b, buildDelegationChallengeHeader as c, generateDelegationSid as d, ACCEPT_CHALLENGE_HEADER as f, classifyResponseShape as g, BLOCKED_PATH as h, buildChallengeWire as i, buildDelegationInstructions as l, serveBodyReadable200 as m, resolveChallengeContext as n, buildDelegationChallengeBody as o, selectBodyReadable200 as p, ChallengeWireError as r, buildDelegationChallengeEnvelope as s, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS as t, deriveDelegationPickupUri as u, VERDICT_COOKIE_NAME as v, isLegacyDetectionClass as w, resolveBotSignals as x, deriveVerdict as y };
|
|
593
|
-
//# sourceMappingURL=host-adapter-
|
|
593
|
+
//# sourceMappingURL=host-adapter-BKdQHwbi.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-adapter-DHyISsIf.mjs","names":[],"sources":["../src/utils/detection-class.ts","../src/utils/bot-signals.ts","../src/host-adapter/verdict-cookie.ts","../src/host-adapter/content-negotiation.ts","../src/host-adapter/decision-mapping.ts","../src/host-adapter/fetcher-envelope.ts","../src/host-adapter/challenge-wire.ts","../src/host-adapter/challenge-context.ts"],"sourcesContent":["/**\n * Utilities for converting between DetectionClass discriminated union and database enum\n */\n\nimport type { DetectionClass } from '../core/detection';\n\n// Database enum values (post-migration 0029)\n// Legacy values ('automation', 'unknown') are handled in conversion functions for backwards compatibility\nexport type DetectionClassEnum = 'human' | 'ai_agent' | 'bot' | 'incomplete_data';\n\n/**\n * Convert DetectionClass discriminated union to database enum string\n * Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively\n */\nexport function detectionClassToEnum(detectionClass: DetectionClass): DetectionClassEnum {\n switch (detectionClass.type) {\n case 'Human':\n return 'human';\n case 'AiAgent':\n return 'ai_agent';\n case 'Automation':\n // Legacy: Automation → Bot (migration 0029)\n return 'bot';\n case 'Bot':\n return 'bot';\n case 'IncompleteData':\n return 'incomplete_data';\n case 'Unknown':\n default:\n // Legacy: Unknown → IncompleteData (migration 0029)\n return 'incomplete_data';\n }\n}\n\n/**\n * Convert database enum string to DetectionClass discriminated union\n * Handles both current and legacy enum values for backwards compatibility\n */\nexport function enumToDetectionClass(enumValue: DetectionClassEnum | string): DetectionClass {\n switch (enumValue) {\n case 'human':\n return { type: 'Human' };\n case 'ai_agent':\n return { type: 'AiAgent' };\n case 'automation':\n // Legacy value: convert to Bot for consistency\n return { type: 'Bot' };\n case 'bot':\n return { type: 'Bot' };\n case 'incomplete_data':\n return { type: 'IncompleteData' };\n case 'unknown':\n // Legacy value: convert to IncompleteData for consistency\n return { type: 'IncompleteData' };\n default:\n return { type: 'IncompleteData' };\n }\n}\n\n/**\n * Check if a value is a valid string-based detection class (current or legacy)\n */\nexport function isLegacyDetectionClass(value: unknown): value is DetectionClassEnum {\n return (\n typeof value === 'string' &&\n // Current values + legacy values for backwards compatibility\n ['human', 'ai_agent', 'bot', 'incomplete_data', 'automation', 'unknown'].includes(value)\n );\n}\n\n/**\n * Migrate legacy string detection class to new discriminated union\n * @deprecated Use enumToDetectionClass instead\n */\nexport function migrateLegacyDetectionClass(value: string): DetectionClass {\n return enumToDetectionClass(value);\n}\n\n/**\n * Safely convert any detection class value to the discriminated union format\n */\nexport function normalizeDetectionClass(value: unknown): DetectionClass {\n // If it's already a discriminated union, return as-is\n if (value && typeof value === 'object' && 'type' in value) {\n return value as DetectionClass;\n }\n\n // If it's a valid string enum (current or legacy), convert it\n if (isLegacyDetectionClass(value)) {\n return enumToDetectionClass(value);\n }\n\n // Default fallback (migration 0029)\n return { type: 'IncompleteData' };\n}\n\n/**\n * Safely convert any detection class value to database enum format\n */\nexport function normalizeDetectionClassEnum(value: unknown): DetectionClassEnum {\n // If it's a discriminated union, convert to enum\n if (value && typeof value === 'object' && 'type' in value) {\n return detectionClassToEnum(value as DetectionClass);\n }\n\n // If it's a valid string enum (current or legacy), convert to current enum\n if (isLegacyDetectionClass(value)) {\n // Convert through discriminated union to handle legacy values properly\n return detectionClassToEnum(enumToDetectionClass(value));\n }\n\n // Default fallback (migration 0029)\n return 'incomplete_data';\n}\n","/**\n * Runtime-agnostic Cloudflare bot-management signal resolution.\n *\n * Ports the client-ip.ts trust-policy pattern (#4814) to bot signals, for\n * the class of bug PR #4269 shipped and #4282 reverted same-day: #4269 set\n * `KYA-CF-Bot-Score`/`KYA-CF-Verified-Bot` headers on the gateway's\n * origin-bound proxy request, then read them back from a completely\n * different request object (the ingest API call) — a header handoff across\n * a trust boundary. It also treated Cloudflare's bot score `0` as the\n * strongest possible bot signal, when Cloudflare defines `0` as \"Bot\n * Management did not run for this request,\" not \"confirmed bot.\"\n *\n * Same-request-object rule: this resolver only ever consumes the candidate\n * object the trusted runtime handed the CALLER directly (`request.cf` on a\n * Cloudflare Worker) — never a value forwarded via a header on a different\n * request object. Callers must pass their own `request.cf` straight through,\n * not something re-derived from headers.\n */\n\nexport type BotSignalsSource = 'cloudflare-bot-management' | 'explicit' | 'none';\n\nexport interface BotSignalsResolution {\n /**\n * 1-99 only. Cloudflare defines `0` as \"not computed\" (Bot Management\n * didn't run), not \"confirmed bot\" — `0` and any out-of-range value\n * normalize to `undefined` here, never surfaced as a real score.\n */\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n asn?: number;\n asOrganization?: string;\n source: BotSignalsSource;\n}\n\nexport type BotSignalsTrustPolicy =\n | { platform: 'cloudflare' }\n | { platform: 'vercel' }\n | { platform: 'trusted-proxy' }\n | { platform: 'direct' };\n\n/**\n * The subset of Cloudflare's `request.cf` this resolver reads. Pass\n * `request.cf` (or an equivalent test double) directly — `botManagement`\n * only populates when Bot Management is enabled on the zone; `asn`/\n * `asOrganization` are separate top-level `request.cf` fields, not nested\n * inside `botManagement`.\n */\nexport interface CloudflareRequestCf {\n botManagement?: {\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n } | null;\n asn?: number | null;\n asOrganization?: string | null;\n}\n\nexport interface ResolveBotSignalsInput {\n /**\n * `request.cf` from the SAME request object being classified. Cloudflare\n * is the only platform with a bot-management surface today — no\n * framework-provided equivalent exists yet on Vercel/Express/etc., so\n * this is the sole real candidate source; `policy` still selects per\n * runtime so a future platform's equivalent slots in without a redesign.\n */\n cloudflareRequestCf?: CloudflareRequestCf | null;\n /** Only honored when the caller has independently authenticated it (tests). */\n explicitBotSignals?: Omit<BotSignalsResolution, 'source'> | null;\n explicitBotSignalsTrusted?: boolean;\n policy: BotSignalsTrustPolicy;\n}\n\n/** Cloudflare bot score: only 1-99 are real values; 0 or out-of-range normalize to absent. */\nfunction normalizeBotScore(raw: number | null | undefined): number | undefined {\n if (typeof raw !== 'number' || !Number.isFinite(raw) || !Number.isInteger(raw)) return undefined;\n if (raw < 1 || raw > 99) return undefined;\n return raw;\n}\n\nfunction normalizeVerifiedBot(raw: boolean | null | undefined): boolean | undefined {\n return typeof raw === 'boolean' ? raw : undefined;\n}\n\nfunction normalizeString(raw: string | null | undefined): string | undefined {\n return raw && raw.length > 0 ? raw : undefined;\n}\n\nfunction normalizeAsn(raw: number | null | undefined): number | undefined {\n return typeof raw === 'number' && Number.isFinite(raw) && Number.isInteger(raw) && raw > 0\n ? raw\n : undefined;\n}\n\nfunction resolveExplicit(input: ResolveBotSignalsInput): BotSignalsResolution | null {\n if (input.explicitBotSignalsTrusted !== true || !input.explicitBotSignals) return null;\n const explicit = input.explicitBotSignals;\n return {\n score: normalizeBotScore(explicit.score),\n verifiedBot: normalizeVerifiedBot(explicit.verifiedBot),\n ja4: normalizeString(explicit.ja4),\n asn: normalizeAsn(explicit.asn),\n asOrganization: normalizeString(explicit.asOrganization),\n source: 'explicit',\n };\n}\n\nfunction resolveCloudflare(input: ResolveBotSignalsInput): BotSignalsResolution {\n const cf = input.cloudflareRequestCf;\n if (!cf) return { source: 'none' };\n\n return {\n score: normalizeBotScore(cf.botManagement?.score),\n verifiedBot: normalizeVerifiedBot(cf.botManagement?.verifiedBot),\n ja4: normalizeString(cf.botManagement?.ja4),\n asn: normalizeAsn(cf.asn),\n asOrganization: normalizeString(cf.asOrganization),\n source: 'cloudflare-bot-management',\n };\n}\n\n/** Resolve bot signals using an explicit deployment trust profile. */\nexport function resolveBotSignals(input: ResolveBotSignalsInput): BotSignalsResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'vercel':\n case 'trusted-proxy':\n case 'direct':\n // No bot-management (or equivalent) surface on these platforms today —\n // resolves cleanly absent rather than guessing at a shape that doesn't\n // exist yet. Add a resolve function here if/when one does.\n return { source: 'none' };\n }\n}\n","/**\n * Verdict cookie — byte-format contract shared across host runtimes.\n *\n * Sites-1's Sonner toast depends on `__checkpoint_verdict=%7B%22verdict%22\n * %3A%22<v>%22...%7D` (single URL-encoded JSON). If this format drifts,\n * the toast renders incorrectly or not at all.\n *\n * Phase E (#TBD) extracted these helpers from `checkpoint-nextjs/src/\n * adapt.ts` so the Express host (and any future host) can reproduce the\n * exact same cookie shape. The runtime-specific cookie-write call (e.g.\n * `NextResponse.cookies.set()` vs `express.Response.cookie()`) stays in\n * each host's `adapt.ts`; only the encoding logic is shared.\n *\n * **Return raw JSON, not URL-encoded.** Both Next.js's cookies API and\n * Express's `res.cookie()` URL-encode the value when serializing to the\n * Set-Cookie header (per RFC 6265 + each framework's cookie library).\n * Pre-encoding here would double-encode (`%7B` → `%257B`) and break\n * Sonner.\n */\n\n/**\n * Structural view of the orchestrator's `RenderedResponse` — just the\n * fields these helpers need. Defined locally to avoid a circular\n * dependency between `checkpoint-shared` and `checkpoint-wasm-runtime`\n * (the canonical owner of the full type). The actual type from\n * `@kya-os/checkpoint-wasm-runtime/orchestrator` is structurally\n * assignable to this.\n */\nexport interface RenderedResponseLike {\n /** HTTP status — `null` means pass-through (Permit / Observe). */\n status: number | null;\n /** Engine-emitted response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Canonical cookie name. Sites-1's `/blocked` page reads from this\n * exact key; do not rename without updating the dashboard route.\n */\nexport const VERDICT_COOKIE_NAME = '__checkpoint_verdict';\n\n/**\n * The three-state verdict surfaced to client-side UI. Maps from the\n * `RenderedResponse.status` field (which itself maps from the engine's\n * `Decision` variant).\n *\n * - `'allowed'` — Permit, or Observe-mode (any verdict, status null)\n * - `'redirected'` — Decision::Redirect → status 302\n * - `'denied'` — Decision::Block / Challenge / Instruct (4xx)\n */\nexport type Verdict = 'allowed' | 'denied' | 'redirected';\n\n/**\n * Compute the verdict label from a `RenderedResponse`.\n */\nexport function deriveVerdict(rendered: RenderedResponseLike): Verdict {\n if (rendered.status === null) return 'allowed';\n if (rendered.status === 302) return 'redirected';\n return 'denied';\n}\n\n/**\n * Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast\n * reads. Byte-format pinned by tests in both `checkpoint-nextjs` and\n * `checkpoint-express`:\n *\n * - allowed: `{\"verdict\":\"allowed\"}`\n * - denied: `{\"verdict\":\"denied\",\"reason\":\"<r>\"}`\n * - redirected: `{\"verdict\":\"redirected\"}`\n *\n * Returns raw JSON; the host's cookie-write call URL-encodes.\n */\nexport function encodeVerdictCookie(rendered: RenderedResponseLike): string {\n const verdict = deriveVerdict(rendered);\n const reason = rendered.headers['X-Checkpoint-Reason'];\n const value = reason ? { verdict, reason } : { verdict };\n return JSON.stringify(value);\n}\n","/**\n * Content negotiation — framework-agnostic Accept-header parsing for\n * host adapters.\n *\n * The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching\n * decisions; the host wrapper does that based on what the client\n * accepts. Both Next.js (NextRequest) and Express (Request) carry the\n * Accept header in different shapes — `req.headers.get('accept')` vs\n * `req.get('Accept')` vs `req.headers.accept` — so we accept any\n * Headers-like input and do the parsing here.\n */\n\n/**\n * `true` when the client signaled it accepts HTML or XHTML. Used by\n * host adapters to choose between an HTML `/blocked` rewrite (browsers)\n * and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).\n *\n * Loose match — q-values, parameters, and additional MIME types are\n * allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't\n * matter here; we only care whether HTML is present at all.\n *\n * Accepts:\n * - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)\n * - a plain `Record<string, string>` (Express, Connect, Fastify)\n * - a single string (caller already extracted the Accept value)\n * - `undefined` (treated as no-HTML)\n */\nexport function acceptsHtml(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): boolean {\n const accept = extractAccept(input);\n if (!accept) return false;\n return accept.includes('text/html') || accept.includes('application/xhtml+xml');\n}\n\nfunction extractAccept(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): string | undefined {\n if (!input) return undefined;\n if (typeof input === 'string') return input;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get('accept') ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 § 5.1);\n // try both common casings. Express lowercases by default; Next.js\n // header objects also lowercase.\n const rec = input as Record<string, string | string[] | undefined>;\n const value = rec.accept ?? rec.Accept;\n if (Array.isArray(value)) return value.join(',');\n return value;\n}\n","/**\n * Decision mapping — framework-agnostic classification of\n * `RenderedResponse` shapes that drive host-adapter branching.\n *\n * Phase D's `checkpoint-nextjs/src/adapt.ts` open-coded these four\n * branches (pass-through / redirect / HTML-block / JSON-block). Phase E\n * extracted them so the Express adapter — and any future host — can\n * share the classifier. The actual response construction stays\n * framework-specific (NextResponse.next() vs Express res.status().json()).\n */\n\nimport type { RenderedResponseLike } from './verdict-cookie';\n\n/**\n * Path the `/blocked` dashboard route lives at. HTML clients that hit\n * a 4xx verdict get rewritten here at status 200 so the page renders\n * with the verdict cookie set and Sonner can pick up the toast.\n *\n * Hard-coded by convention; if a customer ever needs a custom path,\n * pass it through `CheckpointConfig.blockedPath` and override in the\n * host adapter (not in this lookup).\n */\nexport const BLOCKED_PATH = '/blocked';\n\n/**\n * The four mutually-exclusive shapes a `RenderedResponse` can take,\n * driving the host adapter's branching. The host renders each shape\n * with its framework-native primitives.\n */\nexport type ResponseShape =\n /** Permit (status null) OR Observe-mode any-verdict — pass through with cookie + headers. */\n | 'pass-through'\n /** Decision::Redirect → 302 + Location header. */\n | 'redirect'\n /** 4xx + HTML-accepting client → rewrite to `/blocked` at status 200 for Sonner. */\n | 'html-block'\n /** 4xx + non-HTML client (or 5xx) → JSON body at the orchestrator's status. */\n | 'json-block';\n\n/**\n * Classify a `RenderedResponse` into one of the four host-adapter\n * branches. `clientAcceptsHtml` comes from `acceptsHtml()` in\n * `content-negotiation.ts`.\n */\nexport function classifyResponseShape(\n rendered: RenderedResponseLike,\n clientAcceptsHtml: boolean\n): ResponseShape {\n if (rendered.status === null) return 'pass-through';\n if (rendered.status === 302 && rendered.headers.Location) return 'redirect';\n if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return 'html-block';\n return 'json-block';\n}\n","/**\n * Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).\n *\n * AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx\n * responses and never surface the body to the LLM, so the §8.1 step-up\n * challenge served at 401 is invisible. The fix is a dual envelope: keep\n * the spec 401 for capable/discovery clients, and serve a body-readable\n * HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying\n * agents so they can read the body + relay the consent link.\n *\n * `serveBodyReadable200` is the shared selection predicate every TS PEP\n * (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its\n * challenge-emission mode is `negotiated`. Centralising it here — rather\n * than re-implementing per PEP — makes drift structurally impossible; the\n * fetcher-200 fixture freezes envelope BYTES, this function freezes the\n * SELECTION.\n *\n * **This is a cooperative-UX bridge, NOT an access control.** A spoofer\n * that hides its identity and does not opt in simply receives the spec\n * 401 (and the original body-drop). Access is still gated entirely by the\n * unchanged detection + delegation verification — never by which envelope\n * is selected.\n */\n\nimport { normalizeDetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Header inputs the predicate accepts — a WHATWG `Headers`, a plain\n * header record (Express/Next.js style), or absent. Mirrors the input\n * union `acceptsHtml` accepts so callers pass their native headers\n * unchanged.\n */\nexport type FetcherHeaderInput =\n | Headers\n | Record<string, string | string[] | undefined>\n | undefined;\n\n/**\n * Durable opt-in header — the primary, framework-agnostic signal that a\n * caller is a cooperative agent able to handle the 200 fetcher envelope.\n * Any non-empty value counts as opt-in (value semantics are reconciled\n * with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).\n */\nexport const ACCEPT_CHALLENGE_HEADER = 'kya-accept-challenge';\n\nfunction readHeader(input: FetcherHeaderInput, name: string): string | undefined {\n if (!input) return undefined;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get(name) ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 §5.1).\n const rec = input as Record<string, string | string[] | undefined>;\n const lower = name.toLowerCase();\n for (const key of Object.keys(rec)) {\n if (key.toLowerCase() === lower) {\n const v = rec[key];\n return Array.isArray(v) ? v[0] : (v ?? undefined);\n }\n }\n return undefined;\n}\n\n/**\n * Decide whether a `negotiated`-mode PEP should serve the body-readable\n * HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).\n *\n * Serve 200 when EITHER:\n * 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header\n * (the durable, primary signal), OR\n * 2. detection classifies the caller as an AI agent — BOTH `isAgent` and\n * `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,\n * retired as frameworks adopt the header).\n *\n * Otherwise serve the 401 — spoofers, silent, discovery, and OAuth\n * clients all land here, which is acceptable because this is UX, not a\n * security boundary.\n *\n * Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic\n * mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==\n * AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on\n * the pathological case where the two signals disagree (class says agent,\n * `isAgent` says no): that caller is treated as non-cooperative (spec 401),\n * never demoted past it. In normal engine output the two signals agree, so\n * who-gets-200 is unchanged for real traffic.\n *\n * @param headers request headers (for the opt-in signal)\n * @param detectionClass the caller's detection class in any representation\n * the engine produces (a `DetectionClass` object, the\n * `ai_agent` wire string, or absent)\n * @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`\n * heuristic so a class/`isAgent` disagreement gets the 401\n */\nexport function serveBodyReadable200(\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n // 1. Durable, primary signal: explicit opt-in header (independent of isAgent).\n const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);\n if (optIn && optIn.trim().length > 0) return true;\n\n // 2. Transitional UA heuristic: a detected AI agent — both signals must agree.\n if (isAgent && detectionClass !== undefined && detectionClass !== null) {\n if (normalizeDetectionClassEnum(detectionClass) === 'ai_agent') return true;\n }\n\n // 3. Spec 401 path (non-cooperative / silent / discovery / signals-disagree).\n return false;\n}\n\n/**\n * Per-PEP challenge-emission mode (mirrors mcp-i-cloudflare's `mode` and\n * the .NET `DelegationChallengeMode`). The TS engine PEPs (express / nextjs)\n * default to `negotiated`; the gateway worker reads its default from\n * `KYA_HTTP_CHALLENGE_MODE` (negotiated in dev, unset → spec-401 until the\n * prod flip, #3321).\n *\n * - `spec-401` — always the spec 401.\n * - `negotiated` — 200 for cooperative agents (per `serveBodyReadable200`),\n * 401 otherwise.\n * - `always-200` — 200 for everyone (fetcher-first hosts / escape hatch).\n */\nexport type ChallengeEnvelopeMode = 'spec-401' | 'negotiated' | 'always-200';\n\n/**\n * Resolve the challenge-emission mode + request signals into the single\n * boolean each PEP needs: serve the body-readable 200 (`true`) or the spec\n * 401 (`false`). Centralising the mode gate here — not just the predicate —\n * keeps the rollout switch identical across every TS PEP.\n */\nexport function selectBodyReadable200(\n mode: ChallengeEnvelopeMode,\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n if (mode === 'always-200') return true;\n if (mode === 'negotiated') return serveBodyReadable200(headers, detectionClass, isAgent);\n return false;\n}\n","/**\n * Canonical fixture-pinned KYA HTTP challenge-wire builder.\n *\n * The builder is transport-neutral and Edge-safe. Hosts must register the\n * challenge and resolve every URI before calling it; this module validates and\n * serializes those trusted values without network, database, or request access.\n */\n\nimport { KYA_HTTP_ERROR } from '../mcpi/kya-http-error-codes';\nimport type { AssuranceTier } from '../policy/schemas';\n\nconst PROTECTED_RESOURCE_METADATA_PATH = '/.well-known/oauth-protected-resource';\nconst DEFAULT_POLL_INTERVAL_S = 3;\n// eslint-disable-next-line no-control-regex -- deliberate: reject RFC 9110 quoted-string-unsafe control characters, not a stray literal.\nconst INVALID_QUOTED_VALUE = /[\\u0000-\\u001f\\u007f\"\\\\]/;\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\nconst SID = /^kya-[0-9a-f]{16,}$/;\nconst ASSURANCE_TIERS = new Set<string>([\n 'anonymous',\n 'attested-bearer',\n 'key-bound',\n 'registered',\n 'delegated',\n]);\n\n/** Ordered HTTP header pair. Names may repeat. */\nexport type HeaderEntry = readonly [name: string, value: string];\n\nexport type ChallengeWireKind = 'delegation' | 'approval_quorum';\n\ninterface ChallengeWireInputBase {\n /** Protected-resource host, optionally including a port. */\n realm: string;\n /** Registered challenge/session identifier. */\n sid: string;\n /** Authorization-Host consent URL returned by registration. */\n consentUri: string;\n /** Authorization-Host pickup URL returned or resolved by registration. */\n pickupUri: string;\n /** Scopes demanded by policy. Empty means omit the optional scope parameter. */\n requiredScopes?: readonly string[];\n /** Optional poll cadence; omission retains the server default without an auth-param. */\n pollIntervalS?: number;\n /** Registered, signed proof. Opaque to the renderer. */\n challengeProof: unknown;\n /** Optional assurance floor demanded by policy. */\n minAssurance?: AssuranceTier;\n}\n\n/** Complete registered context for an OAuth-compatible delegation step-up. */\nexport interface DelegationChallengeWireInput extends ChallengeWireInputBase {\n kind?: 'delegation';\n /** Exact RFC 9728 discovery URI configured for the protected resource. */\n resourceMetadataUri: string;\n}\n\n/** Complete registered context for an N-of-M approval step-up. */\nexport interface ApprovalQuorumChallengeWireInput extends ChallengeWireInputBase {\n kind: 'approval_quorum';\n quorum: number;\n actionNonce: string;\n}\n\nexport type ChallengeWireInput = DelegationChallengeWireInput | ApprovalQuorumChallengeWireInput;\n\ninterface CommonChallengeKyaos {\n sid: string;\n consent_uri: string;\n pickup_uri: string;\n required_scopes?: string[];\n min_assurance?: AssuranceTier;\n poll_interval_s: number;\n challenge_proof: unknown;\n}\n\ninterface DelegationChallengeKyaos extends CommonChallengeKyaos {\n action: {\n type: 'delegation';\n consent_uri: string;\n pickup_uri: string;\n poll_interval_s: number;\n pin: { header: 'X-KYA-Pickup-Token' };\n retry: { header: 'Authorization'; scheme: 'Bearer'; value_from: 'delegation' };\n };\n}\n\ninterface ApprovalQuorumChallengeKyaos extends CommonChallengeKyaos {\n kind: 'approval_quorum';\n quorum: number;\n action_nonce: string;\n}\n\n/** Canonical body shared by the 401 and body-readable 200 envelopes. */\nexport interface DelegationChallengeBody {\n error: typeof KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED;\n kyaos: DelegationChallengeKyaos | ApprovalQuorumChallengeKyaos;\n instructions: string;\n}\n\nexport interface DelegationChallengeEnvelope {\n status: 401 | 200;\n headers: HeaderEntry[];\n body: DelegationChallengeBody;\n}\n\nexport type DelegationChallengeEnvelopeMode = 'spec-401' | 'fetcher-200';\n\nexport type ChallengeWireErrorCode =\n | 'invalid-realm'\n | 'invalid-sid'\n | 'invalid-uri'\n | 'invalid-scope'\n | 'invalid-assurance'\n | 'invalid-interval'\n | 'invalid-proof'\n | 'invalid-kind'\n | 'invalid-quorum'\n | 'invalid-action-nonce'\n | 'unsupported-envelope';\n\n/** Typed validation failure raised before any response is materialized. */\nexport class ChallengeWireError extends TypeError {\n readonly code: ChallengeWireErrorCode;\n\n constructor(code: ChallengeWireErrorCode, message: string) {\n super(message);\n this.name = 'ChallengeWireError';\n this.code = code;\n }\n}\n\n/** Generate a 128-bit, lower-case hexadecimal challenge id. */\nexport function generateDelegationSid(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return `kya-${hex}`;\n}\n\n/** Derive pickup from the registered consent origin, never request Host. */\nexport function deriveDelegationPickupUri(consentUri: string, sid: string): string {\n const consent = parseHttpsUrl('consentUri', consentUri);\n assertQuotedValue('sid', sid, 'invalid-sid');\n return `${consent.origin}/api/delegation/pickup/${sid}`;\n}\n\n/** Build the byte-pinned Delegation authentication field value. */\nexport function buildDelegationChallengeHeader(input: ChallengeWireInput): string {\n const normalized = validateInput(input);\n const params: Array<readonly [string, string]> = [\n ['realm', normalized.realm],\n ['sid', normalized.sid],\n ['consent_uri', normalized.consentUri],\n ['pickup_uri', normalized.pickupUri],\n ];\n if (normalized.requiredScopes.length > 0) {\n params.push(['scope', normalized.requiredScopes.join(' ')]);\n }\n if (normalized.minAssurance) {\n params.push(['min_assurance', normalized.minAssurance]);\n }\n if (input.pollIntervalS !== undefined) {\n params.push(['interval', String(normalized.pollIntervalS)]);\n }\n params.push(['kind', normalized.kind]);\n\n return `Delegation ${params.map(([name, value]) => `${name}=\"${value}\"`).join(', ')}`;\n}\n\n/** Build RFC 9728 Bearer discovery for a protected-resource realm. */\nexport function buildDelegationBearerHeader(realm: string): string {\n assertRealm(realm);\n return `Bearer resource_metadata=\"https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}\"`;\n}\n\n/** Build the four required machine-followable delegation instruction elements. */\nexport function buildDelegationInstructions(\n consentUri: string,\n pickupUri: string,\n pollIntervalS: number\n): string {\n return (\n `This action requires human authorization. First establish your pickup binding at ${pickupUri}. ` +\n `If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token encoded as unpadded base64url and send it as X-KYA-Pickup-Token on EVERY poll. ` +\n `After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. ` +\n `Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. ` +\n `When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`\n );\n}\n\n/** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */\nexport function buildDelegationChallengeBody(input: ChallengeWireInput): DelegationChallengeBody {\n const normalized = validateInput(input);\n const common: CommonChallengeKyaos = {\n sid: normalized.sid,\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n ...(normalized.requiredScopes.length > 0\n ? { required_scopes: [...normalized.requiredScopes] }\n : {}),\n ...(normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {}),\n poll_interval_s: normalized.pollIntervalS,\n challenge_proof: input.challengeProof,\n };\n\n if (normalized.kind === 'approval_quorum') {\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n sid: common.sid,\n kind: 'approval_quorum',\n quorum: normalized.quorum!,\n action_nonce: normalized.actionNonce!,\n consent_uri: common.consent_uri,\n pickup_uri: common.pickup_uri,\n ...(common.required_scopes ? { required_scopes: common.required_scopes } : {}),\n ...(common.min_assurance ? { min_assurance: common.min_assurance } : {}),\n poll_interval_s: common.poll_interval_s,\n challenge_proof: common.challenge_proof,\n },\n instructions: buildApprovalQuorumInstructions(normalized),\n };\n }\n\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n ...common,\n action: {\n type: 'delegation',\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n poll_interval_s: normalized.pollIntervalS,\n pin: { header: 'X-KYA-Pickup-Token' },\n retry: { header: 'Authorization', scheme: 'Bearer', value_from: 'delegation' },\n },\n },\n instructions: buildDelegationInstructions(\n normalized.consentUri,\n normalized.pickupUri,\n normalized.pollIntervalS\n ),\n };\n}\n\n/** Build either the canonical 401 or its body-identical fetcher-200 envelope. */\nexport function buildDelegationChallengeEnvelope(\n input: ChallengeWireInput,\n mode: DelegationChallengeEnvelopeMode = 'spec-401'\n): DelegationChallengeEnvelope {\n const normalized = validateInput(input);\n if (normalized.kind === 'approval_quorum' && mode === 'fetcher-200') {\n throw new ChallengeWireError(\n 'unsupported-envelope',\n 'fetcher-200 is not fixture-defined for approval_quorum'\n );\n }\n\n const body = buildDelegationChallengeBody(input);\n if (normalized.kind === 'approval_quorum') {\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['Retry-After', String(normalized.pollIntervalS)],\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ],\n body,\n };\n }\n\n const hintHeaders: HeaderEntry[] = [\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ['KYA-Auth-Required', 'true'],\n ['KYA-Auth-Url', normalized.consentUri],\n ['Link', `<${normalized.consentUri}>; rel=\"kya-authorize\"`],\n ['KYA-Action', 'challenge'],\n ];\n if (mode === 'fetcher-200') {\n return { status: 200, headers: hintHeaders, body };\n }\n\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['WWW-Authenticate', `Bearer resource_metadata=\"${normalized.resourceMetadataUri}\"`],\n ['Retry-After', String(normalized.pollIntervalS)],\n ...hintHeaders,\n ],\n body,\n };\n}\n\n/** Preferred generic name; the legacy export remains for host compatibility. */\nexport const buildChallengeWire = buildDelegationChallengeEnvelope;\n\ninterface ValidatedInput {\n realm: string;\n sid: string;\n consentUri: string;\n pickupUri: string;\n resourceMetadataUri?: string;\n requiredScopes: readonly string[];\n pollIntervalS: number;\n minAssurance?: AssuranceTier;\n kind: ChallengeWireKind;\n quorum?: number;\n actionNonce?: string;\n}\n\nfunction validateInput(input: ChallengeWireInput): ValidatedInput {\n assertRealm(input.realm);\n assertQuotedValue('sid', input.sid, 'invalid-sid');\n if (!SID.test(input.sid)) {\n throw new ChallengeWireError(\n 'invalid-sid',\n 'sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy'\n );\n }\n\n const consent = parseHttpsUrl('consentUri', input.consentUri);\n const pickup = parseHttpsUrl('pickupUri', input.pickupUri);\n const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;\n if (pickup.href !== expectedPickup) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'pickupUri must use the registered consent origin and sid'\n );\n }\n\n const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;\n if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) {\n throw new ChallengeWireError(\n 'invalid-interval',\n 'pollIntervalS must be an integer from 1 through 999'\n );\n }\n if (input.challengeProof === undefined || input.challengeProof === null) {\n throw new ChallengeWireError('invalid-proof', 'challengeProof is required');\n }\n const requiredScopes = input.requiredScopes ?? [];\n for (const scope of requiredScopes) {\n if (!SCOPE_TOKEN.test(scope)) {\n throw new ChallengeWireError('invalid-scope', `invalid required scope: ${scope}`);\n }\n }\n if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) {\n throw new ChallengeWireError(\n 'invalid-assurance',\n `invalid minAssurance: ${input.minAssurance}`\n );\n }\n\n const kind = input.kind ?? 'delegation';\n if (kind !== 'delegation' && kind !== 'approval_quorum') {\n throw new ChallengeWireError('invalid-kind', `unsupported challenge kind: ${String(kind)}`);\n }\n\n let resourceMetadataUri: string | undefined;\n let quorum: number | undefined;\n let actionNonce: string | undefined;\n if (kind === 'delegation') {\n resourceMetadataUri = parseHttpsUrl(\n 'resourceMetadataUri',\n (input as DelegationChallengeWireInput).resourceMetadataUri\n ).href;\n const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;\n if (resourceMetadataUri !== expectedMetadata) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'resourceMetadataUri must be the protected resource RFC 9728 metadata URL'\n );\n }\n } else {\n const approval = input as ApprovalQuorumChallengeWireInput;\n quorum = approval.quorum;\n actionNonce = approval.actionNonce;\n if (!Number.isInteger(quorum) || quorum < 1) {\n throw new ChallengeWireError('invalid-quorum', 'quorum must be a positive integer');\n }\n assertQuotedValue('actionNonce', actionNonce, 'invalid-action-nonce');\n }\n\n return {\n realm: input.realm,\n sid: input.sid,\n consentUri: consent.href,\n pickupUri: pickup.href,\n resourceMetadataUri,\n requiredScopes,\n pollIntervalS,\n minAssurance: input.minAssurance,\n kind,\n quorum,\n actionNonce,\n };\n}\n\nfunction buildApprovalQuorumInstructions(input: ValidatedInput): string {\n return (\n `This action requires approval from ${input.quorum} human approvers. ` +\n `Show your user this link to begin the approval process: ${input.consentUri}. ` +\n `Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). ` +\n `When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`\n );\n}\n\nfunction assertRealm(realm: string): void {\n assertQuotedValue('realm', realm, 'invalid-realm');\n if (realm.includes('/') || realm.includes('@') || realm.includes('?') || realm.includes('#')) {\n throw new ChallengeWireError('invalid-realm', 'realm must be a host with an optional port');\n }\n try {\n const parsed = new URL(`https://${realm}`);\n if (parsed.host !== realm) throw new Error('invalid authority');\n } catch {\n throw new ChallengeWireError(\n 'invalid-realm',\n 'realm must be a valid host with an optional port'\n );\n }\n}\n\nfunction assertQuotedValue(name: string, value: string, code: ChallengeWireErrorCode): void {\n if (typeof value !== 'string' || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) {\n throw new ChallengeWireError(\n code,\n `${name} contains characters unsafe for an HTTP quoted-string`\n );\n }\n}\n\nfunction parseHttpsUrl(name: string, value: string): URL {\n assertQuotedValue(name, value, 'invalid-uri');\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new ChallengeWireError('invalid-uri', `${name} must be an absolute HTTPS URL`);\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {\n throw new ChallengeWireError(\n 'invalid-uri',\n `${name} must be an absolute HTTPS URL without credentials`\n );\n }\n return parsed;\n}\n","import { buildChallengeWire, type ChallengeWireInput } from './challenge-wire';\n\nexport const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3000;\n\nexport type ChallengeContextFailure = 'timeout' | 'resolver-error' | 'invalid-context';\n\nexport interface ChallengeContextFailureEvent {\n reason: ChallengeContextFailure;\n message: string;\n}\n\nexport interface ResolveChallengeContextOptions {\n timeoutMs?: number;\n onFailure?: (event: ChallengeContextFailureEvent) => void;\n}\n\n/**\n * Resolve and validate registered challenge context at the async host boundary.\n * Resolver failures become an absent context so the renderer can emit the\n * canonical retryable status-pending response; secrets and proof values are\n * never included in failure events.\n */\nexport async function resolveChallengeContext<TContext>(\n resolver:\n | ((\n context: TContext\n ) => ChallengeWireInput | undefined | Promise<ChallengeWireInput | undefined>)\n | undefined,\n context: TContext,\n options: ResolveChallengeContextOptions = {}\n): Promise<ChallengeWireInput | undefined> {\n if (!resolver) return undefined;\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;\n if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {\n throw new TypeError('challenge context timeout must be a positive integer');\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const value = await Promise.race([\n Promise.resolve(resolver(context)),\n new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(\n () => reject(new ChallengeContextTimeoutError(timeoutMs)),\n timeoutMs\n );\n }),\n ]);\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n if (!value) return undefined;\n\n try {\n buildChallengeWire(value, 'spec-401');\n return value;\n } catch (error) {\n options.onFailure?.({\n reason: 'invalid-context',\n message: (error as Error).message,\n });\n return undefined;\n }\n } catch (error) {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n options.onFailure?.({\n reason: error instanceof ChallengeContextTimeoutError ? 'timeout' : 'resolver-error',\n message:\n error instanceof ChallengeContextTimeoutError\n ? error.message\n : 'challenge context resolver failed',\n });\n return undefined;\n }\n}\n\nclass ChallengeContextTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`challenge context resolution exceeded ${timeoutMs}ms`);\n this.name = 'ChallengeContextTimeoutError';\n }\n}\n"],"mappings":";;;;;;;AAcA,SAAgB,qBAAqB,gBAAoD;CACvF,QAAQ,eAAe,MAAvB;EACE,KAAK,SACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,cAEH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,kBACH,OAAO;EAET,SAEE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,qBAAqB,WAAwD;CAC3F,QAAQ,WAAR;EACE,KAAK,SACH,OAAO,EAAE,MAAM,QAAQ;EACzB,KAAK,YACH,OAAO,EAAE,MAAM,UAAU;EAC3B,KAAK,cAEH,OAAO,EAAE,MAAM,MAAM;EACvB,KAAK,OACH,OAAO,EAAE,MAAM,MAAM;EACvB,KAAK,mBACH,OAAO,EAAE,MAAM,iBAAiB;EAClC,KAAK,WAEH,OAAO,EAAE,MAAM,iBAAiB;EAClC,SACE,OAAO,EAAE,MAAM,iBAAiB;CACpC;AACF;;;;AAKA,SAAgB,uBAAuB,OAA6C;CAClF,OACE,OAAO,UAAU,YAEjB;EAAC;EAAS;EAAY;EAAO;EAAmB;EAAc;CAAS,CAAC,CAAC,SAAS,KAAK;AAE3F;;;;;AAMA,SAAgB,4BAA4B,OAA+B;CACzE,OAAO,qBAAqB,KAAK;AACnC;;;;AAKA,SAAgB,wBAAwB,OAAgC;CAEtE,IAAI,SAAS,OAAO,UAAU,YAAY,UAAU,OAClD,OAAO;CAIT,IAAI,uBAAuB,KAAK,GAC9B,OAAO,qBAAqB,KAAK;CAInC,OAAO,EAAE,MAAM,iBAAiB;AAClC;;;;AAKA,SAAgB,4BAA4B,OAAoC;CAE9E,IAAI,SAAS,OAAO,UAAU,YAAY,UAAU,OAClD,OAAO,qBAAqB,KAAuB;CAIrD,IAAI,uBAAuB,KAAK,GAE9B,OAAO,qBAAqB,qBAAqB,KAAK,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,QAAQ,YAAY;GAClB,QAAQ,iBAAiB,+BAA+B,YAAY;GACpE,SACE,iBAAiB,+BACb,MAAM,UACN;EACR,CAAC;EACD;CACF;AACF;AAEA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,YAAY,WAAmB;EAC7B,MAAM,yCAAyC,UAAU,GAAG;EAC5D,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"host-adapter-BKdQHwbi.mjs","names":[],"sources":["../src/utils/detection-class.ts","../src/utils/bot-signals.ts","../src/host-adapter/verdict-cookie.ts","../src/host-adapter/content-negotiation.ts","../src/host-adapter/decision-mapping.ts","../src/host-adapter/fetcher-envelope.ts","../src/host-adapter/challenge-wire.ts","../src/host-adapter/challenge-context.ts"],"sourcesContent":["/**\n * Utilities for converting between DetectionClass discriminated union and database enum\n */\n\nimport type { DetectionClass } from '../core/detection';\n\n// Database enum values (post-migration 0029)\n// Legacy values ('automation', 'unknown') are handled in conversion functions for backwards compatibility\nexport type DetectionClassEnum = 'human' | 'ai_agent' | 'bot' | 'incomplete_data';\n\n/**\n * Convert DetectionClass discriminated union to database enum string\n * Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively\n */\nexport function detectionClassToEnum(detectionClass: DetectionClass): DetectionClassEnum {\n switch (detectionClass.type) {\n case 'Human':\n return 'human';\n case 'AiAgent':\n return 'ai_agent';\n case 'Automation':\n // Legacy: Automation → Bot (migration 0029)\n return 'bot';\n case 'Bot':\n return 'bot';\n case 'IncompleteData':\n return 'incomplete_data';\n case 'Unknown':\n default:\n // Legacy: Unknown → IncompleteData (migration 0029)\n return 'incomplete_data';\n }\n}\n\n/**\n * Convert database enum string to DetectionClass discriminated union\n * Handles both current and legacy enum values for backwards compatibility\n */\nexport function enumToDetectionClass(enumValue: DetectionClassEnum | string): DetectionClass {\n switch (enumValue) {\n case 'human':\n return { type: 'Human' };\n case 'ai_agent':\n return { type: 'AiAgent' };\n case 'automation':\n // Legacy value: convert to Bot for consistency\n return { type: 'Bot' };\n case 'bot':\n return { type: 'Bot' };\n case 'incomplete_data':\n return { type: 'IncompleteData' };\n case 'unknown':\n // Legacy value: convert to IncompleteData for consistency\n return { type: 'IncompleteData' };\n default:\n return { type: 'IncompleteData' };\n }\n}\n\n/**\n * Check if a value is a valid string-based detection class (current or legacy)\n */\nexport function isLegacyDetectionClass(value: unknown): value is DetectionClassEnum {\n return (\n typeof value === 'string' &&\n // Current values + legacy values for backwards compatibility\n ['human', 'ai_agent', 'bot', 'incomplete_data', 'automation', 'unknown'].includes(value)\n );\n}\n\n/**\n * Migrate legacy string detection class to new discriminated union\n * @deprecated Use enumToDetectionClass instead\n */\nexport function migrateLegacyDetectionClass(value: string): DetectionClass {\n return enumToDetectionClass(value);\n}\n\n/**\n * Safely convert any detection class value to the discriminated union format\n */\nexport function normalizeDetectionClass(value: unknown): DetectionClass {\n // If it's already a discriminated union, return as-is\n if (value && typeof value === 'object' && 'type' in value) {\n return value as DetectionClass;\n }\n\n // If it's a valid string enum (current or legacy), convert it\n if (isLegacyDetectionClass(value)) {\n return enumToDetectionClass(value);\n }\n\n // Default fallback (migration 0029)\n return { type: 'IncompleteData' };\n}\n\n/**\n * Safely convert any detection class value to database enum format\n */\nexport function normalizeDetectionClassEnum(value: unknown): DetectionClassEnum {\n // If it's a discriminated union, convert to enum\n if (value && typeof value === 'object' && 'type' in value) {\n return detectionClassToEnum(value as DetectionClass);\n }\n\n // If it's a valid string enum (current or legacy), convert to current enum\n if (isLegacyDetectionClass(value)) {\n // Convert through discriminated union to handle legacy values properly\n return detectionClassToEnum(enumToDetectionClass(value));\n }\n\n // Default fallback (migration 0029)\n return 'incomplete_data';\n}\n","/**\n * Runtime-agnostic Cloudflare bot-management signal resolution.\n *\n * Ports the client-ip.ts trust-policy pattern (#4814) to bot signals, for\n * the class of bug PR #4269 shipped and #4282 reverted same-day: #4269 set\n * `KYA-CF-Bot-Score`/`KYA-CF-Verified-Bot` headers on the gateway's\n * origin-bound proxy request, then read them back from a completely\n * different request object (the ingest API call) — a header handoff across\n * a trust boundary. It also treated Cloudflare's bot score `0` as the\n * strongest possible bot signal, when Cloudflare defines `0` as \"Bot\n * Management did not run for this request,\" not \"confirmed bot.\"\n *\n * Same-request-object rule: this resolver only ever consumes the candidate\n * object the trusted runtime handed the CALLER directly (`request.cf` on a\n * Cloudflare Worker) — never a value forwarded via a header on a different\n * request object. Callers must pass their own `request.cf` straight through,\n * not something re-derived from headers.\n */\n\nexport type BotSignalsSource = 'cloudflare-bot-management' | 'explicit' | 'none';\n\nexport interface BotSignalsResolution {\n /**\n * 1-99 only. Cloudflare defines `0` as \"not computed\" (Bot Management\n * didn't run), not \"confirmed bot\" — `0` and any out-of-range value\n * normalize to `undefined` here, never surfaced as a real score.\n */\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n asn?: number;\n asOrganization?: string;\n source: BotSignalsSource;\n}\n\nexport type BotSignalsTrustPolicy =\n | { platform: 'cloudflare' }\n | { platform: 'vercel' }\n | { platform: 'trusted-proxy' }\n | { platform: 'direct' };\n\n/**\n * The subset of Cloudflare's `request.cf` this resolver reads. Pass\n * `request.cf` (or an equivalent test double) directly — `botManagement`\n * only populates when Bot Management is enabled on the zone; `asn`/\n * `asOrganization` are separate top-level `request.cf` fields, not nested\n * inside `botManagement`.\n */\nexport interface CloudflareRequestCf {\n botManagement?: {\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n } | null;\n asn?: number | null;\n asOrganization?: string | null;\n}\n\nexport interface ResolveBotSignalsInput {\n /**\n * `request.cf` from the SAME request object being classified. Cloudflare\n * is the only platform with a bot-management surface today — no\n * framework-provided equivalent exists yet on Vercel/Express/etc., so\n * this is the sole real candidate source; `policy` still selects per\n * runtime so a future platform's equivalent slots in without a redesign.\n */\n cloudflareRequestCf?: CloudflareRequestCf | null;\n /** Only honored when the caller has independently authenticated it (tests). */\n explicitBotSignals?: Omit<BotSignalsResolution, 'source'> | null;\n explicitBotSignalsTrusted?: boolean;\n policy: BotSignalsTrustPolicy;\n}\n\n/** Cloudflare bot score: only 1-99 are real values; 0 or out-of-range normalize to absent. */\nfunction normalizeBotScore(raw: number | null | undefined): number | undefined {\n if (typeof raw !== 'number' || !Number.isFinite(raw) || !Number.isInteger(raw)) return undefined;\n if (raw < 1 || raw > 99) return undefined;\n return raw;\n}\n\nfunction normalizeVerifiedBot(raw: boolean | null | undefined): boolean | undefined {\n return typeof raw === 'boolean' ? raw : undefined;\n}\n\nfunction normalizeString(raw: string | null | undefined): string | undefined {\n return raw && raw.length > 0 ? raw : undefined;\n}\n\nfunction normalizeAsn(raw: number | null | undefined): number | undefined {\n return typeof raw === 'number' && Number.isFinite(raw) && Number.isInteger(raw) && raw > 0\n ? raw\n : undefined;\n}\n\nfunction resolveExplicit(input: ResolveBotSignalsInput): BotSignalsResolution | null {\n if (input.explicitBotSignalsTrusted !== true || !input.explicitBotSignals) return null;\n const explicit = input.explicitBotSignals;\n return {\n score: normalizeBotScore(explicit.score),\n verifiedBot: normalizeVerifiedBot(explicit.verifiedBot),\n ja4: normalizeString(explicit.ja4),\n asn: normalizeAsn(explicit.asn),\n asOrganization: normalizeString(explicit.asOrganization),\n source: 'explicit',\n };\n}\n\nfunction resolveCloudflare(input: ResolveBotSignalsInput): BotSignalsResolution {\n const cf = input.cloudflareRequestCf;\n if (!cf) return { source: 'none' };\n\n return {\n score: normalizeBotScore(cf.botManagement?.score),\n verifiedBot: normalizeVerifiedBot(cf.botManagement?.verifiedBot),\n ja4: normalizeString(cf.botManagement?.ja4),\n asn: normalizeAsn(cf.asn),\n asOrganization: normalizeString(cf.asOrganization),\n source: 'cloudflare-bot-management',\n };\n}\n\n/** Resolve bot signals using an explicit deployment trust profile. */\nexport function resolveBotSignals(input: ResolveBotSignalsInput): BotSignalsResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'vercel':\n case 'trusted-proxy':\n case 'direct':\n // No bot-management (or equivalent) surface on these platforms today —\n // resolves cleanly absent rather than guessing at a shape that doesn't\n // exist yet. Add a resolve function here if/when one does.\n return { source: 'none' };\n }\n}\n","/**\n * Verdict cookie — byte-format contract shared across host runtimes.\n *\n * Sites-1's Sonner toast depends on `__checkpoint_verdict=%7B%22verdict%22\n * %3A%22<v>%22...%7D` (single URL-encoded JSON). If this format drifts,\n * the toast renders incorrectly or not at all.\n *\n * Phase E (#TBD) extracted these helpers from `checkpoint-nextjs/src/\n * adapt.ts` so the Express host (and any future host) can reproduce the\n * exact same cookie shape. The runtime-specific cookie-write call (e.g.\n * `NextResponse.cookies.set()` vs `express.Response.cookie()`) stays in\n * each host's `adapt.ts`; only the encoding logic is shared.\n *\n * **Return raw JSON, not URL-encoded.** Both Next.js's cookies API and\n * Express's `res.cookie()` URL-encode the value when serializing to the\n * Set-Cookie header (per RFC 6265 + each framework's cookie library).\n * Pre-encoding here would double-encode (`%7B` → `%257B`) and break\n * Sonner.\n */\n\n/**\n * Structural view of the orchestrator's `RenderedResponse` — just the\n * fields these helpers need. Defined locally to avoid a circular\n * dependency between `checkpoint-shared` and `checkpoint-wasm-runtime`\n * (the canonical owner of the full type). The actual type from\n * `@kya-os/checkpoint-wasm-runtime/orchestrator` is structurally\n * assignable to this.\n */\nexport interface RenderedResponseLike {\n /** HTTP status — `null` means pass-through (Permit / Observe). */\n status: number | null;\n /** Engine-emitted response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Canonical cookie name. Sites-1's `/blocked` page reads from this\n * exact key; do not rename without updating the dashboard route.\n */\nexport const VERDICT_COOKIE_NAME = '__checkpoint_verdict';\n\n/**\n * The three-state verdict surfaced to client-side UI. Maps from the\n * `RenderedResponse.status` field (which itself maps from the engine's\n * `Decision` variant).\n *\n * - `'allowed'` — Permit, or Observe-mode (any verdict, status null)\n * - `'redirected'` — Decision::Redirect → status 302\n * - `'denied'` — Decision::Block / Challenge / Instruct (4xx)\n */\nexport type Verdict = 'allowed' | 'denied' | 'redirected';\n\n/**\n * Compute the verdict label from a `RenderedResponse`.\n */\nexport function deriveVerdict(rendered: RenderedResponseLike): Verdict {\n if (rendered.status === null) return 'allowed';\n if (rendered.status === 302) return 'redirected';\n return 'denied';\n}\n\n/**\n * Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast\n * reads. Byte-format pinned by tests in both `checkpoint-nextjs` and\n * `checkpoint-express`:\n *\n * - allowed: `{\"verdict\":\"allowed\"}`\n * - denied: `{\"verdict\":\"denied\",\"reason\":\"<r>\"}`\n * - redirected: `{\"verdict\":\"redirected\"}`\n *\n * Returns raw JSON; the host's cookie-write call URL-encodes.\n */\nexport function encodeVerdictCookie(rendered: RenderedResponseLike): string {\n const verdict = deriveVerdict(rendered);\n const reason = rendered.headers['X-Checkpoint-Reason'];\n const value = reason ? { verdict, reason } : { verdict };\n return JSON.stringify(value);\n}\n","/**\n * Content negotiation — framework-agnostic Accept-header parsing for\n * host adapters.\n *\n * The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching\n * decisions; the host wrapper does that based on what the client\n * accepts. Both Next.js (NextRequest) and Express (Request) carry the\n * Accept header in different shapes — `req.headers.get('accept')` vs\n * `req.get('Accept')` vs `req.headers.accept` — so we accept any\n * Headers-like input and do the parsing here.\n */\n\n/**\n * `true` when the client signaled it accepts HTML or XHTML. Used by\n * host adapters to choose between an HTML `/blocked` rewrite (browsers)\n * and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).\n *\n * Loose match — q-values, parameters, and additional MIME types are\n * allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't\n * matter here; we only care whether HTML is present at all.\n *\n * Accepts:\n * - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)\n * - a plain `Record<string, string>` (Express, Connect, Fastify)\n * - a single string (caller already extracted the Accept value)\n * - `undefined` (treated as no-HTML)\n */\nexport function acceptsHtml(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): boolean {\n const accept = extractAccept(input);\n if (!accept) return false;\n return accept.includes('text/html') || accept.includes('application/xhtml+xml');\n}\n\nfunction extractAccept(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): string | undefined {\n if (!input) return undefined;\n if (typeof input === 'string') return input;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get('accept') ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 § 5.1);\n // try both common casings. Express lowercases by default; Next.js\n // header objects also lowercase.\n const rec = input as Record<string, string | string[] | undefined>;\n const value = rec.accept ?? rec.Accept;\n if (Array.isArray(value)) return value.join(',');\n return value;\n}\n","/**\n * Decision mapping — framework-agnostic classification of\n * `RenderedResponse` shapes that drive host-adapter branching.\n *\n * Phase D's `checkpoint-nextjs/src/adapt.ts` open-coded these four\n * branches (pass-through / redirect / HTML-block / JSON-block). Phase E\n * extracted them so the Express adapter — and any future host — can\n * share the classifier. The actual response construction stays\n * framework-specific (NextResponse.next() vs Express res.status().json()).\n */\n\nimport type { RenderedResponseLike } from './verdict-cookie';\n\n/**\n * Path the `/blocked` dashboard route lives at. HTML clients that hit\n * a 4xx verdict get rewritten here at status 200 so the page renders\n * with the verdict cookie set and Sonner can pick up the toast.\n *\n * Hard-coded by convention; if a customer ever needs a custom path,\n * pass it through `CheckpointConfig.blockedPath` and override in the\n * host adapter (not in this lookup).\n */\nexport const BLOCKED_PATH = '/blocked';\n\n/**\n * The four mutually-exclusive shapes a `RenderedResponse` can take,\n * driving the host adapter's branching. The host renders each shape\n * with its framework-native primitives.\n */\nexport type ResponseShape =\n /** Permit (status null) OR Observe-mode any-verdict — pass through with cookie + headers. */\n | 'pass-through'\n /** Decision::Redirect → 302 + Location header. */\n | 'redirect'\n /** 4xx + HTML-accepting client → rewrite to `/blocked` at status 200 for Sonner. */\n | 'html-block'\n /** 4xx + non-HTML client (or 5xx) → JSON body at the orchestrator's status. */\n | 'json-block';\n\n/**\n * Classify a `RenderedResponse` into one of the four host-adapter\n * branches. `clientAcceptsHtml` comes from `acceptsHtml()` in\n * `content-negotiation.ts`.\n */\nexport function classifyResponseShape(\n rendered: RenderedResponseLike,\n clientAcceptsHtml: boolean\n): ResponseShape {\n if (rendered.status === null) return 'pass-through';\n if (rendered.status === 302 && rendered.headers.Location) return 'redirect';\n if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return 'html-block';\n return 'json-block';\n}\n","/**\n * Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).\n *\n * AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx\n * responses and never surface the body to the LLM, so the §8.1 step-up\n * challenge served at 401 is invisible. The fix is a dual envelope: keep\n * the spec 401 for capable/discovery clients, and serve a body-readable\n * HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying\n * agents so they can read the body + relay the consent link.\n *\n * `serveBodyReadable200` is the shared selection predicate every TS PEP\n * (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its\n * challenge-emission mode is `negotiated`. Centralising it here — rather\n * than re-implementing per PEP — makes drift structurally impossible; the\n * fetcher-200 fixture freezes envelope BYTES, this function freezes the\n * SELECTION.\n *\n * **This is a cooperative-UX bridge, NOT an access control.** A spoofer\n * that hides its identity and does not opt in simply receives the spec\n * 401 (and the original body-drop). Access is still gated entirely by the\n * unchanged detection + delegation verification — never by which envelope\n * is selected.\n */\n\nimport { normalizeDetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Header inputs the predicate accepts — a WHATWG `Headers`, a plain\n * header record (Express/Next.js style), or absent. Mirrors the input\n * union `acceptsHtml` accepts so callers pass their native headers\n * unchanged.\n */\nexport type FetcherHeaderInput =\n | Headers\n | Record<string, string | string[] | undefined>\n | undefined;\n\n/**\n * Durable opt-in header — the primary, framework-agnostic signal that a\n * caller is a cooperative agent able to handle the 200 fetcher envelope.\n * Any non-empty value counts as opt-in (value semantics are reconciled\n * with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).\n */\nexport const ACCEPT_CHALLENGE_HEADER = 'kya-accept-challenge';\n\nfunction readHeader(input: FetcherHeaderInput, name: string): string | undefined {\n if (!input) return undefined;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get(name) ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 §5.1).\n const rec = input as Record<string, string | string[] | undefined>;\n const lower = name.toLowerCase();\n for (const key of Object.keys(rec)) {\n if (key.toLowerCase() === lower) {\n const v = rec[key];\n return Array.isArray(v) ? v[0] : (v ?? undefined);\n }\n }\n return undefined;\n}\n\n/**\n * Decide whether a `negotiated`-mode PEP should serve the body-readable\n * HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).\n *\n * Serve 200 when EITHER:\n * 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header\n * (the durable, primary signal), OR\n * 2. detection classifies the caller as an AI agent — BOTH `isAgent` and\n * `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,\n * retired as frameworks adopt the header).\n *\n * Otherwise serve the 401 — spoofers, silent, discovery, and OAuth\n * clients all land here, which is acceptable because this is UX, not a\n * security boundary.\n *\n * Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic\n * mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==\n * AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on\n * the pathological case where the two signals disagree (class says agent,\n * `isAgent` says no): that caller is treated as non-cooperative (spec 401),\n * never demoted past it. In normal engine output the two signals agree, so\n * who-gets-200 is unchanged for real traffic.\n *\n * @param headers request headers (for the opt-in signal)\n * @param detectionClass the caller's detection class in any representation\n * the engine produces (a `DetectionClass` object, the\n * `ai_agent` wire string, or absent)\n * @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`\n * heuristic so a class/`isAgent` disagreement gets the 401\n */\nexport function serveBodyReadable200(\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n // 1. Durable, primary signal: explicit opt-in header (independent of isAgent).\n const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);\n if (optIn && optIn.trim().length > 0) return true;\n\n // 2. Transitional UA heuristic: a detected AI agent — both signals must agree.\n if (isAgent && detectionClass !== undefined && detectionClass !== null) {\n if (normalizeDetectionClassEnum(detectionClass) === 'ai_agent') return true;\n }\n\n // 3. Spec 401 path (non-cooperative / silent / discovery / signals-disagree).\n return false;\n}\n\n/**\n * Per-PEP challenge-emission mode (mirrors mcp-i-cloudflare's `mode` and\n * the .NET `DelegationChallengeMode`). The TS engine PEPs (express / nextjs)\n * default to `negotiated`; the gateway worker reads its default from\n * `KYA_HTTP_CHALLENGE_MODE` (negotiated in dev, unset → spec-401 until the\n * prod flip, #3321).\n *\n * - `spec-401` — always the spec 401.\n * - `negotiated` — 200 for cooperative agents (per `serveBodyReadable200`),\n * 401 otherwise.\n * - `always-200` — 200 for everyone (fetcher-first hosts / escape hatch).\n */\nexport type ChallengeEnvelopeMode = 'spec-401' | 'negotiated' | 'always-200';\n\n/**\n * Resolve the challenge-emission mode + request signals into the single\n * boolean each PEP needs: serve the body-readable 200 (`true`) or the spec\n * 401 (`false`). Centralising the mode gate here — not just the predicate —\n * keeps the rollout switch identical across every TS PEP.\n */\nexport function selectBodyReadable200(\n mode: ChallengeEnvelopeMode,\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n if (mode === 'always-200') return true;\n if (mode === 'negotiated') return serveBodyReadable200(headers, detectionClass, isAgent);\n return false;\n}\n","/**\n * Canonical fixture-pinned KYA HTTP challenge-wire builder.\n *\n * The builder is transport-neutral and Edge-safe. Hosts must register the\n * challenge and resolve every URI before calling it; this module validates and\n * serializes those trusted values without network, database, or request access.\n */\n\nimport { KYA_HTTP_ERROR } from '../mcpi/kya-http-error-codes';\nimport type { AssuranceTier } from '../policy/schemas';\n\nconst PROTECTED_RESOURCE_METADATA_PATH = '/.well-known/oauth-protected-resource';\nconst DEFAULT_POLL_INTERVAL_S = 3;\n// eslint-disable-next-line no-control-regex -- deliberate: reject RFC 9110 quoted-string-unsafe control characters, not a stray literal.\nconst INVALID_QUOTED_VALUE = /[\\u0000-\\u001f\\u007f\"\\\\]/;\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\nconst SID = /^kya-[0-9a-f]{16,}$/;\nconst ASSURANCE_TIERS = new Set<string>([\n 'anonymous',\n 'attested-bearer',\n 'key-bound',\n 'registered',\n 'delegated',\n]);\n\n/** Ordered HTTP header pair. Names may repeat. */\nexport type HeaderEntry = readonly [name: string, value: string];\n\nexport type ChallengeWireKind = 'delegation' | 'approval_quorum';\n\ninterface ChallengeWireInputBase {\n /** Protected-resource host, optionally including a port. */\n realm: string;\n /** Registered challenge/session identifier. */\n sid: string;\n /** Authorization-Host consent URL returned by registration. */\n consentUri: string;\n /** Authorization-Host pickup URL returned or resolved by registration. */\n pickupUri: string;\n /** Scopes demanded by policy. Empty means omit the optional scope parameter. */\n requiredScopes?: readonly string[];\n /** Optional poll cadence; omission retains the server default without an auth-param. */\n pollIntervalS?: number;\n /** Registered, signed proof. Opaque to the renderer. */\n challengeProof: unknown;\n /** Optional assurance floor demanded by policy. */\n minAssurance?: AssuranceTier;\n}\n\n/** Complete registered context for an OAuth-compatible delegation step-up. */\nexport interface DelegationChallengeWireInput extends ChallengeWireInputBase {\n kind?: 'delegation';\n /** Exact RFC 9728 discovery URI configured for the protected resource. */\n resourceMetadataUri: string;\n}\n\n/** Complete registered context for an N-of-M approval step-up. */\nexport interface ApprovalQuorumChallengeWireInput extends ChallengeWireInputBase {\n kind: 'approval_quorum';\n quorum: number;\n actionNonce: string;\n}\n\nexport type ChallengeWireInput = DelegationChallengeWireInput | ApprovalQuorumChallengeWireInput;\n\ninterface CommonChallengeKyaos {\n sid: string;\n consent_uri: string;\n pickup_uri: string;\n required_scopes?: string[];\n min_assurance?: AssuranceTier;\n poll_interval_s: number;\n challenge_proof: unknown;\n}\n\ninterface DelegationChallengeKyaos extends CommonChallengeKyaos {\n action: {\n type: 'delegation';\n consent_uri: string;\n pickup_uri: string;\n poll_interval_s: number;\n pin: { header: 'X-KYA-Pickup-Token' };\n retry: { header: 'Authorization'; scheme: 'Bearer'; value_from: 'delegation' };\n };\n}\n\ninterface ApprovalQuorumChallengeKyaos extends CommonChallengeKyaos {\n kind: 'approval_quorum';\n quorum: number;\n action_nonce: string;\n}\n\n/** Canonical body shared by the 401 and body-readable 200 envelopes. */\nexport interface DelegationChallengeBody {\n error: typeof KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED;\n kyaos: DelegationChallengeKyaos | ApprovalQuorumChallengeKyaos;\n instructions: string;\n}\n\nexport interface DelegationChallengeEnvelope {\n status: 401 | 200;\n headers: HeaderEntry[];\n body: DelegationChallengeBody;\n}\n\nexport type DelegationChallengeEnvelopeMode = 'spec-401' | 'fetcher-200';\n\nexport type ChallengeWireErrorCode =\n | 'invalid-realm'\n | 'invalid-sid'\n | 'invalid-uri'\n | 'invalid-scope'\n | 'invalid-assurance'\n | 'invalid-interval'\n | 'invalid-proof'\n | 'invalid-kind'\n | 'invalid-quorum'\n | 'invalid-action-nonce'\n | 'unsupported-envelope';\n\n/** Typed validation failure raised before any response is materialized. */\nexport class ChallengeWireError extends TypeError {\n readonly code: ChallengeWireErrorCode;\n\n constructor(code: ChallengeWireErrorCode, message: string) {\n super(message);\n this.name = 'ChallengeWireError';\n this.code = code;\n }\n}\n\n/** Generate a 128-bit, lower-case hexadecimal challenge id. */\nexport function generateDelegationSid(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return `kya-${hex}`;\n}\n\n/** Derive pickup from the registered consent origin, never request Host. */\nexport function deriveDelegationPickupUri(consentUri: string, sid: string): string {\n const consent = parseHttpsUrl('consentUri', consentUri);\n assertQuotedValue('sid', sid, 'invalid-sid');\n return `${consent.origin}/api/delegation/pickup/${sid}`;\n}\n\n/** Build the byte-pinned Delegation authentication field value. */\nexport function buildDelegationChallengeHeader(input: ChallengeWireInput): string {\n const normalized = validateInput(input);\n const params: Array<readonly [string, string]> = [\n ['realm', normalized.realm],\n ['sid', normalized.sid],\n ['consent_uri', normalized.consentUri],\n ['pickup_uri', normalized.pickupUri],\n ];\n if (normalized.requiredScopes.length > 0) {\n params.push(['scope', normalized.requiredScopes.join(' ')]);\n }\n if (normalized.minAssurance) {\n params.push(['min_assurance', normalized.minAssurance]);\n }\n if (input.pollIntervalS !== undefined) {\n params.push(['interval', String(normalized.pollIntervalS)]);\n }\n params.push(['kind', normalized.kind]);\n\n return `Delegation ${params.map(([name, value]) => `${name}=\"${value}\"`).join(', ')}`;\n}\n\n/** Build RFC 9728 Bearer discovery for a protected-resource realm. */\nexport function buildDelegationBearerHeader(realm: string): string {\n assertRealm(realm);\n return `Bearer resource_metadata=\"https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}\"`;\n}\n\n/** Build the four required machine-followable delegation instruction elements. */\nexport function buildDelegationInstructions(\n consentUri: string,\n pickupUri: string,\n pollIntervalS: number\n): string {\n return (\n `This action requires human authorization. First establish your pickup binding at ${pickupUri}. ` +\n `If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token encoded as unpadded base64url and send it as X-KYA-Pickup-Token on EVERY poll. ` +\n `After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. ` +\n `Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. ` +\n `When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`\n );\n}\n\n/** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */\nexport function buildDelegationChallengeBody(input: ChallengeWireInput): DelegationChallengeBody {\n const normalized = validateInput(input);\n const common: CommonChallengeKyaos = {\n sid: normalized.sid,\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n ...(normalized.requiredScopes.length > 0\n ? { required_scopes: [...normalized.requiredScopes] }\n : {}),\n ...(normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {}),\n poll_interval_s: normalized.pollIntervalS,\n challenge_proof: input.challengeProof,\n };\n\n if (normalized.kind === 'approval_quorum') {\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n sid: common.sid,\n kind: 'approval_quorum',\n quorum: normalized.quorum!,\n action_nonce: normalized.actionNonce!,\n consent_uri: common.consent_uri,\n pickup_uri: common.pickup_uri,\n ...(common.required_scopes ? { required_scopes: common.required_scopes } : {}),\n ...(common.min_assurance ? { min_assurance: common.min_assurance } : {}),\n poll_interval_s: common.poll_interval_s,\n challenge_proof: common.challenge_proof,\n },\n instructions: buildApprovalQuorumInstructions(normalized),\n };\n }\n\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n ...common,\n action: {\n type: 'delegation',\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n poll_interval_s: normalized.pollIntervalS,\n pin: { header: 'X-KYA-Pickup-Token' },\n retry: { header: 'Authorization', scheme: 'Bearer', value_from: 'delegation' },\n },\n },\n instructions: buildDelegationInstructions(\n normalized.consentUri,\n normalized.pickupUri,\n normalized.pollIntervalS\n ),\n };\n}\n\n/** Build either the canonical 401 or its body-identical fetcher-200 envelope. */\nexport function buildDelegationChallengeEnvelope(\n input: ChallengeWireInput,\n mode: DelegationChallengeEnvelopeMode = 'spec-401'\n): DelegationChallengeEnvelope {\n const normalized = validateInput(input);\n if (normalized.kind === 'approval_quorum' && mode === 'fetcher-200') {\n throw new ChallengeWireError(\n 'unsupported-envelope',\n 'fetcher-200 is not fixture-defined for approval_quorum'\n );\n }\n\n const body = buildDelegationChallengeBody(input);\n if (normalized.kind === 'approval_quorum') {\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['Retry-After', String(normalized.pollIntervalS)],\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ],\n body,\n };\n }\n\n const hintHeaders: HeaderEntry[] = [\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ['KYA-Auth-Required', 'true'],\n ['KYA-Auth-Url', normalized.consentUri],\n ['Link', `<${normalized.consentUri}>; rel=\"kya-authorize\"`],\n ['KYA-Action', 'challenge'],\n ];\n if (mode === 'fetcher-200') {\n return { status: 200, headers: hintHeaders, body };\n }\n\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['WWW-Authenticate', `Bearer resource_metadata=\"${normalized.resourceMetadataUri}\"`],\n ['Retry-After', String(normalized.pollIntervalS)],\n ...hintHeaders,\n ],\n body,\n };\n}\n\n/** Preferred generic name; the legacy export remains for host compatibility. */\nexport const buildChallengeWire = buildDelegationChallengeEnvelope;\n\ninterface ValidatedInput {\n realm: string;\n sid: string;\n consentUri: string;\n pickupUri: string;\n resourceMetadataUri?: string;\n requiredScopes: readonly string[];\n pollIntervalS: number;\n minAssurance?: AssuranceTier;\n kind: ChallengeWireKind;\n quorum?: number;\n actionNonce?: string;\n}\n\nfunction validateInput(input: ChallengeWireInput): ValidatedInput {\n assertRealm(input.realm);\n assertQuotedValue('sid', input.sid, 'invalid-sid');\n if (!SID.test(input.sid)) {\n throw new ChallengeWireError(\n 'invalid-sid',\n 'sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy'\n );\n }\n\n const consent = parseHttpsUrl('consentUri', input.consentUri);\n const pickup = parseHttpsUrl('pickupUri', input.pickupUri);\n const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;\n if (pickup.href !== expectedPickup) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'pickupUri must use the registered consent origin and sid'\n );\n }\n\n const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;\n if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) {\n throw new ChallengeWireError(\n 'invalid-interval',\n 'pollIntervalS must be an integer from 1 through 999'\n );\n }\n if (input.challengeProof === undefined || input.challengeProof === null) {\n throw new ChallengeWireError('invalid-proof', 'challengeProof is required');\n }\n const requiredScopes = input.requiredScopes ?? [];\n for (const scope of requiredScopes) {\n if (!SCOPE_TOKEN.test(scope)) {\n throw new ChallengeWireError('invalid-scope', `invalid required scope: ${scope}`);\n }\n }\n if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) {\n throw new ChallengeWireError(\n 'invalid-assurance',\n `invalid minAssurance: ${input.minAssurance}`\n );\n }\n\n const kind = input.kind ?? 'delegation';\n if (kind !== 'delegation' && kind !== 'approval_quorum') {\n throw new ChallengeWireError('invalid-kind', `unsupported challenge kind: ${String(kind)}`);\n }\n\n let resourceMetadataUri: string | undefined;\n let quorum: number | undefined;\n let actionNonce: string | undefined;\n if (kind === 'delegation') {\n resourceMetadataUri = parseHttpsUrl(\n 'resourceMetadataUri',\n (input as DelegationChallengeWireInput).resourceMetadataUri\n ).href;\n const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;\n if (resourceMetadataUri !== expectedMetadata) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'resourceMetadataUri must be the protected resource RFC 9728 metadata URL'\n );\n }\n } else {\n const approval = input as ApprovalQuorumChallengeWireInput;\n quorum = approval.quorum;\n actionNonce = approval.actionNonce;\n if (!Number.isInteger(quorum) || quorum < 1) {\n throw new ChallengeWireError('invalid-quorum', 'quorum must be a positive integer');\n }\n assertQuotedValue('actionNonce', actionNonce, 'invalid-action-nonce');\n }\n\n return {\n realm: input.realm,\n sid: input.sid,\n consentUri: consent.href,\n pickupUri: pickup.href,\n resourceMetadataUri,\n requiredScopes,\n pollIntervalS,\n minAssurance: input.minAssurance,\n kind,\n quorum,\n actionNonce,\n };\n}\n\nfunction buildApprovalQuorumInstructions(input: ValidatedInput): string {\n return (\n `This action requires approval from ${input.quorum} human approvers. ` +\n `Show your user this link to begin the approval process: ${input.consentUri}. ` +\n `Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). ` +\n `When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`\n );\n}\n\nfunction assertRealm(realm: string): void {\n assertQuotedValue('realm', realm, 'invalid-realm');\n if (realm.includes('/') || realm.includes('@') || realm.includes('?') || realm.includes('#')) {\n throw new ChallengeWireError('invalid-realm', 'realm must be a host with an optional port');\n }\n try {\n const parsed = new URL(`https://${realm}`);\n if (parsed.host !== realm) throw new Error('invalid authority');\n } catch {\n throw new ChallengeWireError(\n 'invalid-realm',\n 'realm must be a valid host with an optional port'\n );\n }\n}\n\nfunction assertQuotedValue(name: string, value: string, code: ChallengeWireErrorCode): void {\n if (typeof value !== 'string' || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) {\n throw new ChallengeWireError(\n code,\n `${name} contains characters unsafe for an HTTP quoted-string`\n );\n }\n}\n\nfunction parseHttpsUrl(name: string, value: string): URL {\n assertQuotedValue(name, value, 'invalid-uri');\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new ChallengeWireError('invalid-uri', `${name} must be an absolute HTTPS URL`);\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {\n throw new ChallengeWireError(\n 'invalid-uri',\n `${name} must be an absolute HTTPS URL without credentials`\n );\n }\n return parsed;\n}\n","import { buildChallengeWire, type ChallengeWireInput } from './challenge-wire';\n\nexport const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3000;\n\nexport type ChallengeContextFailure = 'timeout' | 'resolver-error' | 'invalid-context';\n\nexport interface ChallengeContextFailureEvent {\n reason: ChallengeContextFailure;\n message: string;\n}\n\nexport interface ResolveChallengeContextOptions {\n timeoutMs?: number;\n onFailure?: (event: ChallengeContextFailureEvent) => void;\n}\n\n/**\n * Resolve and validate registered challenge context at the async host boundary.\n * Resolver failures become an absent context so the renderer can emit the\n * canonical retryable status-pending response; secrets and proof values are\n * never included in failure events.\n */\nexport async function resolveChallengeContext<TContext>(\n resolver:\n | ((\n context: TContext\n ) => ChallengeWireInput | undefined | Promise<ChallengeWireInput | undefined>)\n | undefined,\n context: TContext,\n options: ResolveChallengeContextOptions = {}\n): Promise<ChallengeWireInput | undefined> {\n if (!resolver) return undefined;\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;\n if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {\n throw new TypeError('challenge context timeout must be a positive integer');\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const value = await Promise.race([\n Promise.resolve(resolver(context)),\n new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(\n () => reject(new ChallengeContextTimeoutError(timeoutMs)),\n timeoutMs\n );\n }),\n ]);\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n if (!value) return undefined;\n\n try {\n buildChallengeWire(value, 'spec-401');\n return value;\n } catch (error) {\n options.onFailure?.({\n reason: 'invalid-context',\n message: (error as Error).message,\n });\n return undefined;\n }\n } catch (error) {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n options.onFailure?.({\n reason: error instanceof ChallengeContextTimeoutError ? 'timeout' : 'resolver-error',\n message:\n error instanceof ChallengeContextTimeoutError\n ? error.message\n : 'challenge context resolver failed',\n });\n return undefined;\n }\n}\n\nclass ChallengeContextTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`challenge context resolution exceeded ${timeoutMs}ms`);\n this.name = 'ChallengeContextTimeoutError';\n }\n}\n"],"mappings":";;;;;;;AAcA,SAAgB,qBAAqB,gBAAoD;CACvF,QAAQ,eAAe,MAAvB;EACE,KAAK,SACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,cAEH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,kBACH,OAAO;EAET,SAEE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,qBAAqB,WAAwD;CAC3F,QAAQ,WAAR;EACE,KAAK,SACH,OAAO,EAAE,MAAM,QAAQ;EACzB,KAAK,YACH,OAAO,EAAE,MAAM,UAAU;EA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O,UAC5D,MAAM,IAAI,mBACR,eACA,GAAG,KAAK,mDACV;CAEF,OAAO;AACT;;;;ACjcA,MAAa,uCAAuC;;;;;;;AAoBpD,eAAsB,wBACpB,UAKA,SACA,UAA0C,CAAC,GACF;CACzC,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,YAAY,QAAQ;CAC1B,IAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,GAC9C,MAAM,IAAI,UAAU,sDAAsD;CAG5E,IAAI;CACJ,IAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,KAAK,CAC/B,QAAQ,QAAQ,SAAS,OAAO,CAAC,GACjC,IAAI,SAAgB,UAAU,WAAW;GACvC,YAAY,iBACJ,OAAO,IAAI,6BAA6B,SAAS,CAAC,GACxD,SACF;EACF,CAAC,CACH,CAAC;EACD,IAAI,cAAc,QAAW,aAAa,SAAS;EACnD,IAAI,CAAC,OAAO,OAAO;EAEnB,IAAI;GACF,mBAAmB,OAAO,UAAU;GACpC,OAAO;EACT,SAAS,OAAO;GACd,QAAQ,YAAY;IAClB,QAAQ;IACR,SAAU,MAAgB;GAC5B,CAAC;GACD;EACF;CACF,SAAS,OAAO;EACd,IAAI,cAAc,QAAW,aAAa,SAAS;EACnD,QAAQ,YAAY;GAClB,QAAQ,iBAAiB,+BAA+B,YAAY;GACpE,SACE,iBAAiB,+BACb,MAAM,UACN;EACR,CAAC;EACD;CACF;AACF;AAEA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,YAAY,WAAmB;EAC7B,MAAM,yCAAyC,UAAU,GAAG;EAC5D,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-
|
|
2
|
-
import { r as AssuranceTier } from "./schemas-
|
|
1
|
+
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-C14E4gi3.js";
|
|
2
|
+
import { r as AssuranceTier } from "./schemas-CGKHzcMV.js";
|
|
3
3
|
//#region src/host-adapter/verdict-cookie.d.ts
|
|
4
4
|
interface RenderedResponseLike {
|
|
5
5
|
status: number | null;
|
|
@@ -153,4 +153,4 @@ interface ResolveBotSignalsInput {
|
|
|
153
153
|
declare function resolveBotSignals(input: ResolveBotSignalsInput): BotSignalsResolution;
|
|
154
154
|
//#endregion
|
|
155
155
|
export { ACCEPT_CHALLENGE_HEADER as A, VERDICT_COOKIE_NAME as B, buildDelegationBearerHeader as C, buildDelegationInstructions as D, buildDelegationChallengeHeader as E, BLOCKED_PATH as F, deriveVerdict as H, ResponseShape as I, classifyResponseShape as L, FetcherHeaderInput as M, selectBodyReadable200 as N, deriveDelegationPickupUri as O, serveBodyReadable200 as P, acceptsHtml as R, buildChallengeWire as S, buildDelegationChallengeEnvelope as T, encodeVerdictCookie as U, Verdict as V, DelegationChallengeBody as _, ResolveBotSignalsInput as a, DelegationChallengeWireInput as b, ChallengeContextFailureEvent as c, resolveChallengeContext as d, ApprovalQuorumChallengeWireInput as f, ChallengeWireKind as g, ChallengeWireInput as h, CloudflareRequestCf as i, ChallengeEnvelopeMode as j, generateDelegationSid as k, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS as l, ChallengeWireErrorCode as m, BotSignalsSource as n, resolveBotSignals as o, ChallengeWireError as p, BotSignalsTrustPolicy as r, ChallengeContextFailure as s, BotSignalsResolution as t, ResolveChallengeContextOptions as u, DelegationChallengeEnvelope as v, buildDelegationChallengeBody as w, HeaderEntry as x, DelegationChallengeEnvelopeMode as y, RenderedResponseLike as z };
|
|
156
|
-
//# sourceMappingURL=index-
|
|
156
|
+
//# sourceMappingURL=index-DnFsmr_o.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-DnFsmr_o.d.ts","names":[],"sources":["../src/host-adapter/verdict-cookie.ts","../src/host-adapter/content-negotiation.ts","../src/host-adapter/decision-mapping.ts","../src/host-adapter/fetcher-envelope.ts","../src/host-adapter/challenge-wire.ts","../src/host-adapter/challenge-context.ts","../src/utils/bot-signals.ts"],"mappings":";;;UA4BiB;EAEf;EAEA,SAAS;;cAOE;KAWD;iBAKI,cAAc,UAAU,uBAAuB;iBAiB/C,oBAAoB,UAAU;;;iBC7C9B,YACd,OAAO,UAAU;;;cCNN;KAOD;iBAeI,sBACd,UAAU,sBACV,6BACC;;;KCfS,qBACR,UACA;cASS;iBAiDG,qBACd,SAAS,oBACT,yBACA;KA2BU;iBAQI,sBACd,MAAM,uBACN,SAAS,oBACT,yBACA;;;KC5GU,wBAAwB,cAAc;KAEtC;UAEF;EAER;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA,eAAe;;UAIA,qCAAqC;EACpD;EAEA;;UAIe,yCAAyC;EACxD;EACA;EACA;;KAGU,qBAAqB,+BAA+B;UAEtD;EACR;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;;UAGQ,iCAAiC;EACzC;IACE;IACA;IACA;IACA;IACA;MAAO;;IACP;MAAS;MAAyB;MAAkB;;;;UAI9C,qCAAqC;EAC7C;EACA;EACA;;UAIe;EACf,cAAc,eAAe;EAC7B,OAAO,2BAA2B;EAClC;;UAGe;EACf;EACA,SAAS;EACT,MAAM;;KAGI;KAEA;cAcC,2BAA2B;WAC7B,MAAM;EAEH,YAAA,MAAM,wBAAwB;;iBAQ5B;iBASA,0BAA0B,oBAAoB;iBAO9C,+BAA+B,OAAO;iBAuBtC,4BAA4B;iBAM5B,4BACd,oBACA,mBACA;iBAYc,6BAA6B,OAAO,qBAAqB;iBAuDzD,iCACd,OAAO,oBACP,OAAM,kCACL;cAgDU,2BAAkB;;;cCxSlB;KAED;UAEK;EACf,QAAQ;EACR;;UAGe;EACf;EACA,aAAa,OAAO;;iBASA,wBAAwB,UAC5C,YAEM,SAAS,aACN,iCAAiC,QAAQ,8CAElD,SAAS,UACT,UAAS,iCACR,QAAQ;;;KCXC;UAEK;EAMf;EACA;EACA;EACA;EACA;EACA,QAAQ;;KAGE;EACN;;EACA;;EACA;;EACA;;UASW;EACf;IACE;IACA;IACA;;EAEF;EACA;;UAGe;EAQf,sBAAsB;EAEtB,qBAAqB,KAAK;EAC1B;EACA,QAAQ;;iBAoDM,kBAAkB,OAAO,yBAAyB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-
|
|
2
|
-
import { r as AssuranceTier } from "./schemas-
|
|
1
|
+
import { t as KYA_HTTP_ERROR } from "./kya-http-error-codes-C14E4gi3.mjs";
|
|
2
|
+
import { r as AssuranceTier } from "./schemas-m-GqyfyO.mjs";
|
|
3
3
|
//#region src/host-adapter/verdict-cookie.d.ts
|
|
4
4
|
interface RenderedResponseLike {
|
|
5
5
|
status: number | null;
|
|
@@ -153,4 +153,4 @@ interface ResolveBotSignalsInput {
|
|
|
153
153
|
declare function resolveBotSignals(input: ResolveBotSignalsInput): BotSignalsResolution;
|
|
154
154
|
//#endregion
|
|
155
155
|
export { ACCEPT_CHALLENGE_HEADER as A, VERDICT_COOKIE_NAME as B, buildDelegationBearerHeader as C, buildDelegationInstructions as D, buildDelegationChallengeHeader as E, BLOCKED_PATH as F, deriveVerdict as H, ResponseShape as I, classifyResponseShape as L, FetcherHeaderInput as M, selectBodyReadable200 as N, deriveDelegationPickupUri as O, serveBodyReadable200 as P, acceptsHtml as R, buildChallengeWire as S, buildDelegationChallengeEnvelope as T, encodeVerdictCookie as U, Verdict as V, DelegationChallengeBody as _, ResolveBotSignalsInput as a, DelegationChallengeWireInput as b, ChallengeContextFailureEvent as c, resolveChallengeContext as d, ApprovalQuorumChallengeWireInput as f, ChallengeWireKind as g, ChallengeWireInput as h, CloudflareRequestCf as i, ChallengeEnvelopeMode as j, generateDelegationSid as k, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS as l, ChallengeWireErrorCode as m, BotSignalsSource as n, resolveBotSignals as o, ChallengeWireError as p, BotSignalsTrustPolicy as r, ChallengeContextFailure as s, BotSignalsResolution as t, ResolveChallengeContextOptions as u, DelegationChallengeEnvelope as v, buildDelegationChallengeBody as w, HeaderEntry as x, DelegationChallengeEnvelopeMode as y, RenderedResponseLike as z };
|
|
156
|
-
//# sourceMappingURL=index-
|
|
156
|
+
//# sourceMappingURL=index-rvw5Bz-r.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-rvw5Bz-r.d.mts","names":[],"sources":["../src/host-adapter/verdict-cookie.ts","../src/host-adapter/content-negotiation.ts","../src/host-adapter/decision-mapping.ts","../src/host-adapter/fetcher-envelope.ts","../src/host-adapter/challenge-wire.ts","../src/host-adapter/challenge-context.ts","../src/utils/bot-signals.ts"],"mappings":";;;UA4BiB;EAEf;EAEA,SAAS;;cAOE;KAWD;iBAKI,cAAc,UAAU,uBAAuB;iBAiB/C,oBAAoB,UAAU;;;iBC7C9B,YACd,OAAO,UAAU;;;cCNN;KAOD;iBAeI,sBACd,UAAU,sBACV,6BACC;;;KCfS,qBACR,UACA;cASS;iBAiDG,qBACd,SAAS,oBACT,yBACA;KA2BU;iBAQI,sBACd,MAAM,uBACN,SAAS,oBACT,yBACA;;;KC5GU,wBAAwB,cAAc;KAEtC;UAEF;EAER;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA,eAAe;;UAIA,qCAAqC;EACpD;EAEA;;UAIe,yCAAyC;EACxD;EACA;EACA;;KAGU,qBAAqB,+BAA+B;UAEtD;EACR;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;;UAGQ,iCAAiC;EACzC;IACE;IACA;IACA;IACA;IACA;MAAO;;IACP;MAAS;MAAyB;MAAkB;;;;UAI9C,qCAAqC;EAC7C;EACA;EACA;;UAIe;EACf,cAAc,eAAe;EAC7B,OAAO,2BAA2B;EAClC;;UAGe;EACf;EACA,SAAS;EACT,MAAM;;KAGI;KAEA;cAcC,2BAA2B;WAC7B,MAAM;EAEH,YAAA,MAAM,wBAAwB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