@vite-hub/auth 0.1.0 → 0.3.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.
- package/README.md +333 -49
- package/dist/abilities-DfAnFYwG.d.ts +93 -0
- package/dist/abilities.d.ts +2 -0
- package/dist/abilities.js +43 -0
- package/dist/ability-error-CqgBrBfR.js +91 -0
- package/dist/ability-error-DcgChwCN.d.ts +34 -0
- package/dist/admin-claim-code-CDipqeAU.js +22 -0
- package/dist/agent.d.ts +5 -5
- package/dist/agent.js +17 -9
- package/dist/application-path-DuTpfGFj.js +62 -0
- package/dist/auth-instance-CR6b1W80.js +1168 -0
- package/dist/bun-sqlite.d.ts +8 -0
- package/dist/cli-ubYJpAL_.d.ts +163 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +47 -7
- package/dist/console-runtime-DTopBP-x.d.ts +71 -0
- package/dist/console-runtime-J9_Vx9pT.js +1166 -0
- package/dist/console-runtime.d.ts +3 -3
- package/dist/console-runtime.js +2 -819
- package/dist/console.d.ts +215 -3
- package/dist/console.js +1 -1
- package/dist/database-options-BRNef9oy.js +29 -0
- package/dist/database-schema-options-ENuRMduM.js +12 -0
- package/dist/database.d.ts +12 -0
- package/dist/database.js +45 -0
- package/dist/definition-CqQMcDEK.js +280 -0
- package/dist/error-diagnostics-C8XtVz0i.js +138 -0
- package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +120 -0
- package/dist/host-declarations.d.ts +2 -1
- package/dist/index.d.ts +24 -3
- package/dist/index.js +3 -102
- package/dist/internal/server.d.ts +5 -0
- package/dist/internal/server.js +858 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/mcp.d.ts +187 -0
- package/dist/mcp.js +353 -0
- package/dist/members-D9lfaEO_.js +533 -0
- package/dist/nuxt-bridge-Cl988STZ.js +44 -0
- package/dist/nuxt.d.ts +13 -5
- package/dist/nuxt.js +90 -13
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/page-tools-shared-l4eyj53D.js +19 -0
- package/dist/presets.js +1 -1
- package/dist/request-z6DHHmrb.js +47 -0
- package/dist/runtime/console.d.ts +3 -7
- package/dist/runtime/console.js +4 -42
- package/dist/runtime/empty-abilities.d.ts +5 -0
- package/dist/runtime/empty-abilities.js +4 -0
- package/dist/runtime/empty-client.d.ts +6 -0
- package/dist/runtime/empty-client.js +5 -0
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/nuxt.js +1 -1
- package/dist/runtime/server.d.ts +2 -0
- package/dist/runtime/server.js +77 -0
- package/dist/runtime/vue-nuxt.d.ts +3 -2
- package/dist/runtime/vue-nuxt.js +157 -5
- package/dist/runtime-state-ojQCzKOc.js +25 -0
- package/dist/schema.d.ts +137 -0
- package/dist/schema.js +147 -0
- package/dist/server-C0qnKN2W.d.ts +143 -0
- package/dist/server-bQGzVQ--.d.ts +41 -0
- package/dist/server.d.ts +3 -2
- package/dist/server.js +3 -3
- package/dist/session-cookies-BbH3UR2m.js +227 -0
- package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
- package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
- package/dist/table-specs-8gq_FCaq.js +771 -0
- package/dist/table-specs-DbXyaXWs.d.ts +842 -0
- package/dist/test.d.ts +26 -0
- package/dist/test.js +25 -0
- package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
- package/dist/vite-CV400XXY.js +1556 -0
- package/dist/vite.d.ts +138 -20
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +330 -21
- package/dist/vue.js +583 -36
- package/package.json +84 -15
- package/dist/application-path-C290OAIs.js +0 -18
- package/dist/cli-mgXvsBtA.d.ts +0 -85
- package/dist/console-B7eERmGv.d.ts +0 -180
- package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
- package/dist/error-diagnostics-CL0yjHiM.js +0 -79
- package/dist/events-config-CjcFOhTE.js +0 -177
- package/dist/inspect-DPtsW8dB.d.ts +0 -36
- package/dist/server-B7LU19dS.js +0 -1730
- package/dist/server-CTD_JAww.d.ts +0 -77
- package/dist/vite-COWkwxsj.js +0 -990
package/README.md
CHANGED
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
|
|
10
10
|
`@vite-hub/auth` defines one server-owned Auth Definition and turns it into a Better Auth server for ViteHub apps.
|
|
11
11
|
|
|
12
|
-
Most applications install `vite-hub` and enable Auth through the framework preset.
|
|
12
|
+
Most applications install `vite-hub`, `@vite-hub/auth`, and `better-auth`, and enable Auth through the framework preset. Use this owner package alone when a focused Vite integration, library, or manual host needs Auth without the rest of ViteHub. Better Auth still owns providers, client plugins, adapters, and sign-in UI.
|
|
13
13
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
16
16
|
```sh
|
|
17
|
-
pnpm add @vite-hub/auth better-auth
|
|
17
|
+
pnpm add @vite-hub/auth better-auth drizzle-orm@1.0.0-rc.5 nitro
|
|
18
18
|
pnpm add -D vite
|
|
19
19
|
```
|
|
20
20
|
|
|
@@ -33,10 +33,11 @@ export default defineAuth({
|
|
|
33
33
|
```ts
|
|
34
34
|
// vite.config.ts
|
|
35
35
|
import { hubAuth } from "@vite-hub/auth/vite";
|
|
36
|
+
import { nitro } from "nitro/vite";
|
|
36
37
|
import { defineConfig } from "vite";
|
|
37
38
|
|
|
38
39
|
export default defineConfig({
|
|
39
|
-
plugins: [hubAuth()],
|
|
40
|
+
plugins: [hubAuth(), nitro()],
|
|
40
41
|
});
|
|
41
42
|
```
|
|
42
43
|
|
|
@@ -52,9 +53,46 @@ curl -i http://localhost:5173/api/auth/sign-up/email \
|
|
|
52
53
|
--data '{"name":"Local User","email":"local@example.com","password":"passwordpassword"}'
|
|
53
54
|
```
|
|
54
55
|
|
|
55
|
-
Successful output has status `200`, a `better-auth.session_token` cookie, and the new user's email. `hubAuth()` discovers `server/auth.ts
|
|
56
|
+
Successful output has status `200`, a `better-auth.session_token` cookie, and the new user's email. `hubAuth()` discovers `server/auth.ts` and generates the Nitro route handler for `/api/auth/**`. Nitro serves it in development and in production builds.
|
|
56
57
|
|
|
57
|
-
This default proves discovery and the session route locally.
|
|
58
|
+
This default proves discovery and the session route locally. Without `database`, a development server keeps users and sessions in the memory of its process, so a user who signs up can sign in until the process restarts. A production build without `database` or `preset` fails with `AUTH_C0063`. Use `authDatabase()` to keep users across restarts and replicas, or the `stateless()` preset for social sign-in without a database. Set `database: "memory"` only when one server process may lose its users when it restarts.
|
|
59
|
+
|
|
60
|
+
## Keep users in the app Database
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// server/auth.ts
|
|
64
|
+
import { admin } from "better-auth/plugins";
|
|
65
|
+
import { defineAuth } from "@vite-hub/auth";
|
|
66
|
+
import { authDatabase } from "@vite-hub/auth/database";
|
|
67
|
+
|
|
68
|
+
export default defineAuth({
|
|
69
|
+
database: authDatabase(),
|
|
70
|
+
emailAndPassword: { enabled: true },
|
|
71
|
+
plugins: [admin()],
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
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
|
+
|
|
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.
|
|
78
|
+
|
|
79
|
+
## First admin
|
|
80
|
+
|
|
81
|
+
`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`.
|
|
82
|
+
|
|
83
|
+
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`.
|
|
84
|
+
|
|
85
|
+
Set `adminClaim: false` on another Auth Definition to make it ignore the host's claim value.
|
|
86
|
+
|
|
87
|
+
With a claim code set, Auth sets `verification.storeInDatabase: true`, including when sessions use `secondaryStorage`. Claim markers use only the database, so a secondary-storage outage cannot block reservation recovery. A failed role grant releases the reservation so the code can be tried again.
|
|
88
|
+
|
|
89
|
+
## Members
|
|
90
|
+
|
|
91
|
+
`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.
|
|
92
|
+
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
`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.
|
|
58
96
|
|
|
59
97
|
## Sessions without a database
|
|
60
98
|
|
|
@@ -87,11 +125,11 @@ For host routes that need runtime secrets, provider credentials, request-derived
|
|
|
87
125
|
// vite.config.ts
|
|
88
126
|
import { hubAuth } from "@vite-hub/auth/vite";
|
|
89
127
|
import { env, hubEnv } from "@vite-hub/env/vite";
|
|
128
|
+
import { nitro } from "nitro/vite";
|
|
90
129
|
import { defineConfig } from "vite";
|
|
91
130
|
|
|
92
131
|
export default defineConfig({
|
|
93
|
-
plugins: [hubEnv(
|
|
94
|
-
env: {
|
|
132
|
+
plugins: [hubEnv({
|
|
95
133
|
server: {
|
|
96
134
|
auth: {
|
|
97
135
|
github: {
|
|
@@ -101,7 +139,7 @@ export default defineConfig({
|
|
|
101
139
|
secret: env({ secret: true, source: env.source("BETTER_AUTH_SECRET") }),
|
|
102
140
|
},
|
|
103
141
|
},
|
|
104
|
-
},
|
|
142
|
+
}), hubAuth(), nitro()],
|
|
105
143
|
});
|
|
106
144
|
```
|
|
107
145
|
|
|
@@ -132,11 +170,15 @@ export default defineAuth(({ env, requestOrigin }) => ({
|
|
|
132
170
|
|
|
133
171
|
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.
|
|
134
172
|
|
|
135
|
-
|
|
173
|
+
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.
|
|
174
|
+
|
|
175
|
+
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()`.
|
|
136
176
|
|
|
137
177
|
The generated Nitro middleware uses `access.signIn` when one of the configured `access.routes` needs a browser redirect. Route objects can add an `authorize` callback when a valid session is not sufficient:
|
|
138
178
|
|
|
139
179
|
```ts
|
|
180
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
181
|
+
|
|
140
182
|
export default defineAuth({
|
|
141
183
|
access: {
|
|
142
184
|
routes: [
|
|
@@ -144,22 +186,32 @@ export default defineAuth({
|
|
|
144
186
|
route: "/_vitehub/**",
|
|
145
187
|
authorize: ({ user }) => user.isAdmin === true,
|
|
146
188
|
},
|
|
147
|
-
{
|
|
148
|
-
route: "/api/_vitehub/console/**",
|
|
149
|
-
authorize: ({ user }) => user.isAdmin === true,
|
|
150
|
-
},
|
|
151
189
|
],
|
|
152
190
|
},
|
|
153
191
|
});
|
|
154
192
|
```
|
|
155
193
|
|
|
156
|
-
Generated route middleware uses `createAuthAccessHandler(routes, definition?)` from `@vite-hub/auth/server
|
|
194
|
+
Generated route middleware uses `createAuthAccessHandler(routes, definition?, publicRoutes?)` from the private `@vite-hub/auth/internal/server` entry. The handler owns path and method matching, overlapping rules, and required authorization callbacks. Its route metadata follows the Definition's `access.routes` order; a route with `authorize: true` and no runtime callback returns `403`. Unmatched requests do not resolve Auth.
|
|
195
|
+
|
|
196
|
+
The Nitro build fails with `AUTH_B0002` when a route rule caches or prerenders a path that `access.routes` guards for `GET` or `HEAD`: `swr`, `cache`, `isr`, `prerender`, or `static`. A cached response is made for one visitor and served to others. Set `cache: false` or `prerender: false` on the guarded pattern to turn off a wider rule. In development, a route rule update that caches a guarded path logs `AUTH_B0002` as a warning.
|
|
197
|
+
|
|
198
|
+
`access.public` lists paths that no access route guards, in the same form as `access.routes`. With `routes: ["/**"]`, every other path needs a session, so the app is private by default. Keep `/api/auth/**` public, so people can sign in. A route rule that caches only public paths passes `AUTH_B0002`. Write the list inline: the Vite plugin reads it at build time, and other values fail with `AUTH_C0064`.
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import { defineAuth } from "@vite-hub/auth";
|
|
202
|
+
|
|
203
|
+
export default defineAuth({
|
|
204
|
+
access: { routes: ["/**"], public: ["/", "/login", "/api/auth/**"] },
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`access.policy: { allow, recheck }` decides who can sign in and stay signed in. Auth calls `allow({ user, accessToken })` when it creates a session; only `true` lets the person in. It calls `allow` again for a session once `recheck` milliseconds (default 300000) have passed, on the next Better Auth request with the session cookie, which includes every `getSession()` call and guard. A refusal deletes the session and its cookies, and the request continues signed out. A throw fails the request and keeps the session. `accessToken(providerId)` returns the user's provider access token, decrypted, so `allow` can call `checkGitHubOrgMember()` or another provider. Throw its `AUTH_GITHUB_UNAVAILABLE` error, so a GitHub outage keeps the sessions. `verifyMcpRequest()` asks the same policy for the user of an MCP access token. The answers are in memory per process. The policy needs a `database` or `secondaryStorage` adapter (`AUTH_C0066`).
|
|
157
209
|
|
|
158
210
|
ViteHub runs `authorize` only after authentication. Return `true` to allow the request, `false` for a `403`, or a `Response` for a custom result. The callback receives the authenticated `user`, `session`, and request; role semantics remain owned by the host. Only `true` grants access. ViteHub sends a `Response` unchanged when it is a Response of this runtime: the native `Response.prototype.status` getter accepts it. Create it with the global `Response`. Every other value gets `403`, including a Response from another Fetch implementation such as the `undici` package, a proxy, and an object shaped like a Response.
|
|
159
211
|
|
|
160
212
|
Guard your own server handlers with `withAuth(handler, definition?)` or `withAuthorization(authorize, handler, definition?)` from `@vite-hub/auth/server`. The guard returns a new handler. That handler checks the request first and calls your handler only when the check passes. Your handler receives the input and a frozen `authorization` with the checked `request`, `session`, and `user`. Otherwise the guard returns the rejection `Response`, so a missed `if` cannot run the protected action.
|
|
161
213
|
|
|
162
|
-
```ts
|
|
214
|
+
```ts fragment
|
|
163
215
|
import { withAuth, withAuthorization } from "@vite-hub/auth/server";
|
|
164
216
|
import type { H3Event } from "h3";
|
|
165
217
|
|
|
@@ -173,13 +225,48 @@ export const photo = withAuthorization(
|
|
|
173
225
|
|
|
174
226
|
Annotate the input type when the host does not infer it, for example inside `defineEventHandler()`.
|
|
175
227
|
|
|
176
|
-
`withAuth()` returns JSON `401` without a session and starts the `access.signIn` redirect for HTML requests. `withAuthorization()` applies one `authorize` rule: `true` for any session or a callback. It returns JSON `401` without a session, `403` when the callback returns `false`, or the callback's `Response`. It never redirects to sign-in. Blob serve routes and Source Collections use it for their `authorize` option.
|
|
228
|
+
`withAuth()` returns JSON `401` without a session and starts the `access.signIn` redirect for HTML requests. Every JSON refusal of the guards has one body in H3's error format: `{ status, statusText, message, data: { code } }`. The code is `SIGNED_OUT` for `401` and `FORBIDDEN` for `403`. Read the code, not the message. `withAuthorization()` applies one `authorize` rule: `true` for any session or a callback. It returns JSON `401` without a session, `403` when the callback returns `false`, or the callback's `Response`. It never redirects to sign-in. The callback gets `{ event, request, session, user }`: `event` is the input of the guarded handler, such as the H3 event. Blob serve routes and Source Collections use it for their `authorize` option.
|
|
229
|
+
`withAnonymousAuthorization(authorize, handler, definition?)` also runs the callback for a signed-out caller, with `session` and `user` set to `null`. `false` returns `401` for that caller and `403` for a signed-in one. Blob serve routes use it with `serve.anonymous: true`.
|
|
230
|
+
|
|
231
|
+
To check inside a handler, call `requireAuth(event)` or `requireAuthorization(event, authorize)`. Each returns the frozen `authorization` or throws an H3 `HTTPError`, so the rest of the handler runs only after the check passes. The errors match the guards above: `requireAuth()` throws `401` or the `access.signIn` redirect, and `requireAuthorization()` throws `401`, `403`, or an HTTP error from the callback's `Response`. The error has the same code in `data.code`, also for the text `403` of an HTML request.
|
|
232
|
+
|
|
233
|
+
The inline guards use H3's JSON error format. They keep the response status and headers, except `content-length`, which changes with the body. JSON object fields stay at the top level, and other JSON values become `data`. JSON media types, such as `application/problem+json`, stay unchanged. Text becomes `message` with a JSON content type. Use `withAuthorization()` when the response body must stay unchanged.
|
|
234
|
+
|
|
235
|
+
```ts fragment
|
|
236
|
+
import { requireAuth, requireAuthorization } from "@vite-hub/auth/server";
|
|
237
|
+
import { defineHandler } from "h3";
|
|
238
|
+
|
|
239
|
+
export const me = defineHandler(async (event) => {
|
|
240
|
+
const { user } = await requireAuth(event);
|
|
241
|
+
return { id: user.id };
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
export const removePost = defineHandler(async (event) => {
|
|
245
|
+
await requireAuthorization(event, ({ user }) => user.role === "admin");
|
|
246
|
+
return deletePost(event);
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Better Auth instance
|
|
251
|
+
|
|
252
|
+
`useAuth(event)` returns the Better Auth instance of your Auth Definition for a request event or a Web `Request`. The Vite plugin writes the type of `server/auth.ts` to `.vitehub/types/auth.d.ts`, so the instance has the endpoints of your plugins without a cast:
|
|
253
|
+
|
|
254
|
+
```ts fragment
|
|
255
|
+
import { requireAuthorization, useAuth } from "@vite-hub/auth/server";
|
|
256
|
+
import { defineHandler } from "h3";
|
|
257
|
+
|
|
258
|
+
// server/auth.ts uses `admin()` from `better-auth/plugins`.
|
|
259
|
+
export default defineHandler(async (event) => {
|
|
260
|
+
await requireAuthorization(event, ({ user }) => user.role === "admin");
|
|
261
|
+
return useAuth(event).api.listUsers({ query: { limit: 20 }, headers: event.req.headers });
|
|
262
|
+
});
|
|
263
|
+
```
|
|
177
264
|
|
|
178
265
|
## Session refresh
|
|
179
266
|
|
|
180
267
|
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.
|
|
181
268
|
|
|
182
|
-
```ts
|
|
269
|
+
```ts fragment
|
|
183
270
|
export default defineAuth({
|
|
184
271
|
session: {
|
|
185
272
|
updateAge: 60 * 60,
|
|
@@ -202,56 +289,71 @@ export default defineAuth({
|
|
|
202
289
|
The hook receives the `session` and `user` as stored before the refresh. To change user fields, update them in your own store: the current response still contains the user that Better Auth read before the refresh.
|
|
203
290
|
|
|
204
291
|
`onRefresh` needs a Better Auth `database` or `secondaryStorage` adapter. Without one, Auth fails with `AUTH_C0042`, because Better Auth refreshes a stateless cookie cache (`session.cookieCache.refreshCache`) without a hook. With a cookie cache in front of a database, the hook runs only when Better Auth reads the database. It does not run when `session.disableSessionRefresh` is set or for a session created without "remember me". With `session.deferSessionRefresh`, it runs on the `POST` that writes the refresh.
|
|
205
|
-
On H3 2, you can guard a route with middleware instead. `requireAuth(definition?)` rejects like `withAuth()`, and `requireAuthorization(authorize, definition?)` rejects like `withAuthorization()`. When the check passes, the middleware calls `next()`. The route handler reads the checked `request`, `session`, and `user` with `getAuthorization(event)`.
|
|
206
292
|
|
|
207
|
-
|
|
208
|
-
import { getAuthorization, requireAuth, requireAuthorization } from "@vite-hub/auth/server";
|
|
209
|
-
import { H3 } from "h3";
|
|
293
|
+
When a guard reads the session, Better Auth can set cookies: the renewed session cookie after `session.updateAge`, a refreshed cookie cache, or the deletion of an ended session. The guards send these cookies with the response, so a person who calls only guarded routes keeps the browser session. In a ViteHub app, H3 adds them to the value, `Response`, refusal, or error of the route, also when an `authorize` callback throws. On a plain Fetch host, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()` put them on the `Response` that they return, also the cookies of an inline guard in their handler. Access middleware, `requireAuth()`, `requireAuthorization()`, `requireAbility()`, and `can()` alone cannot see the response there, so they leave the cookies in `res.headers` of the Standard Context of the Request. Copy those headers to your `Response`. The Agent chat route sends the cookies of `authenticated()` on both hosts. When the `Response` of the route sets a cookie with the same name, the guard sends only the cookie of the route.
|
|
210
294
|
|
|
211
|
-
|
|
212
|
-
.get("/me", event => ({ id: getAuthorization(event).user.id }), {
|
|
213
|
-
middleware: [requireAuth()],
|
|
214
|
-
})
|
|
215
|
-
.delete("/posts/:id", event => deletePost(event), {
|
|
216
|
-
middleware: [requireAuthorization(({ user }) => user.role === "admin")],
|
|
217
|
-
});
|
|
218
|
-
```
|
|
219
|
-
|
|
220
|
-
`getAuthorization(event)` returns only what the Auth middleware attached to that event. It does not read `event.context`, so other code cannot set it. On a route without the middleware, it throws `AUTH_R0017`, so the handler fails closed. The middleware accepts any host with the same `(event, next)` contract and an event with an own `req` request.
|
|
295
|
+
A response with these cookies must stay out of shared caches, so that a cache cannot give one person's session to another person. When the guard sees what the route returns, it adds `private` to the `Cache-Control` of the route, unless it already has `private` or `no-store`. It removes `public` and `s-maxage` and keeps the other directives, such as `max-age`. Access middleware and inline guards cannot see the `Cache-Control` of the route, so they ask for `no-store`, which no directive of the route is stricter than.
|
|
221
296
|
|
|
222
297
|
## Vite Integration
|
|
223
298
|
|
|
224
|
-
Use `server/auth.ts` for the canonical Auth Definition, or `server.auth.ts` when a flat server file fits the project better. Vite discovers one Auth Definition, exposes it through an internal virtual module,
|
|
299
|
+
Use `server/auth.ts` for the canonical Auth Definition, or `server.auth.ts` when a flat server file fits the project better. Vite discovers one Auth Definition, exposes it through an internal virtual module, and registers `/api/auth/**` with Nitro by default. Nitro serves the route in development too, so `/api/auth`, the Console, and server routes use one Auth instance and share its users and sessions.
|
|
225
300
|
|
|
226
301
|
Set `route: false` only when a host integration mounts Auth itself.
|
|
227
302
|
|
|
228
303
|
```ts
|
|
304
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
305
|
+
|
|
229
306
|
export default defineAuth({
|
|
230
307
|
route: false,
|
|
231
308
|
});
|
|
232
309
|
```
|
|
233
310
|
|
|
234
|
-
Manual hosts can mount the
|
|
311
|
+
Manual hosts can mount the default export of `#vitehub/auth/server` directly. It is a Fetchable route, `{ fetch(request) }`. It reads the client address and the Cloudflare bindings from the Standard Context of the Request, which Nitro sets in a ViteHub app.
|
|
312
|
+
|
|
313
|
+
```ts [server/routes/api/auth/[...].ts]
|
|
314
|
+
export { default } from '#vitehub/auth/server'
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
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`.
|
|
318
|
+
|
|
319
|
+
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.
|
|
235
320
|
|
|
236
|
-
Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`,
|
|
237
|
-
Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, `runtime`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback or place them under `runtime`. `access.routes` must be static route strings or `{ authorize, method, route }` objects so the Vite Integration can register Nitro middleware.
|
|
321
|
+
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.
|
|
238
322
|
|
|
239
323
|
|
|
240
|
-
`access.routes` must use a dense array. Empty slots, including commented-out entries that leave commas, fail configuration.
|
|
324
|
+
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.
|
|
325
|
+
|
|
326
|
+
`database` and `secondaryStorage` take Better Auth adapters only. In a static Definition, `database` takes only `authDatabase()`. `authDatabase("auth")` uses the Named Database `auth`:
|
|
241
327
|
|
|
242
328
|
```ts
|
|
329
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
330
|
+
import { authDatabase } from "@vite-hub/auth/database"
|
|
331
|
+
|
|
243
332
|
export default defineAuth({
|
|
244
333
|
basePath: "/auth",
|
|
245
|
-
database:
|
|
246
|
-
secondaryStorage: { store: "auth" },
|
|
334
|
+
database: authDatabase("auth"),
|
|
247
335
|
});
|
|
248
336
|
```
|
|
249
337
|
|
|
250
|
-
|
|
338
|
+
Return another Better Auth `database` adapter, or a `secondaryStorage` adapter, from the Definition callback. Auth rejects `true`, `{ name }`, and `{ store }`, because they do not create storage.
|
|
339
|
+
|
|
340
|
+
## Nuxt
|
|
341
|
+
|
|
342
|
+
Enable Auth in a Nuxt app through `vite-hub/nuxt`:
|
|
343
|
+
|
|
344
|
+
```ts
|
|
345
|
+
// nuxt.config.ts
|
|
346
|
+
export default defineNuxtConfig({
|
|
347
|
+
modules: ["vite-hub/nuxt"],
|
|
348
|
+
vitehub: { auth: true },
|
|
349
|
+
})
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
`@vite-hub/auth/nuxt` is internal. `vite-hub/nuxt` loads it, and it can change in any release. Do not add it to Nuxt `modules`.
|
|
251
353
|
|
|
252
354
|
## Client-side Auth
|
|
253
355
|
|
|
254
|
-
Vue apps can use ViteHub's Better Auth client and normalized session composable directly. `useUserSession()` exposes the current `user` and `session`, sign-in and sign-out actions,
|
|
356
|
+
Vue apps can use ViteHub's Better Auth client and normalized session composable directly. `useUserSession()` exposes the current `user` and `session`, sign-in and sign-out actions, `loggedIn`, `pending`, and `ready` computed refs, and the Better Auth `client`.
|
|
255
357
|
|
|
256
358
|
```ts
|
|
257
359
|
// lib/auth-client.ts
|
|
@@ -260,7 +362,13 @@ import { useUserSession } from "@vite-hub/auth/vue";
|
|
|
260
362
|
export const session = useUserSession();
|
|
261
363
|
```
|
|
262
364
|
|
|
263
|
-
|
|
365
|
+
`session.signOut()` calls Better Auth's `signOut()` and sets `user` and `session` to `null` at once, in every component that reads the session. It does not wait for Better Auth to read the session again. `signOut({ redirectTo: "/" })` then opens that page: a plain Vue app loads it with `location.assign()`, and Nuxt opens it with `navigateTo()`. Better Auth gets the other options, such as `fetchOptions`, and `signOut()` returns Better Auth's result. When the sign-out fails, the session and the page stay. When the server answers with the provider's sign-out page, such as with OpenID Connect logout, `signOut()` opens that page in place of `redirectTo`, after the `onSignOut()` listeners, and only when it is an `http:` or `https:` page. With `disableRedirect: true`, it returns that page in `data.url` and opens `redirectTo`.
|
|
366
|
+
|
|
367
|
+
On the server, `signOut(event, { redirectTo })` from `@vite-hub/auth/server` ends the session of a request event or a Web `Request` and returns the response that clears the session cookies: a `303` redirect to `redirectTo`, or `204` without it. If Better Auth returns a provider logout URL, the response redirects there first and passes `redirectTo` as the return URL. Return it from a route such as `server/routes/logout.get.ts`. `redirectTo` must be a path of the app, or it throws `AUTH_SIGN_OUT_REDIRECT_INVALID`.
|
|
368
|
+
|
|
369
|
+
That default talks to `/api/auth` on the same origin. In a Nuxt app below `app.baseURL`, such as `/app/`, it talks to `/app/api/auth`, and the server serves Auth routes and OAuth callbacks below the same path.
|
|
370
|
+
|
|
371
|
+
In Nuxt, the default client also uses the Auth Definition's `basePath`. With `basePath: "/auth"` below `app.baseURL` `/app/`, `useUserSession()`, `useSession()`, and the page guard all call `/app/auth`. They share one Better Auth client. In the browser, the client uses the `app.baseURL` of the page, so a `NUXT_APP_BASE_URL` that a deployment sets at runtime also applies. On the server, Nuxt reads the session from the Nitro route, below the base path of the build.
|
|
264
372
|
|
|
265
373
|
```ts
|
|
266
374
|
// server/auth.ts
|
|
@@ -272,6 +380,8 @@ export default defineAuth({
|
|
|
272
380
|
});
|
|
273
381
|
```
|
|
274
382
|
|
|
383
|
+
Outside Nuxt, pass the same path to the Better Auth client, below the app base path:
|
|
384
|
+
|
|
275
385
|
```ts
|
|
276
386
|
// lib/auth-client.ts
|
|
277
387
|
import { createAuthClient, useUserSession } from "@vite-hub/auth/vue";
|
|
@@ -282,11 +392,30 @@ export const authClient = createAuthClient({
|
|
|
282
392
|
export const userSession = useUserSession(authClient);
|
|
283
393
|
```
|
|
284
394
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useSession()` and `useUserSession()` return their refs at once: they are pending until the client loads in the browser, and stay pending during server rendering. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
|
|
395
|
+
To add Better Auth client plugins to the default client, export its options from `auth.client.ts` in the Vite root, which is `app/auth.client.ts` in a Nuxt app. `hubAuth()` finds the file. The default client loads it together with `better-auth/vue` on first use, and `useUserSession()`, `useAuthClient()`, and the Nuxt page guard share that one client. The generated `.vitehub/types/auth.d.ts` registers the type of the file, so `client.admin` is typed. Restart the dev server after you add or remove the file.
|
|
288
396
|
|
|
289
397
|
```ts
|
|
398
|
+
// app/auth.client.ts
|
|
399
|
+
import { adminClient } from "better-auth/client/plugins";
|
|
400
|
+
import { defineAuthClient } from "@vite-hub/auth/vue";
|
|
401
|
+
|
|
402
|
+
export default defineAuthClient({
|
|
403
|
+
plugins: [adminClient()],
|
|
404
|
+
});
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
```ts fragment
|
|
408
|
+
import { useUserSession } from "@vite-hub/auth/vue";
|
|
409
|
+
|
|
410
|
+
const { client } = useUserSession();
|
|
411
|
+
const { data } = await client.admin.listUsers({ query: { limit: 10 } });
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
The exported `createAuthClient` keeps Better Auth's option and plugin inference for a second client with its own base path or plugins. Without `basePath`, it uses the same path as the default client. The zero-config composables use ViteHub's shared default client. Its type is `RegisteredAuthClient`: `hubAuth()` writes the type of the Auth Definition to `.vitehub/types/auth.d.ts`, so `user` and `session` have the fields that `additionalFields`, server plugins such as `admin()`, and `customSession()` add. The client imports only this type, not server code. A client from `createAuthClient()` needs Better Auth's client plugins, such as `customSessionClient<RegisteredAuth>()`, and `inferAdditionalFields<RegisteredAuth>()` for the same fields. React, Svelte, Solid, and other framework clients remain available from Better Auth's framework entrypoints.
|
|
415
|
+
|
|
416
|
+
The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useSession()` and `useUserSession()` return their refs at once: they are pending until the client loads in the browser. In Nuxt, a call in a component starts with the session that the server read for the request, so it is settled during server rendering and hydration. The browser then does not load Better Auth or read the session again until the session can change: a call such as `signOut()`, `refresh()`, the tab shows again, the network comes back, another tab signs out or updates the user, Better Auth's `refetchInterval` passes, or the session expires. Like Better Auth, it waits while the browser is offline. Better Auth then starts with the server's session, so a read that fails does not sign the page out. So without a page guard, a page that only shows the user reads the session once, on the server. When the server's session is unknown, such as on a prerendered page, the browser loads Better Auth at once. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
|
|
417
|
+
|
|
418
|
+
```ts fragment
|
|
290
419
|
import { loadAuthClient } from "@vite-hub/auth/vue";
|
|
291
420
|
import { authClient } from "./auth-client";
|
|
292
421
|
|
|
@@ -294,8 +423,145 @@ const client = await loadAuthClient(authClient);
|
|
|
294
423
|
client.$store.listen("$sessionSignal", () => {});
|
|
295
424
|
```
|
|
296
425
|
|
|
426
|
+
All calls of `useSession()` and `useUserSession()` for one client share one session state: one for each page in the browser, and one for each request on the server. A list of 100 components that call `useUserSession()` makes one Better Auth subscription, not 100. `refresh()` reads the session again, updates every component, and returns the session, or `null` without one. Calls at the same time share one read. On the server, `refresh()` returns the session that the server read for the request, and does not load Better Auth. `ready` is `true` after the first read. It stays `true` while a later read runs, and after a read that failed.
|
|
427
|
+
|
|
428
|
+
```ts fragment
|
|
429
|
+
import { useUserSession } from "@vite-hub/auth/vue";
|
|
430
|
+
|
|
431
|
+
const { refresh } = useUserSession();
|
|
432
|
+
const session = await refresh();
|
|
433
|
+
if (!session) console.log("Signed out");
|
|
434
|
+
```
|
|
435
|
+
|
|
297
436
|
Read [Better Auth's client docs](https://www.better-auth.com/docs/getting-started/concepts/client) for framework entrypoints and session helpers.
|
|
298
437
|
|
|
438
|
+
## Abilities
|
|
439
|
+
|
|
440
|
+
Write named permission rules once in `shared/abilities.ts`, next to the `server/` folder. The server and the app run the same rules. The design comes from [Capsa](https://github.com/OrlS15/nuxt-capsa) by Orlando Sica.
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
// shared/abilities.ts
|
|
444
|
+
import { defineAbilities, deny, guest } from "@vite-hub/auth/abilities";
|
|
445
|
+
|
|
446
|
+
export interface Post { authorId: string; published: boolean }
|
|
447
|
+
|
|
448
|
+
export default defineAbilities({
|
|
449
|
+
"posts.read": guest((user, post: Post) => post.published || user?.id === post.authorId),
|
|
450
|
+
"posts.edit": (user, post: Post) => user.id === post.authorId || "not-author",
|
|
451
|
+
"posts.publish": (user, post: Post) => user.id === post.authorId || deny("not-found", { status: 404 }),
|
|
452
|
+
});
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
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.
|
|
456
|
+
|
|
457
|
+
- 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.
|
|
458
|
+
- 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.
|
|
459
|
+
- 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.
|
|
460
|
+
|
|
461
|
+
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)`.
|
|
462
|
+
|
|
463
|
+
`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`.
|
|
464
|
+
|
|
465
|
+
## Nuxt: server session and page guard
|
|
466
|
+
|
|
467
|
+
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()`, `useSession()`, 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()` and `useSession()` start 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.
|
|
468
|
+
|
|
469
|
+
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.
|
|
470
|
+
|
|
471
|
+
The server session lookup, the page guard, and the auto-imported composables use the Auth Definition's `basePath`, below Nuxt's `app.baseURL`.
|
|
472
|
+
|
|
473
|
+
During server rendering, a client call such as `listSessions()` or a plugin endpoint such as `organization.list()` calls the app in-process with the visitor's cookie. Call it in `<script setup>` or in `useAsyncData()`, and the page renders its data on the server. When Better Auth refreshes the session cookie, the page response sets it. A client with its own `baseURL` or `fetchOptions.customFetchImpl` keeps them, so its server calls do not carry the visitor's cookie. Better Auth's origin check refuses a `POST` call during server rendering with `403`, so make calls that change data in the browser. A prerendered or cached page renders without the visitor's cookie, so its calls answer as signed out.
|
|
474
|
+
|
|
475
|
+
```vue
|
|
476
|
+
<!-- app/pages/sessions.vue -->
|
|
477
|
+
<script setup lang="ts">
|
|
478
|
+
import { useAuthClient } from "vite-hub/auth/vue";
|
|
479
|
+
|
|
480
|
+
const { data: sessions } = await useAsyncData("sessions", async () => {
|
|
481
|
+
const { data } = await useAuthClient().listSessions();
|
|
482
|
+
return data ?? [];
|
|
483
|
+
});
|
|
484
|
+
</script>
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
`definePageMeta({ auth })` guards a page on the server and on client navigation:
|
|
488
|
+
|
|
489
|
+
| `auth` | Who may open the page | Others go to |
|
|
490
|
+
| --- | --- | --- |
|
|
491
|
+
| `'user'` or `true` | Visitors with a session | `redirects.login` (default `/login`), with `?redirect=<the page>` |
|
|
492
|
+
| `'guest'` | Visitors without a session, such as on the login page | `redirects.guest` (default `/`) |
|
|
493
|
+
| `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
|
|
494
|
+
| `false` or unset | Everyone | |
|
|
495
|
+
|
|
496
|
+
```ts
|
|
497
|
+
// nuxt.config.ts
|
|
498
|
+
export default defineNuxtConfig({
|
|
499
|
+
modules: ["vite-hub/nuxt"],
|
|
500
|
+
vitehub: { auth: { redirects: { login: "/sign-in", guest: "/app" } } },
|
|
501
|
+
})
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
On client navigation, the guard reads the session into the same state as `useUserSession()` and `useSession()`. 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.
|
|
505
|
+
|
|
506
|
+
The guard runs when the route changes. A sign-out does not change the route, so `signOut()` of `useUserSession()` does the guard's work: on a `'user'` page, it sends the visitor to the login page of that page, with `?redirect=<the page>`. `redirectTo` takes priority. Other pages stay open.
|
|
507
|
+
|
|
508
|
+
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.
|
|
509
|
+
|
|
510
|
+
## GitHub organization membership
|
|
511
|
+
|
|
512
|
+
`isGitHubOrgMember(accessToken, org, { cacheMs, timeoutMs })` from `@vite-hub/auth` returns `true` 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 `false`. 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.
|
|
513
|
+
|
|
514
|
+
```ts fragment
|
|
515
|
+
import { isGitHubOrgMember } from "@vite-hub/auth";
|
|
516
|
+
|
|
517
|
+
const member = await isGitHubOrgMember(account.accessToken, "acme", { cacheMs: 300_000 });
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
`checkGitHubOrgMember()` runs the same check and returns `[error, undefined]`, so the app can say why access failed. `error.code` is `AUTH_GITHUB_TOKEN_INVALID` (401 or no token), `AUTH_GITHUB_ORG_ACCESS_DENIED` (403, a missing `read:org` scope, or SAML single sign-on that the token is not authorized for), `AUTH_GITHUB_UNAVAILABLE` (network error, timeout, 429, 5xx, or rate limit), or `AUTH_GITHUB_NOT_ORG_MEMBER` (404 or a pending invitation). An empty `org` throws `AUTH_GITHUB_ORG_REQUIRED`.
|
|
521
|
+
|
|
522
|
+
```ts fragment
|
|
523
|
+
import { checkGitHubOrgMember } from "@vite-hub/auth";
|
|
524
|
+
|
|
525
|
+
const [error] = await checkGitHubOrgMember(account.accessToken, "acme", { cacheMs: 300_000 });
|
|
526
|
+
if (error?.code === "AUTH_GITHUB_TOKEN_INVALID") return redirectToSignIn();
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
## MCP OAuth
|
|
530
|
+
|
|
531
|
+
`@vite-hub/auth/forward` signs people in through a trusted reverse proxy, such as oauth2-proxy, Cloudflare Access, or Tailscale Serve. `forwardAuth({ header, verify })` is a Better Auth plugin. On each Better Auth request with the header, which includes every `getSession()` call and guard, it calls `verify({ value, headers, request })`. Auth never trusts the header by itself: `verify` must prove it, for example by calling the provider with the token, checking a JWT signature, or comparing a secret that only the proxy sends, and return `{ providerId, accountId, email, name, emailVerified, image?, accessToken? }` or `null`. An identity signs in as the Better Auth account `providerId:accountId`, with Better Auth's account linking rules, and the request sees the session at once. The session of the cookie, or a session that the process made for the same identity, is reused. `null` ignores the header. `forwardAuth()` without `header` or `verify` fails with `AUTH_C0067`, and a `verify` result that is not an identity fails the request with `AUTH_R0022`.
|
|
532
|
+
|
|
533
|
+
```ts
|
|
534
|
+
import { defineAuth } from "@vite-hub/auth";
|
|
535
|
+
import { forwardAuth } from "@vite-hub/auth/forward";
|
|
536
|
+
|
|
537
|
+
export default defineAuth({
|
|
538
|
+
plugins: [
|
|
539
|
+
forwardAuth({
|
|
540
|
+
header: "x-forwarded-user",
|
|
541
|
+
verify: ({ value, headers }) =>
|
|
542
|
+
headers.get("x-proxy-secret") === process.env.PROXY_SECRET
|
|
543
|
+
? { providerId: "proxy", accountId: value, email: value, name: value, emailVerified: true }
|
|
544
|
+
: null,
|
|
545
|
+
}),
|
|
546
|
+
],
|
|
547
|
+
});
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
`@vite-hub/auth/mcp` makes Better Auth the OAuth 2.1 authorization server of an MCP server that the app owns, such as `/mcp`. `mcpOAuth({ resource, loginPage })` returns `jwt()`, `oauthProvider()` with open dynamic registration for native MCP clients, and a guard that bounds the registration body and its fields. `serveMcpOAuthDiscovery(request)` answers the protected resource, authorization server, and OpenID documents at the origin root, with CORS for any origin and `204` for an `OPTIONS` preflight, and returns `undefined` for other paths. `verifyMcpRequest(request)` returns `[error, caller]` with the user, scopes, and client name of a valid access token. `deleteUnusedMcpClients()` deletes registrations that never finished sign-in. Install `@better-auth/oauth-provider` with the version of `better-auth` that this package uses.
|
|
551
|
+
|
|
552
|
+
```ts
|
|
553
|
+
// server/auth.ts
|
|
554
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
555
|
+
import { mcpOAuth } from "@vite-hub/auth/mcp"
|
|
556
|
+
|
|
557
|
+
export default defineAuth(({ requestOrigin }) => ({
|
|
558
|
+
baseURL: requestOrigin,
|
|
559
|
+
plugins: [...mcpOAuth({ resource: `${requestOrigin}/mcp`, loginPage: "/oauth" })],
|
|
560
|
+
}))
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
Read [Sign MCP clients in](https://vitehub.dev/docs/auth/configure#sign-mcp-clients-in).
|
|
564
|
+
|
|
299
565
|
## Authenticated Agents
|
|
300
566
|
|
|
301
567
|
Use `authenticated()` when an Agent should derive its Agent Invoker from the current Auth Session.
|
|
@@ -325,14 +591,32 @@ const error = new ViteHubError("AUTHENTICATION_REQUIRED", "Sign in to use this A
|
|
|
325
591
|
|
|
326
592
|
`error.toJSON()` includes `name`, `code`, and `message`, while omitting `cause` and stack data. If a default Better Auth request or session operation fails, `authenticated()`, `withAuth()`, and `withAuthorization()` throw the same shared error with code `AUTH_PROVIDER_OPERATION_FAILED` and safe operation details; raw provider diagnostics remain available only through `cause`. Existing ViteHub errors and structural `AbortError` objects keep their identity. Missing APIs, malformed responses, invalid Auth configuration, and invalid custom callback results use package-owned `AUTH_C####`, `AUTH_B####`, or `AUTH_R####` Nostics codes.
|
|
327
593
|
|
|
594
|
+
## Test a signed-in route
|
|
595
|
+
|
|
596
|
+
`signIn()` from `@vite-hub/auth/test` writes a user and a session to the Auth database and returns headers with the session cookie. Pass them to a `Request`, and `requireAuth()` accepts it. Auth creates the user when no user has this email, and other fields, such as `role`, go to the new user. It sends no email and calls no provider.
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
import { requireAuth } from "@vite-hub/auth/server";
|
|
600
|
+
import { signIn } from "@vite-hub/auth/test";
|
|
601
|
+
|
|
602
|
+
const { headers } = await signIn({ email: "ada@example.com", role: "admin" });
|
|
603
|
+
const { user } = await requireAuth(new Request("http://localhost/api/me", { headers }));
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
Apps that install `vite-hub` call `hub.signIn()` from `setupViteHubTest()`. In a test, the default memory database of a Definition without `database` is emptied by `reset()`. A Definition with the `stateless()` preset has no database, so `signIn()` fails with `AUTH_TEST_SIGN_IN_STATELESS`.
|
|
607
|
+
|
|
328
608
|
## Production checks
|
|
329
609
|
|
|
330
|
-
- Supply a strong Better Auth secret from Server Env at request time; never put it in Public Env, client code, Agent input, logs, or traces. Without `secret`, `secrets`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_SECRETS`, or `AUTH_SECRET`, Auth uses `deriveSecret("vitehub:auth")` from `VITEHUB_SECRET
|
|
610
|
+
- Supply a strong Better Auth secret from Server Env at request time; never put it in Public Env, client code, Agent input, logs, or traces. Without `secret`, `secrets`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_SECRETS`, or `AUTH_SECRET`, Auth uses `deriveSecret("vitehub:auth")` from `VITEHUB_SECRET`.
|
|
331
611
|
- Set request-aware `baseURL` or use `requestOrigin` so callback and cookie origins match the deployed host.
|
|
332
|
-
-
|
|
333
|
-
- Protect application and Console
|
|
612
|
+
- Use `authDatabase()` and apply its migration, configure another Better Auth database adapter, or use `stateless()` for social sign-in without a database.
|
|
613
|
+
- Protect application routes and the Console endpoint explicitly. Authentication proves a session; application-owned `authorize` callbacks define roles and permissions.
|
|
334
614
|
- Keep automatic `/api/auth/**` exposure enabled unless the host mounts the stable handler itself, and verify the chosen `basePath` on both server and client.
|
|
335
615
|
|
|
616
|
+
## Passwords in a WebContainer
|
|
617
|
+
|
|
618
|
+
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.
|
|
619
|
+
|
|
336
620
|
Read the complete [Auth guide](https://vitehub.dev/docs/auth), [Auth Users and Agent Invokers](https://vitehub.dev/docs/agents/invokers), the [host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix), and the project's [pre-1.0 security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md).
|
|
337
621
|
|
|
338
622
|
## Auth event log
|
|
@@ -341,7 +625,7 @@ Opt in with `events: { store: createDatabaseAuthEventStore({ db }) }` in `define
|
|
|
341
625
|
|
|
342
626
|
The default retention is 90 days and 100,000 records, with cleanup after each append. Override `retention.maxAgeMs` or `retention.maxRecords`, or use `retention: false`. IP addresses are discarded. User agents become a coarse device class. Admin updates store field names, not secret values.
|
|
343
627
|
|
|
344
|
-
Use `listAuthEvents(filters)` and `aggregateAuthEvents({ from, to })` from `@vite-hub/auth/server`, or use the store directly. Lists use cursor pagination and one SQL query after initialization. Aggregates use one statement for a consistent snapshot and count distinct users over the whole window. `@vite-hub/auth/runtime/console` exports these readers
|
|
628
|
+
Use `listAuthEvents(filters)` and `aggregateAuthEvents({ from, to })` from `@vite-hub/auth/server`, or use the store directly. Lists use cursor pagination and one SQL query after initialization. Aggregates use one statement for a consistent snapshot and count distinct users over the whole window. `@vite-hub/auth/runtime/console` exports these readers for the Console. No Console UI is added.
|
|
345
629
|
|
|
346
630
|
For `vitehub auth events`, configure `events.authorize`. The read endpoint requires a session and an explicit `true` result. Give the CLI the Auth base URL with `--url`, and the session cookie through `VITEHUB_AUTH_COOKIE`.
|
|
347
631
|
|
|
@@ -349,7 +633,7 @@ Event writes are separate from auth mutations. Storage failures warn with `AUTH_
|
|
|
349
633
|
|
|
350
634
|
## Auth Console
|
|
351
635
|
|
|
352
|
-
The primary Auth Definition adds
|
|
636
|
+
The primary Auth Definition adds an Auth section to the ViteHub Console. It lists users, active sessions, organizations, and approved OAuth clients. Better Auth additional fields become columns. Set `console.fields.<name>.editable` to allow edits, `console.columns` for batch computed values, and `console.roles` or `console.actions` for read-only policy with a reason. `console.roles.read` gives the Console roles that the app computes, for labels and the Admins filter, without writing them. `console.access` holds short descriptions of the app's sign-in rules.
|
|
353
637
|
|
|
354
638
|
`getAuthConsoleForRequest(request)` from `@vite-hub/auth/server` exposes the same inspection API to trusted server code. Changes use Better Auth's plugin APIs. Impersonation is off unless the host passes `{ impersonation: true }` as the third argument, as `console.impersonation` does, and it needs `events.store`.
|
|
355
639
|
|