@vite-hub/auth 0.4.1 → 0.5.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 (66) hide show
  1. package/README.md +31 -7
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-9jC7iuN0.d.ts} +2 -2
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-DUWJ6Q1W.d.ts} +1 -1
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-DmnUGicq.js} +1 -1
  6. package/dist/access-pages-FNQTyGRD.js +96 -0
  7. package/dist/agent.js +3 -3
  8. package/dist/{auth-instance-CmDogt4D.js → auth-instance-zYMjldPG.js} +227 -25
  9. package/dist/{cli-ubYJpAL_.d.ts → cli-NCtitmny.d.ts} +1 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-CuXRDhGy.js} +67 -33
  13. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-Dqidb3zF.d.ts} +13 -11
  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-DpOVjUti.js → database-options-CcjUG-us.js} +1 -1
  18. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CTKCAfqW.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BCaLA9kW.js → definition-BFT9T6In.js} +12 -4
  22. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-uEbxSY2G.js} +8 -2
  23. package/dist/{events-DCfuicoo.js → events-DJmO9a9I.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -2
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +4 -4
  28. package/dist/internal/server.js +4 -4
  29. package/dist/{invariant-D8_xBqmZ.js → invariant-DolT9EEx.js} +1 -1
  30. package/dist/{mcp-token-CpxLyl_p.js → mcp-token-BhonlK9C.js} +2 -2
  31. package/dist/mcp.js +1 -1
  32. package/dist/{members-DdlsS8kJ.js → members-Cl3hFRjk.js} +3 -3
  33. package/dist/nitro-kit-32CVgbWS.js +44 -0
  34. package/dist/nuxt.d.ts +32 -19
  35. package/dist/nuxt.js +337 -16
  36. package/dist/own-access-C8pwo_Kn.js +31 -0
  37. package/dist/own-access-CdgEICjO.d.ts +20 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/runtime/console.d.ts +1 -1
  40. package/dist/runtime/console.js +2 -2
  41. package/dist/runtime/empty-abilities.d.ts +1 -1
  42. package/dist/runtime/empty-definition.d.ts +1 -1
  43. package/dist/runtime/server.d.ts +3 -2
  44. package/dist/runtime/server.js +23 -14
  45. package/dist/runtime/vue-nuxt.js +70 -28
  46. package/dist/schema.d.ts +71 -19
  47. package/dist/schema.js +5 -3
  48. package/dist/{server-C8TlOrSy.d.ts → server-B-zNtSvm.d.ts} +9 -10
  49. package/dist/{server-BM-RSf1T.d.ts → server-Ci2i6p1S.d.ts} +7 -6
  50. package/dist/{server-BG_MFd4q.js → server-CyqLFm3L.js} +45 -25
  51. package/dist/server.d.ts +2 -2
  52. package/dist/server.js +2 -2
  53. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-CZmZS5QF.js} +2 -2
  54. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DWIyCCJO.js} +1 -1
  55. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BhWz_U0M.d.ts} +255 -1
  56. package/dist/{table-specs-CURphR3n.js → table-specs-D0VLp1U4.js} +43 -43
  57. package/dist/test.d.ts +1 -1
  58. package/dist/test.js +2 -2
  59. package/dist/{types-CruflEFI.d.ts → types-gl-myjZc.d.ts} +51 -4
  60. package/dist/{vite-Dy0Xhq4H.js → vite-QKjsPLwP.js} +349 -120
  61. package/dist/vite.d.ts +6 -2
  62. package/dist/vite.js +1 -1
  63. package/dist/vue.d.ts +17 -68
  64. package/dist/vue.js +22 -69
  65. package/package.json +13 -9
  66. package/dist/shared-DRtfuFsV.js +0 -12
@@ -1,12 +1,34 @@
1
+ import { t as authErrorDiagnostics } from "../error-diagnostics-uEbxSY2G.js";
1
2
  import { r as unwrapAuthRequest } from "../request-z6DHHmrb.js";
2
3
  import { n as getAuthRuntimeState } from "../runtime-state-ojQCzKOc.js";
3
4
  import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-DuTpfGFj.js";
5
+ import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-C8pwo_Kn.js";
4
6
  //#region src/runtime/server.ts
5
7
  function setAuthRuntimeEnvResolver(resolver, definition) {
6
8
  const state = getAuthRuntimeState();
7
9
  if (definition) state.envResolvers?.set(definition, resolver);
8
10
  else state.envResolver = resolver;
9
11
  }
12
+ function assertSamePages(pages = {}, built) {
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;
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
+ }
17
+ /**
18
+ * Stops the server when `access.pages` of the Auth Definition differs from the map that the Nuxt build read, for
19
+ * example when `access` is a variable: the build guards only the pages that it reads. A Definition callback returns its
20
+ * options when Auth resolves them, so the check runs on each result.
21
+ */
22
+ function checkBuiltAuthPages(definition, built) {
23
+ const { options } = definition;
24
+ if (typeof options !== "function") return assertSamePages(options.access?.pages, built);
25
+ const resolve = (context) => {
26
+ const resolved = options(context);
27
+ assertSamePages(resolved.access?.pages, built);
28
+ return resolved;
29
+ };
30
+ definition.options = resolve;
31
+ }
10
32
  /**
11
33
  * Let a trusted server integration authenticate one exact mounted path without a browser session.
12
34
  * Resolved users still pass every matching Auth access route's authorize callback, with an empty session.
@@ -17,19 +39,6 @@ function setAuthAccessIdentityResolver(path, resolver) {
17
39
  if (resolver) state.accessIdentityResolvers.set(path, resolver);
18
40
  else state.accessIdentityResolvers.delete(path);
19
41
  }
20
- /**
21
- * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
22
- * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
23
- * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
24
- */
25
- const authAccessHandlerMeta = Object.freeze({ vitehubAuthAccess: "handler" });
26
- /** Whether Nitro routed the request event to a handler with `authAccessHandlerMeta`. A plain Request has no route. */
27
- function routedToAccessHandler(input) {
28
- if (!("context" in input) || !(input.context instanceof Object)) return false;
29
- const route = Reflect.get(input.context, "matchedRoute");
30
- const meta = route instanceof Object ? Reflect.get(route, "meta") : void 0;
31
- return meta instanceof Object && Reflect.get(meta, "vitehubAuthAccess") === authAccessHandlerMeta.vitehubAuthAccess;
32
- }
33
42
  function matchesPath(rule, pathname) {
34
43
  return pathname === rule.path || rule.recursive && (rule.path === "" || pathname.startsWith(`${rule.path}/`));
35
44
  }
