@kya-os/mcp-i-cloudflare 1.18.0 → 1.18.2
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/README.md +273 -54
- package/dist/adapter.d.ts +3 -17
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +30 -477
- package/dist/adapter.js.map +1 -1
- package/dist/agent.d.ts +59 -35
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +383 -406
- package/dist/agent.js.map +1 -1
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +150 -94
- package/dist/app.js.map +1 -1
- package/dist/audit/deployment-binding.d.ts +16 -16
- package/dist/authority-outcome.d.ts +110 -0
- package/dist/authority-outcome.d.ts.map +1 -0
- package/dist/authority-outcome.js +154 -0
- package/dist/authority-outcome.js.map +1 -0
- package/dist/config.d.ts +8 -77
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +0 -83
- package/dist/config.js.map +1 -1
- package/dist/delegation-http/bearer-retry.d.ts +84 -32
- package/dist/delegation-http/bearer-retry.d.ts.map +1 -1
- package/dist/delegation-http/bearer-retry.js +124 -139
- package/dist/delegation-http/bearer-retry.js.map +1 -1
- package/dist/delegation-http/connect-gate.d.ts +47 -0
- package/dist/delegation-http/connect-gate.d.ts.map +1 -0
- package/dist/delegation-http/connect-gate.js +104 -0
- package/dist/delegation-http/connect-gate.js.map +1 -0
- package/dist/delegation-http/constants.d.ts +4 -49
- package/dist/delegation-http/constants.d.ts.map +1 -1
- package/dist/delegation-http/constants.js +4 -58
- package/dist/delegation-http/constants.js.map +1 -1
- package/dist/delegation-http/issuer-binding.d.ts +26 -0
- package/dist/delegation-http/issuer-binding.d.ts.map +1 -0
- package/dist/delegation-http/issuer-binding.js +51 -0
- package/dist/delegation-http/issuer-binding.js.map +1 -0
- package/dist/delegation-http/lazy-auth-gate.d.ts +88 -0
- package/dist/delegation-http/lazy-auth-gate.d.ts.map +1 -0
- package/dist/delegation-http/lazy-auth-gate.js +203 -0
- package/dist/delegation-http/lazy-auth-gate.js.map +1 -0
- package/dist/delegation-http/native-challenge.d.ts +52 -0
- package/dist/delegation-http/native-challenge.d.ts.map +1 -0
- package/dist/delegation-http/native-challenge.js +124 -0
- package/dist/delegation-http/native-challenge.js.map +1 -0
- package/dist/delegation-http/native-consent-redirect.d.ts +21 -0
- package/dist/delegation-http/native-consent-redirect.d.ts.map +1 -0
- package/dist/delegation-http/native-consent-redirect.js +43 -0
- package/dist/delegation-http/native-consent-redirect.js.map +1 -0
- package/dist/delegation-http/native-http.d.ts +1 -86
- package/dist/delegation-http/native-http.d.ts.map +1 -1
- package/dist/delegation-http/native-http.js +2 -130
- package/dist/delegation-http/native-http.js.map +1 -1
- package/dist/delegation-http/native-oauth-state-do.d.ts +13 -35
- package/dist/delegation-http/native-oauth-state-do.d.ts.map +1 -1
- package/dist/delegation-http/native-oauth-state-do.js +10 -165
- package/dist/delegation-http/native-oauth-state-do.js.map +1 -1
- package/dist/delegation-http/protected-resource.d.ts +37 -0
- package/dist/delegation-http/protected-resource.d.ts.map +1 -0
- package/dist/delegation-http/protected-resource.js +43 -0
- package/dist/delegation-http/protected-resource.js.map +1 -0
- package/dist/delegation-http/request-proof.d.ts +20 -0
- package/dist/delegation-http/request-proof.d.ts.map +1 -0
- package/dist/delegation-http/request-proof.js +29 -0
- package/dist/delegation-http/request-proof.js.map +1 -0
- package/dist/delegation-http/sid.d.ts +4 -12
- package/dist/delegation-http/sid.d.ts.map +1 -1
- package/dist/delegation-http/sid.js +4 -19
- package/dist/delegation-http/sid.js.map +1 -1
- package/dist/delegation-http/well-known-capability.d.ts +8 -12
- package/dist/delegation-http/well-known-capability.d.ts.map +1 -1
- package/dist/delegation-http/well-known-capability.js +9 -18
- package/dist/delegation-http/well-known-capability.js.map +1 -1
- package/dist/helpers/env-mapper.d.ts.map +1 -1
- package/dist/helpers/env-mapper.js +7 -29
- package/dist/helpers/env-mapper.js.map +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -8
- package/dist/index.js.map +1 -1
- package/dist/proof-generator.d.ts +24 -17
- package/dist/proof-generator.d.ts.map +1 -1
- package/dist/proof-generator.js +42 -56
- package/dist/proof-generator.js.map +1 -1
- package/dist/runtime/oauth-handler.d.ts +1 -1
- package/dist/runtime/oauth-handler.d.ts.map +1 -1
- package/dist/runtime/oauth-handler.js +15 -30
- package/dist/runtime/oauth-handler.js.map +1 -1
- package/dist/runtime.d.ts +34 -10
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +54 -12
- package/dist/runtime.js.map +1 -1
- package/dist/security/admission-refusal.d.ts +3 -3
- package/dist/security/admission-refusal.d.ts.map +1 -1
- package/dist/security/admission-refusal.js +14 -6
- package/dist/security/admission-refusal.js.map +1 -1
- package/dist/security/holder-binding.d.ts +34 -0
- package/dist/security/holder-binding.d.ts.map +1 -0
- package/dist/security/holder-binding.js +75 -0
- package/dist/security/holder-binding.js.map +1 -0
- package/dist/security/mcp-admission.d.ts +29 -1
- package/dist/security/mcp-admission.d.ts.map +1 -1
- package/dist/security/mcp-admission.js +78 -12
- package/dist/security/mcp-admission.js.map +1 -1
- package/dist/security/native-holder-admission.d.ts +39 -0
- package/dist/security/native-holder-admission.d.ts.map +1 -0
- package/dist/security/native-holder-admission.js +65 -0
- package/dist/security/native-holder-admission.js.map +1 -0
- package/dist/security/outcome-proof.d.ts +39 -0
- package/dist/security/outcome-proof.d.ts.map +1 -0
- package/dist/security/outcome-proof.js +54 -0
- package/dist/security/outcome-proof.js.map +1 -0
- package/dist/security/request-nonce-store.d.ts +43 -0
- package/dist/security/request-nonce-store.d.ts.map +1 -0
- package/dist/security/request-nonce-store.js +129 -0
- package/dist/security/request-nonce-store.js.map +1 -0
- package/dist/security/routed-request.d.ts +41 -0
- package/dist/security/routed-request.d.ts.map +1 -0
- package/dist/security/routed-request.js +86 -0
- package/dist/security/routed-request.js.map +1 -0
- package/dist/security/sign-in-amr.d.ts +23 -0
- package/dist/security/sign-in-amr.d.ts.map +1 -0
- package/dist/security/sign-in-amr.js +44 -0
- package/dist/security/sign-in-amr.js.map +1 -0
- package/dist/services/approval-route.d.ts +3 -2
- package/dist/services/approval-route.d.ts.map +1 -1
- package/dist/services/approval-route.js.map +1 -1
- package/dist/services/checkpoint-decision.d.ts +56 -0
- package/dist/services/checkpoint-decision.d.ts.map +1 -0
- package/dist/services/checkpoint-decision.js +109 -0
- package/dist/services/checkpoint-decision.js.map +1 -0
- package/dist/services/consent-page-renderer.d.ts.map +1 -1
- package/dist/services/consent-page-renderer.js +2 -3
- package/dist/services/consent-page-renderer.js.map +1 -1
- package/dist/services/consent.service.d.ts +11 -49
- package/dist/services/consent.service.d.ts.map +1 -1
- package/dist/services/consent.service.js +81 -307
- package/dist/services/consent.service.js.map +1 -1
- package/dist/services/credential-auth.handler.d.ts.map +1 -1
- package/dist/services/credential-auth.handler.js +2 -8
- package/dist/services/credential-auth.handler.js.map +1 -1
- package/dist/services/delegation-authority.d.ts +53 -0
- package/dist/services/delegation-authority.d.ts.map +1 -0
- package/dist/services/delegation-authority.js +130 -0
- package/dist/services/delegation-authority.js.map +1 -0
- package/dist/services/delegation-trust.d.ts +35 -64
- package/dist/services/delegation-trust.d.ts.map +1 -1
- package/dist/services/delegation-trust.js +98 -279
- package/dist/services/delegation-trust.js.map +1 -1
- package/dist/services/delegation.service.d.ts +83 -105
- package/dist/services/delegation.service.d.ts.map +1 -1
- package/dist/services/delegation.service.js +166 -518
- package/dist/services/delegation.service.js.map +1 -1
- package/dist/services/idp-token-storage.d.ts +32 -12
- package/dist/services/idp-token-storage.d.ts.map +1 -1
- package/dist/services/idp-token-storage.js +79 -36
- package/dist/services/idp-token-storage.js.map +1 -1
- package/dist/services/issuer-keys.d.ts +55 -0
- package/dist/services/issuer-keys.d.ts.map +1 -0
- package/dist/services/issuer-keys.js +184 -0
- package/dist/services/issuer-keys.js.map +1 -0
- package/dist/services/oauth-security.service.d.ts +17 -1
- package/dist/services/oauth-security.service.d.ts.map +1 -1
- package/dist/services/oauth-security.service.js +29 -10
- package/dist/services/oauth-security.service.js.map +1 -1
- package/dist/services/resource-audience.d.ts +12 -9
- package/dist/services/resource-audience.d.ts.map +1 -1
- package/dist/services/resource-audience.js +12 -9
- package/dist/services/resource-audience.js.map +1 -1
- package/dist/services/unenforceable-tool-protection.d.ts +32 -0
- package/dist/services/unenforceable-tool-protection.d.ts.map +1 -0
- package/dist/services/unenforceable-tool-protection.js +90 -0
- package/dist/services/unenforceable-tool-protection.js.map +1 -0
- package/dist/services/upstream-fetch.d.ts +14 -0
- package/dist/services/upstream-fetch.d.ts.map +1 -0
- package/dist/services/upstream-fetch.js +56 -0
- package/dist/services/upstream-fetch.js.map +1 -0
- package/dist/types.d.ts +5 -18
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/tool-security-schemes.d.ts +65 -0
- package/dist/utils/tool-security-schemes.d.ts.map +1 -0
- package/dist/utils/tool-security-schemes.js +168 -0
- package/dist/utils/tool-security-schemes.js.map +1 -0
- package/package.json +4 -5
- package/dist/delegation-http/anchor-do.d.ts +0 -84
- package/dist/delegation-http/anchor-do.d.ts.map +0 -1
- package/dist/delegation-http/anchor-do.js +0 -412
- package/dist/delegation-http/anchor-do.js.map +0 -1
- package/dist/delegation-http/anchor-registration-validate.d.ts +0 -61
- package/dist/delegation-http/anchor-registration-validate.d.ts.map +0 -1
- package/dist/delegation-http/anchor-registration-validate.js +0 -191
- package/dist/delegation-http/anchor-registration-validate.js.map +0 -1
- package/dist/delegation-http/anchor-registration.d.ts +0 -62
- package/dist/delegation-http/anchor-registration.d.ts.map +0 -1
- package/dist/delegation-http/anchor-registration.js +0 -337
- package/dist/delegation-http/anchor-registration.js.map +0 -1
- package/dist/delegation-http/anchor-routing.d.ts +0 -20
- package/dist/delegation-http/anchor-routing.d.ts.map +0 -1
- package/dist/delegation-http/anchor-routing.js +0 -27
- package/dist/delegation-http/anchor-routing.js.map +0 -1
- package/dist/delegation-http/challenge-middleware.d.ts +0 -28
- package/dist/delegation-http/challenge-middleware.d.ts.map +0 -1
- package/dist/delegation-http/challenge-middleware.js +0 -190
- package/dist/delegation-http/challenge-middleware.js.map +0 -1
- package/dist/delegation-http/challenge.d.ts +0 -102
- package/dist/delegation-http/challenge.d.ts.map +0 -1
- package/dist/delegation-http/challenge.js +0 -223
- package/dist/delegation-http/challenge.js.map +0 -1
- package/dist/delegation-http/consent-anchor-bridge.d.ts +0 -70
- package/dist/delegation-http/consent-anchor-bridge.d.ts.map +0 -1
- package/dist/delegation-http/consent-anchor-bridge.js +0 -1130
- package/dist/delegation-http/consent-anchor-bridge.js.map +0 -1
- package/dist/delegation-http/consent-preparation-page.d.ts +0 -18
- package/dist/delegation-http/consent-preparation-page.d.ts.map +0 -1
- package/dist/delegation-http/consent-preparation-page.js +0 -172
- package/dist/delegation-http/consent-preparation-page.js.map +0 -1
- package/dist/delegation-http/credential-consent.d.ts +0 -149
- package/dist/delegation-http/credential-consent.d.ts.map +0 -1
- package/dist/delegation-http/credential-consent.js +0 -338
- package/dist/delegation-http/credential-consent.js.map +0 -1
- package/dist/delegation-http/native-capabilities.d.ts +0 -4
- package/dist/delegation-http/native-capabilities.d.ts.map +0 -1
- package/dist/delegation-http/native-capabilities.js +0 -53
- package/dist/delegation-http/native-capabilities.js.map +0 -1
- package/dist/delegation-http/native-oauth-state.d.ts +0 -28
- package/dist/delegation-http/native-oauth-state.d.ts.map +0 -1
- package/dist/delegation-http/native-oauth-state.js +0 -146
- package/dist/delegation-http/native-oauth-state.js.map +0 -1
- package/dist/delegation-http/native-oauth.d.ts +0 -26
- package/dist/delegation-http/native-oauth.d.ts.map +0 -1
- package/dist/delegation-http/native-oauth.js +0 -401
- package/dist/delegation-http/native-oauth.js.map +0 -1
- package/dist/delegation-http/native-pickup.d.ts +0 -20
- package/dist/delegation-http/native-pickup.d.ts.map +0 -1
- package/dist/delegation-http/native-pickup.js +0 -227
- package/dist/delegation-http/native-pickup.js.map +0 -1
- package/dist/delegation-http/pickup-routes.d.ts +0 -43
- package/dist/delegation-http/pickup-routes.d.ts.map +0 -1
- package/dist/delegation-http/pickup-routes.js +0 -166
- package/dist/delegation-http/pickup-routes.js.map +0 -1
- package/dist/delegation-http/register.d.ts +0 -26
- package/dist/delegation-http/register.d.ts.map +0 -1
- package/dist/delegation-http/register.js +0 -95
- package/dist/delegation-http/register.js.map +0 -1
- package/dist/delegation-http/registrar-auth.d.ts +0 -24
- package/dist/delegation-http/registrar-auth.d.ts.map +0 -1
- package/dist/delegation-http/registrar-auth.js +0 -61
- package/dist/delegation-http/registrar-auth.js.map +0 -1
- package/dist/delegation-http/remote-issuer.d.ts +0 -52
- package/dist/delegation-http/remote-issuer.d.ts.map +0 -1
- package/dist/delegation-http/remote-issuer.js +0 -324
- package/dist/delegation-http/remote-issuer.js.map +0 -1
- package/dist/delegation-http/types.d.ts +0 -116
- package/dist/delegation-http/types.d.ts.map +0 -1
- package/dist/delegation-http/types.js +0 -11
- package/dist/delegation-http/types.js.map +0 -1
|
@@ -1,1130 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* draft-kya-http-02 delegation layer — consent → pickup bridge.
|
|
3
|
-
*
|
|
4
|
-
* The worker is its own Tier-2 authorization host: the §8.1 challenge points the
|
|
5
|
-
* caller's user at `consent_uri = /consent?sid=kya-…`, served here. This module is
|
|
6
|
-
* the route-order interception that `register.ts` wires BEFORE the legacy `/consent`
|
|
7
|
-
* routes; it only ever handles requests whose query carries an anchor sid (the
|
|
8
|
-
* `next()` fall-through for everything else lives in `register.ts`), so the legacy
|
|
9
|
-
* consent service is untouched.
|
|
10
|
-
*
|
|
11
|
-
* - `GET /consent?sid=kya-…` reads the anchor via `INTERNAL_PICKUP_INFO`. An unknown
|
|
12
|
-
* sid → 404 page; an expired sid → a "link expired" page; otherwise the SAME
|
|
13
|
-
* branded `@kya-os/consent` Lit shell `consent.service.ts` renders for the
|
|
14
|
-
* OAuth path, driven by the project's own `consentConfig`. The anchor sid
|
|
15
|
-
* travels to the approve POST as the shell's `session-id` attribute (see
|
|
16
|
-
* `resolveApproveSid`), since the Lit component has no way to append a query
|
|
17
|
-
* string to its hardcoded `/consent/approve` fetch target.
|
|
18
|
-
* - `POST /consent/approve?sid=kya-…` mints a delegation VC-JWT using the SAME
|
|
19
|
-
* `@kya-os/mcp` primitives `consent.service.ts` uses (`wrapDelegationAsVC` →
|
|
20
|
-
* `createUnsignedVCJWT` → sign → `completeVCJWT`) — calling them directly here, NOT
|
|
21
|
-
* editing the service — then parks it on the anchor via `INTERNAL_PICKUP_APPROVE`.
|
|
22
|
-
* If the anchor is gone (DO 410/404) the approval FAILS with an error page and
|
|
23
|
-
* mints nothing reachable: consent on an EXPIRED anchor MUST fail.
|
|
24
|
-
*
|
|
25
|
-
* @module @kya-os/mcp-i-cloudflare/delegation-http/consent-anchor-bridge
|
|
26
|
-
*/
|
|
27
|
-
import { wrapDelegationAsVC, createUnsignedVCJWT, completeVCJWT, base64urlEncodeFromBytes, generateDidKeyFromBase64, didKeyFragment, } from "@kya-os/mcp";
|
|
28
|
-
import { generateConsentShell, resolveCapabilitiesForScopes, } from "@kya-os/consent";
|
|
29
|
-
import { beginNativeOAuth, verifyNativeOAuthIdentity } from "./native-oauth";
|
|
30
|
-
import { nativeCapabilitiesForScopes } from "./native-capabilities";
|
|
31
|
-
import { consentPreparationPage } from "./consent-preparation-page";
|
|
32
|
-
import { WebCryptoProvider } from "../providers/crypto";
|
|
33
|
-
import { getConfiguredIdentity } from "../providers/storage";
|
|
34
|
-
import { escapeHtml } from "../services/consent-templates/base/escape";
|
|
35
|
-
import { createCredentialAuthHandler } from "../services/credential-auth.handler";
|
|
36
|
-
import { ConsentConfigService, } from "../services/consent-config.service";
|
|
37
|
-
import { getAnchorStub } from "./anchor-routing";
|
|
38
|
-
import { INTERNAL_PICKUP_INFO, INTERNAL_PICKUP_APPROVE } from "./constants";
|
|
39
|
-
import { isAnchorSid, isNamespacedAnchorSid } from "./sid";
|
|
40
|
-
import { nativeHolderBinding, nativeUnavailable, validNativeStatus, } from "./native-http";
|
|
41
|
-
import { resolveAnchorCredentialProvider, resolveCredentialIdentity, notifyDelegation, } from "./credential-consent";
|
|
42
|
-
/** Internal origin for durable-object stub fetches — the DO routes by pathname only. */
|
|
43
|
-
const DO_INTERNAL_ORIGIN = "https://do.internal";
|
|
44
|
-
/**
|
|
45
|
-
* POST a JSON body to one of the anchor's `/_internal/pickup/*` routes. Returns the
|
|
46
|
-
* durable-object response so callers can branch on its status.
|
|
47
|
-
*/
|
|
48
|
-
async function callAnchor(env, sid, internalPath, body) {
|
|
49
|
-
const stub = getAnchorStub(env, sid);
|
|
50
|
-
const response = await stub.fetch(new URL(internalPath, DO_INTERNAL_ORIGIN).toString(), {
|
|
51
|
-
method: "POST",
|
|
52
|
-
headers: { "Content-Type": "application/json" },
|
|
53
|
-
body: JSON.stringify(body),
|
|
54
|
-
});
|
|
55
|
-
return response;
|
|
56
|
-
}
|
|
57
|
-
/** An HTML response with the mandated `Cache-Control: no-store`. */
|
|
58
|
-
function htmlResponse(html, status) {
|
|
59
|
-
return new Response(html, {
|
|
60
|
-
status,
|
|
61
|
-
headers: {
|
|
62
|
-
"Content-Type": "text/html; charset=utf-8",
|
|
63
|
-
"Cache-Control": "no-store",
|
|
64
|
-
},
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* A JSON response with the mandated `Cache-Control: no-store`. Mirrors
|
|
69
|
-
* {@link htmlResponse} — used by `POST /consent/approve` (a JSON API consumed
|
|
70
|
-
* by the `@kya-os/consent` Lit component's `fetch()`, never a browser
|
|
71
|
-
* navigation), unlike `GET /consent`, which still renders the HTML shell.
|
|
72
|
-
*/
|
|
73
|
-
function jsonResponse(body, status) {
|
|
74
|
-
return new Response(JSON.stringify(body), {
|
|
75
|
-
status,
|
|
76
|
-
headers: {
|
|
77
|
-
"Content-Type": "application/json",
|
|
78
|
-
"Cache-Control": "no-store",
|
|
79
|
-
},
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
/** Minimal self-contained HTML page shell (no external bundle dependency). */
|
|
83
|
-
function page(title, bodyInner) {
|
|
84
|
-
return `<!DOCTYPE html>
|
|
85
|
-
<html lang="en">
|
|
86
|
-
<head>
|
|
87
|
-
<meta charset="UTF-8">
|
|
88
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
89
|
-
<title>${escapeHtml(title)}</title>
|
|
90
|
-
</head>
|
|
91
|
-
<body>
|
|
92
|
-
${bodyInner}
|
|
93
|
-
</body>
|
|
94
|
-
</html>`;
|
|
95
|
-
}
|
|
96
|
-
/** Generic approval-failed page (e.g. the anchor expired between GET and POST). */
|
|
97
|
-
function approvalFailedPage(message, status = 410) {
|
|
98
|
-
return htmlResponse(page("Authorization failed", `<main class="kya-consent-failed">
|
|
99
|
-
<h1>Authorization failed</h1>
|
|
100
|
-
<p>${escapeHtml(message)}</p>
|
|
101
|
-
</main>`), status);
|
|
102
|
-
}
|
|
103
|
-
const REQUEST_NOT_PREPARED = {
|
|
104
|
-
title: "Your agent has not prepared this request yet",
|
|
105
|
-
body: "Before you can approve, your agent must establish the secure key that will receive your permission. No access has been granted.",
|
|
106
|
-
nextStep: "Return to your chat and ask your agent to finish preparing this authorization request before sharing the approval link.",
|
|
107
|
-
unsupported: "If the agent's tools cannot sign requests, this flow cannot be completed in that tool. Do not send your password or browser cookies to the agent.",
|
|
108
|
-
};
|
|
109
|
-
/** Public readiness projection; never return the internal anchor or any credential. */
|
|
110
|
-
function preparationStatus(state, status = 200, expiresAt = Date.now()) {
|
|
111
|
-
const body = {
|
|
112
|
-
authorization: state === "approval_ready"
|
|
113
|
-
? { state, approval_ready: true }
|
|
114
|
-
: { state, approval_ready: false },
|
|
115
|
-
expires_in: Math.max(0, Math.min(600, Math.floor((expiresAt - Date.now()) / 1000))),
|
|
116
|
-
poll_interval_s: 3,
|
|
117
|
-
};
|
|
118
|
-
return jsonResponse(body, status);
|
|
119
|
-
}
|
|
120
|
-
/** Branding is optional; an unavailable control plane cannot hang the recovery UI. */
|
|
121
|
-
async function preparationBranding(env) {
|
|
122
|
-
let timeout;
|
|
123
|
-
try {
|
|
124
|
-
return await Promise.race([
|
|
125
|
-
new ConsentConfigService(env)
|
|
126
|
-
.getConsentConfig(env.CHECKPOINT_PROJECT_ID || "")
|
|
127
|
-
.then((config) => config.branding),
|
|
128
|
-
new Promise((resolve) => {
|
|
129
|
-
timeout = setTimeout(() => resolve(undefined), 1500);
|
|
130
|
-
}),
|
|
131
|
-
]);
|
|
132
|
-
}
|
|
133
|
-
catch {
|
|
134
|
-
return undefined;
|
|
135
|
-
}
|
|
136
|
-
finally {
|
|
137
|
-
clearTimeout(timeout);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* JSON 404 body for `POST /consent/approve` on an unknown anchor sid — the
|
|
142
|
-
* JSON-API twin of the GET /consent recovery page.
|
|
143
|
-
*/
|
|
144
|
-
function notFoundJson() {
|
|
145
|
-
return jsonResponse({
|
|
146
|
-
error_code: "kyaos/consent-request-not-found",
|
|
147
|
-
error: "We could not find this authorization request. It may have already completed or been cancelled.",
|
|
148
|
-
}, 404);
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Generic JSON approval-failed body for `POST /consent/approve` (e.g. the
|
|
152
|
-
* anchor expired between GET and POST). The JSON-API twin of
|
|
153
|
-
* {@link approvalFailedPage}, which stays HTML-only for the `GET /consent`
|
|
154
|
-
* page render's own error cases.
|
|
155
|
-
*/
|
|
156
|
-
function approvalFailedJson(message, status = 410) {
|
|
157
|
-
return jsonResponse({
|
|
158
|
-
error: message,
|
|
159
|
-
// Public diagnostic codes, never token or internal state values.
|
|
160
|
-
...(status === 410 ? { error_code: "kyaos/pickup-expired" } : {}),
|
|
161
|
-
}, status);
|
|
162
|
-
}
|
|
163
|
-
/** A rejected form stays rejected. Read-only readiness selects the safe recovery. */
|
|
164
|
-
async function rejectedFormResponse(env, sid) {
|
|
165
|
-
if (!env.OAUTH_ENCRYPTION_SECRET)
|
|
166
|
-
return jsonResponse({
|
|
167
|
-
error_code: "kyaos/consent-request-unavailable",
|
|
168
|
-
error: "We couldn't check this approval request. Return to your assistant to check its status before trying again.",
|
|
169
|
-
}, 403);
|
|
170
|
-
try {
|
|
171
|
-
const response = await callAnchor(env, sid, INTERNAL_PICKUP_INFO, { sid });
|
|
172
|
-
if (response.status === 404)
|
|
173
|
-
return notFoundJson();
|
|
174
|
-
if (response.status === 410)
|
|
175
|
-
return approvalFailedJson("This approval request has expired. Return to your assistant for a new approval link.");
|
|
176
|
-
if (response.ok) {
|
|
177
|
-
const info = (await response.json());
|
|
178
|
-
if (Number.isFinite(info.expiresAt) && info.expiresAt <= Date.now())
|
|
179
|
-
return approvalFailedJson("This approval request has expired. Return to your assistant for a new approval link.");
|
|
180
|
-
if (Number.isFinite(info.expiresAt) &&
|
|
181
|
-
info.expiresAt > Date.now() &&
|
|
182
|
-
info.status === "pinned")
|
|
183
|
-
return jsonResponse({
|
|
184
|
-
error_code: "kyaos/consent-form-invalid",
|
|
185
|
-
error: "We couldn't verify this approval page. Reload and sign in again, then review the permissions. This submission did not approve access.",
|
|
186
|
-
}, 403);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
catch {
|
|
190
|
-
// Do not claim expiry or offer a form refresh without a valid live anchor.
|
|
191
|
-
}
|
|
192
|
-
return jsonResponse({
|
|
193
|
-
error_code: "kyaos/consent-request-unavailable",
|
|
194
|
-
error: "We couldn't check this approval request. Return to your assistant to check its status before trying again.",
|
|
195
|
-
}, 403);
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Success body after a delegation is parked on the anchor: `@kya-os/consent`'s
|
|
199
|
-
* `handleApprove()` reads `result.delegation_id` (and, absent a
|
|
200
|
-
* `redirectUrl`, renders its own success screen from it) — the anchor path
|
|
201
|
-
* mints in a single POST with no clickwrap redirect, so `redirectUrl` is
|
|
202
|
-
* deliberately omitted.
|
|
203
|
-
*/
|
|
204
|
-
function successJson(delegationId, expiresAtUnix) {
|
|
205
|
-
return jsonResponse({
|
|
206
|
-
success: true,
|
|
207
|
-
delegation_id: delegationId,
|
|
208
|
-
...(expiresAtUnix !== undefined ? { expires_at: expiresAtUnix } : {}),
|
|
209
|
-
}, 200);
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Resolve capability groups for the shell: prefer the operator-authored
|
|
213
|
-
* `consentConfig.capabilities`; otherwise derive from the anchor's required
|
|
214
|
-
* scopes via the `@kya-os/consent` default registry. Mirrors
|
|
215
|
-
* `consent.service.ts`'s own fallback so the humanized capability layout
|
|
216
|
-
* renders even when the dashboard hasn't pushed capability metadata yet.
|
|
217
|
-
*/
|
|
218
|
-
function resolveAnchorCapabilities(consentConfig, scopes) {
|
|
219
|
-
if (consentConfig.capabilities && consentConfig.capabilities.length > 0) {
|
|
220
|
-
return consentConfig.capabilities;
|
|
221
|
-
}
|
|
222
|
-
if (scopes.length === 0)
|
|
223
|
-
return undefined;
|
|
224
|
-
const derived = resolveCapabilitiesForScopes(scopes);
|
|
225
|
-
if (derived.length === 0)
|
|
226
|
-
return undefined;
|
|
227
|
-
return [{ id: "default", label: "Permissions", capabilities: derived }];
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Render the branded `@kya-os/consent` Lit shell for the anchor path — the SAME
|
|
231
|
-
* screen `consent.service.ts` renders for the OAuth / consent-only flow
|
|
232
|
-
* (`TemplateRenderer.renderCSR` / `renderCredentialPageCSR`), driven by the
|
|
233
|
-
* project's own `consentConfig` (branding, terms, credentials copy, and
|
|
234
|
-
* capabilities) fetched via `ConsentConfigService`.
|
|
235
|
-
*
|
|
236
|
-
* `anchorSid` makes the component submit an explicit `sid` field to the shared
|
|
237
|
-
* approval endpoint. `sessionId` is still supplied for existing component
|
|
238
|
-
* behavior, but opaque native IDs must not select a route through session_id.
|
|
239
|
-
*/
|
|
240
|
-
function renderAnchorConsentShell(params) {
|
|
241
|
-
const { consentConfig, info, sid, csrfToken, serverUrl, projectId, credential, oauth, } = params;
|
|
242
|
-
// Credential branch: source labels from the REAL merchant-configured fields —
|
|
243
|
-
// `provider.config.consentOverrides` (per-provider overrides:
|
|
244
|
-
// `identityFieldLabel` / `passwordFieldLabel`, populated by
|
|
245
|
-
// `credential-consent.ts`'s `buildCredentialConfig`) and the project's own
|
|
246
|
-
// `consentConfig.credentials` block (placeholders / remember-me / forgot-
|
|
247
|
-
// password, which have no per-provider equivalent at all) — falling back to
|
|
248
|
-
// the shell's hardcoded defaults last. `CredentialProviderConfig` has no
|
|
249
|
-
// top-level `usernameLabel`/`usernamePlaceholder`/etc fields (reading them was
|
|
250
|
-
// an `as any` bug that always silently fell to the hardcoded defaults); typing
|
|
251
|
-
// `cpc` for real lets the compiler catch that class of mistake again.
|
|
252
|
-
const cpc = credential?.provider.config;
|
|
253
|
-
const cpcOverrides = cpc?.consentOverrides;
|
|
254
|
-
const shellConfig = {
|
|
255
|
-
branding: consentConfig.branding,
|
|
256
|
-
terms: consentConfig.terms,
|
|
257
|
-
customFields: consentConfig.customFields,
|
|
258
|
-
ui: consentConfig.ui,
|
|
259
|
-
expirationDays: consentConfig.expirationDays,
|
|
260
|
-
credentials: credential
|
|
261
|
-
? {
|
|
262
|
-
usernameLabel: cpcOverrides?.identityFieldLabel ||
|
|
263
|
-
consentConfig.credentials?.usernameLabel ||
|
|
264
|
-
"Username",
|
|
265
|
-
usernamePlaceholder: consentConfig.credentials?.usernamePlaceholder ||
|
|
266
|
-
"Enter your username",
|
|
267
|
-
passwordLabel: cpcOverrides?.passwordFieldLabel ||
|
|
268
|
-
consentConfig.credentials?.passwordLabel ||
|
|
269
|
-
"Password",
|
|
270
|
-
passwordPlaceholder: consentConfig.credentials?.passwordPlaceholder ||
|
|
271
|
-
"Enter your password",
|
|
272
|
-
showRememberMe: consentConfig.credentials?.showRememberMe ?? true,
|
|
273
|
-
showForgotPassword: consentConfig.credentials?.showForgotPassword ?? false,
|
|
274
|
-
forgotPasswordUrl: consentConfig.credentials?.forgotPasswordUrl,
|
|
275
|
-
}
|
|
276
|
-
: consentConfig.credentials,
|
|
277
|
-
};
|
|
278
|
-
// Native fallbacks must not inherit the legacy registry's illustrative Cedar.
|
|
279
|
-
// Only operator-authored rows describe policy; unknown requested scopes use
|
|
280
|
-
// the exact-scope disclosure produced by the native projection.
|
|
281
|
-
const catalog = info.nativeHttp
|
|
282
|
-
? consentConfig.capabilities
|
|
283
|
-
: resolveAnchorCapabilities(consentConfig, info.requiredScopes);
|
|
284
|
-
const shellOptions = {
|
|
285
|
-
config: shellConfig,
|
|
286
|
-
tool: "",
|
|
287
|
-
scopes: info.requiredScopes,
|
|
288
|
-
agentDid: info.agentDid || "",
|
|
289
|
-
sessionId: sid,
|
|
290
|
-
anchorSid: sid,
|
|
291
|
-
projectId,
|
|
292
|
-
serverUrl,
|
|
293
|
-
// Browser-tab title only (the in-page heading is `shellConfig.ui.title`,
|
|
294
|
-
// shared across screens) — surface the provider's display name here for the
|
|
295
|
-
// credential branch instead of dropping it entirely.
|
|
296
|
-
pageTitle: credential
|
|
297
|
-
? `Sign in to ${credential.provider.displayName}`
|
|
298
|
-
: "Permission Request",
|
|
299
|
-
csrfToken,
|
|
300
|
-
nativeScopeSelection: !!info.nativeHttp,
|
|
301
|
-
...(info.nativeHttp ? { requestExpiresAt: info.expiresAt } : {}),
|
|
302
|
-
...(oauth
|
|
303
|
-
? {
|
|
304
|
-
authMode: oauth.complete ? "consent-only" : "oauth",
|
|
305
|
-
provider: oauth.provider,
|
|
306
|
-
oauthUrl: oauth.oauthUrl,
|
|
307
|
-
oauthProviderType: "oauth",
|
|
308
|
-
oauthProviderName: oauth.provider,
|
|
309
|
-
}
|
|
310
|
-
: {}),
|
|
311
|
-
capabilities: info.nativeHttp
|
|
312
|
-
? nativeCapabilitiesForScopes(catalog, info.requiredScopes)
|
|
313
|
-
: catalog,
|
|
314
|
-
// Native HTTP proves the holder key, not an external provider identity.
|
|
315
|
-
// Static configuration must not label that anonymous holder as a verified
|
|
316
|
-
// agent vendor. Legacy MCP presentation keeps its existing metadata.
|
|
317
|
-
agentMetadata: info.nativeHttp ? undefined : consentConfig.agentMetadata,
|
|
318
|
-
consentTheme: consentConfig.theme,
|
|
319
|
-
headlineVerb: consentConfig.headlineVerb,
|
|
320
|
-
revocationPath: consentConfig.revocationPath,
|
|
321
|
-
inactivityDays: consentConfig.inactivityDays,
|
|
322
|
-
...(credential
|
|
323
|
-
? {
|
|
324
|
-
authMode: "credentials",
|
|
325
|
-
provider: credential.provider.providerId,
|
|
326
|
-
authorizationType: "password",
|
|
327
|
-
}
|
|
328
|
-
: {}),
|
|
329
|
-
};
|
|
330
|
-
return generateConsentShell(shellOptions);
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* Resolve the worker's own origin for the shell's `serverUrl` — the same-origin
|
|
334
|
-
* target the `@kya-os/consent` Lit component POSTs its approve request to.
|
|
335
|
-
*
|
|
336
|
-
* Resolution order:
|
|
337
|
-
* 1. The pinned branded `realm` host (a project config value, e.g.
|
|
338
|
-
* `consent.acme.com`) when set — returns `https://${realm}` so the sign-in
|
|
339
|
-
* shell and its approve POST stay on the branded host instead of bouncing to
|
|
340
|
-
* the raw `…kya-os.ai` origin. Because `realm` is a pinned config value (not
|
|
341
|
-
* a request-derived Host), this does NOT reintroduce Host-reflection.
|
|
342
|
-
* 2. The explicit `MCP_SERVER_URL` env var (matches `consent.service.ts`'s own
|
|
343
|
-
* resolution).
|
|
344
|
-
* 3. The incoming request's origin (last-resort fallback).
|
|
345
|
-
*
|
|
346
|
-
* `realm` is intentionally trimmed; an empty/whitespace-only value falls through.
|
|
347
|
-
*/
|
|
348
|
-
export function resolveServerUrl(env, c, realm) {
|
|
349
|
-
const pinned = typeof realm === "string" ? realm.trim() : "";
|
|
350
|
-
if (pinned)
|
|
351
|
-
return `https://${pinned}`;
|
|
352
|
-
const configured = env.MCP_SERVER_URL;
|
|
353
|
-
if (configured && configured !== "null" && configured.startsWith("http")) {
|
|
354
|
-
return configured;
|
|
355
|
-
}
|
|
356
|
-
const raw = c.req?.raw;
|
|
357
|
-
if (raw) {
|
|
358
|
-
try {
|
|
359
|
-
return new URL(raw.url).origin;
|
|
360
|
-
}
|
|
361
|
-
catch {
|
|
362
|
-
// Fall through to empty string (relative fetch — resolves against the
|
|
363
|
-
// page's own origin in a real browser).
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
return "";
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* Resolve an explicit anchor `sid` from the query or body. Older anchor forms
|
|
370
|
-
* submit only `session_id`; recognize those only by the original kya namespace.
|
|
371
|
-
* An ordinary legacy UUID must not select the HTTP handler merely because it
|
|
372
|
-
* also meets the opaque HTTP ID syntax. The selected handler still validates
|
|
373
|
-
* CSRF and persisted anchor state before granting any authority.
|
|
374
|
-
*
|
|
375
|
-
* Peeks the body via `clone()` so the ORIGINAL request stream is never consumed
|
|
376
|
-
* here — `readBodyFields` still performs the one real body read, downstream in
|
|
377
|
-
* `handleAnchorConsentApprove`. `register.ts` calls this BEFORE routing so a
|
|
378
|
-
* flag-off or non-anchor `/consent/approve` POST falls through to `next()` with
|
|
379
|
-
* its body untouched (only a clone was ever read).
|
|
380
|
-
*/
|
|
381
|
-
export async function resolveApproveSid(c) {
|
|
382
|
-
const query = c.req.query("sid");
|
|
383
|
-
if (isAnchorSid(query))
|
|
384
|
-
return query;
|
|
385
|
-
const raw = c.req?.raw;
|
|
386
|
-
if (!raw)
|
|
387
|
-
return undefined;
|
|
388
|
-
try {
|
|
389
|
-
const contentType = raw.headers.get("Content-Type") || "";
|
|
390
|
-
const clone = raw.clone();
|
|
391
|
-
let explicitSid;
|
|
392
|
-
let sessionId;
|
|
393
|
-
if (contentType.includes("application/json")) {
|
|
394
|
-
const body = (await clone.json());
|
|
395
|
-
explicitSid = body.sid;
|
|
396
|
-
sessionId = body.session_id;
|
|
397
|
-
}
|
|
398
|
-
else {
|
|
399
|
-
const form = await clone.formData();
|
|
400
|
-
explicitSid = form.get("sid");
|
|
401
|
-
sessionId = form.get("session_id");
|
|
402
|
-
}
|
|
403
|
-
if (explicitSid != null) {
|
|
404
|
-
return typeof explicitSid === "string" && isAnchorSid(explicitSid)
|
|
405
|
-
? explicitSid
|
|
406
|
-
: undefined;
|
|
407
|
-
}
|
|
408
|
-
return isNamespacedAnchorSid(sessionId) ? sessionId : undefined;
|
|
409
|
-
}
|
|
410
|
-
catch {
|
|
411
|
-
return undefined;
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
// ── CSRF (mirrors consent.service's HMAC token format, bound to the anchor sid) ──
|
|
415
|
-
/** Base64url-encode bytes without padding. */
|
|
416
|
-
function base64UrlEncodeBytes(bytes) {
|
|
417
|
-
return btoa(String.fromCharCode(...bytes))
|
|
418
|
-
.replace(/\+/g, "-")
|
|
419
|
-
.replace(/\//g, "_")
|
|
420
|
-
.replace(/=/g, "");
|
|
421
|
-
}
|
|
422
|
-
/** Base64url-encode a UTF-8 string without padding. */
|
|
423
|
-
function base64UrlEncodeString(value) {
|
|
424
|
-
return base64UrlEncodeBytes(new TextEncoder().encode(value));
|
|
425
|
-
}
|
|
426
|
-
/** Base64url-decode to a UTF-8 string (re-adding the stripped `=` padding for atob). */
|
|
427
|
-
function base64UrlDecodeString(value) {
|
|
428
|
-
const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
429
|
-
return atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
|
|
430
|
-
}
|
|
431
|
-
/**
|
|
432
|
-
* Compute the domain-separated CSRF HMAC (`csrf:<secret>` key material), matching
|
|
433
|
-
* `consent.service.ts` so the two never collide on the same secret.
|
|
434
|
-
*/
|
|
435
|
-
async function computeCsrfHmac(secret, data) {
|
|
436
|
-
const encoder = new TextEncoder();
|
|
437
|
-
const key = await crypto.subtle.importKey("raw", encoder.encode(`csrf:${secret}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
438
|
-
return crypto.subtle.sign("HMAC", key, encoder.encode(data));
|
|
439
|
-
}
|
|
440
|
-
/** Constant-time string comparison to avoid CSRF token timing oracles. */
|
|
441
|
-
function constantTimeEqual(a, b) {
|
|
442
|
-
if (a.length !== b.length)
|
|
443
|
-
return false;
|
|
444
|
-
let diff = 0;
|
|
445
|
-
for (let i = 0; i < a.length; i++) {
|
|
446
|
-
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
447
|
-
}
|
|
448
|
-
return diff === 0;
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* Mint a CSRF token bound to the anchor `sid`: `${hmacB64}.${payloadB64}` over
|
|
452
|
-
* `{ sid, exp }`. Returns a non-validating random token when no secret is configured
|
|
453
|
-
* (graceful degradation — the form still renders).
|
|
454
|
-
*/
|
|
455
|
-
async function mintCsrfToken(env, sid) {
|
|
456
|
-
const secret = env.OAUTH_ENCRYPTION_SECRET;
|
|
457
|
-
if (!secret) {
|
|
458
|
-
return base64UrlEncodeBytes(crypto.getRandomValues(new Uint8Array(32)));
|
|
459
|
-
}
|
|
460
|
-
const exp = Math.floor(Date.now() / 1000) + 600;
|
|
461
|
-
const payloadB64 = base64UrlEncodeString(JSON.stringify({ sid, exp }));
|
|
462
|
-
const hmacB64 = base64UrlEncodeBytes(new Uint8Array(await computeCsrfHmac(secret, payloadB64)));
|
|
463
|
-
return `${hmacB64}.${payloadB64}`;
|
|
464
|
-
}
|
|
465
|
-
/** Validate a CSRF token against the anchor `sid` (HMAC + `sid` binding + expiry). */
|
|
466
|
-
async function validateCsrfToken(env, sid, token) {
|
|
467
|
-
if (!token)
|
|
468
|
-
return false;
|
|
469
|
-
const secret = env.OAUTH_ENCRYPTION_SECRET;
|
|
470
|
-
if (!secret) {
|
|
471
|
-
// Fail CLOSED: with no secret we cannot validate the double-submit token, so an
|
|
472
|
-
// anchor consent-approve POST on this state-changing endpoint must be rejected.
|
|
473
|
-
// (Inheriting consent.service's legacy "graceful degradation to no-CSRF" is not
|
|
474
|
-
// acceptable on this new surface.) Set OAUTH_ENCRYPTION_SECRET, or use
|
|
475
|
-
// MCPI_TEST_CONSENT in an explicit development environment for local testing.
|
|
476
|
-
console.warn("[kya-http] CSRF capability unavailable; rejecting consent approval");
|
|
477
|
-
return false;
|
|
478
|
-
}
|
|
479
|
-
const dot = token.indexOf(".");
|
|
480
|
-
if (dot === -1)
|
|
481
|
-
return false;
|
|
482
|
-
const hmacB64 = token.substring(0, dot);
|
|
483
|
-
const payloadB64 = token.substring(dot + 1);
|
|
484
|
-
try {
|
|
485
|
-
const payload = JSON.parse(base64UrlDecodeString(payloadB64));
|
|
486
|
-
if (payload.sid !== sid)
|
|
487
|
-
return false;
|
|
488
|
-
if (typeof payload.exp === "number" &&
|
|
489
|
-
payload.exp < Math.floor(Date.now() / 1000)) {
|
|
490
|
-
return false;
|
|
491
|
-
}
|
|
492
|
-
const expectedB64 = base64UrlEncodeBytes(new Uint8Array(await computeCsrfHmac(secret, payloadB64)));
|
|
493
|
-
return constantTimeEqual(hmacB64, expectedB64);
|
|
494
|
-
}
|
|
495
|
-
catch {
|
|
496
|
-
return false;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
/**
|
|
500
|
-
* Whether CSRF is relaxed for local/miniflare testing. Requires BOTH
|
|
501
|
-
* `MCPI_TEST_CONSENT === "true"` AND an explicit development environment (W3): the
|
|
502
|
-
* flag alone must NEVER disable CSRF on a production/default deployment.
|
|
503
|
-
*/
|
|
504
|
-
function isTestConsentMode(env) {
|
|
505
|
-
// `MCPI_TEST_CONSENT` / `ENVIRONMENT` are deploy-time vars not declared on the
|
|
506
|
-
// strict CloudflareEnv interface (mirrors config.ts reading `MCPI_HTTP_CHALLENGE`).
|
|
507
|
-
const bag = env;
|
|
508
|
-
if (String(bag.MCPI_TEST_CONSENT) !== "true")
|
|
509
|
-
return false;
|
|
510
|
-
// Fail closed: only an explicit development environment may relax CSRF. Production,
|
|
511
|
-
// staging, unset, and empty all keep CSRF enforced.
|
|
512
|
-
const environment = String(bag.ENVIRONMENT ?? bag.MCPI_ENV ?? "").toLowerCase();
|
|
513
|
-
return environment === "development";
|
|
514
|
-
}
|
|
515
|
-
// ── VC-JWT minting (same primitive chain as consent.service.issueDelegationVC) ──
|
|
516
|
-
/**
|
|
517
|
-
* draft-kya-http-02 §4.3 claims for a CROSS-RESOURCE delegation. An anchor
|
|
518
|
-
* registered by an external PEP carries the resource org's DID; the minted
|
|
519
|
-
* VC-JWT must then present exactly what checkpoint's claim gate
|
|
520
|
-
* (`delegation-claims.ts` `checkDelegationClaims`) pins:
|
|
521
|
-
* - `aud` === the resource org's DID (`kyaos/audience-mismatch` otherwise) —
|
|
522
|
-
* the ORG, not the resource URL: scope remains the per-resource boundary,
|
|
523
|
-
* and per-resource audience would require rewriting the verifier's
|
|
524
|
-
* audience/trust model;
|
|
525
|
-
* - `sid` — the anchor sid, required non-empty (`kyaos/session-mismatch`);
|
|
526
|
-
* - `server_did` — the challenged resource's DID, attribution only (nothing
|
|
527
|
-
* verifies it today; it gives audit trails a per-resource record and a
|
|
528
|
-
* re-mint-free path to tighten audience later).
|
|
529
|
-
*
|
|
530
|
-
* A SELF-ISSUED anchor has no `audience`, so this returns the unsigned parts'
|
|
531
|
-
* original `signingInput` untouched — the self-gating VC-JWT stays
|
|
532
|
-
* byte-identical (the regression guard). `encodedHeader` is reused verbatim so
|
|
533
|
-
* the only re-encoded segment is the payload actually being extended (via this
|
|
534
|
-
* module's own base64url helper — the CSRF token codec below).
|
|
535
|
-
*/
|
|
536
|
-
function withCrossResourceClaims(unsigned, info, sid) {
|
|
537
|
-
if (!info.audience)
|
|
538
|
-
return unsigned.signingInput;
|
|
539
|
-
const payload = {
|
|
540
|
-
...unsigned.payload,
|
|
541
|
-
aud: info.audience,
|
|
542
|
-
sid,
|
|
543
|
-
...(info.serverDid ? { server_did: info.serverDid } : {}),
|
|
544
|
-
};
|
|
545
|
-
return `${unsigned.encodedHeader}.${base64UrlEncodeString(JSON.stringify(payload))}`;
|
|
546
|
-
}
|
|
547
|
-
/**
|
|
548
|
-
* Mint a delegation VC-JWT for an approved anchor, wrap it as a VC, and sign it —
|
|
549
|
-
* the primitive chain `consent.service.ts` uses, called here directly (the service
|
|
550
|
-
* is a hot file and is never edited).
|
|
551
|
-
*
|
|
552
|
-
* Issuer identity: prefers the deployment's own configured identity
|
|
553
|
-
* (`MCP_IDENTITY_AGENT_DID` / `MCP_IDENTITY_PRIVATE_KEY` / `MCP_IDENTITY_PUBLIC_KEY`
|
|
554
|
-
* — the same Ed25519 keypair every deployment is provisioned with at deploy time),
|
|
555
|
-
* so the credential is signed by a stable, resolvable DID another PEP could pre-
|
|
556
|
-
* register as trusted — not a fresh ephemeral `did:key` per approval that only this
|
|
557
|
-
* worker's own anchor-based self-trust can ever make sense of. A deployment with no
|
|
558
|
-
* configured identity (predates identity provisioning, or was never redeployed with
|
|
559
|
-
* one) falls back to today's ephemeral generation unchanged.
|
|
560
|
-
*
|
|
561
|
-
* A deployment whose configured identity is PRESENT BUT INCONSISTENT (the three
|
|
562
|
-
* vars do not describe one key pair) does NOT get the ephemeral fallback:
|
|
563
|
-
* `getConfiguredIdentity` throws, the approve handler's mint catch turns that into
|
|
564
|
-
* a 500 that parks nothing, and the worker log names the mismatched pair. Minting
|
|
565
|
-
* anyway, with either the mismatched key or a fresh did:key, would hide a
|
|
566
|
-
* misprovisioned identity behind a credential no relying party can verify.
|
|
567
|
-
*
|
|
568
|
-
* `authorizedUser` (credential path only): the merchant-authenticated shopper the
|
|
569
|
-
* approve handler resolved BEFORE minting. When present, the shopper's identity is
|
|
570
|
-
* bound into the credential itself — `credentialSubject.delegation.userDid` /
|
|
571
|
-
* `.userIdentifier` / `.metadata.provenance` — not just the fire-and-forget
|
|
572
|
-
* dashboard notify. Without it, a merchant-signed-in mint verified fine but
|
|
573
|
-
* carried no user claims, so the merchant site's DelegationHolder was null and
|
|
574
|
-
* identity-keyed actions were refused. Absent (consent-only anchors), the mint
|
|
575
|
-
* stays anonymous and omits all three claims exactly as before.
|
|
576
|
-
*/
|
|
577
|
-
async function mintDelegationVcJwt(env, sid, info, expiresInS, authorizedUser, native, termsAccepted = false) {
|
|
578
|
-
if (info.nativeHttp && native?.remoteIssuer) {
|
|
579
|
-
if (info.nativeIssuerDid !== native.issuerDid ||
|
|
580
|
-
!info.holderKeyId ||
|
|
581
|
-
!info.audience ||
|
|
582
|
-
!authorizedUser?.userDid ||
|
|
583
|
-
!info.nativePolicyRevision?.policyId ||
|
|
584
|
-
!/^[0-9a-f]{64}$/.test(info.nativePolicyRevision.composedPolicyHash ?? ""))
|
|
585
|
-
throw new Error("Native issuance prerequisites unavailable");
|
|
586
|
-
return native.remoteIssuer.issueDelegation({
|
|
587
|
-
session_id: sid,
|
|
588
|
-
holder_keyid: info.holderKeyId,
|
|
589
|
-
user_did: authorizedUser.userDid,
|
|
590
|
-
required_scopes: info.requiredScopes,
|
|
591
|
-
audience: info.audience,
|
|
592
|
-
policy_id: info.nativePolicyRevision.policyId,
|
|
593
|
-
composed_blob_hash: info.nativePolicyRevision.composedPolicyHash,
|
|
594
|
-
terms_accepted: termsAccepted,
|
|
595
|
-
amr: authorizedUser.amr ?? ["pwd"],
|
|
596
|
-
});
|
|
597
|
-
}
|
|
598
|
-
const cryptoProvider = new WebCryptoProvider();
|
|
599
|
-
// Throws ConfiguredIdentityError on an inconsistent triple. See the doc
|
|
600
|
-
// comment above; the caller's mint catch is the intended failure path.
|
|
601
|
-
const configuredIdentity = await getConfiguredIdentity(env);
|
|
602
|
-
if (info.nativeHttp &&
|
|
603
|
-
(!configuredIdentity ||
|
|
604
|
-
!native ||
|
|
605
|
-
configuredIdentity.did !== info.nativeIssuerDid ||
|
|
606
|
-
configuredIdentity.did !== native.issuerDid ||
|
|
607
|
-
!info.holderKeyId ||
|
|
608
|
-
!info.audience ||
|
|
609
|
-
!authorizedUser?.userDid ||
|
|
610
|
-
typeof native.issueCredentialStatus !== "function"))
|
|
611
|
-
throw new Error("Native issuance prerequisites unavailable");
|
|
612
|
-
let issuerDid;
|
|
613
|
-
let keyId;
|
|
614
|
-
let signingPrivateKey;
|
|
615
|
-
if (configuredIdentity) {
|
|
616
|
-
issuerDid = configuredIdentity.did;
|
|
617
|
-
keyId = configuredIdentity.kid;
|
|
618
|
-
signingPrivateKey = configuredIdentity.privateKey;
|
|
619
|
-
}
|
|
620
|
-
else {
|
|
621
|
-
const rawKeyPair = await cryptoProvider.generateKeyPair();
|
|
622
|
-
issuerDid = generateDidKeyFromBase64(rawKeyPair.publicKey);
|
|
623
|
-
keyId = `${issuerDid}#${didKeyFragment(issuerDid)}`;
|
|
624
|
-
signingPrivateKey = rawKeyPair.privateKey;
|
|
625
|
-
}
|
|
626
|
-
// Subject (the agent the delegation is granted to). An externally-registered
|
|
627
|
-
// anchor carries the registering PEP's agent DID (verified `detected_agent_did`
|
|
628
|
-
// when present, else the session `agent_did` — possibly the anonymous-principal
|
|
629
|
-
// sentinel); a self-issued anchor does not, so fall back to the worker's
|
|
630
|
-
// configured agent DID when present (the same value as the issuer when an
|
|
631
|
-
// identity is configured, and an independent ephemeral holder DID when it
|
|
632
|
-
// isn't — both were already true of the subject's own fallback before this).
|
|
633
|
-
const binding = info.nativeHttp
|
|
634
|
-
? await nativeHolderBinding(info.holderKeyId)
|
|
635
|
-
: undefined;
|
|
636
|
-
const agentDid = binding?.did || info.agentDid || env.MCP_IDENTITY_AGENT_DID || issuerDid;
|
|
637
|
-
const nowS = Math.floor(Date.now() / 1000);
|
|
638
|
-
const delegation = {
|
|
639
|
-
id: `urn:uuid:${sid}`,
|
|
640
|
-
issuerDid,
|
|
641
|
-
subjectDid: agentDid,
|
|
642
|
-
vcId: `urn:uuid:${sid}`,
|
|
643
|
-
constraints: {
|
|
644
|
-
scopes: info.requiredScopes,
|
|
645
|
-
notBefore: nowS,
|
|
646
|
-
notAfter: nowS + expiresInS,
|
|
647
|
-
// §11.7 outer===inner audience invariant (checkpoint's own mints bind the
|
|
648
|
-
// audience in BOTH the JWT aud and constraints.audience): set the inner
|
|
649
|
-
// half for cross-resource anchors so verifiers reading either slot agree.
|
|
650
|
-
...(info.audience ? { audience: info.audience } : {}),
|
|
651
|
-
},
|
|
652
|
-
signature: "",
|
|
653
|
-
status: "active",
|
|
654
|
-
createdAt: nowS,
|
|
655
|
-
// `wrapDelegationAsVC` has no provenance option, so provenance rides in the
|
|
656
|
-
// delegation record's metadata — the same convention checkpoint's own
|
|
657
|
-
// gateway mint uses — and passes through into
|
|
658
|
-
// `credentialSubject.delegation.metadata` verbatim. `oauth_client_derived`
|
|
659
|
-
// is the AGENT_IDENTITY_PROVENANCE value checkpoint's merchant-credential
|
|
660
|
-
// consent path records for a credential-provider-verified sign-in.
|
|
661
|
-
...(authorizedUser
|
|
662
|
-
? { metadata: { provenance: "oauth_client_derived" } }
|
|
663
|
-
: {}),
|
|
664
|
-
};
|
|
665
|
-
const unsignedVC = wrapDelegationAsVC(delegation, {
|
|
666
|
-
id: `urn:uuid:${sid}`,
|
|
667
|
-
issuanceDate: new Date().toISOString(),
|
|
668
|
-
// Bind the authenticated shopper into the credential itself.
|
|
669
|
-
// `wrapDelegationAsVC` conditionally spreads both claims into
|
|
670
|
-
// `credentialSubject.delegation`, so an anonymous (consent-only) mint omits
|
|
671
|
-
// them exactly as before. `userEmail ?? userId` matches checkpoint's
|
|
672
|
-
// userIdentifier convention.
|
|
673
|
-
userDid: authorizedUser?.userDid,
|
|
674
|
-
userIdentifier: authorizedUser?.userEmail ?? authorizedUser?.userId,
|
|
675
|
-
});
|
|
676
|
-
const credentialStatus = info.nativeHttp
|
|
677
|
-
? await native.issueCredentialStatus({
|
|
678
|
-
sid,
|
|
679
|
-
issuerDid,
|
|
680
|
-
audience: info.audience,
|
|
681
|
-
holderDid: agentDid,
|
|
682
|
-
expiresAtUnix: nowS + expiresInS,
|
|
683
|
-
userDid: authorizedUser.userDid,
|
|
684
|
-
requiredScopes: info.requiredScopes,
|
|
685
|
-
policyRevision: info.nativePolicyRevision,
|
|
686
|
-
})
|
|
687
|
-
: undefined;
|
|
688
|
-
if (info.nativeHttp && !validNativeStatus(credentialStatus))
|
|
689
|
-
throw new Error("Native status allocation failed");
|
|
690
|
-
const vcWithIssuer = {
|
|
691
|
-
...unsignedVC,
|
|
692
|
-
issuer: issuerDid,
|
|
693
|
-
...(credentialStatus ? { credentialStatus } : {}),
|
|
694
|
-
};
|
|
695
|
-
const unsigned = createUnsignedVCJWT(vcWithIssuer, { keyId });
|
|
696
|
-
// Cross-resource anchors extend the payload (aud/sid/server_did) BEFORE
|
|
697
|
-
// signing; self-issued anchors sign the original input, byte-identical.
|
|
698
|
-
let signingInput = withCrossResourceClaims(unsigned, info, sid);
|
|
699
|
-
if (binding) {
|
|
700
|
-
// The pin's verified public key, never a form field, owns the credential.
|
|
701
|
-
const payload = {
|
|
702
|
-
...unsigned.payload,
|
|
703
|
-
aud: info.audience,
|
|
704
|
-
sid,
|
|
705
|
-
assurance: "key-bound",
|
|
706
|
-
cnf: { jkt: binding.jkt },
|
|
707
|
-
iat: nowS,
|
|
708
|
-
nbf: nowS,
|
|
709
|
-
exp: nowS + expiresInS,
|
|
710
|
-
type: ["VerifiableCredential", "DelegationCredential"],
|
|
711
|
-
scope: info.requiredScopes,
|
|
712
|
-
amr: authorizedUser?.amr ?? ["pwd"],
|
|
713
|
-
credentialStatus,
|
|
714
|
-
policy_revision: {
|
|
715
|
-
policy_id: info.nativePolicyRevision?.policyId,
|
|
716
|
-
composed_blob_hash: info.nativePolicyRevision?.composedPolicyHash,
|
|
717
|
-
},
|
|
718
|
-
...(info.serverDid ? { server_did: info.serverDid } : {}),
|
|
719
|
-
};
|
|
720
|
-
signingInput = `${unsigned.encodedHeader}.${base64UrlEncodeString(JSON.stringify(payload))}`;
|
|
721
|
-
}
|
|
722
|
-
const signatureBytes = await cryptoProvider.sign(new TextEncoder().encode(signingInput), signingPrivateKey);
|
|
723
|
-
const signature = base64urlEncodeFromBytes(signatureBytes);
|
|
724
|
-
// Return the resolved subject alongside the JWT so the notify report sends the
|
|
725
|
-
// SAME DID the VC carries (never an empty `agent_did`, which mismatches the VC
|
|
726
|
-
// and fails checkpoint's notify schema).
|
|
727
|
-
return {
|
|
728
|
-
vcJwt: completeVCJWT(signingInput, signature),
|
|
729
|
-
subjectDid: agentDid,
|
|
730
|
-
expiresAtUnix: nowS + expiresInS,
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
// ── Public handlers ──────────────────────────────────────────────────────────
|
|
734
|
-
/**
|
|
735
|
-
* Render the anchor consent surface for `GET /consent?sid=kya-…`.
|
|
736
|
-
*/
|
|
737
|
-
export async function handleAnchorConsentGet(c, sid, env, cfg) {
|
|
738
|
-
const statusOnly = c.req.query("view") === "preparation";
|
|
739
|
-
const recovery = async (state, status) => statusOnly
|
|
740
|
-
? preparationStatus(state, status)
|
|
741
|
-
: consentPreparationPage({
|
|
742
|
-
sid,
|
|
743
|
-
expiresIn: 0,
|
|
744
|
-
scopes: [],
|
|
745
|
-
terminalState: state,
|
|
746
|
-
status,
|
|
747
|
-
branding: await preparationBranding(env),
|
|
748
|
-
});
|
|
749
|
-
let infoResponse;
|
|
750
|
-
try {
|
|
751
|
-
infoResponse = await callAnchor(env, sid, INTERNAL_PICKUP_INFO, { sid });
|
|
752
|
-
}
|
|
753
|
-
catch {
|
|
754
|
-
return recovery("unavailable", 502);
|
|
755
|
-
}
|
|
756
|
-
if (infoResponse.status === 404)
|
|
757
|
-
return recovery("not_found", 404);
|
|
758
|
-
if (infoResponse.status === 410)
|
|
759
|
-
return recovery("expired", 410);
|
|
760
|
-
if (!infoResponse.ok) {
|
|
761
|
-
return recovery("unavailable", 502);
|
|
762
|
-
}
|
|
763
|
-
let info;
|
|
764
|
-
try {
|
|
765
|
-
info = (await infoResponse.json());
|
|
766
|
-
}
|
|
767
|
-
catch {
|
|
768
|
-
return recovery("unavailable", 502);
|
|
769
|
-
}
|
|
770
|
-
if (!info ||
|
|
771
|
-
!Number.isFinite(info.expiresAt) ||
|
|
772
|
-
!["pending", "pinned", "approved"].includes(info.status))
|
|
773
|
-
return recovery("unavailable", 502);
|
|
774
|
-
if (info.nativeHttp &&
|
|
775
|
-
(!cfg.native || info.nativeIssuerDid !== cfg.native.issuerDid))
|
|
776
|
-
return recovery("unavailable", 503);
|
|
777
|
-
if (info.nativeHttp && Date.now() >= info.expiresAt)
|
|
778
|
-
return recovery("expired", 410);
|
|
779
|
-
if (info.nativeHttp && (!info.holderKeyId || info.status === "pending")) {
|
|
780
|
-
if (statusOnly)
|
|
781
|
-
return preparationStatus("preparation_required", 200, info.expiresAt);
|
|
782
|
-
const branding = await preparationBranding(env);
|
|
783
|
-
return consentPreparationPage({
|
|
784
|
-
sid,
|
|
785
|
-
branding,
|
|
786
|
-
scopes: info.requiredScopes,
|
|
787
|
-
expiresIn: Math.max(0, Math.floor((info.expiresAt - Date.now()) / 1000)),
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
|
-
if (info.nativeHttp) {
|
|
791
|
-
try {
|
|
792
|
-
// Registration may name an anonymous detector principal. Human consent
|
|
793
|
-
// must display the proved pickup holder that will receive this grant.
|
|
794
|
-
info.agentDid = (await nativeHolderBinding(info.holderKeyId)).did;
|
|
795
|
-
}
|
|
796
|
-
catch {
|
|
797
|
-
return recovery("unavailable", 503);
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
// Approval is terminal for the consent UI, even after the holder has picked up
|
|
801
|
-
// its grant. Reopening this link must not create CSRF/OAuth state or start a
|
|
802
|
-
// second sign-in: native OAuth intentionally accepts only a pinned anchor.
|
|
803
|
-
if (info.nativeHttp && info.status === "approved") {
|
|
804
|
-
return statusOnly
|
|
805
|
-
? preparationStatus("completed", 200, info.expiresAt)
|
|
806
|
-
: consentPreparationPage({
|
|
807
|
-
sid,
|
|
808
|
-
expiresIn: 0,
|
|
809
|
-
scopes: [],
|
|
810
|
-
terminalState: "completed",
|
|
811
|
-
status: 200,
|
|
812
|
-
branding: await preparationBranding(env),
|
|
813
|
-
});
|
|
814
|
-
}
|
|
815
|
-
// A read-only UI check does not mint CSRF/OAuth state, pin a key, approve,
|
|
816
|
-
// or retrieve a delegation. Navigation rechecks the same anchor before login.
|
|
817
|
-
if (statusOnly) {
|
|
818
|
-
if (!info.nativeHttp)
|
|
819
|
-
return preparationStatus("unavailable", 404);
|
|
820
|
-
return preparationStatus("approval_ready", 200, info.expiresAt);
|
|
821
|
-
}
|
|
822
|
-
const csrfToken = await mintCsrfToken(env, sid);
|
|
823
|
-
const projectId = env.CHECKPOINT_PROJECT_ID || "";
|
|
824
|
-
const consentConfig = await new ConsentConfigService(env).getConsentConfig(projectId);
|
|
825
|
-
const serverUrl = resolveServerUrl(env, c, cfg.realm);
|
|
826
|
-
// When the project protects these scopes with a credential provider (merchant
|
|
827
|
-
// sign-in), render the branded sign-in form instead of the bare "Allow" form —
|
|
828
|
-
// so the shopper authenticates before authorizing and the minted delegation is
|
|
829
|
-
// bound to their identity. Falls back to consent-only when there is no such
|
|
830
|
-
// provider (resolution failed, or no checkpoint link), preserving today's
|
|
831
|
-
// behavior exactly.
|
|
832
|
-
const resolution = await resolveAnchorCredentialProvider(env, info.requiredScopes, { respectConfiguredProvider: !!info.nativeHttp });
|
|
833
|
-
if (resolution.status === "credential") {
|
|
834
|
-
return htmlResponse(renderAnchorConsentShell({
|
|
835
|
-
consentConfig,
|
|
836
|
-
info,
|
|
837
|
-
sid,
|
|
838
|
-
csrfToken,
|
|
839
|
-
serverUrl,
|
|
840
|
-
projectId,
|
|
841
|
-
credential: { provider: resolution.provider },
|
|
842
|
-
}), 200);
|
|
843
|
-
}
|
|
844
|
-
if (info.nativeHttp && cfg.native && resolution.status === "none") {
|
|
845
|
-
try {
|
|
846
|
-
// The mode is only presentation. Approval always requires the signed
|
|
847
|
-
// fragment assertion; query flags never establish a human identity.
|
|
848
|
-
const complete = c.req.query("mode") === "consent-only";
|
|
849
|
-
const oauth = await beginNativeOAuth(env, sid, info, cfg.native, !complete);
|
|
850
|
-
if (!oauth)
|
|
851
|
-
return nativeUnavailable();
|
|
852
|
-
return htmlResponse(renderAnchorConsentShell({
|
|
853
|
-
consentConfig,
|
|
854
|
-
info,
|
|
855
|
-
sid,
|
|
856
|
-
csrfToken,
|
|
857
|
-
serverUrl: cfg.native.authorizationOrigin,
|
|
858
|
-
projectId,
|
|
859
|
-
oauth: { ...oauth, complete },
|
|
860
|
-
}), 200);
|
|
861
|
-
}
|
|
862
|
-
catch {
|
|
863
|
-
return nativeUnavailable();
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
// "none" and "unavailable" both render the consent-only form. On "unavailable"
|
|
867
|
-
// the approve POST re-resolves and FAILS CLOSED, so a form shown during a
|
|
868
|
-
// transient error can never lead to an anonymous mint for a credential project.
|
|
869
|
-
return htmlResponse(renderAnchorConsentShell({
|
|
870
|
-
consentConfig,
|
|
871
|
-
info,
|
|
872
|
-
sid,
|
|
873
|
-
csrfToken,
|
|
874
|
-
serverUrl,
|
|
875
|
-
projectId,
|
|
876
|
-
}), 200);
|
|
877
|
-
}
|
|
878
|
-
/**
|
|
879
|
-
* Handle anchor approval for `POST /consent/approve?sid=kya-…`. Mints a VC-JWT and
|
|
880
|
-
* parks it on the anchor; an expired/unknown anchor makes the approval FAIL.
|
|
881
|
-
*/
|
|
882
|
-
export async function handleAnchorConsentApprove(c, sid, env, cfg) {
|
|
883
|
-
// Read the POST body EXACTLY ONCE. The CSRF token and the credential fields
|
|
884
|
-
// both live in it; reading it twice (a second clone after CSRF) is unreliable
|
|
885
|
-
// across runtimes — the second read can throw and silently yield empty
|
|
886
|
-
// credentials, failing every sign-in. Extract everything from this one parse.
|
|
887
|
-
const bodyFields = await readBodyFields(c);
|
|
888
|
-
// CSRF, unless test mode relaxes it for miniflare POSTs.
|
|
889
|
-
if (!isTestConsentMode(env)) {
|
|
890
|
-
const valid = await validateCsrfToken(env, sid, bodyFields.csrf_token);
|
|
891
|
-
if (!valid) {
|
|
892
|
-
return rejectedFormResponse(env, sid);
|
|
893
|
-
}
|
|
894
|
-
}
|
|
895
|
-
// Read the anchor first: if it is already gone, fail BEFORE minting anything.
|
|
896
|
-
let infoResponse;
|
|
897
|
-
try {
|
|
898
|
-
infoResponse = await callAnchor(env, sid, INTERNAL_PICKUP_INFO, { sid });
|
|
899
|
-
}
|
|
900
|
-
catch {
|
|
901
|
-
return jsonResponse({
|
|
902
|
-
error_code: "kyaos/consent-request-unavailable",
|
|
903
|
-
error: "We couldn't check this approval request. Return to your assistant to check its status before trying again.",
|
|
904
|
-
}, 502);
|
|
905
|
-
}
|
|
906
|
-
if (infoResponse.status === 404)
|
|
907
|
-
return notFoundJson();
|
|
908
|
-
if (infoResponse.status === 410) {
|
|
909
|
-
return approvalFailedJson("This authorization request has expired. Nothing was authorized.");
|
|
910
|
-
}
|
|
911
|
-
if (!infoResponse.ok) {
|
|
912
|
-
return approvalFailedJson("This authorization request could not be loaded. Please start over.", 502);
|
|
913
|
-
}
|
|
914
|
-
const info = (await infoResponse.json());
|
|
915
|
-
if (info.nativeHttp &&
|
|
916
|
-
(!Number.isFinite(info.expiresAt) || info.expiresAt <= Date.now()))
|
|
917
|
-
return approvalFailedJson("This approval request has expired. Return to your assistant for a new approval link.");
|
|
918
|
-
if (info.nativeHttp && (!info.holderKeyId || info.status === "pending")) {
|
|
919
|
-
return approvalFailedJson(`${REQUEST_NOT_PREPARED.title}. ${REQUEST_NOT_PREPARED.body} ${REQUEST_NOT_PREPARED.nextStep} ${REQUEST_NOT_PREPARED.unsupported}`, 409);
|
|
920
|
-
}
|
|
921
|
-
if (info.nativeHttp &&
|
|
922
|
-
(!cfg.native || info.nativeIssuerDid !== cfg.native.issuerDid))
|
|
923
|
-
return nativeUnavailable();
|
|
924
|
-
let approvedScopes = info.requiredScopes;
|
|
925
|
-
if (info.nativeHttp) {
|
|
926
|
-
try {
|
|
927
|
-
const selected = JSON.parse(bodyFields.scopes ?? "null");
|
|
928
|
-
if (!Array.isArray(selected) ||
|
|
929
|
-
!selected.length ||
|
|
930
|
-
selected.length > info.requiredScopes.length ||
|
|
931
|
-
new Set(selected).size !== selected.length ||
|
|
932
|
-
!selected.every((scope) => typeof scope === "string" && info.requiredScopes.includes(scope)))
|
|
933
|
-
return jsonResponse({ error: "kyaos/scope-insufficient" }, 403);
|
|
934
|
-
approvedScopes = selected;
|
|
935
|
-
}
|
|
936
|
-
catch {
|
|
937
|
-
return jsonResponse({ error: "kyaos/scope-insufficient" }, 403);
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
// Credential path: when a credential provider protects these scopes, the
|
|
941
|
-
// shopper must sign in before we mint. Authenticate against the provider's own
|
|
942
|
-
// endpoint, then resolve the checkpoint user DID — both BEFORE minting, so a
|
|
943
|
-
// bad password parks nothing. `null` provider → consent-only (unchanged).
|
|
944
|
-
const resolution = await resolveAnchorCredentialProvider(env, info.requiredScopes, { respectConfiguredProvider: !!info.nativeHttp });
|
|
945
|
-
// Fail CLOSED when the sign-in requirement could not be determined (a
|
|
946
|
-
// checkpoint /providers error or ambiguous config). Falling through to a
|
|
947
|
-
// consent-only mint here would skip merchant sign-in for a credential-
|
|
948
|
-
// protected project on a transient error — the exact bypass we must prevent.
|
|
949
|
-
if (resolution.status === "unavailable") {
|
|
950
|
-
return approvalFailedJson("We could not verify the sign-in requirement for this request. Please try again.", 503);
|
|
951
|
-
}
|
|
952
|
-
const provider = resolution.status === "credential" ? resolution.provider : null;
|
|
953
|
-
let authorizedUser = null;
|
|
954
|
-
if (provider) {
|
|
955
|
-
// The @kya-os/consent Lit component always submits fixed `username` /
|
|
956
|
-
// `password` field names (see mcp-consent.ts `renderCredentials()`),
|
|
957
|
-
// regardless of the provider's own `requestBodyTemplate` placeholder names
|
|
958
|
-
// (e.g. `{{email}}`). Strip every meta field the shell's own
|
|
959
|
-
// `handleApprove()` can emit (session/routing metadata, never a credential)
|
|
960
|
-
// so a future provider `requestBodyTemplate` placeholder can never collide
|
|
961
|
-
// with it. This is NOT the same set `consent.service.ts`'s
|
|
962
|
-
// `handleCredentialApproval` destructures: that method also serves MCP
|
|
963
|
-
// inline-tool-call and OAuth-linked-clickwrap requests this anchor path
|
|
964
|
-
// never receives (`inline_mode`, `approved`), and has no `sid` (an
|
|
965
|
-
// anchor-only concept some external PEPs may still post in the body rather
|
|
966
|
-
// than the query). Pass everything else through as credentials;
|
|
967
|
-
// `credential-auth.handler.ts`'s own alias resolution
|
|
968
|
-
// (`resolveCredentialField`) maps `username`/`email`/`identifier`/… onto
|
|
969
|
-
// whatever the template actually needs.
|
|
970
|
-
const { sid: _sid, csrf_token: _csrfToken, tool: _tool, scopes: _scopes, agent_did: _agentDid, session_id: _sessionId, project_id: _projectId, provider: _providerField, provider_type: _providerType, auth_mode: _authMode, termsAccepted: _termsAccepted, credential_provider_type: _credentialProviderType, credential_provider: _credentialProvider, oauth_provider_type: _oauthProviderType, user_did: _userDid, identity_assertion: _identityAssertion, credential_user_email: _credentialUserEmail, credential_provider_user_id: _credentialProviderUserId, ...credentials } = bodyFields;
|
|
971
|
-
const handler = createCredentialAuthHandler({
|
|
972
|
-
fetch: (...args) => globalThis.fetch(...args),
|
|
973
|
-
logger: info.nativeHttp
|
|
974
|
-
? () => { }
|
|
975
|
-
: (msg, data) => console.debug(`[kya-http] ${msg}`, data),
|
|
976
|
-
});
|
|
977
|
-
const authResult = await handler.authenticate(provider.config, credentials);
|
|
978
|
-
if (!authResult.success) {
|
|
979
|
-
return jsonResponse(info.nativeHttp && authResult.authenticationRejected
|
|
980
|
-
? {
|
|
981
|
-
error_code: "kyaos/credentials-not-accepted",
|
|
982
|
-
error: "Those credentials were not accepted. Please check them and try again.",
|
|
983
|
-
}
|
|
984
|
-
: {
|
|
985
|
-
error: authResult.error ||
|
|
986
|
-
"Those credentials were not accepted. Please try again.",
|
|
987
|
-
}, 401);
|
|
988
|
-
}
|
|
989
|
-
const identity = await resolveCredentialIdentity(env, {
|
|
990
|
-
projectId: env.CHECKPOINT_PROJECT_ID || "",
|
|
991
|
-
provider: provider.providerId,
|
|
992
|
-
userId: authResult.userId || "unknown",
|
|
993
|
-
userEmail: authResult.userEmail,
|
|
994
|
-
userDisplayName: authResult.userDisplayName,
|
|
995
|
-
});
|
|
996
|
-
if (!identity.success || !identity.userDid) {
|
|
997
|
-
return approvalFailedJson("We signed you in but could not resolve your identity. Please start over.", 500);
|
|
998
|
-
}
|
|
999
|
-
authorizedUser = {
|
|
1000
|
-
userDid: identity.userDid,
|
|
1001
|
-
userId: authResult.userId,
|
|
1002
|
-
userEmail: authResult.userEmail,
|
|
1003
|
-
};
|
|
1004
|
-
}
|
|
1005
|
-
if (info.nativeHttp && cfg.native && !provider) {
|
|
1006
|
-
authorizedUser = await verifyNativeOAuthIdentity(env, sid, info, cfg.native, bodyFields.identity_assertion || "");
|
|
1007
|
-
}
|
|
1008
|
-
let vcJwt;
|
|
1009
|
-
let subjectDid;
|
|
1010
|
-
let expiresAtUnix;
|
|
1011
|
-
if (info.nativeHttp && !authorizedUser?.userDid) {
|
|
1012
|
-
return jsonResponse({
|
|
1013
|
-
error: "We couldn't verify this sign-in for the approval request. Return to your assistant for a fresh approval link.",
|
|
1014
|
-
error_code: "kyaos/session-mismatch",
|
|
1015
|
-
}, 401);
|
|
1016
|
-
}
|
|
1017
|
-
const expiresInS = info.nativeHttp ? 3600 : cfg.delegationExpiresInS;
|
|
1018
|
-
try {
|
|
1019
|
-
({ vcJwt, subjectDid, expiresAtUnix } = await mintDelegationVcJwt(env, sid, { ...info, requiredScopes: approvedScopes }, expiresInS,
|
|
1020
|
-
// Credential path only: carry the authenticated shopper's identity into
|
|
1021
|
-
// the minted VC itself (not just the dashboard notify below). `null`
|
|
1022
|
-
// (consent-only) leaves the mint anonymous, claims omitted as today.
|
|
1023
|
-
authorizedUser ?? undefined, cfg.native, bodyFields.termsAccepted === "true" || bodyFields.termsAccepted === "on"));
|
|
1024
|
-
}
|
|
1025
|
-
catch (error) {
|
|
1026
|
-
if (info.nativeHttp)
|
|
1027
|
-
return nativeUnavailable();
|
|
1028
|
-
// A mint failure (keygen/sign) must surface as a styled no-store error page, not
|
|
1029
|
-
// an unhandled throw that escapes to a bare 500 — and must park nothing (we fail
|
|
1030
|
-
// before the INTERNAL_PICKUP_APPROVE call below).
|
|
1031
|
-
console.warn(`[kya-http] delegation mint failed (sid=${sid}):`, error instanceof Error ? error.message : String(error));
|
|
1032
|
-
return approvalFailedJson("We could not complete the authorization. Please start over.", 500);
|
|
1033
|
-
}
|
|
1034
|
-
const approveResponse = await callAnchor(env, sid, INTERNAL_PICKUP_APPROVE, {
|
|
1035
|
-
sid,
|
|
1036
|
-
vcJwt,
|
|
1037
|
-
expiresInS,
|
|
1038
|
-
...(info.nativeHttp ? { expiresAtUnix } : {}),
|
|
1039
|
-
});
|
|
1040
|
-
// Consent on an EXPIRED (410) or unknown (404) anchor MUST fail and mint nothing
|
|
1041
|
-
// reachable — the minted JWT is never returned to the caller in that case.
|
|
1042
|
-
if (approveResponse.status === 410) {
|
|
1043
|
-
return approvalFailedJson(info.nativeHttp
|
|
1044
|
-
? "This authorization request expired before delivery completed. Please start a new request."
|
|
1045
|
-
: "This authorization request expired before it could be completed. Nothing was authorized.");
|
|
1046
|
-
}
|
|
1047
|
-
if (approveResponse.status === 404)
|
|
1048
|
-
return notFoundJson();
|
|
1049
|
-
if (info.nativeHttp && approveResponse.status === 409) {
|
|
1050
|
-
return approvalFailedJson("This request already has a different approval. Please start a new request.", 409);
|
|
1051
|
-
}
|
|
1052
|
-
if (!approveResponse.ok) {
|
|
1053
|
-
return approvalFailedJson("We could not complete the authorization. Please start over.", 502);
|
|
1054
|
-
}
|
|
1055
|
-
// A repeated approval keeps the first parked VC. Report its deadline, never
|
|
1056
|
-
// a newly minted timestamp, and never deliver a credential to the browser.
|
|
1057
|
-
let parkedExpiresAtUnix;
|
|
1058
|
-
if (info.nativeHttp) {
|
|
1059
|
-
const parked = (await approveResponse.json().catch(() => null));
|
|
1060
|
-
if (!Number.isSafeInteger(parked?.expiresAtUnix) ||
|
|
1061
|
-
parked?.expiresAtUnix !== expiresAtUnix ||
|
|
1062
|
-
parked.expiresAtUnix * 1000 <= Date.now() ||
|
|
1063
|
-
!Number.isSafeInteger(parked.expiresAtUnix * 1000))
|
|
1064
|
-
return nativeUnavailable();
|
|
1065
|
-
parkedExpiresAtUnix = parked.expiresAtUnix;
|
|
1066
|
-
}
|
|
1067
|
-
// Report the minted delegation to checkpoint so it appears in the dashboard,
|
|
1068
|
-
// attributed to the signed-in customer. Only the credential path has a
|
|
1069
|
-
// `user_did` (the notify schema requires one), so a consent-only anchor
|
|
1070
|
-
// reports nothing — there is no user to attribute it to.
|
|
1071
|
-
if (authorizedUser && provider && !cfg.native?.remoteIssuer) {
|
|
1072
|
-
// FIRE-AND-FORGET: dispatch the report but NEVER await it — the VC is already
|
|
1073
|
-
// parked and the shopper's approval must not hang on a slow/hung checkpoint.
|
|
1074
|
-
// `waitUntil` (when the runtime provides it) lets the report finish after the
|
|
1075
|
-
// success page is returned; `notifyDelegation` swallows its own errors.
|
|
1076
|
-
const report = notifyDelegation(env, {
|
|
1077
|
-
sid,
|
|
1078
|
-
agentDid: subjectDid,
|
|
1079
|
-
userDid: authorizedUser.userDid,
|
|
1080
|
-
userId: authorizedUser.userId,
|
|
1081
|
-
userIdentifier: authorizedUser.userEmail,
|
|
1082
|
-
scopes: info.requiredScopes,
|
|
1083
|
-
provider: provider.providerId,
|
|
1084
|
-
// Record the same expiry the VC was minted with, matching the OAuth path.
|
|
1085
|
-
expiresAt: new Date(Date.now() + expiresInS * 1000).toISOString(),
|
|
1086
|
-
});
|
|
1087
|
-
const execCtx = c.executionCtx;
|
|
1088
|
-
execCtx?.waitUntil?.(report);
|
|
1089
|
-
}
|
|
1090
|
-
return successJson(`urn:uuid:${sid}`, parkedExpiresAtUnix);
|
|
1091
|
-
}
|
|
1092
|
-
/**
|
|
1093
|
-
* Read every string field from the POST body ONCE via the underlying native
|
|
1094
|
-
* Request (`c.req.raw`), for both the CSRF token and the credential fields. Reads
|
|
1095
|
-
* `raw` directly (no clone) because it is consumed a single time — a second read
|
|
1096
|
-
* of the same body is unreliable across runtimes. The sid travels in the query,
|
|
1097
|
-
* so consuming the body here never interferes with route-order interception.
|
|
1098
|
-
* Returns an empty object on parse failure.
|
|
1099
|
-
*/
|
|
1100
|
-
async function readBodyFields(c) {
|
|
1101
|
-
const out = {};
|
|
1102
|
-
const raw = c.req?.raw;
|
|
1103
|
-
if (!raw)
|
|
1104
|
-
return out;
|
|
1105
|
-
try {
|
|
1106
|
-
const contentType = raw.headers.get("Content-Type") || "";
|
|
1107
|
-
if (contentType.includes("application/json")) {
|
|
1108
|
-
const body = (await raw.json());
|
|
1109
|
-
for (const [key, value] of Object.entries(body)) {
|
|
1110
|
-
if (typeof value === "string")
|
|
1111
|
-
out[key] = value;
|
|
1112
|
-
else if (key === "scopes" && Array.isArray(value))
|
|
1113
|
-
out[key] = JSON.stringify(value);
|
|
1114
|
-
else if (key === "termsAccepted" && typeof value === "boolean")
|
|
1115
|
-
out[key] = String(value);
|
|
1116
|
-
}
|
|
1117
|
-
return out;
|
|
1118
|
-
}
|
|
1119
|
-
const form = await raw.formData();
|
|
1120
|
-
form.forEach((value, key) => {
|
|
1121
|
-
if (typeof value === "string")
|
|
1122
|
-
out[key] = value;
|
|
1123
|
-
});
|
|
1124
|
-
return out;
|
|
1125
|
-
}
|
|
1126
|
-
catch {
|
|
1127
|
-
return out;
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
//# sourceMappingURL=consent-anchor-bridge.js.map
|