@vite-hub/auth 0.3.1 → 0.4.1
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 +49 -34
- package/dist/{abilities-DfAnFYwG.d.ts → abilities-CbmTAoS_.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-CqgBrBfR.js → ability-error-IeZQBr_-.js} +1 -1
- package/dist/agent.js +6 -5
- package/dist/{auth-instance-CR6b1W80.js → auth-instance-CmDogt4D.js} +20 -13
- package/dist/cli.js +1 -1
- package/dist/{console-runtime-DTopBP-x.d.ts → console-runtime-D2ai-Et5.d.ts} +1 -1
- package/dist/{console-runtime-J9_Vx9pT.js → console-runtime-_LrpyCYY.js} +2 -2
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -1
- package/dist/console.d.ts +1 -1
- package/dist/{database-options-BRNef9oy.js → database-options-DpOVjUti.js} +1 -1
- package/dist/{database-schema-options-ENuRMduM.js → database-schema-options-Sk-1Bvyu.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +3 -3
- package/dist/{definition-CqQMcDEK.js → definition-BCaLA9kW.js} +146 -8
- package/dist/{error-diagnostics-C8XtVz0i.js → error-diagnostics-Dymr-S_n.js} +40 -4
- package/dist/{events-ByzenEVj.js → events-DCfuicoo.js} +6 -14
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +3 -8
- package/dist/index.js +3 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +6 -858
- package/dist/mcp-config-DRRlCAWN.js +18 -0
- package/dist/mcp-token-CpxLyl_p.js +222 -0
- package/dist/mcp.d.ts +96 -85
- package/dist/mcp.js +3 -184
- package/dist/{members-D9lfaEO_.js → members-DdlsS8kJ.js} +5 -5
- package/dist/nuxt.d.ts +15 -2
- package/dist/nuxt.js +9 -12
- package/dist/{presets-BGZi6Dfu.d.ts → presets-CHndEv5i.d.ts} +3 -4
- package/dist/presets.d.ts +2 -2
- package/dist/presets.js +3 -13
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -1
- package/dist/runtime/empty-definition.d.ts +2 -1
- package/dist/runtime/empty-definition.js +2 -1
- package/dist/runtime/nuxt.js +2 -2
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/vue-nuxt.js +15 -7
- package/dist/schema.js +1 -1
- package/dist/server-BG_MFd4q.js +980 -0
- package/dist/{server-C0qnKN2W.d.ts → server-BM-RSf1T.d.ts} +76 -15
- package/dist/{server-bQGzVQ--.d.ts → server-C8TlOrSy.d.ts} +3 -3
- package/dist/server.d.ts +2 -2
- package/dist/server.js +3 -3
- package/dist/{session-cookies-BbH3UR2m.js → session-cookies-DVzjOKc7.js} +69 -5
- package/dist/{set-cookie-C8NOhdRE.js → set-cookie-DmqWq6kj.js} +1 -1
- package/dist/{shared-BwcdRGxD.js → shared-DRtfuFsV.js} +1 -1
- package/dist/{table-specs-8gq_FCaq.js → table-specs-CURphR3n.js} +1 -1
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-CNaeH2Fd.d.ts → types-CruflEFI.d.ts} +62 -43
- package/dist/{vite-CV400XXY.js → vite-Dy0Xhq4H.js} +195 -149
- package/dist/vite.d.ts +2 -1
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +4 -19
- package/dist/vue.js +6 -9
- package/package.json +9 -9
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
+
//#region src/mcp-config.ts
|
|
3
|
+
const mcpRegistrationPluginId = "vitehub-mcp-registration";
|
|
4
|
+
/**
|
|
5
|
+
* The resources of MCP OAuth: the Better Auth `oauthProvider()` with `resources` and JWT access tokens of `jwt()`, from
|
|
6
|
+
* `mcpOAuth()` or added by hand. Empty when the Auth has no MCP OAuth, also with `disableJwtPlugin`, whose access tokens
|
|
7
|
+
* are opaque. `verifyMcpRequest()` and `requireCaller()` both use this one rule.
|
|
8
|
+
*/
|
|
9
|
+
function mcpOAuthResources(plugins = []) {
|
|
10
|
+
const provider = plugins.find((plugin) => plugin.id === "oauth-provider")?.options;
|
|
11
|
+
if (!isRecord(provider) || !Array.isArray(provider.resources) || provider.disableJwtPlugin === true) return [];
|
|
12
|
+
if (!plugins.some((plugin) => plugin.id === "jwt")) return [];
|
|
13
|
+
return provider.resources.flatMap((entry) => typeof entry === "string" ? [entry] : isRecord(entry) && typeof entry.identifier === "string" ? [entry.identifier] : []);
|
|
14
|
+
}
|
|
15
|
+
/** True for a token in the JWS compact form (`header.payload.signature`), the form of an MCP OAuth access token. */
|
|
16
|
+
const isJwsToken = (token) => /^[\w-]+\.[\w-]+\.[\w-]+$/.test(token);
|
|
17
|
+
//#endregion
|
|
18
|
+
export { mcpOAuthResources as n, mcpRegistrationPluginId as r, isJwsToken as t };
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { l as findAccessPolicyPlugin } from "./members-DdlsS8kJ.js";
|
|
3
|
+
import { t as authForRequest } from "./auth-instance-CmDogt4D.js";
|
|
4
|
+
import { n as mcpOAuthResources } from "./mcp-config-DRRlCAWN.js";
|
|
5
|
+
import { defineErrors } from "@vite-hub/runtime";
|
|
6
|
+
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
7
|
+
//#region \0rolldown/runtime.js
|
|
8
|
+
var __defProp = Object.defineProperty;
|
|
9
|
+
var __exportAll = (all, no_symbols) => {
|
|
10
|
+
let target = {};
|
|
11
|
+
for (var name in all) __defProp(target, name, {
|
|
12
|
+
get: all[name],
|
|
13
|
+
enumerable: true
|
|
14
|
+
});
|
|
15
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
16
|
+
return target;
|
|
17
|
+
};
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/mcp-token.ts
|
|
20
|
+
var mcp_token_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
+
appAuth: () => appAuth,
|
|
22
|
+
baseScopes: () => baseScopes,
|
|
23
|
+
deleteUnusedMcpClients: () => deleteUnusedMcpClients,
|
|
24
|
+
mcpOAuthAuth: () => mcpOAuthAuth,
|
|
25
|
+
pathOf: () => pathOf,
|
|
26
|
+
stateOf: () => stateOf,
|
|
27
|
+
verifyAppAccessToken: () => verifyAppAccessToken,
|
|
28
|
+
verifyMcpRequest: () => verifyMcpRequest
|
|
29
|
+
});
|
|
30
|
+
const mcpErrors = /*#__PURE__*/ defineErrors({
|
|
31
|
+
docs: "https://vitehub.dev/docs/auth/diagnostics",
|
|
32
|
+
codes: {
|
|
33
|
+
AUTH_MCP_OAUTH_MISSING: {
|
|
34
|
+
why: "The Auth has no MCP OAuth: its plugins do not include `jwt()` and `oauthProvider()` with `resources`.",
|
|
35
|
+
fix: "Add `...mcpOAuth({ resource, loginPage })` from `vite-hub/auth/mcp` to the `plugins` of `defineAuth()`."
|
|
36
|
+
},
|
|
37
|
+
AUTH_MCP_TOKEN_MISSING: {
|
|
38
|
+
why: "The request has no `Authorization: Bearer` access token.",
|
|
39
|
+
fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
|
|
40
|
+
},
|
|
41
|
+
AUTH_MCP_TOKEN_INVALID: {
|
|
42
|
+
why: ({ reason }) => `The access token is not valid: ${reason}`,
|
|
43
|
+
fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again."
|
|
44
|
+
},
|
|
45
|
+
AUTH_MCP_CLEANUP_FAILED: {
|
|
46
|
+
why: "The Auth database could not list or delete OAuth clients.",
|
|
47
|
+
fix: "Read `error.cause` for the database error, then run the cleanup again."
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const baseScopes = [
|
|
52
|
+
"openid",
|
|
53
|
+
"profile",
|
|
54
|
+
"email",
|
|
55
|
+
"offline_access"
|
|
56
|
+
];
|
|
57
|
+
async function stateOf(auth) {
|
|
58
|
+
const context = await auth.$context;
|
|
59
|
+
const plugins = context.options.plugins ?? [];
|
|
60
|
+
const provider = plugins.find((plugin) => plugin.id === "oauth-provider")?.options;
|
|
61
|
+
const resources = mcpOAuthResources(plugins);
|
|
62
|
+
if (!resources.length) throw mcpErrors.AUTH_MCP_OAUTH_MISSING();
|
|
63
|
+
const jwtOptions = plugins.find((plugin) => plugin.id === "jwt")?.options;
|
|
64
|
+
const issuer = isRecord(jwtOptions) && isRecord(jwtOptions.jwt) && typeof jwtOptions.jwt.issuer === "string" ? jwtOptions.jwt.issuer : context.baseURL;
|
|
65
|
+
const scopes = isRecord(provider) && Array.isArray(provider.scopes) ? provider.scopes.filter((scope) => typeof scope === "string") : baseScopes;
|
|
66
|
+
return {
|
|
67
|
+
issuer: issuer.replace(/\/+$/, ""),
|
|
68
|
+
resources,
|
|
69
|
+
scopes
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
|
|
73
|
+
const appAuth = (request) => mcpOAuthAuth(authForRequest(request));
|
|
74
|
+
/** The app's Better Auth, as the MCP helpers read it. */
|
|
75
|
+
function mcpOAuthAuth(auth) {
|
|
76
|
+
return auth;
|
|
77
|
+
}
|
|
78
|
+
const clockToleranceSeconds = 30;
|
|
79
|
+
function banned(user) {
|
|
80
|
+
if (user.banned !== true) return false;
|
|
81
|
+
const expires = user.banExpires;
|
|
82
|
+
const until = expires instanceof Date ? expires.getTime() : typeof expires === "string" || typeof expires === "number" ? new Date(expires).getTime() : NaN;
|
|
83
|
+
return Number.isNaN(until) || until > Date.now();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
87
|
+
* authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
|
|
88
|
+
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
|
|
89
|
+
* session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
|
|
90
|
+
* use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
|
|
91
|
+
* access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
|
|
92
|
+
* bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
|
|
93
|
+
* any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
|
|
94
|
+
* bearer token and `AUTH_MCP_TOKEN_INVALID` for a token that fails a check. Throws `AUTH_MCP_OAUTH_MISSING` when the Auth has no `mcpOAuth()`.
|
|
95
|
+
*/
|
|
96
|
+
async function verifyMcpRequest(request, options = {}) {
|
|
97
|
+
const token = bearerToken(request.headers);
|
|
98
|
+
if (!token) return [mcpErrors.AUTH_MCP_TOKEN_MISSING(), void 0];
|
|
99
|
+
const auth = options.auth ?? appAuth(request);
|
|
100
|
+
const state = await stateOf(auth);
|
|
101
|
+
const url = new URL(request.url);
|
|
102
|
+
return await verifyToken(token, auth, state, options.resource ?? state.resources.find((entry) => new URL(entry).origin === url.origin && pathOf(entry) === url.pathname.replace(/\/+$/, "")), url.pathname);
|
|
103
|
+
}
|
|
104
|
+
/** The token of an `Authorization: Bearer` header. */
|
|
105
|
+
const bearerToken = (headers) => /^Bearer\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
|
|
106
|
+
/**
|
|
107
|
+
* Check an MCP access token for any `mcpOAuth()` resource at the origin of the request, for `requireCaller()`, which
|
|
108
|
+
* accepts the token on every route of the app.
|
|
109
|
+
*/
|
|
110
|
+
async function verifyAppAccessToken(token, origin, pathname, instance) {
|
|
111
|
+
const auth = mcpOAuthAuth(instance);
|
|
112
|
+
const state = await stateOf(auth);
|
|
113
|
+
return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
|
|
114
|
+
}
|
|
115
|
+
async function verifyToken(token, auth, state, resource, path) {
|
|
116
|
+
if (!resource?.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: `${path} is not a resource of \`mcpOAuth()\`.` }), void 0];
|
|
117
|
+
const jwks = await auth.api.getJwks();
|
|
118
|
+
const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
|
|
119
|
+
const algorithms = [...new Set(keys.flatMap((key) => typeof key.alg === "string" ? [key.alg] : []))];
|
|
120
|
+
if (!algorithms.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the Auth has no signing keys." }), void 0];
|
|
121
|
+
let payload;
|
|
122
|
+
try {
|
|
123
|
+
payload = await verifyJwsAccessToken(token, {
|
|
124
|
+
jwksFetch: async () => jwks,
|
|
125
|
+
verifyOptions: {
|
|
126
|
+
algorithms,
|
|
127
|
+
audience: typeof resource === "string" ? resource : [...resource],
|
|
128
|
+
clockTolerance: clockToleranceSeconds,
|
|
129
|
+
issuer: state.issuer,
|
|
130
|
+
requiredClaims: ["exp", "sub"]
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return [mcpErrors.AUTH_MCP_TOKEN_INVALID({
|
|
135
|
+
cause: error,
|
|
136
|
+
reason: error instanceof Error ? error.message : "the signature or a claim does not match."
|
|
137
|
+
}), void 0];
|
|
138
|
+
}
|
|
139
|
+
if (payload.cnf !== void 0) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "sender-constrained access tokens are not supported; use a bearer token." }), void 0];
|
|
140
|
+
const context = await auth.$context;
|
|
141
|
+
const user = await context.internalAdapter.findUserById(String(payload.sub));
|
|
142
|
+
if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the user does not exist or is banned." }), void 0];
|
|
143
|
+
const policy = findAccessPolicyPlugin(context.options.plugins);
|
|
144
|
+
if (policy && !await policy.allows(user, `mcp:${user.id}`)) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "`access.policy` or `VITEHUB_MEMBERS` does not allow the user." }), void 0];
|
|
145
|
+
const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
|
|
146
|
+
const client = clientId ? await context.adapter.findOne({
|
|
147
|
+
model: "oauthClient",
|
|
148
|
+
where: [{
|
|
149
|
+
field: "clientId",
|
|
150
|
+
value: clientId
|
|
151
|
+
}]
|
|
152
|
+
}) : void 0;
|
|
153
|
+
if (!clientId || !isRecord(client) || client.disabled) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the OAuth client does not exist or is disabled." }), void 0];
|
|
154
|
+
const scope = payload.scope;
|
|
155
|
+
const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
|
|
156
|
+
if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
|
|
157
|
+
const session = await context.adapter.findOne({
|
|
158
|
+
model: "session",
|
|
159
|
+
where: [{
|
|
160
|
+
field: "id",
|
|
161
|
+
value: payload.sid
|
|
162
|
+
}]
|
|
163
|
+
});
|
|
164
|
+
if (!isRecord(session) || !(session.expiresAt instanceof Date) || session.expiresAt.getTime() <= Date.now()) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the session does not exist or has expired." }), void 0];
|
|
165
|
+
}
|
|
166
|
+
return [void 0, {
|
|
167
|
+
clientId,
|
|
168
|
+
clientName: typeof client.name === "string" && client.name ? client.name : void 0,
|
|
169
|
+
scopes,
|
|
170
|
+
user
|
|
171
|
+
}];
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
|
|
175
|
+
* token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
|
|
176
|
+
* of deleted clients.
|
|
177
|
+
*/
|
|
178
|
+
async function deleteUnusedMcpClients(options = {}) {
|
|
179
|
+
const auth = options.auth ?? appAuth(new Request("http://localhost/"));
|
|
180
|
+
try {
|
|
181
|
+
const { adapter } = await auth.$context;
|
|
182
|
+
const cutoff = new Date(Date.now() - (options.olderThan ?? 864e5));
|
|
183
|
+
const clients = await adapter.findMany({
|
|
184
|
+
limit: options.limit ?? 500,
|
|
185
|
+
model: "oauthClient",
|
|
186
|
+
where: [{
|
|
187
|
+
field: "createdAt",
|
|
188
|
+
operator: "lt",
|
|
189
|
+
value: cutoff
|
|
190
|
+
}]
|
|
191
|
+
});
|
|
192
|
+
let deleted = 0;
|
|
193
|
+
for (const client of clients) {
|
|
194
|
+
if (!isRecord(client) || typeof client.clientId !== "string") continue;
|
|
195
|
+
const where = [{
|
|
196
|
+
field: "clientId",
|
|
197
|
+
value: client.clientId
|
|
198
|
+
}];
|
|
199
|
+
if ((await Promise.all([
|
|
200
|
+
"oauthConsent",
|
|
201
|
+
"oauthAccessToken",
|
|
202
|
+
"oauthRefreshToken"
|
|
203
|
+
].map((model) => adapter.count({
|
|
204
|
+
model,
|
|
205
|
+
where
|
|
206
|
+
})))).some((count) => count > 0)) continue;
|
|
207
|
+
await adapter.deleteMany({
|
|
208
|
+
model: "oauthClientResource",
|
|
209
|
+
where
|
|
210
|
+
});
|
|
211
|
+
deleted += await adapter.deleteMany({
|
|
212
|
+
model: "oauthClient",
|
|
213
|
+
where
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return [void 0, { deleted }];
|
|
217
|
+
} catch (error) {
|
|
218
|
+
return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
//#endregion
|
|
222
|
+
export { pathOf as a, mcp_token_exports as i, baseScopes as n, stateOf as o, deleteUnusedMcpClients as r, verifyMcpRequest as s, appAuth as t };
|
package/dist/mcp.d.ts
CHANGED
|
@@ -2,58 +2,10 @@ import { Result } from "@vite-hub/runtime";
|
|
|
2
2
|
import { BetterAuthPlugin } from "better-auth";
|
|
3
3
|
import { oauthProvider } from "@better-auth/oauth-provider";
|
|
4
4
|
import { jwt } from "better-auth/plugins";
|
|
5
|
-
//#region src/mcp.d.ts
|
|
6
|
-
|
|
7
|
-
type OAuthProviderOptions = Parameters<typeof oauthProvider>[0];
|
|
8
|
-
/** Options of {@link mcpOAuth}. */
|
|
9
|
-
export interface McpOAuthOptions {
|
|
10
|
-
/**
|
|
11
|
-
* The absolute URL of each MCP endpoint that accepts the tokens, such as `https://app.example.com/mcp`. Inside
|
|
12
|
-
* `defineAuth(({ requestOrigin }) => …)`, use `${requestOrigin}/mcp`.
|
|
13
|
-
*/
|
|
14
|
-
resource: string | readonly string[];
|
|
15
|
-
/** The page where a signed-out person signs in. Better Auth sends them there with a signed query. */
|
|
16
|
-
loginPage: string;
|
|
17
|
-
/** The page where a signed-in person allows or denies the client. Defaults to `loginPage`. */
|
|
18
|
-
consentPage?: string;
|
|
19
|
-
/** Scopes in addition to `openid`, `profile`, `email`, and `offline_access`. */
|
|
20
|
-
scopes?: readonly string[];
|
|
21
|
-
/** The `iss` of the access tokens, without a trailing slash. Defaults to the Better Auth base URL, such as `https://app.example.com/api/auth`. */
|
|
22
|
-
issuer?: string;
|
|
23
|
-
/** Limits of dynamic client registration, which anyone may call. */
|
|
24
|
-
registration?: {
|
|
25
|
-
/** The largest request body. Defaults to 16 KiB. */
|
|
26
|
-
maxBytes?: number;
|
|
27
|
-
};
|
|
28
|
-
/** Other `oauthProvider()` options, such as `codeExpiresIn`. They win over the defaults of `mcpOAuth()`. */
|
|
29
|
-
provider?: Partial<OAuthProviderOptions>;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* The plugins of {@link mcpOAuth}, with their own types, so the typed Auth of a Definition that spreads them has the
|
|
33
|
-
* JWT and OAuth provider endpoints, such as `api.getJwks`.
|
|
34
|
-
*/
|
|
35
|
-
export type McpOAuthPlugins = [ReturnType<typeof jwt>, ReturnType<typeof oauthProvider>, BetterAuthPlugin];
|
|
36
|
-
/**
|
|
37
|
-
* The Better Auth plugins that let MCP clients sign in to an MCP server of the app with OAuth 2.1: `jwt()` signs the
|
|
38
|
-
* access tokens for the resource, and `oauthProvider()` registers clients, shows the login and consent pages, and issues
|
|
39
|
-
* the tokens. Clients register themselves with no `application_type`, and a loopback or private-use redirect makes them
|
|
40
|
-
* native clients. Registration is open, so its body and its fields are bounded. Better Auth's limiter allows 5
|
|
41
|
-
* registrations per minute for each client IP. `defineAuth()` turns it on outside a development server, on every host.
|
|
42
|
-
* DPoP-bound client registration is refused; these helpers support bearer tokens.
|
|
43
|
-
*
|
|
44
|
-
* ```ts [server/auth.ts]
|
|
45
|
-
* import { defineAuth } from "vite-hub/auth"
|
|
46
|
-
* import { mcpOAuth } from "vite-hub/auth/mcp"
|
|
47
|
-
*
|
|
48
|
-
* export default defineAuth(({ requestOrigin }) => ({
|
|
49
|
-
* baseURL: requestOrigin,
|
|
50
|
-
* plugins: [...mcpOAuth({ resource: `${requestOrigin}/mcp`, loginPage: "/oauth" })],
|
|
51
|
-
* }))
|
|
52
|
-
* ```
|
|
53
|
-
*/
|
|
54
|
-
export declare function mcpOAuth(options: McpOAuthOptions): McpOAuthPlugins;
|
|
5
|
+
//#region src/mcp-token.d.ts
|
|
6
|
+
type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
|
|
55
7
|
/** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
|
|
56
|
-
|
|
8
|
+
interface McpOAuthAuth {
|
|
57
9
|
$context: Promise<{
|
|
58
10
|
baseURL: string;
|
|
59
11
|
options: {
|
|
@@ -104,35 +56,8 @@ export interface McpOAuthAuth {
|
|
|
104
56
|
getOpenIdConfig: (...args: never[]) => unknown;
|
|
105
57
|
};
|
|
106
58
|
}
|
|
107
|
-
/** Options of {@link serveMcpOAuthDiscovery}. */
|
|
108
|
-
export interface McpOAuthDiscoveryOptions {
|
|
109
|
-
/** The Better Auth instance. Defaults to the app Auth for the request. */
|
|
110
|
-
auth?: McpOAuthAuth;
|
|
111
|
-
/** `resource_name` of the protected resource metadata, which a client shows before sign-in. */
|
|
112
|
-
resourceName?: string;
|
|
113
|
-
/** `resource_documentation`, a page about the MCP server. */
|
|
114
|
-
resourceDocumentation?: string;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Answer the OAuth discovery documents that MCP clients read at the origin root, or return `undefined` for another path:
|
|
118
|
-
*
|
|
119
|
-
* - `/.well-known/oauth-protected-resource<resource path>` (RFC 9728) for each resource of `mcpOAuth()`. The bare path
|
|
120
|
-
* describes the first resource at the request origin.
|
|
121
|
-
* - `/.well-known/oauth-authorization-server<issuer path>` (RFC 8414) and `/.well-known/openid-configuration<issuer path>`,
|
|
122
|
-
* which Better Auth serves only below its own base path. The bare paths answer too.
|
|
123
|
-
*
|
|
124
|
-
* Every answer allows any origin with CORS, and an `OPTIONS` preflight gets `204`, so MCP clients in a browser read them.
|
|
125
|
-
*
|
|
126
|
-
* ```ts [server/middleware/mcp-oauth.ts]
|
|
127
|
-
* import { defineHandler } from "h3"
|
|
128
|
-
* import { serveMcpOAuthDiscovery } from "vite-hub/auth/mcp"
|
|
129
|
-
*
|
|
130
|
-
* export default defineHandler(event => serveMcpOAuthDiscovery(event.req, { resourceName: "My app" }))
|
|
131
|
-
* ```
|
|
132
|
-
*/
|
|
133
|
-
export declare function serveMcpOAuthDiscovery(request: Request, options?: McpOAuthDiscoveryOptions): Promise<Response | undefined>;
|
|
134
59
|
/** The person and the client of a valid MCP access token. */
|
|
135
|
-
|
|
60
|
+
interface McpCaller {
|
|
136
61
|
/** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
|
|
137
62
|
user: {
|
|
138
63
|
id: string;
|
|
@@ -144,16 +69,19 @@ export interface McpCaller {
|
|
|
144
69
|
/** The scopes that the person approved. */
|
|
145
70
|
scopes: string[];
|
|
146
71
|
/** The OAuth client id, from `azp` or `client_id`. */
|
|
147
|
-
clientId: string
|
|
72
|
+
clientId: string;
|
|
148
73
|
/** The name the client registered, such as "Claude Code". */
|
|
149
74
|
clientName: string | undefined;
|
|
150
75
|
}
|
|
151
76
|
/** Options of {@link verifyMcpRequest}. */
|
|
152
|
-
|
|
77
|
+
interface VerifyMcpRequestOptions {
|
|
153
78
|
/** The Better Auth instance. Defaults to the app Auth for the request. */
|
|
154
79
|
auth?: McpOAuthAuth;
|
|
155
|
-
/**
|
|
156
|
-
|
|
80
|
+
/**
|
|
81
|
+
* The resource that the token must name as its audience, or a list of which it must name one. Defaults to the
|
|
82
|
+
* `mcpOAuth()` resource at the path of the request.
|
|
83
|
+
*/
|
|
84
|
+
resource?: string | readonly string[];
|
|
157
85
|
}
|
|
158
86
|
/**
|
|
159
87
|
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
@@ -168,7 +96,7 @@ export interface VerifyMcpRequestOptions {
|
|
|
168
96
|
*/
|
|
169
97
|
export declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<Result<McpCaller, "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING">>;
|
|
170
98
|
/** Options of {@link deleteUnusedMcpClients}. */
|
|
171
|
-
|
|
99
|
+
interface DeleteUnusedMcpClientsOptions {
|
|
172
100
|
/** The Better Auth instance. Defaults to the app Auth. */
|
|
173
101
|
auth?: McpOAuthAuth;
|
|
174
102
|
/** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
|
|
@@ -184,4 +112,87 @@ export interface DeleteUnusedMcpClientsOptions {
|
|
|
184
112
|
export declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
|
|
185
113
|
deleted: number;
|
|
186
114
|
}, "AUTH_MCP_CLEANUP_FAILED">>;
|
|
187
|
-
//#endregion
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/mcp.d.ts
|
|
117
|
+
/**
|
|
118
|
+
* OAuth 2.1 sign-in for an MCP server of the app, with Better Auth as the authorization server. `mcpOAuth()` adds the
|
|
119
|
+
* plugins, `serveMcpOAuthDiscovery()` answers the well-known documents at the origin root, `verifyMcpRequest()` checks the
|
|
120
|
+
* access token of a request, and `deleteUnusedMcpClients()` removes registrations that never signed anyone in.
|
|
121
|
+
*/
|
|
122
|
+
type OAuthProviderOptions = Parameters<typeof oauthProvider>[0];
|
|
123
|
+
/** Options of {@link mcpOAuth}. */
|
|
124
|
+
export interface McpOAuthOptions {
|
|
125
|
+
/**
|
|
126
|
+
* The absolute URL of each MCP endpoint that accepts the tokens, such as `https://app.example.com/mcp`. Inside
|
|
127
|
+
* `defineAuth(({ requestOrigin }) => …)`, use `${requestOrigin}/mcp`.
|
|
128
|
+
*/
|
|
129
|
+
resource: string | readonly string[];
|
|
130
|
+
/** The page where a signed-out person signs in. Better Auth sends them there with a signed query. */
|
|
131
|
+
loginPage: string;
|
|
132
|
+
/** The page where a signed-in person allows or denies the client. Defaults to `loginPage`. */
|
|
133
|
+
consentPage?: string;
|
|
134
|
+
/** Scopes in addition to `openid`, `profile`, `email`, and `offline_access`. */
|
|
135
|
+
scopes?: readonly string[];
|
|
136
|
+
/** The `iss` of the access tokens, without a trailing slash. Defaults to the Better Auth base URL, such as `https://app.example.com/api/auth`. */
|
|
137
|
+
issuer?: string;
|
|
138
|
+
/** Limits of dynamic client registration, which anyone may call. */
|
|
139
|
+
registration?: {
|
|
140
|
+
/** The largest request body. Defaults to 16 KiB. */
|
|
141
|
+
maxBytes?: number;
|
|
142
|
+
};
|
|
143
|
+
/** Other `oauthProvider()` options, such as `codeExpiresIn`. They win over the defaults of `mcpOAuth()`. */
|
|
144
|
+
provider?: Partial<OAuthProviderOptions>;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The plugins of {@link mcpOAuth}, with their own types, so the typed Auth of a Definition that spreads them has the
|
|
148
|
+
* JWT and OAuth provider endpoints, such as `api.getJwks`.
|
|
149
|
+
*/
|
|
150
|
+
export type McpOAuthPlugins = [ReturnType<typeof jwt>, ReturnType<typeof oauthProvider>, BetterAuthPlugin];
|
|
151
|
+
/**
|
|
152
|
+
* The Better Auth plugins that let MCP clients sign in to an MCP server of the app with OAuth 2.1: `jwt()` signs the
|
|
153
|
+
* access tokens for the resource, and `oauthProvider()` registers clients, shows the login and consent pages, and issues
|
|
154
|
+
* the tokens. Clients register themselves with no `application_type`, and a loopback or private-use redirect makes them
|
|
155
|
+
* native clients. Registration is open, so its body and its fields are bounded. Better Auth's limiter allows 5
|
|
156
|
+
* registrations per minute for each client IP. `defineAuth()` turns it on outside a development server, on every host.
|
|
157
|
+
* DPoP-bound client registration is refused; these helpers support bearer tokens.
|
|
158
|
+
*
|
|
159
|
+
* ```ts [server/auth.ts]
|
|
160
|
+
* import { defineAuth } from "vite-hub/auth"
|
|
161
|
+
* import { mcpOAuth } from "vite-hub/auth/mcp"
|
|
162
|
+
*
|
|
163
|
+
* export default defineAuth(({ requestOrigin }) => ({
|
|
164
|
+
* baseURL: requestOrigin,
|
|
165
|
+
* plugins: [...mcpOAuth({ resource: `${requestOrigin}/mcp`, loginPage: "/oauth" })],
|
|
166
|
+
* }))
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export declare function mcpOAuth(options: McpOAuthOptions): McpOAuthPlugins;
|
|
170
|
+
/** Options of {@link serveMcpOAuthDiscovery}. */
|
|
171
|
+
export interface McpOAuthDiscoveryOptions {
|
|
172
|
+
/** The Better Auth instance. Defaults to the app Auth for the request. */
|
|
173
|
+
auth?: McpOAuthAuth;
|
|
174
|
+
/** `resource_name` of the protected resource metadata, which a client shows before sign-in. */
|
|
175
|
+
resourceName?: string;
|
|
176
|
+
/** `resource_documentation`, a page about the MCP server. */
|
|
177
|
+
resourceDocumentation?: string;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Answer the OAuth discovery documents that MCP clients read at the origin root, or return `undefined` for another path:
|
|
181
|
+
*
|
|
182
|
+
* - `/.well-known/oauth-protected-resource<resource path>` (RFC 9728) for each resource of `mcpOAuth()`. The bare path
|
|
183
|
+
* describes the first resource at the request origin.
|
|
184
|
+
* - `/.well-known/oauth-authorization-server<issuer path>` (RFC 8414) and `/.well-known/openid-configuration<issuer path>`,
|
|
185
|
+
* which Better Auth serves only below its own base path. The bare paths answer too.
|
|
186
|
+
*
|
|
187
|
+
* Every answer allows any origin with CORS, and an `OPTIONS` preflight gets `204`, so MCP clients in a browser read them.
|
|
188
|
+
*
|
|
189
|
+
* ```ts [server/middleware/mcp-oauth.ts]
|
|
190
|
+
* import { defineHandler } from "h3"
|
|
191
|
+
* import { serveMcpOAuthDiscovery } from "vite-hub/auth/mcp"
|
|
192
|
+
*
|
|
193
|
+
* export default defineHandler(event => serveMcpOAuthDiscovery(event.req, { resourceName: "My app" }))
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
export declare function serveMcpOAuthDiscovery(request: Request, options?: McpOAuthDiscoveryOptions): Promise<Response | undefined>;
|
|
197
|
+
//#endregion
|
|
198
|
+
export type { DeleteUnusedMcpClientsOptions, McpCaller, McpOAuthAuth, McpOAuthErrorCode, VerifyMcpRequestOptions };
|