@vite-hub/auth 0.5.1 → 0.6.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 (69) hide show
  1. package/README.md +2 -2
  2. package/dist/{abilities-3L1Y5Pnw.d.ts → abilities-D3XlrYDw.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-BpI9Ps8A.js} +64 -54
  8. package/dist/cli.js +1 -1
  9. package/dist/{console-runtime-vc3JQEuq.js → console-runtime-CaIXVtB_.js} +7 -206
  10. package/dist/console-runtime-DAjLTLrN.d.ts +32 -0
  11. package/dist/console-runtime.d.ts +3 -3
  12. package/dist/console-runtime.js +1 -1
  13. package/dist/{console-types-51lkf0lk.js → console-types-NrX5TWl3.js} +2 -1
  14. package/dist/console.d.ts +3 -3
  15. package/dist/console.js +1 -1
  16. package/dist/{database-options-DQ-8qYMl.js → database-options-B87hDU4j.js} +1 -1
  17. package/dist/{database-schema-options-CkSeU9V3.js → database-schema-options-peXHNLkJ.js} +1 -1
  18. package/dist/database.d.ts +2 -2
  19. package/dist/database.js +5 -5
  20. package/dist/{definition-MDGMNKrK.js → definition-BypPLIbI.js} +3 -3
  21. package/dist/{error-diagnostics-BssJr_2t.js → error-diagnostics-CUPwukgE.js} +1 -1
  22. package/dist/{events-DZqMiae_.js → events-BXU1_9mc.js} +2 -1
  23. package/dist/forward-sign-ins-BWXPPTRz.js +4 -0
  24. package/dist/forward.d.ts +24 -0
  25. package/dist/forward.js +42 -4
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +3 -3
  28. package/dist/internal/server.d.ts +2 -2
  29. package/dist/internal/server.js +4 -4
  30. package/dist/mcp-token-CmQbXbTu.d.ts +125 -0
  31. package/dist/{mcp-token--KuLYEub.js → mcp-token-DzGivm7f.js} +42 -17
  32. package/dist/mcp.d.ts +2 -111
  33. package/dist/mcp.js +2 -2
  34. package/dist/{members-D3_Q5XJb.js → members-CwPIx10t.js} +3 -3
  35. package/dist/{nitro-kit-Bg4xUZAI.js → nitro-kit-BumWIKa5.js} +1 -1
  36. package/dist/nuxt.d.ts +1 -1
  37. package/dist/nuxt.js +3 -3
  38. package/dist/{own-access-DQgqxTbI.js → own-access-CYsakJiH.js} +1 -1
  39. package/dist/{own-access-C22hSIuF.d.ts → own-access-Dt-I5-PT.d.ts} +1 -1
  40. package/dist/presets.js +1 -1
  41. package/dist/runtime/console.d.ts +1 -1
  42. package/dist/runtime/console.js +2 -2
  43. package/dist/runtime/empty-abilities.d.ts +1 -1
  44. package/dist/runtime/empty-definition.d.ts +1 -1
  45. package/dist/runtime/server.d.ts +2 -2
  46. package/dist/runtime/server.js +3 -3
  47. package/dist/runtime-state-C0Rd1W4m.js +15 -0
  48. package/dist/schema.d.ts +1 -1
  49. package/dist/schema.js +1 -1
  50. package/dist/{server-CFWlYQJb.d.ts → server-Cun232hb.d.ts} +13 -8
  51. package/dist/{server-DCsgxFPP.d.ts → server-DL9MSuyj.d.ts} +2 -2
  52. package/dist/{server-D4Hi4TBI.js → server-_eUOlAJ8.js} +11 -11
  53. package/dist/server.d.ts +3 -2
  54. package/dist/server.js +2 -2
  55. package/dist/{session-cookies-1FMcMnRh.js → session-cookies-fR6Pv4kD.js} +2 -2
  56. package/dist/{set-cookie-DkqM1kvj.js → set-cookie-DVfi-nJX.js} +1 -1
  57. package/dist/{table-specs-jw0jjU6l.js → table-specs-CCSY4tiS.js} +17 -14
  58. package/dist/{table-specs-BLm_Zlss.d.ts → table-specs-P4LvbOlX.d.ts} +28 -21
  59. package/dist/test.d.ts +1 -1
  60. package/dist/test.js +2 -2
  61. package/dist/{types-BHSgxyvV.d.ts → types-BP9_XUr9.d.ts} +3 -21
  62. package/dist/{vite-D1xC9n1O.js → vite-Dem1i1rL.js} +92 -27
  63. package/dist/vite.d.ts +1 -1
  64. package/dist/vite.js +1 -1
  65. package/dist/vue.d.ts +2 -2
  66. package/dist/vue.js +1 -1
  67. package/package.json +8 -8
  68. package/dist/console-runtime-BP1ZKJB0.d.ts +0 -71
  69. package/dist/runtime-state-DtKUfxKq.js +0 -24
