@kya-os/checkpoint-shared 1.5.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +98 -1
  2. package/dist/beacon-types/index.d.mts +12 -1
  3. package/dist/beacon-types/index.d.mts.map +1 -1
  4. package/dist/beacon-types/index.d.ts +12 -1
  5. package/dist/beacon-types/index.d.ts.map +1 -1
  6. package/dist/beacon-types/index.js +18 -1
  7. package/dist/beacon-types/index.mjs +18 -2
  8. package/dist/beacon-types/index.mjs.map +1 -1
  9. package/dist/{browser-posture-D4j2a5gi.d.ts → browser-posture-B8YiPa5c.d.ts} +6 -6
  10. package/dist/{browser-posture-D4j2a5gi.d.ts.map → browser-posture-B8YiPa5c.d.ts.map} +1 -1
  11. package/dist/{browser-posture-DVoHMHjY.d.mts → browser-posture-BLhw-MON.d.mts} +6 -6
  12. package/dist/{browser-posture-DVoHMHjY.d.mts.map → browser-posture-BLhw-MON.d.mts.map} +1 -1
  13. package/dist/browser-posture-cookie.js +1 -1
  14. package/dist/browser-posture-cookie.mjs +1 -1
  15. package/dist/browser-posture-cookie.mjs.map +1 -1
  16. package/dist/browser-posture-proof.d.mts +2 -2
  17. package/dist/browser-posture-proof.d.mts.map +1 -1
  18. package/dist/browser-posture-proof.d.ts +2 -2
  19. package/dist/browser-posture-proof.d.ts.map +1 -1
  20. package/dist/browser-posture-proof.js +43 -2
  21. package/dist/browser-posture-proof.mjs +43 -2
  22. package/dist/browser-posture-proof.mjs.map +1 -1
  23. package/dist/browser-posture.d.mts +1 -1
  24. package/dist/browser-posture.d.ts +1 -1
  25. package/dist/browser-posture.js +3 -3
  26. package/dist/browser-posture.mjs +3 -3
  27. package/dist/browser-posture.mjs.map +1 -1
  28. package/dist/canonical-signer/index.d.mts.map +1 -1
  29. package/dist/canonical-signer/index.d.ts.map +1 -1
  30. package/dist/canonical-signer/index.js +86 -51
  31. package/dist/canonical-signer/index.mjs +86 -51
  32. package/dist/canonical-signer/index.mjs.map +1 -1
  33. package/dist/clearance.d.mts +1 -1
  34. package/dist/clearance.d.ts +1 -1
  35. package/dist/clearance.js +2 -2
  36. package/dist/clearance.mjs +2 -2
  37. package/dist/client-ip-DFamiNoz.d.mts +34 -0
  38. package/dist/client-ip-DFamiNoz.d.mts.map +1 -0
  39. package/dist/client-ip-DFamiNoz.d.ts +34 -0
  40. package/dist/client-ip-DFamiNoz.d.ts.map +1 -0
  41. package/dist/client-ip.d.mts +2 -0
  42. package/dist/client-ip.d.ts +2 -0
  43. package/dist/client-ip.js +7 -0
  44. package/dist/client-ip.mjs +3 -0
  45. package/dist/errors/index.d.mts +17 -0
  46. package/dist/errors/index.d.mts.map +1 -1
  47. package/dist/errors/index.d.ts +17 -0
  48. package/dist/errors/index.d.ts.map +1 -1
  49. package/dist/errors/index.js +75 -3
  50. package/dist/errors/index.mjs +75 -3
  51. package/dist/errors/index.mjs.map +1 -1
  52. package/dist/{external-Ct8j_hto.d.ts → external-B7WI9FyQ.d.mts} +2 -2
  53. package/dist/{external-Ct8j_hto.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
  54. package/dist/{external-Ct8j_hto.d.mts → external-B7WI9FyQ.d.ts} +2 -2
  55. package/dist/{external-Ct8j_hto.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
  56. package/dist/gateway-client-ip.d.mts +1 -1
  57. package/dist/gateway-client-ip.d.ts +1 -1
  58. package/dist/gateway-client-ip.js +1 -1
  59. package/dist/gateway-client-ip.mjs +1 -1
  60. package/dist/host-adapter/index.d.mts +2 -0
  61. package/dist/host-adapter/index.d.ts +2 -0
  62. package/dist/host-adapter/index.js +23 -0
  63. package/dist/host-adapter/index.mjs +3 -0
  64. package/dist/host-adapter-C-4IxmqM.mjs +540 -0
  65. package/dist/host-adapter-C-4IxmqM.mjs.map +1 -0
  66. package/dist/host-adapter-CwW9YB0U.js +694 -0
  67. package/dist/index-B7rTovHa.d.mts +707 -0
  68. package/dist/index-B7rTovHa.d.mts.map +1 -0
  69. package/dist/index-HaqfPtaL.d.ts +707 -0
  70. package/dist/index-HaqfPtaL.d.ts.map +1 -0
  71. package/dist/index.d.mts +742 -937
  72. package/dist/index.d.mts.map +1 -1
  73. package/dist/index.d.ts +742 -937
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +758 -1193
  76. package/dist/index.mjs +659 -1148
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
  79. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
  80. package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
  81. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
  82. package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
  83. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
  84. package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
  85. package/dist/kya-http.d.mts +3 -0
  86. package/dist/kya-http.d.ts +3 -0
  87. package/dist/kya-http.js +11 -0
  88. package/dist/kya-http.mjs +4 -0
  89. package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
  90. package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
  91. package/dist/mcpi/approval-grant/index.js +10 -1
  92. package/dist/mcpi/approval-grant/index.mjs +10 -1
  93. package/dist/mcpi/approval-grant/index.mjs.map +1 -1
  94. package/dist/mcpi/dashboard-config/index.d.mts +3 -2
  95. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  96. package/dist/mcpi/dashboard-config/index.d.ts +3 -2
  97. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  98. package/dist/policy/enforcement.d.mts +2 -0
  99. package/dist/policy/enforcement.d.ts +2 -0
  100. package/dist/policy/enforcement.js +15 -0
  101. package/dist/policy/enforcement.mjs +3 -0
  102. package/dist/{posture-origins-Dl7i8j93.mjs → posture-origins-Ba83O0cD.mjs} +3 -3
  103. package/dist/posture-origins-Ba83O0cD.mjs.map +1 -0
  104. package/dist/{posture-origins-CEm83u4D.js → posture-origins-CdVOdiMT.js} +7 -1
  105. package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
  106. package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
  107. package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
  108. package/dist/registered-sid-D3g-gZQF.d.mts +11 -0
  109. package/dist/registered-sid-D3g-gZQF.d.mts.map +1 -0
  110. package/dist/registered-sid-D3g-gZQF.d.ts +11 -0
  111. package/dist/registered-sid-D3g-gZQF.d.ts.map +1 -0
  112. package/dist/registered-sid-eLCNZvIF.js +170 -0
  113. package/dist/registered-sid-hUl-bvM5.mjs +142 -0
  114. package/dist/registered-sid-hUl-bvM5.mjs.map +1 -0
  115. package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
  116. package/dist/schemas-7qodsG-Z.mjs.map +1 -0
  117. package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
  118. package/dist/step-up-BjP--hG-.d.mts +114 -0
  119. package/dist/step-up-BjP--hG-.d.mts.map +1 -0
  120. package/dist/step-up-BjP--hG-.d.ts +114 -0
  121. package/dist/step-up-BjP--hG-.d.ts.map +1 -0
  122. package/dist/step-up-C2d8C20x.js +1697 -0
  123. package/dist/step-up-COlmWJN8.mjs +1513 -0
  124. package/dist/step-up-COlmWJN8.mjs.map +1 -0
  125. package/fixtures/cli-registration.v2.json +115 -0
  126. package/fixtures/detection/reason-codes.json +1 -1
  127. package/fixtures/kya-http/README.md +34 -26
  128. package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
  129. package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
  130. package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
  131. package/fixtures/reviewer-grant-revocation.v1.json +285 -0
  132. package/package.json +26 -4
  133. package/dist/posture-origins-Dl7i8j93.mjs.map +0 -1
  134. package/dist/schemas-DxY-dk9y.mjs.map +0 -1
  135. package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
@@ -0,0 +1,694 @@
1
+ const require_kya_http_error_codes = require('./kya-http-error-codes-UYb1zpGM.js');
2
+
3
+ //#region src/utils/detection-class.ts
4
+ /**
5
+ * Convert DetectionClass discriminated union to database enum string
6
+ * Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively
7
+ */
8
+ function detectionClassToEnum(detectionClass) {
9
+ switch (detectionClass.type) {
10
+ case "Human": return "human";
11
+ case "AiAgent": return "ai_agent";
12
+ case "Automation": return "bot";
13
+ case "Bot": return "bot";
14
+ case "IncompleteData": return "incomplete_data";
15
+ default: return "incomplete_data";
16
+ }
17
+ }
18
+ /**
19
+ * Convert database enum string to DetectionClass discriminated union
20
+ * Handles both current and legacy enum values for backwards compatibility
21
+ */
22
+ function enumToDetectionClass(enumValue) {
23
+ switch (enumValue) {
24
+ case "human": return { type: "Human" };
25
+ case "ai_agent": return { type: "AiAgent" };
26
+ case "automation": return { type: "Bot" };
27
+ case "bot": return { type: "Bot" };
28
+ case "incomplete_data": return { type: "IncompleteData" };
29
+ case "unknown": return { type: "IncompleteData" };
30
+ default: return { type: "IncompleteData" };
31
+ }
32
+ }
33
+ /**
34
+ * Check if a value is a valid string-based detection class (current or legacy)
35
+ */
36
+ function isLegacyDetectionClass(value) {
37
+ return typeof value === "string" && [
38
+ "human",
39
+ "ai_agent",
40
+ "bot",
41
+ "incomplete_data",
42
+ "automation",
43
+ "unknown"
44
+ ].includes(value);
45
+ }
46
+ /**
47
+ * Migrate legacy string detection class to new discriminated union
48
+ * @deprecated Use enumToDetectionClass instead
49
+ */
50
+ function migrateLegacyDetectionClass(value) {
51
+ return enumToDetectionClass(value);
52
+ }
53
+ /**
54
+ * Safely convert any detection class value to the discriminated union format
55
+ */
56
+ function normalizeDetectionClass(value) {
57
+ if (value && typeof value === "object" && "type" in value) return value;
58
+ if (isLegacyDetectionClass(value)) return enumToDetectionClass(value);
59
+ return { type: "IncompleteData" };
60
+ }
61
+ /**
62
+ * Safely convert any detection class value to database enum format
63
+ */
64
+ function normalizeDetectionClassEnum(value) {
65
+ if (value && typeof value === "object" && "type" in value) return detectionClassToEnum(value);
66
+ if (isLegacyDetectionClass(value)) return detectionClassToEnum(enumToDetectionClass(value));
67
+ return "incomplete_data";
68
+ }
69
+
70
+ //#endregion
71
+ //#region src/host-adapter/verdict-cookie.ts
72
+ /**
73
+ * Canonical cookie name. Sites-1's `/blocked` page reads from this
74
+ * exact key; do not rename without updating the dashboard route.
75
+ */
76
+ const VERDICT_COOKIE_NAME = "__checkpoint_verdict";
77
+ /**
78
+ * Compute the verdict label from a `RenderedResponse`.
79
+ */
80
+ function deriveVerdict(rendered) {
81
+ if (rendered.status === null) return "allowed";
82
+ if (rendered.status === 302) return "redirected";
83
+ return "denied";
84
+ }
85
+ /**
86
+ * Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast
87
+ * reads. Byte-format pinned by tests in both `checkpoint-nextjs` and
88
+ * `checkpoint-express`:
89
+ *
90
+ * - allowed: `{"verdict":"allowed"}`
91
+ * - denied: `{"verdict":"denied","reason":"<r>"}`
92
+ * - redirected: `{"verdict":"redirected"}`
93
+ *
94
+ * Returns raw JSON; the host's cookie-write call URL-encodes.
95
+ */
96
+ function encodeVerdictCookie(rendered) {
97
+ const verdict = deriveVerdict(rendered);
98
+ const reason = rendered.headers["X-Checkpoint-Reason"];
99
+ return JSON.stringify(reason ? {
100
+ verdict,
101
+ reason
102
+ } : { verdict });
103
+ }
104
+
105
+ //#endregion
106
+ //#region src/host-adapter/content-negotiation.ts
107
+ /**
108
+ * Content negotiation — framework-agnostic Accept-header parsing for
109
+ * host adapters.
110
+ *
111
+ * The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching
112
+ * decisions; the host wrapper does that based on what the client
113
+ * accepts. Both Next.js (NextRequest) and Express (Request) carry the
114
+ * Accept header in different shapes — `req.headers.get('accept')` vs
115
+ * `req.get('Accept')` vs `req.headers.accept` — so we accept any
116
+ * Headers-like input and do the parsing here.
117
+ */
118
+ /**
119
+ * `true` when the client signaled it accepts HTML or XHTML. Used by
120
+ * host adapters to choose between an HTML `/blocked` rewrite (browsers)
121
+ * and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).
122
+ *
123
+ * Loose match — q-values, parameters, and additional MIME types are
124
+ * allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't
125
+ * matter here; we only care whether HTML is present at all.
126
+ *
127
+ * Accepts:
128
+ * - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)
129
+ * - a plain `Record<string, string>` (Express, Connect, Fastify)
130
+ * - a single string (caller already extracted the Accept value)
131
+ * - `undefined` (treated as no-HTML)
132
+ */
133
+ function acceptsHtml(input) {
134
+ const accept = extractAccept(input);
135
+ if (!accept) return false;
136
+ return accept.includes("text/html") || accept.includes("application/xhtml+xml");
137
+ }
138
+ function extractAccept(input) {
139
+ if (!input) return void 0;
140
+ if (typeof input === "string") return input;
141
+ if (typeof input.get === "function") return input.get("accept") ?? void 0;
142
+ const rec = input;
143
+ const value = rec.accept ?? rec.Accept;
144
+ if (Array.isArray(value)) return value.join(",");
145
+ return value;
146
+ }
147
+
148
+ //#endregion
149
+ //#region src/host-adapter/decision-mapping.ts
150
+ /**
151
+ * Path the `/blocked` dashboard route lives at. HTML clients that hit
152
+ * a 4xx verdict get rewritten here at status 200 so the page renders
153
+ * with the verdict cookie set and Sonner can pick up the toast.
154
+ *
155
+ * Hard-coded by convention; if a customer ever needs a custom path,
156
+ * pass it through `CheckpointConfig.blockedPath` and override in the
157
+ * host adapter (not in this lookup).
158
+ */
159
+ const BLOCKED_PATH = "/blocked";
160
+ /**
161
+ * Classify a `RenderedResponse` into one of the four host-adapter
162
+ * branches. `clientAcceptsHtml` comes from `acceptsHtml()` in
163
+ * `content-negotiation.ts`.
164
+ */
165
+ function classifyResponseShape(rendered, clientAcceptsHtml) {
166
+ if (rendered.status === null) return "pass-through";
167
+ if (rendered.status === 302 && rendered.headers.Location) return "redirect";
168
+ if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return "html-block";
169
+ return "json-block";
170
+ }
171
+
172
+ //#endregion
173
+ //#region src/host-adapter/fetcher-envelope.ts
174
+ /**
175
+ * Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).
176
+ *
177
+ * AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx
178
+ * responses and never surface the body to the LLM, so the §8.1 step-up
179
+ * challenge served at 401 is invisible. The fix is a dual envelope: keep
180
+ * the spec 401 for capable/discovery clients, and serve a body-readable
181
+ * HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying
182
+ * agents so they can read the body + relay the consent link.
183
+ *
184
+ * `serveBodyReadable200` is the shared selection predicate every TS PEP
185
+ * (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its
186
+ * challenge-emission mode is `negotiated`. Centralising it here — rather
187
+ * than re-implementing per PEP — makes drift structurally impossible; the
188
+ * fetcher-200 fixture freezes envelope BYTES, this function freezes the
189
+ * SELECTION.
190
+ *
191
+ * **This is a cooperative-UX bridge, NOT an access control.** A spoofer
192
+ * that hides its identity and does not opt in simply receives the spec
193
+ * 401 (and the original body-drop). Access is still gated entirely by the
194
+ * unchanged detection + delegation verification — never by which envelope
195
+ * is selected.
196
+ */
197
+ /**
198
+ * Durable opt-in header — the primary, framework-agnostic signal that a
199
+ * caller is a cooperative agent able to handle the 200 fetcher envelope.
200
+ * Any non-empty value counts as opt-in (value semantics are reconciled
201
+ * with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).
202
+ */
203
+ const ACCEPT_CHALLENGE_HEADER = "kya-accept-challenge";
204
+ function readHeader(input, name) {
205
+ if (!input) return void 0;
206
+ if (typeof input.get === "function") return input.get(name) ?? void 0;
207
+ const rec = input;
208
+ const lower = name.toLowerCase();
209
+ for (const key of Object.keys(rec)) if (key.toLowerCase() === lower) {
210
+ const v = rec[key];
211
+ return Array.isArray(v) ? v[0] : v ?? void 0;
212
+ }
213
+ }
214
+ /**
215
+ * Decide whether a `negotiated`-mode PEP should serve the body-readable
216
+ * HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).
217
+ *
218
+ * Serve 200 when EITHER:
219
+ * 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header
220
+ * (the durable, primary signal), OR
221
+ * 2. detection classifies the caller as an AI agent — BOTH `isAgent` and
222
+ * `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,
223
+ * retired as frameworks adopt the header).
224
+ *
225
+ * Otherwise serve the 401 — spoofers, silent, discovery, and OAuth
226
+ * clients all land here, which is acceptable because this is UX, not a
227
+ * security boundary.
228
+ *
229
+ * Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic
230
+ * mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==
231
+ * AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on
232
+ * the pathological case where the two signals disagree (class says agent,
233
+ * `isAgent` says no): that caller is treated as non-cooperative (spec 401),
234
+ * never demoted past it. In normal engine output the two signals agree, so
235
+ * who-gets-200 is unchanged for real traffic.
236
+ *
237
+ * @param headers request headers (for the opt-in signal)
238
+ * @param detectionClass the caller's detection class in any representation
239
+ * the engine produces (a `DetectionClass` object, the
240
+ * `ai_agent` wire string, or absent)
241
+ * @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`
242
+ * heuristic so a class/`isAgent` disagreement gets the 401
243
+ */
244
+ function serveBodyReadable200(headers, detectionClass, isAgent) {
245
+ const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);
246
+ if (optIn && optIn.trim().length > 0) return true;
247
+ if (isAgent && detectionClass !== void 0 && detectionClass !== null) {
248
+ if (normalizeDetectionClassEnum(detectionClass) === "ai_agent") return true;
249
+ }
250
+ return false;
251
+ }
252
+ /**
253
+ * Resolve the challenge-emission mode + request signals into the single
254
+ * boolean each PEP needs: serve the body-readable 200 (`true`) or the spec
255
+ * 401 (`false`). Centralising the mode gate here — not just the predicate —
256
+ * keeps the rollout switch identical across every TS PEP.
257
+ */
258
+ function selectBodyReadable200(mode, headers, detectionClass, isAgent) {
259
+ if (mode === "always-200") return true;
260
+ if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass, isAgent);
261
+ return false;
262
+ }
263
+
264
+ //#endregion
265
+ //#region src/host-adapter/challenge-wire.ts
266
+ /**
267
+ * Canonical fixture-pinned KYA HTTP challenge-wire builder.
268
+ *
269
+ * The builder is transport-neutral and Edge-safe. Hosts must register the
270
+ * challenge and resolve every URI before calling it; this module validates and
271
+ * serializes those trusted values without network, database, or request access.
272
+ */
273
+ const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
274
+ const DEFAULT_POLL_INTERVAL_S = 3;
275
+ const INVALID_QUOTED_VALUE = /[\u0000-\u001f\u007f"\\]/;
276
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
277
+ const SID = /^kya-[0-9a-f]{16,}$/;
278
+ const ASSURANCE_TIERS = /* @__PURE__ */ new Set([
279
+ "anonymous",
280
+ "attested-bearer",
281
+ "key-bound",
282
+ "registered",
283
+ "delegated"
284
+ ]);
285
+ /** Typed validation failure raised before any response is materialized. */
286
+ var ChallengeWireError = class extends TypeError {
287
+ code;
288
+ constructor(code, message) {
289
+ super(message);
290
+ this.name = "ChallengeWireError";
291
+ this.code = code;
292
+ }
293
+ };
294
+ /** Generate a 128-bit, lower-case hexadecimal challenge id. */
295
+ function generateDelegationSid() {
296
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
297
+ crypto.getRandomValues(bytes);
298
+ let hex = "";
299
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
300
+ return `kya-${hex}`;
301
+ }
302
+ /** Derive pickup from the registered consent origin, never request Host. */
303
+ function deriveDelegationPickupUri(consentUri, sid) {
304
+ const consent = parseHttpsUrl("consentUri", consentUri);
305
+ assertQuotedValue("sid", sid, "invalid-sid");
306
+ return `${consent.origin}/api/delegation/pickup/${sid}`;
307
+ }
308
+ /** Build the byte-pinned Delegation authentication field value. */
309
+ function buildDelegationChallengeHeader(input) {
310
+ const normalized = validateInput(input);
311
+ const params = [
312
+ ["realm", normalized.realm],
313
+ ["sid", normalized.sid],
314
+ ["consent_uri", normalized.consentUri],
315
+ ["pickup_uri", normalized.pickupUri]
316
+ ];
317
+ if (normalized.requiredScopes.length > 0) params.push(["scope", normalized.requiredScopes.join(" ")]);
318
+ if (normalized.minAssurance) params.push(["min_assurance", normalized.minAssurance]);
319
+ if (input.pollIntervalS !== void 0) params.push(["interval", String(normalized.pollIntervalS)]);
320
+ params.push(["kind", normalized.kind]);
321
+ return `Delegation ${params.map(([name, value]) => `${name}="${value}"`).join(", ")}`;
322
+ }
323
+ /** Build RFC 9728 Bearer discovery for a protected-resource realm. */
324
+ function buildDelegationBearerHeader(realm) {
325
+ assertRealm(realm);
326
+ return `Bearer resource_metadata="https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}"`;
327
+ }
328
+ /** Build the four required machine-followable delegation instruction elements. */
329
+ function buildDelegationInstructions(consentUri, pickupUri, pollIntervalS) {
330
+ return `This action requires human authorization. First establish your pickup binding at ${pickupUri}. 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. After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`;
331
+ }
332
+ /** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */
333
+ function buildDelegationChallengeBody(input) {
334
+ const normalized = validateInput(input);
335
+ const common = {
336
+ sid: normalized.sid,
337
+ consent_uri: normalized.consentUri,
338
+ pickup_uri: normalized.pickupUri,
339
+ ...normalized.requiredScopes.length > 0 ? { required_scopes: [...normalized.requiredScopes] } : {},
340
+ ...normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {},
341
+ poll_interval_s: normalized.pollIntervalS,
342
+ challenge_proof: input.challengeProof
343
+ };
344
+ if (normalized.kind === "approval_quorum") return {
345
+ error: require_kya_http_error_codes.KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
346
+ kyaos: {
347
+ sid: common.sid,
348
+ kind: "approval_quorum",
349
+ quorum: normalized.quorum,
350
+ action_nonce: normalized.actionNonce,
351
+ consent_uri: common.consent_uri,
352
+ pickup_uri: common.pickup_uri,
353
+ ...common.required_scopes ? { required_scopes: common.required_scopes } : {},
354
+ ...common.min_assurance ? { min_assurance: common.min_assurance } : {},
355
+ poll_interval_s: common.poll_interval_s,
356
+ challenge_proof: common.challenge_proof
357
+ },
358
+ instructions: buildApprovalQuorumInstructions(normalized)
359
+ };
360
+ return {
361
+ error: require_kya_http_error_codes.KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
362
+ kyaos: {
363
+ ...common,
364
+ action: {
365
+ type: "delegation",
366
+ consent_uri: normalized.consentUri,
367
+ pickup_uri: normalized.pickupUri,
368
+ poll_interval_s: normalized.pollIntervalS,
369
+ pin: { header: "X-KYA-Pickup-Token" },
370
+ retry: {
371
+ header: "Authorization",
372
+ scheme: "Bearer",
373
+ value_from: "delegation"
374
+ }
375
+ }
376
+ },
377
+ instructions: buildDelegationInstructions(normalized.consentUri, normalized.pickupUri, normalized.pollIntervalS)
378
+ };
379
+ }
380
+ /** Build either the canonical 401 or its body-identical fetcher-200 envelope. */
381
+ function buildDelegationChallengeEnvelope(input, mode = "spec-401") {
382
+ const normalized = validateInput(input);
383
+ if (normalized.kind === "approval_quorum" && mode === "fetcher-200") throw new ChallengeWireError("unsupported-envelope", "fetcher-200 is not fixture-defined for approval_quorum");
384
+ const body = buildDelegationChallengeBody(input);
385
+ if (normalized.kind === "approval_quorum") return {
386
+ status: 401,
387
+ headers: [
388
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
389
+ ["Retry-After", String(normalized.pollIntervalS)],
390
+ ["Content-Type", "application/json"],
391
+ ["Cache-Control", "no-store"]
392
+ ],
393
+ body
394
+ };
395
+ const hintHeaders = [
396
+ ["Content-Type", "application/json"],
397
+ ["Cache-Control", "no-store"],
398
+ ["KYA-Auth-Required", "true"],
399
+ ["KYA-Auth-Url", normalized.consentUri],
400
+ ["Link", `<${normalized.consentUri}>; rel="kya-authorize"`],
401
+ ["KYA-Action", "challenge"]
402
+ ];
403
+ if (mode === "fetcher-200") return {
404
+ status: 200,
405
+ headers: hintHeaders,
406
+ body
407
+ };
408
+ return {
409
+ status: 401,
410
+ headers: [
411
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
412
+ ["WWW-Authenticate", `Bearer resource_metadata="${normalized.resourceMetadataUri}"`],
413
+ ["Retry-After", String(normalized.pollIntervalS)],
414
+ ...hintHeaders
415
+ ],
416
+ body
417
+ };
418
+ }
419
+ /** Preferred generic name; the legacy export remains for host compatibility. */
420
+ const buildChallengeWire = buildDelegationChallengeEnvelope;
421
+ function validateInput(input) {
422
+ assertRealm(input.realm);
423
+ assertQuotedValue("sid", input.sid, "invalid-sid");
424
+ if (!SID.test(input.sid)) throw new ChallengeWireError("invalid-sid", "sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy");
425
+ const consent = parseHttpsUrl("consentUri", input.consentUri);
426
+ const pickup = parseHttpsUrl("pickupUri", input.pickupUri);
427
+ const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;
428
+ if (pickup.href !== expectedPickup) throw new ChallengeWireError("invalid-uri", "pickupUri must use the registered consent origin and sid");
429
+ const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;
430
+ if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) throw new ChallengeWireError("invalid-interval", "pollIntervalS must be an integer from 1 through 999");
431
+ if (input.challengeProof === void 0 || input.challengeProof === null) throw new ChallengeWireError("invalid-proof", "challengeProof is required");
432
+ const requiredScopes = input.requiredScopes ?? [];
433
+ for (const scope of requiredScopes) if (!SCOPE_TOKEN.test(scope)) throw new ChallengeWireError("invalid-scope", `invalid required scope: ${scope}`);
434
+ if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) throw new ChallengeWireError("invalid-assurance", `invalid minAssurance: ${input.minAssurance}`);
435
+ const kind = input.kind ?? "delegation";
436
+ if (kind !== "delegation" && kind !== "approval_quorum") throw new ChallengeWireError("invalid-kind", `unsupported challenge kind: ${String(kind)}`);
437
+ let resourceMetadataUri;
438
+ let quorum;
439
+ let actionNonce;
440
+ if (kind === "delegation") {
441
+ resourceMetadataUri = parseHttpsUrl("resourceMetadataUri", input.resourceMetadataUri).href;
442
+ const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;
443
+ if (resourceMetadataUri !== expectedMetadata) throw new ChallengeWireError("invalid-uri", "resourceMetadataUri must be the protected resource RFC 9728 metadata URL");
444
+ } else {
445
+ const approval = input;
446
+ quorum = approval.quorum;
447
+ actionNonce = approval.actionNonce;
448
+ if (!Number.isInteger(quorum) || quorum < 1) throw new ChallengeWireError("invalid-quorum", "quorum must be a positive integer");
449
+ assertQuotedValue("actionNonce", actionNonce, "invalid-action-nonce");
450
+ }
451
+ return {
452
+ realm: input.realm,
453
+ sid: input.sid,
454
+ consentUri: consent.href,
455
+ pickupUri: pickup.href,
456
+ resourceMetadataUri,
457
+ requiredScopes,
458
+ pollIntervalS,
459
+ minAssurance: input.minAssurance,
460
+ kind,
461
+ quorum,
462
+ actionNonce
463
+ };
464
+ }
465
+ function buildApprovalQuorumInstructions(input) {
466
+ return `This action requires approval from ${input.quorum} human approvers. Show your user this link to begin the approval process: ${input.consentUri}. 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). When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`;
467
+ }
468
+ function assertRealm(realm) {
469
+ assertQuotedValue("realm", realm, "invalid-realm");
470
+ if (realm.includes("/") || realm.includes("@") || realm.includes("?") || realm.includes("#")) throw new ChallengeWireError("invalid-realm", "realm must be a host with an optional port");
471
+ try {
472
+ if (new URL(`https://${realm}`).host !== realm) throw new Error("invalid authority");
473
+ } catch {
474
+ throw new ChallengeWireError("invalid-realm", "realm must be a valid host with an optional port");
475
+ }
476
+ }
477
+ function assertQuotedValue(name, value, code) {
478
+ if (typeof value !== "string" || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) throw new ChallengeWireError(code, `${name} contains characters unsafe for an HTTP quoted-string`);
479
+ }
480
+ function parseHttpsUrl(name, value) {
481
+ assertQuotedValue(name, value, "invalid-uri");
482
+ let parsed;
483
+ try {
484
+ parsed = new URL(value);
485
+ } catch {
486
+ throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL`);
487
+ }
488
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL without credentials`);
489
+ return parsed;
490
+ }
491
+
492
+ //#endregion
493
+ //#region src/host-adapter/challenge-context.ts
494
+ const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3e3;
495
+ /**
496
+ * Resolve and validate registered challenge context at the async host boundary.
497
+ * Resolver failures become an absent context so the renderer can emit the
498
+ * canonical retryable status-pending response; secrets and proof values are
499
+ * never included in failure events.
500
+ */
501
+ async function resolveChallengeContext(resolver, context, options = {}) {
502
+ if (!resolver) return void 0;
503
+ const timeoutMs = options.timeoutMs ?? 3e3;
504
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new TypeError("challenge context timeout must be a positive integer");
505
+ let timeoutId;
506
+ try {
507
+ const value = await Promise.race([Promise.resolve(resolver(context)), new Promise((_resolve, reject) => {
508
+ timeoutId = setTimeout(() => reject(new ChallengeContextTimeoutError(timeoutMs)), timeoutMs);
509
+ })]);
510
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
511
+ if (!value) return void 0;
512
+ try {
513
+ buildChallengeWire(value, "spec-401");
514
+ return value;
515
+ } catch (error) {
516
+ options.onFailure?.({
517
+ reason: "invalid-context",
518
+ message: error.message
519
+ });
520
+ return;
521
+ }
522
+ } catch (error) {
523
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
524
+ options.onFailure?.({
525
+ reason: error instanceof ChallengeContextTimeoutError ? "timeout" : "resolver-error",
526
+ message: error instanceof ChallengeContextTimeoutError ? error.message : "challenge context resolver failed"
527
+ });
528
+ return;
529
+ }
530
+ }
531
+ var ChallengeContextTimeoutError = class extends Error {
532
+ constructor(timeoutMs) {
533
+ super(`challenge context resolution exceeded ${timeoutMs}ms`);
534
+ this.name = "ChallengeContextTimeoutError";
535
+ }
536
+ };
537
+
538
+ //#endregion
539
+ Object.defineProperty(exports, 'ACCEPT_CHALLENGE_HEADER', {
540
+ enumerable: true,
541
+ get: function () {
542
+ return ACCEPT_CHALLENGE_HEADER;
543
+ }
544
+ });
545
+ Object.defineProperty(exports, 'BLOCKED_PATH', {
546
+ enumerable: true,
547
+ get: function () {
548
+ return BLOCKED_PATH;
549
+ }
550
+ });
551
+ Object.defineProperty(exports, 'ChallengeWireError', {
552
+ enumerable: true,
553
+ get: function () {
554
+ return ChallengeWireError;
555
+ }
556
+ });
557
+ Object.defineProperty(exports, 'DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS', {
558
+ enumerable: true,
559
+ get: function () {
560
+ return DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
561
+ }
562
+ });
563
+ Object.defineProperty(exports, 'VERDICT_COOKIE_NAME', {
564
+ enumerable: true,
565
+ get: function () {
566
+ return VERDICT_COOKIE_NAME;
567
+ }
568
+ });
569
+ Object.defineProperty(exports, 'acceptsHtml', {
570
+ enumerable: true,
571
+ get: function () {
572
+ return acceptsHtml;
573
+ }
574
+ });
575
+ Object.defineProperty(exports, 'buildChallengeWire', {
576
+ enumerable: true,
577
+ get: function () {
578
+ return buildChallengeWire;
579
+ }
580
+ });
581
+ Object.defineProperty(exports, 'buildDelegationBearerHeader', {
582
+ enumerable: true,
583
+ get: function () {
584
+ return buildDelegationBearerHeader;
585
+ }
586
+ });
587
+ Object.defineProperty(exports, 'buildDelegationChallengeBody', {
588
+ enumerable: true,
589
+ get: function () {
590
+ return buildDelegationChallengeBody;
591
+ }
592
+ });
593
+ Object.defineProperty(exports, 'buildDelegationChallengeEnvelope', {
594
+ enumerable: true,
595
+ get: function () {
596
+ return buildDelegationChallengeEnvelope;
597
+ }
598
+ });
599
+ Object.defineProperty(exports, 'buildDelegationChallengeHeader', {
600
+ enumerable: true,
601
+ get: function () {
602
+ return buildDelegationChallengeHeader;
603
+ }
604
+ });
605
+ Object.defineProperty(exports, 'buildDelegationInstructions', {
606
+ enumerable: true,
607
+ get: function () {
608
+ return buildDelegationInstructions;
609
+ }
610
+ });
611
+ Object.defineProperty(exports, 'classifyResponseShape', {
612
+ enumerable: true,
613
+ get: function () {
614
+ return classifyResponseShape;
615
+ }
616
+ });
617
+ Object.defineProperty(exports, 'deriveDelegationPickupUri', {
618
+ enumerable: true,
619
+ get: function () {
620
+ return deriveDelegationPickupUri;
621
+ }
622
+ });
623
+ Object.defineProperty(exports, 'deriveVerdict', {
624
+ enumerable: true,
625
+ get: function () {
626
+ return deriveVerdict;
627
+ }
628
+ });
629
+ Object.defineProperty(exports, 'detectionClassToEnum', {
630
+ enumerable: true,
631
+ get: function () {
632
+ return detectionClassToEnum;
633
+ }
634
+ });
635
+ Object.defineProperty(exports, 'encodeVerdictCookie', {
636
+ enumerable: true,
637
+ get: function () {
638
+ return encodeVerdictCookie;
639
+ }
640
+ });
641
+ Object.defineProperty(exports, 'enumToDetectionClass', {
642
+ enumerable: true,
643
+ get: function () {
644
+ return enumToDetectionClass;
645
+ }
646
+ });
647
+ Object.defineProperty(exports, 'generateDelegationSid', {
648
+ enumerable: true,
649
+ get: function () {
650
+ return generateDelegationSid;
651
+ }
652
+ });
653
+ Object.defineProperty(exports, 'isLegacyDetectionClass', {
654
+ enumerable: true,
655
+ get: function () {
656
+ return isLegacyDetectionClass;
657
+ }
658
+ });
659
+ Object.defineProperty(exports, 'migrateLegacyDetectionClass', {
660
+ enumerable: true,
661
+ get: function () {
662
+ return migrateLegacyDetectionClass;
663
+ }
664
+ });
665
+ Object.defineProperty(exports, 'normalizeDetectionClass', {
666
+ enumerable: true,
667
+ get: function () {
668
+ return normalizeDetectionClass;
669
+ }
670
+ });
671
+ Object.defineProperty(exports, 'normalizeDetectionClassEnum', {
672
+ enumerable: true,
673
+ get: function () {
674
+ return normalizeDetectionClassEnum;
675
+ }
676
+ });
677
+ Object.defineProperty(exports, 'resolveChallengeContext', {
678
+ enumerable: true,
679
+ get: function () {
680
+ return resolveChallengeContext;
681
+ }
682
+ });
683
+ Object.defineProperty(exports, 'selectBodyReadable200', {
684
+ enumerable: true,
685
+ get: function () {
686
+ return selectBodyReadable200;
687
+ }
688
+ });
689
+ Object.defineProperty(exports, 'serveBodyReadable200', {
690
+ enumerable: true,
691
+ get: function () {
692
+ return serveBodyReadable200;
693
+ }
694
+ });