@vite-hub/auth 0.4.1 → 0.5.1

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 (89) hide show
  1. package/README.md +32 -8
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-3L1Y5Pnw.d.ts} +2 -4
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/abilities.js +1 -2
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-BHhPkrZd.js} +3 -5
  6. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-C1c30O6E.d.ts} +1 -5
  7. package/dist/access-pages-BwImVHN_.js +94 -0
  8. package/dist/{admin-claim-code-CDipqeAU.js → admin-claim-code-C3X_U43x.js} +1 -2
  9. package/dist/agent.d.ts +1 -3
  10. package/dist/agent.js +5 -6
  11. package/dist/{application-path-DuTpfGFj.js → application-path-zKi7NrvK.js} +1 -2
  12. package/dist/{auth-instance-CmDogt4D.js → auth-instance-_J7R9Qs1.js} +239 -50
  13. package/dist/{cli-ubYJpAL_.d.ts → cli-C5pAfY4x.d.ts} +1 -6
  14. package/dist/cli.d.ts +2 -4
  15. package/dist/cli.js +3 -4
  16. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-BP1ZKJB0.d.ts} +13 -13
  17. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-vc3JQEuq.js} +72 -40
  18. package/dist/console-runtime.d.ts +2 -2
  19. package/dist/console-runtime.js +1 -2
  20. package/dist/{console-types-CmmnKGMx.js → console-types-51lkf0lk.js} +1 -2
  21. package/dist/console.d.ts +1 -5
  22. package/dist/console.js +2 -3
  23. package/dist/{database-options-DpOVjUti.js → database-options-DQ-8qYMl.js} +2 -3
  24. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CkSeU9V3.js} +2 -3
  25. package/dist/database.d.ts +1 -3
  26. package/dist/database.js +5 -6
  27. package/dist/{definition-BCaLA9kW.js → definition-MDGMNKrK.js} +20 -18
  28. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-BssJr_2t.js} +9 -4
  29. package/dist/{events-DCfuicoo.js → events-DZqMiae_.js} +4 -6
  30. package/dist/forward.d.ts +1 -3
  31. package/dist/forward.js +2 -3
  32. package/dist/index.d.ts +4 -7
  33. package/dist/index.js +4 -3
  34. package/dist/internal/server.d.ts +4 -4
  35. package/dist/internal/server.js +5 -5
  36. package/dist/{invariant-D8_xBqmZ.js → invariant-Dj2R1eMr.js} +2 -3
  37. package/dist/{mcp-config-DRRlCAWN.js → mcp-config-C7srUMIZ.js} +2 -3
  38. package/dist/{mcp-token-CpxLyl_p.js → mcp-token--KuLYEub.js} +7 -18
  39. package/dist/mcp.d.ts +0 -4
  40. package/dist/mcp.js +4 -5
  41. package/dist/{members-DdlsS8kJ.js → members-D3_Q5XJb.js} +10 -14
  42. package/dist/nitro-kit-Bg4xUZAI.js +43 -0
  43. package/dist/{nuxt-bridge-Cl988STZ.js → nuxt-bridge-pRyfYD5c.js} +1 -2
  44. package/dist/nuxt.d.ts +31 -24
  45. package/dist/nuxt.js +336 -18
  46. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  47. package/dist/own-access-C22hSIuF.d.ts +18 -0
  48. package/dist/own-access-DQgqxTbI.js +30 -0
  49. package/dist/{page-tools-shared-l4eyj53D.js → page-tools-shared-CtoKaNQZ.js} +1 -2
  50. package/dist/{presets-CHndEv5i.d.ts → presets-C6AtiRdI.d.ts} +0 -2
  51. package/dist/presets.d.ts +1 -1
  52. package/dist/presets.js +2 -3
  53. package/dist/{request-z6DHHmrb.js → request-Dpq7GO8B.js} +2 -4
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +2 -2
  56. package/dist/runtime/empty-abilities.d.ts +1 -3
  57. package/dist/runtime/empty-abilities.js +1 -2
  58. package/dist/runtime/empty-client.d.ts +0 -2
  59. package/dist/runtime/empty-client.js +1 -2
  60. package/dist/runtime/empty-definition.d.ts +1 -3
  61. package/dist/runtime/empty-definition.js +1 -2
  62. package/dist/runtime/nuxt.d.ts +1 -3
  63. package/dist/runtime/nuxt.js +1 -2
  64. package/dist/runtime/server.d.ts +3 -2
  65. package/dist/runtime/server.js +27 -19
  66. package/dist/runtime/vue-nuxt.d.ts +0 -2
  67. package/dist/runtime/vue-nuxt.js +74 -33
  68. package/dist/{runtime-state-ojQCzKOc.js → runtime-state-DtKUfxKq.js} +1 -2
  69. package/dist/schema.d.ts +71 -23
  70. package/dist/schema.js +6 -5
  71. package/dist/{server-BM-RSf1T.d.ts → server-CFWlYQJb.d.ts} +7 -14
  72. package/dist/{server-BG_MFd4q.js → server-D4Hi4TBI.js} +51 -33
  73. package/dist/{server-C8TlOrSy.d.ts → server-DCsgxFPP.d.ts} +9 -14
  74. package/dist/server.d.ts +2 -2
  75. package/dist/server.js +2 -2
  76. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-1FMcMnRh.js} +6 -8
  77. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DkqM1kvj.js} +3 -5
  78. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BLm_Zlss.d.ts} +255 -3
  79. package/dist/{table-specs-CURphR3n.js → table-specs-jw0jjU6l.js} +43 -44
  80. package/dist/test.d.ts +2 -4
  81. package/dist/test.js +3 -4
  82. package/dist/{types-CruflEFI.d.ts → types-BHSgxyvV.d.ts} +50 -11
  83. package/dist/{vite-Dy0Xhq4H.js → vite-D1xC9n1O.js} +365 -152
  84. package/dist/vite.d.ts +7 -14
  85. package/dist/vite.js +1 -2
  86. package/dist/vue.d.ts +17 -72
  87. package/dist/vue.js +25 -73
  88. package/package.json +35 -30
  89. package/dist/shared-DRtfuFsV.js +0 -12
