@vite-hub/auth 0.6.1 → 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 (64) hide show
  1. package/README.md +28 -7
  2. package/dist/{abilities-BYOcyQ9B.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-BWiRS9QZ.js → auth-instance-5RSiFTDC.js} +145 -57
  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/{console-runtime-CaIXVtB_.js → console-runtime-Bg_PAl7e.js} +5 -3
  13. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-XcplYv4R.d.ts} +1 -1
  14. package/dist/console-runtime.d.ts +2 -2
  15. package/dist/console-runtime.js +1 -1
  16. package/dist/console.d.ts +1 -1
  17. package/dist/{database-options-B87hDU4j.js → database-options-DE9lMwu1.js} +1 -1
  18. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-CCQsNhjc.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BypPLIbI.js → definition-DeEeqTLC.js} +18 -4
  22. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DkzL9ltR.js} +13 -4
  23. package/dist/{events-BXU1_9mc.js → events-BUaoHFoC.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +3 -3
  28. package/dist/internal/server.js +5 -4
  29. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-DG1jmw4o.d.ts} +1 -0
  30. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-DgveSGEl.js} +26 -8
  31. package/dist/mcp.d.ts +1 -1
  32. package/dist/mcp.js +2 -2
  33. package/dist/{members-CwPIx10t.js → members-CRlYyxVk.js} +188 -152
  34. package/dist/nuxt.d.ts +1 -1
  35. package/dist/nuxt.js +27 -14
  36. package/dist/{own-access-BNcxKrDl.d.ts → own-access-BvVUjaeL.d.ts} +1 -1
  37. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/roles-BGi8CyBG.js +17 -0
  40. package/dist/runtime/console.d.ts +1 -1
  41. package/dist/runtime/console.js +2 -2
  42. package/dist/runtime/empty-abilities.d.ts +1 -1
  43. package/dist/runtime/empty-definition.d.ts +1 -1
  44. package/dist/runtime/server.d.ts +2 -2
  45. package/dist/runtime/server.js +5 -3
  46. package/dist/runtime/vue-nuxt.js +27 -11
  47. package/dist/schema.js +1 -1
  48. package/dist/{server-C4Kni3Vj.d.ts → server-1G_BbfBD.d.ts} +20 -7
  49. package/dist/{server-BHniJi2m.d.ts → server-B8kTFrHP.d.ts} +3 -2
  50. package/dist/{server-Iru6jcnW.js → server-iQNOXyfS.js} +49 -22
  51. package/dist/server.d.ts +5 -2
  52. package/dist/server.js +9 -3
  53. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-DN0svCKj.js} +2 -2
  54. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-CMB3t4NF.js} +1 -1
  55. package/dist/{table-specs-CCSY4tiS.js → table-specs-C3-bLOSF.js} +1 -1
  56. package/dist/test.d.ts +1 -1
  57. package/dist/test.js +2 -2
  58. package/dist/{types-DmH31d2t.d.ts → types-BmRGse4l.d.ts} +21 -5
  59. package/dist/{vite-CpWhT1Wi.js → vite-GRzej8Cs.js} +58 -17
  60. package/dist/vite.d.ts +18 -3
  61. package/dist/vite.js +1 -1
  62. package/dist/vue.d.ts +2 -2
  63. package/dist/vue.js +1 -1
  64. package/package.json +9 -8
@@ -58,6 +58,7 @@ interface ProvisionStep {
58
58
  id: string;
59
59
  provider: ProvisionProvider;
60
60
  plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
61
+ hasResources?: (context: Pick<ProvisionContext, "env">) => boolean;
61
62
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
62
63
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
63
64
  }
@@ -74,10 +75,13 @@ interface ViteHubCliSpawnResult {
74
75
  signal?: NodeJS.Signals | null;
75
76
  /** The output of the child when `stdout` is `pipe`. */
76
77
  stdout?: string;
78
+ /** The error output of the child when `stderr` is `pipe`. */
79
+ stderr?: string;
77
80
  }
