@vite-hub/auth 0.6.0 → 0.7.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 (67) hide show
  1. package/README.md +28 -7
  2. package/dist/{abilities-D3XlrYDw.d.ts → abilities-CfvuGrBv.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-OKoyOwPM.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-Bej95blM.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +25 -6
  8. package/dist/{auth-instance-BpI9Ps8A.js → auth-instance-5RSiFTDC.js} +151 -82
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/client-request-BzMKtfCY.js +52 -0
  13. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Bg_PAl7e.js} +5 -3
  14. package/dist/{console-runtime-DAjLTLrN.d.ts → console-runtime-XcplYv4R.d.ts} +1 -1
  15. package/dist/console-runtime.d.ts +2 -2
  16. package/dist/console-runtime.js +1 -1
  17. package/dist/console.d.ts +1 -1
  18. package/dist/{database-options-B87hDU4j.js → database-options-DE9lMwu1.js} +1 -1
  19. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-CCQsNhjc.js} +1 -1
  20. package/dist/database.d.ts +1 -1
  21. package/dist/database.js +4 -4
  22. package/dist/{definition-BypPLIbI.js → definition-DeEeqTLC.js} +18 -4
  23. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DkzL9ltR.js} +13 -4
  24. package/dist/{events-BXU1_9mc.js → events-BUaoHFoC.js} +1 -1
  25. package/dist/forward.js +1 -1
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +4 -3
  28. package/dist/internal/server.d.ts +3 -3
  29. package/dist/internal/server.js +5 -4
  30. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-DG1jmw4o.d.ts} +1 -0
  31. package/dist/{mcp-token-DzGivm7f.js → mcp-token-DgveSGEl.js} +28 -8
  32. package/dist/mcp.d.ts +1 -1
  33. package/dist/mcp.js +4 -2
  34. package/dist/{members-CwPIx10t.js → members-CRlYyxVk.js} +188 -152
  35. package/dist/nuxt.d.ts +1 -1
  36. package/dist/nuxt.js +27 -14
  37. package/dist/{own-access-Dt-I5-PT.d.ts → own-access-BvVUjaeL.d.ts} +1 -1
  38. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  39. package/dist/presets.js +1 -1
  40. package/dist/roles-BGi8CyBG.js +17 -0
  41. package/dist/runtime/client-request-plugin.d.ts +1 -0
  42. package/dist/runtime/client-request-plugin.js +18 -0
  43. package/dist/runtime/console.d.ts +1 -1
  44. package/dist/runtime/console.js +2 -2
  45. package/dist/runtime/empty-abilities.d.ts +1 -1
  46. package/dist/runtime/empty-definition.d.ts +1 -1
  47. package/dist/runtime/server.d.ts +2 -2
  48. package/dist/runtime/server.js +5 -3
  49. package/dist/runtime/vue-nuxt.js +27 -11
  50. package/dist/schema.js +1 -1
  51. package/dist/{server-Cun232hb.d.ts → server-1G_BbfBD.d.ts} +20 -7
  52. package/dist/{server-DL9MSuyj.d.ts → server-B8kTFrHP.d.ts} +3 -2
  53. package/dist/{server-_eUOlAJ8.js → server-iQNOXyfS.js} +50 -22
  54. package/dist/server.d.ts +5 -2
  55. package/dist/server.js +9 -3
  56. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-DN0svCKj.js} +2 -2
  57. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-CMB3t4NF.js} +1 -1
  58. package/dist/{table-specs-CCSY4tiS.js → table-specs-C3-bLOSF.js} +1 -1
  59. package/dist/test.d.ts +1 -1
  60. package/dist/test.js +2 -2
  61. package/dist/{types-BP9_XUr9.d.ts → types-BmRGse4l.d.ts} +26 -5
  62. package/dist/{vite-Dem1i1rL.js → vite-GRzej8Cs.js} +59 -17
  63. package/dist/vite.d.ts +18 -3
  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 +9 -8
