@vite-hub/auth 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +31 -7
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-9jC7iuN0.d.ts} +2 -2
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-DUWJ6Q1W.d.ts} +1 -1
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-DmnUGicq.js} +1 -1
  6. package/dist/access-pages-FNQTyGRD.js +96 -0
  7. package/dist/agent.js +3 -3
  8. package/dist/{auth-instance-CmDogt4D.js → auth-instance-zYMjldPG.js} +227 -25
  9. package/dist/{cli-ubYJpAL_.d.ts → cli-NCtitmny.d.ts} +1 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-CuXRDhGy.js} +67 -33
  13. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-Dqidb3zF.d.ts} +13 -11
  14. package/dist/console-runtime.d.ts +2 -2
  15. package/dist/console-runtime.js +1 -1
  16. package/dist/console.d.ts +1 -1
  17. package/dist/{database-options-DpOVjUti.js → database-options-CcjUG-us.js} +1 -1
  18. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CTKCAfqW.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BCaLA9kW.js → definition-BFT9T6In.js} +12 -4
  22. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-uEbxSY2G.js} +8 -2
  23. package/dist/{events-DCfuicoo.js → events-DJmO9a9I.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -2
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +4 -4
  28. package/dist/internal/server.js +4 -4
  29. package/dist/{invariant-D8_xBqmZ.js → invariant-DolT9EEx.js} +1 -1
  30. package/dist/{mcp-token-CpxLyl_p.js → mcp-token-BhonlK9C.js} +2 -2
  31. package/dist/mcp.js +1 -1
  32. package/dist/{members-DdlsS8kJ.js → members-Cl3hFRjk.js} +3 -3
  33. package/dist/nitro-kit-32CVgbWS.js +44 -0
  34. package/dist/nuxt.d.ts +32 -19
  35. package/dist/nuxt.js +337 -16
  36. package/dist/own-access-C8pwo_Kn.js +31 -0
  37. package/dist/own-access-CdgEICjO.d.ts +20 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/runtime/console.d.ts +1 -1
  40. package/dist/runtime/console.js +2 -2
  41. package/dist/runtime/empty-abilities.d.ts +1 -1
  42. package/dist/runtime/empty-definition.d.ts +1 -1
  43. package/dist/runtime/server.d.ts +3 -2
  44. package/dist/runtime/server.js +23 -14
  45. package/dist/runtime/vue-nuxt.js +70 -28
  46. package/dist/schema.d.ts +71 -19
  47. package/dist/schema.js +5 -3
  48. package/dist/{server-C8TlOrSy.d.ts → server-B-zNtSvm.d.ts} +9 -10
  49. package/dist/{server-BM-RSf1T.d.ts → server-Ci2i6p1S.d.ts} +7 -6
  50. package/dist/{server-BG_MFd4q.js → server-CyqLFm3L.js} +45 -25
  51. package/dist/server.d.ts +2 -2
  52. package/dist/server.js +2 -2
  53. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-CZmZS5QF.js} +2 -2
  54. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DWIyCCJO.js} +1 -1
  55. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BhWz_U0M.d.ts} +255 -1
  56. package/dist/{table-specs-CURphR3n.js → table-specs-D0VLp1U4.js} +43 -43
  57. package/dist/test.d.ts +1 -1
  58. package/dist/test.js +2 -2
  59. package/dist/{types-CruflEFI.d.ts → types-gl-myjZc.d.ts} +51 -4
  60. package/dist/{vite-Dy0Xhq4H.js → vite-QKjsPLwP.js} +349 -120
  61. package/dist/vite.d.ts +6 -2
  62. package/dist/vite.js +1 -1
  63. package/dist/vue.d.ts +17 -68
  64. package/dist/vue.js +22 -69
  65. package/package.json +13 -9
  66. package/dist/shared-DRtfuFsV.js +0 -12
