@vite-hub/auth 0.7.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 (78) hide show
  1. package/README.md +59 -6
  2. package/dist/{abilities-CfvuGrBv.d.ts → abilities-6LE7VSdN.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-OKoyOwPM.js → ability-error-Ccm5Iy4F.js} +1 -1
  5. package/dist/{access-pages-Bej95blM.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 +11 -11
  8. package/dist/{application-path-zKi7NrvK.js → application-path-LMc_ptL9.js} +0 -2
  9. package/dist/{auth-instance-5RSiFTDC.js → auth-instance-0PTsOttV.js} +41 -57
  10. package/dist/bun-sqlite.d.ts +0 -2
  11. package/dist/cli.js +2 -2
  12. package/dist/client-extension-BVBVUqa1.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-BlOx9hWC.js} +3 -19
  15. package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-D2FUATXQ.d.ts} +1 -1
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-CPhnGap9.js +36 -0
  20. package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-BQyynyhw.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +22 -11
  23. package/dist/{definition-DeEeqTLC.js → definition-CvmvHaQT.js} +4 -12
  24. package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-BpQy1iIO.js} +35 -4
  25. package/dist/{events-BUaoHFoC.js → events-aP_Rz_gx.js} +1 -1
  26. package/dist/extension-B35v_o1u.js +133 -0
  27. package/dist/extension-C2giF7w2.d.ts +59 -0
  28. package/dist/forward.d.ts +0 -5
  29. package/dist/forward.js +1 -1
  30. package/dist/index.d.ts +4 -3
  31. package/dist/index.js +4 -3
  32. package/dist/internal/server.d.ts +3 -3
  33. package/dist/internal/server.js +5 -5
  34. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-DYlTXmr6.js} +9 -1
  35. package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
  36. package/dist/{mcp-token-DgveSGEl.js → mcp-token-i-8NMulH.js} +28 -6
  37. package/dist/mcp.d.ts +2 -7
  38. package/dist/mcp.js +26 -7
  39. package/dist/{members-CRlYyxVk.js → members-USm08YwK.js} +4 -6
  40. package/dist/nuxt.d.ts +4 -14
  41. package/dist/nuxt.js +29 -61
  42. package/dist/{own-access-BvVUjaeL.d.ts → own-access-B7VRd92K.d.ts} +1 -1
  43. package/dist/presets.js +1 -1
  44. package/dist/{request-Dpq7GO8B.js → request-CdlcvqVc.js} +0 -1
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +5 -4
  55. package/dist/runtime/vue-nuxt.js +2 -18
  56. package/dist/schema.d.ts +32 -17
  57. package/dist/schema.js +39 -16
  58. package/dist/{server-1G_BbfBD.d.ts → server-4_EXgXFn.d.ts} +25 -8
  59. package/dist/{server-iQNOXyfS.js → server-CZR2dVVp.js} +43 -352
  60. package/dist/{server-B8kTFrHP.d.ts → server-DAIBBKbR.d.ts} +3 -2
  61. package/dist/server.d.ts +3 -3
  62. package/dist/server.js +4 -4
  63. package/dist/{session-cookies-DN0svCKj.js → session-cookies-CfXdF1yd.js} +5 -33
  64. package/dist/{set-cookie-CMB3t4NF.js → set-cookie-BYZslovs.js} +1 -1
  65. package/dist/{table-specs-C3-bLOSF.js → table-specs-Cvjc_Ccs.js} +28 -2
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-VYAy_jJ7.d.ts} +5 -2
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-BmRGse4l.d.ts → types-DakualFJ.d.ts} +20 -4
  70. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  71. package/dist/{vite-GRzej8Cs.js → vite-DVvWaN3D.js} +652 -301
  72. package/dist/vite.d.ts +35 -17
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -34
  75. package/dist/vue.js +40 -66
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-DE9lMwu1.js +0 -28
package/README.md CHANGED
@@ -81,11 +81,13 @@ 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
- 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-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-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-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-DkzL9ltR.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-DkzL9ltR.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-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-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
@@ -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 };
@@ -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,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
- 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";
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-Bej95blM.js";
14
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-CMB3t4NF.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
+ 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,
@@ -634,11 +656,6 @@ function createAuthEventsPlugin(options) {
634
656
  };
635
657
  }
636
658
  // src/impersonation-plugin.ts
