@vite-hub/auth 0.5.1 → 0.6.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.
Files changed (72) hide show
  1. package/README.md +2 -2
  2. package/dist/{abilities-3L1Y5Pnw.d.ts → abilities-BYOcyQ9B.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-BHhPkrZd.js → ability-error-D3-u8k1A.js} +1 -1
  5. package/dist/{access-pages-BwImVHN_.js → access-pages-9aKr6z-k.js} +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{auth-instance-_J7R9Qs1.js → auth-instance-BWiRS9QZ.js} +73 -82
  8. package/dist/cli.js +1 -1
  9. package/dist/client-request-BzMKtfCY.js +52 -0
  10. package/dist/{console-runtime-vc3JQEuq.js → console-runtime-CaIXVtB_.js} +7 -206
  11. package/dist/console-runtime-DMH1I2fl.d.ts +32 -0
  12. package/dist/console-runtime.d.ts +3 -3
  13. package/dist/console-runtime.js +1 -1
  14. package/dist/{console-types-51lkf0lk.js → console-types-NrX5TWl3.js} +2 -1
  15. package/dist/console.d.ts +3 -3
  16. package/dist/console.js +1 -1
  17. package/dist/{database-options-DQ-8qYMl.js → database-options-B87hDU4j.js} +1 -1
  18. package/dist/{database-schema-options-CkSeU9V3.js → database-schema-options-peXHNLkJ.js} +1 -1
  19. package/dist/database.d.ts +2 -2
  20. package/dist/database.js +5 -5
  21. package/dist/{definition-MDGMNKrK.js → definition-BypPLIbI.js} +3 -3
  22. package/dist/{error-diagnostics-BssJr_2t.js → error-diagnostics-CUPwukgE.js} +1 -1
  23. package/dist/{events-DZqMiae_.js → events-BXU1_9mc.js} +2 -1
  24. package/dist/forward-sign-ins-BWXPPTRz.js +4 -0
  25. package/dist/forward.d.ts +24 -0
  26. package/dist/forward.js +42 -4
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +3 -3
  29. package/dist/internal/server.d.ts +2 -2
  30. package/dist/internal/server.js +4 -4
  31. package/dist/mcp-token-CmQbXbTu.d.ts +125 -0
  32. package/dist/{mcp-token--KuLYEub.js → mcp-token-CuqdbBy8.js} +45 -18
  33. package/dist/mcp.d.ts +2 -111
  34. package/dist/mcp.js +5 -3
  35. package/dist/{members-D3_Q5XJb.js → members-CwPIx10t.js} +3 -3
  36. package/dist/{nitro-kit-Bg4xUZAI.js → nitro-kit-BumWIKa5.js} +1 -1
  37. package/dist/nuxt.d.ts +1 -1
  38. package/dist/nuxt.js +3 -3
  39. package/dist/{own-access-C22hSIuF.d.ts → own-access-BNcxKrDl.d.ts} +1 -1
  40. package/dist/{own-access-DQgqxTbI.js → own-access-CYsakJiH.js} +1 -1
  41. package/dist/presets.js +1 -1
  42. package/dist/runtime/client-request-plugin.d.ts +1 -0
  43. package/dist/runtime/client-request-plugin.js +18 -0
  44. package/dist/runtime/console.d.ts +1 -1
  45. package/dist/runtime/console.js +2 -2
  46. package/dist/runtime/empty-abilities.d.ts +1 -1
  47. package/dist/runtime/empty-definition.d.ts +1 -1
  48. package/dist/runtime/server.d.ts +2 -2
  49. package/dist/runtime/server.js +3 -3
  50. package/dist/runtime-state-C0Rd1W4m.js +15 -0
  51. package/dist/schema.d.ts +1 -1
  52. package/dist/schema.js +1 -1
  53. package/dist/{server-DCsgxFPP.d.ts → server-BHniJi2m.d.ts} +2 -2
  54. package/dist/{server-CFWlYQJb.d.ts → server-C4Kni3Vj.d.ts} +13 -8
  55. package/dist/{server-D4Hi4TBI.js → server-Iru6jcnW.js} +13 -12
  56. package/dist/server.d.ts +3 -2
  57. package/dist/server.js +2 -2
  58. package/dist/{session-cookies-1FMcMnRh.js → session-cookies-fR6Pv4kD.js} +2 -2
  59. package/dist/{set-cookie-DkqM1kvj.js → set-cookie-DVfi-nJX.js} +1 -1
  60. package/dist/{table-specs-jw0jjU6l.js → table-specs-CCSY4tiS.js} +17 -14
  61. package/dist/{table-specs-BLm_Zlss.d.ts → table-specs-P4LvbOlX.d.ts} +28 -21
  62. package/dist/test.d.ts +1 -1
  63. package/dist/test.js +2 -2
  64. package/dist/{types-BHSgxyvV.d.ts → types-DmH31d2t.d.ts} +8 -21
  65. package/dist/{vite-D1xC9n1O.js → vite-CpWhT1Wi.js} +93 -27
  66. package/dist/vite.d.ts +1 -1
  67. package/dist/vite.js +1 -1
  68. package/dist/vue.d.ts +2 -2
  69. package/dist/vue.js +1 -1
  70. package/package.json +8 -8
  71. package/dist/console-runtime-BP1ZKJB0.d.ts +0 -71
  72. package/dist/runtime-state-DtKUfxKq.js +0 -24
