@vite-hub/auth 0.6.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -12
- package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
- package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
- package/dist/agent.d.ts +2 -3
- package/dist/agent.js +31 -12
- package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
- package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1 -1
- package/dist/client-extension-BgUlm6hy.d.ts +33 -0
- package/dist/client-request-B1DCz3a9.js +29 -0
- package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
- package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -1
- package/dist/console.d.ts +1 -1
- package/dist/database-options-Cms7BI3c.js +36 -0
- package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +13 -8
- package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
- package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
- package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
- package/dist/extension-BWmjJhoN.d.ts +59 -0
- package/dist/extension-mCx4TrsO.js +133 -0
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +5 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +5 -4
- package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
- package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
- package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +27 -6
- package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
- package/dist/nuxt.d.ts +4 -14
- package/dist/nuxt.js +53 -20
- package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
- package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
- package/dist/presets.js +1 -1
- package/dist/roles-BGi8CyBG.js +17 -0
- package/dist/runtime/client-request-plugin.d.ts +2 -1
- package/dist/runtime/client-request-plugin.js +8 -5
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -1
- package/dist/runtime/empty-client.d.ts +3 -0
- package/dist/runtime/empty-client.js +3 -1
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/server.d.ts +4 -3
- package/dist/runtime/server.js +7 -4
- package/dist/runtime/vue-nuxt.js +27 -11
- package/dist/schema.d.ts +32 -14
- package/dist/schema.js +21 -14
- package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
- package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
- package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
- package/dist/server.d.ts +6 -3
- package/dist/server.js +9 -3
- package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
- package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
- package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
- package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
- package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
- package/dist/vite-CZ_Z6IR3.d.ts +28 -0
- package/dist/vite.d.ts +41 -6
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +4 -3
- package/dist/vue.js +39 -4
- package/package.json +9 -8
- package/dist/client-request-BzMKtfCY.js +0 -52
- package/dist/database-options-B87hDU4j.js +0 -28
package/README.md
CHANGED
|
@@ -72,11 +72,22 @@ 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
|
-
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
86
|
+
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path or the `#layers/<name>/` alias of a Nuxt layer, imports and calls them. A project plugin in the Definition or an extension adds its literal `schema` fields on `user`, `session`, `account`, and `verification`. A project plugin that adds a field to another plugin’s table still needs that field in the Database schema. A project plugin that the build cannot read fails with `AUTH_PLUGIN_SCHEMA_UNREADABLE`. An app Definition that replaces a Nuxt layer Definition must keep its tables and columns, or the build fails with `AUTH_LAYER_DEFINITION_REPLACED`. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
87
|
+
|
|
88
|
+
The tables have text IDs by default. With `advanced.database.generateId: "uuid"` written inline in the Definition, the plugin passes `generateId: "uuid"` to `createAuthPostgresSchema()`: on Postgres each `id` is `uuid` with a `gen_random_uuid()` default, each column that references an `id` is `uuid`, and the database makes the ID. SQLite has no uuid type, so its columns stay text and Better Auth makes the UUID. `serial` and `false` fail with `AUTH_C0053`, and so does a Postgres Database whose ID columns do not match the `generateId` of the running options. For a foreign key to a `uuid` ID, use a `uuid` column that references the generated `authPostgresSchema` table.
|
|
78
89
|
|
|
79
|
-
Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults.
|
|
90
|
+
Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. `authSqliteSchema` and `authPostgresSchema` give you the table objects that Auth contributes. Use them for foreign keys and for Drizzle relations to tables such as `user` and `organization`: `defineRelationsPart({ user: authSqliteSchema.user, order }, r => ({ order: { user: r.one.user({ from: r.order.userId, to: r.user.id }) } }))`.
|
|
80
91
|
|
|
81
92
|
## Delete an account
|
|
82
93
|
|
|
@@ -98,9 +109,9 @@ Pass `deleteAccount: { beforeDelete }` to delete the app's own rows first, or th
|
|
|
98
109
|
|
|
99
110
|
## First admin
|
|
100
111
|
|
|
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,
|
|
112
|
+
`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
113
|
|
|
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`.
|
|
114
|
+
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
115
|
|
|
105
116
|
Set `adminClaim: false` on another Auth Definition to make it ignore the host's claim value.
|
|
106
117
|
|
|
@@ -108,12 +119,14 @@ With a claim code set, Auth sets `verification.storeInDatabase: true`, including
|
|
|
108
119
|
|
|
109
120
|
## Members
|
|
110
121
|
|
|
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.
|
|
122
|
+
`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
123
|
|
|
113
124
|
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
125
|
|
|
115
126
|
`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
127
|
|
|
128
|
+
`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`.
|
|
129
|
+
|
|
117
130
|
## Sessions without a database
|
|
118
131
|
|
|
119
132
|
`stateless()` keeps each session in an encrypted cookie. Sessions survive restarts and work across replicas and Workers when every instance uses the same secret.
|
|
@@ -192,11 +205,13 @@ When `@vite-hub/env` is installed, the Auth Definition callback receives the typ
|
|
|
192
205
|
|
|
193
206
|
Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: true`. `requestOrigin`, the default `baseURL`, and the `Origin` check then use the first `X-Forwarded-Proto` and `X-Forwarded-Host` values. Set it only when a proxy you run sets these headers. It does not change the client IP of the rate limiter and `session.ipAddress`: on the Node host behind your own proxy, set `vitehub({ trustProxy: true })` for that. Proxy trust uses the options of the Definition, or the object that its callback returns.
|
|
194
207
|
|
|
195
|
-
Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
|
|
208
|
+
Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `authMiddleware()`, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
|
|
209
|
+
|
|
210
|
+
Auth keeps the `Origin` check on in dev, in tests, and in production. A `POST` that carries the session cookie, and every sign-in or sign-up `POST` that sends an `Origin`, answers `403` with `INVALID_ORIGIN` when the `Origin` is not `baseURL` or in `trustedOrigins`. Better Auth turns this check off when `TEST` or `NODE_ENV=test` is set, but Auth does not, so a server that a Vitest run starts checks the `Origin` as production does. To turn the check off, set `advanced.disableOriginCheck: true`.
|
|
196
211
|
|
|
197
212
|
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
213
|
|
|
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:
|
|
214
|
+
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
215
|
|
|
201
216
|
```ts
|
|
202
217
|
import { defineAuth } from "@vite-hub/auth"
|
|
@@ -208,6 +223,7 @@ export default defineAuth({
|
|
|
208
223
|
route: "/_vitehub/**",
|
|
209
224
|
authorize: ({ user }) => user.isAdmin === true,
|
|
210
225
|
},
|
|
226
|
+
{ route: "/api/dashboard/**", role: ["team", "admin"] },
|
|
211
227
|
],
|
|
212
228
|
},
|
|
213
229
|
});
|
|
@@ -256,7 +272,7 @@ The inline guards use H3's JSON error format. They keep the response status and
|
|
|
256
272
|
|
|
257
273
|
```ts fragment
|
|
258
274
|
import { requireAuth, requireAuthorization } from "@vite-hub/auth/server";
|
|
259
|
-
import { defineHandler } from "h3";
|
|
275
|
+
import { defineHandler } from "nitro/h3";
|
|
260
276
|
|
|
261
277
|
export const me = defineHandler(async (event) => {
|
|
262
278
|
const { user } = await requireAuth(event);
|
|
@@ -269,13 +285,32 @@ export const removePost = defineHandler(async (event) => {
|
|
|
269
285
|
});
|
|
270
286
|
```
|
|
271
287
|
|
|
288
|
+
H3 applies `validate.query` and `validate.headers` before the handler runs, so a guest who sends a bad query can get `400` before a guard in the handler runs. Put `authMiddleware(authorize?)` in the route's `middleware` to check access first. It returns nothing when the check passes, and rejects like `requireAuth()`, or like `requireAuthorization()` when you pass `authorize`. Do not put `requireAuth` itself in `middleware`: H3 sends what a middleware returns, which is the session. A `requireAuth(event)` in the handler reuses the session that the middleware read.
|
|
289
|
+
|
|
290
|
+
```ts fragment
|
|
291
|
+
import { authMiddleware, requireAuth } from "@vite-hub/auth/server";
|
|
292
|
+
import { defineValidatedHandler } from "nitro/h3";
|
|
293
|
+
import * as v from "valibot";
|
|
294
|
+
|
|
295
|
+
export const inbox = defineValidatedHandler({
|
|
296
|
+
middleware: [authMiddleware()],
|
|
297
|
+
validate: { query: v.object({ view: v.picklist(["open", "archived"]) }) },
|
|
298
|
+
handler: async (event) => {
|
|
299
|
+
const { user } = await requireAuth(event);
|
|
300
|
+
return { user: user.id, view: event.url.searchParams.get("view") };
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
For path parameters, call H3's `getValidatedRouterParams(event, schema)` in the handler after checking access.
|
|
306
|
+
|
|
272
307
|
### Better Auth instance
|
|
273
308
|
|
|
274
309
|
`useAuth(event)` returns the Better Auth instance of your Auth Definition for a request event or a Web `Request`. The Vite plugin writes the type of `server/auth.ts` to `.vitehub/types/auth.d.ts`, so the instance has the endpoints of your plugins without a cast:
|
|
275
310
|
|
|
276
311
|
```ts fragment
|
|
277
312
|
import { requireAuthorization, useAuth } from "@vite-hub/auth/server";
|
|
278
|
-
import { defineHandler } from "h3";
|
|
313
|
+
import { defineHandler } from "nitro/h3";
|
|
279
314
|
|
|
280
315
|
// server/auth.ts uses `admin()` from `better-auth/plugins`.
|
|
281
316
|
export default defineHandler(async (event) => {
|
|
@@ -284,6 +319,8 @@ export default defineHandler(async (event) => {
|
|
|
284
319
|
});
|
|
285
320
|
```
|
|
286
321
|
|
|
322
|
+
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.
|
|
323
|
+
|
|
287
324
|
## Session refresh
|
|
288
325
|
|
|
289
326
|
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 +375,11 @@ export { default } from '#vitehub/auth/server'
|
|
|
338
375
|
|
|
339
376
|
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
377
|
|
|
378
|
+
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.
|
|
379
|
+
|
|
341
380
|
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
381
|
|
|
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.
|
|
382
|
+
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
383
|
|
|
345
384
|
|
|
346
385
|
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.
|
|
@@ -433,6 +472,38 @@ const { client } = useUserSession();
|
|
|
433
472
|
const { data } = await client.admin.listUsers({ query: { limit: 10 } });
|
|
434
473
|
```
|
|
435
474
|
|
|
475
|
+
### Add to Auth from a Nuxt layer
|
|
476
|
+
|
|
477
|
+
A Nuxt layer that does not own the Auth Definition adds Better Auth server plugins and `user` fields with `extendAuth()` in `server/auth.extend.ts`, and client plugins with `extendAuthClient()` in `app/auth.client.extend.ts`. The app imports no layer file. The app can have both files too, and a Vite app has them in `server/` and beside `auth.client.ts`.
|
|
478
|
+
|
|
479
|
+
```ts
|
|
480
|
+
// layers/payments/server/auth.extend.ts
|
|
481
|
+
import { extendAuth } from "@vite-hub/auth";
|
|
482
|
+
|
|
483
|
+
export default extendAuth({
|
|
484
|
+
plugins: [
|
|
485
|
+
{
|
|
486
|
+
id: "polar",
|
|
487
|
+
schema: { user: { fields: { polarCustomerId: { type: "string", required: false } } } },
|
|
488
|
+
},
|
|
489
|
+
],
|
|
490
|
+
});
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
// layers/payments/app/auth.client.extend.ts
|
|
495
|
+
import { extendAuthClient } from "@vite-hub/auth/vue";
|
|
496
|
+
|
|
497
|
+
export default extendAuthClient({
|
|
498
|
+
plugins: [{ id: "polar" }],
|
|
499
|
+
});
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
- A part takes `plugins`, and `extendAuth()` also takes `user.additionalFields`. Each other option stays in `defineAuth()` or `defineAuthClient()`, or the build fails with `AUTH_EXTENSION_OPTION_INVALID`.
|
|
503
|
+
- Merge order: the Definition, the file of the app, then the files of the layers in Nuxt priority order. Each plugin list keeps its order.
|
|
504
|
+
- `server/auth.extend.ts` without an Auth Definition fails with `AUTH_EXTENSION_WITHOUT_DEFINITION`. Two sources with one plugin id fail with `AUTH_DUPLICATE_PLUGIN`. Two declarations of one `user` field with different attributes fail with `AUTH_FIELD_CONFLICT`.
|
|
505
|
+
- The runtime, the generated schema of `authDatabase()`, `.vitehub/types/auth.d.ts`, and `vitehub inspect definitions` read the same list of files.
|
|
506
|
+
|
|
436
507
|
The exported `createAuthClient` keeps Better Auth's option and plugin inference for a second client with its own base path or plugins. Without `basePath`, it uses the same path as the default client. The zero-config composables use ViteHub's shared default client. Its type is `RegisteredAuthClient`: `hubAuth()` writes the type of the Auth Definition to `.vitehub/types/auth.d.ts`, so `user` and `session` have the fields that `additionalFields`, server plugins such as `admin()`, and `customSession()` add. The client imports only this type, not server code. A client from `createAuthClient()` needs Better Auth's client plugins, such as `customSessionClient<RegisteredAuth>()`, and `inferAdditionalFields<RegisteredAuth>()` for the same fields. React, Svelte, Solid, and other framework clients remain available from Better Auth's framework entrypoints.
|
|
437
508
|
|
|
438
509
|
The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useUserSession()` returns its refs at once: they are pending until the client loads in the browser. In Nuxt, a call in a component starts with the session that the server read for the request, so it is settled during server rendering and hydration. The browser then does not load Better Auth or read the session again until the session can change: a call such as `signOut()`, `refresh()`, the tab shows again, the network comes back, another tab signs out or updates the user, Better Auth's `refetchInterval` passes, or the session expires. Like Better Auth, it waits while the browser is offline. Better Auth then starts with the server's session, so a read that fails does not sign the page out. So without a page guard, a page that only shows the user reads the session once, on the server. When the server's session is unknown, such as on a prerendered page, the browser loads Better Auth at once. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
|
|
@@ -513,6 +584,7 @@ const { data: sessions } = await useAsyncData("sessions", async () => {
|
|
|
513
584
|
| `'user'` or `true` | Visitors with a session | `access.signIn` (default `/login`), with `?redirect=<the page>`. A provider opens `<basePath>/sign-in`. |
|
|
514
585
|
| `'guest'` | Visitors without a session, such as on the login page | `access.afterSignIn` (default `/`) |
|
|
515
586
|
| `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
|
|
587
|
+
| `{ 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
588
|
| `false` | Everyone | |
|
|
517
589
|
| Not set | The mode of the most specific `access.pages` pattern, or everyone if no pattern matches | |
|
|
518
590
|
|
|
@@ -525,9 +597,9 @@ export default defineAuth({
|
|
|
525
597
|
})
|
|
526
598
|
```
|
|
527
599
|
|
|
528
|
-
To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, or `
|
|
600
|
+
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
601
|
|
|
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.
|
|
602
|
+
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
603
|
|
|
532
604
|
```ts
|
|
533
605
|
// server/auth.ts
|
|
@@ -616,6 +688,8 @@ export default defineAgent({
|
|
|
616
688
|
|
|
617
689
|
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
690
|
|
|
691
|
+
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.
|
|
692
|
+
|
|
619
693
|
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
694
|
|
|
621
695
|
```ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { H as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-CnO5bHEF.js";
|
|
2
2
|
/** A 4xx status that a rule can refuse with. `403` is the default. */
|
|
3
3
|
type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
|
|
4
4
|
declare const abilityDenial: unique symbol;
|
package/dist/abilities.d.ts
CHANGED
|
@@ -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-
|
|
1
|
+
import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-IOwpkcz4.js";
|
|
2
2
|
export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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
|
|
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 {
|
|
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
|
-
*
|
|
45
|
-
*
|
|
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-
|
|
2
|
-
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-
|
|
3
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-Bva-P-_C.js";
|
|
2
|
+
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-BNtY3hMp.js";
|
|
3
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
|
|
4
4
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
5
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
6
6
|
// src/agent.ts
|
|
@@ -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
|
-
|
|
12
|
+
function authUserIdOf(invoker) {
|
|
13
13
|
const meta = invoker?.meta;
|
|
14
|
-
|
|
14
|
+
return (isRecord(meta) ? nonEmptyString(meta.authUserId) : void 0) ?? (invoker?.kind === "authUser" ? nonEmptyString(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" ? nonEmptyString(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;
|
|
@@ -20,7 +36,7 @@ const agentAuth = { async user(invoker) {
|
|
|
20
36
|
} catch (cause) {
|
|
21
37
|
throwAuthenticationProviderError(cause, "get-user");
|
|
22
38
|
}
|
|
23
|
-
return isRecord(user) &&
|
|
39
|
+
return isRecord(user) && nonEmptyString(user.id) ? user : null;
|
|
24
40
|
} };
|
|
25
41
|
function authenticationRequired(message = "[vitehub] Authentication required.") {
|
|
26
42
|
if (!message || message.length > 16384) invalidAuthenticationErrorOptions();
|
|
@@ -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;
|
|
@@ -77,18 +96,18 @@ function readProviderField(read) {
|
|
|
77
96
|
}
|
|
78
97
|
}
|
|
79
98
|
async function createDefaultInvoker(options, context, providerFields) {
|
|
80
|
-
const userId = await resolveAuthenticatedValue(options.id, context) ?? providerFields?.userId ??
|
|
99
|
+
const userId = await resolveAuthenticatedValue(options.id, context) ?? providerFields?.userId ?? nonEmptyString(context.user.id);
|
|
81
100
|
if (!userId) throw authenticationRequired("[vitehub] Authenticated user is missing an id.");
|
|
82
101
|
const kind = await resolveAuthenticatedValue(options.kind, context) ?? "authUser";
|
|
83
102
|
const label = await resolveAuthenticatedValue(options.label, context) ?? (providerFields && readProviderField(() => defaultLabel(providerFields.user, providerFields.userId))) ?? defaultLabel(context.user);
|
|
84
|
-
const sessionId = providerFields ? readProviderField(() =>
|
|
103
|
+
const sessionId = providerFields ? readProviderField(() => nonEmptyString(providerFields.session.id)) : nonEmptyString(context.session.id);
|
|
85
104
|
return {
|
|
86
105
|
id: userId,
|
|
87
106
|
kind,
|
|
88
107
|
label,
|
|
89
108
|
meta: {
|
|
90
109
|
...normalizeMeta(await resolveAuthenticatedValue(options.meta, context)),
|
|
91
|
-
authUserId: providerFields?.userId ??
|
|
110
|
+
authUserId: providerFields?.userId ?? nonEmptyString(context.user.id) ?? userId,
|
|
92
111
|
...sessionId ? { authSessionId: sessionId } : {}
|
|
93
112
|
}
|
|
94
113
|
};
|
|
@@ -98,14 +117,14 @@ function resolveAuthenticatedValue(value, context) {
|
|
|
98
117
|
return value;
|
|
99
118
|
}
|
|
100
119
|
function defaultLabel(user, fallbackId = user.id) {
|
|
101
|
-
return
|
|
120
|
+
return nonEmptyString(user.email) ?? nonEmptyString(user.name) ?? fallbackId;
|
|
102
121
|
}
|
|
103
122
|
function normalizeMeta(value) {
|
|
104
123
|
if (!value) return {};
|
|
105
124
|
if (!isRecord(value)) throw authErrorDiagnostics.AUTH_R0002({ message: "[vitehub] authenticated({ meta }) must resolve to an object." });
|
|
106
125
|
return value;
|
|
107
126
|
}
|
|
108
|
-
function
|
|
127
|
+
function nonEmptyString(value) {
|
|
109
128
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
110
129
|
}
|
|
111
130
|
export { agentAuth, authenticated };
|