637
- /**
638
- * Better Auth endpoints that create a credential which outlives an impersonation session, change how the user signs
639
- * in, or start another impersonation: OAuth, MCP, and device grants, API keys, passkeys, passwords, email and phone
640
- * number changes, linked accounts, two-factor setup, and one-time tokens that open a new session.
641
- */
642
659
  const credentialPaths = /* @__PURE__ */ new Set([
643
660
  "/account-info",
644
661
  "/admin/impersonate-user",
@@ -660,21 +677,18 @@ const credentialPaths = /* @__PURE__ */ new Set([
660
677
  "/two-factor/generate-backup-codes",
661
678
  "/unlink-account"
662
679
  ]);
663
- /** `/update-user` fields that change how the user signs in. The username plugin sets `username` from `displayUsername`. */
664
680
  const identityFields = ["displayUsername", "username"];
665
681
  const credentialPrefixes = [
666
682
  "/device/",
667
683
  "/mcp/",
668
684
  "/oauth2/"
669
685
  ];
670
- /** Reads below those prefixes. They show the user's grants and clients, so a support view still works. */
671
686
  const grantReads = /^\/oauth2\/(?:get-|public-client|userinfo)|^\/mcp\/get-session$/;
672
687
  function createsCredential(path, body) {
673
688
  if (!path) return false;
674
689
  if (path === "/update-user") return typeof body === "object" && body !== null && identityFields.some((field) => field in body);
675
690
  return credentialPaths.has(path) || credentialPrefixes.some((prefix) => path.startsWith(prefix)) && !grantReads.test(path);
676
691
  }
677
- /** The current expiry of the request's impersonation session, when the update would move it later. */
678
692
  function keptExpiry(...[data, endpoint]) {
679
693
  const current = endpoint?.context.session?.session;
680
694
  if (!current?.impersonatedBy || !data.expiresAt) return;
@@ -741,9 +755,8 @@ function createImpersonationPlugin() {
741
755
  * Better Auth instances that it creates: `handler` and each `api` endpoint.
742
756
  */
743
757
  const clientAddressHeader = "x-vitehub-client-address";
744
- /** The addresses that `handleAuthRequest()` read from the request event, for the Request that it passes to Better Auth. */
745
758
  const eventAddresses = /* @__PURE__ */ new WeakMap();
746
- function readString(value, path) {
759
+ function readStringAtPath(value, path) {
747
760
  let current = value;
748
761
  for (const key of path) {
749
762
  if (current === null || typeof current !== "object" && typeof current !== "function") return void 0;
@@ -757,7 +770,7 @@ function readString(value, path) {
757
770
  * not read.
758
771
  */
759
772
  function eventClientAddress(event) {
760
- return readString(event, [
773
+ return readStringAtPath(event, [
761
774
  "~standard",
762
775
  "runtime",
763
776
  "clientAddress"
@@ -768,9 +781,8 @@ function setRequestClientAddress(request, address) {
768
781
  if (address) eventAddresses.set(request, address);
769
782
  return request;
770
783
  }
771
- /** Return the request with only the host address in {@link clientAddressHeader}. srvx adds that address as `ip`. */
772
784
  function addressedRequest(request) {
773
- const address = eventAddresses.get(request) ?? readString(request, ["ip"]);
785
+ const address = eventAddresses.get(request) ?? readStringAtPath(request, ["ip"]);
774
786
  if (request.headers.get("x-vitehub-client-address") === (address ?? null)) return request;
775
787
  const headers = new Headers(request.headers);
776
788
  if (address) headers.set(clientAddressHeader, address);
@@ -787,7 +799,6 @@ function addressedRequest(request) {
787
799
  }
788
800
  return new Request(request.url, init);
789
801
  }
790
- /** Headers of an `api` call have no host address, so remove a value that the caller copied from client headers. */
791
802
  function withoutClientAddress(input) {
792
803
  if (!input || typeof input !== "object") return input;
793
804
  let result = input;
@@ -934,7 +945,6 @@ function isPlainData(value) {
934
945
  const prototype = Object.getPrototypeOf(value);
935
946
  return Array.isArray(value) ? prototype === Array.prototype : prototype === Object.prototype || prototype === null;
936
947
  }
937
- /** Write the key of `value` to `parts`. Returns false for a value that gives no key. */
938
948
  function writeKey(value, parts, parents) {
939
949
  if (typeof value === "symbol") return false;
940
950
  if (typeof value === "string") {
@@ -971,18 +981,12 @@ function optionsKey(value) {
971
981
  return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
972
982
  }
973
983
  // src/runtime-options.ts
974
- /** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
975
984
  function isAuthDatabasePlacement(value) {
976
985
  return typeof value === "boolean" || isRecord(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key === "dedicated" || key === "name");
977
986
  }
978
- /** `true` or `{ store }`: the removed placement form, which is not a Better Auth adapter. */
979
987
  function isAuthSecondaryStoragePlacement(value) {
980
988
  return typeof value === "boolean" || isRecord(value) && Object.hasOwn(value, "store") && Object.keys(value).every((key) => key === "store");
981
989
  }
982
- /**
983
- * Without a database, Better Auth keeps users and sessions in the memory of one instance. Auth creates an instance for
984
- * each set of resolved options, so the instances of one Auth Definition share these tables. A restart still removes them.
985
- */
986
990
  function sharedMemoryDatabase(definition) {
987
991
  const state = getAuthRuntimeState();
988
992
  const databases = getViteHubTestMode()?.backend("auth", () => /* @__PURE__ */ new WeakMap(), resetAuth) ?? (state.memoryDatabases ??= /* @__PURE__ */ new WeakMap());
@@ -1003,12 +1007,6 @@ function isDevelopmentServer() {
1003
1007
  const mode = globalThis.process?.env?.NODE_ENV;
1004
1008
  return mode === "development" || mode === "test";
1005
1009
  }
1006
- /**
1007
- * Better Auth turns its limiter on only when `NODE_ENV` is `production`, and keeps its counters in the memory of the
1008
- * process unless a `secondaryStorage` is set. Auth turns it on outside a development server, and keeps the counters in
1009
- * the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them. It counts
1010
- * only requests to the endpoints of the instance.
1011
- */
1012
1010
  function withRateLimitDefaults(options, ownsDatabase) {
1013
1011
  const rateLimit = options.rateLimit;
1014
1012
  const database = ownsDatabase && !rateLimit?.storage && !rateLimit?.customStorage && !options.secondaryStorage;
@@ -1019,13 +1017,6 @@ function withRateLimitDefaults(options, ownsDatabase) {
1019
1017
  ...database ? { storage: "database" } : {}
1020
1018
  };
1021
1019
  }
1022
- /**
1023
- * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
1024
- * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
1025
- * `vitehub({ trustProxy: true })` makes that address the last `X-Forwarded-For` value, which the proxy adds.
1026
- * Better Auth also turns off its Origin and CSRF checks when `TEST` or `NODE_ENV=test` is set, such as in a server that
1027
- * a Vitest run starts. Auth serves real requests, so only `advanced.disableOriginCheck` turns them off.
1028
- */
1029
1020
  function withAdvancedDefaults(advanced) {
1030
1021
  const disableOriginCheck = advanced?.disableOriginCheck ?? false;
1031
1022
  if (advanced?.ipAddress?.ipAddressHeaders) return {
@@ -1041,10 +1032,6 @@ function withAdvancedDefaults(advanced) {
1041
1032
  }
1042
1033
  };
1043
1034
  }
1044
- /**
1045
- * The environment values that an instance for these options uses. Auth reads a value only when the options use it, so
1046
- * the instance key and the instance read the same values, and a value that the options replace cannot fail a request.
1047
- */
1048
1035
  function readProviderEnvironment(options, event) {
1049
1036
  const bindings = authCloudflareEnv(event);
1050
1037
  return {
@@ -1139,7 +1126,6 @@ function stripViteHubOptions(definition, options, environment) {
1139
1126
  basePath: resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0))
1140
1127
  };
1141
1128
  }
1142
- /** Moves `session.onRefresh` into a Better Auth plugin, because Better Auth does not read it. */
1143
1129
  function withSessionRefresh(options, hasSessionStore) {
1144
1130
  const session = options.session;
1145
1131
  if (!session?.onRefresh) return {};
@@ -1230,7 +1216,6 @@ function resolveAuthOptions(definition, input = {}) {
1230
1216
  const environment = resolveEnvironment();
1231
1217
  return withResolvedSecrets(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1232
1218
  },
1233
- /** Equal for two resolutions of this Definition that give Better Auth equal options, else `undefined`. */
1234
1219
  get providerKey() {
1235
1220
  const snapshot = resolveSnapshot();
1236
1221
  const database = authDatabaseName(snapshot.database);
@@ -1262,14 +1247,13 @@ const markerAttributes = [
1262
1247
  "partitioned"
1263
1248
  ];
1264
1249
  function requestSource(input) {
1265
- if (isRequestLike(input)) return input;
1266
- if (isRequestLike(input?.request)) return input.request;
1250
+ if (isRequest(input)) return input;
1251
+ if (isRequest(input?.request)) return input.request;
1267
1252
  const headers = new Headers(input?.headers);
1268
1253
  return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
1269
1254
  }
1270
- /** The value of one cookie in the request of an API call or a handler request. */
1271
1255
  function requestCookie(input, name) {
1272
- const headers = isRequestLike(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1256
+ const headers = isRequest(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1273
1257
  for (const part of headers?.get("cookie")?.split(";") ?? []) {
1274
1258
  const separator = part.indexOf("=");
1275
1259
  if (separator !== -1 && part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
@@ -1440,4 +1424,4 @@ function authForRequest(request, event, definition = resolveDefaultDefinition())
1440
1424
  env: envResolverFor(definition)
1441
1425
  }));
1442
1426
  }
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 };
1427
+ 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 };
@@ -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-DkzL9ltR.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. */
@@ -0,0 +1,33 @@
1
+ import { i as OnlyKeys } from "./extension-C2giF7w2.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 };