@vite-hub/auth 0.6.1 → 0.7.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 (64) hide show
  1. package/README.md +28 -7
  2. package/dist/{abilities-BYOcyQ9B.d.ts → abilities-CfvuGrBv.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-OKoyOwPM.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-Bej95blM.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +25 -6
  8. package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-5RSiFTDC.js} +145 -57
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Bg_PAl7e.js} +5 -3
  13. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-XcplYv4R.d.ts} +1 -1
  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-B87hDU4j.js → database-options-DE9lMwu1.js} +1 -1
  18. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-CCQsNhjc.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BypPLIbI.js → definition-DeEeqTLC.js} +18 -4
  22. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DkzL9ltR.js} +13 -4
  23. package/dist/{events-BXU1_9mc.js → events-BUaoHFoC.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +3 -3
  28. package/dist/internal/server.js +5 -4
  29. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-DG1jmw4o.d.ts} +1 -0
  30. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-DgveSGEl.js} +26 -8
  31. package/dist/mcp.d.ts +1 -1
  32. package/dist/mcp.js +2 -2
  33. package/dist/{members-CwPIx10t.js → members-CRlYyxVk.js} +188 -152
  34. package/dist/nuxt.d.ts +1 -1
  35. package/dist/nuxt.js +27 -14
  36. package/dist/{own-access-BNcxKrDl.d.ts → own-access-BvVUjaeL.d.ts} +1 -1
  37. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/roles-BGi8CyBG.js +17 -0
  40. package/dist/runtime/console.d.ts +1 -1
  41. package/dist/runtime/console.js +2 -2
  42. package/dist/runtime/empty-abilities.d.ts +1 -1
  43. package/dist/runtime/empty-definition.d.ts +1 -1
  44. package/dist/runtime/server.d.ts +2 -2
  45. package/dist/runtime/server.js +5 -3
  46. package/dist/runtime/vue-nuxt.js +27 -11
  47. package/dist/schema.js +1 -1
  48. package/dist/{server-C4Kni3Vj.d.ts → server-1G_BbfBD.d.ts} +20 -7
  49. package/dist/{server-BHniJi2m.d.ts → server-B8kTFrHP.d.ts} +3 -2
  50. package/dist/{server-Iru6jcnW.js → server-iQNOXyfS.js} +49 -22
  51. package/dist/server.d.ts +5 -2
  52. package/dist/server.js +9 -3
  53. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-DN0svCKj.js} +2 -2
  54. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-CMB3t4NF.js} +1 -1
  55. package/dist/{table-specs-CCSY4tiS.js → table-specs-C3-bLOSF.js} +1 -1
  56. package/dist/test.d.ts +1 -1
  57. package/dist/test.js +2 -2
  58. package/dist/{types-DmH31d2t.d.ts → types-BmRGse4l.d.ts} +21 -5
  59. package/dist/{vite-CpWhT1Wi.js → vite-GRzej8Cs.js} +58 -17
  60. package/dist/vite.d.ts +18 -3
  61. package/dist/vite.js +1 -1
  62. package/dist/vue.d.ts +2 -2
  63. package/dist/vue.js +1 -1
  64. package/package.json +9 -8
package/README.md CHANGED
@@ -72,6 +72,15 @@ export default defineAuth({
72
72
  });
73
73
  ```
74
74
 
75
+ ```bash
76
+ pnpm add @vite-hub/database
77
+ pnpm add -D drizzle-kit@1.0.0-rc.6
78
+ pnpm vitehub database generate
79
+ pnpm vitehub database migrate
80
+ ```
81
+
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
+
75
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`.
76
85
 
77
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.
@@ -98,9 +107,9 @@ Pass `deleteAccount: { beforeDelete }` to delete the app's own rows first, or th
98
107
 
99
108
  ## First admin
100
109
 
101
- `VITEHUB_ADMINS` is a comma-separated list of social accounts, each `<provider>:<account id>`, such as `github:22072217`. When a listed account signs in or is linked, its user gets the first `adminRoles` entry of Better Auth's `admin()` plugin (`admin` by default), in place of the default role. Removing an entry does not remove the role. Without `admin()`, Auth fails with `AUTH_C0051`. The Auth Console lists the rule in its access notes. Emails are refused (`AUTH_C0058`), because a password sign-up does not prove email ownership. The removed `VITEHUB_ADMIN_EMAILS` fails with `AUTH_C0057`.
110
+ `VITEHUB_ADMINS` is a comma-separated list of social accounts, each `<provider>:<account id>`, such as `github:22072217`, and emails, such as `ada@example.com`. When a listed account signs in or is linked, or a user with a listed email signs in or verifies it, the user gets the first `adminRoles` entry of Better Auth's `admin()` plugin (`admin` by default), in place of the default role. Removing an entry does not remove the role. Without `admin()`, Auth fails with `AUTH_C0051`. The Auth Console lists the rule in its access notes. An email entry matches only a verified email (`user.emailVerified`), so a password sign-up with the admin's email gets no role until the person opens the verification link. A prefixed email, such as `email:ada@example.com`, fails with `AUTH_C0058`. The removed `VITEHUB_ADMIN_EMAILS` fails with `AUTH_C0057`.
102
111
 