@@ -1,8 +1,9 @@
1
- import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-9aKr6z-k.js";
1
+ import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
2
+ import { n as isAuthRole } from "./roles-BGi8CyBG.js";
2
3
  import { t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
4
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
4
5
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
- import { r as authDatabaseName } from "./database-options-B87hDU4j.js";
6
+ import { r as authDatabaseName } from "./database-options-DE9lMwu1.js";
6
7
  import { parseDuration } from "@vite-hub/runtime";
7
8
  // src/stateless-user-id.ts
8
9
  const pendingUserIds = /* @__PURE__ */ new WeakMap();
@@ -307,6 +308,7 @@ const authRuntimeOptionNames = /* @__PURE__ */ new Set([
307
308
  const accessRouteKeys = /* @__PURE__ */ new Set([
308
309
  "authorize",
309
310
  "method",
311
+ "role",
310
312
  "route"
311
313
  ]);
312
314
  function validateAuthDatabase(value) {
@@ -356,6 +358,18 @@ function validateAuthAccessRoute(value, label) {
356
358
  validateRouteValue(value.route, `${label}.route`);
357
359
  if (typeof value.authorize !== "undefined" && typeof value.authorize !== "function") throw authErrorDiagnostics.AUTH_C0033({ message: `\`defineAuth()\` ${label}.authorize must be a function.` });
358
360
  if (typeof value.method !== "undefined") validateStringValue(value.method, `${label}.method`);
361
+ validateAuthAccessRole(value.role, label);
362
+ }
363
+ function validateAuthAccessRole(value, label) {
364
+ if (typeof value !== "undefined" && !isAuthRole(value)) throw authErrorDiagnostics.AUTH_ACCESS_ROLE_INVALID({ message: `\`defineAuth()\` ${label}.role must be a role name or a non-empty list of role names, such as \`role: ["team", "admin"]\`.` });
365
+ }
366
+ /** Also checked when a Definition callback returns the options, so a route never runs with a role it cannot match. */
367
+ function validateAuthAccessRouteRoles(access) {
368
+ const routes = isRecord(access) ? access.routes : void 0;
369
+ if (!Array.isArray(routes)) return;
370
+ routes.forEach((route, index) => {
371
+ if (isRecord(route)) validateAuthAccessRole(route.role, `access.routes[${index}]`);
372
+ });
359
373
  }
360
374
  function validateAuthAccess(value) {
361
375
  if (typeof value === "undefined") return;
@@ -417,4 +431,4 @@ function defineAuthOptions(options) {
417
431
  applyAuthPreset(options);
418
432
  return { options };
419
433
  }
420
- export { createDeleteAccount as a, applyAuthPreset as c, validateAuthComponents as i, defineAuth as n, validateDeleteAccount as o, validateAuthAccessPolicy as r, validateAuthEvents as s, assertNoRuntimeOption as t };
434
+ export { validateAuthComponents as a, validateAuthEvents as c, validateAuthAccessRouteRoles as i, applyAuthPreset as l, defineAuth as n, createDeleteAccount as o, validateAuthAccessPolicy as r, validateDeleteAccount as s, assertNoRuntimeOption as t };
@@ -49,10 +49,15 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
49
49
  why: "Invalid password hash",
50
50
  fix: "The stored password hash is not `<salt>:<key>`. Hash new passwords with `hashPasswordWithNoble()` or the Better Auth hasher, and reset the password of the user whose hash is broken."
51
51
  },
52
+ AUTH_SECRET_MISSING: {
53
+ why: "Auth has no secret to sign sessions, so Better Auth would use its public default secret. `VITEHUB_SECRET` is not set, and the app sets no Better Auth secret.",
54
+ fix: "Run `pnpm vitehub secret generate` and set the output as `VITEHUB_SECRET` in the server environment. On Cloudflare, run `pnpm exec wrangler secret put VITEHUB_SECRET`. To keep a Better Auth secret, set `BETTER_AUTH_SECRET`, or return `secret` from the Definition callback."
55
+ },
52
56
  AUTH_SIGN_OUT_REDIRECT_INVALID: {
53
57
  why: ({ redirectTo }) => `\`signOut()\` redirects only to a path of the app, not to ${JSON.stringify(redirectTo)}.`,
54
58
  fix: "Pass a path that starts with one `/`, for example `signOut(event, { redirectTo: '/login' })`. A value from the query string can point to another site, so check it against your own pages first."
55
59
  },
60
+ AUTH_ACCESS_ROLE_INVALID: withFix("Set `role` to a role name or a non-empty list of role names without commas, as Better Auth's `admin()` plugin stores them in `user.role`, for example `{ route: '/api/**', role: ['team', 'admin'] }` or `pages: { '/dashboard/**': { role: 'team' } }`."),
56
61
  AUTH_AFTER_SIGN_IN_INVALID: {
57
62
  why: "`defineAuth()` access.afterSignIn must be an inline path of the app that starts with one `/`.",
58
63
  fix: "Set `access.afterSignIn` to a string literal path, for example `afterSignIn: '/dashboard'`. The Nuxt page guard reads it at build time."
@@ -61,7 +66,11 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
61
66
  why: "`defineAuth()` components must be an inline object with only `prefix`, an inline non-empty string.",
62
67
  fix: "Write `components: { prefix: 'Custom' }` in `defineAuth()` to register `<CustomAuthPermission>`, or remove `components`. The Nuxt module reads the prefix at build time, so it cannot use a variable or an expression."
63
68
  },
64
- AUTH_PAGE_ROUTES_INVALID: withFix("Write `access.pages` inline in `defineAuth()`, and do not use a spread or a computed key in `access`. Start each key with `/` and use only static segments, `:name`, and a last `**`. Keep one key for the same pages, and set each value to `'user'`, `'guest'`, or `false`, for example `pages: { '/dashboard/**': 'user', '/login': 'guest' }`. For an optional segment, add one key with the segment and one key without it."),
69
+ AUTH_DATABASE_DISABLED: {
70
+ why: ({ definition }) => `${definition} keeps users in the app Database with \`authDatabase()\`, but \`vitehub()\` sets \`database: false\`.`,
71
+ fix: "Remove `database: false` from `vitehub()`, or from the `vitehub` key of `nuxt.config.ts`. `authDatabase()` turns the Database on. To keep the Database off, set `database: \"memory\"` or `preset: stateless()` in `defineAuth()`."
72
+ },
73
+ AUTH_PAGE_ROUTES_INVALID: withFix("Write `access.pages` inline in `defineAuth()`, and do not use a spread or a computed key in `access`. Start each key with `/` and use only static segments, `:name`, and a last `**`. Keep one key for the same pages, and set each value to `'user'`, `'guest'`, `false`, or `{ role }`, for example `pages: { '/dashboard/**': 'user', '/login': 'guest' }`. For an optional segment, add one key with the segment and one key without it."),
65
74
  AUTH_REDIRECTS_MOVED: {
66
75
  why: "`vitehub({ auth })` takes only `true` or `false`. The `redirects` option moved to the Auth Definition.",
67
76
  fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`. `vitehub migrate` moves them."
@@ -123,8 +132,8 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
123
132
  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
133
  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
134
  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
- AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217`."),
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`."),
135
+ AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account or email in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217,ada@example.com`."),
136
+ AUTH_C0058: withFix("Write each `VITEHUB_ADMINS` entry as `<provider>:<account id>`, for example `github:22072217`, or as an email, for example `ada@example.com`. Run `gh api users/<login> --jq .id` to get a GitHub account id."),
128
137
  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."),
129
138
  AUTH_R0018: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }` in `defineAuth()`."),
130
139
  AUTH_R0003: withFix("Keep one of `server/auth.ts` and `server.auth.ts` and delete the others that the message lists. For Nuxt layers, add `server/auth.ts` to the app to select the Definition."),
@@ -153,7 +162,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
153
162
  AUTH_R0014: withFix("Pass a function that returns `true`, `false`, or a `Response`, for example `withAuthorization(({ user }) => user.role === 'admin', handler)`. `withAuthorization()` and `requireAuthorization()` also take `true` for any signed-in user. `withAnonymousAuthorization()` takes only a function."),
154
163
  AUTH_R0015: withFix("Pass your handler function, for example `withAuth((event, { user }) => ({ id: user.id }))`."),
155
164
  AUTH_R0016: withFix("Set `VITEHUB_SECRET` to at least 32 random characters. Run `openssl rand -base64 32` to make one."),
156
- AUTH_R0019: withFix("Pass `authDatabase()` inline as `database` of `defineAuth()`, enable the Database integration, and run `vitehub database generate`. Run `vitehub inspect definitions --kind database` to list the tables."),
165
+ AUTH_R0019: withFix("Pass `authDatabase()` inline as `database` of `defineAuth()`, then run `vitehub database generate` and `vitehub database migrate`. Run `vitehub inspect definitions --kind database` to list the tables."),
157
166
  AUTH_R0020: withFix("Add the named rule to `shared/abilities.ts` with `defineAbilities()`, or use an existing ability name."),
158
167
  AUTH_R0021: withFix("Return the result at once. Load data before the ability check and pass it as a rule argument; remove `async` from the rule."),
159
168
  AUTH_R0022: withFix("Send the request to an origin that `vitehub({ publicUrl })` returns for one of your Agents, or set `baseURL` in the Auth Definition. The request Host cannot choose the Auth origin."),
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.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";
package/dist/forward.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
2
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
3
3
  import { createAuthMiddleware } from "better-auth/api";
4
4
  import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
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 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";
2
+ import { A as AuthRuntimeEnv, At as AuthEventActor, B as DiscoveredAuthDefinition, Bt as AuthEventsConfiguration, C as AuthGuardedHandler, D as AuthReservedOption, Dt as hasRole, Et as AuthRole, 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, 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 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, 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 AuthEventWindow } from "./types-BmRGse4l.js";
3
+ import { n as checksOwnAccess } from "./own-access-BvVUjaeL.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>>;
@@ -18,4 +18,4 @@ type GitHubOrgMemberErrorCode = "AUTH_GITHUB_NOT_ORG_MEMBER" | "AUTH_GITHUB_ORG_
18
18
  * Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
19
19
  */
20
20
  export declare function checkGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<Result<void, GitHubOrgMemberErrorCode>>;
21
- export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthComponentsOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDeleteAccountOptions, type AuthDevice, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention };
21
+ export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthComponentsOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDeleteAccountOptions, type AuthDevice, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRole, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, hasRole };
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
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";
1
+ import { n as defineAuth } from "./definition-DeEeqTLC.js";
2
+ import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-BUaoHFoC.js";
3
3
  import { n as checksOwnAccess } from "./own-access-CYsakJiH.js";
4
- export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
4
+ import { t as hasRole } from "./roles-BGi8CyBG.js";
5
+ export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth, hasRole };
@@ -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-Cun232hb.js";
3
- import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-DL9MSuyj.js";
2
+ import { A as sendSessionCookies, C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as createBetterAuthOptions, N as findVerifiedAuthUserId, O as withAuth, P as getAuthForDefinition, 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, 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-1G_BbfBD.js";
3
+ import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-B8kTFrHP.js";
4
4
  import { n as AbilityErrorData, t as AbilityError } from "../ability-error-C1c30O6E.js";
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 };
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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
@@ -1,6 +1,7 @@
1
+ import { n as sendSessionCookies } from "../session-cookies-DN0svCKj.js";
1
2
  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
+ import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-5RSiFTDC.js";
3
4
  import { setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver } from "../runtime/server.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
- 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 };
5
+ import { t as AbilityError } from "../ability-error-OKoyOwPM.js";
6
+ 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-iQNOXyfS.js";
7
+ 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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
@@ -19,6 +19,7 @@ interface McpOAuthAuth {
19
19
  $context: Promise<{
20
20
  baseURL: string;
21
21
  options: {
22
+ advanced?: unknown;
22
23
  plugins?: ReadonlyArray<{
23
24
  id?: string;
24
25
  options?: unknown;
@@ -1,5 +1,6 @@
1
- import { l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
2
- import { t as authForRequest } from "./auth-instance-BpI9Ps8A.js";
1
+ import { g as findAccessPolicyPlugin } from "./members-CRlYyxVk.js";
2
+ import { t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-5RSiFTDC.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";
@@ -72,7 +73,8 @@ async function stateOf(auth) {
72
73
  return {
73
74
  issuer: issuer.replace(/\/+$/, ""),
74
75
  resources,
75
- scopes
76
+ scopes,
77
+ trustProxyHeaders: trustsProxyHeaders(context.options)
76
78
  };
77
79
  }
78
80
  const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
@@ -105,18 +107,36 @@ async function verifyMcpRequest(request, options = {}) {
105
107
  const auth = options.auth ?? appAuth(request);
106
108
  const state = await stateOf(auth);
107
109
  const url = new URL(request.url);
108
- 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);
110
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
111
+ return await verifyToken(token, auth, state, options.resource ?? state.resources.find((entry) => new URL(entry).origin === origin && pathOf(entry) === url.pathname.replace(/\/+$/, "")), url.pathname);
109
112
  }
110
113
  /** The token of an `Authorization: Bearer` header. */
111
114
  const bearerToken = (headers) => /^Bearer\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
112
115
  /**
113
- * Check an MCP access token for any `mcpOAuth()` resource at the origin of the request, for `requireCaller()`, which
114
- * accepts the token on every route of the app.
116
+ * Check an MCP access token for `requireCaller()` on any route of the app. The token must name the `mcpOAuth()` resource
117
+ * of the origin with the longest matching path. At that path, prefer an exact query match, then a resource without a
118
+ * query. If the path is outside every resource or the origin has just one resource, use the first resource of the origin.
115
119
  */
116
- async function verifyAppAccessToken(token, origin, pathname, instance) {
120
+ async function verifyAppAccessToken(token, origin, url, instance) {
117
121
  const auth = mcpOAuthAuth(instance);
118
122
  const state = await stateOf(auth);
119
- return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
123
+ return await verifyToken(token, auth, state, appResourceAt(state.resources, origin, url), url.pathname);
124
+ }
125
+ function appResourceAt(resources, origin, url) {
126
+ const atOrigin = resources.map((identifier) => ({
127
+ identifier,
128
+ url: new URL(identifier)
129
+ })).filter((entry) => entry.url.origin === origin);
130
+ if (atOrigin.length <= 1) return atOrigin[0]?.identifier;
131
+ const path = url.pathname.replace(/\/+$/, "");
132
+ const matching = atOrigin.map((entry) => ({
133
+ ...entry,
134
+ path: entry.url.pathname.replace(/\/+$/, "")
135
+ })).filter((entry) => path === entry.path || path.startsWith(`${entry.path}/`)).sort((first, second) => second.path.length - first.path.length);
136
+ const longest = matching[0]?.path;
137
+ if (longest === void 0) return atOrigin[0]?.identifier;
138
+ const atPath = matching.filter((entry) => entry.path === longest);
139
+ return (atPath.find((entry) => entry.url.search === url.search) ?? atPath.find((entry) => !entry.url.search))?.identifier;
120
140
  }
121
141
  async function verifyToken(token, auth, state, resource, path) {
122
142
  const refuse = (reason, detail, clientId, cause) => [mcpErrors.AUTH_MCP_TOKEN_INVALID({
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
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";
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-DG1jmw4o.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";
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 { c as verifyMcpRequest, i as mcpTokenInvalidReasons, n as baseScopes, o as pathOf, r as deleteUnusedMcpClients, s as stateOf, t as appAuth } from "./mcp-token-DzGivm7f.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-DgveSGEl.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,10 +150,11 @@ 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);
153
154
  const suffix = pathname.slice(`/.well-known/${document}`.length).replace(/\/+$/, "");
154
155
  const auth = options.auth ?? appAuth(request);
155
156
  const state = await stateOf(auth);
157
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
156
158
  if (document === "oauth-protected-resource") {
157
159
  const resource = state.resources.find((entry) => new URL(entry).origin === origin && (!suffix || pathOf(entry) === suffix));
158
160
  if (!resource) return void 0;