@pithy-sh/auth 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/dist/audit/actions.d.ts +39 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +40 -1
- package/dist/audit/emit.d.ts +34 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +47 -1
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +31 -11
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +25 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +9 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +6 -2
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +56 -10
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -11
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +46 -11
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +12 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +25 -4
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +142 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +66 -10
- package/dist/http/routes.d.ts +2 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +35 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +44 -1
- package/dist/http/views.d.ts +22 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +40 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +86 -41
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/transitions.d.ts +22 -1
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +51 -4
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +20 -5
- package/dist/purge/contribution.d.ts.map +1 -1
- package/dist/purge/contribution.js +20 -6
- package/dist/purge/run.d.ts +75 -5
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +117 -14
- package/dist/purge/workflow.d.ts +15 -2
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +51 -7
- package/dist/test-utils/accountFootprint.d.ts +5 -2
- package/dist/test-utils/accountFootprint.d.ts.map +1 -1
- package/dist/test-utils/accountFootprint.js +7 -2
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +59 -7
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +39 -0
- package/src/audit/emit.ts +63 -0
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +80 -23
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +15 -3
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +68 -3
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +48 -11
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +29 -3
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +134 -8
- package/src/http/routes.ts +63 -4
- package/src/http/schemas.ts +85 -0
- package/src/http/views.ts +46 -2
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +51 -1
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/transitions.ts +75 -5
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/set.ts +7 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +37 -10
- package/src/purge/run.ts +179 -16
- package/src/purge/workflow.ts +65 -7
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +10 -1
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
|
|
5
|
+
import type { ExecutionContext } from "@cloudflare/workers-types";
|
|
6
|
+
import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
|
|
7
|
+
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
8
|
+
import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
9
|
+
import { HttpError, pithyErrorHandler } from "@pithy-sh/core/src/error/http";
|
|
10
|
+
import {
|
|
11
|
+
ForbiddenError,
|
|
12
|
+
NotFoundError,
|
|
13
|
+
PithyError,
|
|
14
|
+
UnauthorizedError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
} from "@pithy-sh/core/src/error/pithyError";
|
|
17
|
+
import { AuthContext } from "@pithy-sh/core/src/http/authContext";
|
|
18
|
+
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
|
|
19
|
+
import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
|
|
20
|
+
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
21
|
+
import { type AppTool, offeredTools } from "@pithy-sh/core/src/mcp/tools";
|
|
22
|
+
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
23
|
+
import type { Context, Hono, MiddlewareHandler } from "hono";
|
|
24
|
+
import { AuthAuditActions } from "../../audit/actions";
|
|
25
|
+
import { authDatabase } from "../../data/tables";
|
|
26
|
+
import { requireAuth } from "../../http/middleware";
|
|
27
|
+
import { resolveDb } from "../../http/resolve";
|
|
28
|
+
import type { AuthInstance } from "../../instance/auth";
|
|
29
|
+
import { lifecycleRefusalFor } from "../../lifecycle/enforce";
|
|
30
|
+
import { PACKAGE_VERSION } from "../../version.generated";
|
|
31
|
+
import { argumentClass } from "../argumentClass";
|
|
32
|
+
import { verifiedHost } from "../clientMetadata";
|
|
33
|
+
import { consentView } from "../consent";
|
|
34
|
+
import { dispatchedOutcome, dispatchRequest, type ToolArguments, toolArguments } from "../dispatch";
|
|
35
|
+
import { floorAdmits, type McpFloor } from "../floor";
|
|
36
|
+
import type { McpHost } from "../host";
|
|
37
|
+
import { MCP_SCOPE, MCP_SCOPES } from "../provider";
|
|
38
|
+
import { answer } from "../rpc";
|
|
39
|
+
import {
|
|
40
|
+
recordToolCall,
|
|
41
|
+
requestedToolName,
|
|
42
|
+
type ToolCallActor,
|
|
43
|
+
type ToolCallCorrelation,
|
|
44
|
+
type ToolCallResult,
|
|
45
|
+
toolCallEvent,
|
|
46
|
+
} from "../toolAudit";
|
|
47
|
+
import { redirectList } from "./redirectList";
|
|
48
|
+
import {
|
|
49
|
+
AuthorizationServerMetadata,
|
|
50
|
+
type ConnectedApplication,
|
|
51
|
+
ConnectedApplications,
|
|
52
|
+
ConsentDecision,
|
|
53
|
+
ConsentView,
|
|
54
|
+
ProtectedResourceMetadata,
|
|
55
|
+
RevokedApplication,
|
|
56
|
+
RpcResponse,
|
|
57
|
+
} from "./responses";
|
|
58
|
+
import { ConnectionParam, ConsentBody, ConsentQuery, McpRequestBody } from "./schemas";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The MCP capability's routes (`docs/AGENT-ACCESS.md` §4).
|
|
62
|
+
*
|
|
63
|
+
* - `POST <path>` — the MCP endpoint. A bearer token minted for this endpoint, and nothing else, gets in.
|
|
64
|
+
* - `GET|DELETE <path>` — 405. The endpoint is stateless: it opens no event stream and holds no session to end.
|
|
65
|
+
* - `GET /.well-known/oauth-protected-resource<path>` — where a client learns which authorization server to ask.
|
|
66
|
+
* - `GET /.well-known/oauth-authorization-server<basePath>` — that server's metadata, at the RFC 8414 address.
|
|
67
|
+
* - `GET|POST <path>/consent` — what the scaffolded consent screen reads, and the one decision it sends.
|
|
68
|
+
* - `GET <path>/connections`, `DELETE <path>/connections/:clientId` — what the user approved, and the revoke.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/** What the routes are built over. Read lazily: the host and the router exist only once `createBackend` has run. */
|
|
72
|
+
export interface McpRouteDeps {
|
|
73
|
+
readonly path: string;
|
|
74
|
+
readonly floor: McpFloor;
|
|
75
|
+
readonly host: () => McpHost;
|
|
76
|
+
readonly app: () => Hono<PithyHonoEnv>;
|
|
77
|
+
readonly tools: () => readonly AppTool[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A verified MCP caller: who, through which client, for which organization, and what their role allows. */
|
|
81
|
+
interface VerifiedCaller {
|
|
82
|
+
readonly auth: AuthContext;
|
|
83
|
+
readonly clientId: string;
|
|
84
|
+
readonly tenant: string | null;
|
|
85
|
+
readonly roleAllows: ((power: string) => boolean) | null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A verified caller, and when their request arrived. */
|
|
89
|
+
interface McpCaller extends VerifiedCaller {
|
|
90
|
+
readonly receivedAt: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Each MCP request's verified caller, set by {@link mcpCallerGuard} and read by the endpoint's handler. */
|
|
94
|
+
const callers = new WeakMap<Request, McpCaller>();
|
|
95
|
+
|
|
96
|
+
/** The key set `verifyJwsAccessToken` takes. */
|
|
97
|
+
type JwksSet = Awaited<ReturnType<Exclude<Parameters<typeof verifyJwsAccessToken>[1]["jwksFetch"], string>>>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The provider's endpoints this module calls. `AuthInstance` is typed over the kit's own plugins, so the ones a
|
|
101
|
+
* composed provider adds are absent from its type; this names the two, as the provider declares them.
|
|
102
|
+
*/
|
|
103
|
+
interface ProviderApi {
|
|
104
|
+
getJwks(): Promise<unknown>;
|
|
105
|
+
getOAuthServerConfig(): Promise<unknown>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function providerApi(instance: AuthInstance): ProviderApi {
|
|
109
|
+
return instance.api as unknown as ProviderApi;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The provider's database, through Better Auth's own adapter — which maps the models to the `pithy_mcp_*` tables. */
|
|
113
|
+
async function adapterOf(instance: AuthInstance) {
|
|
114
|
+
return (await instance.$context).adapter;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The MCP endpoint's absolute URL for this request, and the issuer that mints its tokens. */
|
|
118
|
+
function addresses(c: Context<PithyHonoEnv>, deps: McpRouteDeps): { resource: string; issuer: string; base: string } {
|
|
119
|
+
const host = deps.host();
|
|
120
|
+
const base = host.baseURL(c.req.raw).replace(/\/$/, "");
|
|
121
|
+
return { base, resource: `${base}${deps.path}`, issuer: `${base}${host.basePath}` };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The protected-resource metadata URL a challenge names. */
|
|
125
|
+
function metadataUrl(base: string, path: string): string {
|
|
126
|
+
return `${base}/.well-known/oauth-protected-resource${path}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The refusal an unauthenticated MCP request gets: a 401 naming where to find the authorization server. */
|
|
130
|
+
function challenge(c: Context<PithyHonoEnv>, deps: McpRouteDeps, detail: string): Response {
|
|
131
|
+
const { base } = addresses(c, deps);
|
|
132
|
+
const response = pithyErrorHandler(
|
|
133
|
+
new UnauthorizedError({
|
|
134
|
+
message: "Authentication required.",
|
|
135
|
+
action: "Authorize the MCP client against this application, then retry with its access token.",
|
|
136
|
+
detail,
|
|
137
|
+
}),
|
|
138
|
+
c,
|
|
139
|
+
);
|
|
140
|
+
response.headers.set(
|
|
141
|
+
"WWW-Authenticate",
|
|
142
|
+
`Bearer resource_metadata="${metadataUrl(base, deps.path)}", scope="${MCP_SCOPE}"`,
|
|
143
|
+
);
|
|
144
|
+
return response;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function claim(payload: Record<string, unknown>, name: string): string | undefined {
|
|
148
|
+
const value = payload[name];
|
|
149
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Verify the caller, or answer the refusal. **Identity only — never permission.** The token proves who and through
|
|
154
|
+
* which client; it is checked for its signature, issuer, audience and expiry, for a consent still on record, for a
|
|
155
|
+
* session still live, and for an account in good standing. What the caller may *do* is never read off it.
|
|
156
|
+
*/
|
|
157
|
+
async function verifyCaller(c: Context<PithyHonoEnv>, deps: McpRouteDeps): Promise<VerifiedCaller | Response> {
|
|
158
|
+
const bearer = /^Bearer\s+(.+)$/i.exec(c.req.header("authorization") ?? "")?.[1]?.trim();
|
|
159
|
+
if (!bearer) return challenge(c, deps, "no bearer token on the MCP request");
|
|
160
|
+
const host = deps.host();
|
|
161
|
+
const instance = await host.instance(c);
|
|
162
|
+
const { resource, issuer } = addresses(c, deps);
|
|
163
|
+
let payload: Record<string, unknown>;
|
|
164
|
+
try {
|
|
165
|
+
payload = (await verifyJwsAccessToken(bearer, {
|
|
166
|
+
jwksFetch: async () => (await providerApi(instance).getJwks()) as JwksSet,
|
|
167
|
+
verifyOptions: { audience: resource, issuer },
|
|
168
|
+
})) as Record<string, unknown>;
|
|
169
|
+
} catch {
|
|
170
|
+
return challenge(c, deps, "the MCP access token did not verify for this resource");
|
|
171
|
+
}
|
|
172
|
+
const userId = claim(payload, "sub");
|
|
173
|
+
const sessionId = claim(payload, "sid");
|
|
174
|
+
const clientId = claim(payload, "azp") ?? claim(payload, "client_id");
|
|
175
|
+
if (!userId || !sessionId || !clientId)
|
|
176
|
+
return challenge(c, deps, "the MCP access token names no user, session or client");
|
|
177
|
+
const adapter = await adapterOf(instance);
|
|
178
|
+
// Revocation is immediate: the connected-applications screen deletes the consent, and every token minted under it
|
|
179
|
+
// stops here on its next call rather than living out its hour.
|
|
180
|
+
const consent = await adapter.findOne({
|
|
181
|
+
model: "oauthConsent",
|
|
182
|
+
where: [
|
|
183
|
+
{ field: "clientId", value: clientId },
|
|
184
|
+
{ field: "userId", value: userId },
|
|
185
|
+
],
|
|
186
|
+
});
|
|
187
|
+
if (!consent) return challenge(c, deps, `client ${clientId} holds no consent from user ${userId}`);
|
|
188
|
+
const session = await adapter.findOne<{ expiresAt: Date | string }>({
|
|
189
|
+
model: "session",
|
|
190
|
+
where: [{ field: "id", value: sessionId }],
|
|
191
|
+
});
|
|
192
|
+
const now = new Date();
|
|
193
|
+
if (!session || new Date(session.expiresAt).getTime() <= now.getTime()) {
|
|
194
|
+
return challenge(c, deps, `session ${sessionId} the token was minted under has ended`);
|
|
195
|
+
}
|
|
196
|
+
const refusal = await lifecycleRefusalFor(authDatabase(resolveDb(c.env, host.database)), userId, null, now);
|
|
197
|
+
if (refusal) throw refusal;
|
|
198
|
+
const auth = AuthContext.parse({ userId, sessionId, scopes: [], locale: null });
|
|
199
|
+
c.set("auth", auth);
|
|
200
|
+
const acting = await c.var.actingOrganization();
|
|
201
|
+
const roleAllows = acting === null ? null : (power: string) => acting.roleAllows(power);
|
|
202
|
+
const admitted = await floorAdmits(deps.floor, {
|
|
203
|
+
roleAllows,
|
|
204
|
+
entitlements: async () => grantedEntitlementKeys(await c.var.entitlements.list(), now),
|
|
205
|
+
});
|
|
206
|
+
if (!admitted) {
|
|
207
|
+
throw new ForbiddenError({
|
|
208
|
+
message: "Your account cannot connect an agent to this application.",
|
|
209
|
+
detail: `user ${userId} is below the MCP endpoint's floor`,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return { auth, clientId, tenant: acting?.organizationId ?? null, roleAllows };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The MCP endpoint's guard: the caller verified, or the refusal. A guard rather than a step inside the handler, so it
|
|
217
|
+
* runs before the body is validated — an unauthenticated client gets the challenge that names the authorization
|
|
218
|
+
* server, whatever it sent, and learns nothing about which bodies are well-formed.
|
|
219
|
+
*/
|
|
220
|
+
function mcpCallerGuard(deps: McpRouteDeps): MiddlewareHandler<PithyHonoEnv> {
|
|
221
|
+
return async (c, next) => {
|
|
222
|
+
const receivedAt = Date.now();
|
|
223
|
+
const caller = await verifyCaller(c, deps);
|
|
224
|
+
if (caller instanceof Response) return caller;
|
|
225
|
+
callers.set(c.req.raw, { ...caller, receivedAt });
|
|
226
|
+
await next();
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** What a request's tool-call row and its route's rows are joined by, and where the call came from. */
|
|
231
|
+
function correlationOf(c: Context<PithyHonoEnv>): ToolCallCorrelation {
|
|
232
|
+
return {
|
|
233
|
+
requestId: c.req.header("cf-ray") ?? crypto.randomUUID(),
|
|
234
|
+
ip: c.req.header("cf-connecting-ip") ?? null,
|
|
235
|
+
userAgent: c.req.header("user-agent") ?? null,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** The correlation, as the headers the dispatched request carries to the route. */
|
|
240
|
+
function correlationHeaders(correlation: ToolCallCorrelation): Record<string, string> {
|
|
241
|
+
return {
|
|
242
|
+
"cf-ray": correlation.requestId,
|
|
243
|
+
...(correlation.ip === null ? {} : { "cf-connecting-ip": correlation.ip }),
|
|
244
|
+
...(correlation.userAgent === null ? {} : { "user-agent": correlation.userAgent }),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** One tool call, through the whole app, as the caller. */
|
|
249
|
+
async function callTool(
|
|
250
|
+
c: Context<PithyHonoEnv>,
|
|
251
|
+
deps: McpRouteDeps,
|
|
252
|
+
caller: McpCaller,
|
|
253
|
+
correlation: ToolCallCorrelation,
|
|
254
|
+
tool: AppTool,
|
|
255
|
+
args: ToolArguments,
|
|
256
|
+
): Promise<{ status: number; body: unknown; bytes: number }> {
|
|
257
|
+
let request: Request;
|
|
258
|
+
try {
|
|
259
|
+
request = dispatchRequest(new URL(c.req.url).origin, tool, args, caller.auth, correlationHeaders(correlation));
|
|
260
|
+
} catch (error) {
|
|
261
|
+
// Arguments that build no request to the tool's route are the agent's to correct, so they are answered as the
|
|
262
|
+
// route would answer them, inside a tool result, rather than as an HTTP failure of the transport.
|
|
263
|
+
if (!(error instanceof PithyError)) throw error;
|
|
264
|
+
const body = { error: HttpError.encode(error.payload) };
|
|
265
|
+
return { status: error.payload.status, body, bytes: new TextEncoder().encode(JSON.stringify(body)).byteLength };
|
|
266
|
+
}
|
|
267
|
+
let executionCtx: ExecutionContext | undefined;
|
|
268
|
+
try {
|
|
269
|
+
executionCtx = c.executionCtx as unknown as ExecutionContext;
|
|
270
|
+
} catch {
|
|
271
|
+
executionCtx = undefined;
|
|
272
|
+
}
|
|
273
|
+
return dispatchedOutcome(await deps.app().fetch(request, c.env, executionCtx));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Who a tool-call row names: the caller, and the client's name as it registered itself. */
|
|
277
|
+
async function toolCallActor(c: Context<PithyHonoEnv>, deps: McpRouteDeps, caller: McpCaller): Promise<ToolCallActor> {
|
|
278
|
+
const client = await (await adapterOf(await deps.host().instance(c))).findOne<{ name?: string | null }>({
|
|
279
|
+
model: "oauthClient",
|
|
280
|
+
where: [{ field: "clientId", value: caller.clientId }],
|
|
281
|
+
});
|
|
282
|
+
return {
|
|
283
|
+
userId: caller.auth.userId,
|
|
284
|
+
sessionId: caller.auth.sessionId,
|
|
285
|
+
clientId: caller.clientId,
|
|
286
|
+
clientReportedName: client?.name ?? null,
|
|
287
|
+
tenant: caller.tenant,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Write the row for one tool call. Never fails the call. */
|
|
292
|
+
function auditToolCall(
|
|
293
|
+
c: Context<PithyHonoEnv>,
|
|
294
|
+
deps: McpRouteDeps,
|
|
295
|
+
caller: McpCaller,
|
|
296
|
+
correlation: ToolCallCorrelation,
|
|
297
|
+
tool: string | null,
|
|
298
|
+
result: ToolCallResult,
|
|
299
|
+
): Promise<void> {
|
|
300
|
+
const durationMs = Date.now() - caller.receivedAt;
|
|
301
|
+
return recordToolCall(c.var.emit, async () =>
|
|
302
|
+
toolCallEvent({ actor: await toolCallActor(c, deps, caller), correlation, tool, durationMs, result }),
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** One tool call, made and recorded. */
|
|
307
|
+
async function auditedCall(
|
|
308
|
+
c: Context<PithyHonoEnv>,
|
|
309
|
+
deps: McpRouteDeps,
|
|
310
|
+
caller: McpCaller,
|
|
311
|
+
correlation: ToolCallCorrelation,
|
|
312
|
+
tool: AppTool,
|
|
313
|
+
raw: Record<string, unknown>,
|
|
314
|
+
): Promise<{ status: number; body: unknown }> {
|
|
315
|
+
const args = toolArguments(raw);
|
|
316
|
+
const classed = argumentClass(tool.path, args);
|
|
317
|
+
let outcome: { status: number; body: unknown; bytes: number };
|
|
318
|
+
try {
|
|
319
|
+
outcome = await callTool(c, deps, caller, correlation, tool, args);
|
|
320
|
+
} catch (error) {
|
|
321
|
+
await auditToolCall(c, deps, caller, correlation, tool.name, {
|
|
322
|
+
kind: "answered",
|
|
323
|
+
status: 500,
|
|
324
|
+
responseBytes: 0,
|
|
325
|
+
arguments: classed,
|
|
326
|
+
});
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
await auditToolCall(c, deps, caller, correlation, tool.name, {
|
|
330
|
+
kind: "answered",
|
|
331
|
+
status: outcome.status,
|
|
332
|
+
responseBytes: outcome.bytes,
|
|
333
|
+
arguments: classed,
|
|
334
|
+
});
|
|
335
|
+
return outcome;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Emit one consent event. Never fatal: the audit seam swallows its own failures. */
|
|
339
|
+
async function audit(c: Context<PithyHonoEnv>, event: Omit<AuditEventInput, "actorType">): Promise<void> {
|
|
340
|
+
await c.var.emit({
|
|
341
|
+
actorType: "user",
|
|
342
|
+
actorId: c.var.auth?.userId ?? null,
|
|
343
|
+
sessionId: c.var.auth?.sessionId ?? null,
|
|
344
|
+
ip: c.req.header("cf-connecting-ip") ?? null,
|
|
345
|
+
userAgent: c.req.header("user-agent") ?? null,
|
|
346
|
+
...event,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Hand the decision to the provider's own consent endpoint, as the browser's request — its session credential and
|
|
352
|
+
* its origin — so every check the provider makes on a consent runs here unchanged. It needs the request itself,
|
|
353
|
+
* which a direct `api` call does not carry.
|
|
354
|
+
*/
|
|
355
|
+
async function decide(
|
|
356
|
+
c: Context<PithyHonoEnv>,
|
|
357
|
+
deps: McpRouteDeps,
|
|
358
|
+
instance: AuthInstance,
|
|
359
|
+
body: { accept: boolean; oauth_query: string },
|
|
360
|
+
): Promise<{ url: string }> {
|
|
361
|
+
const { issuer } = addresses(c, deps);
|
|
362
|
+
const headers = new Headers(c.req.raw.headers);
|
|
363
|
+
headers.delete("content-length");
|
|
364
|
+
headers.set("content-type", "application/json");
|
|
365
|
+
const response = await instance.handler(
|
|
366
|
+
new Request(`${issuer}/oauth2/consent`, { method: "POST", headers, body: JSON.stringify(body) }),
|
|
367
|
+
);
|
|
368
|
+
const decided = (await response.json().catch(() => ({}))) as { url?: unknown };
|
|
369
|
+
if (!response.ok || typeof decided.url !== "string") {
|
|
370
|
+
throw new ValidationError({
|
|
371
|
+
message: "This authorization request could not be completed. Start again from the application.",
|
|
372
|
+
detail: `the provider answered the consent with ${response.status}`,
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
return { url: decided.url };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** The signed authorization query, verified, as parameters. */
|
|
379
|
+
async function signedQuery(instance: AuthInstance, raw: string): Promise<URLSearchParams> {
|
|
380
|
+
const query = raw.startsWith("?") ? raw.slice(1) : raw;
|
|
381
|
+
const secret = (await instance.$context).secret;
|
|
382
|
+
if (!(await verifyOAuthQueryParams(query, secret))) {
|
|
383
|
+
throw new ValidationError({
|
|
384
|
+
message: "This authorization request has expired. Start again from the application.",
|
|
385
|
+
detail: "the consent screen's oauth_query did not verify or has expired",
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
return new URLSearchParams(query);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The caller's role, as a `ToolCaller` reads it. */
|
|
392
|
+
async function roleOf(c: Context<PithyHonoEnv>): Promise<((power: string) => boolean) | null> {
|
|
393
|
+
const acting = await c.var.actingOrganization();
|
|
394
|
+
return acting === null ? null : (power: string) => acting.roleAllows(power);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Register every route. */
|
|
398
|
+
export function registerMcpRoutes(app: Hono<PithyHonoEnv>, deps: McpRouteDeps): void {
|
|
399
|
+
const { path } = deps;
|
|
400
|
+
const csrf = requireSameOrigin();
|
|
401
|
+
|
|
402
|
+
const protectedResource = (c: Context<PithyHonoEnv>) => {
|
|
403
|
+
const { resource, issuer } = addresses(c, deps);
|
|
404
|
+
return c.json({
|
|
405
|
+
resource,
|
|
406
|
+
authorization_servers: [issuer],
|
|
407
|
+
scopes_supported: [...MCP_SCOPES],
|
|
408
|
+
bearer_methods_supported: ["header"],
|
|
409
|
+
resource_name: "This application's MCP endpoint",
|
|
410
|
+
} satisfies ProtectedResourceMetadata);
|
|
411
|
+
};
|
|
412
|
+
const protectedResourceSpec = describeRoute({
|
|
413
|
+
summary: "Name the authorization server for the MCP endpoint.",
|
|
414
|
+
description: "RFC 9728 protected-resource metadata. Where an MCP client starts, from the endpoint's URL alone.",
|
|
415
|
+
verification: "public",
|
|
416
|
+
responses: { 200: ProtectedResourceMetadata },
|
|
417
|
+
});
|
|
418
|
+
app.get(`/.well-known/oauth-protected-resource${path}`, protectedResourceSpec, protectedResource);
|
|
419
|
+
app.get("/.well-known/oauth-protected-resource", protectedResourceSpec, protectedResource);
|
|
420
|
+
|
|
421
|
+
const serverMetadata = async (c: Context<PithyHonoEnv>) => {
|
|
422
|
+
const instance = await deps.host().instance(c);
|
|
423
|
+
const metadata = (await providerApi(instance).getOAuthServerConfig()) as AuthorizationServerMetadata;
|
|
424
|
+
return c.json(metadata satisfies AuthorizationServerMetadata);
|
|
425
|
+
};
|
|
426
|
+
const serverMetadataSpec = describeRoute({
|
|
427
|
+
summary: "Describe the authorization server that mints MCP tokens.",
|
|
428
|
+
description: "RFC 8414 authorization-server metadata, at the address its issuer implies.",
|
|
429
|
+
verification: "public",
|
|
430
|
+
responses: { 200: AuthorizationServerMetadata },
|
|
431
|
+
});
|
|
432
|
+
// The issuer carries auth's base path, so RFC 8414 puts its metadata at the well-known prefix plus that path. A
|
|
433
|
+
// client that drops the path asks the bare address; both answer, and both answer for this Worker's one issuer.
|
|
434
|
+
app.get(`/.well-known/oauth-authorization-server${deps.host().basePath}`, serverMetadataSpec, serverMetadata);
|
|
435
|
+
app.get("/.well-known/oauth-authorization-server", serverMetadataSpec, serverMetadata);
|
|
436
|
+
|
|
437
|
+
app.post(
|
|
438
|
+
path,
|
|
439
|
+
describeRoute({
|
|
440
|
+
summary: "Serve the app's MCP tools to an agent acting as a user.",
|
|
441
|
+
description:
|
|
442
|
+
"Streamable HTTP, stateless, one JSON-RPC message per request answered in the body. The bearer token must be one this application minted for this endpoint. `tools/list` holds only what the caller's role allows, and every call runs through the route it names, as the caller.",
|
|
443
|
+
verification: "bearer",
|
|
444
|
+
responses: {
|
|
445
|
+
200: RpcResponse,
|
|
446
|
+
202: { description: "A notification, accepted. No body." },
|
|
447
|
+
},
|
|
448
|
+
}),
|
|
449
|
+
mcpCallerGuard(deps),
|
|
450
|
+
validate("json", McpRequestBody),
|
|
451
|
+
async (c) => {
|
|
452
|
+
const caller = callers.get(c.req.raw);
|
|
453
|
+
if (caller === undefined) return challenge(c, deps, "the MCP request reached its handler unverified");
|
|
454
|
+
const correlation = correlationOf(c);
|
|
455
|
+
const reply = await answer(c.req.valid("json"), {
|
|
456
|
+
server: { name: "pithy", version: PACKAGE_VERSION },
|
|
457
|
+
tools: async () => offeredTools(deps.tools(), { roleAllows: caller.roleAllows, scopes: caller.auth.scopes }),
|
|
458
|
+
call: (tool, args) => auditedCall(c, deps, caller, correlation, tool, args),
|
|
459
|
+
refused: (name) =>
|
|
460
|
+
auditToolCall(c, deps, caller, correlation, requestedToolName(name), {
|
|
461
|
+
kind: "refused",
|
|
462
|
+
reason: deps.tools().some((tool) => tool.name === name) ? "withheld" : "unknown",
|
|
463
|
+
}),
|
|
464
|
+
});
|
|
465
|
+
if (reply === null) return c.body(null, 202);
|
|
466
|
+
return c.json(reply as RpcResponse);
|
|
467
|
+
},
|
|
468
|
+
);
|
|
469
|
+
|
|
470
|
+
// The streamable HTTP transport requires a GET on the endpoint to answer an event stream or 405, and a client that
|
|
471
|
+
// gets anything else reports the endpoint broken. DELETE ends a transport session, and this endpoint keeps none.
|
|
472
|
+
app.on(
|
|
473
|
+
["GET", "DELETE"],
|
|
474
|
+
path,
|
|
475
|
+
describeRoute({
|
|
476
|
+
summary: "Refuse to open an event stream or end a session on the MCP endpoint.",
|
|
477
|
+
description:
|
|
478
|
+
"The endpoint is stateless and answers every message in the response body, so it offers no server-sent event stream and has no session to end. Always 405, with `Allow: POST`.",
|
|
479
|
+
verification: "public",
|
|
480
|
+
responses: { 405: { description: "Only POST is served here." } },
|
|
481
|
+
}),
|
|
482
|
+
(c) => c.body(null, 405, { Allow: "POST" }),
|
|
483
|
+
);
|
|
484
|
+
|
|
485
|
+
app.get(
|
|
486
|
+
`${path}/consent`,
|
|
487
|
+
describeRoute({
|
|
488
|
+
summary: "Show what an application asking to act as you will be able to do.",
|
|
489
|
+
description:
|
|
490
|
+
"Read by the scaffolded consent screen. The client's name is as it reported itself; its host is verified only when its id is its metadata document's URL; the redirect URI is the one the authorization server enforces. Only operations your role allows are listed.",
|
|
491
|
+
verification: ["bearer", "session"],
|
|
492
|
+
responses: { 200: ConsentView },
|
|
493
|
+
}),
|
|
494
|
+
requireAuth(),
|
|
495
|
+
validate("query", ConsentQuery),
|
|
496
|
+
async (c) => {
|
|
497
|
+
const instance = await deps.host().instance(c);
|
|
498
|
+
const query = await signedQuery(instance, c.req.valid("query").oauth_query);
|
|
499
|
+
const clientId = query.get("client_id") ?? "";
|
|
500
|
+
const client = await (await adapterOf(instance)).findOne<{
|
|
501
|
+
name?: string | null;
|
|
502
|
+
uri?: string | null;
|
|
503
|
+
clientDiscoveryId?: string | null;
|
|
504
|
+
}>({
|
|
505
|
+
model: "oauthClient",
|
|
506
|
+
where: [{ field: "clientId", value: clientId }],
|
|
507
|
+
});
|
|
508
|
+
if (!client) throw new NotFoundError({ message: "No such application.", detail: `client ${clientId}` });
|
|
509
|
+
const caller = { roleAllows: await roleOf(c), scopes: c.var.auth?.scopes ?? [] };
|
|
510
|
+
const view = consentView({
|
|
511
|
+
client: {
|
|
512
|
+
id: clientId,
|
|
513
|
+
verifiedHost: verifiedHost({ clientId, clientDiscoveryId: client.clientDiscoveryId }),
|
|
514
|
+
reportedName: client.name ?? null,
|
|
515
|
+
reportedUri: client.uri ?? null,
|
|
516
|
+
redirectUri: query.get("redirect_uri") ?? "",
|
|
517
|
+
},
|
|
518
|
+
tools: deps.tools(),
|
|
519
|
+
caller,
|
|
520
|
+
requestedScopes: (query.get("scope") ?? "").split(" ").filter((scope) => scope.length > 0),
|
|
521
|
+
});
|
|
522
|
+
return c.json(view satisfies ConsentView);
|
|
523
|
+
},
|
|
524
|
+
);
|
|
525
|
+
|
|
526
|
+
app.post(
|
|
527
|
+
`${path}/consent`,
|
|
528
|
+
describeRoute({
|
|
529
|
+
summary: "Let an application act as you in this application, or refuse it.",
|
|
530
|
+
description:
|
|
531
|
+
"One decision for the whole request; nothing is selectable. Approving is audited as `auth/mcp_grant_approved`, refusing as `auth/mcp_grant_denied`. Answers where to send the browser next.",
|
|
532
|
+
verification: ["bearer", "session"],
|
|
533
|
+
responses: { 200: ConsentDecision },
|
|
534
|
+
}),
|
|
535
|
+
requireAuth(),
|
|
536
|
+
csrf,
|
|
537
|
+
validate("json", ConsentBody),
|
|
538
|
+
async (c) => {
|
|
539
|
+
const { oauth_query, accept } = c.req.valid("json");
|
|
540
|
+
const instance = await deps.host().instance(c);
|
|
541
|
+
const query = await signedQuery(instance, oauth_query);
|
|
542
|
+
const decided = await decide(c, deps, instance, { accept, oauth_query: query.toString() });
|
|
543
|
+
const redirect = decided.url;
|
|
544
|
+
const clientId = query.get("client_id") ?? "";
|
|
545
|
+
await audit(c, {
|
|
546
|
+
action: accept ? AuthAuditActions.mcpGrantApproved : AuthAuditActions.mcpGrantDenied,
|
|
547
|
+
outcome: "success",
|
|
548
|
+
resourceType: "mcp_client",
|
|
549
|
+
resourceId: clientId,
|
|
550
|
+
metadata: { redirectUri: query.get("redirect_uri") ?? null, scope: query.get("scope") ?? null },
|
|
551
|
+
});
|
|
552
|
+
return c.json({ redirect } satisfies ConsentDecision);
|
|
553
|
+
},
|
|
554
|
+
);
|
|
555
|
+
|
|
556
|
+
app.get(
|
|
557
|
+
`${path}/connections`,
|
|
558
|
+
describeRoute({
|
|
559
|
+
summary: "List the applications acting as you.",
|
|
560
|
+
description: "What you approved, when, and where each sends its tokens. Revoking is the only narrowing there is.",
|
|
561
|
+
verification: ["bearer", "session"],
|
|
562
|
+
responses: { 200: ConnectedApplications },
|
|
563
|
+
}),
|
|
564
|
+
requireAuth(),
|
|
565
|
+
async (c) => {
|
|
566
|
+
const userId = c.var.auth?.userId ?? "";
|
|
567
|
+
const adapter = await adapterOf(await deps.host().instance(c));
|
|
568
|
+
const consents = await adapter.findMany<{ clientId: string; createdAt: Date | string }>({
|
|
569
|
+
model: "oauthConsent",
|
|
570
|
+
where: [{ field: "userId", value: userId }],
|
|
571
|
+
});
|
|
572
|
+
const applications: ConnectedApplication[] = [];
|
|
573
|
+
for (const consent of consents) {
|
|
574
|
+
const client = await adapter.findOne<{
|
|
575
|
+
name?: string | null;
|
|
576
|
+
redirectUris?: string[] | string | null;
|
|
577
|
+
clientDiscoveryId?: string | null;
|
|
578
|
+
}>({
|
|
579
|
+
model: "oauthClient",
|
|
580
|
+
where: [{ field: "clientId", value: consent.clientId }],
|
|
581
|
+
});
|
|
582
|
+
const uris = client?.redirectUris;
|
|
583
|
+
applications.push({
|
|
584
|
+
clientId: consent.clientId,
|
|
585
|
+
verifiedHost: verifiedHost({ clientId: consent.clientId, clientDiscoveryId: client?.clientDiscoveryId }),
|
|
586
|
+
reportedName: client?.name ?? null,
|
|
587
|
+
redirectUris: Array.isArray(uris) ? uris : typeof uris === "string" ? redirectList(uris) : [],
|
|
588
|
+
approvedAt: new Date(consent.createdAt).toISOString(),
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
applications.sort((a, b) => b.approvedAt.localeCompare(a.approvedAt));
|
|
592
|
+
return c.json({ applications } satisfies ConnectedApplications);
|
|
593
|
+
},
|
|
594
|
+
);
|
|
595
|
+
|
|
596
|
+
app.delete(
|
|
597
|
+
`${path}/connections/:clientId`,
|
|
598
|
+
describeRoute({
|
|
599
|
+
summary: "Revoke an application acting as you.",
|
|
600
|
+
description:
|
|
601
|
+
"Takes effect on its next call: the consent, its refresh tokens and its stored access tokens go, and the MCP endpoint refuses a token with no consent behind it. Audited as `auth/mcp_grant_revoked`. No administrator needed.",
|
|
602
|
+
verification: ["bearer", "session"],
|
|
603
|
+
responses: { 200: RevokedApplication },
|
|
604
|
+
}),
|
|
605
|
+
requireAuth(),
|
|
606
|
+
csrf,
|
|
607
|
+
validate("param", ConnectionParam),
|
|
608
|
+
async (c) => {
|
|
609
|
+
const userId = c.var.auth?.userId ?? "";
|
|
610
|
+
const { clientId } = c.req.valid("param");
|
|
611
|
+
const adapter = await adapterOf(await deps.host().instance(c));
|
|
612
|
+
const where = [
|
|
613
|
+
{ field: "clientId", value: clientId },
|
|
614
|
+
{ field: "userId", value: userId },
|
|
615
|
+
];
|
|
616
|
+
const held = await adapter.findMany({ model: "oauthConsent", where });
|
|
617
|
+
if (held.length === 0) {
|
|
618
|
+
throw new NotFoundError({
|
|
619
|
+
message: "No such connected application.",
|
|
620
|
+
detail: `client ${clientId} for ${userId}`,
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
await adapter.deleteMany({ model: "oauthConsent", where });
|
|
624
|
+
await adapter.deleteMany({ model: "oauthRefreshToken", where });
|
|
625
|
+
await adapter.deleteMany({ model: "oauthAccessToken", where });
|
|
626
|
+
await audit(c, {
|
|
627
|
+
action: AuthAuditActions.mcpGrantRevoked,
|
|
628
|
+
outcome: "success",
|
|
629
|
+
resourceType: "mcp_client",
|
|
630
|
+
resourceId: clientId,
|
|
631
|
+
});
|
|
632
|
+
return c.json({ revoked: true } satisfies RevokedApplication);
|
|
633
|
+
},
|
|
634
|
+
);
|
|
635
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { RpcMessage } from "../rpc";
|
|
6
|
+
|
|
7
|
+
/** The MCP endpoint's body: one JSON-RPC message. */
|
|
8
|
+
export const McpRequestBody = RpcMessage;
|
|
9
|
+
|
|
10
|
+
/** The consent screen's question: the signed authorization query the provider redirected it with. */
|
|
11
|
+
export const ConsentQuery = z
|
|
12
|
+
.object({
|
|
13
|
+
oauth_query: z
|
|
14
|
+
.string()
|
|
15
|
+
.min(1)
|
|
16
|
+
.max(8192)
|
|
17
|
+
.describe("The query string the authorization server redirected the screen with, signed by it."),
|
|
18
|
+
})
|
|
19
|
+
.describe("Which authorization request the consent screen is about.");
|
|
20
|
+
|
|
21
|
+
/** The consent decision: one, for the whole request. */
|
|
22
|
+
export const ConsentBody = z
|
|
23
|
+
.object({
|
|
24
|
+
oauth_query: z
|
|
25
|
+
.string()
|
|
26
|
+
.min(1)
|
|
27
|
+
.max(8192)
|
|
28
|
+
.describe("The query string the authorization server redirected the screen with, signed by it."),
|
|
29
|
+
accept: z.boolean().describe("Whether you let this client act as you in this application."),
|
|
30
|
+
})
|
|
31
|
+
.strict()
|
|
32
|
+
.describe("One decision: let this client act as you, or not. Nothing in it is selectable.");
|
|
33
|
+
|
|
34
|
+
/** Which connected application. */
|
|
35
|
+
export const ConnectionParam = z
|
|
36
|
+
.object({ clientId: z.string().min(1).max(256).describe("The client's id.") })
|
|
37
|
+
.describe("One connected application.");
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { Capability } from "@pithy-sh/core/src/capability/capability";
|
|
5
|
+
import type { McpWiring } from "./host";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* How auth recognizes the MCP capability composed beside it, without importing it — the capability imports
|
|
9
|
+
* auth's guard, so the reverse import would be a cycle. A name and the one field auth reads.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The MCP capability's name. */
|
|
13
|
+
export const MCP_CAPABILITY_NAME = "mcp";
|
|
14
|
+
|
|
15
|
+
/** Is this the MCP capability? */
|
|
16
|
+
export function isMcpCapability(capability: Capability): capability is Capability & { readonly mcpWiring: McpWiring } {
|
|
17
|
+
return capability.name === MCP_CAPABILITY_NAME && "mcpWiring" in capability;
|
|
18
|
+
}
|