package/README.md CHANGED
@@ -74,7 +74,9 @@ export default defineAuth({
74
74
 
75
75
  `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, 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`.
76
76
 
77
- The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module 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.
77
+ The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `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.
78
+
79
+ 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`.
78
80
 
79
81
  ## Delete an account
80
82
 
@@ -188,7 +190,7 @@ export default defineAuth(({ env, requestOrigin }) => ({
188
190
 
189
191
  When `@vite-hub/env` is installed, the Auth Definition callback receives the typed server env. It also receives `requestOrigin`, so same-origin apps do not need a separate auth URL environment variable.
190
192
 
191
- 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. Proxy trust uses the options of the Definition, or the object that its callback returns.
193
+ 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.
192
194
 
193
195
  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()`.
194
196
 
@@ -475,18 +477,18 @@ export default defineAbilities({
475
477
  A rule gets the signed-in user, then its arguments, and returns at once. `true` allows. `false` and a code refuse with `403`, and `deny(code, { status, details })` with another 4xx status. A signed-out visitor gets `401` with the code `signed-out` before the rule runs, except in a `guest()` rule, where `user` is `null`. The Vite plugin serves the file as `#vitehub/auth/abilities` and registers its type in `.vitehub/types/auth.d.ts`, so ability names and arguments type-check.
476
478
 
477
479
  - Server: `requireAbility(event, name, ...args)` from `@vite-hub/auth/server` returns the checked `{ request, session, user }`, or throws `AbilityError`. H3 2 sends it with the rule's status and `{ code, details }` in `data`. `can(event, name, ...args)` returns a boolean.
478
- - Vue: `useAbility().can(name, ...args)`, `useAbility().cannot(name, ...args)`, `<Can do="posts.edit" :with="post">`, and `<Cannot>` from `@vite-hub/auth/vue`. They give no answer (`undefined`, or no content) until the session is known. `<Can>` and `<Cannot>` take the one argument of a rule in `with`, the list of any other rule in `args` (`:args="[from, to]"`), and `pending` to show nothing while data loads. The arguments go to the rule as they are, the same as on the server. `<Can>` renders the `#denied` slot with `{ code, details }` when the rule refuses. `<Cannot>` renders its default slot with `{ code, details }` only when the rule refuses. The Nuxt module auto-imports all of them.
480
+ - Vue: `useAbility().can(name, ...args)`, `useAbility().cannot(name, ...args)`, and `<AuthPermission check="posts.edit" :args="[post]">` from `@vite-hub/auth/vue`. The component renders `#allowed` or `#denied` with `{ code, details }`. Default content is shorthand for `#allowed`; a named `#allowed` takes precedence. Neither slot renders until the session is known or while `pending` is true. All rules use an `args` tuple, checked against the rule signature. Nuxt registers the component only when the app or a layer has `shared/abilities.ts`, and an app component with the same name wins. Set `components: { prefix: "Custom" }` in `defineAuth()` to register `<CustomAuthPermission>`. Prefixes follow Nuxt's component prefix rules, which drop the prefix words that the name starts with: `MyAuth` registers `<MyAuthPermission>`.
479
481
  - Vue pages: `await useAbility().authorize(name, ...args)` throws when the rule refuses, with the status and `{ code, details }` data of `requireAbility()`. In Nuxt, the error is fatal and shows the error page. Without Nuxt, it is an `AbilityError`. In the browser, except while Nuxt hydrates, it sends one `/get-session` request for the current session. On the server, a session that the server could not read counts as signed out.
480
482
 
481
- Nuxt uses the Auth Definition's base path for the shared browser client. In other Vue apps, call `provideAuthClient(client)` from `@vite-hub/auth/vue` in a parent component's setup to share a custom client with descendant Auth composables and `<Can>`. You can also pass a client directly to `useAbility(client)`.
483
+ Nuxt uses the Auth Definition's base path for the shared browser client. In other Vue apps, call `provideAuthClient(client)` from `@vite-hub/auth/vue` in a parent component's setup to share a custom client with descendant Auth composables and `<AuthPermission>`. You can also pass a client directly to `useAbility(client)`.
482
484
 
483
485
  `requireAuthorization(event, authorize)` checks inside the handler, and `withAuthorization()` wraps it. Use them for checks that need only the user. A rule that needs data the handler loads belongs in `shared/abilities.ts`.
484
486
 
485
487
  ## Nuxt: server session and page guard
486
488
 
487
- In Nuxt, the server reads the session only for a page that needs it: a page with an `auth` guard, or a page whose components call `useUserSession()` or `useAbility()`, or render `<Can>`. It reads the session once for each page request, waits for it before it renders those components, settles their refs as soon as it has the session, so an async `setup()` can wait for `ready`, and sends it to the browser in the page payload, without the session token. `useUserSession()` starts from it, so a signed-in page renders signed in on the server and does not flash signed out while Better Auth loads. A call outside a component, such as in a plugin or a route middleware, cannot make the server wait, so on the server it starts pending unless the page guard already read the session. To protect a page, use the `auth` page guard. A request without a session cookie skips the lookup, so pages for signed-out visitors do not load Better Auth. A prerendered or cached page was rendered without the visitor's cookie, so its session counts as unknown.
489
+ In Nuxt, the server reads the session only for a page that needs it: a page with an `auth` guard, or a page whose components call `useUserSession()` or `useAbility()`, or render `<AuthPermission>`. It reads the session once for each page request, waits for it before it renders those components, settles their refs as soon as it has the session, so an async `setup()` can wait for `ready`, and sends it to the browser in the page payload, without the session token. `useUserSession()` starts from it, so a signed-in page renders signed in on the server and does not flash signed out while Better Auth loads. A call outside a component, such as in a plugin or a route middleware, cannot make the server wait, so on the server it starts pending unless the page guard already read the session. To protect a page, use the `auth` page guard. A request without a session cookie skips the lookup, so pages for signed-out visitors do not load Better Auth. A prerendered or cached page was rendered without the visitor's cookie, so its session counts as unknown.
488
490
 
489
- The browser downloads Better Auth's client only when the page uses it. The Auth composables come the same way: with a page that calls them or renders `<Can>`, or when the browser opens a page with an `auth` guard. The Auth plugin in the app entry is about 2 KB gzipped. Nuxt prefetches neither on other pages.
491
+ The browser downloads Better Auth's client only when the page uses it. The Auth composables come the same way: with a page that calls them or renders `<AuthPermission>`, or when the browser opens a page with an `auth` guard. The Auth plugin in the app entry is about 2 KB gzipped. Nuxt prefetches neither on other pages.
490
492
 
491
493
  The server session lookup, the page guard, and the auto-imported composables use the Auth Definition's `basePath`, below Nuxt's `app.baseURL`.
492
494
 
@@ -511,7 +513,8 @@ const { data: sessions } = await useAsyncData("sessions", async () => {
511
513
  | `'user'` or `true` | Visitors with a session | `access.signIn` (default `/login`), with `?redirect=<the page>`. A provider opens `<basePath>/sign-in`. |
512
514
  | `'guest'` | Visitors without a session, such as on the login page | `access.afterSignIn` (default `/`) |
513
515
  | `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
514
- | `false` or unset | Everyone | |
516
+ | `false` | Everyone | |
517
+ | Not set | The mode of the most specific `access.pages` pattern, or everyone if no pattern matches | |
515
518
 
516
519
  ```ts
517
520
  // server/auth.ts
@@ -522,12 +525,29 @@ export default defineAuth({
522
525
  })
523
526
  ```
524
527
 
528
+ To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, or `false` in `access.pages`. The Nuxt module reads it at build time and adds the guard to the `appMiddleware` route rule of each pattern, so the server render and navigation in the browser send the visitor to the same page. The most specific pattern wins, `false` removes the guard of a wider pattern, and `definePageMeta({ auth })` of a page wins over all patterns. A key has static segments, `:name`, and a last `/**`. Optional, repeated, and regex params stop the build with `AUTH_PAGE_ROUTES_INVALID`, because Nuxt then orders patterns by position and not by how specific they are. So do two keys that match the same pages, such as keys that differ only in param names, letter case, or percent-encoding.
529
+
530
+ The build also stops with `AUTH_PAGE_ROUTES_INVALID` when `access.pages` applies a `'user'` guard to `access.signIn` or to a `redirectTo` for signed-out visitors. A guest-only page can still redirect signed-in users to a `'user'` page.
531
+
532
+ ```ts
533
+ // server/auth.ts
534
+ import { defineAuth } from "@vite-hub/auth"
535
+
536
+ export default defineAuth({
537
+ access: { pages: { "/dashboard/**": "user", "/dashboard/pricing": false, "/login": "guest" } },
538
+ })
539
+ ```
540
+
541
+ On client navigation, the guard reads the session, so Better Auth can extend an active session and the guard sees each sign-in and sign-out. On the first navigation during hydration, the guard can reuse a signed-in session from the server for the same guarded page, but not for a prerendered or cached page. A signed-out server response still needs a browser read: cookies scoped to the Auth endpoint may not reach the page request. Only the latest navigation decides: when a newer navigation starts before the session read answers, the guard ignores the answer. The guard never redirects a page to itself.
542
+
525
543
  On client navigation, the guard reads the session into the same state as `useUserSession()`. When the guard finds that the session ended, such as after a sign-out in another tab, every component shows the visitor as signed out before the redirect.
526
544
 
527
545
  The guard runs when the route changes. On a `'user'` page, `signOut()` of `useUserSession()` sends the visitor to its sign-in page, with `?redirect=<the page>`. `redirectTo` takes priority. With provider sign-in and no `redirectTo`, Nuxt shows a signed-out page instead of starting OAuth again: even `/` might be protected. Pass `signOut({ redirectTo: '/goodbye' })` to send the visitor to a public page of your choice. Other pages stay open by default.
528
546
 
529
547
  The page guard decides where the browser goes. Protect data in server routes with `withAuth()`, `requireAuth()`, or `access.routes`. Read [Protect pages in Nuxt](https://vitehub.dev/docs/auth/protect-pages) for the full task.
530
548
 
549
+ The Nitro build fails with `AUTH_GUARDED_PAGE_CACHED` when a route rule caches or prerenders a page that `definePageMeta({ auth })` guards: `swr`, `cache`, `isr`, `prerender`, or `static`. The page guard runs when the server renders the page, so a cached page serves the render of one visitor to all visitors. Set `cache: false` or `prerender: false` on the guarded pattern to turn off a wider rule. The check reads `<page>/_payload.json` as a separate path, so use a pattern such as `'/dashboard/**'` that matches the page and its payload. A public page with a static path, such as `/users/public`, may be cached when the route rule key is that exact path or its `/_payload.json`. A guest page, such as the login page, may be prerendered, and a path with `ssr: false` is not checked. With `access.pages`, a path whose most specific key is `false` may be cached, and a path whose most specific key is `'guest'` may be prerendered. The check reads `auth` when `definePageMeta()` sets it to a literal value. The module adds `auth` to Nuxt's `experimental.extraPageMetaExtractionKeys` for this.
550
+
531
551
  ## GitHub organization membership
532
552
 
533
553
  `checkGitHubOrgMember(accessToken, org, { cacheMs, timeoutMs })` from `@vite-hub/auth` returns `[undefined, undefined]` only for an active membership. The token needs `read:org`. A pending invitation, a non-2xx response, a network error, or a timeout (default 5 seconds) returns `[error, undefined]`, so the app can say why access failed. There is no cache by default. With `cacheMs`, a successful check is kept in memory for that time per token and organization, under a SHA-256 key.
@@ -628,6 +648,10 @@ Apps that install `vite-hub` call `hub.signIn()` from `setupViteHubTest()`. In a
628
648
  - Protect application routes and the Console endpoint explicitly. Authentication proves a session; application-owned `authorize` callbacks define roles and permissions.
629
649
  - Keep automatic `/api/auth/**` exposure enabled unless the host mounts the stable handler itself, and verify the chosen `basePath` on both server and client.
630
650
 
651
+ ## Auth outcomes in request logs
652
+
653
+ With the evlog Nitro module registered, each request's wide event gets an `auth` field: `{ outcome, path?, provider?, status?, code?, userId? }`. `outcome` is `success` for a completed sign-in or sign-up, `failure` for a Better Auth error, such as a failed OAuth callback that the browser only sees as a redirect with `?error=`, and `refused` for a refusal of an Auth guard. `code` is Better Auth's error code, the OAuth `error`, or `SIGNED_OUT` / `FORBIDDEN`. Better Auth's warnings and errors also go on the event; the app's own `logger` option still gets every message. The event never holds an email address, a token, or a URL query. Without evlog, nothing is set. See [Server API](https://vitehub.dev/docs/auth/server-api#see-auth-outcomes-on-each-request).
654
+
631
655
  ## Passwords in a WebContainer
632
656
 
633
657
  In a StackBlitz WebContainer, every `node:crypto` `scrypt` call fails. There, Auth sets `emailAndPassword.password` to the scrypt of `@noble/hashes`, with Better Auth's default parameters and `salt:key` format. A hash made on another host verifies in the WebContainer, and the other way around. Auth logs one `[vitehub] Auth hashes passwords with the scrypt of @noble/hashes` line when it first builds its options. Hashing is slower (about 3 seconds per sign-up or sign-in). A `hash` or `verify` function in the Auth Definition always wins. Other hosts keep Better Auth's default.
@@ -1,4 +1,4 @@
1
- import { B as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-CruflEFI.js";
1
+ import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-gl-myjZc.js";
2
2
  //#region src/abilities.d.ts
3
3
  /** A 4xx status that a rule can refuse with. `403` is the default. */
4
4
  type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
@@ -75,7 +75,7 @@ type RefusalOf<Verdict> = Verdict extends false ? {
75
75
  details: undefined;
76
76
  } : never;
77
77
  /**
78
- * Each way a rule can refuse, as `<Can>` passes it to the `#denied` slot and the server error puts it in `data`.
78
+ * Each way a rule can refuse, as `<AuthPermission>` passes it to the `#denied` slot and the server error puts it in `data`.
79
79
  * A signed-out visitor gets `signed-out` from every rule that is not open to guests.
80
80
  *
81
81
  * @example
@@ -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-CbmTAoS_.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-9jC7iuN0.js";
2
2
  export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
@@ -8,7 +8,7 @@ interface AbilityCheckRefusal {
8
8
  }
9
9
  //#endregion
10
10
  //#region src/ability-error.d.ts
11
- /** The code and details of a refusal, as the error body's `data` and the `#denied` slot of `<Can>` carry them. */
11
+ /** The code and details of a refusal, as the error body's `data` and the `#denied` slot of `<AuthPermission>` carry them. */
12
12
  interface AbilityErrorData {
13
13
  code?: string;
14
14
  details?: unknown;
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
2
  import { HTTPError } from "nitro/h3";
3
3
  //#region src/ability-check.ts
4
4
  const signedOut = Object.freeze({
@@ -0,0 +1,96 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ //#region src/shared.ts
3
+ const defaultAuthBasePath = "/api/auth";
4
+ function normalizeAuthBasePath(value) {
5
+ const path = value?.trim() || defaultAuthBasePath;
6
+ if (!path.startsWith("/")) throw authErrorDiagnostics.AUTH_R0013({ message: "`defineAuth()` basePath must start with `/`." });
7
+ const normalized = path.replace(/\/+$/g, "");
8
+ if (!normalized) throw authErrorDiagnostics.AUTH_R0013({ message: "`defineAuth()` basePath must resolve to a non-empty path." });
9
+ return normalized;
10
+ }
11
+ //#endregion
12
+ //#region src/access-pages.ts
13
+ /**
14
+ * Normalizes a path as Nuxt does before it matches route rules: it decodes percent-encoding and, unless the router is
15
+ * case sensitive, folds each UTF-16 code unit to the lower case of its upper case. That is how a Vue Router path regular
16
+ * expression with the `i` flag and without `u` compares characters, so `σ`, `ς`, and `Σ` match.
17
+ */
18
+ function normalizePagePath(path, sensitive = false) {
19
+ const decoded = decodePath(path);
20
+ if (sensitive) return decoded;
21
+ return decoded.replace(/[A-Z]+|[^\0-\x7F]/g, (char) => {
22
+ if (char.charCodeAt(0) < 128) return char.toLowerCase();
23
+ const upper = char.toUpperCase();
24
+ if (upper.length !== 1 || upper.charCodeAt(0) < 128) return char;
25
+ const lower = upper.toLowerCase();
26
+ return lower.length === 1 && lower.toUpperCase() === upper ? lower : upper;
27
+ });
28
+ }
29
+ /** Nuxt keeps a path that `decodeURI()` rejects as it is. */
30
+ function decodePath(path) {
31
+ try {
32
+ return decodeURI(path);
33
+ } catch {
34
+ return path;
35
+ }
36
+ }
37
+ /** Nuxt orders matches by their segments from the left: a static segment, then `:name` or `*`, then `**`. */
38
+ function segmentRank(segment) {
39
+ if (segment === void 0) return 3;
40
+ if (segment.startsWith("**")) return 0;
41
+ return segment.startsWith(":") || segment === "*" ? 1 : 2;
42
+ }
43
+ /** True when the pattern `a` wins over the pattern `b` on every path that both match. */
44
+ function accessPageBeats(a, b) {
45
+ const left = a.split("/").slice(1);
46
+ const right = b.split("/").slice(1);
47
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
48
+ const order = segmentRank(left[index]) - segmentRank(right[index]);
49
+ if (order) return order > 0;
50
+ }
51
+ return false;
52
+ }
53
+ /** Finds the winning key in Nuxt's merge order: ordinary matches, then new matches through encoded slashes. */
54
+ async function createAccessPageMatcher(pages, sensitive = false) {
55
+ const { addRoute, createRouter, findAllRoutes } = await import("rou3");
56
+ const router = createRouter();
57
+ for (const key of Object.keys(pages)) addRoute(router, "", normalizePagePath(key, sensitive), key);
58
+ const match = (path) => {
59
+ const normalized = normalizePagePath(path, sensitive).replace(/[\0-\x20"#<>^`{}\x7F-\uFFFC]+/g, (run) => encodeURIComponent(run.replace(/[\uD800-\uDFFF]/gu, "�")));
60
+ return findAllRoutes(router, "", normalized, { params: false }).map((route) => route.data);
61
+ };
62
+ return (path) => {
63
+ const matches = match(path);
64
+ const split = path.replace(/%2f/gi, "/");
65
+ if (split !== path) matches.push(...match(split).filter((key) => !matches.includes(key)));
66
+ return matches.at(-1);
67
+ };
68
+ }
69
+ /** A static segment or `:name`. */
70
+ const pageSegment = /^(?:[^:*?+(){}/]+|:[A-Za-z_]\w*)$/;
71
+ /**
72
+ * Checks `access.pages`. The Nuxt module attaches the page guard to each pattern with an `appMiddleware` route rule,
73
+ * and Nuxt merges the rules of all matching patterns so that the most specific pattern wins.
74
+ *
75
+ * Nuxt orders matches by their segments from the left: a static segment wins over `:name`, which wins over `**`.
76
+ * Optional, repeated, and regex params and duplicate patterns break this order, because Nuxt then orders the matches by
77
+ * position in `routeRules`. A `*` matches one segment in the middle of a pattern but every depth at its end, so
78
+ * `access.pages` does not accept it. Only the patterns that keep the order pass, so a wider pattern never silently
79
+ * replaces a narrower one.
80
+ */
81
+ function assertAuthPages(pages) {
82
+ if (typeof pages !== "object" || pages === null || Array.isArray(pages)) throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access.pages must be an object of route patterns." });
83
+ const shapes = /* @__PURE__ */ new Map();
84
+ for (const [path, mode] of Object.entries(pages)) {
85
+ const invalid = (reason) => authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(path)}: ${JSON.stringify(mode)}. ${reason}` });
86
+ if (mode !== "user" && mode !== "guest" && mode !== false) throw invalid("A value must be 'user', 'guest', or false.");
87
+ const segments = path.split("/").slice(1);
88
+ if (!path.startsWith("/") || path !== "/" && !segments.every((segment, index) => pageSegment.test(segment) || segment === "**" && index === segments.length - 1)) throw invalid("A key must start with `/` and have only static segments, `:name`, and a last `**`.");
89
+ const shape = segments.map((segment) => segment.startsWith(":") ? ":" : normalizePagePath(segment)).join("/");
90
+ const same = shapes.get(shape);
91
+ if (same !== void 0) throw invalid(`It matches the same pages as ${JSON.stringify(same)}. Keep one of them.`);
92
+ shapes.set(shape, path);
93
+ }
94
+ }
95
+ //#endregion
96
+ export { normalizeAuthBasePath as a, normalizePagePath as i, assertAuthPages as n, createAccessPageMatcher as r, accessPageBeats as t };
package/dist/agent.js CHANGED
@@ -1,7 +1,7 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DmqWq6kj.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DWIyCCJO.js";
3
3
  import { t as isRecord } from "./object-Da1zyPCR.js";
4
- import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DVzjOKc7.js";
4
+ import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-CZmZS5QF.js";
5
5
  import { ViteHubError } from "@vite-hub/runtime";
6
6
  //#region src/agent.ts
7
7
  let server;
@@ -1,23 +1,23 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DmqWq6kj.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DWIyCCJO.js";
3
3
  import { t as isRecord } from "./object-Da1zyPCR.js";
4
4
  import { n as authRequestEvent, t as authCloudflareEnv } from "./request-z6DHHmrb.js";
5
- import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-DdlsS8kJ.js";
6
- import { i as resetAuth, n as getAuthRuntimeState, t as authProcessMemoryDatabase } from "./runtime-state-ojQCzKOc.js";
7
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DCfuicoo.js";
5
+ import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-Cl3hFRjk.js";
6
+ import { i as resetAuth, n as getAuthRuntimeState, r as isAuthProcessMemoryDatabase, t as authProcessMemoryDatabase } from "./runtime-state-ojQCzKOc.js";
7
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DJmO9a9I.js";
8
8
  import { i as resolveAuthMountPath } from "./application-path-DuTpfGFj.js";
9
- import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
10
- import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-DpOVjUti.js";
11
- import { t as assertAuthDatabaseNames } from "./database-schema-options-Sk-1Bvyu.js";
12
- import { a as validateDeleteAccount, i as createDeleteAccount, o as validateAuthEvents, r as validateAuthAccessPolicy, s as applyAuthPreset, t as assertNoRuntimeOption } from "./definition-BCaLA9kW.js";
9
+ import { a as normalizeAuthBasePath } from "./access-pages-FNQTyGRD.js";
10
+ import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-CcjUG-us.js";
11
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-CTKCAfqW.js";
12
+ import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-BFT9T6In.js";
13
13
  import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-l4eyj53D.js";
14
14
  import { resolvePublicUrl } from "@vite-hub/runtime";
15
15
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
16
16
  import { AsyncLocalStorage } from "node:async_hooks";
17
- import { createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sensitiveSessionMiddleware } from "better-auth/api";
17
+ import { createAuthEndpoint, createAuthMiddleware, getOAuthState, getSessionFromCtx, isAPIError, sensitiveSessionMiddleware } from "better-auth/api";
18
18
  import { getCookies } from "better-auth/cookies";
19
19
  import { getAuthTables } from "better-auth/db";
20
- import { APIError as APIError$1, betterAuth, isRequestLike, resolveBaseURL } from "better-auth";
20
+ import { APIError as APIError$1, betterAuth, createLogger, isRequestLike, resolveBaseURL } from "better-auth";
21
21
  import { memoryAdapter } from "better-auth/adapters/memory";
22
22
  import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
23
23
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
@@ -140,12 +140,178 @@ function deriveAuthSecret(event) {
140
140
  return derived.secret;
141
141
  }
142
142
  //#endregion
143
- //#region src/event-plugin.ts
143
+ //#region ../internal/src/runtime/request-log.ts
144
+ function isRequestLog(value) {
145
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
146
+ }
147
+ function contextLog(value) {
148
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
149
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
150
+ }
151
+ /**
152
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
153
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
154
+ */
155
+ function requestLog(input) {
156
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
157
+ return isRequestLog(log) ? log : void 0;
158
+ }
159
+ //#endregion
160
+ //#region src/request-log.ts
144
161
  const authHandlerEvent = new AsyncLocalStorage();
145
- /** Run a Better Auth handler with the request event that `events.authorize` gets. */
162
+ const recorded = /* @__PURE__ */ new WeakSet();
163
+ /** Run a Better Auth handler with the request event that endpoints, hooks, and the logger get. */
146
164
  function runWithAuthEvent(event, run) {
147
165
  return authHandlerEvent.run(event, run);
148
166
  }
167
+ /** The request event of the running `handleAuthRequest()`. */
168
+ function currentAuthEvent() {
169
+ return authHandlerEvent.getStore();
170
+ }
171
+ function requestOf(ctx) {
172
+ return currentAuthEvent() ?? ctx?.request;
173
+ }
174
+ /** The evlog request logger of the running Auth request, or of the endpoint's Request. */
175
+ function authRequestLog(ctx) {
176
+ return requestLog(requestOf(ctx));
177
+ }
178
+ /** Sets the `auth` field of a request's wide event. Without evlog, it does nothing. */
179
+ function setAuthOutcome(request, outcome) {
180
+ const log = requestLog(request);
181
+ if (!log || !request) return;
182
+ recorded.add(request);
183
+ log.set({ auth: outcome });
184
+ }
185
+ /**
186
+ * Sets `auth` from a Better Auth response when no endpoint set it, such as a refusal of Better Auth's rate limit or
187
+ * origin check. The code comes from Better Auth's JSON error body.
188
+ */
189
+ async function setAuthResponseOutcome(request, response) {
190
+ if (response.status < 400 || recorded.has(request) || !requestLog(request)) return;
191
+ let code;
192
+ if (response.headers.get("content-type")?.includes("json")) {
193
+ const body = await response.clone().json().catch(() => void 0);
194
+ code = errorCode(body !== null && typeof body === "object" ? Reflect.get(body, "code") : void 0);
195
+ }
196
+ setAuthOutcome(request, {
197
+ outcome: "failure",
198
+ status: response.status,
199
+ ...code ? { code } : {}
200
+ });
201
+ }
202
+ function errorCode(value) {
203
+ return typeof value === "string" && /^[\w.-]{1,100}$/.test(value) ? value : void 0;
204
+ }
205
+ const signInPath = /^\/(?:sign-in|sign-up|callback|oauth2\/callback|magic-link\/verify|passkey\/verify-authentication|siwe\/verify|two-factor\/verify-|email-otp\/verify-email)/;
206
+ function provider(ctx) {
207
+ const path = ctx.path ?? "";
208
+ const value = path.startsWith("/callback/") || path.startsWith("/oauth2/callback/") ? ctx.params?.id ?? ctx.params?.providerId : ctx.body !== null && typeof ctx.body === "object" ? Reflect.get(ctx.body, "provider") : void 0;
209
+ return typeof value === "string" && ctx.context.socialProviders.some((entry) => entry.id === value) ? value : void 0;
210
+ }
211
+ async function redirectError(ctx, headers) {
212
+ if (ctx.path !== "/callback/:id" && ctx.path !== "/oauth2/callback/:providerId") return void 0;
213
+ if (ctx.path === "/callback/:id" && ctx.method === "POST") return void 0;
214
+ const location = headers ? new Headers(headers).get("location") : null;
215
+ if (!location) return void 0;
216
+ const { baseURL, options } = ctx.context;
217
+ const state = await getOAuthState();
218
+ try {
219
+ const target = new URL(location, baseURL);
220
+ if (state && [state.callbackURL, state.newUserURL].some((url) => url && new URL(url, baseURL).href === target.href)) return void 0;
221
+ const errorPage = new URL(state?.errorURL || options.onAPIError?.errorURL || `${baseURL}/error`, baseURL);
222
+ const prefix = errorPage.search.endsWith("&") || !errorPage.search ? errorPage.search || "?" : `${errorPage.search}&`;
223
+ if (target.origin !== errorPage.origin || target.pathname !== errorPage.pathname || !target.search.startsWith(`${prefix}error=`)) return void 0;
224
+ return errorCode(new URLSearchParams(target.search.slice(prefix.length)).get("error"));
225
+ } catch {
226
+ return;
227
+ }
228
+ }
229
+ async function endpointOutcome(ctx, createdUserId) {
230
+ const path = ctx.path ?? "";
231
+ const oauthProvider = provider(ctx);
232
+ const fields = {
233
+ path,
234
+ ...oauthProvider ? { provider: oauthProvider } : {}
235
+ };
236
+ const returned = Reflect.get(ctx.context, "returned");
237
+ const redirect = isAPIError(returned) && returned.status === "FOUND";
238
+ if (isAPIError(returned) && !redirect) {
239
+ const code = errorCode(returned.body?.code);
240
+ return {
241
+ ...fields,
242
+ outcome: "failure",
243
+ status: returned.statusCode,
244
+ ...code ? { code } : {}
245
+ };
246
+ }
247
+ const session = ctx.context.newSession;
248
+ if (session && signInPath.test(path)) return {
249
+ ...fields,
250
+ outcome: "success",
251
+ userId: session.user.id
252
+ };
253
+ const oauthError = redirect ? await redirectError(ctx, returned.headers) : void 0;
254
+ if (oauthError) return {
255
+ ...fields,
256
+ outcome: "failure",
257
+ status: 302,
258
+ code: oauthError
259
+ };
260
+ if (createdUserId && !redirect) return {
261
+ ...fields,
262
+ outcome: "success",
263
+ userId: createdUserId
264
+ };
265
+ }
266
+ /** Sets the outcome of each Better Auth endpoint on the request's wide event. */
267
+ function createRequestLogPlugin() {
268
+ const signUps = /* @__PURE__ */ new WeakMap();
269
+ return {
270
+ id: "vitehub-request-log",
271
+ init: () => ({ options: { databaseHooks: { user: { create: { async after(user, ctx) {
272
+ const request = requestOf(ctx);
273
+ if (ctx?.path === "/sign-up/email" && request && requestLog(request)) signUps.set(request, user.id);
274
+ } } } } } }),
275
+ hooks: { after: [{
276
+ matcher: () => true,
277
+ handler: createAuthMiddleware(async (ctx) => {
278
+ const request = requestOf(ctx);
279
+ if (!requestLog(request)) return;
280
+ const outcome = await endpointOutcome(ctx, request && signUps.get(request));
281
+ if (outcome) setAuthOutcome(request, outcome);
282
+ })
283
+ }] }
284
+ };
285
+ }
286
+ function scrub(text) {
287
+ return /^(Invalid (?:origin|callbackURL|redirectURL|errorCallbackURL|newUserCallbackURL|redirect URL)):/i.exec(text)?.[1] ?? text.replace(/\bhttps?:\/\/[^\s"'`<>]+/gi, "[url]").replace(/[?#][^\s"'`<>]*/g, "").replace(/[^\s"'`<>@]+(?:@|%40)[^\s"'`<>@]+\.[a-z]{2,}/gi, "[email]").slice(0, 500);
288
+ }
289
+ /**
290
+ * Better Auth's `logger` that also writes warnings and errors to the request's wide event. The app's own `log`, or
291
+ * Better Auth's console output, still gets every message. Only the message goes on the event: the other arguments can
292
+ * hold provider responses.
293
+ */
294
+ function withRequestLogger(logger) {
295
+ let fallback;
296
+ return {
297
+ ...logger,
298
+ log(level, message, ...args) {
299
+ const log = level === "warn" || level === "error" ? authRequestLog() : void 0;
300
+ if (log) {
301
+ const text = `[Better Auth] ${scrub(message)}`;
302
+ if (level === "warn") log.warn(text);
303
+ else log.error(text);
304
+ }
305
+ if (logger?.log) logger.log(level, message, ...args);
306
+ else (fallback ??= createLogger({
307
+ ...logger,
308
+ log: void 0
309
+ }))[level](message, ...args);
310
+ }
311
+ };
312
+ }
313
+ //#endregion
314
+ //#region src/event-plugin.ts
149
315
  function record(value) {
150
316
  return value !== null && typeof value === "object" ? value : {};
151
317
  }
@@ -204,7 +370,10 @@ function createAuthEventsPlugin(options) {
204
370
  try {
205
371
  await options.store.append(event);
206
372
  } catch {
207
- console.warn("[vitehub] AUTH_EVENT_WRITE_FAILED: Could not record an auth event.");
373
+ const message = "AUTH_EVENT_WRITE_FAILED: Could not record an auth event.";
374
+ const log = authRequestLog(ctx);
375
+ if (log) log.warn(`[vitehub] ${message}`, { authEvent: { type } });
376
+ else console.warn(`[vitehub] ${message}`);
208
377
  return false;
209
378
  }
210
379
  if (options.onEvent) await notify(options.onEvent, event, ctx);
@@ -212,18 +381,20 @@ function createAuthEventsPlugin(options) {
212
381
  }
213
382
  /** Hand the callback to the host `waitUntil()` when it has one, so it does not delay the response. Else wait for it. */
214
383
  async function notify(onEvent, event, ctx) {
384
+ const request = currentAuthEvent() ?? (ctx?.request ? authRequestEvent(ctx.request) : void 0);
385
+ const waitUntil = request ? getStandardContext(request).waitUntil : void 0;
386
+ const log = waitUntil ? void 0 : authRequestLog(ctx);
215
387
  const task = (async () => {
216
388
  try {
217
389
  await onEvent(event);
218
390
  } catch (error) {
219
- console.error(authErrorDiagnostics.AUTH_EVENT_CALLBACK_FAILED({
391
+ if (log) log.error("AUTH_EVENT_CALLBACK_FAILED: Auth event callback failed.", { authEvent: { type: event.type } });
392
+ else console.error(authErrorDiagnostics.AUTH_EVENT_CALLBACK_FAILED({
220
393
  type: event.type,
221
394
  cause: error
222
395
  }));
223
396
  }
224
397
  })();
225
- const request = authHandlerEvent.getStore() ?? (ctx?.request ? authRequestEvent(ctx.request) : void 0);
226
- const waitUntil = request ? getStandardContext(request).waitUntil : void 0;
227
398
  if (waitUntil) try {
228
399
  waitUntil(task);
229
400
  return;
@@ -408,7 +579,7 @@ function createAuthEventsPlugin(options) {
408
579
  }, async (ctx) => {
409
580
  if (!ctx.request) throw new APIError$1("FORBIDDEN");
410
581
  const authorization = await options.authorize({
411
- event: authHandlerEvent.getStore() ?? authRequestEvent(ctx.request),
582
+ event: currentAuthEvent() ?? authRequestEvent(ctx.request),
412
583
  request: ctx.request,
413
584
  user: ctx.context.session.user,
414
585
  session: ctx.context.session.session
@@ -714,6 +885,23 @@ function optionsKey(value) {
714
885
  return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
715
886
  }
716
887
  //#endregion
888
+ //#region src/site-roles.ts
889
+ /**
890
+ * The `user.role` field of Better Auth's `admin()` plugin, without its endpoints. Site access keeps the roles it gives in
891
+ * this field, and Comments and the Console page tool read them from the session user. Users cannot set it.
892
+ *
893
+ * Auth adds it without `admin()` only where Auth owns the user table, `authDatabase()` and the memory database, because
894
+ * Better Auth refuses every request when a declared field has no column.
895
+ */
896
+ const siteRolesPlugin = {
897
+ id: "vitehub-site-roles",
898
+ schema: { user: { fields: { role: {
899
+ type: "string",
900
+ required: false,
901
+ input: false
902
+ } } } }
903
+ };
904
+ //#endregion
717
905
  //#region src/runtime-options.ts
718
906
  /** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
719
907
  function isAuthDatabasePlacement(value) {
@@ -764,17 +952,16 @@ function withRateLimitDefaults(options, ownsDatabase) {
764
952
  }
765
953
  /**
766
954
  * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
767
- * send. Auth gives it the address that the host reports instead. With `trustedProxyHeaders`, the proxy address is the
768
- * peer, so `X-Forwarded-For` comes first.
955
+ * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
956
+ * `vitehub({ trustProxy: true })` makes that address the last `X-Forwarded-For` value, which the proxy adds.
769
957
  */
770
958
  function withClientAddressHeaders(advanced) {
771
959
  if (advanced?.ipAddress?.ipAddressHeaders) return advanced;
772
- const ipAddressHeaders = advanced?.trustedProxyHeaders ? ["x-forwarded-for", clientAddressHeader] : [clientAddressHeader];
773
960
  return {
774
961
  ...advanced,
775
962
  ipAddress: {
776
963
  ...advanced?.ipAddress,
777
- ipAddressHeaders
964
+ ipAddressHeaders: [clientAddressHeader]
778
965
  }
779
966
  };
780
967
  }
@@ -803,7 +990,7 @@ function readProviderEnvironment(options, event) {
803
990
  }
804
991
  function stripViteHubOptions(definition, options, environment) {
805
992
  validateDeleteAccount(options);
806
- const { access, adminClaim: _adminClaim, console: _console, database, deleteAccount, events, route: _route, secondaryStorage, ...rest } = applyAuthPreset(options);
993
+ const { access, adminClaim: _adminClaim, components, console: _console, database, deleteAccount, events, route: _route, secondaryStorage, ...rest } = applyAuthPreset(options);
807
994
  if (isAuthDatabasePlacement(database)) throw authErrorDiagnostics.AUTH_C0061({ message: "Auth `database` must be a Better Auth adapter, such as `authDatabase()`. `true` and `{ name }` do not create storage, so users and sessions would stay in memory." });
808
995
  if (isAuthSecondaryStoragePlacement(secondaryStorage)) throw authErrorDiagnostics.AUTH_C0062({ message: "Auth `secondaryStorage` must be a Better Auth adapter. `true` and `{ store }` do not create storage." });
809
996
  const memory = database === "memory";
@@ -816,6 +1003,7 @@ function stripViteHubOptions(definition, options, environment) {
816
1003
  assertAuthDatabaseNames(rest);
817
1004
  }
818
1005
  validateAuthEvents(events);
1006
+ validateAuthComponents(components);
819
1007
  const sessionRefresh = withSessionRefresh(rest, Boolean(storage.database || storage.secondaryStorage));
820
1008
  if (!storage.database && options.preset === void 0) {
821
1009
  if (!memory && !isDevelopmentServer()) throw authMemoryDatabaseError();
@@ -826,6 +1014,7 @@ function stripViteHubOptions(definition, options, environment) {
826
1014
  if (policy && !storage.database && !storage.secondaryStorage) throw authErrorDiagnostics.AUTH_C0066({ message: "`defineAuth()` access.policy needs a Better Auth `database` or `secondaryStorage` adapter. A session that lives only in a cookie cannot be ended." });
827
1015
  const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
828
1016
  const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
1017
+ const siteRoles = !impersonation && !Object.hasOwn(rest.user?.additionalFields ?? {}, "role") && !declaredPlugins.some((plugin) => Object.hasOwn(plugin.schema?.user?.fields ?? {}, "role")) && (authDatabaseName(database) !== void 0 || isAuthProcessMemoryDatabase(storage.database));
829
1018
  const { admins, adminClaim, members } = environment;
830
1019
  assertMembersSessionStore(members, Boolean(storage.database || storage.secondaryStorage));
831
1020
  const membersGate = members.length ? createMembersGate(members, admins, declaredPlugins) : void 0;
@@ -836,6 +1025,7 @@ function stripViteHubOptions(definition, options, environment) {
836
1025
  ...declaredPlugins,
837
1026
  ...accountDeletion ? [accountDeletion.plugin] : [],
838
1027
  ...impersonation ? [createImpersonationPlugin()] : [],
1028
+ ...siteRoles ? [siteRolesPlugin] : [],
839
1029
  ...adminsPlugin ? [adminsPlugin] : [],
840
1030
  ...adminClaimPlugin ? [adminClaimPlugin] : [],
841
1031
  ...policy || membersGate ? [createAccessPolicyPlugin({
@@ -865,7 +1055,12 @@ function stripViteHubOptions(definition, options, environment) {
865
1055
  storeInDatabase: true
866
1056
  } } : {},
867
1057
  ...databaseHooks ? { databaseHooks } : {},
868
- plugins: eventPlugin ? [...plugins, eventPlugin] : plugins,
1058
+ plugins: [
1059
+ ...plugins,
1060
+ ...eventPlugin ? [eventPlugin] : [],
1061
+ createRequestLogPlugin()
1062
+ ],
1063
+ logger: withRequestLogger(rest.logger),
869
1064
  advanced: withClientAddressHeaders(rest.advanced),
870
1065
  rateLimit,
871
1066
  ...eventPlugin ? { hooks: {
@@ -1110,6 +1305,13 @@ function resolveDefaultDefinition() {
1110
1305
  if (!definitionForApp) throw authErrorDiagnostics.AUTH_R0005({ message: "[vitehub] No Auth Definition was discovered. Add `server/auth.ts` or `server.auth.ts`." });
1111
1306
  return definitionForApp;
1112
1307
  }
1308
+ async function findVerifiedAuthUserId(email, request) {
1309
+ if (!definitionForApp) return void 0;
1310
+ const context = await authForRequest(request, authRequestEvent(request), definitionForApp).$context;
1311
+ if (!context.options.database) return void 0;
1312
+ const found = await context.internalAdapter.findUserByEmail(email);
1313
+ return found?.user.emailVerified === true && found.user.email.trim().toLowerCase() === email ? found.user.id : void 0;
1314
+ }
1113
1315
  function createBetterAuthOptions(definition) {
1114
1316
  return resolveAuthOptions(definition, { env: envResolverFor(definition) }).providerOptions;
1115
1317
  }
@@ -1172,4 +1374,4 @@ function authForRequest(request, event, definition = resolveDefaultDefinition())
1172
1374
  }));
1173
1375
  }
1174
1376
  //#endregion
1175
- export { requestProvider as a, resolveAuthOptions as c, setRequestClientAddress as d, withClientAddress as f, getAuthForDefinition as i, trustsProxyHeaders as l, forwardedRequestOrigin as m, createBetterAuthOptions as n, resolveDefaultDefinition as o, runWithAuthEvent as p, envResolverFor as r, withSessionMarker as s, authForRequest as t, eventClientAddress as u };
1377
+ export { forwardedRequestOrigin as _, getAuthForDefinition as a, withSessionMarker as c, eventClientAddress as d, setRequestClientAddress as f, setAuthResponseOutcome as g, setAuthOutcome as h, findVerifiedAuthUserId as i, resolveAuthOptions as l, runWithAuthEvent as m, createBetterAuthOptions as n, requestProvider as o, withClientAddress as p, envResolverFor as r, resolveDefaultDefinition as s, authForRequest as t, trustsProxyHeaders as u };