103
- For an app without social sign-in, `vitehub auth claim` prints a one-time code and the `VITEHUB_ADMIN_CLAIM` value (its SHA-256) to set on the host. The first signed-in user who sends it to `POST <auth base>/vitehub/admin-claim` gets the admin role. A row in the `verification` table marks the code as used. A malformed value fails with `AUTH_C0059`.
112
+ For an app without social sign-in or email verification, `vitehub auth claim` prints a one-time code and the `VITEHUB_ADMIN_CLAIM` value (its SHA-256) to set on the host. The first signed-in user who sends it to `POST <auth base>/vitehub/admin-claim` gets the admin role. A row in the `verification` table marks the code as used. A malformed value fails with `AUTH_C0059`.
104
113
 
105
114
  Set `adminClaim: false` on another Auth Definition to make it ignore the host's claim value.
106
115
 
@@ -108,12 +117,14 @@ With a claim code set, Auth sets `verification.storeInDatabase: true`, including
108
117
 
109
118
  ## Members
110
119
 
111
- `VITEHUB_MEMBERS` lets only some people sign up and sign in. It is a comma-separated list of entries: `<provider>:<account id>` (such as `github:22072217`), an email, `@<domain>`, or `github-org:<organization>`. Email and domain entries match only an email that the provider verified. An organization entry adds the `read:org` scope to the GitHub provider and checks the membership with `checkGitHubOrgMember()`. The accounts in `VITEHUB_ADMINS` and users with the admin role always get in.
120
+ `VITEHUB_MEMBERS` lets only some people sign up and sign in. It is a comma-separated list of entries: `<provider>:<account id>` (such as `github:22072217`), an email, `@<domain>`, or `github-org:<organization>`. Email and domain entries match only an email that the provider verified. An organization entry adds the `read:org` scope to the GitHub provider and checks the membership with `checkGitHubOrgMember()`. The accounts and verified emails in `VITEHUB_ADMINS` and users with the admin role always get in.
112
121
 
113
122
  Auth refuses to create a user that no entry lets in, and refuses each new session. A refusal answers `403` with `AUTH_NOT_MEMBER`, or an OAuth redirect with `?error=AUTH_NOT_MEMBER`. The list runs in the same plugin as `access.policy`, so a removed person loses a running session within five minutes and their MCP access tokens stop working. It needs stored sessions (`AUTH_MEMBERS_SESSION_STORE_REQUIRED`). An invalid entry fails with `AUTH_MEMBERS_ENTRY_INVALID`. The Auth Console lists the entries in its access notes, with the number of emails in place of the emails.
114
123
 
115
124
  `checkAuthMember(userId, event?)` from `@vite-hub/auth/server` runs the same rules for code that has a user id but no session, such as an upload ticket. It returns `[undefined, undefined]` for a member or when the variable is not set, `AUTH_NOT_MEMBER` for a refused or unknown user, and `AUTH_GITHUB_UNAVAILABLE` when GitHub cannot answer. A confirmed organization membership is reused for five minutes.
116
125
 
126
+ `hasAuthMembers(context)` from the same entry tells whether an Auth context applies `VITEHUB_MEMBERS`. In a route, pass `await useAuth(request).$context`. In a Better Auth hook, pass `ctx.context`.
127
+
117
128
  ## Sessions without a database
118
129
 
119
130
  `stateless()` keeps each session in an encrypted cookie. Sessions survive restarts and work across replicas and Workers when every instance uses the same secret.
@@ -194,9 +205,11 @@ Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: t
194
205
 
195
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()`.
196
207
 
208
+ 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
+
197
210
  With a provider in `access.signIn`, the Auth route also answers `GET /api/auth/sign-in?redirect=/docs` and `GET /api/auth/sign-out?redirect=/`, below the Auth Base Path. The sign-in path starts `access.signIn` and comes back to `redirect` (default: `access.afterSignIn`, or `/`). A signed-in visitor goes to `redirect` at once. The sign-out path ends the session and goes to `redirect` (default `/`). It refuses a request from another site (`Sec-Fetch-Site` `cross-site` or `same-site`) and a prefetch or prerender (`Sec-Purpose`) with `403`. `redirect` must be a path of the app, below `app.baseURL` like the page guard's `?redirect=`, or the answer is `400`. Without a provider in `access.signIn`, Better Auth answers these paths with `404`.
198
211
 
199
- The generated Nitro middleware starts the provider of `access.signIn` when one of the configured `access.routes` needs a browser redirect. A sign-in page, such as `signIn: "/login"`, is for the Nuxt page guard: server guards answer `401`. Route objects can add an `authorize` callback when a valid session is not sufficient:
212
+ The generated Nitro middleware starts the provider of `access.signIn` when one of the configured `access.routes` needs a browser redirect. A sign-in page, such as `signIn: "/login"`, is for the Nuxt page guard: server guards answer `401`. Route objects can add a `role` or an `authorize` callback when a valid session is not sufficient. `role` is a role name or a list of role names. A signed-in user without one of them gets `403`, and `authorize` runs only after the role check passes. Auth reads `user.role`, where Better Auth's `admin()` plugin stores the roles of a user separated by commas. `hasRole(user, roles)` from `@vite-hub/auth` checks the same rule in app code:
200
213
 
201
214
  ```ts
202
215
  import { defineAuth } from "@vite-hub/auth"
@@ -208,6 +221,7 @@ export default defineAuth({
208
221
  route: "/_vitehub/**",
209
222
  authorize: ({ user }) => user.isAdmin === true,
210
223
  },
224
+ { route: "/api/dashboard/**", role: ["team", "admin"] },
211
225
  ],
212
226
  },
213
227
  });
@@ -284,6 +298,8 @@ export default defineHandler(async (event) => {
284
298
  });
285
299
  ```
286
300
 
301
+ In development, `useAuth(event)` uses the request origin if no Auth URL is configured. Pass the event so that direct API calls can make absolute links, such as password reset links.
302
+
287
303
  ## Session refresh
288
304
 
289
305
  Better Auth extends a stored session when the session passes `session.updateAge`. Use `session.onRefresh` to check the user again at that time, for example against a ban list.
@@ -338,9 +354,11 @@ export { default } from '#vitehub/auth/server'
338
354
 
339
355
  For a manual adapter that creates plain Web `Request` objects, use `createAuthHandler(definition)` from `@vite-hub/auth/server` and call the returned handler as `handler(request, { clientAddress })`. Read `clientAddress` from the host's peer address, such as Node's `incomingMessage.socket.remoteAddress`, never from a client-sent header. Auth uses it for per-client rate limiting and `session.ipAddress`; without it, plain Web requests share an addressless rate-limit bucket. srvx requests already carry their host address as `ip`.
340
356
 
357
+ By default, Auth counts only requests that match a static endpoint. To limit a route with a path parameter, such as `/callback/:id`, set a wildcard in `rateLimit.customRules`, such as `/callback/*`. Each concrete path then gets its own counter.
358
+
341
359
  App Auth loads Better Auth on demand. Nitro imports the Auth route on its first request. The generated access middleware imports `#vitehub/auth/server` only for a request that an access route matches. Generated app Auth startup code imports `@vite-hub/auth/runtime/server`, which has no Better Auth import. Your own code loads Better Auth when it imports `@vite-hub/auth/server`, so import it in routes, not in plugins or global middleware, to keep it out of the startup.
342
360
 
343
- Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback. The callback returns all the options in one object, and Auth does not merge it with other options. `defineAuth()` rejects the removed `runtime` option with `AUTH_C0039`. `access.routes` must be static route strings or `{ authorize, method, route }` objects, and `access.public` static route strings, so the Vite Integration can register Nitro middleware.
361
+ Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback. The callback returns all the options in one object, and Auth does not merge it with other options. `defineAuth()` rejects the removed `runtime` option with `AUTH_C0039`. `access.routes` must be static route strings or `{ authorize, method, role, route }` objects, and `access.public` static route strings, so the Vite Integration can register Nitro middleware.
344
362
 
345
363
 
346
364
  Each access route is a literal path, or a literal path that ends with `/**` to match the path and every path below it. Other pattern syntax (`*`, `:name`, `(`, `{`, `?`), also when percent-encoded such as `%3A`, and `.` or `..` segments fail with `AUTH_C0068`. A route with `method: "GET"` also guards `HEAD`, because H3 runs the GET handler for `HEAD`. The access middleware compares paths after the same normalization as the Nitro router: it decodes needless percent escapes and ignores one trailing slash in requests. Configured routes drop all trailing slashes, as router registration does. `access.routes` must use a dense array. Empty slots, including commented-out entries that leave commas, fail configuration.
@@ -513,6 +531,7 @@ const { data: sessions } = await useAsyncData("sessions", async () => {
513
531
  | `'user'` or `true` | Visitors with a session | `access.signIn` (default `/login`), with `?redirect=<the page>`. A provider opens `<basePath>/sign-in`. |
514
532
  | `'guest'` | Visitors without a session, such as on the login page | `access.afterSignIn` (default `/`) |
515
533
  | `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
534
+ | `{ role }` | Signed-in users with one of the roles | `access.signIn` for visitors without a session. A user without the role gets a 403 error page. |
516
535
  | `false` | Everyone | |
517
536
  | Not set | The mode of the most specific `access.pages` pattern, or everyone if no pattern matches | |
518
537
 
@@ -525,9 +544,9 @@ export default defineAuth({
525
544
  })
526
545
  ```
527
546
 
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.
547
+ To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, `false`, or `{ role }` in `access.pages`. `{ role: ['team', 'admin'] }` works like `'user'` and shows a 403 error page to a signed-in user without one of the roles. The module attaches one `vitehub-auth-role-<i>` middleware for each distinct role. 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
548
 
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.
549
+ An invalid `role`, on a page or a route, fails with `AUTH_ACCESS_ROLE_INVALID`. The build also stops with `AUTH_PAGE_ROUTES_INVALID` when `access.pages` applies a `'user'` or `{ role }` 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
550
 
532
551
  ```ts
533
552
  // server/auth.ts
@@ -616,6 +635,8 @@ export default defineAgent({
616
635
 
617
636
  By default, the Auth Package reads the same-app Better Auth session from the request and maps the Auth User to an Agent Invoker with `kind: "authUser"`. Customize `id`, `kind`, `label`, or `meta` for normal identity shaping, and use `source` or `map` when the Agent consumes JWTs, bearer tokens, OAuth/OIDC provider output, or product-specific identity.
618
637
 
638
+ A run without a request, such as a Schedule or Queue run, has no session. Server code names the Auth user in the input: `runAgent(agent, { prompt, context: { invoker: { id: user.id, kind: "authUser" } } }, { schedule })`. `authenticated()` accepts that Invoker only when the run has no request, and sets `meta.authUserId` from its `id`. It refuses a run without a request that names no Auth user, or another kind of Invoker. `agentAuth.user()` reads `meta.authUserId`, else the `id` of an `authUser` Invoker.
639
+
619
640
  When authentication is required but unavailable, `authenticated()` throws `ViteHubError` with code `AUTHENTICATION_REQUIRED`. HTTP adapters map that code to `401`; the transport status is not part of the error object.
620
641
 
621
642
  ```ts
@@ -1,4 +1,4 @@
1
- import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-DmH31d2t.js";
1
+ import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BmRGse4l.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-BYOcyQ9B.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-CfvuGrBv.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-CUPwukgE.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
2
  import { HTTPError } from "nitro/h3";
3
3
  // src/ability-check.ts
4
4
  const signedOut = Object.freeze({
@@ -1,4 +1,5 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
2
+ import { n as isAuthRole } from "./roles-BGi8CyBG.js";
2
3
  // src/shared.ts
3
4
  const defaultAuthBasePath = "/api/auth";
4
5
  function normalizeAuthBasePath(value) {
@@ -9,6 +10,10 @@ function normalizeAuthBasePath(value) {
9
10
  return normalized;
10
11
  }
11
12
  // src/access-pages.ts
13
+ /** Whether an `access.pages` value needs a signed-in user: `'user'` or `{ role }`. */
14
+ function isUserPage(mode) {
15
+ return mode === "user" || typeof mode === "object" && mode !== null;
16
+ }
12
17
  /**
13
18
  * Normalizes a path as Nuxt does before it matches route rules: it decodes percent-encoding and, unless the router is
14
19
  * case sensitive, folds each UTF-16 code unit to the lower case of its upper case. That is how a Vue Router path regular
@@ -82,7 +87,9 @@ function assertAuthPages(pages) {
82
87
  const shapes = /* @__PURE__ */ new Map();
83
88
  for (const [path, mode] of Object.entries(pages)) {
84
89
  const invalid = (reason) => authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(path)}: ${JSON.stringify(mode)}. ${reason}` });
85
- if (mode !== "user" && mode !== "guest" && mode !== false) throw invalid("A value must be 'user', 'guest', or false.");
90
+ if (typeof mode === "object" && mode !== null && !Array.isArray(mode)) {
91
+ if (Object.keys(mode).some((key) => key !== "role") || !isAuthRole(Reflect.get(mode, "role"))) throw authErrorDiagnostics.AUTH_ACCESS_ROLE_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(path)}: ${JSON.stringify(mode)}. An object value has only \`role\`, a role name or a non-empty list of role names.` });
92
+ } else if (mode !== "user" && mode !== "guest" && mode !== false) throw invalid("A value must be 'user', 'guest', false, or `{ role }`.");
86
93
  const segments = path.split("/").slice(1);
87
94
  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 `**`.");
88
95
  const shape = segments.map((segment) => segment.startsWith(":") ? ":" : normalizePagePath(segment)).join("/");
@@ -91,4 +98,4 @@ function assertAuthPages(pages) {
91
98
  shapes.set(shape, path);
92
99
  }
93
100
  }
94
- export { normalizeAuthBasePath as a, normalizePagePath as i, assertAuthPages as n, createAccessPageMatcher as r, accessPageBeats as t };
101
+ export { normalizePagePath as a, isUserPage as i, assertAuthPages as n, normalizeAuthBasePath as o, createAccessPageMatcher as r, accessPageBeats as t };
package/dist/agent.d.ts CHANGED
@@ -41,9 +41,8 @@ export interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig
41
41
  */
42
42
  export interface AgentAuth {
43
43
  /**
44
- * The Auth user an Invoker stands for. `authenticated()` records the user id as `invoker.meta.authUserId`, and this reads
45
- * that user from the Auth database again, so it also works when an approved tool call runs later. Null for an Invoker
46
- * without `authUserId`, or when the user no longer exists.
44
+ * Reads the Auth user from the database by `invoker.meta.authUserId` or, for an `authUser` Invoker, by its `id`.
45
+ * Returns null when the Invoker does not name an Auth user or the user no longer exists.
47
46
  */
48
47
  user(invoker: AgentInvoker | null | undefined): Promise<AuthenticatedUser | null>;
49
48
  }
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DVfi-nJX.js";
2
- import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-fR6Pv4kD.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
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";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
5
  import { ViteHubError } from "@vite-hub/runtime";
6
6
  // src/agent.ts
@@ -9,9 +9,25 @@ const loadServer = () => server ??= import("./internal/server.js").catch((error)
9
9
  server = void 0;
10
10
  throw error;
11
11
  });
12
- const agentAuth = { async user(invoker) {
12
+ function authUserIdOf(invoker) {
13
13
  const meta = invoker?.meta;
14
- const userId = isRecord(meta) ? readString(meta.authUserId) : void 0;
14
+ return (isRecord(meta) ? readString(meta.authUserId) : void 0) ?? (invoker?.kind === "authUser" ? readString(invoker.id) : void 0);
15
+ }
16
+ function namedAuthUserInvoker(context) {
17
+ const inputContext = context.input?.context;
18
+ if (!isRecord(inputContext) || inputContext.invoker === void 0) return void 0;
19
+ const invoker = context.defaultInvoker;
20
+ const userId = invoker.kind === "authUser" ? readString(invoker.id) : void 0;
21
+ return userId ? {
22
+ ...invoker,
23
+ meta: {
24
+ ...invoker.meta,
25
+ authUserId: userId
26
+ }
27
+ } : void 0;
28
+ }
29
+ const agentAuth = { async user(invoker) {
30
+ const userId = authUserIdOf(invoker);
15
31
  if (!userId) return null;
16
32
  const { getAuth } = await loadServer();
17
33
  let user;
@@ -31,7 +47,10 @@ function authenticated(options = {}) {
31
47
  let auth;
32
48
  let providerFields;
33
49
  if (options.source) auth = await options.source(context);
34
- else {
50
+ else if (!context.request) {
51
+ const named = namedAuthUserInvoker(context);
52
+ if (named) return named;
53
+ } else {
35
54
  const resolved = await defaultAuthenticatedSource(context);
36
55
  auth = resolved?.auth;
37
56
  providerFields = resolved ?? void 0;
@@ -1,30 +1,32 @@
1
1
  import { i as forwardedRequestOrigin, t as clientRequest } from "./client-request-BzMKtfCY.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { i as resolveAuthMountPath } from "./application-path-zKi7NrvK.js";
4
- import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-CwPIx10t.js";
5
- import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
6
- import { t as assertAuthDatabaseNames } from "./database-schema-options-peXHNLkJ.js";
7
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
8
- import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-BypPLIbI.js";
9
- import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
10
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BXU1_9mc.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";
11
10
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
11
+ import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
12
12
  import { n as resetAuth, t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
13
- import { a as normalizeAuthBasePath } from "./access-pages-9aKr6z-k.js";
14
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DVfi-nJX.js";
15
- import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-CtoKaNQZ.js";
13
+ import { o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
14
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-CMB3t4NF.js";
15
+ import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-dVJBPPTk.js";
16
16
  import { resolvePublicUrl } from "@vite-hub/runtime";
17
17
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
18
18
  import { AsyncLocalStorage } from "node:async_hooks";
19
19
  import { createAuthEndpoint, createAuthMiddleware, getOAuthState, getSessionFromCtx, isAPIError, sensitiveSessionMiddleware } from "better-auth/api";
20
20
  import { getCookies } from "better-auth/cookies";
21
21
  import { getAuthTables } from "better-auth/db";
22
- import { APIError as APIError$1, betterAuth, createLogger, isRequestLike, resolveBaseURL } from "better-auth";
22
+ import { APIError as APIError$1, BetterAuthError, betterAuth, createLogger, getBaseURL, isDynamicBaseURLConfig, isRequestLike, resolveBaseURL, trimTrailingSlashes } from "better-auth";
23
23
  import { memoryAdapter } from "better-auth/adapters/memory";
24
24
  import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
25
+ import { configuredAppOrigin, configuredPublicOrigins } from "@vite-hub/runtime/internal/public-url";
25
26
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
26
27
  import { isWebContainer } from "@vite-hub/web-container/env";
27
28
  import { hkdfSync } from "node:crypto";
29
+ import { addRoute, createRouter, findRoute } from "better-auth-rou3";
28
30
  // src/password.ts
29
31
  const scryptOptions = {
30
32
  N: 16384,
@@ -89,27 +91,44 @@ Object.freeze({ prefix: "sha256=" });
89
91
  // src/secret.ts
90
92
  /** The `deriveSecret()` purpose of the Better Auth secret. `vitehub secret derive vitehub:auth` prints it. */
91
93
  const authSecretPurpose = "vitehub:auth";
92
- const betterAuthSecretNames = [
93
- "BETTER_AUTH_SECRET",
94
- "BETTER_AUTH_SECRETS",
95
- "AUTH_SECRET"
96
- ];
94
+ const publicDefaultSecret = "better-auth-secret-12345678901234567890";
95
+ function parseVersionedSecrets(value) {
96
+ return value?.split(",").map((entry, index) => {
97
+ const separator = entry.indexOf(":");
98
+ const version = Number.parseInt(entry.slice(0, separator), 10);
99
+ const secret = entry.slice(separator + 1).trim();
100
+ if (separator === -1 || !Number.isInteger(version) || version < 0 || !secret) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry at position ${index + 1}. Expected a non-negative version and a non-empty secret: "<version>:<secret>".`);
101
+ return {
102
+ version,
103
+ value: secret
104
+ };
105
+ });
106
+ }
107
+ function resolveAuthSecrets(options, bindings, development) {
108
+ const env = globalThis.process?.env;
109
+ const readEnvSecret = (name) => {
110
+ const binding = bindings?.[name];
111
+ return typeof binding === "string" && binding || env?.[name] || void 0;
112
+ };
113
+ const secrets = options.secrets ?? parseVersionedSecrets(readEnvSecret("BETTER_AUTH_SECRETS"));
114
+ const legacySecret = options.secret || readEnvSecret("BETTER_AUTH_SECRET") || readEnvSecret("AUTH_SECRET");
115
+ const keepDevelopmentDefault = development && (Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets"));
116
+ const secret = legacySecret ?? (secrets || keepDevelopmentDefault ? void 0 : deriveAuthSecret({
117
+ ...env,
118
+ ...bindings
119
+ }));
120
+ return {
121
+ secret,
122
+ secrets,
123
+ secretMissing: !development && (!secret && !secrets || secret === publicDefaultSecret || secrets?.some((key) => key.value === publicDefaultSecret) === true)
124
+ };
125
+ }
97
126
  let derived;
98
127
  function hex(buffer) {
99
128
  return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
100
129
  }
101
- /**
102
- * The Better Auth secret derived from the root app secret, `VITEHUB_SECRET`, equal to
103
- * `deriveSecret("vitehub:auth")`. Returns `undefined` when the environment sets a Better Auth secret or no root secret.
104
- * It is synchronous because Better Auth reads its options synchronously.
105
- */
106
- function deriveAuthSecret(event) {
107
- const env = {
108
- ...globalThis.process?.env,
109
- ...authCloudflareEnv(event)
110
- };
111
- if (betterAuthSecretNames.some((name) => env[name])) return void 0;
112
- const root = readViteHubSecret(env);
130
+ function deriveAuthSecret(environment) {
131
+ const root = readViteHubSecret(environment);
113
132
  if (!root) return void 0;
114
133
  if (root.length < 32) throw authErrorDiagnostics.AUTH_R0016({ message: `[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.` });
115
134
  if (derived?.root !== root) derived = {
@@ -803,6 +822,72 @@ function withClientAddress(auth) {
803
822
  fetch: addressedHandler
804
823
  });
805
824
  }
825
+ // src/rate-limit-endpoints.ts
826
+ const binders = /* @__PURE__ */ new WeakMap();
827
+ function endpointRouter(api) {
828
+ const router = createRouter();
829
+ for (const endpoint of Object.values(api)) {
830
+ const { path, options } = endpoint;
831
+ if (!path || !options) continue;
832
+ if (("metadata" in options ? options.metadata : void 0)?.SERVER_ONLY) continue;
833
+ const methods = Array.isArray(options.method) ? options.method : [options.method];
834
+ for (const method of methods) addRoute(router, method, path, path);
835
+ }
836
+ return router;
837
+ }
838
+ function matchEndpoint(auth) {
839
+ let router;
840
+ return async (request) => {
841
+ const context = await auth.$context;
842
+ const { advanced, baseURL } = context.options;
843
+ const basePath = context.options.basePath || "/api/auth";
844
+ const resolved = isDynamicBaseURLConfig(auth.options.baseURL) ? resolveBaseURL(baseURL, basePath, request, void 0, advanced?.trustedProxyHeaders ?? false) : context.baseURL || getBaseURL(void 0, basePath, request, void 0, advanced?.trustedProxyHeaders);
845
+ if (!resolved) return;
846
+ const mount = trimTrailingSlashes(new URL(resolved).pathname);
847
+ const pathname = new URL(request.url).pathname;
848
+ if (mount && !pathname.startsWith(`${mount}/`)) return;
849
+ const path = pathname.slice(mount.length);
850
+ if (!path || path.includes("//")) return;
851
+ router ??= endpointRouter(auth.api);
852
+ const route = findRoute(router, request.method, path, { params: false })?.data;
853
+ if (!route || !auth.options.advanced?.skipTrailingSlashes && path.endsWith("/") !== route.endsWith("/")) return;
854
+ return !/[:*(){\\]/.test(route) && trimTrailingSlashes(route) === trimTrailingSlashes(path) ? "static" : "pattern";
855
+ };
856
+ }
857
+ /**
858
+ * These rules count a request only when its path is a static endpoint path of the instance, so that each client
859
+ * address has a fixed set of counters. Exact rules of the app apply as declared; wildcard rules also match parameterized endpoints. Each
860
+ * wildcard rule object also stays under a key that no request path matches, because Better Auth reads the windows of
861
+ * rule objects to decide which stored counters have expired.
862
+ * {@link withEndpointRateLimits} gives the rules the endpoints of the instance; until then, every request counts.
863
+ */
864
+ function endpointRateLimitRules(rules) {
865
+ let match;
866
+ const guard = (rule) => async (request, current) => {
867
+ if (match && !await match(request)) return false;
868
+ return typeof rule === "function" ? rule(request, current) : rule;
869
+ };
870
+ const guarded = {};
871
+ for (const [path, rule] of Object.entries(rules ?? {})) {
872
+ if (!path.includes("*")) {
873
+ guarded[path] = rule;
874
+ continue;
875
+ }
876
+ guarded[path] = guard(rule);
877
+ if (rule && typeof rule === "object") guarded[`vitehub:window:${rule.window}`] = rule;
878
+ }
879
+ if (!Object.hasOwn(guarded, "**")) guarded["**"] = async (request, current) => !match || await match(request) === "static" ? current : false;
880
+ binders.set(guarded, (auth) => {
881
+ match ??= matchEndpoint(auth);
882
+ });
883
+ return guarded;
884
+ }
885
+ /** Give the rules of {@link endpointRateLimitRules} the endpoints of the instance that uses them. */
886
+ function withEndpointRateLimits(auth) {
887
+ const rules = auth.options?.rateLimit?.customRules;
888
+ if (rules) binders.get(rules)?.(auth);
889
+ return auth;
890
+ }
806
891
  // src/session-refresh.ts
807
892
  /**
808
893
  * Runs `session.onRefresh` from the Better Auth `session.update.before` database hook.
@@ -921,7 +1006,8 @@ function isDevelopmentServer() {
921
1006
  /**
922
1007
  * Better Auth turns its limiter on only when `NODE_ENV` is `production`, and keeps its counters in the memory of the
923
1008
  * process unless a `secondaryStorage` is set. Auth turns it on outside a development server, and keeps the counters in
924
- * the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them.
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.
925
1011
  */
926
1012
  function withRateLimitDefaults(options, ownsDatabase) {
927
1013
  const rateLimit = options.rateLimit;
@@ -929,6 +1015,7 @@ function withRateLimitDefaults(options, ownsDatabase) {
929
1015
  return {
930
1016
  ...rateLimit,
931
1017
  enabled: rateLimit?.enabled ?? !isDevelopmentServer(),
1018
+ customRules: endpointRateLimitRules(rateLimit?.customRules),
932
1019
  ...database ? { storage: "database" } : {}
933
1020
  };
934
1021
  }
@@ -936,38 +1023,36 @@ function withRateLimitDefaults(options, ownsDatabase) {
936
1023
  * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
937
1024
  * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
938
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.
939
1028
  */
940
- function withClientAddressHeaders(advanced) {
941
- if (advanced?.ipAddress?.ipAddressHeaders) return advanced;
1029
+ function withAdvancedDefaults(advanced) {
1030
+ const disableOriginCheck = advanced?.disableOriginCheck ?? false;
1031
+ if (advanced?.ipAddress?.ipAddressHeaders) return {
1032
+ ...advanced,
1033
+ disableOriginCheck
1034
+ };
942
1035
  return {
943
1036
  ...advanced,
1037
+ disableOriginCheck,
944
1038
  ipAddress: {
945
1039
  ...advanced?.ipAddress,
946
1040
  ipAddressHeaders: [clientAddressHeader]
947
1041
  }
948
1042
  };
949
1043
  }
950
- const betterAuthSetupVariables = [
951
- "AUTH_SECRET",
952
- "BETTER_AUTH_SECRET",
953
- "BETTER_AUTH_SECRETS",
954
- "BETTER_AUTH_TRUSTED_ORIGINS"
955
- ];
956
1044
  /**
957
1045
  * The environment values that an instance for these options uses. Auth reads a value only when the options use it, so
958
1046
  * the instance key and the instance read the same values, and a value that the options replace cannot fail a request.
959
1047
  */
960
1048
  function readProviderEnvironment(options, event) {
961
- const env = {
962
- ...globalThis.process?.env,
963
- ...authCloudflareEnv(event)
964
- };
1049
+ const bindings = authCloudflareEnv(event);
965
1050
  return {
966
1051
  admins: readAdmins(event),
967
1052
  members: readMembers(event),
968
1053
  adminClaim: options.adminClaim === false ? void 0 : readAdminClaim(event),
969
- secret: Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets") ? void 0 : deriveAuthSecret(event),
970
- betterAuth: betterAuthSetupVariables.map((name) => env[name] ?? null)
1054
+ ...resolveAuthSecrets(options, bindings, isDevelopmentServer()),
1055
+ trustedOrigins: bindings?.BETTER_AUTH_TRUSTED_ORIGINS ?? globalThis.process?.env?.BETTER_AUTH_TRUSTED_ORIGINS
971
1056
  };
972
1057
  }
973
1058
  function stripViteHubOptions(definition, options, environment) {
@@ -993,6 +1078,7 @@ function stripViteHubOptions(definition, options, environment) {
993
1078
  }
994
1079
  const policy = isRecord(access) ? access.policy : void 0;
995
1080
  validateAuthAccessPolicy(policy);
1081
+ validateAuthAccessRouteRoles(access);
996
1082
  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." });
997
1083
  const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
998
1084
  const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
@@ -1041,7 +1127,7 @@ function stripViteHubOptions(definition, options, environment) {
1041
1127
  createRequestLogPlugin()
1042
1128
  ],
1043
1129
  logger: withRequestLogger(rest.logger),
1044
- advanced: withClientAddressHeaders(rest.advanced),
1130
+ advanced: withAdvancedDefaults(rest.advanced),
1045
1131
  rateLimit,
1046
1132
  ...eventPlugin ? { hooks: {
1047
1133
  ...rest.hooks,
@@ -1065,12 +1151,13 @@ function withSessionRefresh(options, hasSessionStore) {
1065
1151
  session: betterAuthSession
1066
1152
  };
1067
1153
  }
1068
- /** Without a configured secret, Better Auth signs with the secret derived from `VITEHUB_SECRET`. */
1069
- function withDerivedSecret(options, { secret }) {
1070
- return secret ? {
1154
+ function withResolvedSecrets(options, { secret, secrets, secretMissing }) {
1155
+ if (secretMissing) throw authErrorDiagnostics.AUTH_SECRET_MISSING();
1156
+ return {
1071
1157
  ...options,
1072
- secret
1073
- } : options;
1158
+ ...secret ? { secret } : {},
1159
+ ...secrets ? { secrets } : {}
1160
+ };
1074
1161
  }
1075
1162
  function trustsProxyHeaders(options) {
1076
1163
  return isRecord(options) && isRecord(options.advanced) && options.advanced.trustedProxyHeaders === true;
@@ -1085,8 +1172,9 @@ function resolveAuthOptions(definition, input = {}) {
1085
1172
  const usesContext = !request || callback;
1086
1173
  const env = usesContext ? input.env?.(input.event) ?? {} : {};
1087
1174
  const client = request && clientRequest(request);
1088
- const clientUrlOrigin = client ? new URL(client.url).origin : void 0;
1089
- const proxiedOrigin = client ? forwardedRequestOrigin(client) : void 0;
1175
+ const publicOrigin = client ? configuredAppOrigin(client) : void 0;
1176
+ const clientUrlOrigin = client ? publicOrigin ?? new URL(client.url).origin : void 0;
1177
+ const proxiedOrigin = client ? publicOrigin ?? forwardedRequestOrigin(client) : void 0;
1090
1178
  const resolveAt = (origin) => {
1091
1179
  const context = {
1092
1180
  env,
@@ -1118,7 +1206,7 @@ function resolveAuthOptions(definition, input = {}) {
1118
1206
  let requestRuntimeOptions = callback ? declared : {};
1119
1207
  if (client) {
1120
1208
  const requestOrigin = trusted && proxiedOrigin ? proxiedOrigin : client.url;
1121
- const baseURL = requestRuntimeOptions.baseURL || resolvePublicUrl({ request: { url: requestOrigin } });
1209
+ const baseURL = requestRuntimeOptions.baseURL || publicOrigin || resolvePublicUrl({ request: { url: requestOrigin } });
1122
1210
  if (!baseURL) throw authErrorDiagnostics.AUTH_R0022({ message: `[vitehub] The request host ${new URL(requestOrigin).host} is not an origin of vitehub({ publicUrl }), so Auth has no base URL.` });
1123
1211
  requestRuntimeOptions = {
1124
1212
  ...!Object.hasOwn(declared, "trustedOrigins") ? { trustedOrigins: [baseURL] } : {},
@@ -1140,7 +1228,7 @@ function resolveAuthOptions(definition, input = {}) {
1140
1228
  get providerOptions() {
1141
1229
  const options = resolveSnapshot();
1142
1230
  const environment = resolveEnvironment();
1143
- return withDerivedSecret(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1231
+ return withResolvedSecrets(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1144
1232
  },
1145
1233
  /** Equal for two resolutions of this Definition that give Better Auth equal options, else `undefined`. */
1146
1234
  get providerKey() {
@@ -1275,7 +1363,7 @@ function hasRequestRuntimeOptions(definition) {
1275
1363
  return typeof definition.options === "function" || trustsProxyHeaders(definition.options);
1276
1364
  }
1277
1365
  function hasConfiguredPublicUrl() {
1278
- return typeof __VITEHUB_PUBLIC_URL__ !== "undefined" && Boolean(__VITEHUB_PUBLIC_URL__?.url || Object.keys(__VITEHUB_PUBLIC_URL__?.agents ?? {}).length);
1366
+ return configuredPublicOrigins().length > 0;
1279
1367
  }
1280
1368
  function envResolverFor(definition) {
1281
1369
  return getAuthRuntimeState().envResolvers?.get(definition) ?? getAuthRuntimeState().envResolver;
@@ -1296,7 +1384,7 @@ function createBetterAuthOptions(definition) {
1296
1384
  }
1297
1385
  function createAuthenticationProvider(options) {
1298
1386
  try {
1299
- return withSessionMarker(withClientAddress(betterAuth(options)));
1387
+ return withSessionMarker(withEndpointRateLimits(withClientAddress(betterAuth(options))));
1300
1388
  } catch (cause) {
1301
1389
  throwAuthenticationProviderError(cause, "get-auth-for-request");
1302
1390
  }
@@ -1345,11 +1433,11 @@ function requestProvider(definition, resolved) {
1345
1433
  * `useAuth(event)`. The Console reads it through `@vite-hub/auth/runtime/console`.
1346
1434
  */
1347
1435
  function authForRequest(request, event, definition = resolveDefaultDefinition()) {
1348
- if (!hasRequestRuntimeOptions(definition) && !hasConfiguredPublicUrl()) return getAuthForDefinition(definition);
1436
+ if (!hasRequestRuntimeOptions(definition) && !hasConfiguredPublicUrl() && (!isDevelopmentServer() || getBaseURL())) return getAuthForDefinition(definition);
1349
1437
  return requestProvider(definition, resolveAuthOptions(definition, {
1350
1438
  request,
1351
1439
  event,
1352
1440
  env: envResolverFor(definition)
1353
1441
  }));
1354
1442
  }
1355
- export { 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 };
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 };