package/dist/console.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AuthConsoleEventGroup, Ct as authConsoleActionNames, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as AuthConsoleValue, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleRoles, at as AuthConsoleHostSession, bt as AuthConsoleUser, ct as AuthConsoleList, dt as AuthConsoleOrganization, et as AuthConsoleEventUser, ft as AuthConsoleOrganizationDetail, gt as AuthConsoleQuery, ht as AuthConsolePolicy, it as AuthConsoleHostOptions, lt as AuthConsoleMutation, mt as AuthConsolePage, nt as AuthConsoleFieldPolicy, ot as AuthConsoleHostUserInput, pt as AuthConsoleOverview, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleImpersonation, tt as AuthConsoleField, ut as AuthConsoleOptions, vt as AuthConsoleSession, wt as authConsoleEventGroups, xt as AuthConsoleUserDetail, yt as AuthConsoleSessionUser } from "./types-BHSgxyvV.js";
1
+ import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-BP9_XUr9.js";
2
2
  /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
3
3
  interface ViteHubConsoleDefinitionCatalogView {
4
4
  kind: "definition-catalog";
@@ -66,7 +66,7 @@ interface ViteHubConsoleOperationAction {
66
66
  operation: string;
67
67
  input: Readonly<Record<string, string>>;
68
68
  /**
69
- * The result is `{ url }`, such as a one-time link or a provider sign-in: the Console opens it in a new tab, and loads
69
+ * The result is `{ url }`, such as a provider sign-in: the Console opens it in a new tab, and loads
70
70
  * the list again when the person comes back. The URL must be `https:`, or `http:` on a loopback host.
71
71
  */
72
72
  tab?: true;
@@ -212,4 +212,4 @@ interface ViteHubConsoleSectionDescriptor<TView extends ViteHubConsoleSectionVie
212
212
  }
213
213
  /** The owner descriptor. The host supplies the navigation and renders the Auth views. */
214
214
  export declare const authConsoleSection: ViteHubConsoleAuthSection;
215
- export { type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type AuthConsoleHostSession, type AuthConsoleHostUserInput, type AuthConsoleImpersonation, type AuthConsoleList, type AuthConsoleMutation, type AuthConsoleOptions, type AuthConsoleOrganization, type AuthConsoleOrganizationDetail, type AuthConsoleOverview, type AuthConsolePage, type AuthConsolePolicy, type AuthConsoleQuery, type AuthConsoleRoles, type AuthConsoleSession, type AuthConsoleSessionUser, type AuthConsoleUser, type AuthConsoleUserDetail, type AuthConsoleValue, type authConsoleActionNames, authConsoleEventGroups };
215
+ export { type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type AuthConsoleImpersonation, type AuthConsoleList, type AuthConsoleMutation, type AuthConsoleOptions, type AuthConsoleOrganization, type AuthConsoleOrganizationDetail, type AuthConsoleOverview, type AuthConsolePage, type AuthConsolePolicy, type AuthConsoleQuery, type AuthConsoleRoles, type AuthConsoleSession, type AuthConsoleSessionUser, type AuthConsoleUser, type AuthConsoleUserDetail, type AuthConsoleValue, type authConsoleActionNames, authConsoleEventGroups };
package/dist/console.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as authConsoleEventGroups } from "./console-types-51lkf0lk.js";
1
+ import { n as authConsoleEventGroups } from "./console-types-NrX5TWl3.js";
2
2
  // src/console.ts
3
3
  /** The owner descriptor. The host supplies the navigation and renders the Auth views. */
