@pithy-sh/auth 0.10.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/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- 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 +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- 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 +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- 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 +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- 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 +87 -42
- 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/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- 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/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- 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/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -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/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -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 +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- 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 +176 -12
- 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 +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- 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 +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- 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/0005_purge_once.ts +42 -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/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- 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,517 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { AuthAuditActions } from "../../audit/actions.js";
|
|
4
|
+
import { authDatabase } from "../../data/tables.js";
|
|
5
|
+
import { dispatchRequest, dispatchedOutcome, toolArguments } from "../dispatch.js";
|
|
6
|
+
import { lifecycleRefusalFor } from "../../lifecycle/enforce.js";
|
|
7
|
+
import { MCP_SCOPES } from "../provider.js";
|
|
8
|
+
import { resolveDb } from "../../http/resolve.js";
|
|
9
|
+
import { requireAuth } from "../../http/middleware.js";
|
|
10
|
+
import { PACKAGE_VERSION } from "../../version.generated.js";
|
|
11
|
+
import { verifiedHost } from "../clientMetadata.js";
|
|
12
|
+
import { floorAdmits } from "../floor.js";
|
|
13
|
+
import { argumentClass } from "../argumentClass.js";
|
|
14
|
+
import { consentView } from "../consent.js";
|
|
15
|
+
import { answer } from "../rpc.js";
|
|
16
|
+
import { recordToolCall, requestedToolName, toolCallEvent } from "../toolAudit.js";
|
|
17
|
+
import { redirectList } from "./redirectList.js";
|
|
18
|
+
import { AuthorizationServerMetadata, ConnectedApplications, ConsentDecision, ConsentView, ProtectedResourceMetadata, RevokedApplication, RpcResponse } from "./responses.js";
|
|
19
|
+
import { ConnectionParam, ConsentBody, ConsentQuery, McpRequestBody } from "./schemas.js";
|
|
20
|
+
import { ForbiddenError, NotFoundError, PithyError, UnauthorizedError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
21
|
+
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
|
|
22
|
+
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
23
|
+
import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
|
|
24
|
+
import { AuthContext } from "@pithy-sh/core/src/http/authContext";
|
|
25
|
+
import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
|
|
26
|
+
import { offeredTools } from "@pithy-sh/core/src/mcp/tools";
|
|
27
|
+
import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
28
|
+
import { HttpError, pithyErrorHandler } from "@pithy-sh/core/src/error/http";
|
|
29
|
+
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
30
|
+
//#region src/mcp/http/routes.ts
|
|
31
|
+
/** Each MCP request's verified caller, set by {@link mcpCallerGuard} and read by the endpoint's handler. */
|
|
32
|
+
const callers = /* @__PURE__ */ new WeakMap();
|
|
33
|
+
function providerApi(instance) {
|
|
34
|
+
return instance.api;
|
|
35
|
+
}
|
|
36
|
+
/** The provider's database, through Better Auth's own adapter — which maps the models to the `pithy_mcp_*` tables. */
|
|
37
|
+
async function adapterOf(instance) {
|
|
38
|
+
return (await instance.$context).adapter;
|
|
39
|
+
}
|
|
40
|
+
/** The MCP endpoint's absolute URL for this request, and the issuer that mints its tokens. */
|
|
41
|
+
function addresses(c, deps) {
|
|
42
|
+
const host = deps.host();
|
|
43
|
+
const base = host.baseURL(c.req.raw).replace(/\/$/, "");
|
|
44
|
+
return {
|
|
45
|
+
base,
|
|
46
|
+
resource: `${base}${deps.path}`,
|
|
47
|
+
issuer: `${base}${host.basePath}`
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The protected-resource metadata URL a challenge names. */
|
|
51
|
+
function metadataUrl(base, path) {
|
|
52
|
+
return `${base}/.well-known/oauth-protected-resource${path}`;
|
|
53
|
+
}
|
|
54
|
+
/** The refusal an unauthenticated MCP request gets: a 401 naming where to find the authorization server. */
|
|
55
|
+
function challenge(c, deps, detail) {
|
|
56
|
+
const { base } = addresses(c, deps);
|
|
57
|
+
const response = pithyErrorHandler(new UnauthorizedError({
|
|
58
|
+
message: "Authentication required.",
|
|
59
|
+
action: "Authorize the MCP client against this application, then retry with its access token.",
|
|
60
|
+
detail
|
|
61
|
+
}), c);
|
|
62
|
+
response.headers.set("WWW-Authenticate", `Bearer resource_metadata="${metadataUrl(base, deps.path)}", scope="mcp"`);
|
|
63
|
+
return response;
|
|
64
|
+
}
|
|
65
|
+
function claim(payload, name) {
|
|
66
|
+
const value = payload[name];
|
|
67
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Verify the caller, or answer the refusal. **Identity only — never permission.** The token proves who and through
|
|
71
|
+
* which client; it is checked for its signature, issuer, audience and expiry, for a consent still on record, for a
|
|
72
|
+
* session still live, and for an account in good standing. What the caller may *do* is never read off it.
|
|
73
|
+
*/
|
|
74
|
+
async function verifyCaller(c, deps) {
|
|
75
|
+
const bearer = /^Bearer\s+(.+)$/i.exec(c.req.header("authorization") ?? "")?.[1]?.trim();
|
|
76
|
+
if (!bearer) return challenge(c, deps, "no bearer token on the MCP request");
|
|
77
|
+
const host = deps.host();
|
|
78
|
+
const instance = await host.instance(c);
|
|
79
|
+
const { resource, issuer } = addresses(c, deps);
|
|
80
|
+
let payload;
|
|
81
|
+
try {
|
|
82
|
+
payload = await verifyJwsAccessToken(bearer, {
|
|
83
|
+
jwksFetch: async () => await providerApi(instance).getJwks(),
|
|
84
|
+
verifyOptions: {
|
|
85
|
+
audience: resource,
|
|
86
|
+
issuer
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
} catch {
|
|
90
|
+
return challenge(c, deps, "the MCP access token did not verify for this resource");
|
|
91
|
+
}
|
|
92
|
+
const userId = claim(payload, "sub");
|
|
93
|
+
const sessionId = claim(payload, "sid");
|
|
94
|
+
const clientId = claim(payload, "azp") ?? claim(payload, "client_id");
|
|
95
|
+
if (!userId || !sessionId || !clientId) return challenge(c, deps, "the MCP access token names no user, session or client");
|
|
96
|
+
const adapter = await adapterOf(instance);
|
|
97
|
+
if (!await adapter.findOne({
|
|
98
|
+
model: "oauthConsent",
|
|
99
|
+
where: [{
|
|
100
|
+
field: "clientId",
|
|
101
|
+
value: clientId
|
|
102
|
+
}, {
|
|
103
|
+
field: "userId",
|
|
104
|
+
value: userId
|
|
105
|
+
}]
|
|
106
|
+
})) return challenge(c, deps, `client ${clientId} holds no consent from user ${userId}`);
|
|
107
|
+
const session = await adapter.findOne({
|
|
108
|
+
model: "session",
|
|
109
|
+
where: [{
|
|
110
|
+
field: "id",
|
|
111
|
+
value: sessionId
|
|
112
|
+
}]
|
|
113
|
+
});
|
|
114
|
+
const now = /* @__PURE__ */ new Date();
|
|
115
|
+
if (!session || new Date(session.expiresAt).getTime() <= now.getTime()) return challenge(c, deps, `session ${sessionId} the token was minted under has ended`);
|
|
116
|
+
const refusal = await lifecycleRefusalFor(authDatabase(resolveDb(c.env, host.database)), userId, null, now);
|
|
117
|
+
if (refusal) throw refusal;
|
|
118
|
+
const auth = AuthContext.parse({
|
|
119
|
+
userId,
|
|
120
|
+
sessionId,
|
|
121
|
+
scopes: [],
|
|
122
|
+
locale: null
|
|
123
|
+
});
|
|
124
|
+
c.set("auth", auth);
|
|
125
|
+
const acting = await c.var.actingOrganization();
|
|
126
|
+
const roleAllows = acting === null ? null : (power) => acting.roleAllows(power);
|
|
127
|
+
if (!await floorAdmits(deps.floor, {
|
|
128
|
+
roleAllows,
|
|
129
|
+
entitlements: async () => grantedEntitlementKeys(await c.var.entitlements.list(), now)
|
|
130
|
+
})) throw new ForbiddenError({
|
|
131
|
+
message: "Your account cannot connect an agent to this application.",
|
|
132
|
+
detail: `user ${userId} is below the MCP endpoint's floor`
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
auth,
|
|
136
|
+
clientId,
|
|
137
|
+
tenant: acting?.organizationId ?? null,
|
|
138
|
+
roleAllows
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The MCP endpoint's guard: the caller verified, or the refusal. A guard rather than a step inside the handler, so it
|
|
143
|
+
* runs before the body is validated — an unauthenticated client gets the challenge that names the authorization
|
|
144
|
+
* server, whatever it sent, and learns nothing about which bodies are well-formed.
|
|
145
|
+
*/
|
|
146
|
+
function mcpCallerGuard(deps) {
|
|
147
|
+
return async (c, next) => {
|
|
148
|
+
const receivedAt = Date.now();
|
|
149
|
+
const caller = await verifyCaller(c, deps);
|
|
150
|
+
if (caller instanceof Response) return caller;
|
|
151
|
+
callers.set(c.req.raw, {
|
|
152
|
+
...caller,
|
|
153
|
+
receivedAt
|
|
154
|
+
});
|
|
155
|
+
await next();
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** What a request's tool-call row and its route's rows are joined by, and where the call came from. */
|
|
159
|
+
function correlationOf(c) {
|
|
160
|
+
return {
|
|
161
|
+
requestId: c.req.header("cf-ray") ?? crypto.randomUUID(),
|
|
162
|
+
ip: c.req.header("cf-connecting-ip") ?? null,
|
|
163
|
+
userAgent: c.req.header("user-agent") ?? null
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** The correlation, as the headers the dispatched request carries to the route. */
|
|
167
|
+
function correlationHeaders(correlation) {
|
|
168
|
+
return {
|
|
169
|
+
"cf-ray": correlation.requestId,
|
|
170
|
+
...correlation.ip === null ? {} : { "cf-connecting-ip": correlation.ip },
|
|
171
|
+
...correlation.userAgent === null ? {} : { "user-agent": correlation.userAgent }
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** One tool call, through the whole app, as the caller. */
|
|
175
|
+
async function callTool(c, deps, caller, correlation, tool, args) {
|
|
176
|
+
let request;
|
|
177
|
+
try {
|
|
178
|
+
request = dispatchRequest(new URL(c.req.url).origin, tool, args, caller.auth, correlationHeaders(correlation));
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (!(error instanceof PithyError)) throw error;
|
|
181
|
+
const body = { error: HttpError.encode(error.payload) };
|
|
182
|
+
return {
|
|
183
|
+
status: error.payload.status,
|
|
184
|
+
body,
|
|
185
|
+
bytes: new TextEncoder().encode(JSON.stringify(body)).byteLength
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
let executionCtx;
|
|
189
|
+
try {
|
|
190
|
+
executionCtx = c.executionCtx;
|
|
191
|
+
} catch {
|
|
192
|
+
executionCtx = void 0;
|
|
193
|
+
}
|
|
194
|
+
return dispatchedOutcome(await deps.app().fetch(request, c.env, executionCtx));
|
|
195
|
+
}
|
|
196
|
+
/** Who a tool-call row names: the caller, and the client's name as it registered itself. */
|
|
197
|
+
async function toolCallActor(c, deps, caller) {
|
|
198
|
+
const client = await (await adapterOf(await deps.host().instance(c))).findOne({
|
|
199
|
+
model: "oauthClient",
|
|
200
|
+
where: [{
|
|
201
|
+
field: "clientId",
|
|
202
|
+
value: caller.clientId
|
|
203
|
+
}]
|
|
204
|
+
});
|
|
205
|
+
return {
|
|
206
|
+
userId: caller.auth.userId,
|
|
207
|
+
sessionId: caller.auth.sessionId,
|
|
208
|
+
clientId: caller.clientId,
|
|
209
|
+
clientReportedName: client?.name ?? null,
|
|
210
|
+
tenant: caller.tenant
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/** Write the row for one tool call. Never fails the call. */
|
|
214
|
+
function auditToolCall(c, deps, caller, correlation, tool, result) {
|
|
215
|
+
const durationMs = Date.now() - caller.receivedAt;
|
|
216
|
+
return recordToolCall(c.var.emit, async () => toolCallEvent({
|
|
217
|
+
actor: await toolCallActor(c, deps, caller),
|
|
218
|
+
correlation,
|
|
219
|
+
tool,
|
|
220
|
+
durationMs,
|
|
221
|
+
result
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
/** One tool call, made and recorded. */
|
|
225
|
+
async function auditedCall(c, deps, caller, correlation, tool, raw) {
|
|
226
|
+
const args = toolArguments(raw);
|
|
227
|
+
const classed = argumentClass(tool.path, args);
|
|
228
|
+
let outcome;
|
|
229
|
+
try {
|
|
230
|
+
outcome = await callTool(c, deps, caller, correlation, tool, args);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
await auditToolCall(c, deps, caller, correlation, tool.name, {
|
|
233
|
+
kind: "answered",
|
|
234
|
+
status: 500,
|
|
235
|
+
responseBytes: 0,
|
|
236
|
+
arguments: classed
|
|
237
|
+
});
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
await auditToolCall(c, deps, caller, correlation, tool.name, {
|
|
241
|
+
kind: "answered",
|
|
242
|
+
status: outcome.status,
|
|
243
|
+
responseBytes: outcome.bytes,
|
|
244
|
+
arguments: classed
|
|
245
|
+
});
|
|
246
|
+
return outcome;
|
|
247
|
+
}
|
|
248
|
+
/** Emit one consent event. Never fatal: the audit seam swallows its own failures. */
|
|
249
|
+
async function audit(c, event) {
|
|
250
|
+
await c.var.emit({
|
|
251
|
+
actorType: "user",
|
|
252
|
+
actorId: c.var.auth?.userId ?? null,
|
|
253
|
+
sessionId: c.var.auth?.sessionId ?? null,
|
|
254
|
+
ip: c.req.header("cf-connecting-ip") ?? null,
|
|
255
|
+
userAgent: c.req.header("user-agent") ?? null,
|
|
256
|
+
...event
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Hand the decision to the provider's own consent endpoint, as the browser's request — its session credential and
|
|
261
|
+
* its origin — so every check the provider makes on a consent runs here unchanged. It needs the request itself,
|
|
262
|
+
* which a direct `api` call does not carry.
|
|
263
|
+
*/
|
|
264
|
+
async function decide(c, deps, instance, body) {
|
|
265
|
+
const { issuer } = addresses(c, deps);
|
|
266
|
+
const headers = new Headers(c.req.raw.headers);
|
|
267
|
+
headers.delete("content-length");
|
|
268
|
+
headers.set("content-type", "application/json");
|
|
269
|
+
const response = await instance.handler(new Request(`${issuer}/oauth2/consent`, {
|
|
270
|
+
method: "POST",
|
|
271
|
+
headers,
|
|
272
|
+
body: JSON.stringify(body)
|
|
273
|
+
}));
|
|
274
|
+
const decided = await response.json().catch(() => ({}));
|
|
275
|
+
if (!response.ok || typeof decided.url !== "string") throw new ValidationError({
|
|
276
|
+
message: "This authorization request could not be completed. Start again from the application.",
|
|
277
|
+
detail: `the provider answered the consent with ${response.status}`
|
|
278
|
+
});
|
|
279
|
+
return { url: decided.url };
|
|
280
|
+
}
|
|
281
|
+
/** The signed authorization query, verified, as parameters. */
|
|
282
|
+
async function signedQuery(instance, raw) {
|
|
283
|
+
const query = raw.startsWith("?") ? raw.slice(1) : raw;
|
|
284
|
+
const secret = (await instance.$context).secret;
|
|
285
|
+
if (!await verifyOAuthQueryParams(query, secret)) throw new ValidationError({
|
|
286
|
+
message: "This authorization request has expired. Start again from the application.",
|
|
287
|
+
detail: "the consent screen's oauth_query did not verify or has expired"
|
|
288
|
+
});
|
|
289
|
+
return new URLSearchParams(query);
|
|
290
|
+
}
|
|
291
|
+
/** The caller's role, as a `ToolCaller` reads it. */
|
|
292
|
+
async function roleOf(c) {
|
|
293
|
+
const acting = await c.var.actingOrganization();
|
|
294
|
+
return acting === null ? null : (power) => acting.roleAllows(power);
|
|
295
|
+
}
|
|
296
|
+
/** Register every route. */
|
|
297
|
+
function registerMcpRoutes(app, deps) {
|
|
298
|
+
const { path } = deps;
|
|
299
|
+
const csrf = requireSameOrigin();
|
|
300
|
+
const protectedResource = (c) => {
|
|
301
|
+
const { resource, issuer } = addresses(c, deps);
|
|
302
|
+
return c.json({
|
|
303
|
+
resource,
|
|
304
|
+
authorization_servers: [issuer],
|
|
305
|
+
scopes_supported: [...MCP_SCOPES],
|
|
306
|
+
bearer_methods_supported: ["header"],
|
|
307
|
+
resource_name: "This application's MCP endpoint"
|
|
308
|
+
});
|
|
309
|
+
};
|
|
310
|
+
const protectedResourceSpec = describeRoute({
|
|
311
|
+
summary: "Name the authorization server for the MCP endpoint.",
|
|
312
|
+
description: "RFC 9728 protected-resource metadata. Where an MCP client starts, from the endpoint's URL alone.",
|
|
313
|
+
verification: "public",
|
|
314
|
+
responses: { 200: ProtectedResourceMetadata }
|
|
315
|
+
});
|
|
316
|
+
app.get(`/.well-known/oauth-protected-resource${path}`, protectedResourceSpec, protectedResource);
|
|
317
|
+
app.get("/.well-known/oauth-protected-resource", protectedResourceSpec, protectedResource);
|
|
318
|
+
const serverMetadata = async (c) => {
|
|
319
|
+
const metadata = await providerApi(await deps.host().instance(c)).getOAuthServerConfig();
|
|
320
|
+
return c.json(metadata);
|
|
321
|
+
};
|
|
322
|
+
const serverMetadataSpec = describeRoute({
|
|
323
|
+
summary: "Describe the authorization server that mints MCP tokens.",
|
|
324
|
+
description: "RFC 8414 authorization-server metadata, at the address its issuer implies.",
|
|
325
|
+
verification: "public",
|
|
326
|
+
responses: { 200: AuthorizationServerMetadata }
|
|
327
|
+
});
|
|
328
|
+
app.get(`/.well-known/oauth-authorization-server${deps.host().basePath}`, serverMetadataSpec, serverMetadata);
|
|
329
|
+
app.get("/.well-known/oauth-authorization-server", serverMetadataSpec, serverMetadata);
|
|
330
|
+
app.post(path, describeRoute({
|
|
331
|
+
summary: "Serve the app's MCP tools to an agent acting as a user.",
|
|
332
|
+
description: "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.",
|
|
333
|
+
verification: "bearer",
|
|
334
|
+
responses: {
|
|
335
|
+
200: RpcResponse,
|
|
336
|
+
202: { description: "A notification, accepted. No body." }
|
|
337
|
+
}
|
|
338
|
+
}), mcpCallerGuard(deps), validate("json", McpRequestBody), async (c) => {
|
|
339
|
+
const caller = callers.get(c.req.raw);
|
|
340
|
+
if (caller === void 0) return challenge(c, deps, "the MCP request reached its handler unverified");
|
|
341
|
+
const correlation = correlationOf(c);
|
|
342
|
+
const reply = await answer(c.req.valid("json"), {
|
|
343
|
+
server: {
|
|
344
|
+
name: "pithy",
|
|
345
|
+
version: PACKAGE_VERSION
|
|
346
|
+
},
|
|
347
|
+
tools: async () => offeredTools(deps.tools(), {
|
|
348
|
+
roleAllows: caller.roleAllows,
|
|
349
|
+
scopes: caller.auth.scopes
|
|
350
|
+
}),
|
|
351
|
+
call: (tool, args) => auditedCall(c, deps, caller, correlation, tool, args),
|
|
352
|
+
refused: (name) => auditToolCall(c, deps, caller, correlation, requestedToolName(name), {
|
|
353
|
+
kind: "refused",
|
|
354
|
+
reason: deps.tools().some((tool) => tool.name === name) ? "withheld" : "unknown"
|
|
355
|
+
})
|
|
356
|
+
});
|
|
357
|
+
if (reply === null) return c.body(null, 202);
|
|
358
|
+
return c.json(reply);
|
|
359
|
+
});
|
|
360
|
+
app.on(["GET", "DELETE"], path, describeRoute({
|
|
361
|
+
summary: "Refuse to open an event stream or end a session on the MCP endpoint.",
|
|
362
|
+
description: "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`.",
|
|
363
|
+
verification: "public",
|
|
364
|
+
responses: { 405: { description: "Only POST is served here." } }
|
|
365
|
+
}), (c) => c.body(null, 405, { Allow: "POST" }));
|
|
366
|
+
app.get(`${path}/consent`, describeRoute({
|
|
367
|
+
summary: "Show what an application asking to act as you will be able to do.",
|
|
368
|
+
description: "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.",
|
|
369
|
+
verification: ["bearer", "session"],
|
|
370
|
+
responses: { 200: ConsentView }
|
|
371
|
+
}), requireAuth(), validate("query", ConsentQuery), async (c) => {
|
|
372
|
+
const instance = await deps.host().instance(c);
|
|
373
|
+
const query = await signedQuery(instance, c.req.valid("query").oauth_query);
|
|
374
|
+
const clientId = query.get("client_id") ?? "";
|
|
375
|
+
const client = await (await adapterOf(instance)).findOne({
|
|
376
|
+
model: "oauthClient",
|
|
377
|
+
where: [{
|
|
378
|
+
field: "clientId",
|
|
379
|
+
value: clientId
|
|
380
|
+
}]
|
|
381
|
+
});
|
|
382
|
+
if (!client) throw new NotFoundError({
|
|
383
|
+
message: "No such application.",
|
|
384
|
+
detail: `client ${clientId}`
|
|
385
|
+
});
|
|
386
|
+
const caller = {
|
|
387
|
+
roleAllows: await roleOf(c),
|
|
388
|
+
scopes: c.var.auth?.scopes ?? []
|
|
389
|
+
};
|
|
390
|
+
const view = consentView({
|
|
391
|
+
client: {
|
|
392
|
+
id: clientId,
|
|
393
|
+
verifiedHost: verifiedHost({
|
|
394
|
+
clientId,
|
|
395
|
+
clientDiscoveryId: client.clientDiscoveryId
|
|
396
|
+
}),
|
|
397
|
+
reportedName: client.name ?? null,
|
|
398
|
+
reportedUri: client.uri ?? null,
|
|
399
|
+
redirectUri: query.get("redirect_uri") ?? ""
|
|
400
|
+
},
|
|
401
|
+
tools: deps.tools(),
|
|
402
|
+
caller,
|
|
403
|
+
requestedScopes: (query.get("scope") ?? "").split(" ").filter((scope) => scope.length > 0)
|
|
404
|
+
});
|
|
405
|
+
return c.json(view);
|
|
406
|
+
});
|
|
407
|
+
app.post(`${path}/consent`, describeRoute({
|
|
408
|
+
summary: "Let an application act as you in this application, or refuse it.",
|
|
409
|
+
description: "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.",
|
|
410
|
+
verification: ["bearer", "session"],
|
|
411
|
+
responses: { 200: ConsentDecision }
|
|
412
|
+
}), requireAuth(), csrf, validate("json", ConsentBody), async (c) => {
|
|
413
|
+
const { oauth_query, accept } = c.req.valid("json");
|
|
414
|
+
const instance = await deps.host().instance(c);
|
|
415
|
+
const query = await signedQuery(instance, oauth_query);
|
|
416
|
+
const redirect = (await decide(c, deps, instance, {
|
|
417
|
+
accept,
|
|
418
|
+
oauth_query: query.toString()
|
|
419
|
+
})).url;
|
|
420
|
+
const clientId = query.get("client_id") ?? "";
|
|
421
|
+
await audit(c, {
|
|
422
|
+
action: accept ? AuthAuditActions.mcpGrantApproved : AuthAuditActions.mcpGrantDenied,
|
|
423
|
+
outcome: "success",
|
|
424
|
+
resourceType: "mcp_client",
|
|
425
|
+
resourceId: clientId,
|
|
426
|
+
metadata: {
|
|
427
|
+
redirectUri: query.get("redirect_uri") ?? null,
|
|
428
|
+
scope: query.get("scope") ?? null
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
return c.json({ redirect });
|
|
432
|
+
});
|
|
433
|
+
app.get(`${path}/connections`, describeRoute({
|
|
434
|
+
summary: "List the applications acting as you.",
|
|
435
|
+
description: "What you approved, when, and where each sends its tokens. Revoking is the only narrowing there is.",
|
|
436
|
+
verification: ["bearer", "session"],
|
|
437
|
+
responses: { 200: ConnectedApplications }
|
|
438
|
+
}), requireAuth(), async (c) => {
|
|
439
|
+
const userId = c.var.auth?.userId ?? "";
|
|
440
|
+
const adapter = await adapterOf(await deps.host().instance(c));
|
|
441
|
+
const consents = await adapter.findMany({
|
|
442
|
+
model: "oauthConsent",
|
|
443
|
+
where: [{
|
|
444
|
+
field: "userId",
|
|
445
|
+
value: userId
|
|
446
|
+
}]
|
|
447
|
+
});
|
|
448
|
+
const applications = [];
|
|
449
|
+
for (const consent of consents) {
|
|
450
|
+
const client = await adapter.findOne({
|
|
451
|
+
model: "oauthClient",
|
|
452
|
+
where: [{
|
|
453
|
+
field: "clientId",
|
|
454
|
+
value: consent.clientId
|
|
455
|
+
}]
|
|
456
|
+
});
|
|
457
|
+
const uris = client?.redirectUris;
|
|
458
|
+
applications.push({
|
|
459
|
+
clientId: consent.clientId,
|
|
460
|
+
verifiedHost: verifiedHost({
|
|
461
|
+
clientId: consent.clientId,
|
|
462
|
+
clientDiscoveryId: client?.clientDiscoveryId
|
|
463
|
+
}),
|
|
464
|
+
reportedName: client?.name ?? null,
|
|
465
|
+
redirectUris: Array.isArray(uris) ? uris : typeof uris === "string" ? redirectList(uris) : [],
|
|
466
|
+
approvedAt: new Date(consent.createdAt).toISOString()
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
applications.sort((a, b) => b.approvedAt.localeCompare(a.approvedAt));
|
|
470
|
+
return c.json({ applications });
|
|
471
|
+
});
|
|
472
|
+
app.delete(`${path}/connections/:clientId`, describeRoute({
|
|
473
|
+
summary: "Revoke an application acting as you.",
|
|
474
|
+
description: "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.",
|
|
475
|
+
verification: ["bearer", "session"],
|
|
476
|
+
responses: { 200: RevokedApplication }
|
|
477
|
+
}), requireAuth(), csrf, validate("param", ConnectionParam), async (c) => {
|
|
478
|
+
const userId = c.var.auth?.userId ?? "";
|
|
479
|
+
const { clientId } = c.req.valid("param");
|
|
480
|
+
const adapter = await adapterOf(await deps.host().instance(c));
|
|
481
|
+
const where = [{
|
|
482
|
+
field: "clientId",
|
|
483
|
+
value: clientId
|
|
484
|
+
}, {
|
|
485
|
+
field: "userId",
|
|
486
|
+
value: userId
|
|
487
|
+
}];
|
|
488
|
+
if ((await adapter.findMany({
|
|
489
|
+
model: "oauthConsent",
|
|
490
|
+
where
|
|
491
|
+
})).length === 0) throw new NotFoundError({
|
|
492
|
+
message: "No such connected application.",
|
|
493
|
+
detail: `client ${clientId} for ${userId}`
|
|
494
|
+
});
|
|
495
|
+
await adapter.deleteMany({
|
|
496
|
+
model: "oauthConsent",
|
|
497
|
+
where
|
|
498
|
+
});
|
|
499
|
+
await adapter.deleteMany({
|
|
500
|
+
model: "oauthRefreshToken",
|
|
501
|
+
where
|
|
502
|
+
});
|
|
503
|
+
await adapter.deleteMany({
|
|
504
|
+
model: "oauthAccessToken",
|
|
505
|
+
where
|
|
506
|
+
});
|
|
507
|
+
await audit(c, {
|
|
508
|
+
action: AuthAuditActions.mcpGrantRevoked,
|
|
509
|
+
outcome: "success",
|
|
510
|
+
resourceType: "mcp_client",
|
|
511
|
+
resourceId: clientId
|
|
512
|
+
});
|
|
513
|
+
return c.json({ revoked: true });
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
517
|
+
export { registerMcpRoutes };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
/** The MCP endpoint's body: one JSON-RPC message. */
|
|
5
|
+
export declare const McpRequestBody: z.ZodObject<{
|
|
6
|
+
jsonrpc: z.ZodLiteral<"2.0">;
|
|
7
|
+
id: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
8
|
+
method: z.ZodString;
|
|
9
|
+
params: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
/** The consent screen's question: the signed authorization query the provider redirected it with. */
|
|
12
|
+
export declare const ConsentQuery: z.ZodObject<{
|
|
13
|
+
oauth_query: z.ZodString;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
/** The consent decision: one, for the whole request. */
|
|
16
|
+
export declare const ConsentBody: z.ZodObject<{
|
|
17
|
+
oauth_query: z.ZodString;
|
|
18
|
+
accept: z.ZodBoolean;
|
|
19
|
+
}, z.core.$strict>;
|
|
20
|
+
/** Which connected application. */
|
|
21
|
+
export declare const ConnectionParam: z.ZodObject<{
|
|
22
|
+
clientId: z.ZodString;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
//# sourceMappingURL=schemas.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/schemas.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,qDAAqD;AACrD,eAAO,MAAM,cAAc;;;;;iBAAa,CAAC;AAEzC,qGAAqG;AACrG,eAAO,MAAM,YAAY;;iBAQ8C,CAAC;AAExE,wDAAwD;AACxD,eAAO,MAAM,WAAW;;;kBAUqE,CAAC;AAE9F,mCAAmC;AACnC,eAAO,MAAM,eAAe;;iBAEa,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { RpcMessage } from "../rpc.js";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/mcp/http/schemas.ts
|
|
6
|
+
/** The MCP endpoint's body: one JSON-RPC message. */
|
|
7
|
+
const McpRequestBody = RpcMessage;
|
|
8
|
+
/** The consent screen's question: the signed authorization query the provider redirected it with. */
|
|
9
|
+
const ConsentQuery = z.object({ oauth_query: z.string().min(1).max(8192).describe("The query string the authorization server redirected the screen with, signed by it.") }).describe("Which authorization request the consent screen is about.");
|
|
10
|
+
/** The consent decision: one, for the whole request. */
|
|
11
|
+
const ConsentBody = z.object({
|
|
12
|
+
oauth_query: z.string().min(1).max(8192).describe("The query string the authorization server redirected the screen with, signed by it."),
|
|
13
|
+
accept: z.boolean().describe("Whether you let this client act as you in this application.")
|
|
14
|
+
}).strict().describe("One decision: let this client act as you, or not. Nothing in it is selectable.");
|
|
15
|
+
/** Which connected application. */
|
|
16
|
+
const ConnectionParam = z.object({ clientId: z.string().min(1).max(256).describe("The client's id.") }).describe("One connected application.");
|
|
17
|
+
//#endregion
|
|
18
|
+
export { ConnectionParam, ConsentBody, ConsentQuery, McpRequestBody };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { Capability } from "@pithy-sh/core/src/capability/capability";
|
|
4
|
+
import type { McpWiring } from "./host";
|
|
5
|
+
/**
|
|
6
|
+
* How auth recognizes the MCP capability composed beside it, without importing it — the capability imports
|
|
7
|
+
* auth's guard, so the reverse import would be a cycle. A name and the one field auth reads.
|
|
8
|
+
*/
|
|
9
|
+
/** The MCP capability's name. */
|
|
10
|
+
export declare const MCP_CAPABILITY_NAME = "mcp";
|
|
11
|
+
/** Is this the MCP capability? */
|
|
12
|
+
export declare function isMcpCapability(capability: Capability): capability is Capability & {
|
|
13
|
+
readonly mcpWiring: McpWiring;
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=marker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"marker.d.ts","sourceRoot":"","sources":["../../src/mcp/marker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0CAA0C,CAAC;AAC3E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAExC;;;GAGG;AAEH,iCAAiC;AACjC,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AAEzC,kCAAkC;AAClC,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,UAAU,GAAG;IAAE,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAA;CAAE,CAEpH"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
//#region src/mcp/marker.ts
|
|
4
|
+
/**
|
|
5
|
+
* How auth recognizes the MCP capability composed beside it, without importing it — the capability imports
|
|
6
|
+
* auth's guard, so the reverse import would be a cycle. A name and the one field auth reads.
|
|
7
|
+
*/
|
|
8
|
+
/** The MCP capability's name. */
|
|
9
|
+
const MCP_CAPABILITY_NAME = "mcp";
|
|
10
|
+
/** Is this the MCP capability? */
|
|
11
|
+
function isMcpCapability(capability) {
|
|
12
|
+
return capability.name === "mcp" && "mcpWiring" in capability;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { MCP_CAPABILITY_NAME, isMcpCapability };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { type ClientDiscovery } from "@better-auth/oauth-provider";
|
|
4
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
5
|
+
/**
|
|
6
|
+
* The authorization server the MCP capability composes into the auth instance (`docs/AGENT-ACCESS.md` §4).
|
|
7
|
+
*
|
|
8
|
+
* **Composed, not written.** Better Auth's OAuth 2.1 provider turns the instance into an authorization server:
|
|
9
|
+
* dynamic client registration, PKCE, resource-bound JWT access tokens signed by the JWKS the `jwt` plugin already
|
|
10
|
+
* keeps, refresh tokens, and the RFC 8414 metadata a client discovers it by. Beside registration, this module plugs in
|
|
11
|
+
* the Client ID Metadata Document discovery from `@better-auth/cimd` (`./clientMetadata.ts`), so a client may also be
|
|
12
|
+
* known by the URL of a document it publishes. That one extension adds the registration path the MCP specification
|
|
13
|
+
* prefers; everything else this module adds is policy, and every line of that narrows the provider's defaults.
|
|
14
|
+
*
|
|
15
|
+
* **One scope, and it is not a permission.** The consent is informational (§4.3): one decision, *let this client
|
|
16
|
+
* act as you in this application*, so the token carries no permission selection. {@link MCP_SCOPE} is the only
|
|
17
|
+
* scope a client may hold beside `offline_access`, which buys a refresh token and nothing else. The role is the only
|
|
18
|
+
* authority over what a call may do, and the routes enforce it, so there is no scope vocabulary to ask for.
|
|
19
|
+
*
|
|
20
|
+
* **The token binds the resource and the user, and nothing else.** The one resource is this Worker's MCP endpoint,
|
|
21
|
+
* seeded as the provider's only resource and linked to every client at registration, so a token minted for it is a
|
|
22
|
+
* JWT whose `aud` is that URL and cannot be replayed at another. `sub` is the user and `sid` the session they
|
|
23
|
+
* consented in; the MCP endpoint refuses a token whose session has ended.
|
|
24
|
+
*
|
|
25
|
+
* **No client credentials grant.** A token here acts *as somebody*; a machine-to-machine token acts as nobody, which
|
|
26
|
+
* is the control-plane seam's job (§1), not this one's.
|
|
27
|
+
*
|
|
28
|
+
* **The consent screen every time.** The provider skips consent for a client that already holds it; this kit asks
|
|
29
|
+
* again, so a client asking for access again is a new decision the user can see, and an audited one. A client asking
|
|
30
|
+
* to be shown nothing (`prompt=none`) is refused with `consent_required` before the provider runs, because the
|
|
31
|
+
* provider would answer it with a code whenever a consent is on record.
|
|
32
|
+
*/
|
|
33
|
+
/** The one OAuth scope this server issues. A constant, not a vocabulary. */
|
|
34
|
+
export declare const MCP_SCOPE = "mcp";
|
|
35
|
+
/** The scopes a client may request: {@link MCP_SCOPE}, and `offline_access` for a refresh token. */
|
|
36
|
+
export declare const MCP_SCOPES: readonly ["mcp", "offline_access"];
|
|
37
|
+
/**
|
|
38
|
+
* The provider's tables, under this capability's prefix. Better Auth names a plugin's tables after its models;
|
|
39
|
+
* every table this kit provides is `pithy_<capability>_<table>`, so each one is renamed here, once.
|
|
40
|
+
*/
|
|
41
|
+
export declare const MCP_MODEL_NAMES: {
|
|
42
|
+
readonly oauthClient: "pithyMcpClients";
|
|
43
|
+
readonly oauthResource: "pithyMcpResources";
|
|
44
|
+
readonly oauthClientResource: "pithyMcpClientResources";
|
|
45
|
+
readonly oauthRefreshToken: "pithyMcpRefreshTokens";
|
|
46
|
+
readonly oauthAccessToken: "pithyMcpAccessTokens";
|
|
47
|
+
readonly oauthConsent: "pithyMcpConsents";
|
|
48
|
+
readonly oauthClientAssertion: "pithyMcpClientAssertions";
|
|
49
|
+
};
|
|
50
|
+
/** The plugin id of the kit's consent-every-time hook. */
|
|
51
|
+
export declare const MCP_CONSENT_PLUGIN_ID = "pithy-mcp-consent";
|
|
52
|
+
/** What the provider needs to know about this Worker. */
|
|
53
|
+
export interface McpProviderSettings {
|
|
54
|
+
/** The MCP endpoint's absolute URL: the one resource, and every token's audience. */
|
|
55
|
+
readonly resource: string;
|
|
56
|
+
/** The scaffolded screen's path, which is both the sign-in and the consent page for this flow. */
|
|
57
|
+
readonly consentPage: string;
|
|
58
|
+
/** How a client whose id is an HTTPS URL is resolved from the metadata document served there. */
|
|
59
|
+
readonly clientDiscovery: ClientDiscovery;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The `prompt` an authorize request runs with — always including `consent` — or `null` when the client asked for
|
|
63
|
+
* `none`. `none` asks for a grant with no screen, and this server has no such grant to give.
|
|
64
|
+
*/
|
|
65
|
+
export declare function consentPrompt(prompt: unknown): string | null;
|
|
66
|
+
/**
|
|
67
|
+
* The provider plugin and the kit's consent hook, for one Worker's MCP endpoint.
|
|
68
|
+
*
|
|
69
|
+
* Typed as plain `BetterAuthPlugin`s, the way the kit's translator and sign-in gate are. Every reader takes them as
|
|
70
|
+
* that already: the instance's plugin list is the adopter's `BetterAuthPlugin[]` with these appended, and the
|
|
71
|
+
* migration plan reads a `BetterAuthPlugin[]`. So the widening erases nothing a caller sees, and it keeps the
|
|
72
|
+
* provider's inferred type out of the shipped declaration, which would otherwise name `better-call` internals a
|
|
73
|
+
* declaration cannot reach.
|
|
74
|
+
*/
|
|
75
|
+
export declare function mcpAuthorizationServer(settings: McpProviderSettings): McpProviderPlugins;
|
|
76
|
+
/** The plugins {@link mcpAuthorizationServer} composes: the provider, then the consent hook. */
|
|
77
|
+
export type McpProviderPlugins = readonly [provider: BetterAuthPlugin, consent: BetterAuthPlugin];
|
|
78
|
+
//# sourceMappingURL=provider.d.ts.map
|