@vite-hub/auth 0.7.0 → 0.8.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 (72) hide show
  1. package/README.md +58 -5
  2. package/dist/{abilities-CfvuGrBv.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-OKoyOwPM.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-Bej95blM.js → access-pages-C69nwa99.js} +1 -1
  6. package/dist/agent.js +11 -11
  7. package/dist/{auth-instance-5RSiFTDC.js → auth-instance-WeEK1zDd.js} +39 -17
  8. package/dist/cli.js +1 -1
  9. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  10. package/dist/client-request-B1DCz3a9.js +29 -0
  11. package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  12. package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-Dk3j4Jmz.js} +2 -2
  13. package/dist/console-runtime.d.ts +2 -2
  14. package/dist/console-runtime.js +1 -1
  15. package/dist/console.d.ts +1 -1
  16. package/dist/{database-options-DE9lMwu1.js → database-options-Cms7BI3c.js} +12 -4
  17. package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-IlHEeUBK.js} +1 -1
  18. package/dist/database.d.ts +1 -1
  19. package/dist/database.js +12 -7
  20. package/dist/{definition-DeEeqTLC.js → definition-EpeI5LUG.js} +3 -3
  21. package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-DZHuHXPP.js} +33 -1
  22. package/dist/{events-BUaoHFoC.js → events-Cm7Iwq47.js} +1 -1
  23. package/dist/extension-BWmjJhoN.d.ts +59 -0
  24. package/dist/extension-mCx4TrsO.js +133 -0
  25. package/dist/forward.js +1 -1
  26. package/dist/index.d.ts +4 -3
  27. package/dist/index.js +4 -3
  28. package/dist/internal/server.d.ts +3 -3
  29. package/dist/internal/server.js +5 -5
  30. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  31. package/dist/{mcp-token-DgveSGEl.js → mcp-token-BleQZK6H.js} +28 -5
  32. package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
  33. package/dist/mcp.d.ts +2 -2
  34. package/dist/mcp.js +26 -5
  35. package/dist/{members-CRlYyxVk.js → members-7OMdqha_.js} +2 -2
  36. package/dist/nuxt.d.ts +4 -14
  37. package/dist/nuxt.js +29 -9
  38. package/dist/{own-access-BvVUjaeL.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  39. package/dist/presets.js +1 -1
  40. package/dist/runtime/client-request-plugin.d.ts +2 -1
  41. package/dist/runtime/client-request-plugin.js +8 -5
  42. package/dist/runtime/console.d.ts +1 -1
  43. package/dist/runtime/console.js +2 -2
  44. package/dist/runtime/empty-abilities.d.ts +1 -1
  45. package/dist/runtime/empty-client.d.ts +3 -0
  46. package/dist/runtime/empty-client.js +3 -1
  47. package/dist/runtime/empty-definition.d.ts +1 -1
  48. package/dist/runtime/server.d.ts +4 -3
  49. package/dist/runtime/server.js +3 -2
  50. package/dist/runtime/vue-nuxt.js +1 -1
  51. package/dist/schema.d.ts +32 -14
  52. package/dist/schema.js +21 -14
  53. package/dist/{server-iQNOXyfS.js → server-5t-HA7I1.js} +41 -316
  54. package/dist/{server-1G_BbfBD.d.ts → server-DyP1v-sZ.d.ts} +25 -6
  55. package/dist/{server-B8kTFrHP.d.ts → server-mmp8EfcE.d.ts} +3 -2
  56. package/dist/server.d.ts +3 -3
  57. package/dist/server.js +4 -4
  58. package/dist/{session-cookies-DN0svCKj.js → session-cookies-BNtY3hMp.js} +4 -16
  59. package/dist/{set-cookie-CMB3t4NF.js → set-cookie-Bva-P-_C.js} +1 -1
  60. package/dist/{table-specs-C3-bLOSF.js → table-specs-Bm7QJCbu.js} +1 -1
  61. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  62. package/dist/test.d.ts +1 -1
  63. package/dist/test.js +2 -2
  64. package/dist/{types-BmRGse4l.d.ts → types-CnO5bHEF.d.ts} +20 -2
  65. package/dist/{vite-GRzej8Cs.js → vite-7I1bJvqA.js} +641 -240
  66. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  67. package/dist/vite.d.ts +33 -13
  68. package/dist/vite.js +1 -1
  69. package/dist/vue.d.ts +4 -3
  70. package/dist/vue.js +39 -4
  71. package/package.json +8 -8
  72. package/dist/client-request-BzMKtfCY.js +0 -52
package/README.md CHANGED
@@ -83,9 +83,11 @@ pnpm vitehub database migrate
83
83
 
84
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`.
85
85
 
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, imports and calls them. 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.
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
 
88
- Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. Use `authSqliteSchema` and `authPostgresSchema` for foreign keys to core tables such as `user` and `organization`.
88
+ The tables have text IDs by default. With `advanced.database.generateId: "uuid"` written inline in the Definition, the plugin passes `generateId: "uuid"` to `createAuthPostgresSchema()`: on Postgres each `id` is `uuid` with a `gen_random_uuid()` default, each column that references an `id` is `uuid`, and the database makes the ID. SQLite has no uuid type, so its columns stay text and Better Auth makes the UUID. `serial` and `false` fail with `AUTH_C0053`, and so does a Postgres Database whose ID columns do not match the `generateId` of the running options. For a foreign key to a `uuid` ID, use a `uuid` column that references the generated `authPostgresSchema` table.
89
+
90
+ Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. `authSqliteSchema` and `authPostgresSchema` give you the table objects that Auth contributes. Use them for foreign keys and for Drizzle relations to tables such as `user` and `organization`: `defineRelationsPart({ user: authSqliteSchema.user, order }, r => ({ order: { user: r.one.user({ from: r.order.userId, to: r.user.id }) } }))`.
89
91
 
90
92
  ## Delete an account
91
93
 
@@ -203,7 +205,7 @@ When `@vite-hub/env` is installed, the Auth Definition callback receives the typ
203
205
 
204
206
  Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: true`. `requestOrigin`, the default `baseURL`, and the `Origin` check then use the first `X-Forwarded-Proto` and `X-Forwarded-Host` values. Set it only when a proxy you run sets these headers. It does not change the client IP of the rate limiter and `session.ipAddress`: on the Node host behind your own proxy, set `vitehub({ trustProxy: true })` for that. Proxy trust uses the options of the Definition, or the object that its callback returns.
205
207
 
206
- Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
208
+ Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `authMiddleware()`, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
207
209
 
208
210
  Auth keeps the `Origin` check on in dev, in tests, and in production. A `POST` that carries the session cookie, and every sign-in or sign-up `POST` that sends an `Origin`, answers `403` with `INVALID_ORIGIN` when the `Origin` is not `baseURL` or in `trustedOrigins`. Better Auth turns this check off when `TEST` or `NODE_ENV=test` is set, but Auth does not, so a server that a Vitest run starts checks the `Origin` as production does. To turn the check off, set `advanced.disableOriginCheck: true`.
209
211
 
@@ -270,7 +272,7 @@ The inline guards use H3's JSON error format. They keep the response status and
270
272
 
271
273
  ```ts fragment
272
274
  import { requireAuth, requireAuthorization } from "@vite-hub/auth/server";
273
- import { defineHandler } from "h3";
275
+ import { defineHandler } from "nitro/h3";
274
276
 
275
277
  export const me = defineHandler(async (event) => {
276
278
  const { user } = await requireAuth(event);
@@ -283,13 +285,32 @@ export const removePost = defineHandler(async (event) => {
283
285
  });
284
286
  ```
285
287
 
288
+ H3 applies `validate.query` and `validate.headers` before the handler runs, so a guest who sends a bad query can get `400` before a guard in the handler runs. Put `authMiddleware(authorize?)` in the route's `middleware` to check access first. It returns nothing when the check passes, and rejects like `requireAuth()`, or like `requireAuthorization()` when you pass `authorize`. Do not put `requireAuth` itself in `middleware`: H3 sends what a middleware returns, which is the session. A `requireAuth(event)` in the handler reuses the session that the middleware read.
289
+
290
+ ```ts fragment
291
+ import { authMiddleware, requireAuth } from "@vite-hub/auth/server";
292
+ import { defineValidatedHandler } from "nitro/h3";
293
+ import * as v from "valibot";
294
+
295
+ export const inbox = defineValidatedHandler({
296
+ middleware: [authMiddleware()],
297
+ validate: { query: v.object({ view: v.picklist(["open", "archived"]) }) },
298
+ handler: async (event) => {
299
+ const { user } = await requireAuth(event);
300
+ return { user: user.id, view: event.url.searchParams.get("view") };
301
+ },
302
+ });
303
+ ```
304
+
305
+ For path parameters, call H3's `getValidatedRouterParams(event, schema)` in the handler after checking access.
306
+
286
307
  ### Better Auth instance
287
308
 
288
309
  `useAuth(event)` returns the Better Auth instance of your Auth Definition for a request event or a Web `Request`. The Vite plugin writes the type of `server/auth.ts` to `.vitehub/types/auth.d.ts`, so the instance has the endpoints of your plugins without a cast:
289
310
 
290
311
  ```ts fragment
291
312
  import { requireAuthorization, useAuth } from "@vite-hub/auth/server";
292
- import { defineHandler } from "h3";
313
+ import { defineHandler } from "nitro/h3";
293
314
 
294
315
  // server/auth.ts uses `admin()` from `better-auth/plugins`.
295
316
  export default defineHandler(async (event) => {
@@ -451,6 +472,38 @@ const { client } = useUserSession();
451
472
  const { data } = await client.admin.listUsers({ query: { limit: 10 } });
452
473
  ```
453
474
 
475
+ ### Add to Auth from a Nuxt layer
476
+
477
+ A Nuxt layer that does not own the Auth Definition adds Better Auth server plugins and `user` fields with `extendAuth()` in `server/auth.extend.ts`, and client plugins with `extendAuthClient()` in `app/auth.client.extend.ts`. The app imports no layer file. The app can have both files too, and a Vite app has them in `server/` and beside `auth.client.ts`.
478
+
479
+ ```ts
480
+ // layers/payments/server/auth.extend.ts
481
+ import { extendAuth } from "@vite-hub/auth";
482
+
483
+ export default extendAuth({
484
+ plugins: [
485
+ {
486
+ id: "polar",
487
+ schema: { user: { fields: { polarCustomerId: { type: "string", required: false } } } },
488
+ },
489
+ ],
490
+ });
491
+ ```
492
+
493
+ ```ts
494
+ // layers/payments/app/auth.client.extend.ts
495
+ import { extendAuthClient } from "@vite-hub/auth/vue";
496
+
497
+ export default extendAuthClient({
498
+ plugins: [{ id: "polar" }],
499
+ });
500
+ ```
501
+
502
+ - A part takes `plugins`, and `extendAuth()` also takes `user.additionalFields`. Each other option stays in `defineAuth()` or `defineAuthClient()`, or the build fails with `AUTH_EXTENSION_OPTION_INVALID`.
503
+ - Merge order: the Definition, the file of the app, then the files of the layers in Nuxt priority order. Each plugin list keeps its order.
504
+ - `server/auth.extend.ts` without an Auth Definition fails with `AUTH_EXTENSION_WITHOUT_DEFINITION`. Two sources with one plugin id fail with `AUTH_DUPLICATE_PLUGIN`. Two declarations of one `user` field with different attributes fail with `AUTH_FIELD_CONFLICT`.
505
+ - The runtime, the generated schema of `authDatabase()`, `.vitehub/types/auth.d.ts`, and `vitehub inspect definitions` read the same list of files.
506
+
454
507
  The exported `createAuthClient` keeps Better Auth's option and plugin inference for a second client with its own base path or plugins. Without `basePath`, it uses the same path as the default client. The zero-config composables use ViteHub's shared default client. Its type is `RegisteredAuthClient`: `hubAuth()` writes the type of the Auth Definition to `.vitehub/types/auth.d.ts`, so `user` and `session` have the fields that `additionalFields`, server plugins such as `admin()`, and `customSession()` add. The client imports only this type, not server code. A client from `createAuthClient()` needs Better Auth's client plugins, such as `customSessionClient<RegisteredAuth>()`, and `inferAdditionalFields<RegisteredAuth>()` for the same fields. React, Svelte, Solid, and other framework clients remain available from Better Auth's framework entrypoints.
455
508
 
456
509
  The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useUserSession()` returns its refs at once: they are pending until the client loads in the browser. In Nuxt, a call in a component starts with the session that the server read for the request, so it is settled during server rendering and hydration. The browser then does not load Better Auth or read the session again until the session can change: a call such as `signOut()`, `refresh()`, the tab shows again, the network comes back, another tab signs out or updates the user, Better Auth's `refetchInterval` passes, or the session expires. Like Better Auth, it waits while the browser is offline. Better Auth then starts with the server's session, so a read that fails does not sign the page out. So without a page guard, a page that only shows the user reads the session once, on the server. When the server's session is unknown, such as on a prerendered page, the browser loads Better Auth at once. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
@@ -1,4 +1,4 @@
1
- import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BmRGse4l.js";
1
+ import { H as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-CnO5bHEF.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-CfvuGrBv.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-IOwpkcz4.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-DkzL9ltR.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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-DkzL9ltR.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
2
2
  import { n as isAuthRole } from "./roles-BGi8CyBG.js";
3
3
  // src/shared.ts
4
4
  const defaultAuthBasePath = "/api/auth";
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-CMB3t4NF.js";
2
- import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DN0svCKj.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
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";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
5
  import { ViteHubError } from "@vite-hub/runtime";
6
6
  // src/agent.ts
@@ -11,13 +11,13 @@ const loadServer = () => server ??= import("./internal/server.js").catch((error)
11
11
  });
12
12
  function authUserIdOf(invoker) {
13
13
  const meta = invoker?.meta;
14
- return (isRecord(meta) ? readString(meta.authUserId) : void 0) ?? (invoker?.kind === "authUser" ? readString(invoker.id) : void 0);
14
+ return (isRecord(meta) ? nonEmptyString(meta.authUserId) : void 0) ?? (invoker?.kind === "authUser" ? nonEmptyString(invoker.id) : void 0);
15
15
  }
16
16
  function namedAuthUserInvoker(context) {
17
17
  const inputContext = context.input?.context;
18
18
  if (!isRecord(inputContext) || inputContext.invoker === void 0) return void 0;
19
19
  const invoker = context.defaultInvoker;
20
- const userId = invoker.kind === "authUser" ? readString(invoker.id) : void 0;
20
+ const userId = invoker.kind === "authUser" ? nonEmptyString(invoker.id) : void 0;
21
21
  return userId ? {
22
22
  ...invoker,
23
23
  meta: {
@@ -36,7 +36,7 @@ const agentAuth = { async user(invoker) {
36
36
  } catch (cause) {
37
37
  throwAuthenticationProviderError(cause, "get-user");
38
38
  }
39
- return isRecord(user) && readString(user.id) ? user : null;
39
+ return isRecord(user) && nonEmptyString(user.id) ? user : null;
40
40
  } };
41
41
  function authenticationRequired(message = "[vitehub] Authentication required.") {
42
42
  if (!message || message.length > 16384) invalidAuthenticationErrorOptions();
@@ -96,18 +96,18 @@ function readProviderField(read) {
96
96
  }
97
97
  }
98
98
  async function createDefaultInvoker(options, context, providerFields) {
99
- const userId = await resolveAuthenticatedValue(options.id, context) ?? providerFields?.userId ?? readString(context.user.id);
99
+ const userId = await resolveAuthenticatedValue(options.id, context) ?? providerFields?.userId ?? nonEmptyString(context.user.id);
100
100
  if (!userId) throw authenticationRequired("[vitehub] Authenticated user is missing an id.");
101
101
  const kind = await resolveAuthenticatedValue(options.kind, context) ?? "authUser";
102
102
  const label = await resolveAuthenticatedValue(options.label, context) ?? (providerFields && readProviderField(() => defaultLabel(providerFields.user, providerFields.userId))) ?? defaultLabel(context.user);
103
- const sessionId = providerFields ? readProviderField(() => readString(providerFields.session.id)) : readString(context.session.id);
103
+ const sessionId = providerFields ? readProviderField(() => nonEmptyString(providerFields.session.id)) : nonEmptyString(context.session.id);
104
104
  return {
105
105
  id: userId,
106
106
  kind,
107
107
  label,
108
108
  meta: {
109
109
  ...normalizeMeta(await resolveAuthenticatedValue(options.meta, context)),
110
- authUserId: providerFields?.userId ?? readString(context.user.id) ?? userId,
110
+ authUserId: providerFields?.userId ?? nonEmptyString(context.user.id) ?? userId,
111
111
  ...sessionId ? { authSessionId: sessionId } : {}
112
112
  }
113
113
  };
@@ -117,14 +117,14 @@ function resolveAuthenticatedValue(value, context) {
117
117
  return value;
118
118
  }
119
119
  function defaultLabel(user, fallbackId = user.id) {
120
- return readString(user.email) ?? readString(user.name) ?? fallbackId;
120
+ return nonEmptyString(user.email) ?? nonEmptyString(user.name) ?? fallbackId;
121
121
  }
122
122
  function normalizeMeta(value) {
123
123
  if (!value) return {};
124
124
  if (!isRecord(value)) throw authErrorDiagnostics.AUTH_R0002({ message: "[vitehub] authenticated({ meta }) must resolve to an object." });
125
125
  return value;
126
126
  }
127
- function readString(value) {
127
+ function nonEmptyString(value) {
128
128
  return typeof value === "string" && value.length > 0 ? value : void 0;
129
129
  }
130
130
  export { agentAuth, authenticated };
@@ -1,25 +1,26 @@
1
- import { i as forwardedRequestOrigin, t as clientRequest } from "./client-request-BzMKtfCY.js";
1
+ import { t as clientRequest } from "./client-request-B1DCz3a9.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
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-CRlYyxVk.js";
5
- import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-DE9lMwu1.js";
6
- import { t as assertAuthDatabaseNames } from "./database-schema-options-CCQsNhjc.js";
7
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.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-DeEeqTLC.js";
9
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BUaoHFoC.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";
10
10
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
11
11
  import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
12
12
  import { n as resetAuth, t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
13
- import { o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
14
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-CMB3t4NF.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";
15
15
  import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-dVJBPPTk.js";
16
16
  import { resolvePublicUrl } from "@vite-hub/runtime";
17
+ import { isRequest } from "@vite-hub/runtime/internal/response";
17
18
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
18
19
  import { AsyncLocalStorage } from "node:async_hooks";
19
20
  import { createAuthEndpoint, createAuthMiddleware, getOAuthState, getSessionFromCtx, isAPIError, sensitiveSessionMiddleware } from "better-auth/api";
20
21
  import { getCookies } from "better-auth/cookies";
21
22
  import { getAuthTables } from "better-auth/db";
22
- import { APIError as APIError$1, BetterAuthError, betterAuth, createLogger, getBaseURL, isDynamicBaseURLConfig, isRequestLike, resolveBaseURL, trimTrailingSlashes } from "better-auth";
23
+ import { APIError as APIError$1, BetterAuthError, betterAuth, createLogger, getBaseURL, isDynamicBaseURLConfig, resolveBaseURL, trimTrailingSlashes } from "better-auth";
23
24
  import { memoryAdapter } from "better-auth/adapters/memory";
24
25
  import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
25
26
  import { configuredAppOrigin, configuredPublicOrigins } from "@vite-hub/runtime/internal/public-url";
@@ -27,6 +28,27 @@ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
27
28
  import { isWebContainer } from "@vite-hub/web-container/env";
28
29
  import { hkdfSync } from "node:crypto";
29
30
  import { addRoute, createRouter, findRoute } from "better-auth-rou3";
31
+ // ../internal/src/runtime/request-origin.ts
32
+ function firstHeaderValue(headers, name) {
33
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
34
+ }
35
+ /**
36
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
37
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
38
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
39
+ */
40
+ function forwardedRequestOrigin(request) {
41
+ const url = new URL(request.url);
42
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
43
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
44
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
45
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
46
+ try {
47
+ return new URL(`${protocol}://${host}`).origin;
48
+ } catch {
49
+ return url.origin;
50
+ }
51
+ }
30
52
  // src/password.ts
31
53
  const scryptOptions = {
32
54
  N: 16384,
@@ -743,7 +765,7 @@ function createImpersonationPlugin() {
743
765
  const clientAddressHeader = "x-vitehub-client-address";
744
766
  /** The addresses that `handleAuthRequest()` read from the request event, for the Request that it passes to Better Auth. */
745
767
  const eventAddresses = /* @__PURE__ */ new WeakMap();
746
- function readString(value, path) {
768
+ function readStringAtPath(value, path) {
747
769
  let current = value;
748
770
  for (const key of path) {
749
771
  if (current === null || typeof current !== "object" && typeof current !== "function") return void 0;
@@ -757,7 +779,7 @@ function readString(value, path) {
757
779
  * not read.
758
780
  */
759
781
  function eventClientAddress(event) {
760
- return readString(event, [
782
+ return readStringAtPath(event, [
761
783
  "~standard",
762
784
  "runtime",
763
785
  "clientAddress"
@@ -770,7 +792,7 @@ function setRequestClientAddress(request, address) {
770
792
  }
771
793
  /** Return the request with only the host address in {@link clientAddressHeader}. srvx adds that address as `ip`. */
772
794
  function addressedRequest(request) {
773
- const address = eventAddresses.get(request) ?? readString(request, ["ip"]);
795
+ const address = eventAddresses.get(request) ?? readStringAtPath(request, ["ip"]);
774
796
  if (request.headers.get("x-vitehub-client-address") === (address ?? null)) return request;
775
797
  const headers = new Headers(request.headers);
776
798
  if (address) headers.set(clientAddressHeader, address);
@@ -1262,14 +1284,14 @@ const markerAttributes = [
1262
1284
  "partitioned"
1263
1285
  ];
1264
1286
  function requestSource(input) {
1265
- if (isRequestLike(input)) return input;
1266
- if (isRequestLike(input?.request)) return input.request;
1287
+ if (isRequest(input)) return input;
1288
+ if (isRequest(input?.request)) return input.request;
1267
1289
  const headers = new Headers(input?.headers);
1268
1290
  return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
1269
1291
  }
1270
1292
  /** The value of one cookie in the request of an API call or a handler request. */
1271
1293
  function requestCookie(input, name) {
1272
- const headers = isRequestLike(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1294
+ const headers = isRequest(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1273
1295
  for (const part of headers?.get("cookie")?.split(";") ?? []) {
1274
1296
  const separator = part.indexOf("=");
1275
1297
  if (separator !== -1 && part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
@@ -1440,4 +1462,4 @@ function authForRequest(request, event, definition = resolveDefaultDefinition())
1440
1462
  env: envResolverFor(definition)
1441
1463
  }));
1442
1464
  }
1443
- export { setAuthResponseOutcome as _, getAuthForDefinition as a, withSessionMarker as c, withEndpointRateLimits as d, eventClientAddress as f, setAuthOutcome as g, runWithAuthEvent as h, findVerifiedAuthUserId as i, resolveAuthOptions as l, withClientAddress as m, createBetterAuthOptions as n, requestProvider as o, setRequestClientAddress as p, envResolverFor as r, resolveDefaultDefinition as s, authForRequest as t, trustsProxyHeaders as u };
1465
+ export { setAuthResponseOutcome as _, getAuthForDefinition as a, withSessionMarker as c, withEndpointRateLimits as d, eventClientAddress as f, setAuthOutcome as g, runWithAuthEvent as h, findVerifiedAuthUserId as i, resolveAuthOptions as l, withClientAddress as m, createBetterAuthOptions as n, requestProvider as o, setRequestClientAddress as p, envResolverFor as r, resolveDefaultDefinition as s, authForRequest as t, trustsProxyHeaders as u, forwardedRequestOrigin as v };
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
2
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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. */
@@ -0,0 +1,33 @@
1
+ import { i as OnlyKeys } from "./extension-BWmjJhoN.js";
2
+ import { BetterAuthClientOptions } from "better-auth";
3
+ /** What a part of the Auth client options can add. Every other option stays in `defineAuthClient()`. */
4
+ interface AuthClientExtensionOptions {
5
+ /** Better Auth client plugins, added after the plugins of `auth.client.ts`. */
6
+ plugins?: NonNullable<BetterAuthClientOptions["plugins"]>;
7
+ }
8
+ /** A part of the Auth client options, from `extendAuthClient()` in `auth.client.extend.ts`. */
9
+ interface AuthClientExtension<TOptions extends AuthClientExtensionOptions = AuthClientExtensionOptions> {
10
+ extension: TOptions;
11
+ }
12
+ /**
13
+ * A part of the Auth client options: Better Auth client plugins that a Nuxt layer, or the app, adds to the options of
14
+ * `auth.client.ts`. Export it as the default export of `auth.client.extend.ts`, which is in `app/` in a Nuxt app.
15
+ */
16
+ declare function extendAuthClient<const TOptions extends AuthClientExtensionOptions>(options: OnlyKeys<TOptions, "plugins">): AuthClientExtension<TOptions>;
17
+ /** A part with the file that exports it, as the generated client module lists them. */
18
+ interface AuthClientExtensionSource {
19
+ file: string;
20
+ extension: AuthClientExtension;
21
+ }
22
+ type ClientPluginsOf<TOptions> = TOptions extends {
23
+ plugins: infer TPlugins extends readonly unknown[];
24
+ } ? TPlugins : [];
25
+ type ClientExtensionPlugins<TExtensions extends readonly unknown[]> = TExtensions extends readonly [AuthClientExtension<infer TOptions>, ...infer TRest] ? [...ClientPluginsOf<TOptions>, ...ClientExtensionPlugins<TRest>] : [];
26
+ /**
27
+ * The type of the client options with their parts, which generated declarations register. `TExtensions` is the tuple of
28
+ * the default exports of the `auth.client.extend.ts` files, in merge order.
29
+ */
30
+ type ExtendedAuthClientOptions<TOptions, TExtensions extends readonly unknown[]> = Omit<TOptions, "plugins"> & {
31
+ plugins: [...ClientPluginsOf<TOptions>, ...ClientExtensionPlugins<TExtensions>];
32
+ };
33
+ export { extendAuthClient as a, ExtendedAuthClientOptions as i, AuthClientExtensionOptions as n, AuthClientExtensionSource as r, AuthClientExtension as t };
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // ../internal/src/runtime/client-request.ts
3
+ const storageKey = Symbol.for("vitehub.client-request");
4
+ const runtimeGlobal = globalThis;
5
+ const clientRequests = runtimeGlobal[storageKey] ||= new AsyncLocalStorage();
6
+ function isRelativeInProcessRequest(request, client) {
7
+ const url = new URL(request.url);
8
+ if (url.protocol !== "http:") return false;
9
+ if (url.host === "localhost") return true;
10
+ const clientUrl = new URL(client.url);
11
+ url.protocol = clientUrl.protocol;
12
+ return url.host === clientUrl.host || url.host === client.headers.get("host");
13
+ }
14
+ /** Runs `next` with `request` as the client request, unless `request` is a relative request inside a client request. */
15
+ function runWithClientRequest(request, next) {
16
+ const client = clientRequests.getStore();
17
+ return client && isRelativeInProcessRequest(request, client) ? next() : clientRequests.run(request, next);
18
+ }
19
+ /**
20
+ * The request that the client sent. Nitro builds a relative request that the server sends to itself, such as a Nuxt
21
+ * `useFetch()` during server rendering or `serverFetch("/api/...")`, at `http://localhost` or `http://<forwarded Host>`,
22
+ * so the URL of that request does not show the origin of the page. Read origins from this request instead. It needs
23
+ * the Nitro plugin that `clientRequestPlugin()` of `@vite-hub/internal/nitro-kit` gives.
24
+ */
25
+ function clientRequest(request) {
26
+ const client = clientRequests.getStore();
27
+ return client && isRelativeInProcessRequest(request, client) ? client : request;
28
+ }
29
+ export { runWithClientRequest as n, clientRequest as t };
@@ -1,4 +1,4 @@
1
- import { J as AuthConsoleAgent, K as AuthConsoleActivity, Lt as AuthEventStore, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, ct as AuthConsoleOptions, dt as AuthConsoleOverview, gt as AuthConsoleSession, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, ot as AuthConsoleList, q as AuthConsoleActivityQuery, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, yt as AuthConsoleUserDetail } from "./types-BmRGse4l.js";
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";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
4
4
  interface AuthConsole {
@@ -1,7 +1,7 @@
1
- import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-CRlYyxVk.js";
1
+ import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-7OMdqha_.js";
2
2
  import { n as adminClaimVariable } from "./admin-claim-code-C3X_U43x.js";
3
3
  import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
4
- import { r as parseAuthEventList } from "./events-BUaoHFoC.js";
4
+ import { r as parseAuthEventList } from "./events-Cm7Iwq47.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
@@ -1,3 +1,3 @@
1
- import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-BmRGse4l.js";
2
- import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-XcplYv4R.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-CnO5bHEF.js";
2
+ import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-C71weVrt.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-Bg_PAl7e.js";
1
+ export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-Dk3j4Jmz.js";
package/dist/console.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-BmRGse4l.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-CnO5bHEF.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-DkzL9ltR.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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) {
@@ -6,9 +6,17 @@ function authDatabaseName(database) {
6
6
  const name = Reflect.get(database, "vitehubDatabase");
7
7
  return typeof name === "string" ? name : void 0;
8
8
  }
9
- /** The owned schema has text IDs and references, with no database-generated default. */
9
+ /**
10
+ * The owned tables have text IDs that Better Auth makes, or `uuid` IDs on Postgres. `serial` needs integer IDs, and
11
+ * `false` needs a database default that a text ID does not have.
12
+ */
10
13
  function assertAuthDatabaseIdStrategy(generateId) {
11
- if (generateId === "serial" || generateId === "uuid" || generateId === false) throw authErrorDiagnostics.AUTH_C0053({ message: "`authDatabase()` owns tables with text IDs. Use Better Auth's default ID generator or a custom function returning strings; `advanced.database.generateId` cannot be `serial`, `uuid`, or `false`. Use another Better Auth adapter to own a different ID schema." });
14
+ if (generateId === "serial" || generateId === false) throw authErrorDiagnostics.AUTH_C0053({ message: "`authDatabase()` owns tables with text IDs, or `uuid` IDs on Postgres. Use Better Auth's default ID generator, `uuid`, or a custom function returning strings; `advanced.database.generateId` cannot be `serial` or `false`. Use another Better Auth adapter to own a different ID schema." });
15
+ }
16
+ /** The ID columns of a Postgres Database and the `generateId` of the running options do not agree, so no insert can work. */
17
+ function authDatabaseIdColumnError(database, model, uuidColumn) {
18
+ const detail = uuidColumn ? "has a `uuid` ID, but `advanced.database.generateId` is not `\"uuid\"`, so Better Auth would write a text ID" : "has no `uuid` ID, but `advanced.database.generateId` is `\"uuid\"`, so Better Auth would leave the ID to a database default";
19
+ return authErrorDiagnostics.AUTH_C0053({ message: `The \`${model}\` table of the ${JSON.stringify(database)} Database of \`authDatabase()\` ${detail}. Write \`advanced: { database: { generateId: "uuid" } }\` inline in the Auth Definition so that the Auth Vite plugin can read it, then run \`vitehub database generate\` and apply the migration.` });
12
20
  }
13
21
  /** The Auth Vite plugin reads `additionalFields` from the Definition to add their columns, so they must be static. */
14
22
  function authDatabaseAdditionalFieldsError(detail) {
@@ -25,4 +33,4 @@ function authDatabasePlacementError() {
25
33
  function authMemoryDatabaseError() {
26
34
  return authErrorDiagnostics.AUTH_C0063({ message: "`defineAuth()` has no `database` or `preset`. Auth keeps users and sessions in memory only on a development server, because a restart or a second instance loses them." });
27
35
  }
28
- export { authDatabaseSchemaError as a, authDatabasePlacementError as i, authDatabaseAdditionalFieldsError as n, authMemoryDatabaseError as o, authDatabaseName as r, assertAuthDatabaseIdStrategy as t };
36
+ export { authDatabasePlacementError as a, authDatabaseName as i, authDatabaseAdditionalFieldsError as n, authDatabaseSchemaError as o, authDatabaseIdColumnError as r, authMemoryDatabaseError as s, assertAuthDatabaseIdStrategy as t };
@@ -1,4 +1,4 @@
1
- import { a as authDatabaseSchemaError } from "./database-options-DE9lMwu1.js";
1
+ import { o as authDatabaseSchemaError } from "./database-options-Cms7BI3c.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-BmRGse4l.js";
1
+ import { f as AuthAppDatabase } from "./types-CnO5bHEF.js";
2
2
  /**
3
3
  * The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
4
4
  * `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
- import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-DE9lMwu1.js";
3
- import { t as assertAuthDatabaseNames } from "./database-schema-options-CCQsNhjc.js";
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";
4
4
  import { getAuthTables } from "better-auth/db";
5
5
  import { getTableColumns, is, isTable } from "drizzle-orm";
6
6
  import { drizzleAdapter } from "better-auth/adapters/drizzle";
@@ -9,14 +9,18 @@ import { PgAsyncDatabase } from "drizzle-orm/pg-core";
9
9
  // src/database.ts
10
10
  /**
11
11
  * Compares the tables and fields that the options need, with the plugins and additional fields, against the Drizzle
12
- * tables of the Database, before the adapter opens it.
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.
13
14
  */
14
- function assertAuthDatabaseSchema(options, schema, database) {
15
+ function assertAuthDatabaseSchema(options, schema, database, postgres) {
16
+ const uuidIds = options.advanced?.database?.generateId === "uuid";
15
17
  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";
16
18
  for (const [model, table] of Object.entries(getAuthTables(options))) {
17
19
  const drizzleTable = Object.hasOwn(schema, model) ? schema[model] : void 0;
18
20
  if (!isTable(drizzleTable)) throw authDatabaseSchemaError(`the ${JSON.stringify(database)} Database has no \`${model}\` table. ${fix}`);
19
21
  const columns = getTableColumns(drizzleTable);
22
+ const uuidColumn = columns.id?.getSQLType() === "uuid";
23
+ if (postgres && uuidColumn !== uuidIds) throw authDatabaseIdColumnError(database, model, uuidColumn);
20
24
  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}`);
21
25
  }
22
26
  }
@@ -33,9 +37,10 @@ function authDatabase(name = "default") {
33
37
  assertAuthDatabaseNames(options);
34
38
  const entry = Object.hasOwn(databases, name) ? databases[name] : void 0;
35
39
  if (!entry || !Object.hasOwn(entry.schema, "user")) throw authErrorDiagnostics.AUTH_R0019({ message: `[vitehub] \`authDatabase(${JSON.stringify(name)})\` found no Better Auth tables in the ${JSON.stringify(name)} Database. Pass \`authDatabase()\` inline as the \`database\` of \`defineAuth()\` so that Auth adds them, then run \`vitehub database generate\` and \`vitehub database migrate\`. \`vitehub inspect definitions --kind database\` lists the tables of each Database.` });
36
- assertAuthDatabaseSchema(options, entry.schema, name);
40
+ const postgres = is(entry.db, PgAsyncDatabase);
41
+ assertAuthDatabaseSchema(options, entry.schema, name, postgres);
37
42
  return drizzleAdapter(entry.db, {
38
- provider: is(entry.db, PgAsyncDatabase) ? "pg" : "sqlite",
43
+ provider: postgres ? "pg" : "sqlite",
39
44
  schema: entry.schema
40
45
  })(options);
41
46
  };
@@ -1,9 +1,9 @@
1
- import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
1
+ import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
2
2
  import { n as isAuthRole } from "./roles-BGi8CyBG.js";
3
3
  import { t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
4
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
4
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
5
5
  import { t as isRecord } from "./object-CAK6UYR5.js";
6
- import { r as authDatabaseName } from "./database-options-DE9lMwu1.js";
6
+ import { i as authDatabaseName } from "./database-options-Cms7BI3c.js";
7
7
  import { parseDuration } from "@vite-hub/runtime";
8
8
  // src/stateless-user-id.ts
9
9
  const pendingUserIds = /* @__PURE__ */ new WeakMap();