@vite-hub/auth 0.8.0 → 0.9.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 (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{abilities-IOwpkcz4.d.ts → abilities-6LE7VSdN.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-DgR91Jwc.js → ability-error-Ccm5Iy4F.js} +1 -1
  5. package/dist/{access-pages-C69nwa99.js → access-pages-lQGfRvfL.js} +1 -4
  6. package/dist/{admin-claim-code-C3X_U43x.js → admin-claim-code-CMa0eRRm.js} +0 -1
  7. package/dist/agent.js +3 -3
  8. package/dist/{application-path-zKi7NrvK.js → application-path-LMc_ptL9.js} +0 -2
  9. package/dist/{auth-instance-WeEK1zDd.js → auth-instance-0PTsOttV.js} +10 -48
  10. package/dist/bun-sqlite.d.ts +0 -2
  11. package/dist/cli.js +2 -2
  12. package/dist/{client-extension-BgUlm6hy.d.ts → client-extension-BVBVUqa1.d.ts} +1 -1
  13. package/dist/{console-runtime-Dk3j4Jmz.js → console-runtime-BlOx9hWC.js} +3 -19
  14. package/dist/{console-runtime-C71weVrt.d.ts → console-runtime-D2FUATXQ.d.ts} +1 -1
  15. package/dist/console-runtime.d.ts +2 -2
  16. package/dist/console-runtime.js +1 -1
  17. package/dist/console.d.ts +1 -1
  18. package/dist/{database-options-Cms7BI3c.js → database-options-CPhnGap9.js} +1 -1
  19. package/dist/{database-schema-options-IlHEeUBK.js → database-schema-options-BQyynyhw.js} +1 -1
  20. package/dist/database.d.ts +1 -1
  21. package/dist/database.js +15 -9
  22. package/dist/{definition-EpeI5LUG.js → definition-CvmvHaQT.js} +4 -12
  23. package/dist/{error-diagnostics-DZHuHXPP.js → error-diagnostics-BpQy1iIO.js} +2 -3
  24. package/dist/{events-Cm7Iwq47.js → events-aP_Rz_gx.js} +1 -1
  25. package/dist/{extension-mCx4TrsO.js → extension-B35v_o1u.js} +1 -1
  26. package/dist/{extension-BWmjJhoN.d.ts → extension-C2giF7w2.d.ts} +1 -1
  27. package/dist/forward.d.ts +0 -5
  28. package/dist/forward.js +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +3 -3
  31. package/dist/internal/server.d.ts +2 -2
  32. package/dist/internal/server.js +4 -4
  33. package/dist/{mcp-config-Bbr8kQxm.js → mcp-config-DYlTXmr6.js} +1 -1
  34. package/dist/{mcp-token-BleQZK6H.js → mcp-token-i-8NMulH.js} +3 -4
  35. package/dist/mcp.d.ts +0 -5
  36. package/dist/mcp.js +2 -4
  37. package/dist/{members-7OMdqha_.js → members-USm08YwK.js} +4 -6
  38. package/dist/nuxt.d.ts +1 -1
  39. package/dist/nuxt.js +3 -55
  40. package/dist/{own-access-CGiai2L3.d.ts → own-access-B7VRd92K.d.ts} +1 -1
  41. package/dist/presets.js +1 -1
  42. package/dist/{request-Dpq7GO8B.js → request-CdlcvqVc.js} +0 -1
  43. package/dist/runtime/console.d.ts +1 -1
  44. package/dist/runtime/console.js +2 -2
  45. package/dist/runtime/empty-abilities.d.ts +1 -1
  46. package/dist/runtime/empty-client.d.ts +1 -1
  47. package/dist/runtime/empty-definition.d.ts +1 -1
  48. package/dist/runtime/server.d.ts +3 -3
  49. package/dist/runtime/server.js +4 -4
  50. package/dist/runtime/vue-nuxt.js +2 -18
  51. package/dist/schema.d.ts +1 -4
  52. package/dist/schema.js +19 -3
  53. package/dist/{server-DyP1v-sZ.d.ts → server-4_EXgXFn.d.ts} +4 -6
  54. package/dist/{server-5t-HA7I1.js → server-CZR2dVVp.js} +13 -47
  55. package/dist/{server-mmp8EfcE.d.ts → server-DAIBBKbR.d.ts} +3 -3
  56. package/dist/server.d.ts +1 -1
  57. package/dist/server.js +3 -3
  58. package/dist/{session-cookies-BNtY3hMp.js → session-cookies-CfXdF1yd.js} +3 -19
  59. package/dist/{set-cookie-Bva-P-_C.js → set-cookie-BYZslovs.js} +1 -1
  60. package/dist/{table-specs-Bm7QJCbu.js → table-specs-Cvjc_Ccs.js} +28 -2
  61. package/dist/{table-specs-BxKeFD_y.d.ts → table-specs-VYAy_jJ7.d.ts} +0 -2
  62. package/dist/test.d.ts +1 -1
  63. package/dist/test.js +2 -2
  64. package/dist/{types-CnO5bHEF.d.ts → types-DakualFJ.d.ts} +1 -3
  65. package/dist/{vite-7I1bJvqA.js → vite-DVvWaN3D.js} +21 -71
  66. package/dist/vite.d.ts +3 -5
  67. package/dist/vite.js +1 -1
  68. package/dist/vue.d.ts +3 -34
  69. package/dist/vue.js +4 -65
  70. package/package.json +9 -8
package/README.md CHANGED
@@ -81,7 +81,7 @@ pnpm vitehub database migrate
81
81
 
82
82
  `authDatabase()` turns the Database on in `vitehub()`, as Connections does, so the app does not set `database`. `database: false` with `authDatabase()` fails the build with `AUTH_DATABASE_DISABLED`. `@vite-hub/database` stores the tables, and Drizzle Kit writes their migration. On Cloudflare, give the Database a D1 id with a Definition such as `server/databases/default.ts` = `defineDatabase({ cloudflare: { databaseId, databaseName }, schema: {} })`, or run `vitehub provision run --host cloudflare`.
83
83
 
84
- `authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields when the Definition calls `admin()`, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
84
+ `authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields when the Definition calls `admin()`, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). It also contributes their Drizzle relations, `authSqliteRelations` and `authPostgresRelations`, so `db.query` and Better Auth `advanced.database.joins` work on the tables. Each table has a relation to each table that it references and the reverse relation, with the names that Better Auth reads, such as `session.user` and `user.sessions`. With `advanced.database.joins`, the adapter fails with `AUTH_C0056` when the Database lacks one of these relations, for example because an additional field has its name. On SQLite, the JSON and array columns also read the values that the classic Better Auth Drizzle adapter wrote as JSON text. `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
85
85
 
86
86
  The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path or the `#layers/<name>/` alias of a Nuxt layer, imports and calls them. A project plugin in the Definition or an extension adds its literal `schema` fields on `user`, `session`, `account`, and `verification`. A project plugin that adds a field to another plugin’s table still needs that field in the Database schema. A project plugin that the build cannot read fails with `AUTH_PLUGIN_SCHEMA_UNREADABLE`. An app Definition that replaces a Nuxt layer Definition must keep its tables and columns, or the build fails with `AUTH_LAYER_DEFINITION_REPLACED`. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