@@ -1,6 +1,6 @@
1
- import { i as resetAuth } from "../runtime-state-DtKUfxKq.js";
2
- import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-_J7R9Qs1.js";
1
+ import { n as resetAuth } from "../runtime-state-C0Rd1W4m.js";
2
+ import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-BWiRS9QZ.js";
3
3
  import { setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver } from "../runtime/server.js";
4
- import { t as AbilityError } from "../ability-error-BHhPkrZd.js";
5
- import { C as toAuthRequest, D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, c as createAuthForRequest, d as getAuth, f as getAuthConsoleForRequest, g as listAuthEvents, h as handleAuthRequest, i as can, l as createAuthHandler, m as handleAuth, n as assertAuthOrigin, o as createAuth, p as getAuthEvents, r as authRoute, s as createAuthAccessHandler, t as aggregateAuthEvents, u as createAuthRequestRuntimeOptions, v as requireAuth, w as useAuth, x as requireCaller, y as requireAuthAccessRoutes } from "../server-D4Hi4TBI.js";
4
+ import { t as AbilityError } from "../ability-error-D3-u8k1A.js";
5
+ import { C as toAuthRequest, D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, c as createAuthForRequest, d as getAuth, f as getAuthConsoleForRequest, g as listAuthEvents, h as handleAuthRequest, i as can, l as createAuthHandler, m as handleAuth, n as assertAuthOrigin, o as createAuth, p as getAuthEvents, r as authRoute, s as createAuthAccessHandler, t as aggregateAuthEvents, u as createAuthRequestRuntimeOptions, v as requireAuth, w as useAuth, x as requireCaller, y as requireAuthAccessRoutes } from "../server-Iru6jcnW.js";
6
6
  export { AbilityError, aggregateAuthEvents, assertAuthOrigin, can, checkAuthMember, createAuth, createAuthAccessHandler, createAuthForRequest, createAuthHandler, createAuthRequestRuntimeOptions, createBetterAuthOptions, authRoute as default, findVerifiedAuthUserId, getAuth, getAuthConsoleForRequest, getAuthEvents, getAuthForDefinition, handleAuth, handleAuthRequest, listAuthEvents, requireAbility, requireAuth, requireAuthAccessRoutes, requireAuthorization, requireCaller, resetAuth, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
@@ -0,0 +1,125 @@
1
+ import { Result, ResultError } from "@vite-hub/runtime";
2
+ /** Why `verifyMcpRequest()` refused a token, in `error.data.reason` of `AUTH_MCP_TOKEN_INVALID`. */
3
+ declare const mcpTokenInvalidReasons: readonly ["expired", "malformed", "wrong_resource", "no_keys", "sender_constrained", "user_gone", "not_allowed", "client_disabled", "session_ended"];
4
+ type McpTokenInvalidReason = typeof mcpTokenInvalidReasons[number];
5
+ /** `error.data` of `AUTH_MCP_TOKEN_INVALID`. `clientId` is set when the token's signature and claims are valid. */
6
+ type McpTokenInvalidData = {
7
+ reason: McpTokenInvalidReason;
8
+ clientId: string | undefined;
9
+ };
10
+ /** The `AUTH_MCP_TOKEN_INVALID` error. Check `code` to read `data.reason` and `data.clientId`. */
11
+ type McpTokenInvalidError = ResultError<"AUTH_MCP_TOKEN_INVALID", McpTokenInvalidData>;
12
+ /** The error of `verifyMcpRequest()`. Check `code` to read the typed `data`. */
13
+ type VerifyMcpRequestError = McpTokenInvalidError | ResultError<"AUTH_MCP_TOKEN_MISSING", undefined>;
14
+ /** The `[error, caller]` tuple of `verifyMcpRequest()`. */
15
+ type VerifyMcpRequestResult = [error: VerifyMcpRequestError, data: undefined] | [error: undefined, data: McpCaller];
16
+ type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
17
+ /** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
18
+ interface McpOAuthAuth {
19
+ $context: Promise<{
20
+ baseURL: string;
21
+ options: {
22
+ plugins?: ReadonlyArray<{
23
+ id?: string;
24
+ options?: unknown;
25
+ }>;
26
+ };
27
+ internalAdapter: {
28
+ findUserById: (id: string) => Promise<unknown>;
29
+ };
30
+ adapter: {
31
+ findOne: (input: {
32
+ model: string;
33
+ where: Array<{
34
+ field: string;
35
+ value: string;
36
+ }>;
37
+ }) => Promise<unknown>;
38
+ findMany: (input: {
39
+ model: string;
40
+ where: Array<{
41
+ field: string;
42
+ operator?: "lt";
43
+ value: Date;
44
+ }>;
45
+ limit?: number;
46
+ }) => Promise<unknown[]>;
47
+ count: (input: {
48
+ model: string;
49
+ where: Array<{
50
+ field: string;
51
+ value: string;
52
+ }>;
53
+ }) => Promise<number>;
54
+ deleteMany: (input: {
55
+ model: string;
56
+ where: Array<{
57
+ field: string;
58
+ value: string;
59
+ }>;
60
+ }) => Promise<number>;
61
+ };
62
+ }>;
63
+ api: {
64
+ getJwks: (...args: never[]) => Promise<unknown>;
65
+ getOAuthServerConfig: (...args: never[]) => unknown;
66
+ getOpenIdConfig: (...args: never[]) => unknown;
67
+ };
68
+ }
69
+ /** The person and the client of a valid MCP access token. */
70
+ interface McpCaller {
71
+ /** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
72
+ user: {
73
+ id: string;
74
+ email?: string | null;
75
+ name?: string | null;
76
+ image?: string | null;
77
+ [key: string]: unknown;
78
+ };
79
+ /** The scopes that the person approved. */
80
+ scopes: string[];
81
+ /** The OAuth client id, from `azp` or `client_id`. */
82
+ clientId: string;
83
+ /** The name the client registered, such as "Claude Code". */
84
+ clientName: string | undefined;
85
+ }
86
+ /** Options of {@link verifyMcpRequest}. */
87
+ interface VerifyMcpRequestOptions {
88
+ /** The Better Auth instance. Defaults to the app Auth for the request. */
89
+ auth?: McpOAuthAuth;
90
+ /**
91
+ * The resource that the token must name as its audience, or a list of which it must name one. Defaults to the
92
+ * `mcpOAuth()` resource at the path of the request.
93
+ */
94
+ resource?: string | readonly string[];
95
+ }
96
+ /**
97
+ * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
98
+ * authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
99
+ * the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
100
+ * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
101
+ * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
102
+ * access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
103
+ * bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
104
+ * any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
105
+ * 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()`.
106
+ */
107
+ declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<VerifyMcpRequestResult>;
108
+ /** Options of {@link deleteUnusedMcpClients}. */
109
+ interface DeleteUnusedMcpClientsOptions {
110
+ /** The Better Auth instance. Defaults to the app Auth. */
111
+ auth?: McpOAuthAuth;
112
+ /** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
113
+ olderThan?: number;
114
+ /** Clients checked in one call. Defaults to 500. */
115
+ limit?: number;
116
+ }
117
+ /**
118
+ * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
119
+ * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
120
+ * of deleted clients.
121
+ */
122
+ declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
123
+ deleted: number;
124
+ }, "AUTH_MCP_CLEANUP_FAILED">>;
125
+ export { McpTokenInvalidData as a, VerifyMcpRequestError as c, deleteUnusedMcpClients as d, mcpTokenInvalidReasons as f, McpOAuthErrorCode as i, VerifyMcpRequestOptions as l, McpCaller as n, McpTokenInvalidError as o, verifyMcpRequest as p, McpOAuthAuth as r, McpTokenInvalidReason as s, DeleteUnusedMcpClientsOptions as t, VerifyMcpRequestResult as u };
@@ -1,5 +1,6 @@
1
- import { l as findAccessPolicyPlugin } from "./members-D3_Q5XJb.js";
2
- import { t as authForRequest } from "./auth-instance-_J7R9Qs1.js";
1
+ import { l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
2
+ import { t as authForRequest } from "./auth-instance-BWiRS9QZ.js";
3
+ import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
3
4
  import { n as mcpOAuthResources } from "./mcp-config-C7srUMIZ.js";
4
5
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
6
  import { defineErrors } from "@vite-hub/runtime";
@@ -29,8 +30,12 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
29
30
  fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
30
31
  },