@@ -74,4 +83,4 @@ function createLazyAuthAccessHandler(routes, load, publicRoutes = []) {
74
83
  };
75
84
  }
76
85
  //#endregion
77
- export { authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
86
+ export { authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,9 +1,16 @@
1
+ import { n as invariantError } from "../invariant-DolT9EEx.js";
1
2
  import { i as resolveAuthMountPath } from "../application-path-DuTpfGFj.js";
2
3
  import "../page-tools-shared-l4eyj53D.js";
3
4
  import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler } from "../nuxt-bridge-Cl988STZ.js";
4
- import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRequestFetch, useRequestURL, useRouter, useRuntimeConfig, useState } from "#app";
5
+ import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRouter, useRuntimeConfig, useState } from "#app";
5
6
  //#region src/runtime/vue-nuxt.ts
7
+ /** Vue Router gives the same params in other forms: `"a"` or `["a"]`, `[]` or `""` or nothing for an empty one, and any key order. */
8
+ function sameParams(a, b) {
9
+ const values = (value) => JSON.stringify(value === void 0 || value === "" ? [] : [value].flat());
10
+ return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].every((key) => values(a[key]) === values(b[key]));
11
+ }
6
12
  const stateKey = "vitehub:auth:session";
13
+ const guardRouteKey = "vitehub:auth:guard-route";
7
14
  /**
8
15
  * True when the request may have a session: ViteHub's `vitehub_session` marker cookie, which Auth sets next to the
9
16
  * session cookie, or Better Auth's own `<prefix>.session_token` and `<prefix>.session_data` cookies.
@@ -22,7 +29,20 @@ function reviveDates(value) {
22
29
  }
23
30
  /** Forward Better Auth's `Set-Cookie` headers, such as a refreshed session, to the page response. */
24
31
  function appendSetCookies(event, response) {
25
- for (const cookie of response.headers.getSetCookie?.() ?? []) event.res?.headers?.append("set-cookie", cookie);
32
+ for (const cookie of response.headers.getSetCookie()) event.res.headers.append("set-cookie", cookie);
33
+ }
34
+ const unforwardedHeaders = /^(?:accept|accept-encoding|connection|content-.+|expect|if-.+|keep-alive|proxy-.+|te|trailer|transfer-encoding|upgrade)$/;
35
+ async function pageFetch(event, path, init) {
36
+ if (import.meta.client) throw invariantError("Auth page fetch runs only on the Nuxt server");
37
+ const { serverFetch } = await import("nitro");
38
+ const request = new Request(`${event.url.origin}${path}`, init);
39
+ for (const [name, value] of event.req.headers) if (!unforwardedHeaders.test(name) && !request.headers.has(name)) request.headers.set(name, value);
40
+ Object.assign(request, {
41
+ ip: event.req.ip,
42
+ runtime: event.req.runtime,
43
+ waitUntil: event.req.waitUntil
44
+ });
45
+ return serverFetch(request);
26
46
  }
27
47
  /**
28
48
  * The path and query of a URL that Better Auth's client built. The client can build an absolute URL from a variable
@@ -32,24 +52,18 @@ function pathOf(input) {
32
52
  const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost");
33
53
  return url.pathname + url.search;
34
54
  }
35
- /**
36
- * The fetch of the current page request for Better Auth's client, or `undefined` outside a request. Nuxt's request fetch
37
- * calls the app in-process with the headers of the page request, such as the cookie, and its `native` form answers with
38
- * the `Response` that Better Auth reads.
39
- */
40
55
  function currentRequestFetch() {
41
56
  const nuxtApp = tryUseNuxtApp();
42
57
  const event = nuxtApp ? useRequestEvent() : void 0;
43
58
  if (!nuxtApp || !event) return void 0;
44
- const { native } = useRequestFetch();
45
59
  const requestFetch = async (input, init) => {
46
- const response = await native(pathOf(input), init);
60
+ const response = await pageFetch(event, pathOf(input), init);
47
61
  appendSetCookies(event, response);
48
62
  return response;
49
63
  };
50
64
  return {
51
65
  request: nuxtApp,
52
- origin: useRequestURL().origin,
66
+ origin: event.url.origin,
53
67
  fetch: requestFetch
54
68
  };
55
69
  }