4
4
  const authConsoleSection = {
@@ -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
  // src/database-options.ts
3
3
  /** Reads the adapter's target without loading Better Auth or the Database runtime. */
4
4
  function authDatabaseName(database) {
@@ -1,4 +1,4 @@
1
- import { a as authDatabaseSchemaError } from "./database-options-DQ-8qYMl.js";
1
+ import { a as authDatabaseSchemaError } from "./database-options-B87hDU4j.js";
2
2
  import { getAuthTables } from "better-auth/db";
3
3
  // src/database-schema-options.ts
4
4
  /** Better Auth reads each table by its key and each column by its field key, so the options must not rename them. */
@@ -1,7 +1,7 @@
1
- import { f as AuthAppDatabase } from "./types-BHSgxyvV.js";
1
+ import { f as AuthAppDatabase } from "./types-BP9_XUr9.js";
2
2
  /**
3
3
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
4
- * `database` of `defineAuth()`. Auth then adds the Better Auth tables, with the fields of `admin()`, the
4
+ * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
5
5
  * Console MCP OAuth tables, the table of Better Auth's limiter, the `additionalFields` of the Definition, and the tables of
6
6
  * the plugins that it calls, such as `twoFactor()` and `apiKey()`, to that Database. The adapter uses the Database of each
7
7
  * request: SQLite, libSQL, Cloudflare D1, or Postgres.
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
2
- import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-DQ-8qYMl.js";
3
- import { t as assertAuthDatabaseNames } from "./database-schema-options-CkSeU9V3.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
+ import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
3
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-peXHNLkJ.js";
4
4
  import { getAuthTables } from "better-auth/db";
5
5
  import { getTableColumns, is, isTable } from "drizzle-orm";
6
6
  import { drizzleAdapter } from "better-auth/adapters/drizzle";
@@ -12,7 +12,7 @@ import { PgAsyncDatabase } from "drizzle-orm/pg-core";
12
12
  * tables of the Database, before the adapter opens it.
13
13
  */
14
14
  function assertAuthDatabaseSchema(options, schema, database) {
15
- const fix = "Call the plugin in `server/auth.ts`, or in a file that it imports with a relative path, and write `additionalFields` inline in `server/auth.ts`, so that the Auth Vite plugin adds the columns. Then run `vitehub database generate` and apply the migration";
15
+ const fix = "Import the plugin by name from its package, such as `import { admin } from \"better-auth/plugins\"`, and call it in `server/auth.ts` or in a file that it imports with a relative path. Auth does not read a default import of the plugin, or a namespace that a local file re-exports. Write `additionalFields` inline in `server/auth.ts`, so that the Auth Vite plugin adds the columns. Then run `vitehub database generate` and apply the migration";
16
16
  for (const [model, table] of Object.entries(getAuthTables(options))) {
17
17
  const drizzleTable = Object.hasOwn(schema, model) ? schema[model] : void 0;
18
18
  if (!isTable(drizzleTable)) throw authDatabaseSchemaError(`the ${JSON.stringify(database)} Database has no \`${model}\` table. ${fix}`);
@@ -22,7 +22,7 @@ function assertAuthDatabaseSchema(options, schema, database) {
22
22
  }
23
23
  /**
24
24
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
25
- * `database` of `defineAuth()`. Auth then adds the Better Auth tables, with the fields of `admin()`, the
25
+ * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
26
26
  * Console MCP OAuth tables, the table of Better Auth's limiter, the `additionalFields` of the Definition, and the tables of
27
27
  * the plugins that it calls, such as `twoFactor()` and `apiKey()`, to that Database. The adapter uses the Database of each
28
28
  * request: SQLite, libSQL, Cloudflare D1, or Postgres.
@@ -1,8 +1,8 @@
1
- import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-BwImVHN_.js";
1
+ import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-9aKr6z-k.js";
2
2
  import { t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
- import { r as authDatabaseName } from "./database-options-DQ-8qYMl.js";
5
+ import { r as authDatabaseName } from "./database-options-B87hDU4j.js";
6
6
  import { parseDuration } from "@vite-hub/runtime";
7
7
  // src/stateless-user-id.ts
8
8
  const pendingUserIds = /* @__PURE__ */ new WeakMap();
@@ -122,7 +122,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
122
122
  AUTH_C0053: withFix("Remove `advanced.database.generateId`, or set it to a function that returns strings. Use another Better Auth adapter for numeric or UUID IDs."),
123
123
  AUTH_C0054: withFix("Call `authDatabase()` inline as `database` in the object of `defineAuth()`, or in the one object that its callback returns. Do not select it in a branch."),
124
124
  AUTH_C0055: withFix("Write `additionalFields` inline in `server/auth.ts`, with a literal `type` for each field, for example `user: { additionalFields: { login: { type: 'string', required: false } } }`."),
125
- AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, call it in `server/auth.ts` or in a file that `server/auth.ts` imports with a relative path, so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
125
+ AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, import it by name from its package, such as `import { admin } from 'better-auth/plugins'`, and call it in `server/auth.ts` or in a file that `server/auth.ts` imports with a relative path, so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
126
126
  AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217`."),
127
127
  AUTH_C0058: withFix("Write each `VITEHUB_ADMINS` entry as `<provider>:<account id>`, for example `github:22072217`. Run `gh api users/<login> --jq .id` to get a GitHub account id. For an app with only email sign-in, remove `VITEHUB_ADMINS`, then run `vitehub auth claim`."),
128
128
  AUTH_C0059: withFix("Run `vitehub auth claim` and set `VITEHUB_ADMIN_CLAIM` to the `sha256:` value that it prints. Do not set the code itself."),
@@ -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 { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { defineErrors } from "@vite-hub/runtime";
4
4
  import { sql } from "drizzle-orm";
@@ -115,6 +115,7 @@ const authEventTypes = [
115
115
  "user.signed_out",
116
116
  "sign_in.failed",
117
117
  "session.revoked",
118
+ "session.expired",
118
119
  "user.banned",
119
120
  "user.unbanned",
120
121
  "user.role_changed",
@@ -0,0 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // src/forward-sign-ins.ts
3
+ const forwardSignIns = new AsyncLocalStorage();
4
+ export { forwardSignIns as t };
package/dist/forward.d.ts CHANGED
@@ -26,6 +26,23 @@ export interface ForwardAuthVerifyContext {
26
26
  /** The request, when Better Auth has one. A direct `auth.api` call has only headers. */
27
27
  request?: Request;
28
28
  }
29
+ /** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
30
+ export declare const forwardAuthRefusalCodes: readonly ["account_not_linked", "unable_to_link_account", "unable_to_update_account", "signup_disabled", "unable_to_create_user", "email_not_verified", "unable_to_create_session", "denied", "refused"];
31
+ export type ForwardAuthRefusalCode = typeof forwardAuthRefusalCodes[number];
32
+ /** What `onRefused` gets when Better Auth refuses to sign in an identity that `verify` returned. */
33
+ export interface ForwardAuthRefusal {
34
+ /**
35
+ * Why Better Auth refused, such as `account_not_linked` for an existing user whose email the identity does not prove.
36
+ * `denied` when Better Auth threw a client error, such as a `user.validateUserInfo` refusal or an `APIError` from a
37
+ * session hook, which is in `error`. `refused` for a reason this version does not know.
38
+ */
39
+ code: ForwardAuthRefusalCode;
40
+ /** The `APIError` that Better Auth threw, when `code` is `denied`. */
41
+ error?: unknown;
42
+ identity: ForwardedIdentity;
43
+ headers: Headers;
44
+ request?: Request;
45
+ }
29
46
  export interface ForwardAuthOptions {
30
47
  /** The request header that the proxy sets, such as `x-auth-request-access-token` or `cf-access-jwt-assertion`. */
31
48
  header: string;
@@ -36,6 +53,13 @@ export interface ForwardAuthOptions {
36
53
  * so cache slow checks in it.
37
54
  */
38
55
  verify: (context: ForwardAuthVerifyContext) => ForwardedIdentity | null | Promise<ForwardedIdentity | null>;
56
+ /**
57
+ * Runs when Better Auth refuses to sign in an identity that `verify` returned, for a log or a metric. A refusal that
58
+ * Better Auth returns leaves the request signed out; a client error that it throws, such as the `403` of
59
+ * `user.validateUserInfo`, still answers the request. Auth calls it on each such request, before the response, and a
60
+ * thrown error fails the request.
61
+ */
62
+ onRefused?: (refusal: ForwardAuthRefusal) => void | Promise<void>;
39
63
  }
40
64
  export declare const forwardAuthPluginId = "vitehub-forward-auth";
41
65
  /**
package/dist/forward.js CHANGED
@@ -1,9 +1,27 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
+ import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
2
3
  import { createAuthMiddleware } from "better-auth/api";
3
4
  import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
4
5
  import { handleOAuthUserInfo, setTokenUtil } from "better-auth/oauth2";
6
+ import { APIError as APIError$1 } from "better-auth";
5
7
  // src/forward.ts
8
+ /** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
9
+ const forwardAuthRefusalCodes = [
10
+ "account_not_linked",
11
+ "unable_to_link_account",
12
+ "unable_to_update_account",
13
+ "signup_disabled",
14
+ "unable_to_create_user",
15
+ "email_not_verified",
16
+ "unable_to_create_session",
17
+ "denied",
18
+ "refused"
19
+ ];
6
20
  const forwardAuthPluginId = "vitehub-forward-auth";
21
+ const refusalCode = (error) => {
22
+ const code = typeof error === "string" ? error.trim().toLowerCase().replaceAll(" ", "_") : "";
23
+ return forwardAuthRefusalCodes.find((entry) => entry === code) ?? "refused";
24
+ };
7
25
  const nonEmpty = (value) => typeof value === "string" && value.trim().length > 0;
8
26
  function assertIdentity(value) {
9
27
  const field = (name) => value instanceof Object ? Reflect.get(value, name) : void 0;
@@ -19,7 +37,7 @@ function assertIdentity(value) {
19
37
  function forwardAuth(options) {
20
38
  const header = options?.header;
21
39
  if (!nonEmpty(header) || typeof options.verify !== "function") throw authErrorDiagnostics.AUTH_C0067({ message: "`forwardAuth()` needs a `header` name and a `verify` function. Auth never trusts a forwarded header without `verify`." });
22
- const verify = options.verify;
40
+ const { onRefused, verify } = options;
23
41
  const sessions = /* @__PURE__ */ new Map();
24
42
  const signIns = /* @__PURE__ */ new Map();
25
43
  return {
@@ -75,7 +93,7 @@ function forwardAuth(options) {
75
93
  let session = reusable ? await live(reusable.token) : null;
76
94
  if (!session || session.session.userId !== reusable?.userId) {
77
95
  sessions.delete(key);
78
- const { data } = await handleOAuthUserInfo(ctx, {
96
+ const signIn = () => handleOAuthUserInfo(ctx, {
79
97
  userInfo: {
80
98
  id: identity.accountId,
81
99
  email: identity.email,
@@ -90,7 +108,27 @@ function forwardAuth(options) {
90
108
  },
91
109
  overrideUserInfo: true
92
110
  });
111
+ let result;
112
+ try {
113
+ result = await forwardSignIns.run(true, signIn);
114
+ } catch (error) {
115
+ if (error instanceof APIError$1 && error.statusCode < 500) await onRefused?.({
116
+ code: "denied",
117
+ error,
118
+ identity,
119
+ headers,
120
+ ...ctx.request ? { request: ctx.request } : {}
121
+ });
122
+ throw error;
123
+ }
124
+ const { data, error } = result;
93
125
  if (!data) {
126
+ await onRefused?.({
127
+ code: refusalCode(error),
128
+ identity,
129
+ headers,
130
+ ...ctx.request ? { request: ctx.request } : {}
131
+ });
94
132
  deleteSessionCookie(ctx);
95
133
  applySetCookies(headers, ctx.responseHeaders?.getSetCookie() ?? []);
96
134
  ctx.context.session = null;
@@ -116,4 +154,4 @@ function forwardAuth(options) {
116
154
  }] }
117
155
  };
118
156
  }
119
- export { forwardAuth, forwardAuthPluginId };
157
+ export { forwardAuth, forwardAuthPluginId, forwardAuthRefusalCodes };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { A as AuthRuntimeEnv, At as AuthEventActor, B as DiscoveredAuthDefinition, Bt as AuthEventsConfiguration, C as AuthGuardedHandler, D as AuthReservedOption, F as AuthSessionRefresh, Ft as AuthEventPage, Ht as defaultAuthEventRetention, I as AuthSessionRefreshContext, It as AuthEventRetention, L as AuthSessionRefreshFields, Lt as AuthEventStore, M as AuthRuntimeOption, Mt as AuthEventCounts, N as AuthRuntimeOptions, Nt as AuthEventListInput, O as AuthResolvedDefinitionOptions, Ot as AuthDevice, P as AuthSessionOptions, Pt as AuthEventMetadata, R as AuthSignInConfiguration, Rt as AuthEventType, S as AuthFor, T as AuthRequest, U as ResolvedAuthViteConfig, V as RegisteredAuth, Vt as createDatabaseAuthEventStore, W as ViteHubAuth, X as AuthConsoleColumn, _ as AuthDefinition, _t as AuthConsoleRoles, a as AuthAccessPolicy, b as AuthDefinitionResolver, c as AuthAccessRouteConfiguration, d as AuthAnonymousGuardedHandler, g as AuthComponentsOptions, h as AuthBetterAuthRuntimeOptions, ht as AuthConsolePolicy, i as AuthAccessConfiguration, j as AuthRuntimeOnlyOptions, jt as AuthEventAggregates, k as AuthRuntimeContext, kt as AuthEvent, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, nt as AuthConsoleFieldPolicy, o as AuthAccessPolicyContext, p as AuthAuthorization, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, ut as AuthConsoleOptions, v as AuthDefinitionInput, w as AuthOptions, x as AuthDeleteAccountOptions, y as AuthDefinitionOptions, z as AuthViteHubOptions, zt as AuthEventWindow } from "./types-BHSgxyvV.js";
3
- import { n as checksOwnAccess } from "./own-access-C22hSIuF.js";
2
+ import { A as AuthRuntimeEnv, At as AuthEventCounts, B as DiscoveredAuthDefinition, Bt as defaultAuthEventRetention, C as AuthGuardedHandler, D as AuthReservedOption, Dt as AuthEvent, Et as AuthDevice, F as AuthSessionRefresh, Ft as AuthEventStore, I as AuthSessionRefreshContext, It as AuthEventType, L as AuthSessionRefreshFields, Lt as AuthEventWindow, M as AuthRuntimeOption, Mt as AuthEventMetadata, N as AuthRuntimeOptions, Nt as AuthEventPage, O as AuthResolvedDefinitionOptions, Ot as AuthEventActor, P as AuthSessionOptions, Pt as AuthEventRetention, R as AuthSignInConfiguration, Rt as AuthEventsConfiguration, S as AuthFor, T as AuthRequest, U as ResolvedAuthViteConfig, V as RegisteredAuth, W as ViteHubAuth, X as AuthConsoleColumn, _ as AuthDefinition, a as AuthAccessPolicy, b as AuthDefinitionResolver, c as AuthAccessRouteConfiguration, ct as AuthConsoleOptions, d as AuthAnonymousGuardedHandler, g as AuthComponentsOptions, h as AuthBetterAuthRuntimeOptions, ht as AuthConsoleRoles, i as AuthAccessConfiguration, j as AuthRuntimeOnlyOptions, jt as AuthEventListInput, k as AuthRuntimeContext, kt as AuthEventAggregates, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, nt as AuthConsoleFieldPolicy, o as AuthAccessPolicyContext, p as AuthAuthorization, pt as AuthConsolePolicy, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionInput, w as AuthOptions, x as AuthDeleteAccountOptions, y as AuthDefinitionOptions, z as AuthViteHubOptions, zt as createDatabaseAuthEventStore } from "./types-BP9_XUr9.js";
3
+ import { n as checksOwnAccess } from "./own-access-Dt-I5-PT.js";
4
4
  import { n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-C6AtiRdI.js";
5
5
  import { Result } from "@vite-hub/runtime";
6
6
  export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as defineAuth } from "./definition-MDGMNKrK.js";
2
- import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-DZqMiae_.js";
3
- import { n as checksOwnAccess } from "./own-access-DQgqxTbI.js";
1
+ import { n as defineAuth } from "./definition-BypPLIbI.js";
2
+ import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-BXU1_9mc.js";
3
+ import { n as checksOwnAccess } from "./own-access-CYsakJiH.js";
4
4
  export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
@@ -1,5 +1,5 @@
1
1
  /// <reference path="../host-declarations.d.ts" />
2
- import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-CFWlYQJb.js";
3
- import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-DCsgxFPP.js";
2
+ import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-Cun232hb.js";
3
+ import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-DL9MSuyj.js";
4
4
  import { n as AbilityErrorData, t as AbilityError } from "../ability-error-C1c30O6E.js";
5
5
  export { AbilityError, type AbilityErrorData, AuthEventReadErrorCode, AuthSignOutOptions, 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 };
@@ -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-BpI9Ps8A.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-_eUOlAJ8.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,5 @@
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-BpI9Ps8A.js";
3
3
  import { n as mcpOAuthResources } from "./mcp-config-C7srUMIZ.js";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
@@ -29,8 +29,12 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
29
29
  fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
30
30
  },
31
31
  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."
32
+ why: ({ detail }) => `The access token is not valid: ${detail}`,
33
+ fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again.",
34
+ data: ({ clientId, reason }) => ({
35
+ clientId,
36
+ reason
37
+ })
34
38
  },
35
39
  AUTH_MCP_CLEANUP_FAILED: {
36
40
  why: "The Auth database could not list or delete OAuth clients.",
@@ -38,6 +42,18 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
38
42
  }
39
43
  }
40
44
  });
45
+ /** Why `verifyMcpRequest()` refused a token, in `error.data.reason` of `AUTH_MCP_TOKEN_INVALID`. */
46
+ const mcpTokenInvalidReasons = [
47
+ "expired",
48
+ "malformed",
49
+ "wrong_resource",
50
+ "no_keys",
51
+ "sender_constrained",
52
+ "user_gone",
53
+ "not_allowed",
54
+ "client_disabled",
55
+ "session_ended"
56
+ ];
41
57
  const baseScopes = [
42
58
  "openid",
43
59
  "profile",
@@ -103,11 +119,17 @@ async function verifyAppAccessToken(token, origin, pathname, instance) {
103
119
  return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
104
120
  }
105
121
  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];
122
+ const refuse = (reason, detail, clientId, cause) => [mcpErrors.AUTH_MCP_TOKEN_INVALID({
123
+ cause,
124
+ clientId,
125
+ detail,
126
+ reason
127
+ }), void 0];
128
+ if (!resource?.length) return refuse("wrong_resource", `${path} is not a resource of \`mcpOAuth()\`.`);
107
129
  const jwks = await auth.api.getJwks();
108
130
  const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
109
131
  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];
132
+ if (!algorithms.length) return refuse("no_keys", "the Auth has no signing keys.");
111
133
  let payload;
112
134
  try {
113
135
  payload = await verifyJwsAccessToken(token, {
@@ -121,18 +143,15 @@ async function verifyToken(token, auth, state, resource, path) {
121
143
  }
122
144
  });
123
145
  } 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];
146
+ return refuse(verifyFailure(error), error instanceof Error ? error.message : "the signature or a claim does not match.", void 0, error);
128
147
  }
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];
148
+ const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
149
+ if (payload.cnf !== void 0) return refuse("sender_constrained", "sender-constrained access tokens are not supported; use a bearer token.", clientId);
130
150
  const context = await auth.$context;