31
32
  AUTH_MCP_TOKEN_INVALID: {
32
- why: ({ reason }) => `The access token is not valid: ${reason}`,
33
- fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again."
33
+ why: ({ detail }) => `The access token is not valid: ${detail}`,
34
+ fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again.",
35
+ data: ({ clientId, reason }) => ({
36
+ clientId,
37
+ reason
38
+ })
34
39
  },
35
40
  AUTH_MCP_CLEANUP_FAILED: {
36
41
  why: "The Auth database could not list or delete OAuth clients.",
@@ -38,6 +43,18 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
38
43
  }
39
44
  }
40
45
  });
46
+ /** Why `verifyMcpRequest()` refused a token, in `error.data.reason` of `AUTH_MCP_TOKEN_INVALID`. */
47
+ const mcpTokenInvalidReasons = [
48
+ "expired",
49
+ "malformed",
50
+ "wrong_resource",
51
+ "no_keys",
52
+ "sender_constrained",
53
+ "user_gone",
54
+ "not_allowed",
55
+ "client_disabled",
56
+ "session_ended"
57
+ ];
41
58
  const baseScopes = [
42
59
  "openid",
43
60
  "profile",
@@ -89,7 +106,8 @@ async function verifyMcpRequest(request, options = {}) {
89
106
  const auth = options.auth ?? appAuth(request);
90
107
  const state = await stateOf(auth);
91
108
  const url = new URL(request.url);
92
- 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);
109
+ const origin = clientRequestOrigin(request);
110
+ return await verifyToken(token, auth, state, options.resource ?? state.resources.find((entry) => new URL(entry).origin === origin && pathOf(entry) === url.pathname.replace(/\/+$/, "")), url.pathname);
93
111
  }