78
81
  interface ViteHubCliSpawnOptions {
79
82
  cwd?: string;
80
83
  env?: NodeJS.ProcessEnv;
84
+ onOutput?: (text: string, stream: "stdout" | "stderr") => void;
81
85
  stderr?: "inherit" | "pipe";
82
86
  /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
83
87
  stdin?: "ignore" | "inherit";
@@ -85,7 +89,17 @@ interface ViteHubCliSpawnOptions {
85
89
  stdout?: "inherit" | "pipe" | "stderr";
86
90
  }
87
91
  type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
92
+ /** Where a call to an app goes through the Console: the operation endpoint of the app's Console project, and the token of `vitehub login`. */
93
+ interface ViteHubCliConsoleRoute {
94
+ authorization: string;
95
+ target: string;
96
+ }
88
97
  interface ViteHubCliContext extends ViteHubCliStreams {
98
+ /**
99
+ * Finds the app at `url` in the Console of `vitehub login` and returns the route that lets the Console sign the call.
100
+ * Returns nothing when the command must call the app directly, such as when a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` is set.
101
+ */
102
+ consoleRoute?: (url: string, signal: AbortSignal) => Promise<ViteHubCliConsoleRoute | undefined>;
89
103
  cwd: string;
90
104
  env: NodeJS.ProcessEnv;
91
105
  /** Replaces `fetch` for commands that call a running app, so tests need no server. */
@@ -104,6 +118,7 @@ interface ViteHubCliContext extends ViteHubCliStreams {
104
118
  spawn: ViteHubCliSpawn;
105
119
  }
106
120
  interface ViteHubCliProvision {
121
+ env?: NodeJS.ProcessEnv;
107
122
  rootDir: string;
108
123
  steps: readonly ProvisionStep[];
109
124
  }
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as ViteHubCliContributor } from "./cli-C5pAfY4x.js";
1
+ import { t as ViteHubCliContributor } from "./cli-DL7uCAvz.js";
2
2
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
3
3
  export declare function createAuthCliContributor(options?: {
4
4
  fetch?: typeof fetch;
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
2
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
3
3
  // src/cli.ts
4
4
  const usage = "vitehub auth events --url <auth-base-url> [--type <type>] [--user <id>] [--actor <actor>] [--from <ISO>] [--to <ISO>] [--cursor <cursor>] [--limit <1-200>] [--aggregate]";
5
5
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
@@ -1,7 +1,7 @@
1
- import { m as adminsVariable, p as adminsPluginId, r as membersVariable, s as accessPolicyPluginId, u as adminClaimPluginId } from "./members-CwPIx10t.js";
1
+ import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-CRlYyxVk.js";
2
2
  import { n as adminClaimVariable } from "./admin-claim-code-C3X_U43x.js";
3
3
  import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
4
- import { r as parseAuthEventList } from "./events-BXU1_9mc.js";
4
+ import { r as parseAuthEventList } from "./events-BUaoHFoC.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
6
6
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
7
7
  // ../internal/src/runtime/user-agent.ts
@@ -194,7 +194,9 @@ function adminsAccess(plugins) {
194
194
  const admins = Reflect.get(options, "admins");
195
195
  const role = Reflect.get(options, "role");
196
196
  if (!Array.isArray(admins) || typeof role !== "string") return [];
197
- return [`${adminsVariable} gives the ${role} role to ${admins.join(", ")} on sign-in.`];
197
+ const emails = admins.filter((entry) => typeof entry === "string" && entry.includes("@")).length;
198
+ const listed = [...admins.filter((entry) => typeof entry === "string" && !entry.includes("@")), ...emails ? [`${emails} verified ${emails === 1 ? "email" : "emails"}`] : []];
199
+ return [`${adminsVariable} gives the ${role} role to ${listed.join(", ")} on sign-in.`];
198
200
  }
199
201
  /** The `VITEHUB_MEMBERS` rule as an access note, so the Console shows who may sign in. */
200
202
  function membersAccess(plugins) {
@@ -1,4 +1,4 @@
1
- import { Ft as AuthEventStore, J as AuthConsoleAgent, K as AuthConsoleActivity, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, ct as AuthConsoleOptions, dt as AuthConsoleOverview, gt as AuthConsoleSession, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, ot as AuthConsoleList, q as AuthConsoleActivityQuery, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, yt as AuthConsoleUserDetail } from "./types-DmH31d2t.js";
1
+ import { J as AuthConsoleAgent, K as AuthConsoleActivity, Lt as AuthEventStore, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, ct as AuthConsoleOptions, dt as AuthConsoleOverview, gt as AuthConsoleSession, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, ot as AuthConsoleList, q as AuthConsoleActivityQuery, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, yt as AuthConsoleUserDetail } from "./types-BmRGse4l.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
4
4
  interface AuthConsole {
@@ -1,3 +1,3 @@
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-DmH31d2t.js";
2
- import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-DMH1I2fl.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-BmRGse4l.js";
2
+ import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-XcplYv4R.js";
3
3
  export { AuthConsole, type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, AuthConsoleErrorCode, 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, type authConsoleEventGroups, createAuthConsole, describeAuthConsoleFields };
@@ -1 +1 @@
1
- export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-CaIXVtB_.js";
1
+ export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-Bg_PAl7e.js";
package/dist/console.d.ts CHANGED
@@ -1,4 +1,4 @@
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-DmH31d2t.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-BmRGse4l.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";
@@ -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
  // 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-B87hDU4j.js";
1
+ import { a as authDatabaseSchemaError } from "./database-options-DE9lMwu1.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,4 +1,4 @@
1
- import { f as AuthAppDatabase } from "./types-DmH31d2t.js";
1
+ import { f as AuthAppDatabase } from "./types-BmRGse4l.js";
2
2
  /**
3
3
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
4
4
  * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
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";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
+ import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-DE9lMwu1.js";
3
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-CCQsNhjc.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";
@@ -32,7 +32,7 @@ function authDatabase(name = "default") {
32
32
  assertAuthDatabaseIdStrategy(options.advanced?.database?.generateId);
33
33
  assertAuthDatabaseNames(options);
34
34
  const entry = Object.hasOwn(databases, name) ? databases[name] : void 0;
35
- if (!entry || !Object.hasOwn(entry.schema, "user")) throw authErrorDiagnostics.AUTH_R0019({ message: `[vitehub] \`authDatabase(${JSON.stringify(name)})\` found no Better Auth tables in the ${JSON.stringify(name)} Database. Pass \`authDatabase()\` inline as the \`database\` of \`defineAuth()\` so that Auth adds them, enable the Database integration, and run \`vitehub database generate\`. \`vitehub inspect definitions --kind database\` lists the tables of each Database.` });
35
+ if (!entry || !Object.hasOwn(entry.schema, "user")) throw authErrorDiagnostics.AUTH_R0019({ message: `[vitehub] \`authDatabase(${JSON.stringify(name)})\` found no Better Auth tables in the ${JSON.stringify(name)} Database. Pass \`authDatabase()\` inline as the \`database\` of \`defineAuth()\` so that Auth adds them, then run \`vitehub database generate\` and \`vitehub database migrate\`. \`vitehub inspect definitions --kind database\` lists the tables of each Database.` });
36
36
  assertAuthDatabaseSchema(options, entry.schema, name);
37
37
  return drizzleAdapter(entry.db, {
38
38
  provider: is(entry.db, PgAsyncDatabase) ? "pg" : "sqlite",
@@ -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-DmH31d2t.js";
3
- import { n as checksOwnAccess } from "./own-access-BNcxKrDl.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-C4Kni3Vj.js";
3
- import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-BHniJi2m.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-BWiRS9QZ.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-Iru6jcnW.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,5 @@
1
- import { l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
2
- import { t as authForRequest } from "./auth-instance-BWiRS9QZ.js";
1
+ import { g as findAccessPolicyPlugin } from "./members-CRlYyxVk.js";
2
+ import { t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-5RSiFTDC.js";
3
3
  import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
4
4
  import { n as mcpOAuthResources } from "./mcp-config-C7srUMIZ.js";
5
5
  import { t as isRecord } from "./object-CAK6UYR5.js";
@@ -73,7 +73,8 @@ async function stateOf(auth) {
73
73
  return {
74
74
  issuer: issuer.replace(/\/+$/, ""),
75
75
  resources,
76
- scopes
76
+ scopes,
77
+ trustProxyHeaders: trustsProxyHeaders(context.options)
77
78
  };
78
79
  }
79
80
  const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
@@ -106,19 +107,36 @@ async function verifyMcpRequest(request, options = {}) {
106
107
  const auth = options.auth ?? appAuth(request);
107
108
  const state = await stateOf(auth);
108
109
  const url = new URL(request.url);
109
- const origin = clientRequestOrigin(request);
110
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
110
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);
111
112
  }
112
113
  /** The token of an `Authorization: Bearer` header. */
113
114
  const bearerToken = (headers) => /^Bearer\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
114
115
  /**
115
- * Check an MCP access token for any `mcpOAuth()` resource at the origin of the request, for `requireCaller()`, which
116
- * 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.
117
119
  */
118
- async function verifyAppAccessToken(token, origin, pathname, instance) {
120
+ async function verifyAppAccessToken(token, origin, url, instance) {
119
121
  const auth = mcpOAuthAuth(instance);
120
122
  const state = await stateOf(auth);
121
- 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;
122
140
  }
123
141
  async function verifyToken(token, auth, state, resource, path) {
124
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,7 +1,7 @@
1
1
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
2
  import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
3
3
  import { r as mcpRegistrationPluginId } from "./mcp-config-C7srUMIZ.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
+ 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";
5
5
  import { APIError, createAuthMiddleware } from "better-auth/api";
6
6
  import { oauthProvider, oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
7
7
  import { jwt } from "better-auth/plugins";
@@ -151,10 +151,10 @@ async function serveMcpOAuthDiscovery(request, options = {}) {
151
151
  }
152
152
  async function discoveryDocument(request, document, options) {
153
153
  const { pathname } = new URL(request.url);
154
- const origin = clientRequestOrigin(request);
155
154
  const suffix = pathname.slice(`/.well-known/${document}`.length).replace(/\/+$/, "");
156
155
  const auth = options.auth ?? appAuth(request);
157
156
  const state = await stateOf(auth);
157
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
158
158
  if (document === "oauth-protected-resource") {
159
159
  const resource = state.resources.find((entry) => new URL(entry).origin === origin && (!suffix || pathOf(entry) === suffix));
160
160
  if (!resource) return void 0;