87
87
 
@@ -1,4 +1,4 @@
1
- import { H as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-CnO5bHEF.js";
1
+ import { H as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-DakualFJ.js";
2
2
  /** A 4xx status that a rule can refuse with. `403` is the default. */
3
3
  type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
4
4
  declare const abilityDenial: unique symbol;
@@ -1,2 +1,2 @@
1
- import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-IOwpkcz4.js";
1
+ import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-6LE7VSdN.js";
2
2
  export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  import { HTTPError } from "nitro/h3";
3
3
  // src/ability-check.ts
4
4
  const signedOut = Object.freeze({
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  import { n as isAuthRole } from "./roles-BGi8CyBG.js";
3
3
  // src/shared.ts
4
4
  const defaultAuthBasePath = "/api/auth";
@@ -30,7 +30,6 @@ function normalizePagePath(path, sensitive = false) {
30
30
  return lower.length === 1 && lower.toUpperCase() === upper ? lower : upper;
31
31
  });
32
32
  }
33
- /** Nuxt keeps a path that `decodeURI()` rejects as it is. */
34
33
  function decodePath(path) {
35
34
  try {
36
35
  return decodeURI(path);
@@ -38,7 +37,6 @@ function decodePath(path) {
38
37
  return path;
39
38
  }
40
39
  }
41
- /** Nuxt orders matches by their segments from the left: a static segment, then `:name` or `*`, then `**`. */
42
40
  function segmentRank(segment) {
43
41
  if (segment === void 0) return 3;
44
42
  if (segment.startsWith("**")) return 0;
@@ -70,7 +68,6 @@ async function createAccessPageMatcher(pages, sensitive = false) {
70
68
  return matches.at(-1);
71
69
  };
72
70
  }
73
- /** A static segment or `:name`. */
74
71
  const pageSegment = /^(?:[^:*?+(){}/]+|:[A-Za-z_]\w*)$/;
75
72
  /**
76
73
  * Checks `access.pages`. The Nuxt module attaches the page guard to each pattern with an `appMiddleware` route rule,
@@ -1,7 +1,6 @@
1
1
  // src/admin-claim-code.ts
2
2
  /** The variable with the SHA-256 of a one-time claim code, written by `vitehub auth claim`. */
3
3
  const adminClaimVariable = "VITEHUB_ADMIN_CLAIM";
4
- /** Crockford Base32 without I, L, O, and U, so a person can read the code aloud without mistakes. */
5
4
  const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
6
5
  /** A random code of 16 characters (80 bits), in groups of four. */
7
6
  function createAdminClaimCode() {
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-Bva-P-_C.js";
2
- import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-BNtY3hMp.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-BYZslovs.js";
2
+ import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-CfXdF1yd.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
5
  import { ViteHubError } from "@vite-hub/runtime";
6
6
  // src/agent.ts
@@ -20,9 +20,7 @@ function resolveAuthMountPath(path, appBaseURL) {
20
20
  function authApplicationBaseURL() {
21
21
  return typeof __VITEHUB_AUTH_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_AUTH_APP_BASE_URL__;
22
22
  }
23
- /** Characters that H3 percent-encodes in a route, as its `normalizeRoute()` does. */
24
23
  const routeEncodeRE = /[^!-~]|["#<>^`]/gu;
25
- /** Escapes of characters that need no escape in a path. H3 decodes them before it routes a request. */
26
24
  const needlessEscapeRE = /%(?:2[146-9A-E]|3[0-9ABD]|4[0-9A-F]|5[0-9ABDF]|6[1-9A-F]|7[0-9ACE])/gi;
27
25
  /**
28
26
  * The path as the Nitro router reads it, so that two spellings of one path give the same string. H3 decodes needless
@@ -1,17 +1,17 @@
1
1
  import { t as clientRequest } from "./client-request-B1DCz3a9.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
- import { i as resolveAuthMountPath } from "./application-path-zKi7NrvK.js";
4
- import { a as readMembers, c as createAdminClaimPlugin, f as createAdminsPlugin, h as createAccessPolicyPlugin, l as readAdminClaim, n as createMembersGate, o as withMemberScopes, p as readAdmins, t as assertMembersSessionStore } from "./members-7OMdqha_.js";
5
- import { i as authDatabaseName, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-Cms7BI3c.js";
6
- import { t as assertAuthDatabaseNames } from "./database-schema-options-IlHEeUBK.js";
7
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
8
- import { a as validateAuthComponents, c as validateAuthEvents, i as validateAuthAccessRouteRoles, l as applyAuthPreset, o as createDeleteAccount, r as validateAuthAccessPolicy, s as validateDeleteAccount, t as assertNoRuntimeOption } from "./definition-EpeI5LUG.js";
9
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-Cm7Iwq47.js";
3
+ import { i as resolveAuthMountPath } from "./application-path-LMc_ptL9.js";
4
+ import { a as readMembers, c as createAdminClaimPlugin, f as createAdminsPlugin, h as createAccessPolicyPlugin, l as readAdminClaim, n as createMembersGate, o as withMemberScopes, p as readAdmins, t as assertMembersSessionStore } from "./members-USm08YwK.js";
5
+ import { i as authDatabaseName, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-CPhnGap9.js";
6
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-BQyynyhw.js";
7
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
8
+ import { a as validateAuthComponents, c as validateAuthEvents, i as validateAuthAccessRouteRoles, l as applyAuthPreset, o as createDeleteAccount, r as validateAuthAccessPolicy, s as validateDeleteAccount, t as assertNoRuntimeOption } from "./definition-CvmvHaQT.js";
9
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-aP_Rz_gx.js";
10
10
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
11
- import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
11
+ import { n as authRequestEvent, t as authCloudflareEnv } from "./request-CdlcvqVc.js";
12
12
  import { n as resetAuth, t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
13
- import { o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
14
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-Bva-P-_C.js";
13
+ import { o as normalizeAuthBasePath } from "./access-pages-lQGfRvfL.js";
14
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-BYZslovs.js";
15
15
  import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-dVJBPPTk.js";
16
16
  import { resolvePublicUrl } from "@vite-hub/runtime";
17
17
  import { isRequest } from "@vite-hub/runtime/internal/response";
@@ -656,11 +656,6 @@ function createAuthEventsPlugin(options) {
656
656
  };
657
657
  }
658
658
  // src/impersonation-plugin.ts
659
- /**
660
- * Better Auth endpoints that create a credential which outlives an impersonation session, change how the user signs
661
- * in, or start another impersonation: OAuth, MCP, and device grants, API keys, passkeys, passwords, email and phone
662
- * number changes, linked accounts, two-factor setup, and one-time tokens that open a new session.
663
- */
664
659
  const credentialPaths = /* @__PURE__ */ new Set([
665
660
  "/account-info",
666
661
  "/admin/impersonate-user",
@@ -682,21 +677,18 @@ const credentialPaths = /* @__PURE__ */ new Set([
682
677
  "/two-factor/generate-backup-codes",
683
678
  "/unlink-account"
684
679
  ]);
685
- /** `/update-user` fields that change how the user signs in. The username plugin sets `username` from `displayUsername`. */
686
680
  const identityFields = ["displayUsername", "username"];
687
681
  const credentialPrefixes = [
688
682
  "/device/",
689
683
  "/mcp/",
690
684
  "/oauth2/"
691
685
  ];
692
- /** Reads below those prefixes. They show the user's grants and clients, so a support view still works. */
693
686
  const grantReads = /^\/oauth2\/(?:get-|public-client|userinfo)|^\/mcp\/get-session$/;
694
687
  function createsCredential(path, body) {
695
688
  if (!path) return false;
696
689
  if (path === "/update-user") return typeof body === "object" && body !== null && identityFields.some((field) => field in body);
697
690
  return credentialPaths.has(path) || credentialPrefixes.some((prefix) => path.startsWith(prefix)) && !grantReads.test(path);
698
691
  }
699
- /** The current expiry of the request's impersonation session, when the update would move it later. */
700
692
  function keptExpiry(...[data, endpoint]) {
701
693
  const current = endpoint?.context.session?.session;
702
694
  if (!current?.impersonatedBy || !data.expiresAt) return;
@@ -763,7 +755,6 @@ function createImpersonationPlugin() {
763
755
  * Better Auth instances that it creates: `handler` and each `api` endpoint.
764
756
  */
765
757
  const clientAddressHeader = "x-vitehub-client-address";
766
- /** The addresses that `handleAuthRequest()` read from the request event, for the Request that it passes to Better Auth. */
767
758
  const eventAddresses = /* @__PURE__ */ new WeakMap();
768
759
  function readStringAtPath(value, path) {
769
760
  let current = value;
@@ -790,7 +781,6 @@ function setRequestClientAddress(request, address) {
790
781
  if (address) eventAddresses.set(request, address);
791
782
  return request;
792
783
  }
793
- /** Return the request with only the host address in {@link clientAddressHeader}. srvx adds that address as `ip`. */
794
784
  function addressedRequest(request) {
795
785
  const address = eventAddresses.get(request) ?? readStringAtPath(request, ["ip"]);
796
786
  if (request.headers.get("x-vitehub-client-address") === (address ?? null)) return request;
@@ -809,7 +799,6 @@ function addressedRequest(request) {
809
799
  }
810
800
  return new Request(request.url, init);
811
801
  }
812
- /** Headers of an `api` call have no host address, so remove a value that the caller copied from client headers. */
813
802
  function withoutClientAddress(input) {
814
803
  if (!input || typeof input !== "object") return input;
815
804
  let result = input;
@@ -956,7 +945,6 @@ function isPlainData(value) {
956
945
  const prototype = Object.getPrototypeOf(value);
957
946
  return Array.isArray(value) ? prototype === Array.prototype : prototype === Object.prototype || prototype === null;
958
947
  }
959
- /** Write the key of `value` to `parts`. Returns false for a value that gives no key. */
960
948
  function writeKey(value, parts, parents) {
961
949
  if (typeof value === "symbol") return false;
962
950
  if (typeof value === "string") {
@@ -993,18 +981,12 @@ function optionsKey(value) {
993
981
  return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
994
982
  }
995
983
  // src/runtime-options.ts
996
- /** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
997
984
  function isAuthDatabasePlacement(value) {
998
985
  return typeof value === "boolean" || isRecord(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key === "dedicated" || key === "name");
999
986
  }
1000
- /** `true` or `{ store }`: the removed placement form, which is not a Better Auth adapter. */
1001
987
  function isAuthSecondaryStoragePlacement(value) {
1002
988
  return typeof value === "boolean" || isRecord(value) && Object.hasOwn(value, "store") && Object.keys(value).every((key) => key === "store");
1003
989
  }
1004
- /**
1005
- * Without a database, Better Auth keeps users and sessions in the memory of one instance. Auth creates an instance for
1006
- * each set of resolved options, so the instances of one Auth Definition share these tables. A restart still removes them.
1007
- */
1008
990
  function sharedMemoryDatabase(definition) {
1009
991
  const state = getAuthRuntimeState();
1010
992
  const databases = getViteHubTestMode()?.backend("auth", () => /* @__PURE__ */ new WeakMap(), resetAuth) ?? (state.memoryDatabases ??= /* @__PURE__ */ new WeakMap());
@@ -1025,12 +1007,6 @@ function isDevelopmentServer() {
1025
1007
  const mode = globalThis.process?.env?.NODE_ENV;
1026
1008
  return mode === "development" || mode === "test";
1027
1009
  }
1028
- /**
1029
- * Better Auth turns its limiter on only when `NODE_ENV` is `production`, and keeps its counters in the memory of the
1030
- * process unless a `secondaryStorage` is set. Auth turns it on outside a development server, and keeps the counters in
1031
- * the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them. It counts
1032
- * only requests to the endpoints of the instance.
1033
- */
1034
1010
  function withRateLimitDefaults(options, ownsDatabase) {
1035
1011
  const rateLimit = options.rateLimit;
1036
1012
  const database = ownsDatabase && !rateLimit?.storage && !rateLimit?.customStorage && !options.secondaryStorage;
@@ -1041,13 +1017,6 @@ function withRateLimitDefaults(options, ownsDatabase) {
1041
1017
  ...database ? { storage: "database" } : {}
1042
1018
  };
1043
1019
  }
1044
- /**
1045
- * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
1046
- * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
1047
- * `vitehub({ trustProxy: true })` makes that address the last `X-Forwarded-For` value, which the proxy adds.
1048
- * Better Auth also turns off its Origin and CSRF checks when `TEST` or `NODE_ENV=test` is set, such as in a server that
1049
- * a Vitest run starts. Auth serves real requests, so only `advanced.disableOriginCheck` turns them off.
1050
- */
1051
1020
  function withAdvancedDefaults(advanced) {
1052
1021
  const disableOriginCheck = advanced?.disableOriginCheck ?? false;
1053
1022
  if (advanced?.ipAddress?.ipAddressHeaders) return {
@@ -1063,10 +1032,6 @@ function withAdvancedDefaults(advanced) {
1063
1032
  }
1064
1033
  };
1065
1034
  }
1066
- /**
1067
- * The environment values that an instance for these options uses. Auth reads a value only when the options use it, so
1068
- * the instance key and the instance read the same values, and a value that the options replace cannot fail a request.
1069
- */
1070
1035
  function readProviderEnvironment(options, event) {
1071
1036
  const bindings = authCloudflareEnv(event);
1072
1037
  return {
@@ -1161,7 +1126,6 @@ function stripViteHubOptions(definition, options, environment) {
1161
1126
  basePath: resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0))
1162
1127
  };
1163
1128
  }
1164
- /** Moves `session.onRefresh` into a Better Auth plugin, because Better Auth does not read it. */
1165
1129
  function withSessionRefresh(options, hasSessionStore) {
1166
1130
  const session = options.session;
1167
1131
  if (!session?.onRefresh) return {};
@@ -1252,7 +1216,6 @@ function resolveAuthOptions(definition, input = {}) {
1252
1216
  const environment = resolveEnvironment();
1253
1217
  return withResolvedSecrets(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1254
1218
  },
1255
- /** Equal for two resolutions of this Definition that give Better Auth equal options, else `undefined`. */
1256
1219
  get providerKey() {
1257
1220
  const snapshot = resolveSnapshot();
1258
1221
  const database = authDatabaseName(snapshot.database);
@@ -1289,7 +1252,6 @@ function requestSource(input) {
1289
1252
  const headers = new Headers(input?.headers);
1290
1253
  return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
1291
1254
  }
1292
- /** The value of one cookie in the request of an API call or a handler request. */
1293
1255
  function requestCookie(input, name) {
1294
1256
  const headers = isRequest(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1295
1257
  for (const part of headers?.get("cookie")?.split(";") ?? []) {
@@ -1,5 +1,3 @@
1
- // Better Auth's option types import `Database` from "bun:sqlite". This keeps that type without installing bun-types.
2
- // An app that installs bun-types merges its `Database` class with this interface.
3
1
  declare module "bun:sqlite" {
4
2
  export interface Database {
5
3
  readonly filename: string
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
- import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
2
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-CMa0eRRm.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
3
3
  // src/cli.ts
4
4
  const usage = "vitehub auth events --url <auth-base-url> [--type <type>] [--user <id>] [--actor <actor>] [--from <ISO>] [--to <ISO>] [--cursor <cursor>] [--limit <1-200>] [--aggregate]";
5
5
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
@@ -1,4 +1,4 @@
1
- import { i as OnlyKeys } from "./extension-BWmjJhoN.js";
1
+ import { i as OnlyKeys } from "./extension-C2giF7w2.js";
2
2
  import { BetterAuthClientOptions } from "better-auth";
3
3
  /** What a part of the Auth client options can add. Every other option stays in `defineAuthClient()`. */
4
4
  interface AuthClientExtensionOptions {
@@ -1,7 +1,7 @@
1
- import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-7OMdqha_.js";
2
- import { n as adminClaimVariable } from "./admin-claim-code-C3X_U43x.js";
1
+ import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-USm08YwK.js";
2
+ import { n as adminClaimVariable } from "./admin-claim-code-CMa0eRRm.js";
3
3
  import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
4
- import { r as parseAuthEventList } from "./events-Cm7Iwq47.js";
4
+ import { r as parseAuthEventList } from "./events-aP_Rz_gx.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
6
6
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
7
7
  // ../internal/src/runtime/user-agent.ts
@@ -27,7 +27,6 @@ const userSummary = (user) => ({
27
27
  email: string(user.email),
28
28
  image: typeof user.image === "string" ? user.image : null
29
29
  });
30
- /** Computed readers get public core user fields, never sessions, accounts, or credentials. */
31
30
  const publicUser = (row) => ({
32
31
  ...userSummary(row),
33
32
  emailVerified: row.emailVerified === true,
@@ -48,7 +47,6 @@ const equality = (field, value) => [{
48
47
  value
49
48
  }];
50
49
  const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
51
- /** The admin plugin options, with roles and user ids read as Better Auth reads them. */
52
50
  function adminPlugin(options) {
53
51
  const plugin = options.plugins?.find((plugin) => plugin.id === "admin");
54
52
  const settings = record(plugin?.options);
@@ -59,7 +57,6 @@ function adminPlugin(options) {
59
57
  userIds: strings(settings.adminUserIds)
60
58
  };
61
59
  }
62
- /** Better Auth's admin check: one of the comma-separated roles is an admin role, or the id is an admin user id. */
63
60
  const isAdmin = (admin, id, role) => (role || string(admin.settings.defaultRole) || "user").split(",").some((name) => admin.roles.includes(name)) || admin.userIds.includes(id);
64
61
  const endpoints = {
65
62
  ban: "banUser",
@@ -106,10 +103,6 @@ const errors = defineErrors({
106
103
  }
107
104
  }
108
105
  });
109
- /**
110
- * The Result error of a refused Auth Console call. `detail` names the reason, and becomes the message of a client error.
111
- * A provider failure keeps the reason in `cause`, for the server log only.
112
- */
113
106
  function authConsoleError(status, detail) {
114
107
  const code = status === 400 ? "AUTH_CONSOLE_INVALID_REQUEST" : status === 401 || status === 403 ? "AUTH_CONSOLE_FORBIDDEN" : status === 404 ? "AUTH_CONSOLE_NOT_FOUND" : status === 409 ? "AUTH_CONSOLE_UNAVAILABLE" : void 0;
115
108
  return code ? errors[code]({ detail }) : errors.AUTH_CONSOLE_PROVIDER_FAILED({ cause: detail });
@@ -182,12 +175,6 @@ function describeAuthConsoleFields(options, policy = {}) {
182
175
  }
183
176
  return fields;
184
177
  }
185
- /**
186
- * Read and manage the app's Better Auth data from trusted server code. HTTP hosts must check access before calling it.
187
- * Writes require a real Better Auth session and pass through its plugin APIs. No adapter writes are used here.
188
- * Impersonation stays off unless `host.impersonation` is `true`.
189
- */
190
- /** The `VITEHUB_ADMINS` rule as an access note, so the Console shows why an account is an admin. */
191
178
  function adminsAccess(plugins) {
192
179
  const options = plugins?.find((plugin) => plugin.id === adminsPluginId)?.options;
193
180
  if (!options || typeof options !== "object") return [];
@@ -198,7 +185,6 @@ function adminsAccess(plugins) {
198
185
  const listed = [...admins.filter((entry) => typeof entry === "string" && !entry.includes("@")), ...emails ? [`${emails} verified ${emails === 1 ? "email" : "emails"}`] : []];
199
186
  return [`${adminsVariable} gives the ${role} role to ${listed.join(", ")} on sign-in.`];
200
187
  }
201
- /** The `VITEHUB_MEMBERS` rule as an access note, so the Console shows who may sign in. */
202
188
  function membersAccess(plugins) {
203
189
  const options = plugins?.find((plugin) => plugin.id === accessPolicyPluginId)?.options;
204
190
  const members = options && typeof options === "object" ? Reflect.get(options, "members") : void 0;
@@ -207,7 +193,6 @@ function membersAccess(plugins) {
207
193
  const listed = [...emails ? [`${emails} ${emails === 1 ? "email" : "emails"}`] : [], ...members.filter((entry) => typeof entry === "string" && !/^[^@]+@/.test(entry))];
208
194
  return [`${membersVariable} lets only ${listed.join(", ")}, and the admins, sign up and sign in.`];
209
195
  }
210
- /** The `VITEHUB_ADMIN_CLAIM` rule as an access note. */
211
196
  function adminClaimAccess(plugins) {
212
197
  const options = plugins?.find((plugin) => plugin.id === adminClaimPluginId)?.options;
213
198
  const role = options && typeof options === "object" ? Reflect.get(options, "role") : void 0;
@@ -988,7 +973,6 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
988
973
  session: (request) => result(() => sessionUser(request))
989
974
  };
990
975
  }
991
- /** The value of Better Auth's session cookie for a token: the token and its HMAC-SHA256 signature. */
992
976
  async function signedSessionToken(secret, token) {
993
977
  const encoder = new TextEncoder();
994
978
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
@@ -1,4 +1,4 @@
1
- import { J as AuthConsoleActivityQuery, Q as AuthConsoleDescription, Rt as AuthEventStore, Y as AuthConsoleAgent, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, ft as AuthConsoleOverview, ht as AuthConsoleQuery, lt as AuthConsoleOptions, nt as AuthConsoleField, q as AuthConsoleActivity, st as AuthConsoleList, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
1
+ import { J as AuthConsoleActivityQuery, Q as AuthConsoleDescription, Rt as AuthEventStore, Y as AuthConsoleAgent, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, ft as AuthConsoleOverview, ht as AuthConsoleQuery, lt as AuthConsoleOptions, nt as AuthConsoleField, q as AuthConsoleActivity, st as AuthConsoleList, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, yt as AuthConsoleUser } from "./types-DakualFJ.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
4
4
  interface AuthConsole {
@@ -1,3 +1,3 @@
1
- import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
2
- import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-C71weVrt.js";
1
+ import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-DakualFJ.js";
2
+ import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-D2FUATXQ.js";
3
3
  export { AuthConsole, type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, AuthConsoleErrorCode, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type AuthConsoleImpersonation, type AuthConsoleList, type AuthConsoleMutation, type AuthConsoleOptions, type AuthConsoleOrganization, type AuthConsoleOrganizationDetail, type AuthConsoleOverview, type AuthConsolePage, type AuthConsolePolicy, type AuthConsoleQuery, type AuthConsoleRoles, type AuthConsoleSession, type AuthConsoleSessionUser, type AuthConsoleUser, type AuthConsoleUserDetail, type AuthConsoleValue, type authConsoleActionNames, type authConsoleEventGroups, createAuthConsole, describeAuthConsoleFields };
@@ -1 +1 @@
1
- export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-Dk3j4Jmz.js";
1
+ export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-BlOx9hWC.js";
package/dist/console.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
1
+ import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-DakualFJ.js";
2
2
  /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
3
3
  interface ViteHubConsoleDefinitionCatalogView {
4
4
  kind: "definition-catalog";
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  // src/database-options.ts
3
3
  /** Reads the adapter's target without loading Better Auth or the Database runtime. */
4
4
  function authDatabaseName(database) {
@@ -1,4 +1,4 @@
1
- import { o as authDatabaseSchemaError } from "./database-options-Cms7BI3c.js";
1
+ import { o as authDatabaseSchemaError } from "./database-options-CPhnGap9.js";
2
2
  import { getAuthTables } from "better-auth/db";
3
3
  // src/database-schema-options.ts
4
4
  /** Better Auth reads each table by its key and each column by its field key, so the options must not rename them. */
@@ -1,4 +1,4 @@
1
- import { f as AuthAppDatabase } from "./types-CnO5bHEF.js";
1
+ import { f as AuthAppDatabase } from "./types-DakualFJ.js";
2
2
  /**
3
3
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
4
4
  * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
package/dist/database.js CHANGED
@@ -1,17 +1,13 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
2
- import { o as authDatabaseSchemaError, r as authDatabaseIdColumnError, t as assertAuthDatabaseIdStrategy } from "./database-options-Cms7BI3c.js";
3
- import { t as assertAuthDatabaseNames } from "./database-schema-options-IlHEeUBK.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
+ import { o as authDatabaseSchemaError, r as authDatabaseIdColumnError, t as assertAuthDatabaseIdStrategy } from "./database-options-CPhnGap9.js";
3
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-BQyynyhw.js";
4
+ import { t as authJoinRelations } from "./table-specs-Cvjc_Ccs.js";
4
5
  import { getAuthTables } from "better-auth/db";
5
6
  import { getTableColumns, is, isTable } from "drizzle-orm";
6
- import { drizzleAdapter } from "better-auth/adapters/drizzle";
7
+ import { drizzleAdapter } from "@better-auth/drizzle-adapter/relations-v2";
7
8
  import { databases } from "@vite-hub/database/runtime/registry";
8
9
  import { PgAsyncDatabase } from "drizzle-orm/pg-core";
9
10
  // src/database.ts
10
- /**
11
- * Compares the tables and fields that the options need, with the plugins and additional fields, against the Drizzle
12
- * tables of the Database. On Postgres, it compares the declared ID column type against the ID strategy. It does not
13
- * query the live database.
14
- */
15
11
  function assertAuthDatabaseSchema(options, schema, database, postgres) {
16
12
  const uuidIds = options.advanced?.database?.generateId === "uuid";
17
13
  const fix = "Import the plugin by name from its package, such as `import { admin } from \"better-auth/plugins\"`, and call it in `server/auth.ts` or in a file that it imports with a relative path. Auth does not read a default import of the plugin, or a namespace that a local file re-exports. Write `additionalFields` inline in `server/auth.ts`, so that the Auth Vite plugin adds the columns. Then run `vitehub database generate` and apply the migration";
@@ -24,6 +20,15 @@ function assertAuthDatabaseSchema(options, schema, database, postgres) {
24
20
  for (const key of Object.keys(table.fields)) if (!Object.hasOwn(columns, key)) throw authDatabaseSchemaError(`the \`${model}\` table of the ${JSON.stringify(database)} Database has no \`${key}\` column. ${fix}`);
25
21
  }
26
22
  }
23
+ function assertAuthDatabaseJoins(options, relations, schema, database) {
24
+ if (!options.advanced?.database?.joins) return;
25
+ for (const { model, key } of authJoinRelations(getAuthTables(options))) {
26
+ if (relations[model]?.relations[key]) continue;
27
+ const drizzleTable = schema[model];
28
+ const collides = isTable(drizzleTable) && Object.hasOwn(getTableColumns(drizzleTable), key);
29
+ throw authDatabaseSchemaError(collides ? `the \`${model}\` table of the ${JSON.stringify(database)} Database has a column named \`${key}\`, so it cannot have the \`${key}\` relation that \`advanced.database.joins\` reads. Rename the column, or turn off \`advanced.database.joins\`` : `the \`${model}\` table of the ${JSON.stringify(database)} Database has no \`${key}\` relation, which \`advanced.database.joins\` reads. Add it to the \`relations\` of the Database Definition, or turn off \`advanced.database.joins\``);
30
+ }
31
+ }
27
32
  /**
28
33
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
29
34
  * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
@@ -39,6 +44,7 @@ function authDatabase(name = "default") {
39
44
  if (!entry || !Object.hasOwn(entry.schema, "user")) throw authErrorDiagnostics.AUTH_R0019({ message: `[vitehub] \`authDatabase(${JSON.stringify(name)})\` found no Better Auth tables in the ${JSON.stringify(name)} Database. Pass \`authDatabase()\` inline as the \`database\` of \`defineAuth()\` so that Auth adds them, then run \`vitehub database generate\` and \`vitehub database migrate\`. \`vitehub inspect definitions --kind database\` lists the tables of each Database.` });
40
45
  const postgres = is(entry.db, PgAsyncDatabase);
41
46
  assertAuthDatabaseSchema(options, entry.schema, name, postgres);
47
+ assertAuthDatabaseJoins(options, entry.relations, entry.schema, name);
42
48
  return drizzleAdapter(entry.db, {
43
49
  provider: postgres ? "pg" : "sqlite",
44
50
  schema: entry.schema
@@ -1,9 +1,9 @@
1
- import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
1
+ import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-lQGfRvfL.js";
2
2
  import { n as isAuthRole } from "./roles-BGi8CyBG.js";
3
- import { t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
4
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
3
+ import { t as accessRouteSyntaxError } from "./application-path-LMc_ptL9.js";
4
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
5
5
  import { t as isRecord } from "./object-CAK6UYR5.js";
6
- import { i as authDatabaseName } from "./database-options-Cms7BI3c.js";
6
+ import { i as authDatabaseName } from "./database-options-CPhnGap9.js";
7
7
  import { parseDuration } from "@vite-hub/runtime";
8
8
  // src/stateless-user-id.ts
9
9
  const pendingUserIds = /* @__PURE__ */ new WeakMap();
@@ -17,7 +17,6 @@ async function statelessUserId(providerId, accountId) {
17
17
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input));
18
18
  return Array.from(digest.slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
19
19
  }
20
- /** The account ID that Better Auth stores for this provider profile, from the provider's own `accountSubject`. */
21
20
  async function accountSubject(context, providerId, profile) {
22
21
  const subject = await context.context.socialProviders.find((candidate) => candidate.id === providerId)?.accountSubject({
23
22
  profile,
@@ -126,7 +125,6 @@ function storedPluginId(plugin) {
126
125
  if (isRecord(plugin.schema) && Object.keys(plugin.schema).length > 0) return id;
127
126
  if (verificationPluginIds.has(id)) return id;
128
127
  }
129
- /** Checks that the options can run with `stateless()` and returns the Better Auth options it sets. */
130
128
  function applyStatelessPreset(preset, options) {
131
129
  if (options.database !== void 0) throw authErrorDiagnostics.AUTH_C0044({ message: "`stateless()` keeps sessions in cookies and cannot use `database`. Remove `database`, or remove the preset to store sessions in a database." });
132
130
  if (options.secondaryStorage !== void 0) throw authErrorDiagnostics.AUTH_C0045({ message: "`stateless()` keeps sessions in cookies and cannot use `secondaryStorage`. Remove `secondaryStorage`, or remove the preset to store sessions on the server." });
@@ -196,11 +194,6 @@ const betterAuthModels = /* @__PURE__ */ new Set([
196
194
  "session",
197
195
  "account"
198
196
  ]);
199
- /**
200
- * The rows of the Better Auth tables that name the user, such as passkeys, organization members, and MCP tokens. A
201
- * Database deletes them through `on delete cascade`, but an app schema can lack the foreign keys. The `apikey` table of
202
- * `apiKey()` names its owner in `referenceId`, without a foreign key.
203
- */
204
197
  async function deleteAuthRows(context, user, userApiKeyConfigIds) {
205
198
  const userModel = context.tables.user?.modelName ?? "user";
206
199
  let storedUser;
@@ -391,7 +384,6 @@ function validateAuthComponents(value) {
391
384
  const prefix = value.prefix;
392
385
  if (typeof prefix !== "undefined" && (typeof prefix !== "string" || !prefix.trim() || prefix !== prefix.trim())) throw authErrorDiagnostics.AUTH_COMPONENTS_INVALID();
393
386
  }
394
- /** A path of the app: one `/`, then no `/` or `\`, so it cannot name another site. */
395
387
  function isAppPath(value) {
396
388
  return typeof value === "string" && /^\/(?![/\\])/.test(value);
397
389
  }
@@ -1,7 +1,6 @@
1
1
  import { defineDiagnostics } from "nostics";
2
2
  // src/error-diagnostics.ts
3
3
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
- /** A code whose call site passes the message as `why`, with the fix that the reader applies. */
5
4
  const withFix = (fix) => ({
6
5
  ...dynamicError,
7
6
  fix
@@ -105,11 +104,11 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
105
104
  },
106
105
  AUTH_REDIRECTS_MOVED: {
107
106
  why: "`vitehub({ auth })` takes only `true` or `false`. The `redirects` option moved to the Auth Definition.",
108
- fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`. `vitehub migrate` moves them."
107
+ fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`."
109
108
  },
110
109
  AUTH_SIGN_IN_CALLBACK_URL_MOVED: {
111
110
  why: "`defineAuth()` access.signIn.callbackURL moved to `access.afterSignIn`.",
112
- fix: "Move the value to `access.afterSignIn`, for example `access: { signIn: { provider: 'github' }, afterSignIn: '/dashboard' }`. The page guard also sends signed-in users there from `auth: 'guest'` pages. `vitehub migrate` moves it."
111
+ fix: "Move the value to `access.afterSignIn`, for example `access: { signIn: { provider: 'github' }, afterSignIn: '/dashboard' }`. The page guard also sends signed-in users there from `auth: 'guest'` pages."
113
112
  },
114
113
  AUTH_TEST_SIGN_IN_STATELESS: {
115
114
  why: "`signIn()` writes the user and the session to the Auth database, and a Definition with the `stateless()` preset has none.",
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { defineErrors } from "@vite-hub/runtime";
4
4
  import { sql } from "drizzle-orm";
@@ -1,5 +1,5 @@
1
1
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
3
3
  // src/extension.ts
4
4
  /** The options of a part. The build scanner checks the same keys in the source. */
5
5
  const authExtensionKeys = /* @__PURE__ */ new Set(["plugins", "user"]);
@@ -1,4 +1,4 @@
1
- import { _ as AuthDefinition } from "./types-CnO5bHEF.js";
1
+ import { _ as AuthDefinition } from "./types-DakualFJ.js";
2
2
  import { BetterAuthOptions } from "better-auth";
3
3
  type UserAdditionalFields = NonNullable<NonNullable<BetterAuthOptions["user"]>["additionalFields"]>;
4
4
  /** What a part of the Auth Definition can add. Every other option stays in `defineAuth()`. */
package/dist/forward.d.ts CHANGED
@@ -1,9 +1,4 @@
1
1
  import { BetterAuthPlugin } from "better-auth";
2
- /**
3
- * Sign-in through a trusted reverse proxy, such as oauth2-proxy, Cloudflare Access, or Tailscale Serve. The proxy
4
- * sends the person's identity, or a credential for it, in a request header. Auth trusts the header only when `verify`
5
- * returns an identity, and then signs that identity in as a Better Auth account.
6
- */
7
2
  /** The person that `verify` found in the header. Auth links it to a user as a Better Auth account. */
8
3
  export interface ForwardedIdentity {
9
4
  /** The provider of the account, such as `github` or `cloudflare-access`. */
package/dist/forward.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
2
2
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
3
3
  import { createAuthMiddleware } from "better-auth/api";
4
4
  import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";