@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,3 +1,3 @@
1
- import { s as AbilityRules } from "../abilities-D3XlrYDw.js";
1
+ import { s as AbilityRules } from "../abilities-CfvuGrBv.js";
2
2
  declare const abilities: AbilityRules;
3
3
  export { abilities as default };
@@ -1,4 +1,4 @@
1
- import { _ as AuthDefinition } from "../types-BP9_XUr9.js";
1
+ import { _ as AuthDefinition } from "../types-BmRGse4l.js";
2
2
  declare const definition: AuthDefinition | undefined;
3
3
  export declare function getAuthApp(): object | undefined;
4
4
  export { definition as default };
@@ -1,3 +1,3 @@
1
- import { t as authAccessHandlerMeta } from "../own-access-Dt-I5-PT.js";
2
- import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-DL9MSuyj.js";
1
+ import { t as authAccessHandlerMeta } from "../own-access-BvVUjaeL.js";
2
+ import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-B8kTFrHP.js";
3
3
  export { AuthAccessRouteMatch, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,5 +1,5 @@
1
1
  import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-zKi7NrvK.js";
2
- import { t as authErrorDiagnostics } from "../error-diagnostics-CUPwukgE.js";
2
+ import { t as authErrorDiagnostics } from "../error-diagnostics-DkzL9ltR.js";
3
3
  import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-CYsakJiH.js";
4
4
  import { r as unwrapAuthRequest } from "../request-Dpq7GO8B.js";
5
5
  import { t as getAuthRuntimeState } from "../runtime-state-C0Rd1W4m.js";
@@ -11,7 +11,7 @@ function setAuthRuntimeEnvResolver(resolver, definition) {
11
11
  }
12
12
  function assertSamePages(pages = {}, built) {
13
13
  const keys = Object.keys(pages);
14
- if (keys.length === Object.keys(built).length && keys.every((key) => Object.hasOwn(built, key) && built[key] === pages[key])) return;
14
+ if (keys.length === Object.keys(built).length && keys.every((key) => Object.hasOwn(built, key) && JSON.stringify(built[key]) === JSON.stringify(pages[key]))) return;
15
15
  throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access.pages is not the map that the build read from server/auth.ts, so the build guards other pages. Write `access` and `access.pages` inline in `defineAuth()`, and restart the dev server after you change them." });
16
16
  }
17
17
  /**
@@ -50,6 +50,7 @@ function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
50
50
  const rules = routes.map((route, index) => ({
51
51
  index,
52
52
  authorize: route.authorize === true,
53
+ role: route.role === true,
53
54
  method: route.method?.toUpperCase(),
54
55
  ...resolveAccessRoutePath(route.route)
55
56
  }));
@@ -62,7 +63,8 @@ function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
62
63
  const method = request.method.toUpperCase();
63
64
  return rules.filter((rule) => (!rule.method || rule.method === method || rule.method === "GET" && method === "HEAD") && matchesPath(rule, pathname)).map((rule) => ({
64
65
  index: rule.index,
65
- authorize: rule.authorize
66
+ authorize: rule.authorize,
67
+ role: rule.role
66
68
  }));
67
69
  };
68
70
  }
@@ -1,6 +1,8 @@
1
1
  import { n as invariantError } from "../invariant-Dj2R1eMr.js";
2
- import "../page-tools-shared-CtoKaNQZ.js";
2
+ import "../page-tools-shared-dVJBPPTk.js";
3
3
  import { i as resolveAuthMountPath } from "../application-path-zKi7NrvK.js";
4
+ import { t as authErrorDiagnostics } from "../error-diagnostics-DkzL9ltR.js";
5
+ import { n as isAuthRole, t as hasRole } from "../roles-BGi8CyBG.js";
4
6
  import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler } from "../nuxt-bridge-pRyfYD5c.js";
5
7
  import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRouter, useRuntimeConfig, useState } from "#app";
6
8
  // src/runtime/vue-nuxt.ts
@@ -96,6 +98,9 @@ async function fetchServerSession(event, basePath) {
96
98
  return;
97
99
  }
98
100
  }
101
+ function userOf(session) {
102
+ return typeof session === "object" && session !== null ? Reflect.get(session, "user") ?? null : null;
103
+ }
99
104
  /** The session read of each server request, so the page guard and all components share one read. */
100
105
  const serverReads = /* @__PURE__ */ new WeakMap();
101
106
  const viteHubAuthPlugin = defineNuxtPlugin({
@@ -115,13 +120,18 @@ const viteHubAuthPlugin = defineNuxtPlugin({
115
120
  if (config === false || meta === void 0 || meta === false) return;
116
121
  const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
117
122
  const redirectTo = typeof meta === "object" ? meta.redirectTo : void 0;
123
+ const role = typeof meta === "object" ? meta.role : void 0;
124
+ if (role !== void 0 && !isAuthRole(role)) throw authErrorDiagnostics.AUTH_ACCESS_ROLE_INVALID({ message: "`definePageMeta()` auth.role must be a role name or a non-empty list of role names." });
118
125
  const isThisPage = (target) => {
119
126
  const page = useRouter().resolve(target);
120
127
  return page.matched.length > 0 && page.matched.at(-1) === to.matched.at(-1) && sameParams(page.params, to.params);
121
128
  };
122
- return (loggedIn, signedOut = false) => {
129
+ return (loggedIn, signedOut = false, user) => {
123
130
  if (mode === "guest") return loggedIn && !isThisPage(redirectTo ?? afterSignIn) ? navigateTo(redirectTo ?? afterSignIn) : void 0;
124
- if (loggedIn) return;
131
+ if (loggedIn) return role && user !== void 0 && !hasRole(user, role) ? showError({
132
+ statusCode: 403,
133
+ statusMessage: "Forbidden"
134
+ }) : void 0;
125
135
  const signInTarget = redirectTo ?? signInPage;
126
136
  if (signInTarget && isThisPage(signInTarget)) return showError({
127
137
  statusCode: 401,
@@ -181,28 +191,34 @@ const viteHubAuthPlugin = defineNuxtPlugin({
181
191
  if (!decide) return;
182
192
  const page = to.fullPath.split("#", 1)[0];
183
193
  if (navigation === 1 && !serverSession && !stale && !nuxtApp.payload.error && nuxtApp.isHydrating && useState(guardRouteKey).value === page) return decide(true);
184
- const decideAndSeed = (loggedIn) => {
194
+ const decideAndSeed = (user) => {
195
+ const loggedIn = user !== null;
185
196
  if (serverSession && loggedIn) {
186
197
  useState(guardRouteKey).value = page;
187
198
  useRequestEvent()?.res.headers.set("cache-control", "private, no-store");
188
199
  }
189
- return decide(loggedIn);
200
+ return decide(loggedIn, false, user);
190
201
  };
191
202
  const session = serverSession?.();
192
203
  const app = tryUseNuxtApp();
193
204
  const inApp = (run) => app ? app.runWithContext(run) : run();
194
- const loggedIn = !serverSession ? import("../vue.js").then(({ useUserSession }) => inApp(() => useUserSession().refresh({}))).then((current) => Boolean(current?.session && current?.user)) : session instanceof Promise ? session.then(Boolean) : Boolean(session);
195
- if (typeof loggedIn === "boolean") return decideAndSeed(loggedIn);
196
- return loggedIn.then((value) => {
205
+ const user = !serverSession ? import("../vue.js").then(({ useUserSession }) => inApp(() => useUserSession().refresh({}))).then((current) => current?.session && current?.user ? current.user : null) : session instanceof Promise ? session.then(userOf) : userOf(session);
206
+ if (!(user instanceof Promise)) return decideAndSeed(user);
207
+ return user.then((value) => {
197
208
  if (navigation !== navigations) return;
198
209
  return inApp(() => decideAndSeed(value));
199
210
  });
200
211
  };
201
212
  addRouteMiddleware("vitehub-auth", (to) => guard(to, to.meta.auth, ++navigations), { global: true });
202
- for (const mode of ["user", "guest"]) addRouteMiddleware(`vitehub-auth-${mode}`, (to) => {
213
+ const pageGuards = [
214
+ ["vitehub-auth-user", "user"],
215
+ ["vitehub-auth-guest", "guest"],
216
+ ...(config?.pageRoles ?? []).map((role, index) => [`vitehub-auth-role-${index}`, { role }])
217
+ ];
218
+ for (const [name, meta] of pageGuards) addRouteMiddleware(name, (to) => {
203
219
  if (to.meta.auth !== void 0) return;
204
- routeModes.set(to, mode);
205
- return guard(to, mode, navigations);
220
+ routeModes.set(to, meta);
221
+ return guard(to, meta, navigations);
206
222
  });
207
223
  }
208
224
  });
package/dist/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-CCSY4tiS.js";
1
+ import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-C3-bLOSF.js";
2
2
  import { sql } from "drizzle-orm";
3
3
  import { bigint, boolean, foreignKey, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
4
4
  import { foreignKey as foreignKey$1, index as index$1, integer as integer$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from "drizzle-orm/sqlite-core";
@@ -1,8 +1,8 @@
1
- import { t as AuthConsole } from "./console-runtime-DAjLTLrN.js";
2
- import { C as AuthGuardedHandler, E as AuthRequestInput, Ft as AuthEventStore, H as ResolvedAuthAccessRoute, Lt as AuthEventWindow, N as AuthRuntimeOptions, Nt as AuthEventPage, R as AuthSignInConfiguration, S as AuthFor, T as AuthRequest, V as RegisteredAuth, W as ViteHubAuth, _ as AuthDefinition, d as AuthAnonymousGuardedHandler, h as AuthBetterAuthRuntimeOptions, it as AuthConsoleHostOptions, jt as AuthEventListInput, kt as AuthEventAggregates, p as AuthAuthorization, u as AuthAnonymousAuthorize } from "./types-BP9_XUr9.js";
3
- import { i as AbilityName, n as AbilityAuthorization, t as AbilityArgs } from "./abilities-D3XlrYDw.js";
4
- import { o as McpTokenInvalidError } from "./mcp-token-CmQbXbTu.js";
5
- import "./server-DL9MSuyj.js";
1
+ import { t as AuthConsole } from "./console-runtime-XcplYv4R.js";
2
+ import { C as AuthGuardedHandler, E as AuthRequestInput, Ft as AuthEventPage, H as ResolvedAuthAccessRoute, Lt as AuthEventStore, N as AuthRuntimeOptions, Nt as AuthEventListInput, R as AuthSignInConfiguration, S as AuthFor, T as AuthRequest, V as RegisteredAuth, W as ViteHubAuth, _ as AuthDefinition, d as AuthAnonymousGuardedHandler, h as AuthBetterAuthRuntimeOptions, it as AuthConsoleHostOptions, jt as AuthEventAggregates, p as AuthAuthorization, u as AuthAnonymousAuthorize, zt as AuthEventWindow } from "./types-BmRGse4l.js";
3
+ import { i as AbilityName, n as AbilityAuthorization, t as AbilityArgs } from "./abilities-CfvuGrBv.js";
4
+ import { o as McpTokenInvalidError } from "./mcp-token-DG1jmw4o.js";
5
+ import "./server-B8kTFrHP.js";
6
6
  import "./ability-error-C1c30O6E.js";
7
7
  import { AccessAuthorizeOption, Result, ResultError, ViteHubContext } from "@vite-hub/runtime";
8
8
  import { APIError } from "better-auth/api";
@@ -44,6 +44,15 @@ declare function getAuthForDefinition<TDefinition extends AuthDefinition>(defini
44
44
  * `useAuth(event)`. The Console reads it through `@vite-hub/auth/runtime/console`.
45
45
  */
46
46
  declare function authForRequest(request: Pick<Request, "headers" | "url">, event?: ViteHubContext, definition?: AuthDefinition): RegisteredAuth;
47
+ /**
48
+ * The last step of a guard that sees the outcome of the request: a refusal, or the value or Response of the route.
49
+ *
50
+ * A plain Fetch host sends only this Response, so the session cookies move from the prepared response to a copy of
51
+ * it, once, also for a Response of another Fetch implementation, such as `undici`. H3 adds the prepared response to
52
+ * the outcome itself. In both, a cookie that the Response sets itself wins over the session cookie of the same name,
53
+ * and the Cache-Control of the route becomes `private`, unless it already has `private` or `no-store`.
54
+ */
55
+ declare function sendSessionCookies<T>(input: AuthRequestInput, outcome: T): T | Response;
47
56
  /** Where Better Auth returns after one sign-in that a guard starts. */
48
57
  type AuthSignInURLs = Pick<AuthProviderSignIn, "callbackURL" | "errorCallbackURL">;
49
58
  /** A provider sign-in with the page that Better Auth returns to. */
@@ -137,7 +146,9 @@ declare function requireAuthorization<TInput extends AuthRequestInput>(event: TI
137
146
  declare function requireAuthorization<TInput extends AuthRequestInput>(event: TInput, authorize: AccessAuthorizeOption<TInput & ViteHubContext, false>, definition: AuthDefinition | undefined): Promise<CoreAuthorization>;
138
147
  /**
139
148
  * Return who calls: a person with an Auth Session (`kind: "browser"`), or an Agent with an MCP access token of
140
- * `mcpOAuth()` (`kind: "agent"`), checked like `verifyMcpRequest()` for any `mcpOAuth()` resource of the origin. Like
149
+ * `mcpOAuth()` (`kind: "agent"`), checked like `verifyMcpRequest()`. The longest matching resource path wins. At that
150
+ * path, the query must match exactly unless a resource has no query. On other paths, or when the origin has just one
151
+ * resource, the token must name the first resource of the origin. Like
141
152
  * `verifyMcpRequest()`, it accepts `jwt()` and an `oauthProvider()` with `resources` that the app adds without
142
153
  * `mcpOAuth()`. A bearer token that is not a JWT, such as a session token of `bearer()`, is read as a session.
143
154
  * Returns `AUTH_SIGNED_OUT` without either, and `AUTH_MCP_TOKEN_INVALID` for a JWT bearer token that fails a check.
@@ -174,6 +185,8 @@ declare function can<const Name extends AbilityName>(event: AuthRequestInput, na
174
185
  declare function createAuthAccessHandler(routes: readonly ResolvedAuthAccessRoute[], definition?: AuthDefinition, publicRoutes?: readonly string[]): (input: AuthRequestInput) => Promise<Response | undefined>;
175
186
  declare function requireAuthAccessRoutes(input: AuthRequestInput, routeIndexes: number[], definition?: AuthDefinition, requiredAuthorizeRouteIndexes?: number[], options?: {
176
187
  redirectToSignIn?: boolean;
188
+ /** The indexes of the matched routes that have `role`. A runtime Definition without that role refuses. */
189
+ requiredRoleRouteIndexes?: number[];
177
190
  /** Where Better Auth returns after this sign-in, replacing `access.signIn.callbackURL` and `errorCallbackURL`. */
178
191
  signIn?: AuthSignInURLs;
179
192
  /** Reuse successful checks of these exact rules and Definition on this request, including in app Auth middleware. */
@@ -199,4 +212,4 @@ declare function aggregateAuthEvents(window: AuthEventWindow, definition?: AuthD
199
212
  * `host.impersonation` lets the Console start impersonation. It is off by default.
200
213
  */
201
214
  declare function getAuthConsoleForRequest(request: Request, event?: ViteHubContext, host?: AuthConsoleHostOptions): AuthConsole;
202
- export { authForRequest as A, requireCaller as C, withAnonymousAuthorization as D, useAuth as E, AuthCallerError as F, AuthCallerErrorCode as I, AuthCallerResult as L, findVerifiedAuthUserId as M, getAuthForDefinition as N, withAuth as O, AuthCaller as P, AuthCallerUser as R, requireAuthorization as S, toAuthRequest as T, handleAuthRequest as _, authRoute as a, requireAuth as b, createAuth as c, createAuthHandler as d, createAuthRequestRuntimeOptions as f, handleAuth as g, getAuthEvents as h, assertAuthOrigin as i, createBetterAuthOptions as j, withAuthorization as k, createAuthAccessHandler as l, getAuthConsoleForRequest as m, AuthSignOutOptions as n, can as o, getAuth as p, aggregateAuthEvents as r, checkAuthMember as s, AuthEventReadErrorCode as t, createAuthForRequest as u, listAuthEvents as v, signOut as w, requireAuthAccessRoutes as x, requireAbility as y, AuthMemberErrorCode as z };
215
+ export { sendSessionCookies as A, AuthMemberErrorCode as B, requireCaller as C, withAnonymousAuthorization as D, useAuth as E, AuthCaller as F, AuthCallerError as I, AuthCallerErrorCode as L, createBetterAuthOptions as M, findVerifiedAuthUserId as N, withAuth as O, getAuthForDefinition as P, AuthCallerResult as R, requireAuthorization as S, toAuthRequest as T, handleAuthRequest as _, authRoute as a, requireAuth as b, createAuth as c, createAuthHandler as d, createAuthRequestRuntimeOptions as f, handleAuth as g, getAuthEvents as h, assertAuthOrigin as i, authForRequest as j, withAuthorization as k, createAuthAccessHandler as l, getAuthConsoleForRequest as m, AuthSignOutOptions as n, can as o, getAuth as p, aggregateAuthEvents as r, checkAuthMember as s, AuthEventReadErrorCode as t, createAuthForRequest as u, listAuthEvents as v, signOut as w, requireAuthAccessRoutes as x, requireAbility as y, AuthCallerUser as z };
@@ -1,5 +1,5 @@
1
- import "./own-access-Dt-I5-PT.js";
2
- import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-BP9_XUr9.js";
1
+ import "./own-access-BvVUjaeL.js";
2
+ import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-BmRGse4l.js";
3
3
  import { AccessAuthorizationContext, ViteHubContext } from "@vite-hub/runtime";
4
4
  type AuthRuntimeEnvResolver = (event?: ViteHubContext) => Record<string, unknown>;
5
5
  type AuthAccessIdentityResolver = (request: Request, event: AuthRequestInput, hasSession: boolean) => Promise<AccessAuthorizationContext<unknown, false>["user"] | Response | undefined>;
@@ -19,6 +19,7 @@ declare function setAuthAccessIdentityResolver(path: string, resolver: AuthAcces
19
19
  interface AuthAccessRouteMatch {
20
20
  index: number;
21
21
  authorize: boolean;
22
+ role: boolean;
22
23
  }
23
24
  /**
24
25
  * Return a function that lists the access routes that match a request, in Definition order. A request to a path of
@@ -1,16 +1,19 @@
1
- import { t as createAuthConsole } from "./console-runtime-CaIXVtB_.js";
2
- import { _ as forwardedRequestOrigin, a as getAuthForDefinition, c as withSessionMarker, d as eventClientAddress, f as setRequestClientAddress, g as setAuthResponseOutcome, h as setAuthOutcome, l as resolveAuthOptions, m as runWithAuthEvent, n as createBetterAuthOptions, o as requestProvider, p as withClientAddress, r as envResolverFor, s as resolveDefaultDefinition, t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-BpI9Ps8A.js";
1
+ import { t as createAuthConsole } from "./console-runtime-Bg_PAl7e.js";
2
+ import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { i as resolveAuthMountPath, n as canonicalAccessPath } from "./application-path-zKi7NrvK.js";
4
- import { a as normalizeAuthBasePath } from "./access-pages-9aKr6z-k.js";
4
+ import { o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
5
+ import { t as hasRole } from "./roles-BGi8CyBG.js";
5
6
  import { n as authRequestEvent, r as unwrapAuthRequest } from "./request-Dpq7GO8B.js";
6
- import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-fR6Pv4kD.js";
7
+ import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
8
+ import { _ as setAuthResponseOutcome, a as getAuthForDefinition, c as withSessionMarker, d as withEndpointRateLimits, f as eventClientAddress, g as setAuthOutcome, h as runWithAuthEvent, l as resolveAuthOptions, m as withClientAddress, n as createBetterAuthOptions, o as requestProvider, p as setRequestClientAddress, r as envResolverFor, s as resolveDefaultDefinition, t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-5RSiFTDC.js";
9
+ import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DN0svCKj.js";
7
10
  import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
8
- import { t as readSetCookies } from "./set-cookie-DVfi-nJX.js";
11
+ import { t as readSetCookies } from "./set-cookie-CMB3t4NF.js";
9
12
  import { createAuthAccessRouteMatcher } from "./runtime/server.js";
10
- import { n as checkAbility, t as AbilityError } from "./ability-error-D3-u8k1A.js";
11
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BXU1_9mc.js";
12
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
13
- import { i as notMemberError, l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
13
+ import { n as checkAbility, t as AbilityError } from "./ability-error-OKoyOwPM.js";
14
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BUaoHFoC.js";
15
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
16
+ import { g as findAccessPolicyPlugin, i as notMemberError } from "./members-CRlYyxVk.js";
14
17
  import { n as mcpOAuthResources, t as isJwsToken } from "./mcp-config-C7srUMIZ.js";
15
18
  import { defineErrors, toResultError } from "@vite-hub/runtime";
16
19
  import { HTTPError } from "nitro/h3";
@@ -230,14 +233,14 @@ function createAuthRequestRuntimeOptions(definition, request, event) {
230
233
  }).requestRuntimeOptions;
231
234
  }
232
235
  function createAuth(definition) {
233
- return withSessionMarker(withClientAddress(betterAuth(createBetterAuthOptions(definition))));
236
+ return withSessionMarker(withEndpointRateLimits(withClientAddress(betterAuth(createBetterAuthOptions(definition)))));
234
237
  }
235
238
  function createAuthForRequest(definition, request, event) {
236
- return withSessionMarker(withClientAddress(betterAuth(resolveAuthOptions(definition, {
239
+ return withSessionMarker(withEndpointRateLimits(withClientAddress(betterAuth(resolveAuthOptions(definition, {
237
240
  request,
238
241
  event,
239
242
  env: envResolverFor(definition)
240
- }).providerOptions)));
243
+ }).providerOptions))));
241
244
  }
242
245
  function handleAuthRequest(definition, input, event = authRequestEvent(input)) {
243
246
  const request = unwrapAuthRequest(input);
@@ -487,14 +490,21 @@ async function createSignInResponse(auth, options, signIn, address) {
487
490
  });
488
491
  }
489
492
  const sessionReads = /* @__PURE__ */ new WeakMap();
490
- async function readSession(input, auth, headers) {
491
- const { refusal, session, setCookies } = await getAuthenticationSession(auth, { headers });
493
+ async function readSession(input, auth, headers, query) {
494
+ const { refusal, session, setCookies } = await getAuthenticationSession(auth, query ? {
495
+ headers,
496
+ query
497
+ } : { headers });
492
498
  prepareSessionCookies(input, setCookies);
493
499
  return {
494
500
  refusal,
495
501
  session
496
502
  };
497
503
  }
504
+ function cachesSessions(options) {
505
+ const session = options.session;
506
+ return options.preset === void 0 && isRecord(session) && isRecord(session.cookieCache) && session.cookieCache.enabled === true;
507
+ }
498
508
  async function readRequestSession(input, definition) {
499
509
  const request = unwrapAuthRequest(input);
500
510
  const event = authRequestEvent(input);
@@ -698,19 +708,28 @@ async function runAccessAuthorize(authorize, context, deny = () => createForbidd
698
708
  if (isRuntimeResponse(resolved)) return { response: sendableRuntimeResponse(resolved, context.request) };
699
709
  return { response: deny() };
700
710
  }
701
- async function checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes = [], redirectToSignIn = true, resolveIdentity, signInURLs) {
711
+ async function checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes = [], redirectToSignIn = true, resolveIdentity, signInURLs, requiredRoleRouteIndexes = []) {
702
712
  const { auth, event, options, refusal: providerRefusal, request, session } = await readRequestSession(input, definition);
703
713
  if (providerRefusal) return reject(input, createProviderRefusalResponse(providerRefusal));
704
714
  const identity = await resolveIdentity?.(toRequest(request), input, Boolean(session));
705
715
  if (isRuntimeResponse(identity)) return reject(input, identity);
706
716
  if (identity || session) {
707
- const authorization = checkedAuthorization(request, identity ? {} : session.session, identity ?? session.user);
717
+ let authorization = checkedAuthorization(request, identity ? {} : session.session, identity ?? session.user);
708
718
  if (routeIndexes === void 0) return { authorization };
709
719
  const requiredAuthorizeRoutes = new Set(requiredAuthorizeRouteIndexes);
720
+ const requiredRoleRoutes = new Set(requiredRoleRouteIndexes);
710
721
  const routes = authAccessRoutes(options, routeIndexes);
722
+ if (!identity && cachesSessions(options) && routes.some((route) => typeof route === "object" && route.role !== void 0)) {
723
+ const stored = await readSession(input, auth, request.headers, { disableCookieCache: true });
724
+ if (stored.refusal) return reject(input, createProviderRefusalResponse(stored.refusal));
725
+ if (!stored.session) return reject(input, createRefusalResponse("SIGNED_OUT"));
726
+ authorization = checkedAuthorization(request, stored.session.session, stored.session.user);
727
+ }
711
728
  for (const [index, route] of routes.entries()) {
712
729
  const authorize = typeof route === "object" && route !== null ? route.authorize : void 0;
713
- if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index])) return reject(input, createForbiddenResponse(request));
730
+ const role = typeof route === "object" && route !== null ? route.role : void 0;
731
+ if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index]) || role === void 0 && requiredRoleRoutes.has(routeIndexes[index])) return reject(input, createForbiddenResponse(request));
732
+ if (role !== void 0 && !hasRole(authorization.user, role)) return reject(input, createForbiddenResponse(request));
714
733
  if (!authorize) continue;
715
734
  const rejection = await runAccessAuthorize(authorize, {
716
735
  ...authorization,
@@ -847,9 +866,9 @@ async function readCaller(event, definition) {
847
866
  const auth = authForRequest(request, authRequestEvent(event), definition);
848
867
  const { options } = await auth.$context;
849
868
  if (isJwsToken(token) && mcpOAuthResources(options.plugins).length) {
850
- const { verifyAppAccessToken } = await import("./mcp-token-DzGivm7f.js").then((n) => n.a);
869
+ const { verifyAppAccessToken } = await import("./mcp-token-DgveSGEl.js").then((n) => n.a);
851
870
  const url = new URL(request.url);
852
- const [error, caller] = await verifyAppAccessToken(token, trustsProxyHeaders(options) ? forwardedRequestOrigin(request) : url.origin, url.pathname, auth);
871
+ const [error, caller] = await verifyAppAccessToken(token, clientRequestOrigin(request, trustsProxyHeaders(options)), url, auth);
853
872
  if (error) return [error, void 0];
854
873
  return [void 0, Object.freeze({
855
874
  client: {
@@ -913,13 +932,17 @@ async function can(event, name, ...args) {
913
932
  }
914
933
  const reusableAccessChecks = /* @__PURE__ */ new WeakMap();
915
934
  async function checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options = {}) {
916
- const key = JSON.stringify([routeIndexes, requiredAuthorizeRouteIndexes]);
935
+ const key = JSON.stringify([
936
+ routeIndexes,
937
+ requiredAuthorizeRouteIndexes,
938
+ options.requiredRoleRouteIndexes ?? []
939
+ ]);
917
940
  const request = unwrapAuthRequest(input);
918
941
  let definitions = reusableAccessChecks.get(request);
919
942
  let accepted = definitions?.get(definition);
920
943
  const reusable = accepted?.get(key);
921
944
  if (reusable === true || options.reuse && reusable === false) return;
922
- const { response } = await checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options.redirectToSignIn !== false, getAuthRuntimeState().accessIdentityResolvers?.get(new URL(request.url).pathname), options.signIn);
945
+ const { response } = await checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options.redirectToSignIn !== false, getAuthRuntimeState().accessIdentityResolvers?.get(new URL(request.url).pathname), options.signIn, options.requiredRoleRouteIndexes);
923
946
  if (response) return sendSessionCookies(input, response);
924
947
  if (options.reuse || options.remember) {
925
948
  if (!definitions) reusableAccessChecks.set(request, definitions = /* @__PURE__ */ new WeakMap());
@@ -933,12 +956,17 @@ function createAuthAccessHandler(routes, definition, publicRoutes = []) {
933
956
  return async (input) => {
934
957
  const matched = match(input);
935
958
  if (matched.length === 0) return;
936
- return await checkAuthAccessRequest(input, definition ?? resolveDefaultDefinition(), matched.map((rule) => rule.index), matched.filter((rule) => rule.authorize).map((rule) => rule.index), { remember: true });
959
+ return await checkAuthAccessRequest(input, definition ?? resolveDefaultDefinition(), matched.map((rule) => rule.index), matched.filter((rule) => rule.authorize).map((rule) => rule.index), {
960
+ remember: true,
961
+ requiredRoleRouteIndexes: matched.filter((rule) => rule.role).map((rule) => rule.index)
962
+ });
937
963
  };
938
964
  }
939
965
  async function requireAuthAccessRoutes(input, routeIndexes, definition = resolveDefaultDefinition(), requiredAuthorizeRouteIndexes = [], options = {}) {
940
966
  if (!Array.isArray(routeIndexes) || routeIndexes.length === 0 || routeIndexes.some((routeIndex) => !Number.isSafeInteger(routeIndex) || routeIndex < 0)) throw authErrorDiagnostics.AUTH_R0009({ message: "[vitehub] Auth access route indexes must be a non-empty array of non-negative integers." });
941
967
  if (!Array.isArray(requiredAuthorizeRouteIndexes) || requiredAuthorizeRouteIndexes.some((routeIndex) => !Number.isSafeInteger(routeIndex) || routeIndex < 0)) throw authErrorDiagnostics.AUTH_R0010({ message: "[vitehub] Required Auth authorize route indexes must be an array of non-negative integers." });
968
+ const roleIndexes = options.requiredRoleRouteIndexes;
969
+ if (roleIndexes !== void 0 && (!Array.isArray(roleIndexes) || roleIndexes.some((routeIndex) => !Number.isSafeInteger(routeIndex) || routeIndex < 0))) throw authErrorDiagnostics.AUTH_R0010({ message: "[vitehub] Required Auth role route indexes must be an array of non-negative integers." });
942
970
  return await checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options);
943
971
  }
944
972
  /**
package/dist/server.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, F as AuthCallerError, I as AuthCallerErrorCode, L as AuthCallerResult, O as withAuth, P as AuthCaller, R as AuthCallerUser, S as requireAuthorization, a as authRoute, b as requireAuth, d as createAuthHandler, g as handleAuth, h as getAuthEvents, k as withAuthorization, m as getAuthConsoleForRequest, o as can, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, v as listAuthEvents, w as signOut, y as requireAbility, z as AuthMemberErrorCode } from "./server-Cun232hb.js";
3
- import { a as McpTokenInvalidData, o as McpTokenInvalidError, s as McpTokenInvalidReason } from "./mcp-token-CmQbXbTu.js";
2
+ import { B as AuthMemberErrorCode, C as requireCaller, D as withAnonymousAuthorization, E as useAuth, F as AuthCaller, I as AuthCallerError, L as AuthCallerErrorCode, O as withAuth, R as AuthCallerResult, S as requireAuthorization, a as authRoute, b as requireAuth, d as createAuthHandler, g as handleAuth, h as getAuthEvents, k as withAuthorization, m as getAuthConsoleForRequest, o as can, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, v as listAuthEvents, w as signOut, y as requireAbility, z as AuthCallerUser } from "./server-1G_BbfBD.js";
3
+ import { a as McpTokenInvalidData, o as McpTokenInvalidError, s as McpTokenInvalidReason } from "./mcp-token-DG1jmw4o.js";
4
4
  import { n as AbilityErrorData, t as AbilityError } from "./ability-error-C1c30O6E.js";
5
+ import { AuthContext } from "better-auth";
6
+ /** Whether the resolved Auth context applies `VITEHUB_MEMBERS`. */
7
+ export declare function hasAuthMembers(context: Pick<AuthContext, "options">): boolean;
5
8
  export { AbilityError, type AbilityErrorData, type AuthCaller, type AuthCallerError, type AuthCallerErrorCode, type AuthCallerResult, type AuthCallerUser, type AuthEventReadErrorCode, type AuthMemberErrorCode, type McpTokenInvalidData, type McpTokenInvalidError, type McpTokenInvalidReason, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
package/dist/server.js CHANGED
@@ -1,3 +1,9 @@
1
- import { t as AbilityError } from "./ability-error-D3-u8k1A.js";
2
- import { D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, f as getAuthConsoleForRequest, g as listAuthEvents, i as can, l as createAuthHandler, m as handleAuth, p as getAuthEvents, r as authRoute, t as aggregateAuthEvents, v as requireAuth, w as useAuth, x as requireCaller } from "./server-_eUOlAJ8.js";
3
- export { AbilityError, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
1
+ import { g as findAccessPolicyPlugin } from "./members-CRlYyxVk.js";
2
+ import { t as AbilityError } from "./ability-error-OKoyOwPM.js";
3
+ import { D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, f as getAuthConsoleForRequest, g as listAuthEvents, i as can, l as createAuthHandler, m as handleAuth, p as getAuthEvents, r as authRoute, t as aggregateAuthEvents, v as requireAuth, w as useAuth, x as requireCaller } from "./server-iQNOXyfS.js";
4
+ // src/server.ts
5
+ /** Whether the resolved Auth context applies `VITEHUB_MEMBERS`. */
6
+ function hasAuthMembers(context) {
7
+ return Boolean(findAccessPolicyPlugin(context.options.plugins)?.members);
8
+ }
9
+ export { AbilityError, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, hasAuthMembers, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
@@ -1,5 +1,5 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DVfi-nJX.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-CMB3t4NF.js";
3
3
  import { t as isRecord } from "./object-CAK6UYR5.js";
4
4
  import { n as authRequestEvent } from "./request-Dpq7GO8B.js";
5
5
  import { HTTPError } from "nitro/h3";
@@ -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 { ViteHubError, isViteHubError } from "@vite-hub/runtime";
3
3
  // src/errors.ts
4
4
  function invalidAuthenticationErrorOptions() {
@@ -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
  /**
3
3
  * The Better Auth core tables, with the tables of the plugins that ViteHub ships: `jwt()` and `oauthProvider()` of
4
4
  * `mcpOAuth()`, `organization()`, `passkey()` from `@better-auth/passkey`, and the table of Better Auth's limiter. The
package/dist/test.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as AuthDefinition } from "./types-BP9_XUr9.js";
1
+ import { _ as AuthDefinition } from "./types-BmRGse4l.js";
2
2
  import { Session, User } from "better-auth";
3
3
  /** The user to sign in. Auth creates it when no user has this email. Other fields, such as `role`, go to the new user. */
4
4
  export interface SignInTestUser {
package/dist/test.js CHANGED
@@ -1,5 +1,5 @@
1
- import { s as resolveDefaultDefinition, t as authForRequest } from "./auth-instance-BpI9Ps8A.js";
2
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { s as resolveDefaultDefinition, t as authForRequest } from "./auth-instance-5RSiFTDC.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
3
3
  import { testUtils } from "better-auth/plugins";
4
4
  // src/test.ts
5
5
  /**
@@ -85,6 +85,13 @@ declare function createDatabaseAuthEventStore(options: {
85
85
  db: EnvDatabase;
86
86
  retention?: AuthEventRetention | false;
87
87
  }): AuthEventStore;
88
+ /** One role or a list of roles. A user with any of them passes. */
89
+ type AuthRole = string | readonly string[];
90
+ /**
91
+ * Whether `user.role` has one of `roles`. Better Auth's `admin()` plugin stores the roles of a user as one string,
92
+ * separated by commas, such as `"team,admin"`.
93
+ */
94
+ declare function hasRole(user: unknown, roles: AuthRole): boolean;
88
95
  /** Who may open a page: signed-in users (`user`) or signed-out visitors (`guest`). */
89
96
  type AuthPageMode = "guest" | "user";
90
97
  /**
@@ -95,13 +102,17 @@ type AuthPageMeta = boolean | AuthPageMode | {
95
102
  only?: AuthPageMode;
96
103
  /** Where to send the visitor instead of the configured redirect. */
97
104
  redirectTo?: string;
105
+ /** The role, or one of the roles, that `user.role` must have. A signed-in user without it gets a 403 error page. */
106
+ role?: AuthRole;
98
107
  };
99
108
  /**
100
109
  * `access.pages`: the Nuxt pages that the page guard protects, by route pattern, such as `'/dashboard/**'`. A key has
101
- * static segments, `:name`, and a last `**`. `'user'` and `'guest'` work as in `definePageMeta({ auth })`. `false`
102
- * removes the guard of a wider pattern from the matching pages.
110
+ * static segments, `:name`, and a last `**`. `'user'`, `'guest'`, and `{ role }` work as in `definePageMeta({ auth })`.
111
+ * `false` removes the guard of a wider pattern from the matching pages.
103
112
  */
104
- type AuthPages = Record<`/${string}`, AuthPageMode | false>;
113
+ type AuthPages = Record<`/${string}`, AuthPageMode | false | {
114
+ role: AuthRole;
115
+ }>;
105
116
  type AuthConsoleValue = string | number | boolean | null | string[] | number[];
106
117
  type AuthConsoleFieldType = "string" | "number" | "boolean" | "date" | "string[]" | "number[]" | "json";
107
118
  type AuthConsoleAction = "ban" | "unban" | "remove" | "revokeSession" | "revokeSessions" | "setRole" | "editField" | "impersonate" | "revokeConsent";
@@ -401,7 +412,12 @@ type AuthSessionOptions = NonNullable<BetterAuthOptions["session"]> & {
401
412
  interface AuthRuntimeEnv extends ViteHub.AuthRuntimeEnv {}
402
413
  interface AuthRuntimeContext<TEnv extends Record<string, unknown> = AuthRuntimeEnv> {
403
414
  env: TEnv;
415
+ /**
416
+ * The request that Auth serves. A request that the server sends to itself during server rendering has the URL
417
+ * `http://localhost/...`, so read the origin from `requestOrigin`.
418
+ */
404
419
  request?: Pick<Request, "headers" | "url">;
420
+ /** The origin of the request that the client sent, or `http://localhost` outside a request. */
405
421
  requestOrigin: string;
406
422
  }
407
423
  type AuthRuntimeOptions = Partial<Omit<BetterAuthOptions, "basePath" | "database">> & {
@@ -421,6 +437,8 @@ interface AuthSignInConfiguration {
421
437
  interface AuthAccessRouteConfiguration {
422
438
  authorize?: AuthAccessAuthorize;
423
439
  method?: string;
440
+ /** The role, or one of the roles, that `user.role` must have. A signed-in user without it gets `403`. `authorize` runs after it. */
441
+ role?: AuthRole;
424
442
  route: string;
425
443
  }
426
444
  type AuthAccessRoute = string | AuthAccessRouteConfiguration;
@@ -429,7 +447,7 @@ type AuthAccessAuthorizeResult = AccessAuthorizeResult;
429
447
  type AuthAccessAuthorize<TEvent = ViteHubContext$1> = AccessAuthorize<TEvent, false>;
430
448
  /** The Session and user that the app's Auth Definition returns, with the fields of its plugins and `additionalFields`. */
431
449
  type RegisteredSession<TRegistry> = RegisteredAuth<TRegistry>["$Infer"]["Session"];
432
- type GuardSession<TSession> = Pick<TSession, Extract<keyof TSession, keyof Session>> & Partial<Omit<TSession, keyof Session>>;
450
+ type GuardSession<TSession> = TSession extends object ? Pick<TSession, Extract<keyof TSession, keyof Session>> & Partial<Omit<TSession, keyof Session>> : never;
433
451
  /**
434
452
  * The checked request, Session, and user that a guarded handler receives. Only Auth guards create it.
435
453
  * Guards using the default Definition read plugin and custom fields from the generated Auth registry.
@@ -549,8 +567,11 @@ interface DiscoveredAuthDefinition {
549
567
  source: "server-auth" | "server-auth-suffix";
550
568
  }
551
569
  interface ResolvedAuthAccessRoute {
570
+ /** `authorize` is set, so a request needs the Definition's callback at runtime. */
552
571
  authorize?: true;
553
572
  method?: string;
573
+ /** `role` is set, so a request needs the Definition's role at runtime. */
574
+ role?: true;
554
575
  route: string;
555
576
  }
556
577
  interface ResolvedAuthViteConfig {
@@ -606,4 +627,4 @@ type RegisteredAuth<TRegistry = ViteHub.AuthRegistry> = TRegistry extends {
606
627
  } ? AuthFor<TDefinition> : ViteHubAuth;
607
628
  /** `false` turns Auth off. `server/auth.ts` turns it on, and `defineAuth()` holds every Auth option. */
608
629
  type AuthOptions = false;
609
- export { AuthConsoleEventGroup as $, AuthRuntimeEnv as A, AuthEventCounts as At, DiscoveredAuthDefinition as B, defaultAuthEventRetention as Bt, AuthGuardedHandler as C, AuthPageMeta as Ct, AuthReservedOption as D, AuthEvent as Dt, AuthRequestInput as E, AuthDevice as Et, AuthSessionRefresh as F, AuthEventStore as Ft, AuthConsoleAction as G, ResolvedAuthAccessRoute as H, AuthSessionRefreshContext as I, AuthEventType as It, AuthConsoleAgent as J, AuthConsoleActivity as K, AuthSessionRefreshFields as L, AuthEventWindow as Lt, AuthRuntimeOption as M, AuthEventMetadata as Mt, AuthRuntimeOptions as N, AuthEventPage as Nt, AuthResolvedDefinitionOptions as O, AuthEventActor as Ot, AuthSessionOptions as P, AuthEventRetention as Pt, AuthConsoleEvent as Q, AuthSignInConfiguration as R, AuthEventsConfiguration as Rt, AuthFor as S, authConsoleEventGroups as St, AuthRequest as T, AuthPages as Tt, ResolvedAuthViteConfig as U, RegisteredAuth as V, ViteHubAuth as W, AuthConsoleColumn as X, AuthConsoleCapability as Y, AuthConsoleDescription as Z, AuthDefinition as _, AuthConsoleSessionUser as _t, AuthAccessPolicy as a, AuthConsoleImpersonation as at, AuthDefinitionResolver as b, AuthConsoleValue as bt, AuthAccessRouteConfiguration as c, AuthConsoleOptions as ct, AuthAnonymousGuardedHandler as d, AuthConsoleOverview as dt, AuthConsoleEventUser as et, AuthAppDatabase as f, AuthConsolePage as ft, AuthComponentsOptions as g, AuthConsoleSession as gt, AuthBetterAuthRuntimeOptions as h, AuthConsoleRoles as ht, AuthAccessConfiguration as i, AuthConsoleHostOptions as it, AuthRuntimeOnlyOptions as j, AuthEventListInput as jt, AuthRuntimeContext as k, AuthEventAggregates as kt, AuthAnonymousAuthorization as l, AuthConsoleOrganization as lt, AuthBetterAuthOptions as m, AuthConsoleQuery as mt, AuthAccessAuthorize as n, AuthConsoleFieldPolicy as nt, AuthAccessPolicyContext as o, AuthConsoleList as ot, AuthAuthorization as p, AuthConsolePolicy as pt, AuthConsoleActivityQuery as q, AuthAccessAuthorizeResult as r, AuthConsoleFieldType as rt, AuthAccessRoute as s, AuthConsoleMutation as st, AuthAccessAuthorizationContext as t, AuthConsoleField as tt, AuthAnonymousAuthorize as u, AuthConsoleOrganizationDetail as ut, AuthDefinitionInput as v, AuthConsoleUser as vt, AuthOptions as w, AuthPageMode as wt, AuthDeleteAccountOptions as x, authConsoleActionNames as xt, AuthDefinitionOptions as y, AuthConsoleUserDetail as yt, AuthViteHubOptions as z, createDatabaseAuthEventStore as zt };
630
+ export { AuthConsoleEventGroup as $, AuthRuntimeEnv as A, AuthEventActor as At, DiscoveredAuthDefinition as B, AuthEventsConfiguration as Bt, AuthGuardedHandler as C, AuthPageMeta as Ct, AuthReservedOption as D, hasRole as Dt, AuthRequestInput as E, AuthRole as Et, AuthSessionRefresh as F, AuthEventPage as Ft, AuthConsoleAction as G, ResolvedAuthAccessRoute as H, defaultAuthEventRetention as Ht, AuthSessionRefreshContext as I, AuthEventRetention as It, AuthConsoleAgent as J, AuthConsoleActivity as K, AuthSessionRefreshFields as L, AuthEventStore as Lt, AuthRuntimeOption as M, AuthEventCounts as Mt, AuthRuntimeOptions as N, AuthEventListInput as Nt, AuthResolvedDefinitionOptions as O, AuthDevice as Ot, AuthSessionOptions as P, AuthEventMetadata as Pt, AuthConsoleEvent as Q, AuthSignInConfiguration as R, AuthEventType as Rt, AuthFor as S, authConsoleEventGroups as St, AuthRequest as T, AuthPages as Tt, ResolvedAuthViteConfig as U, RegisteredAuth as V, createDatabaseAuthEventStore as Vt, ViteHubAuth as W, AuthConsoleColumn as X, AuthConsoleCapability as Y, AuthConsoleDescription as Z, AuthDefinition as _, AuthConsoleSessionUser as _t, AuthAccessPolicy as a, AuthConsoleImpersonation as at, AuthDefinitionResolver as b, AuthConsoleValue as bt, AuthAccessRouteConfiguration as c, AuthConsoleOptions as ct, AuthAnonymousGuardedHandler as d, AuthConsoleOverview as dt, AuthConsoleEventUser as et, AuthAppDatabase as f, AuthConsolePage as ft, AuthComponentsOptions as g, AuthConsoleSession as gt, AuthBetterAuthRuntimeOptions as h, AuthConsoleRoles as ht, AuthAccessConfiguration as i, AuthConsoleHostOptions as it, AuthRuntimeOnlyOptions as j, AuthEventAggregates as jt, AuthRuntimeContext as k, AuthEvent as kt, AuthAnonymousAuthorization as l, AuthConsoleOrganization as lt, AuthBetterAuthOptions as m, AuthConsoleQuery as mt, AuthAccessAuthorize as n, AuthConsoleFieldPolicy as nt, AuthAccessPolicyContext as o, AuthConsoleList as ot, AuthAuthorization as p, AuthConsolePolicy as pt, AuthConsoleActivityQuery as q, AuthAccessAuthorizeResult as r, AuthConsoleFieldType as rt, AuthAccessRoute as s, AuthConsoleMutation as st, AuthAccessAuthorizationContext as t, AuthConsoleField as tt, AuthAnonymousAuthorize as u, AuthConsoleOrganizationDetail as ut, AuthDefinitionInput as v, AuthConsoleUser as vt, AuthOptions as w, AuthPageMode as wt, AuthDeleteAccountOptions as x, authConsoleActionNames as xt, AuthDefinitionOptions as y, AuthConsoleUserDetail as yt, AuthViteHubOptions as z, AuthEventWindow as zt };