@@ -60,16 +74,15 @@ function currentRequestFetch() {
60
74
  function readServerSession(basePath) {
61
75
  const event = useRequestEvent();
62
76
  if (!event) return void 0;
63
- if (!hasSessionCookie(event.req?.headers?.get("cookie") ?? void 0)) return null;
64
- return fetchServerSession(event, useRequestFetch(), basePath);
77
+ if (!hasSessionCookie(event.req.headers.get("cookie") ?? void 0)) return null;
78
+ return fetchServerSession(event, basePath);
65
79
  }
66
- /** Asks Better Auth for the session with Nuxt's request fetch, which the caller got in a Nuxt context. */
67
- async function fetchServerSession(event, fetch, basePath) {
80
+ async function fetchServerSession(event, basePath) {
68
81
  try {
69
- const data = await fetch(`${basePath}/get-session`, {
70
- baseURL: "/",
71
- onResponse: ({ response }) => appendSetCookies(event, response)
72
- });
82
+ const response = await pageFetch(event, `${basePath}/get-session`);
83
+ appendSetCookies(event, response);
84
+ if (!response.ok) return void 0;
85
+ const data = await response.json();
73
86
  if (typeof data !== "object" || data === null) return null;
74
87
  const session = Reflect.get(data, "session");
75
88
  const user = Reflect.get(data, "user");
@@ -96,15 +109,24 @@ const viteHubAuthPlugin = defineNuxtPlugin({
96
109
  const config = runtimeConfig.public?.vitehubAuth;
97
110
  const signInPage = config ? config.signInPage : "/login";
98
111
  const afterSignIn = (config || void 0)?.afterSignIn ?? "/";
112
+ const routeModes = /* @__PURE__ */ new WeakMap();
99
113
  /** The page guard of `to`: where a visitor goes, or nothing when the page has no guard. */
100
- const guardOf = (to) => {
101
- const meta = to.meta.auth;
114
+ const guardOf = (to, meta = to.meta.auth) => {
102
115
  if (config === false || meta === void 0 || meta === false) return;
103
116
  const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
104
117
  const redirectTo = typeof meta === "object" ? meta.redirectTo : void 0;
118
+ const isThisPage = (target) => {
119
+ const page = useRouter().resolve(target);
120
+ return page.matched.length > 0 && page.matched.at(-1) === to.matched.at(-1) && sameParams(page.params, to.params);
121
+ };
105
122
  return (loggedIn, signedOut = false) => {
106
- if (mode === "guest") return loggedIn ? navigateTo(redirectTo ?? afterSignIn) : void 0;
123
+ if (mode === "guest") return loggedIn && !isThisPage(redirectTo ?? afterSignIn) ? navigateTo(redirectTo ?? afterSignIn) : void 0;
107
124
  if (loggedIn) return;
125
+ const signInTarget = redirectTo ?? signInPage;
126
+ if (signInTarget && isThisPage(signInTarget)) return showError({
127
+ statusCode: 401,
128
+ statusMessage: "Signed out"
129
+ });
108
130
  if (redirectTo || signInPage !== null) return navigateTo({
109
131
  path: redirectTo ?? signInPage ?? "/login",
110
132
  query: { redirect: to.fullPath }
@@ -121,7 +143,8 @@ const viteHubAuthPlugin = defineNuxtPlugin({
121
143
  const seed = useState(stateKey, () => void 0);
122
144
  seed.value = null;
123
145
  if (redirectTo) return navigateTo(redirectTo, { external: /^(?:[\w+.-]{2,}:|[/\\]{2})/.test(redirectTo) });
124
- return guardOf(useRouter().currentRoute.value)?.(false, true);
146
+ const route = useRouter().currentRoute.value;
147
+ return guardOf(route, route.meta.auth ?? routeModes.get(route))?.(false, true);
125
148
  }));
126
149
  if (config === false) return;
127
150
  const basePath = resolveAuthMountPath(config?.basePath ?? "/api/auth", "window" in globalThis ? runtimeConfig.app?.baseURL : void 0);
@@ -152,16 +175,35 @@ const viteHubAuthPlugin = defineNuxtPlugin({
152
175
  return;
153
176
  }
154
177
  });
155
- addRouteMiddleware("vitehub-auth", (to) => {
156
- const decide = guardOf(to);
178
+ let navigations = 0;
179
+ const guard = (to, meta, navigation) => {
180
+ const decide = guardOf(to, meta);
157
181
  if (!decide) return;
182
+ const page = to.fullPath.split("#", 1)[0];
183
+ if (navigation === 1 && !serverSession && !stale && !nuxtApp.payload.error && nuxtApp.isHydrating && useState(guardRouteKey).value === page) return decide(true);
184
+ const decideAndSeed = (loggedIn) => {
185
+ if (serverSession && loggedIn) {
186
+ useState(guardRouteKey).value = page;
187
+ useRequestEvent()?.res.headers.set("cache-control", "private, no-store");
188
+ }
189
+ return decide(loggedIn);
190
+ };
158
191
  const session = serverSession?.();
159
192
  const app = tryUseNuxtApp();
160
193
  const inApp = (run) => app ? app.runWithContext(run) : run();
161
- 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);
162
- if (typeof loggedIn === "boolean") return decide(loggedIn);
163
- return loggedIn.then((value) => inApp(() => decide(value)));
164
- }, { global: true });
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) => {
197
+ if (navigation !== navigations) return;
198
+ return inApp(() => decideAndSeed(value));
199
+ });
200
+ };
201
+ addRouteMiddleware("vitehub-auth", (to) => guard(to, to.meta.auth, ++navigations), { global: true });
202
+ for (const mode of ["user", "guest"]) addRouteMiddleware(`vitehub-auth-${mode}`, (to) => {
203
+ if (to.meta.auth !== void 0) return;
204
+ routeModes.set(to, mode);
205
+ return guard(to, mode, navigations);
206
+ });
165
207
  }
166
208
  });
167
209
  //#endregion
package/dist/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AuthTableField, c as authPluginSchemas, i as AuthSchemaPlugin, l as authTableSpecs, n as AuthCoreTableSpecs, o as AuthTableName, r as AuthSchemaOptions, s as AuthTableSpec, t as AuthCoreModel, u as resolveAuthTableSpecs } from "./table-specs-DbXyaXWs.js";
1
+ import { a as AuthSchemaPlugin, c as AuthTableSpec, d as resolveAuthTableSpecs, i as AuthSchemaOptions, l as authPluginSchemas, n as AuthCoreTableSpecs, o as AuthTableField, r as AuthPluginSchemas, s as AuthTableName, t as AuthCoreModel, u as authTableSpecs } from "./table-specs-BhWz_U0M.js";
2
2
  import { $Type, BuildColumns, HasDefault, IsPrimaryKey, NotNull } from "drizzle-orm";
3
3
  import { PgBigInt53Builder, PgBooleanBuilder, PgBuildColumns, PgColumn, PgIntegerBuilder, PgJsonbBuilder, PgTableWithColumns, PgTextBuilder, PgTimestampBuilder } from "drizzle-orm/pg-core";
4
4
  import { SQLiteBooleanBuilder, SQLiteColumn, SQLiteIntegerBuilder, SQLiteTableWithColumns, SQLiteTextBuilder, SQLiteTextJsonBuilder, SQLiteTimestampBuilder } from "drizzle-orm/sqlite-core";
@@ -66,13 +66,20 @@ type FieldData<F> = F extends {
66
66
  } ? string[] : F extends {
67
67
  type: "number[]";
68
68
  } ? number[] : unknown;
69
- type WithConstraints<TBuilder, F> = (F extends {
70
- defaultValue: unknown;
71
- } | {
69
+ type WithDefault<TBuilder, TDefault extends boolean> = TDefault extends true ? HasDefault<TBuilder> : TBuilder;
70
+ type WithColumnConstraints<TBuilder, TRequired extends boolean, TDefault extends boolean> = TRequired extends true ? NotNull<WithDefault<TBuilder, TDefault>> : WithDefault<TBuilder, TDefault>;
71
+ type HasValue<TValue> = undefined extends TValue ? false : true;
72
+ type FieldDefault<TField> = TField extends {
73
+ defaultValue: infer TValue;
74
+ } ? HasValue<TValue> : false;
75
+ type HasFieldDefault<TField> = false extends FieldDefault<TField> ? false : true;
76
+ type InsertDefault<TField, TDefault extends boolean> = [TField] extends [{
72
77
  onUpdate: true;
73
- } ? HasDefault<TBuilder> : TBuilder) extends (infer TDefault) ? F extends {
78
+ }] ? true : TDefault;
79
+ type FieldRequired<TField> = [TField] extends [{
74
80
  required: true;
75
- } ? NotNull<TDefault> : TDefault : never;
81
+ }] ? true : false;
82
+ type WithConstraints<TBuilder, TField> = WithColumnConstraints<TBuilder, FieldRequired<TField>, InsertDefault<TField, HasFieldDefault<TField>>>;
76
83
  type SqliteBuilder<F> = F extends {
77
84
  type: "boolean";
78
85
  } ? SQLiteBooleanBuilder : F extends {
@@ -95,32 +102,75 @@ type PostgresBuilder<F> = F extends {
95
102
  } ? PgTextBuilder : F extends {
96
103
  type: "json";
97
104
  } ? PgJsonbBuilder : $Type<PgTextBuilder, FieldData<F>>;
98
- type SqliteColumns<TFields> = {
105
+ type WithSqliteConstraints<TBuilder, TField, TColumns, TName extends string> = [TColumns] extends [never] ? WithConstraints<TBuilder, TField> : [TColumns] extends [Record<TName, infer TColumn extends AuthExistingColumn>] ? WithColumnConstraints<TBuilder, [TColumn] extends [{
106
+ notNull: true;
107
+ }] ? true : false, InsertDefault<TField, [TColumn] extends [{
108
+ default: string;
109
+ }] ? true : false>> : WithColumnConstraints<TBuilder, HasFieldDefault<TField> extends true ? FieldRequired<TField> : false, InsertDefault<TField, HasFieldDefault<TField>>>;
110
+ type SqliteColumns<TFields, TExistingColumns> = {
99
111
  id: IsPrimaryKey<SQLiteTextBuilder<[string, ...string[]]>>;
100
- } & { -readonly [K in keyof TFields]: WithConstraints<SqliteBuilder<TFields[K]>, TFields[K]>; };
112
+ } & { -readonly [K in keyof TFields]: WithSqliteConstraints<SqliteBuilder<TFields[K]>, TFields[K], TExistingColumns, SqlName<K & string>>; };
101
113
  type PostgresColumns<TFields> = {
102
114
  id: IsPrimaryKey<PgTextBuilder>;
103
115
  } & { -readonly [K in keyof TFields]: WithConstraints<PostgresBuilder<TFields[K]>, TFields[K]>; };
104
- /** The Better Auth table `TModel` in a SQLite Database, with a typed column for each field. */
105
- export type AuthSqliteCoreTable<TModel extends AuthTableName> = SQLiteTableWithColumns<{
116
+ /** A SQLite table with a typed column for each field of `TFields`. */
117
+ export type AuthSqliteTableOf<TFields, TExistingColumns = never> = SQLiteTableWithColumns<{
106
118
  name: string;
107
119
  schema: undefined;
108
- columns: BuildColumns<string, SqliteColumns<AuthCoreTableSpecs[TModel]["fields"]>, "sqlite">;
120
+ columns: BuildColumns<string, SqliteColumns<TFields, TExistingColumns>, "sqlite">;
109
121
  dialect: "sqlite";
110
122
  isAlias: false;
111
123
  }>;
112
- /** The Better Auth table `TModel` in a Postgres Database, with a typed column for each field. */
113
- export type AuthPostgresCoreTable<TModel extends AuthTableName> = PgTableWithColumns<{
124
+ /** A Postgres table with a typed column for each field of `TFields`. */
125
+ export type AuthPostgresTableOf<TFields> = PgTableWithColumns<{
114
126
  name: string;
115
127
  schema: undefined;
116
- columns: PgBuildColumns<string, PostgresColumns<AuthCoreTableSpecs[TModel]["fields"]>>;
128
+ columns: PgBuildColumns<string, PostgresColumns<TFields>>;
117
129
  dialect: "pg";
118
130
  isAlias: false;
119
131
  }>;
132
+ /** The Better Auth table `TModel` in a SQLite Database, with a typed column for each field. */
133
+ export type AuthSqliteCoreTable<TModel extends AuthTableName> = AuthSqliteTableOf<AuthCoreTableSpecs[TModel]["fields"]>;
134
+ /** The Better Auth table `TModel` in a Postgres Database, with a typed column for each field. */
135
+ export type AuthPostgresCoreTable<TModel extends AuthTableName> = AuthPostgresTableOf<AuthCoreTableSpecs[TModel]["fields"]>;
120
136
  /** The Better Auth tables for SQLite, libSQL, and Cloudflare D1. Auth adds them to the app Database. */
121
137
  export type AuthSqliteSchema = { readonly [TModel in AuthTableName]: AuthSqliteCoreTable<TModel>; };
122
138
  /** The Better Auth tables for Postgres. Auth adds them to the app Database. */
123
139
  export type AuthPostgresSchema = { readonly [TModel in AuthTableName]: AuthPostgresCoreTable<TModel>; };
140
+ /** The fields of a union of field records, keyed by every key of the union. */
141
+ type MergeFields<TUnion> = { [K in TUnion extends unknown ? keyof TUnion : never]: TUnion extends { readonly [P in K]: infer TField; } ? TField : never; };
142
+ /** `TFirst` wins a key that both have, as `resolveAuthTableSpecs()` keeps the column that a table has already. */
143
+ type Prefer<TFirst, TSecond> = TFirst & Omit<TSecond, keyof TFirst>;
144
+ type HasPlugin<TPlugins, TPlugin> = TPlugins extends readonly [infer TFirst, ...infer TRest] ? [TFirst] extends [TPlugin] ? true : HasPlugin<TRest, TPlugin> : TPlugins extends readonly [...infer TRest, infer TLast] ? [TLast] extends [TPlugin] ? true : HasPlugin<TRest, TPlugin> : false;
145
+ type SchemaPlugins<TOptions> = [TOptions] extends [{
146
+ plugins: infer TPlugins;
147
+ }] ? { [P in AuthSchemaPlugin]: false extends HasPlugin<TPlugins, P> ? never : P; }[AuthSchemaPlugin] : never;
148
+ type PluginFields<TPlugin extends AuthSchemaPlugin, TModel extends string> = TPlugin extends unknown ? AuthPluginSchemas[TPlugin] extends {
149
+ fields: { readonly [K in TModel]: infer TFields; };
150
+ } ? TFields : never : never;
151
+ type PluginTables<TPlugin extends AuthSchemaPlugin> = MergeFields<TPlugin extends unknown ? AuthPluginSchemas[TPlugin] extends {
152
+ tables: infer TTables;
153
+ } ? TTables : never : never>;
154
+ type GuaranteedFieldKeys<TFields, TKey = keyof TFields> = TKey extends keyof TFields ? string extends TKey ? never : [TFields] extends [Record<TKey, AuthTableField>] ? TKey : never : never;
155
+ type AdditionalFields<TOptions, TModel extends string> = TModel extends AuthCoreModel ? [TOptions] extends [{
156
+ additionalFields: { readonly [K in TModel]: infer TFields; };
157
+ }] ? Pick<TFields, GuaranteedFieldKeys<TFields>> : {} : {};
158
+ type TableFields<TOptions, TModel extends AuthTableName> = Prefer<Prefer<AuthCoreTableSpecs[TModel]["fields"], MergeFields<PluginFields<SchemaPlugins<TOptions>, TModel>>>, AdditionalFields<TOptions, TModel>>;
159
+ type PluginTableFields<TOptions, TTable extends keyof PluginTables<SchemaPlugins<TOptions>>> = PluginTables<SchemaPlugins<TOptions>>[TTable] extends {
160
+ fields: infer TFields;
161
+ } ? TFields : never;
162
+ type Lower = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
163
+ type Upper = Uppercase<Lower>;
164
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
165
+ /** The same word boundaries as `authSqlName()`, for lookup in a migration snapshot. */
166
+ type SqlName<TName extends string, TPrevious extends string = "", TResult extends string = ""> = TName extends `${infer TChar}${infer TRest}` ? SqlName<TRest, TChar, `${TResult}${TChar extends Upper ? TPrevious extends Lower | Digit ? "_" : TPrevious extends Upper ? TRest extends `${Lower}${string}` ? "_" : "" : "" : ""}${Lowercase<TChar>}`> : TResult;
167
+ type ExistingColumns<TExisting, TModel extends string> = [TExisting] extends [Record<SqlName<TModel>, {
168
+ columns: infer TColumns;
169
+ }>] ? TColumns : never;
170
+ /** The Better Auth tables for SQLite, with fields from `TOptions` and constraints from a literal migration snapshot. */
171
+ export type AuthSqliteSchemaFor<TOptions extends AuthSchemaOptions, TExisting extends AuthExistingTables | undefined = undefined> = { readonly [TModel in AuthTableName]: AuthSqliteTableOf<TableFields<TOptions, TModel>, ExistingColumns<TExisting, TModel>>; } & { readonly [TTable in keyof PluginTables<SchemaPlugins<TOptions>>]: AuthSqliteTableOf<PluginTableFields<TOptions, TTable>, ExistingColumns<TExisting, TTable & string>>; };
172
+ /** The Better Auth tables for Postgres, with the plugin tables and the plugin and additional columns of `TOptions`. */
173
+ export type AuthPostgresSchemaFor<TOptions extends AuthSchemaOptions> = { readonly [TModel in AuthTableName]: AuthPostgresTableOf<TableFields<TOptions, TModel>>; } & { readonly [TTable in keyof PluginTables<SchemaPlugins<TOptions>>]: AuthPostgresTableOf<PluginTableFields<TOptions, TTable>>; };
124
174
  export declare const authSqliteSchema: AuthSqliteSchema;
125
175
  export declare const authPostgresSchema: AuthPostgresSchema;
126
176
  /**
@@ -128,10 +178,12 @@ export declare const authPostgresSchema: AuthPostgresSchema;
128
178
  * Auth Vite plugin writes a module that calls it when the Auth Definition adds fields or imports a plugin of
129
179
  * `AuthSchemaPlugin`, or when the Database has some of the tables already. `existing` holds those tables, read from the
130
180
  * latest migration: each one keeps the column defaults, unique keys, and foreign keys that only a table rebuild could
131
- * change, so the migration adds columns and indexes, and does not drop a table that other tables reference.
181
+ * change, so the migration adds columns and indexes, and does not drop a table that other tables reference. The
182
+ * columns of the plugins and additional fields are typed from the literal of `options`, with constraints from the
183
+ * snapshot literal when present.
132
184
  */
133
- export declare function createAuthSqliteSchema(options: AuthSchemaOptions, existing?: AuthExistingTables): AuthSqliteSchema & Readonly<Record<string, AuthSqliteTable>>;
134
- /** The Better Auth tables for Postgres, with the plugins and additional fields of `options`. */
135
- export declare function createAuthPostgresSchema(options: AuthSchemaOptions): AuthPostgresSchema & Readonly<Record<string, AuthPostgresTable>>;
185
+ export declare function createAuthSqliteSchema<const TOptions extends AuthSchemaOptions, const TExisting extends AuthExistingTables | undefined = AuthExistingTables | undefined>(options: TOptions, existing?: TExisting): AuthSqliteSchemaFor<TOptions, TExisting>;
186
+ /** The Better Auth tables for Postgres, with the plugins and additional fields of `options`, typed from its literal. */
187
+ export declare function createAuthPostgresSchema<const TOptions extends AuthSchemaOptions>(options: TOptions): AuthPostgresSchemaFor<TOptions>;
136
188
  //#endregion
137
- export { type AuthCoreModel, type AuthCoreTableSpecs, type AuthSchemaOptions, type AuthSchemaPlugin, type AuthTableField, type AuthTableName, type AuthTableSpec, authPluginSchemas, authTableSpecs, resolveAuthTableSpecs };
189
+ export { type AuthCoreModel, type AuthCoreTableSpecs, type AuthPluginSchemas, type AuthSchemaOptions, type AuthSchemaPlugin, type AuthTableField, type AuthTableName, type AuthTableSpec, authPluginSchemas, authTableSpecs, resolveAuthTableSpecs };
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-CURphR3n.js";
1
+ import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-D0VLp1U4.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";
@@ -134,12 +134,14 @@ const authPostgresSchema = buildTables(postgresDialect, authTableSpecs);
134
134
  * Auth Vite plugin writes a module that calls it when the Auth Definition adds fields or imports a plugin of
135
135
  * `AuthSchemaPlugin`, or when the Database has some of the tables already. `existing` holds those tables, read from the
136
136
  * latest migration: each one keeps the column defaults, unique keys, and foreign keys that only a table rebuild could
137
- * change, so the migration adds columns and indexes, and does not drop a table that other tables reference.
137
+ * change, so the migration adds columns and indexes, and does not drop a table that other tables reference. The
138
+ * columns of the plugins and additional fields are typed from the literal of `options`, with constraints from the
139
+ * snapshot literal when present.
138
140
  */
139
141
  function createAuthSqliteSchema(options, existing) {
140
142
  return buildTables(sqliteDialect, resolveAuthTableSpecs(options), existing);
141
143
  }
142
- /** The Better Auth tables for Postgres, with the plugins and additional fields of `options`. */
144
+ /** The Better Auth tables for Postgres, with the plugins and additional fields of `options`, typed from its literal. */
143
145
  function createAuthPostgresSchema(options) {
144
146
  return buildTables(postgresDialect, resolveAuthTableSpecs(options));
145
147
  }
@@ -1,4 +1,5 @@
1
- import { T as AuthRequestInput, V as ResolvedAuthAccessRoute, g as AuthDefinition } from "./types-CruflEFI.js";
1
+ import { E as AuthRequestInput, H as ResolvedAuthAccessRoute, _ as AuthDefinition } from "./types-gl-myjZc.js";
2
+ import "./own-access-CdgEICjO.js";
2
3
  import { AccessAuthorizationContext, ViteHubContext } from "@vite-hub/runtime";
3
4
  //#region src/runtime-state.d.ts
4
5
  type AuthRuntimeEnvResolver = (event?: ViteHubContext) => Record<string, unknown>;
@@ -7,19 +8,17 @@ declare function resetAuth(): void;
7
8
  //#endregion
8
9
  //#region src/runtime/server.d.ts
9
10
  declare function setAuthRuntimeEnvResolver(resolver: AuthRuntimeEnvResolver | undefined, definition?: AuthDefinition): void;
11
+ /**
12
+ * Stops the server when `access.pages` of the Auth Definition differs from the map that the Nuxt build read, for
13
+ * example when `access` is a variable: the build guards only the pages that it reads. A Definition callback returns its
14
+ * options when Auth resolves them, so the check runs on each result.
15
+ */
16
+ declare function checkBuiltAuthPages(definition: AuthDefinition, built: Readonly<Record<string, unknown>>): void;
10
17
  /**
11
18
  * Let a trusted server integration authenticate one exact mounted path without a browser session.
12
19
  * Resolved users still pass every matching Auth access route's authorize callback, with an empty session.
13
20
  */
14
21
  declare function setAuthAccessIdentityResolver(path: string, resolver: AuthAccessIdentityResolver | undefined): void;
15
- /**
16
- * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
17
- * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
18
- * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
19
- */
20
- declare const authAccessHandlerMeta: Readonly<{
21
- vitehubAuthAccess: "handler";
22
- }>;
23
22
  interface AuthAccessRouteMatch {
24
23
  index: number;
25
24
  authorize: boolean;
@@ -38,4 +37,4 @@ declare function createLazyAuthAccessHandler(routes: readonly ResolvedAuthAccess
38
37
  createAuthAccessHandler: (routes: readonly ResolvedAuthAccessRoute[], definition?: undefined, publicRoutes?: readonly string[]) => AuthAccessHandler;
39
38
  }>, publicRoutes?: readonly string[]): AuthAccessHandler;
40
39
  //#endregion
41
- export { setAuthAccessIdentityResolver as a, createLazyAuthAccessHandler as i, authAccessHandlerMeta as n, setAuthRuntimeEnvResolver as o, createAuthAccessRouteMatcher as r, resetAuth as s, AuthAccessRouteMatch as t };
40
+ export { setAuthAccessIdentityResolver as a, createLazyAuthAccessHandler as i, checkBuiltAuthPages as n, setAuthRuntimeEnvResolver as o, createAuthAccessRouteMatcher as r, resetAuth as s, AuthAccessRouteMatch as t };
@@ -1,8 +1,8 @@
1
- import { B as RegisteredAuth, Dt as AuthEventAggregates, Ft as AuthEventWindow, L as AuthSignInConfiguration, M as AuthRuntimeOptions, Nt as AuthEventStore, S as AuthGuardedHandler, T as AuthRequestInput, U as ViteHubAuth, V as ResolvedAuthAccessRoute, d as AuthAnonymousGuardedHandler, g as AuthDefinition, h as AuthBetterAuthRuntimeOptions, jt as AuthEventPage, kt as AuthEventListInput, p as AuthAuthorization, rt as AuthConsoleHostOptions, u as AuthAnonymousAuthorize, w as AuthRequest, x as AuthFor } from "./types-CruflEFI.js";
2
- import { i as AbilityName, n as AbilityAuthorization, t as AbilityArgs } from "./abilities-CbmTAoS_.js";
3
- import { t as AuthConsole } from "./console-runtime-D2ai-Et5.js";
4
- import "./server-C8TlOrSy.js";
5
- import "./ability-error-DcgChwCN.js";
1
+ 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-gl-myjZc.js";
2
+ import { i as AbilityName, n as AbilityAuthorization, t as AbilityArgs } from "./abilities-9jC7iuN0.js";
3
+ import { t as AuthConsole } from "./console-runtime-Dqidb3zF.js";
4
+ import "./server-B-zNtSvm.js";
5
+ import "./ability-error-DUWJ6Q1W.js";
6
6
  import { AccessAuthorizeOption, Result, ViteHubContext } from "@vite-hub/runtime";
7
7
  import { APIError } from "better-auth/api";
8
8
  import { AuthContext, BetterAuthOptions, BetterAuthPlugin, User } from "better-auth";
@@ -36,6 +36,7 @@ type AuthCaller<TRegistry = ViteHub.AuthRegistry> = {
36
36
  type AuthCallerErrorCode = "AUTH_MCP_TOKEN_INVALID" | "AUTH_SIGNED_OUT";
37
37
  //#endregion
38
38
  //#region src/auth-instance.d.ts
39
+ declare function findVerifiedAuthUserId(email: string, request: Request): Promise<string | undefined>;
39
40
  declare function createBetterAuthOptions(definition: AuthDefinition): AuthBetterAuthRuntimeOptions;
40
41
  declare function getAuthForDefinition<TDefinition extends AuthDefinition>(definition: TDefinition): AuthFor<TDefinition>;
41
42
  /**
@@ -201,4 +202,4 @@ declare function aggregateAuthEvents(window: AuthEventWindow, definition?: AuthD
201
202
  */
202
203
  declare function getAuthConsoleForRequest(request: Request, event?: ViteHubContext, host?: AuthConsoleHostOptions): AuthConsole;
203
204
  //#endregion
204
- export { authForRequest as A, requireCaller as C, withAnonymousAuthorization as D, useAuth as E, AuthCallerUser as F, AuthMemberErrorCode as I, getAuthForDefinition as M, AuthCaller as N, withAuth as O, AuthCallerErrorCode as P, 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 };
205
+ export { authForRequest as A, requireCaller as C, withAnonymousAuthorization as D, useAuth as E, AuthCallerErrorCode as F, AuthCallerUser as I, AuthMemberErrorCode as L, findVerifiedAuthUserId as M, getAuthForDefinition as N, withAuth as O, AuthCaller as P, 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 };
@@ -1,16 +1,16 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { t as readSetCookies } from "./set-cookie-DmqWq6kj.js";
3
- import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DVzjOKc7.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ import { t as readSetCookies } from "./set-cookie-DWIyCCJO.js";
3
+ import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-CZmZS5QF.js";
4
4
  import { n as authRequestEvent, r as unwrapAuthRequest } from "./request-z6DHHmrb.js";
5
- import { t as createAuthConsole } from "./console-runtime-_LrpyCYY.js";
6
- import { i as notMemberError, l as findAccessPolicyPlugin } from "./members-DdlsS8kJ.js";
5
+ import { t as createAuthConsole } from "./console-runtime-CuXRDhGy.js";
6
+ import { i as notMemberError, l as findAccessPolicyPlugin } from "./members-Cl3hFRjk.js";
7
7
  import { n as getAuthRuntimeState } from "./runtime-state-ojQCzKOc.js";
8
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DCfuicoo.js";
9
- import { a as requestProvider, c as resolveAuthOptions, d as setRequestClientAddress, f as withClientAddress, i as getAuthForDefinition, l as trustsProxyHeaders, m as forwardedRequestOrigin, n as createBetterAuthOptions, o as resolveDefaultDefinition, p as runWithAuthEvent, r as envResolverFor, s as withSessionMarker, t as authForRequest, u as eventClientAddress } from "./auth-instance-CmDogt4D.js";
8
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DJmO9a9I.js";
9
+ 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-zYMjldPG.js";
10
10
  import { i as resolveAuthMountPath, n as canonicalAccessPath } from "./application-path-DuTpfGFj.js";
11
- import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
11
+ import { a as normalizeAuthBasePath } from "./access-pages-FNQTyGRD.js";
12
12
  import { createAuthAccessRouteMatcher } from "./runtime/server.js";
13
- import { n as checkAbility, t as AbilityError } from "./ability-error-IeZQBr_-.js";
13
+ import { n as checkAbility, t as AbilityError } from "./ability-error-DmnUGicq.js";
14
14
  import { n as mcpOAuthResources, t as isJwsToken } from "./mcp-config-DRRlCAWN.js";
15
15
  import { defineErrors, toResultError } from "@vite-hub/runtime";
16
16
  import { HTTPError } from "nitro/h3";
@@ -249,7 +249,11 @@ function handleAuthRequest(definition, input, event = authRequestEvent(input)) {
249
249
  env: envResolverFor(definition)
250
250
  });
251
251
  const auth = requestProvider(definition, resolved);
252
- return runWithAuthEvent(event, () => handleSignInRoute(auth, resolved.options, request, address) ?? auth.handler(setRequestClientAddress(toRequest(request), address)));
252
+ return runWithAuthEvent(event, async () => {
253
+ const response = await (handleSignInRoute(auth, resolved.options, request, address) ?? auth.handler(setRequestClientAddress(toRequest(request), address)));
254
+ await setAuthResponseOutcome(event, response);
255
+ return response;
256
+ });
253
257
  }
254
258
  /**
255
259
  * With a provider in `access.signIn`, the Auth route also answers `GET <basePath>/sign-in` and `GET <basePath>/sign-out`, so a link
@@ -522,9 +526,18 @@ function checkedAuthorization(request, session, user) {
522
526
  user
523
527
  });
524
528
  }
525
- function reject(response) {
529
+ function reject(input, response) {
530
+ logRefusal(input, response);
526
531
  return { response };
527
532
  }
533
+ function logRefusal(input, response) {
534
+ const code = refusalCodes.get(response);
535
+ setAuthOutcome(input, {
536
+ outcome: "refused",
537
+ status: response.status,
538
+ ...code ? { code } : {}
539
+ });
540
+ }
528
541
  const nativeResponseClone = Object.getOwnPropertyDescriptor(Response.prototype, "clone")?.value;
529
542
  /**
530
543
  * A Response of this runtime with an own `then` would be assimilated as a thenable by the host that awaits it.
@@ -688,9 +701,9 @@ async function runAccessAuthorize(authorize, context, deny = () => createForbidd
688
701
  }
689
702
  async function checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes = [], redirectToSignIn = true, resolveIdentity, signInURLs) {
690
703
  const { auth, event, options, refusal: providerRefusal, request, session } = await readRequestSession(input, definition);
691
- if (providerRefusal) return reject(createProviderRefusalResponse(providerRefusal));
704
+ if (providerRefusal) return reject(input, createProviderRefusalResponse(providerRefusal));
692
705
  const identity = await resolveIdentity?.(toRequest(request), input, Boolean(session));
693
- if (isRuntimeResponse(identity)) return reject(identity);
706
+ if (isRuntimeResponse(identity)) return reject(input, identity);
694
707
  if (identity || session) {
695
708
  const authorization = checkedAuthorization(request, identity ? {} : session.session, identity ?? session.user);
696
709
  if (routeIndexes === void 0) return { authorization };
@@ -698,43 +711,47 @@ async function checkAuthRequest(input, definition, routeIndexes, requiredAuthori
698
711
  const routes = authAccessRoutes(options, routeIndexes);
699
712
  for (const [index, route] of routes.entries()) {
700
713
  const authorize = typeof route === "object" && route !== null ? route.authorize : void 0;
701
- if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index])) return reject(createForbiddenResponse(request));
714
+ if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index])) return reject(input, createForbiddenResponse(request));
702
715
  if (!authorize) continue;
703
716
  const rejection = await runAccessAuthorize(authorize, {
704
717
  ...authorization,
705
718
  event
706
719
  });
707
- if (rejection.response) return reject(rejection.response);
720
+ if (rejection.response) return reject(input, rejection.response);
708
721
  }
709
722
  return { authorization };
710
723
  }
711
- if (!wantsHtml(request)) return reject(createRefusalResponse("SIGNED_OUT"));
712
- if (!redirectToSignIn) return reject(createRefusalResponse("SIGNED_OUT"));
713
- if (new URL(request.url).searchParams.has("auth_error")) return reject(createTextRefusalResponse("Unauthorized.", "SIGNED_OUT"));
724
+ if (!wantsHtml(request)) return reject(input, createRefusalResponse("SIGNED_OUT"));
725
+ if (!redirectToSignIn) return reject(input, createRefusalResponse("SIGNED_OUT"));
726
+ if (new URL(request.url).searchParams.has("auth_error")) return reject(input, createTextRefusalResponse("Unauthorized.", "SIGNED_OUT"));
714
727
  const signIn = providerSignIn(options);
715
- return reject(signIn ? await createSignInResponse(auth, options, {
728
+ return reject(input, signIn ? await createSignInResponse(auth, options, {
716
729
  ...signIn,
717
730
  ...signInURLs
718
731
  }, eventClientAddress(event)) : createRefusalResponse("SIGNED_OUT"));
719
732
  }
720
733
  async function checkAuthorizeRequest(input, authorize, definition) {
721
734
  const { refusal: providerRefusal, request, session } = await readRequestSession(input, definition);
722
- if (providerRefusal) return reject(createProviderRefusalResponse(providerRefusal));
723
- if (!session) return reject(createRefusalResponse("SIGNED_OUT"));
735
+ if (providerRefusal) return reject(input, createProviderRefusalResponse(providerRefusal));
736
+ if (!session) return reject(input, createRefusalResponse("SIGNED_OUT"));
724
737
  const authorization = checkedAuthorization(request, session.session, session.user);
725
738
  if (authorize === true) return { authorization };
726
739
  const rejection = await runAccessAuthorize(authorize, {
727
740
  ...authorization,
728
741
  event: authRequestEvent(input)
729
742
  });
730
- return rejection.response ? reject(rejection.response) : { authorization };
743
+ return rejection.response ? reject(input, rejection.response) : { authorization };
731
744
  }
732
745
  function withAnonymousAuthorization(authorize, handler, definition) {
733
746
  if (typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be a function." });
734
747
  if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAnonymousAuthorization() requires a handler function." });
735
748
  return async (input) => {
736
749
  const { refusal: providerRefusal, request, session } = await readRequestSession(input, definition ?? resolveDefaultDefinition());
737
- if (providerRefusal) return sendSessionCookies(input, createProviderRefusalResponse(providerRefusal));
750
+ if (providerRefusal) {
751
+ const response = createProviderRefusalResponse(providerRefusal);
752
+ logRefusal(input, response);
753
+ return sendSessionCookies(input, response);
754
+ }
738
755
  const authorization = session ? checkedAuthorization(request, session.session, session.user) : Object.freeze({
739
756
  request,
740
757
  session: null,
@@ -745,7 +762,10 @@ function withAnonymousAuthorization(authorize, handler, definition) {
745
762
  ...authorization,
746
763
  event: authRequestEvent(input)
747
764
  }, deny);
748
- if (rejection.response) return sendSessionCookies(input, rejection.response);
765
+ if (rejection.response) {
766
+ logRefusal(input, rejection.response);
767
+ return sendSessionCookies(input, rejection.response);
768
+ }
749
769
  return sendSessionCookies(input, await handler(input, authorization));
750
770
  };
751
771
  }
@@ -828,7 +848,7 @@ async function readCaller(event, definition) {
828
848
  const auth = authForRequest(request, authRequestEvent(event), definition);
829
849
  const { options } = await auth.$context;
830
850
  if (isJwsToken(token) && mcpOAuthResources(options.plugins).length) {
831
- const { verifyAppAccessToken } = await import("./mcp-token-CpxLyl_p.js").then((n) => n.i);
851
+ const { verifyAppAccessToken } = await import("./mcp-token-BhonlK9C.js").then((n) => n.i);
832
852
  const url = new URL(request.url);
833
853
  const [error, caller] = await verifyAppAccessToken(token, trustsProxyHeaders(options) ? forwardedRequestOrigin(request) : url.origin, url.pathname, auth);
834
854
  if (error) return [error, void 0];
package/dist/server.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, F as AuthCallerUser, I as AuthMemberErrorCode, N as AuthCaller, O as withAuth, P as AuthCallerErrorCode, 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 } from "./server-BM-RSf1T.js";
3
- import { n as AbilityErrorData, t as AbilityError } from "./ability-error-DcgChwCN.js";
2
+ import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, F as AuthCallerErrorCode, I as AuthCallerUser, L as AuthMemberErrorCode, O as withAuth, P as AuthCaller, 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 } from "./server-Ci2i6p1S.js";
3
+ import { n as AbilityErrorData, t as AbilityError } from "./ability-error-DUWJ6Q1W.js";
4
4
  export { AbilityError, type AbilityErrorData, type AuthCaller, type AuthCallerErrorCode, type AuthCallerUser, type AuthEventReadErrorCode, type AuthMemberErrorCode, aggregateAuthEvents, can, checkAuthMember, createAuthHandler, authRoute as default, getAuthConsoleForRequest, getAuthEvents, handleAuth, listAuthEvents, requireAbility, requireAuth, requireAuthorization, requireCaller, signOut, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };