@vite-hub/auth 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -0,0 +1,22 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ export { invariant as t };
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,187 @@
1
+ import { Result } from "@vite-hub/runtime";
2
+ import { BetterAuthPlugin } from "better-auth";
3
+ import { oauthProvider } from "@better-auth/oauth-provider";
4
+ import { jwt } from "better-auth/plugins";
5
+ //#region src/mcp.d.ts
6
+ export type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
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;
55
+ /** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
56
+ export interface McpOAuthAuth {
57
+ $context: Promise<{
58
+ baseURL: string;
59
+ options: {
60
+ plugins?: ReadonlyArray<{
61
+ id?: string;
62
+ options?: unknown;
63
+ }>;
64
+ };
65
+ internalAdapter: {
66
+ findUserById: (id: string) => Promise<unknown>;
67
+ };
68
+ adapter: {
69
+ findOne: (input: {
70
+ model: string;
71
+ where: Array<{
72
+ field: string;
73
+ value: string;
74
+ }>;
75
+ }) => Promise<unknown>;
76
+ findMany: (input: {
77
+ model: string;
78
+ where: Array<{
79
+ field: string;
80
+ operator?: "lt";
81
+ value: Date;
82
+ }>;
83
+ limit?: number;
84
+ }) => Promise<unknown[]>;
85
+ count: (input: {
86
+ model: string;
87
+ where: Array<{
88
+ field: string;
89
+ value: string;
90
+ }>;
91
+ }) => Promise<number>;
92
+ deleteMany: (input: {
93
+ model: string;
94
+ where: Array<{
95
+ field: string;
96
+ value: string;
97
+ }>;
98
+ }) => Promise<number>;
99
+ };
100
+ }>;
101
+ api: {
102
+ getJwks: (...args: never[]) => Promise<unknown>;
103
+ getOAuthServerConfig: (...args: never[]) => unknown;
104
+ getOpenIdConfig: (...args: never[]) => unknown;
105
+ };
106
+ }
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
+ /** The person and the client of a valid MCP access token. */
135
+ export interface McpCaller {
136
+ /** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
137
+ user: {
138
+ id: string;
139
+ email?: string | null;
140
+ name?: string | null;
141
+ image?: string | null;
142
+ [key: string]: unknown;
143
+ };
144
+ /** The scopes that the person approved. */
145
+ scopes: string[];
146
+ /** The OAuth client id, from `azp` or `client_id`. */
147
+ clientId: string | undefined;
148
+ /** The name the client registered, such as "Claude Code". */
149
+ clientName: string | undefined;
150
+ }
151
+ /** Options of {@link verifyMcpRequest}. */
152
+ export interface VerifyMcpRequestOptions {
153
+ /** The Better Auth instance. Defaults to the app Auth for the request. */
154
+ auth?: McpOAuthAuth;
155
+ /** The resource that the token must name as its audience. Defaults to the `mcpOAuth()` resource at the path of the request. */
156
+ resource?: string;
157
+ }
158
+ /**
159
+ * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
160
+ * authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
161
+ * the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
162
+ * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
163
+ * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
164
+ * access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
165
+ * bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
166
+ * any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
167
+ * 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()`.
168
+ */
169
+ export declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<Result<McpCaller, "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING">>;
170
+ /** Options of {@link deleteUnusedMcpClients}. */
171
+ export interface DeleteUnusedMcpClientsOptions {
172
+ /** The Better Auth instance. Defaults to the app Auth. */
173
+ auth?: McpOAuthAuth;
174
+ /** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
175
+ olderThan?: number;
176
+ /** Clients checked in one call. Defaults to 500. */
177
+ limit?: number;
178
+ }
179
+ /**
180
+ * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
181
+ * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
182
+ * of deleted clients.
183
+ */
184
+ export declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
185
+ deleted: number;
186
+ }, "AUTH_MCP_CLEANUP_FAILED">>;
187
+ //#endregion
package/dist/mcp.js ADDED
@@ -0,0 +1,353 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { l as findAccessPolicyPlugin } from "./members-D9lfaEO_.js";
3
+ import { t as authForRequest } from "./auth-instance-CR6b1W80.js";
4
+ import { defineErrors } from "@vite-hub/runtime";
5
+ import { APIError, createAuthMiddleware } from "better-auth/api";
6
+ import { verifyJwsAccessToken } from "better-auth/oauth2";
7
+ import { oauthProvider, oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
8
+ import { jwt } from "better-auth/plugins";
9
+ //#region src/mcp.ts
10
+ /**
11
+ * OAuth 2.1 sign-in for an MCP server of the app, with Better Auth as the authorization server. `mcpOAuth()` adds the
12
+ * plugins, `serveMcpOAuthDiscovery()` answers the well-known documents at the origin root, `verifyMcpRequest()` checks the
13
+ * access token of a request, and `deleteUnusedMcpClients()` removes registrations that never signed anyone in.
14
+ */
15
+ const mcpErrors = /*#__PURE__*/ defineErrors({
16
+ docs: "https://vitehub.dev/docs/auth/diagnostics",
17
+ codes: {
18
+ AUTH_MCP_OAUTH_MISSING: {
19
+ why: "The Auth has no MCP OAuth: its plugins do not include `oauthProvider()` with `resources`.",
20
+ fix: "Add `...mcpOAuth({ resource, loginPage })` from `vite-hub/auth/mcp` to the `plugins` of `defineAuth()`."
21
+ },
22
+ AUTH_MCP_TOKEN_MISSING: {
23
+ why: "The request has no `Authorization: Bearer` access token.",
24
+ fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
25
+ },
26
+ AUTH_MCP_TOKEN_INVALID: {
27
+ why: ({ reason }) => `The access token is not valid: ${reason}`,
28
+ fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again."
29
+ },
30
+ AUTH_MCP_CLEANUP_FAILED: {
31
+ why: "The Auth database could not list or delete OAuth clients.",
32
+ fix: "Read `error.cause` for the database error, then run the cleanup again."
33
+ }
34
+ }
35
+ });
36
+ const baseScopes = [
37
+ "openid",
38
+ "profile",
39
+ "email",
40
+ "offline_access"
41
+ ];
42
+ const registerPath = "/oauth2/register";
43
+ /** Bounds RFC 7591 client metadata without restricting the private-use redirect schemes of native MCP clients. */
44
+ function registrationProblem(body, maxBytes) {
45
+ if (!isRecord(body)) return "Client metadata must be an object.";
46
+ const redirects = body.redirect_uris;
47
+ if (!Array.isArray(redirects) || redirects.length < 1 || redirects.length > 5) return "Register between one and five redirect URIs.";
48
+ if (body.dpop_bound_access_tokens === true) return "MCP OAuth supports bearer tokens, not DPoP-bound access tokens.";
49
+ if (JSON.stringify(body).length > maxBytes) return "Client metadata is too large.";
50
+ for (const value of Object.values(body)) {
51
+ if (typeof value === "string" && value.length > 2048) return "Client metadata fields must be at most 2048 characters.";
52
+ if (Array.isArray(value) && (value.length > 10 || value.some((item) => typeof item !== "string" || item.length > 2048))) return "Client metadata lists must have at most 10 strings of at most 2048 characters.";
53
+ }
54
+ if (typeof body.client_name === "string" && body.client_name.length > 160) return "Client name must be at most 160 characters.";
55
+ }
56
+ function metadataError(status, description) {
57
+ return Response.json({
58
+ error: "invalid_client_metadata",
59
+ error_description: description
60
+ }, {
61
+ headers: { "cache-control": "no-store" },
62
+ status
63
+ });
64
+ }
65
+ /** Reads at most `maxBytes` of the body, so a large registration is refused before Better Auth parses it. */
66
+ async function exceedsBytes(request, maxBytes) {
67
+ const length = Number(request.headers.get("content-length"));
68
+ if (Number.isFinite(length) && length > maxBytes) return true;
69
+ const reader = request.clone().body?.getReader();
70
+ if (!reader) return false;
71
+ let bytes = 0;
72
+ try {
73
+ while (true) {
74
+ const chunk = await reader.read();
75
+ if (chunk.done) return false;
76
+ bytes += chunk.value.byteLength;
77
+ if (bytes > maxBytes) return true;
78
+ }
79
+ } finally {
80
+ reader.cancel().catch(() => {});
81
+ }
82
+ }
83
+ function registrationLimits(options) {
84
+ const maxBytes = options.registration?.maxBytes ?? 16384;
85
+ return {
86
+ hooks: { before: [{
87
+ handler: createAuthMiddleware(async (context) => {
88
+ const problem = registrationProblem(context.body, maxBytes);
89
+ if (problem) throw new APIError("BAD_REQUEST", {
90
+ error: "invalid_client_metadata",
91
+ error_description: problem
92
+ });
93
+ }),
94
+ matcher: (context) => context.path === registerPath
95
+ }] },
96
+ id: "vitehub-mcp-registration",
97
+ async onRequest(request) {
98
+ if (request.method !== "POST" || !new URL(request.url).pathname.replace(/\/+$/, "").endsWith(registerPath)) return;
99
+ if (await exceedsBytes(request, maxBytes)) return { response: metadataError(413, "Client metadata is too large.") };
100
+ }
101
+ };
102
+ }
103
+ /**
104
+ * The Better Auth plugins that let MCP clients sign in to an MCP server of the app with OAuth 2.1: `jwt()` signs the
105
+ * access tokens for the resource, and `oauthProvider()` registers clients, shows the login and consent pages, and issues
106
+ * the tokens. Clients register themselves with no `application_type`, and a loopback or private-use redirect makes them
107
+ * native clients. Registration is open, so its body and its fields are bounded. Better Auth's limiter allows 5
108
+ * registrations per minute for each client IP. `defineAuth()` turns it on outside a development server, on every host.
109
+ * DPoP-bound client registration is refused; these helpers support bearer tokens.
110
+ *
111
+ * ```ts [server/auth.ts]
112
+ * import { defineAuth } from "vite-hub/auth"
113
+ * import { mcpOAuth } from "vite-hub/auth/mcp"
114
+ *
115
+ * export default defineAuth(({ requestOrigin }) => ({
116
+ * baseURL: requestOrigin,
117
+ * plugins: [...mcpOAuth({ resource: `${requestOrigin}/mcp`, loginPage: "/oauth" })],
118
+ * }))
119
+ * ```
120
+ */
121
+ function mcpOAuth(options) {
122
+ const resources = typeof options.resource === "string" ? [options.resource] : [...options.resource];
123
+ return [
124
+ jwt({
125
+ disableSettingJwtHeader: true,
126
+ ...options.issuer ? { jwt: { issuer: options.issuer.replace(/\/+$/, "") } } : {}
127
+ }),
128
+ oauthProvider({
129
+ allowDynamicClientRegistration: true,
130
+ allowUnauthenticatedClientRegistration: true,
131
+ clientRegistrationDefaultApplicationType: "infer",
132
+ clientRegistrationDefaultResources: resources,
133
+ consentPage: options.consentPage ?? options.loginPage,
134
+ loginPage: options.loginPage,
135
+ resources,
136
+ scopes: [.../* @__PURE__ */ new Set([...baseScopes, ...options.scopes ?? []])],
137
+ ...options.provider
138
+ }),
139
+ registrationLimits(options)
140
+ ];
141
+ }
142
+ async function stateOf(auth) {
143
+ const context = await auth.$context;
144
+ const plugins = context.options.plugins ?? [];
145
+ const provider = plugins.find((plugin) => plugin.id === "oauth-provider")?.options;
146
+ const resources = isRecord(provider) && Array.isArray(provider.resources) ? provider.resources.flatMap((entry) => typeof entry === "string" ? [entry] : isRecord(entry) && typeof entry.identifier === "string" ? [entry.identifier] : []) : [];
147
+ if (!resources.length) throw mcpErrors.AUTH_MCP_OAUTH_MISSING();
148
+ const jwtOptions = plugins.find((plugin) => plugin.id === "jwt")?.options;
149
+ const issuer = isRecord(jwtOptions) && isRecord(jwtOptions.jwt) && typeof jwtOptions.jwt.issuer === "string" ? jwtOptions.jwt.issuer : context.baseURL;
150
+ const scopes = isRecord(provider) && Array.isArray(provider.scopes) ? provider.scopes.filter((scope) => typeof scope === "string") : baseScopes;
151
+ return {
152
+ issuer: issuer.replace(/\/+$/, ""),
153
+ resources,
154
+ scopes
155
+ };
156
+ }
157
+ const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
158
+ const appAuth = (request) => authForRequest(request);
159
+ const discoveryCors = {
160
+ "access-control-allow-headers": "*",
161
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
162
+ "access-control-allow-origin": "*",
163
+ "access-control-max-age": "86400"
164
+ };
165
+ const discoveryDocuments = [
166
+ "oauth-protected-resource",
167
+ "oauth-authorization-server",
168
+ "openid-configuration"
169
+ ];
170
+ /**
171
+ * Answer the OAuth discovery documents that MCP clients read at the origin root, or return `undefined` for another path:
172
+ *
173
+ * - `/.well-known/oauth-protected-resource<resource path>` (RFC 9728) for each resource of `mcpOAuth()`. The bare path
174
+ * describes the first resource at the request origin.
175
+ * - `/.well-known/oauth-authorization-server<issuer path>` (RFC 8414) and `/.well-known/openid-configuration<issuer path>`,
176
+ * which Better Auth serves only below its own base path. The bare paths answer too.
177
+ *
178
+ * Every answer allows any origin with CORS, and an `OPTIONS` preflight gets `204`, so MCP clients in a browser read them.
179
+ *
180
+ * ```ts [server/middleware/mcp-oauth.ts]
181
+ * import { defineHandler } from "h3"
182
+ * import { serveMcpOAuthDiscovery } from "vite-hub/auth/mcp"
183
+ *
184
+ * export default defineHandler(event => serveMcpOAuthDiscovery(event.req, { resourceName: "My app" }))
185
+ * ```
186
+ */
187
+ async function serveMcpOAuthDiscovery(request, options = {}) {
188
+ const { pathname } = new URL(request.url);
189
+ const document = discoveryDocuments.find((name) => pathname === `/.well-known/${name}` || pathname.startsWith(`/.well-known/${name}/`));
190
+ if (!document) return void 0;
191
+ if (request.method === "OPTIONS") return new Response(null, {
192
+ headers: discoveryCors,
193
+ status: 204
194
+ });
195
+ if (request.method !== "GET" && request.method !== "HEAD") return void 0;
196
+ const response = await discoveryDocument(request, document, options);
197
+ if (!response) return void 0;
198
+ const answer = new Response(response.body, response);
199
+ for (const [name, value] of Object.entries(discoveryCors)) answer.headers.set(name, value);
200
+ return answer;
201
+ }
202
+ async function discoveryDocument(request, document, options) {
203
+ const { origin, pathname } = new URL(request.url);
204
+ const suffix = pathname.slice(`/.well-known/${document}`.length).replace(/\/+$/, "");
205
+ const auth = options.auth ?? appAuth(request);
206
+ const state = await stateOf(auth);
207
+ if (document === "oauth-protected-resource") {
208
+ const resource = state.resources.find((entry) => new URL(entry).origin === origin && (!suffix || pathOf(entry) === suffix));
209
+ if (!resource) return void 0;
210
+ return Response.json({
211
+ authorization_servers: [state.issuer],
212
+ bearer_methods_supported: ["header"],
213
+ resource,
214
+ ...options.resourceDocumentation ? { resource_documentation: options.resourceDocumentation } : {},
215
+ ...options.resourceName ? { resource_name: options.resourceName } : {},
216
+ scopes_supported: state.scopes
217
+ }, { headers: { "cache-control": "public, max-age=15, stale-while-revalidate=15" } });
218
+ }
219
+ if (suffix && suffix !== pathOf(state.issuer)) return void 0;
220
+ return (document === "oauth-authorization-server" ? oauthProviderAuthServerMetadata(auth) : oauthProviderOpenIdConfigMetadata(auth))(request);
221
+ }
222
+ const clockToleranceSeconds = 30;
223
+ function banned(user) {
224
+ if (user.banned !== true) return false;
225
+ const expires = user.banExpires;
226
+ const until = expires instanceof Date ? expires.getTime() : typeof expires === "string" || typeof expires === "number" ? new Date(expires).getTime() : NaN;
227
+ return Number.isNaN(until) || until > Date.now();
228
+ }
229
+ /**
230
+ * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
231
+ * authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
232
+ * the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
233
+ * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
234
+ * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
235
+ * access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
236
+ * bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
237
+ * any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
238
+ * 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()`.
239
+ */
240
+ async function verifyMcpRequest(request, options = {}) {
241
+ const token = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
242
+ if (!token) return [mcpErrors.AUTH_MCP_TOKEN_MISSING(), void 0];
243
+ const auth = options.auth ?? appAuth(request);
244
+ const state = await stateOf(auth);
245
+ const url = new URL(request.url);
246
+ const resource = options.resource ?? state.resources.find((entry) => new URL(entry).origin === url.origin && pathOf(entry) === url.pathname.replace(/\/+$/, ""));
247
+ if (!resource) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: `${url.pathname} is not a resource of \`mcpOAuth()\`.` }), void 0];
248
+ const jwks = await auth.api.getJwks();
249
+ const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
250
+ const algorithms = [...new Set(keys.flatMap((key) => typeof key.alg === "string" ? [key.alg] : []))];
251
+ if (!algorithms.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the Auth has no signing keys." }), void 0];
252
+ let payload;
253
+ try {
254
+ payload = await verifyJwsAccessToken(token, {
255
+ jwksFetch: async () => jwks,
256
+ verifyOptions: {
257
+ algorithms,
258
+ audience: resource,
259
+ clockTolerance: clockToleranceSeconds,
260
+ issuer: state.issuer,
261
+ requiredClaims: ["exp", "sub"]
262
+ }
263
+ });
264
+ } catch (error) {
265
+ return [mcpErrors.AUTH_MCP_TOKEN_INVALID({
266
+ cause: error,
267
+ reason: error instanceof Error ? error.message : "the signature or a claim does not match."
268
+ }), void 0];
269
+ }
270
+ 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];
271
+ const context = await auth.$context;
272
+ const user = await context.internalAdapter.findUserById(String(payload.sub));
273
+ 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];
274
+ const policy = findAccessPolicyPlugin(context.options.plugins);
275
+ 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];
276
+ const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
277
+ const client = clientId ? await context.adapter.findOne({
278
+ model: "oauthClient",
279
+ where: [{
280
+ field: "clientId",
281
+ value: clientId
282
+ }]
283
+ }) : void 0;
284
+ if (!isRecord(client) || client.disabled) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the OAuth client does not exist or is disabled." }), void 0];
285
+ const scope = payload.scope;
286
+ const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
287
+ if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
288
+ const session = await context.adapter.findOne({
289
+ model: "session",
290
+ where: [{
291
+ field: "id",
292
+ value: payload.sid
293
+ }]
294
+ });
295
+ 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];
296
+ }
297
+ return [void 0, {
298
+ clientId,
299
+ clientName: typeof client.name === "string" && client.name ? client.name : void 0,
300
+ scopes,
301
+ user
302
+ }];
303
+ }
304
+ /**
305
+ * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
306
+ * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
307
+ * of deleted clients.
308
+ */
309
+ async function deleteUnusedMcpClients(options = {}) {
310
+ const auth = options.auth ?? appAuth(new Request("http://localhost/"));
311
+ try {
312
+ const { adapter } = await auth.$context;
313
+ const cutoff = new Date(Date.now() - (options.olderThan ?? 864e5));
314
+ const clients = await adapter.findMany({
315
+ limit: options.limit ?? 500,
316
+ model: "oauthClient",
317
+ where: [{
318
+ field: "createdAt",
319
+ operator: "lt",
320
+ value: cutoff
321
+ }]
322
+ });
323
+ let deleted = 0;
324
+ for (const client of clients) {
325
+ if (!isRecord(client) || typeof client.clientId !== "string") continue;
326
+ const where = [{
327
+ field: "clientId",
328
+ value: client.clientId
329
+ }];
330
+ if ((await Promise.all([
331
+ "oauthConsent",
332
+ "oauthAccessToken",
333
+ "oauthRefreshToken"
334
+ ].map((model) => adapter.count({
335
+ model,
336
+ where
337
+ })))).some((count) => count > 0)) continue;
338
+ await adapter.deleteMany({
339
+ model: "oauthClientResource",
340
+ where
341
+ });
342
+ deleted += await adapter.deleteMany({
343
+ model: "oauthClient",
344
+ where
345
+ });
346
+ }
347
+ return [void 0, { deleted }];
348
+ } catch (error) {
349
+ return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
350
+ }
351
+ }
352
+ //#endregion
353
+ export { deleteUnusedMcpClients, mcpOAuth, serveMcpOAuthDiscovery, verifyMcpRequest };