131
151
  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];
152
+ if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return refuse("user_gone", "the user does not exist or is banned.", clientId);
133
153
  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;
154
+ 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
155
  const client = clientId ? await context.adapter.findOne({
137
156
  model: "oauthClient",
138
157
  where: [{
@@ -140,7 +159,7 @@ async function verifyToken(token, auth, state, resource, path) {
140
159
  value: clientId
141
160
  }]
142
161
  }) : 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];
162
+ if (!clientId || !isRecord(client) || client.disabled) return refuse("client_disabled", "the OAuth client does not exist or is disabled.", clientId);
144
163
  const scope = payload.scope;
145
164
  const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
146
165
  if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
@@ -151,7 +170,7 @@ async function verifyToken(token, auth, state, resource, path) {
151
170
  value: payload.sid
152
171
  }]
153
172
  });
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];
173
+ 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
174
  }
156
175
  return [void 0, {
157
176
  clientId,
@@ -160,6 +179,12 @@ async function verifyToken(token, auth, state, resource, path) {
160
179
  user
161
180
  }];
162
181
  }
182
+ function verifyFailure(error) {
183
+ const code = isRecord(error) ? error.code : void 0;
184
+ if (code === "ERR_JWT_EXPIRED") return "expired";
185
+ if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && isRecord(error) && error.claim === "aud") return "wrong_resource";
186
+ return "malformed";
187
+ }
163
188
  /**
164
189
  * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
165
190
  * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
@@ -208,4 +233,4 @@ async function deleteUnusedMcpClients(options = {}) {
208
233
  return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
209
234
  }
210
235
  }
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 };
236
+ 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 };