@@ -1,12 +1,34 @@
1
- import { r as unwrapAuthRequest } from "../request-z6DHHmrb.js";
2
- import { n as getAuthRuntimeState } from "../runtime-state-ojQCzKOc.js";
3
- import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-DuTpfGFj.js";
4
- //#region src/runtime/server.ts
1
+ import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-zKi7NrvK.js";
2
+ import { t as authErrorDiagnostics } from "../error-diagnostics-BssJr_2t.js";
3
+ import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-DQgqxTbI.js";
4
+ import { r as unwrapAuthRequest } from "../request-Dpq7GO8B.js";
5
+ import { n as getAuthRuntimeState } from "../runtime-state-DtKUfxKq.js";
6
+ // 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
  }
@@ -73,5 +82,4 @@ function createLazyAuthAccessHandler(routes, load, publicRoutes = []) {
73
82
  return await (await handler)(input);
74
83
  };
75
84
  }
76
- //#endregion
77
- export { authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
85
+ export { authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,4 +1,2 @@
1
- //#region src/runtime/vue-nuxt.d.ts
2
1
  declare const viteHubAuthPlugin: unknown;
3
- //#endregion
4
2
  export { viteHubAuthPlugin as default };
@@ -1,9 +1,16 @@
1
- import { i as resolveAuthMountPath } from "../application-path-DuTpfGFj.js";
2
- import "../page-tools-shared-l4eyj53D.js";
3
- 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
- //#region src/runtime/vue-nuxt.ts
1
+ import { n as invariantError } from "../invariant-Dj2R1eMr.js";
2
+ import "../page-tools-shared-CtoKaNQZ.js";
3
+ import { i as resolveAuthMountPath } from "../application-path-zKi7NrvK.js";
4
+ 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
+ import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRouter, useRuntimeConfig, useState } from "#app";
6
+ // 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,17 +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
- //#endregion
168
209
  export { viteHubAuthPlugin as default };
@@ -1,4 +1,4 @@
1
- //#region src/runtime-state.ts
1
+ // src/runtime-state.ts
2
2
  const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
3
3
  /**
4
4
  * Marks the database that Auth adds to a Definition without one. It keeps rows in the memory of one process, so a value
@@ -21,5 +21,4 @@ function resetAuth() {
21
21
  state.definition = void 0;
22
22
  state.providers = void 0;
23
23
  }
24
- //#endregion
25
24
  export { resetAuth as i, getAuthRuntimeState as n, isAuthProcessMemoryDatabase as r, authProcessMemoryDatabase as t };
package/dist/schema.d.ts CHANGED
@@ -1,8 +1,7 @@
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-BLm_Zlss.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";
5
- //#region src/existing-tables.d.ts
6
5
  interface AuthExistingColumn {
7
6
  notNull: boolean;
8
7
  /** The SQL text of the column default, such as `'member'` or `(cast(unixepoch('subsecond') * 1000 as integer))`. */
@@ -35,8 +34,6 @@ interface AuthExistingTable {
35
34
  }
36
35
  /** The existing tables, by SQL table name. */
37
36
  type AuthExistingTables = Readonly<Record<string, AuthExistingTable>>;
38
- //#endregion
39
- //#region src/schema.d.ts
40
37
  /** A Better Auth table in a SQLite Database (SQLite, libSQL, or Cloudflare D1), with untyped columns. */
41
38
  export type AuthSqliteTable = SQLiteTableWithColumns<{
42
39
  name: string;
@@ -66,13 +63,20 @@ type FieldData<F> = F extends {
66
63
  } ? string[] : F extends {
67
64
  type: "number[]";
68
65
  } ? number[] : unknown;
69
- type WithConstraints<TBuilder, F> = (F extends {
70
- defaultValue: unknown;
71
- } | {
66
+ type WithDefault<TBuilder, TDefault extends boolean> = TDefault extends true ? HasDefault<TBuilder> : TBuilder;
67
+ type WithColumnConstraints<TBuilder, TRequired extends boolean, TDefault extends boolean> = TRequired extends true ? NotNull<WithDefault<TBuilder, TDefault>> : WithDefault<TBuilder, TDefault>;
68
+ type HasValue<TValue> = undefined extends TValue ? false : true;
69
+ type FieldDefault<TField> = TField extends {
70
+ defaultValue: infer TValue;
71
+ } ? HasValue<TValue> : false;
72
+ type HasFieldDefault<TField> = false extends FieldDefault<TField> ? false : true;
73
+ type InsertDefault<TField, TDefault extends boolean> = [TField] extends [{
72
74
  onUpdate: true;
73
- } ? HasDefault<TBuilder> : TBuilder) extends (infer TDefault) ? F extends {
75
+ }] ? true : TDefault;
76
+ type FieldRequired<TField> = [TField] extends [{
74
77
  required: true;
75
- } ? NotNull<TDefault> : TDefault : never;
78
+ }] ? true : false;
79
+ type WithConstraints<TBuilder, TField> = WithColumnConstraints<TBuilder, FieldRequired<TField>, InsertDefault<TField, HasFieldDefault<TField>>>;
76
80
  type SqliteBuilder<F> = F extends {
77
81
  type: "boolean";
78
82
  } ? SQLiteBooleanBuilder : F extends {
@@ -95,32 +99,75 @@ type PostgresBuilder<F> = F extends {
95
99
  } ? PgTextBuilder : F extends {
96
100
  type: "json";
97
101
  } ? PgJsonbBuilder : $Type<PgTextBuilder, FieldData<F>>;
98
- type SqliteColumns<TFields> = {
102
+ 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 [{
103
+ notNull: true;
104
+ }] ? true : false, InsertDefault<TField, [TColumn] extends [{
105
+ default: string;
106
+ }] ? true : false>> : WithColumnConstraints<TBuilder, HasFieldDefault<TField> extends true ? FieldRequired<TField> : false, InsertDefault<TField, HasFieldDefault<TField>>>;
107
+ type SqliteColumns<TFields, TExistingColumns> = {
99
108
  id: IsPrimaryKey<SQLiteTextBuilder<[string, ...string[]]>>;
100
- } & { -readonly [K in keyof TFields]: WithConstraints<SqliteBuilder<TFields[K]>, TFields[K]>; };
109
+ } & { -readonly [K in keyof TFields]: WithSqliteConstraints<SqliteBuilder<TFields[K]>, TFields[K], TExistingColumns, SqlName<K & string>>; };
101
110
  type PostgresColumns<TFields> = {
102
111
  id: IsPrimaryKey<PgTextBuilder>;
103
112
  } & { -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<{
113
+ /** A SQLite table with a typed column for each field of `TFields`. */
114
+ export type AuthSqliteTableOf<TFields, TExistingColumns = never> = SQLiteTableWithColumns<{
106
115
  name: string;
107
116
  schema: undefined;
108
- columns: BuildColumns<string, SqliteColumns<AuthCoreTableSpecs[TModel]["fields"]>, "sqlite">;
117
+ columns: BuildColumns<string, SqliteColumns<TFields, TExistingColumns>, "sqlite">;
109
118
  dialect: "sqlite";
110
119
  isAlias: false;
111
120
  }>;
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<{
121
+ /** A Postgres table with a typed column for each field of `TFields`. */
122
+ export type AuthPostgresTableOf<TFields> = PgTableWithColumns<{
114
123
  name: string;
115
124
  schema: undefined;
116
- columns: PgBuildColumns<string, PostgresColumns<AuthCoreTableSpecs[TModel]["fields"]>>;
125
+ columns: PgBuildColumns<string, PostgresColumns<TFields>>;
117
126
  dialect: "pg";
118
127
  isAlias: false;
119
128
  }>;
129
+ /** The Better Auth table `TModel` in a SQLite Database, with a typed column for each field. */
130
+ export type AuthSqliteCoreTable<TModel extends AuthTableName> = AuthSqliteTableOf<AuthCoreTableSpecs[TModel]["fields"]>;
131
+ /** The Better Auth table `TModel` in a Postgres Database, with a typed column for each field. */
132
+ export type AuthPostgresCoreTable<TModel extends AuthTableName> = AuthPostgresTableOf<AuthCoreTableSpecs[TModel]["fields"]>;
120
133
  /** The Better Auth tables for SQLite, libSQL, and Cloudflare D1. Auth adds them to the app Database. */
121
134
  export type AuthSqliteSchema = { readonly [TModel in AuthTableName]: AuthSqliteCoreTable<TModel>; };
122
135
  /** The Better Auth tables for Postgres. Auth adds them to the app Database. */
123
136
  export type AuthPostgresSchema = { readonly [TModel in AuthTableName]: AuthPostgresCoreTable<TModel>; };
137
+ /** The fields of a union of field records, keyed by every key of the union. */
138
+ type MergeFields<TUnion> = { [K in TUnion extends unknown ? keyof TUnion : never]: TUnion extends { readonly [P in K]: infer TField; } ? TField : never; };
139
+ /** `TFirst` wins a key that both have, as `resolveAuthTableSpecs()` keeps the column that a table has already. */
140
+ type Prefer<TFirst, TSecond> = TFirst & Omit<TSecond, keyof TFirst>;
141
+ 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;
142
+ type SchemaPlugins<TOptions> = [TOptions] extends [{
143
+ plugins: infer TPlugins;
144
+ }] ? { [P in AuthSchemaPlugin]: false extends HasPlugin<TPlugins, P> ? never : P; }[AuthSchemaPlugin] : never;
145
+ type PluginFields<TPlugin extends AuthSchemaPlugin, TModel extends string> = TPlugin extends unknown ? AuthPluginSchemas[TPlugin] extends {
146
+ fields: { readonly [K in TModel]: infer TFields; };
147
+ } ? TFields : never : never;
148
+ type PluginTables<TPlugin extends AuthSchemaPlugin> = MergeFields<TPlugin extends unknown ? AuthPluginSchemas[TPlugin] extends {
149
+ tables: infer TTables;
150
+ } ? TTables : never : never>;
151
+ type GuaranteedFieldKeys<TFields, TKey = keyof TFields> = TKey extends keyof TFields ? string extends TKey ? never : [TFields] extends [Record<TKey, AuthTableField>] ? TKey : never : never;
152
+ type AdditionalFields<TOptions, TModel extends string> = TModel extends AuthCoreModel ? [TOptions] extends [{
153
+ additionalFields: { readonly [K in TModel]: infer TFields; };
154
+ }] ? Pick<TFields, GuaranteedFieldKeys<TFields>> : {} : {};
155
+ type TableFields<TOptions, TModel extends AuthTableName> = Prefer<Prefer<AuthCoreTableSpecs[TModel]["fields"], MergeFields<PluginFields<SchemaPlugins<TOptions>, TModel>>>, AdditionalFields<TOptions, TModel>>;
156
+ type PluginTableFields<TOptions, TTable extends keyof PluginTables<SchemaPlugins<TOptions>>> = PluginTables<SchemaPlugins<TOptions>>[TTable] extends {
157
+ fields: infer TFields;
158
+ } ? TFields : never;
159
+ 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";
160
+ type Upper = Uppercase<Lower>;
161
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
162
+ /** The same word boundaries as `authSqlName()`, for lookup in a migration snapshot. */
163
+ 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;
164
+ type ExistingColumns<TExisting, TModel extends string> = [TExisting] extends [Record<SqlName<TModel>, {
165
+ columns: infer TColumns;
166
+ }>] ? TColumns : never;
167
+ /** The Better Auth tables for SQLite, with fields from `TOptions` and constraints from a literal migration snapshot. */
168
+ 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>>; };
169
+ /** The Better Auth tables for Postgres, with the plugin tables and the plugin and additional columns of `TOptions`. */
170
+ 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
171
  export declare const authSqliteSchema: AuthSqliteSchema;
125
172
  export declare const authPostgresSchema: AuthPostgresSchema;
126
173
  /**
@@ -128,10 +175,11 @@ export declare const authPostgresSchema: AuthPostgresSchema;
128
175
  * Auth Vite plugin writes a module that calls it when the Auth Definition adds fields or imports a plugin of
129
176
  * `AuthSchemaPlugin`, or when the Database has some of the tables already. `existing` holds those tables, read from the
130
177
  * 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.
178
+ * change, so the migration adds columns and indexes, and does not drop a table that other tables reference. The
179
+ * columns of the plugins and additional fields are typed from the literal of `options`, with constraints from the
180
+ * snapshot literal when present.
132
181
  */
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>>;
136
- //#endregion
137
- export { type AuthCoreModel, type AuthCoreTableSpecs, type AuthSchemaOptions, type AuthSchemaPlugin, type AuthTableField, type AuthTableName, type AuthTableSpec, authPluginSchemas, authTableSpecs, resolveAuthTableSpecs };
182
+ export declare function createAuthSqliteSchema<const TOptions extends AuthSchemaOptions, const TExisting extends AuthExistingTables | undefined = AuthExistingTables | undefined>(options: TOptions, existing?: TExisting): AuthSqliteSchemaFor<TOptions, TExisting>;
183
+ /** The Better Auth tables for Postgres, with the plugins and additional fields of `options`, typed from its literal. */
184
+ export declare function createAuthPostgresSchema<const TOptions extends AuthSchemaOptions>(options: TOptions): AuthPostgresSchemaFor<TOptions>;
185
+ 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,8 +1,8 @@
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-jw0jjU6l.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";
5
- //#region src/schema.ts
5
+ // src/schema.ts
6
6
  const sameColumns = (left, right) => left.length === right.length && left.every((column, index) => column === right[index]);
7
7
  const foreignKeyAction = (action) => action.toLowerCase();
8
8
  function buildTables(dialect, specs, existing) {
@@ -134,14 +134,15 @@ 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
  }
146
- //#endregion
147
148
  export { authPluginSchemas, authPostgresSchema, authSqliteSchema, authTableSpecs, createAuthPostgresSchema, createAuthSqliteSchema, resolveAuthTableSpecs };
@@ -1,16 +1,13 @@
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 { t as AuthConsole } from "./console-runtime-BP1ZKJB0.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-BHSgxyvV.js";
3
+ import { i as AbilityName, n as AbilityAuthorization, t as AbilityArgs } from "./abilities-3L1Y5Pnw.js";
4
+ import "./server-DCsgxFPP.js";
5
+ import "./ability-error-C1c30O6E.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";
9
- //#region src/members.d.ts
10
9
  /** Why `checkAuthMember()` did not let a user in. */
11
10
  type AuthMemberErrorCode = "AUTH_NOT_MEMBER" | "AUTH_GITHUB_UNAVAILABLE";
12
- //#endregion
13
- //#region src/caller.d.ts
14
11
  /** The Auth user of a caller, with the fields of the app's plugins, such as `role` of `admin()`. */
15
12
  type AuthCallerUser = User & Record<string, unknown>;
16
13
  /**
@@ -34,8 +31,7 @@ type AuthCaller<TRegistry = ViteHub.AuthRegistry> = {
34
31
  scopes: string[];
35
32
  };
36
33
  type AuthCallerErrorCode = "AUTH_MCP_TOKEN_INVALID" | "AUTH_SIGNED_OUT";
37
- //#endregion
38
- //#region src/auth-instance.d.ts
34
+ declare function findVerifiedAuthUserId(email: string, request: Request): Promise<string | undefined>;
39
35
  declare function createBetterAuthOptions(definition: AuthDefinition): AuthBetterAuthRuntimeOptions;
40
36
  declare function getAuthForDefinition<TDefinition extends AuthDefinition>(definition: TDefinition): AuthFor<TDefinition>;
41
37
  /**
@@ -43,8 +39,6 @@ declare function getAuthForDefinition<TDefinition extends AuthDefinition>(defini
43
39
  * `useAuth(event)`. The Console reads it through `@vite-hub/auth/runtime/console`.
44
40
  */
45
41
  declare function authForRequest(request: Pick<Request, "headers" | "url">, event?: ViteHubContext, definition?: AuthDefinition): RegisteredAuth;
46
- //#endregion
47
- //#region src/internal/server.d.ts
48
42
  /** Where Better Auth returns after one sign-in that a guard starts. */
49
43
  type AuthSignInURLs = Pick<AuthProviderSignIn, "callbackURL" | "errorCallbackURL">;
50
44
  /** A provider sign-in with the page that Better Auth returns to. */
@@ -200,5 +194,4 @@ declare function aggregateAuthEvents(window: AuthEventWindow, definition?: AuthD
200
194
  * `host.impersonation` lets the Console start impersonation. It is off by default.
201
195
  */
202
196
  declare function getAuthConsoleForRequest(request: Request, event?: ViteHubContext, host?: AuthConsoleHostOptions): AuthConsole;
203
- //#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 };
197
+ 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 };