94
112
  /** The token of an `Authorization: Bearer` header. */
95
113
  const bearerToken = (headers) => /^Bearer\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
@@ -103,11 +121,17 @@ async function verifyAppAccessToken(token, origin, pathname, instance) {
103
121
  return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
104
122
  }
105
123
  async function verifyToken(token, auth, state, resource, path) {
106
- if (!resource?.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: `${path} is not a resource of \`mcpOAuth()\`.` }), void 0];
124
+ const refuse = (reason, detail, clientId, cause) => [mcpErrors.AUTH_MCP_TOKEN_INVALID({
125
+ cause,
126
+ clientId,
127
+ detail,
128
+ reason
129
+ }), void 0];
130
+ if (!resource?.length) return refuse("wrong_resource", `${path} is not a resource of \`mcpOAuth()\`.`);
107
131
  const jwks = await auth.api.getJwks();
108
132
  const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
109
133
  const algorithms = [...new Set(keys.flatMap((key) => typeof key.alg === "string" ? [key.alg] : []))];
110
- if (!algorithms.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the Auth has no signing keys." }), void 0];
134
+ if (!algorithms.length) return refuse("no_keys", "the Auth has no signing keys.");
111
135
  let payload;
112
136
  try {
113
137
  payload = await verifyJwsAccessToken(token, {
@@ -121,18 +145,15 @@ async function verifyToken(token, auth, state, resource, path) {
121
145
  }
122
146
  });
123
147
  } catch (error) {
124
- return [mcpErrors.AUTH_MCP_TOKEN_INVALID({
125
- cause: error,
126
- reason: error instanceof Error ? error.message : "the signature or a claim does not match."
127
- }), void 0];
148
+ return refuse(verifyFailure(error), error instanceof Error ? error.message : "the signature or a claim does not match.", void 0, error);
128
149
  }
129
- 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];
150
+ const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
151
+ if (payload.cnf !== void 0) return refuse("sender_constrained", "sender-constrained access tokens are not supported; use a bearer token.", clientId);
130
152
  const context = await auth.$context;
131
153
  const user = await context.internalAdapter.findUserById(String(payload.sub));
132
- 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];
154
+ if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return refuse("user_gone", "the user does not exist or is banned.", clientId);
133
155
  const policy = findAccessPolicyPlugin(context.options.plugins);
134
- 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];
135
- const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
156
+ if (policy && !await policy.allows(user, `mcp:${user.id}`)) return refuse("not_allowed", "`access.policy` or `VITEHUB_MEMBERS` does not allow the user.", clientId);
136
157
  const client = clientId ? await context.adapter.findOne({
137
158
  model: "oauthClient",
138
159
  where: [{
@@ -140,7 +161,7 @@ async function verifyToken(token, auth, state, resource, path) {
140
161
  value: clientId
141
162
  }]
142
163
  }) : void 0;
143
- if (!clientId || !isRecord(client) || client.disabled) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the OAuth client does not exist or is disabled." }), void 0];
164
+ if (!clientId || !isRecord(client) || client.disabled) return refuse("client_disabled", "the OAuth client does not exist or is disabled.", clientId);
144
165
  const scope = payload.scope;
145
166
  const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
146
167
  if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
@@ -151,7 +172,7 @@ async function verifyToken(token, auth, state, resource, path) {
151
172
  value: payload.sid
152
173
  }]
153
174
  });
154
- 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];
175
+ if (!isRecord(session) || !(session.expiresAt instanceof Date) || session.expiresAt.getTime() <= Date.now()) return refuse("session_ended", "the session does not exist or has expired.", clientId);
155
176
  }
156
177
  return [void 0, {
157
178
  clientId,
@@ -160,6 +181,12 @@ async function verifyToken(token, auth, state, resource, path) {
160
181
  user
161
182
  }];
162
183
  }
184
+ function verifyFailure(error) {
185
+ const code = isRecord(error) ? error.code : void 0;
186
+ if (code === "ERR_JWT_EXPIRED") return "expired";
187
+ if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && isRecord(error) && error.claim === "aud") return "wrong_resource";
188
+ return "malformed";
189
+ }
163
190
  /**
164
191
  * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
165
192
  * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
@@ -208,4 +235,4 @@ async function deleteUnusedMcpClients(options = {}) {
208
235
  return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
209
236
  }
210
237
  }
211
- export { pathOf as a, mcp_token_exports as i, baseScopes as n, stateOf as o, deleteUnusedMcpClients as r, verifyMcpRequest as s, appAuth as t };
238
+ export { mcp_token_exports as a, verifyMcpRequest as c, mcpTokenInvalidReasons as i, baseScopes as n, pathOf as o, deleteUnusedMcpClients as r, stateOf as s, appAuth as t };
package/dist/mcp.d.ts CHANGED
@@ -1,116 +1,7 @@
1
- import { Result } from "@vite-hub/runtime";
1
+ import { a as McpTokenInvalidData, c as VerifyMcpRequestError, d as deleteUnusedMcpClients, f as mcpTokenInvalidReasons, i as McpOAuthErrorCode, l as VerifyMcpRequestOptions, n as McpCaller, o as McpTokenInvalidError, p as verifyMcpRequest, r as McpOAuthAuth, s as McpTokenInvalidReason, t as DeleteUnusedMcpClientsOptions, u as VerifyMcpRequestResult } from "./mcp-token-CmQbXbTu.js";
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
- type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
6
- /** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
7
- interface McpOAuthAuth {
8
- $context: Promise<{
9
- baseURL: string;
10
- options: {
11
- plugins?: ReadonlyArray<{
12
- id?: string;
13
- options?: unknown;
14
- }>;
15
- };
16
- internalAdapter: {
17
- findUserById: (id: string) => Promise<unknown>;
18
- };
19
- adapter: {
20
- findOne: (input: {
21
- model: string;
22
- where: Array<{
23
- field: string;
24
- value: string;
25
- }>;
26
- }) => Promise<unknown>;
27
- findMany: (input: {
28
- model: string;
29
- where: Array<{
30
- field: string;
31
- operator?: "lt";
32
- value: Date;
33
- }>;
34
- limit?: number;
35
- }) => Promise<unknown[]>;
36
- count: (input: {
37
- model: string;
38
- where: Array<{
39
- field: string;
40
- value: string;
41
- }>;
42
- }) => Promise<number>;
43
- deleteMany: (input: {
44
- model: string;
45
- where: Array<{
46
- field: string;
47
- value: string;
48
- }>;
49
- }) => Promise<number>;
50
- };
51
- }>;
52
- api: {
53
- getJwks: (...args: never[]) => Promise<unknown>;
54
- getOAuthServerConfig: (...args: never[]) => unknown;
55
- getOpenIdConfig: (...args: never[]) => unknown;
56
- };
57
- }
58
- /** The person and the client of a valid MCP access token. */
59
- interface McpCaller {
60
- /** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
61
- user: {
62
- id: string;
63
- email?: string | null;
64
- name?: string | null;
65
- image?: string | null;
66
- [key: string]: unknown;
67
- };
68
- /** The scopes that the person approved. */
69
- scopes: string[];
70
- /** The OAuth client id, from `azp` or `client_id`. */
71
- clientId: string;
72
- /** The name the client registered, such as "Claude Code". */
73
- clientName: string | undefined;
74
- }
75
- /** Options of {@link verifyMcpRequest}. */
76
- interface VerifyMcpRequestOptions {
77
- /** The Better Auth instance. Defaults to the app Auth for the request. */
78
- auth?: McpOAuthAuth;
79
- /**
80
- * The resource that the token must name as its audience, or a list of which it must name one. Defaults to the
81
- * `mcpOAuth()` resource at the path of the request.
82
- */
83
- resource?: string | readonly string[];
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
- export declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<Result<McpCaller, "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING">>;
97
- /** Options of {@link deleteUnusedMcpClients}. */
98
- interface DeleteUnusedMcpClientsOptions {
99
- /** The Better Auth instance. Defaults to the app Auth. */
100
- auth?: McpOAuthAuth;
101
- /** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
102
- olderThan?: number;
103
- /** Clients checked in one call. Defaults to 500. */
104
- limit?: number;
105
- }
106
- /**
107
- * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
108
- * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
109
- * of deleted clients.
110
- */
111
- export declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
112
- deleted: number;
113
- }, "AUTH_MCP_CLEANUP_FAILED">>;
114
5
  /**
115
6
  * OAuth 2.1 sign-in for an MCP server of the app, with Better Auth as the authorization server. `mcpOAuth()` adds the
116
7
  * plugins, `serveMcpOAuthDiscovery()` answers the well-known documents at the origin root, `verifyMcpRequest()` checks the
@@ -191,4 +82,4 @@ export interface McpOAuthDiscoveryOptions {
191
82
  * ```
192
83
  */
193
84
  export declare function serveMcpOAuthDiscovery(request: Request, options?: McpOAuthDiscoveryOptions): Promise<Response | undefined>;
194
- export type { DeleteUnusedMcpClientsOptions, McpCaller, McpOAuthAuth, McpOAuthErrorCode, VerifyMcpRequestOptions };
85
+ export { type DeleteUnusedMcpClientsOptions, type McpCaller, type McpOAuthAuth, type McpOAuthErrorCode, type McpTokenInvalidData, type McpTokenInvalidError, type McpTokenInvalidReason, type VerifyMcpRequestError, type VerifyMcpRequestOptions, type VerifyMcpRequestResult, deleteUnusedMcpClients, mcpTokenInvalidReasons, verifyMcpRequest };
package/dist/mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
+ import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
2
3
  import { r as mcpRegistrationPluginId } from "./mcp-config-C7srUMIZ.js";
3
- import { a as pathOf, n as baseScopes, o as stateOf, r as deleteUnusedMcpClients, s as verifyMcpRequest, t as appAuth } from "./mcp-token--KuLYEub.js";
4
+ import { c as verifyMcpRequest, i as mcpTokenInvalidReasons, n as baseScopes, o as pathOf, r as deleteUnusedMcpClients, s as stateOf, t as appAuth } from "./mcp-token-CuqdbBy8.js";
4
5
  import { APIError, createAuthMiddleware } from "better-auth/api";
5
6
  import { oauthProvider, oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
6
7
  import { jwt } from "better-auth/plugins";
@@ -149,7 +150,8 @@ async function serveMcpOAuthDiscovery(request, options = {}) {
149
150
  return answer;
150
151
  }
151
152
  async function discoveryDocument(request, document, options) {
152
- const { origin, pathname } = new URL(request.url);
153
+ const { pathname } = new URL(request.url);
154
+ const origin = clientRequestOrigin(request);
153
155
  const suffix = pathname.slice(`/.well-known/${document}`.length).replace(/\/+$/, "");
154
156
  const auth = options.auth ?? appAuth(request);
155
157
  const state = await stateOf(auth);
@@ -168,4 +170,4 @@ async function discoveryDocument(request, document, options) {
168
170
  if (suffix && suffix !== pathOf(state.issuer)) return void 0;
169
171
  return (document === "oauth-authorization-server" ? oauthProviderAuthServerMetadata(auth) : oauthProviderOpenIdConfigMetadata(auth))(request);
170
172
  }
171
- export { deleteUnusedMcpClients, mcpOAuth, serveMcpOAuthDiscovery, verifyMcpRequest };
173
+ export { deleteUnusedMcpClients, mcpOAuth, mcpTokenInvalidReasons, serveMcpOAuthDiscovery, verifyMcpRequest };
@@ -1,9 +1,9 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
2
  import { t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
3
3
  import { n as adminClaimVariable, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
4
- import { n as getAuthRuntimeState } from "./runtime-state-DtKUfxKq.js";
4
+ import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
5
5
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
6
- import { a as checkGitHubOrgMember } from "./events-DZqMiae_.js";
6
+ import { a as checkGitHubOrgMember } from "./events-BXU1_9mc.js";
7
7
  import { defineErrors, parseDuration } from "@vite-hub/runtime";
8
8
  import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
9
9
  import { createSessionStore, deleteSessionCookie, expireCookie, parseCookies } from "better-auth/cookies";
@@ -2,7 +2,7 @@ import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
2
2
  // ../internal/src/nitro-kit.ts
3
3
  /**
4
4
  * The route meta of a ViteHub handler that Auth access routes leave alone, such as the Console RPC. The handler takes
5
- * only its own signed requests and one-time links, so app access rules do not apply to it.
5
+ * only its own signed requests and signed Site access tokens, so app access rules do not apply to it.
6
6
  */
7
7
  const ownAccessHandlerMeta = Object.freeze({ vitehubAuthAccess: "handler" });
8
8
  /**
package/dist/nuxt.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { Dt as AuthPages, Et as AuthPageMode, Tt as AuthPageMeta, w as AuthOptions } from "./types-BHSgxyvV.js";
2
+ import { Ct as AuthPageMeta, Tt as AuthPages, w as AuthOptions, wt as AuthPageMode } from "./types-DmH31d2t.js";
3
3
  import "vite";
4
4
  interface NuxtLayerDirectoryConfig {
5
5
  rootDir?: string;
package/dist/nuxt.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as writeNuxtAuthDefinition, d as cachingRuleNames, f as createCachingRouteRuleFinder, h as resolveViteHubProjectRoot, l as resolveAuthViteConfig, m as resolveNuxtServerDirs, o as createAuthNitroConfig, p as methodOrder, s as hubAuth, u as authAbilitiesCandidates } from "./vite-D1xC9n1O.js";
2
- import { i as normalizePagePath, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-BwImVHN_.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { c as writeNuxtAuthDefinition, d as cachingRuleNames, f as createCachingRouteRuleFinder, h as resolveViteHubProjectRoot, l as resolveAuthViteConfig, m as resolveNuxtServerDirs, o as createAuthNitroConfig, p as methodOrder, s as hubAuth, u as authAbilitiesCandidates } from "./vite-CpWhT1Wi.js";
2
+ import { i as normalizePagePath, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-9aKr6z-k.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
4
4
  import { realpathSync } from "node:fs";
5
5
  import { dirname, isAbsolute, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
@@ -1,4 +1,4 @@
1
- import { E as AuthRequestInput } from "./types-BHSgxyvV.js";
1
+ import { E as AuthRequestInput } from "./types-DmH31d2t.js";
2
2
  /**
3
3
  * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
4
4
  * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
@@ -1,4 +1,4 @@
1
- import { n as ownAccessHandlerMeta, r as ownAccessRouteMeta } from "./nitro-kit-Bg4xUZAI.js";
1
+ import { n as ownAccessHandlerMeta, r as ownAccessRouteMeta } from "./nitro-kit-BumWIKa5.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  // src/own-access.ts
4
4
  /**
package/dist/presets.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
2
  import { parseDuration } from "@vite-hub/runtime";
3
3
  // src/presets.ts
4
4
  const defaultStatelessMaxAge = 604800;
@@ -0,0 +1 @@
1
+ export default function authClientRequestPlugin(nitroApp: unknown): void;
@@ -0,0 +1,18 @@
1
+ import { t as isRecord } from "../object-CAK6UYR5.js";
2
+ import { r as runWithClientRequest } from "../client-request-BzMKtfCY.js";
3
+ // src/runtime/client-request-plugin.ts
4
+ function isRequest(value) {
5
+ return isRecord(value) && typeof value.url === "string" && value.headers instanceof Headers;
6
+ }
7
+ function authClientRequestPlugin(nitroApp) {
8
+ if (!isRecord(nitroApp)) return;
9
+ const h3 = nitroApp.h3;
10
+ const owner = isRecord(h3) && h3.fetch instanceof Function ? h3 : nitroApp;
11
+ const fetch = owner.fetch;
12
+ if (!(fetch instanceof Function)) return;
13
+ owner.fetch = (request, ...rest) => {
14
+ const call = () => Reflect.apply(fetch, owner, [request, ...rest]);
15
+ return isRequest(request) ? runWithClientRequest(request, call) : call();
16
+ };
17
+ }
18
+ export { authClientRequestPlugin as default };
@@ -1,3 +1,3 @@
1
1
  import "../server.js";
2
- import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-CFWlYQJb.js";
2
+ import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-C4Kni3Vj.js";
3
3
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,4 +1,4 @@
1
- import { g as listAuthEvents, t as aggregateAuthEvents } from "../server-D4Hi4TBI.js";
2
- import { t as authForRequest } from "../auth-instance-_J7R9Qs1.js";
1
+ import { g as listAuthEvents, t as aggregateAuthEvents } from "../server-Iru6jcnW.js";
2
+ import { t as authForRequest } from "../auth-instance-BWiRS9QZ.js";
3
3
  import "../server.js";
4
4
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,3 +1,3 @@
1
- import { s as AbilityRules } from "../abilities-3L1Y5Pnw.js";
1
+ import { s as AbilityRules } from "../abilities-BYOcyQ9B.js";
2
2
  declare const abilities: AbilityRules;
3
3
  export { abilities as default };
@@ -1,4 +1,4 @@
1
- import { _ as AuthDefinition } from "../types-BHSgxyvV.js";
1
+ import { _ as AuthDefinition } from "../types-DmH31d2t.js";
2
2
  declare const definition: AuthDefinition | undefined;
3
3
  export declare function getAuthApp(): object | undefined;
4
4
  export { definition as default };
@@ -1,3 +1,3 @@
1
- import { t as authAccessHandlerMeta } from "../own-access-C22hSIuF.js";
2
- import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-DCsgxFPP.js";
1
+ import { t as authAccessHandlerMeta } from "../own-access-BNcxKrDl.js";
2
+ import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-BHniJi2m.js";
3
3
  export { AuthAccessRouteMatch, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,8 +1,8 @@
1
1
  import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-zKi7NrvK.js";
2
- import { t as authErrorDiagnostics } from "../error-diagnostics-BssJr_2t.js";
3
- import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-DQgqxTbI.js";
2
+ import { t as authErrorDiagnostics } from "../error-diagnostics-CUPwukgE.js";
3
+ import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-CYsakJiH.js";
4
4
  import { r as unwrapAuthRequest } from "../request-Dpq7GO8B.js";
5
- import { n as getAuthRuntimeState } from "../runtime-state-DtKUfxKq.js";
5
+ import { t as getAuthRuntimeState } from "../runtime-state-C0Rd1W4m.js";
6
6
  // src/runtime/server.ts
7
7
  function setAuthRuntimeEnvResolver(resolver, definition) {
8
8
  const state = getAuthRuntimeState();
@@ -0,0 +1,15 @@
1
+ // src/runtime-state.ts
2
+ const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
3
+ function getAuthRuntimeState() {
4
+ const globalScope = globalThis;
5
+ globalScope[authRuntimeStateKey] ??= {};
6
+ globalScope[authRuntimeStateKey].envResolvers ??= /* @__PURE__ */ new WeakMap();
7
+ return globalScope[authRuntimeStateKey];
8
+ }
9
+ function resetAuth() {
10
+ const state = getAuthRuntimeState();
11
+ state.auth = void 0;
12
+ state.definition = void 0;
13
+ state.providers = void 0;
14
+ }
15
+ export { resetAuth as n, getAuthRuntimeState as t };
package/dist/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AuthSchemaPlugin, c as AuthTableSpec, d as resolveAuthTableSpecs, i as AuthSchemaOptions, l as authPluginSchemas, n as AuthCoreTableSpecs, o as AuthTableField, r as AuthPluginSchemas, s as AuthTableName, t as AuthCoreModel, u as authTableSpecs } from "./table-specs-BLm_Zlss.js";
1
+ import { a as AuthSchemaPlugin, c as AuthTableSpec, d as resolveAuthTableSpecs, i as AuthSchemaOptions, l as authPluginSchemas, n as AuthCoreTableSpecs, o as AuthTableField, r as AuthPluginSchemas, s as AuthTableName, t as AuthCoreModel, u as authTableSpecs } from "./table-specs-P4LvbOlX.js";
2
2
  import { $Type, BuildColumns, HasDefault, IsPrimaryKey, NotNull } from "drizzle-orm";
3
3
  import { PgBigInt53Builder, PgBooleanBuilder, PgBuildColumns, PgColumn, PgIntegerBuilder, PgJsonbBuilder, PgTableWithColumns, PgTextBuilder, PgTimestampBuilder } from "drizzle-orm/pg-core";
4
4
  import { SQLiteBooleanBuilder, SQLiteColumn, SQLiteIntegerBuilder, SQLiteTableWithColumns, SQLiteTextBuilder, SQLiteTextJsonBuilder, SQLiteTimestampBuilder } from "drizzle-orm/sqlite-core";
package/dist/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-jw0jjU6l.js";
1
+ import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-CCSY4tiS.js";
2
2
  import { sql } from "drizzle-orm";
3
3
  import { bigint, boolean, foreignKey, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
4
4
  import { foreignKey as foreignKey$1, index as index$1, integer as integer$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from "drizzle-orm/sqlite-core";
@@ -1,5 +1,5 @@
1
- import "./own-access-C22hSIuF.js";
2
- import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-BHSgxyvV.js";
1
+ import "./own-access-BNcxKrDl.js";
2
+ import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-DmH31d2t.js";
3
3
  import { AccessAuthorizationContext, ViteHubContext } from "@vite-hub/runtime";
4
4
  type AuthRuntimeEnvResolver = (event?: ViteHubContext) => Record<string, unknown>;
5
5
  type AuthAccessIdentityResolver = (request: Request, event: AuthRequestInput, hasSession: boolean) => Promise<AccessAuthorizationContext<unknown, false>["user"] | Response | undefined>;