@vite-hub/auth 0.4.1 → 0.5.1
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 +32 -8
- package/dist/{abilities-CbmTAoS_.d.ts → abilities-3L1Y5Pnw.d.ts} +2 -4
- package/dist/abilities.d.ts +1 -1
- package/dist/abilities.js +1 -2
- package/dist/{ability-error-IeZQBr_-.js → ability-error-BHhPkrZd.js} +3 -5
- package/dist/{ability-error-DcgChwCN.d.ts → ability-error-C1c30O6E.d.ts} +1 -5
- package/dist/access-pages-BwImVHN_.js +94 -0
- package/dist/{admin-claim-code-CDipqeAU.js → admin-claim-code-C3X_U43x.js} +1 -2
- package/dist/agent.d.ts +1 -3
- package/dist/agent.js +5 -6
- package/dist/{application-path-DuTpfGFj.js → application-path-zKi7NrvK.js} +1 -2
- package/dist/{auth-instance-CmDogt4D.js → auth-instance-_J7R9Qs1.js} +239 -50
- package/dist/{cli-ubYJpAL_.d.ts → cli-C5pAfY4x.d.ts} +1 -6
- package/dist/cli.d.ts +2 -4
- package/dist/cli.js +3 -4
- package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-BP1ZKJB0.d.ts} +13 -13
- package/dist/{console-runtime-_LrpyCYY.js → console-runtime-vc3JQEuq.js} +72 -40
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -2
- package/dist/{console-types-CmmnKGMx.js → console-types-51lkf0lk.js} +1 -2
- package/dist/console.d.ts +1 -5
- package/dist/console.js +2 -3
- package/dist/{database-options-DpOVjUti.js → database-options-DQ-8qYMl.js} +2 -3
- package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CkSeU9V3.js} +2 -3
- package/dist/database.d.ts +1 -3
- package/dist/database.js +5 -6
- package/dist/{definition-BCaLA9kW.js → definition-MDGMNKrK.js} +20 -18
- package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-BssJr_2t.js} +9 -4
- package/dist/{events-DCfuicoo.js → events-DZqMiae_.js} +4 -6
- package/dist/forward.d.ts +1 -3
- package/dist/forward.js +2 -3
- package/dist/index.d.ts +4 -7
- package/dist/index.js +4 -3
- package/dist/internal/server.d.ts +4 -4
- package/dist/internal/server.js +5 -5
- package/dist/{invariant-D8_xBqmZ.js → invariant-Dj2R1eMr.js} +2 -3
- package/dist/{mcp-config-DRRlCAWN.js → mcp-config-C7srUMIZ.js} +2 -3
- package/dist/{mcp-token-CpxLyl_p.js → mcp-token--KuLYEub.js} +7 -18
- package/dist/mcp.d.ts +0 -4
- package/dist/mcp.js +4 -5
- package/dist/{members-DdlsS8kJ.js → members-D3_Q5XJb.js} +10 -14
- package/dist/nitro-kit-Bg4xUZAI.js +43 -0
- package/dist/{nuxt-bridge-Cl988STZ.js → nuxt-bridge-pRyfYD5c.js} +1 -2
- package/dist/nuxt.d.ts +31 -24
- package/dist/nuxt.js +336 -18
- package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
- package/dist/own-access-C22hSIuF.d.ts +18 -0
- package/dist/own-access-DQgqxTbI.js +30 -0
- package/dist/{page-tools-shared-l4eyj53D.js → page-tools-shared-CtoKaNQZ.js} +1 -2
- package/dist/{presets-CHndEv5i.d.ts → presets-C6AtiRdI.d.ts} +0 -2
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +2 -3
- package/dist/{request-z6DHHmrb.js → request-Dpq7GO8B.js} +2 -4
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -3
- package/dist/runtime/empty-abilities.js +1 -2
- package/dist/runtime/empty-client.d.ts +0 -2
- package/dist/runtime/empty-client.js +1 -2
- package/dist/runtime/empty-definition.d.ts +1 -3
- package/dist/runtime/empty-definition.js +1 -2
- package/dist/runtime/nuxt.d.ts +1 -3
- package/dist/runtime/nuxt.js +1 -2
- package/dist/runtime/server.d.ts +3 -2
- package/dist/runtime/server.js +27 -19
- package/dist/runtime/vue-nuxt.d.ts +0 -2
- package/dist/runtime/vue-nuxt.js +74 -33
- package/dist/{runtime-state-ojQCzKOc.js → runtime-state-DtKUfxKq.js} +1 -2
- package/dist/schema.d.ts +71 -23
- package/dist/schema.js +6 -5
- package/dist/{server-BM-RSf1T.d.ts → server-CFWlYQJb.d.ts} +7 -14
- package/dist/{server-BG_MFd4q.js → server-D4Hi4TBI.js} +51 -33
- package/dist/{server-C8TlOrSy.d.ts → server-DCsgxFPP.d.ts} +9 -14
- package/dist/server.d.ts +2 -2
- package/dist/server.js +2 -2
- package/dist/{session-cookies-DVzjOKc7.js → session-cookies-1FMcMnRh.js} +6 -8
- package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DkqM1kvj.js} +3 -5
- package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BLm_Zlss.d.ts} +255 -3
- package/dist/{table-specs-CURphR3n.js → table-specs-jw0jjU6l.js} +43 -44
- package/dist/test.d.ts +2 -4
- package/dist/test.js +3 -4
- package/dist/{types-CruflEFI.d.ts → types-BHSgxyvV.d.ts} +50 -11
- package/dist/{vite-Dy0Xhq4H.js → vite-D1xC9n1O.js} +365 -152
- package/dist/vite.d.ts +7 -14
- package/dist/vite.js +1 -2
- package/dist/vue.d.ts +17 -72
- package/dist/vue.js +25 -73
- package/package.json +35 -30
- package/dist/shared-DRtfuFsV.js +0 -12
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Most applications install `vite-hub`, `@vite-hub/auth`, and `better-auth`, and e
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
16
16
|
```sh
|
|
17
|
-
pnpm add @vite-hub/auth better-auth drizzle-orm@1.0.0-rc.
|
|
17
|
+
pnpm add @vite-hub/auth better-auth drizzle-orm@1.0.0-rc.6 nitro
|
|
18
18
|
pnpm add -D vite
|
|
19
19
|
```
|
|
20
20
|
|
|
@@ -74,7 +74,9 @@ export default defineAuth({
|
|
|
74
74
|
|
|
75
75
|
`authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
|
|
76
76
|
|
|
77
|
-
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
77
|
+
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
78
|
+
|
|
79
|
+
Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. Use `authSqliteSchema` and `authPostgresSchema` for foreign keys to core tables such as `user` and `organization`.
|
|
78
80
|
|
|
79
81
|
## Delete an account
|
|
80
82
|
|
|
@@ -188,7 +190,7 @@ export default defineAuth(({ env, requestOrigin }) => ({
|
|
|
188
190
|
|
|
189
191
|
When `@vite-hub/env` is installed, the Auth Definition callback receives the typed server env. It also receives `requestOrigin`, so same-origin apps do not need a separate auth URL environment variable.
|
|
190
192
|
|
|
191
|
-
Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: true`. `requestOrigin`, the default `baseURL`, and the `Origin` check then use the first `X-Forwarded-Proto` and `X-Forwarded-Host` values. Set it only when a proxy you run sets these headers. Proxy trust uses the options of the Definition, or the object that its callback returns.
|
|
193
|
+
Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: true`. `requestOrigin`, the default `baseURL`, and the `Origin` check then use the first `X-Forwarded-Proto` and `X-Forwarded-Host` values. Set it only when a proxy you run sets these headers. It does not change the client IP of the rate limiter and `session.ipAddress`: on the Node host behind your own proxy, set `vitehub({ trustProxy: true })` for that. Proxy trust uses the options of the Definition, or the object that its callback returns.
|
|
192
194
|
|
|
193
195
|
Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
|
|
194
196
|
|
|
@@ -475,18 +477,18 @@ export default defineAbilities({
|
|
|
475
477
|
A rule gets the signed-in user, then its arguments, and returns at once. `true` allows. `false` and a code refuse with `403`, and `deny(code, { status, details })` with another 4xx status. A signed-out visitor gets `401` with the code `signed-out` before the rule runs, except in a `guest()` rule, where `user` is `null`. The Vite plugin serves the file as `#vitehub/auth/abilities` and registers its type in `.vitehub/types/auth.d.ts`, so ability names and arguments type-check.
|
|
476
478
|
|
|
477
479
|
- Server: `requireAbility(event, name, ...args)` from `@vite-hub/auth/server` returns the checked `{ request, session, user }`, or throws `AbilityError`. H3 2 sends it with the rule's status and `{ code, details }` in `data`. `can(event, name, ...args)` returns a boolean.
|
|
478
|
-
- Vue: `useAbility().can(name, ...args)`, `useAbility().cannot(name, ...args)`, `<
|
|
480
|
+
- Vue: `useAbility().can(name, ...args)`, `useAbility().cannot(name, ...args)`, and `<AuthPermission check="posts.edit" :args="[post]">` from `@vite-hub/auth/vue`. The component renders `#allowed` or `#denied` with `{ code, details }`. Default content is shorthand for `#allowed`; a named `#allowed` takes precedence. Neither slot renders until the session is known or while `pending` is true. All rules use an `args` tuple, checked against the rule signature. Nuxt registers the component only when the app or a layer has `shared/abilities.ts`, and an app component with the same name wins. Set `components: { prefix: "Custom" }` in `defineAuth()` to register `<CustomAuthPermission>`. Prefixes follow Nuxt's component prefix rules, which drop the prefix words that the name starts with: `MyAuth` registers `<MyAuthPermission>`.
|
|
479
481
|
- Vue pages: `await useAbility().authorize(name, ...args)` throws when the rule refuses, with the status and `{ code, details }` data of `requireAbility()`. In Nuxt, the error is fatal and shows the error page. Without Nuxt, it is an `AbilityError`. In the browser, except while Nuxt hydrates, it sends one `/get-session` request for the current session. On the server, a session that the server could not read counts as signed out.
|
|
480
482
|
|
|
481
|
-
Nuxt uses the Auth Definition's base path for the shared browser client. In other Vue apps, call `provideAuthClient(client)` from `@vite-hub/auth/vue` in a parent component's setup to share a custom client with descendant Auth composables and `<
|
|
483
|
+
Nuxt uses the Auth Definition's base path for the shared browser client. In other Vue apps, call `provideAuthClient(client)` from `@vite-hub/auth/vue` in a parent component's setup to share a custom client with descendant Auth composables and `<AuthPermission>`. You can also pass a client directly to `useAbility(client)`.
|
|
482
484
|
|
|
483
485
|
`requireAuthorization(event, authorize)` checks inside the handler, and `withAuthorization()` wraps it. Use them for checks that need only the user. A rule that needs data the handler loads belongs in `shared/abilities.ts`.
|
|
484
486
|
|
|
485
487
|
## Nuxt: server session and page guard
|
|
486
488
|
|
|
487
|
-
In Nuxt, the server reads the session only for a page that needs it: a page with an `auth` guard, or a page whose components call `useUserSession()` or `useAbility()`, or render `<
|
|
489
|
+
In Nuxt, the server reads the session only for a page that needs it: a page with an `auth` guard, or a page whose components call `useUserSession()` or `useAbility()`, or render `<AuthPermission>`. It reads the session once for each page request, waits for it before it renders those components, settles their refs as soon as it has the session, so an async `setup()` can wait for `ready`, and sends it to the browser in the page payload, without the session token. `useUserSession()` starts from it, so a signed-in page renders signed in on the server and does not flash signed out while Better Auth loads. A call outside a component, such as in a plugin or a route middleware, cannot make the server wait, so on the server it starts pending unless the page guard already read the session. To protect a page, use the `auth` page guard. A request without a session cookie skips the lookup, so pages for signed-out visitors do not load Better Auth. A prerendered or cached page was rendered without the visitor's cookie, so its session counts as unknown.
|
|
488
490
|
|
|
489
|
-
The browser downloads Better Auth's client only when the page uses it. The Auth composables come the same way: with a page that calls them or renders `<
|
|
491
|
+
The browser downloads Better Auth's client only when the page uses it. The Auth composables come the same way: with a page that calls them or renders `<AuthPermission>`, or when the browser opens a page with an `auth` guard. The Auth plugin in the app entry is about 2 KB gzipped. Nuxt prefetches neither on other pages.
|
|
490
492
|
|
|
491
493
|
The server session lookup, the page guard, and the auto-imported composables use the Auth Definition's `basePath`, below Nuxt's `app.baseURL`.
|
|
492
494
|
|
|
@@ -511,7 +513,8 @@ const { data: sessions } = await useAsyncData("sessions", async () => {
|
|
|
511
513
|
| `'user'` or `true` | Visitors with a session | `access.signIn` (default `/login`), with `?redirect=<the page>`. A provider opens `<basePath>/sign-in`. |
|
|
512
514
|
| `'guest'` | Visitors without a session, such as on the login page | `access.afterSignIn` (default `/`) |
|
|
513
515
|
| `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
|
|
514
|
-
| `false`
|
|
516
|
+
| `false` | Everyone | |
|
|
517
|
+
| Not set | The mode of the most specific `access.pages` pattern, or everyone if no pattern matches | |
|
|
515
518
|
|
|
516
519
|
```ts
|
|
517
520
|
// server/auth.ts
|
|
@@ -522,12 +525,29 @@ export default defineAuth({
|
|
|
522
525
|
})
|
|
523
526
|
```
|
|
524
527
|
|
|
528
|
+
To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, or `false` in `access.pages`. The Nuxt module reads it at build time and adds the guard to the `appMiddleware` route rule of each pattern, so the server render and navigation in the browser send the visitor to the same page. The most specific pattern wins, `false` removes the guard of a wider pattern, and `definePageMeta({ auth })` of a page wins over all patterns. A key has static segments, `:name`, and a last `/**`. Optional, repeated, and regex params stop the build with `AUTH_PAGE_ROUTES_INVALID`, because Nuxt then orders patterns by position and not by how specific they are. So do two keys that match the same pages, such as keys that differ only in param names, letter case, or percent-encoding.
|
|
529
|
+
|
|
530
|
+
The build also stops with `AUTH_PAGE_ROUTES_INVALID` when `access.pages` applies a `'user'` guard to `access.signIn` or to a `redirectTo` for signed-out visitors. A guest-only page can still redirect signed-in users to a `'user'` page.
|
|
531
|
+
|
|
532
|
+
```ts
|
|
533
|
+
// server/auth.ts
|
|
534
|
+
import { defineAuth } from "@vite-hub/auth"
|
|
535
|
+
|
|
536
|
+
export default defineAuth({
|
|
537
|
+
access: { pages: { "/dashboard/**": "user", "/dashboard/pricing": false, "/login": "guest" } },
|
|
538
|
+
})
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
On client navigation, the guard reads the session, so Better Auth can extend an active session and the guard sees each sign-in and sign-out. On the first navigation during hydration, the guard can reuse a signed-in session from the server for the same guarded page, but not for a prerendered or cached page. A signed-out server response still needs a browser read: cookies scoped to the Auth endpoint may not reach the page request. Only the latest navigation decides: when a newer navigation starts before the session read answers, the guard ignores the answer. The guard never redirects a page to itself.
|
|
542
|
+
|
|
525
543
|
On client navigation, the guard reads the session into the same state as `useUserSession()`. When the guard finds that the session ended, such as after a sign-out in another tab, every component shows the visitor as signed out before the redirect.
|
|
526
544
|
|
|
527
545
|
The guard runs when the route changes. On a `'user'` page, `signOut()` of `useUserSession()` sends the visitor to its sign-in page, with `?redirect=<the page>`. `redirectTo` takes priority. With provider sign-in and no `redirectTo`, Nuxt shows a signed-out page instead of starting OAuth again: even `/` might be protected. Pass `signOut({ redirectTo: '/goodbye' })` to send the visitor to a public page of your choice. Other pages stay open by default.
|
|
528
546
|
|
|
529
547
|
The page guard decides where the browser goes. Protect data in server routes with `withAuth()`, `requireAuth()`, or `access.routes`. Read [Protect pages in Nuxt](https://vitehub.dev/docs/auth/protect-pages) for the full task.
|
|
530
548
|
|
|
549
|
+
The Nitro build fails with `AUTH_GUARDED_PAGE_CACHED` when a route rule caches or prerenders a page that `definePageMeta({ auth })` guards: `swr`, `cache`, `isr`, `prerender`, or `static`. The page guard runs when the server renders the page, so a cached page serves the render of one visitor to all visitors. Set `cache: false` or `prerender: false` on the guarded pattern to turn off a wider rule. The check reads `<page>/_payload.json` as a separate path, so use a pattern such as `'/dashboard/**'` that matches the page and its payload. A public page with a static path, such as `/users/public`, may be cached when the route rule key is that exact path or its `/_payload.json`. A guest page, such as the login page, may be prerendered, and a path with `ssr: false` is not checked. With `access.pages`, a path whose most specific key is `false` may be cached, and a path whose most specific key is `'guest'` may be prerendered. The check reads `auth` when `definePageMeta()` sets it to a literal value. The module adds `auth` to Nuxt's `experimental.extraPageMetaExtractionKeys` for this.
|
|
550
|
+
|
|
531
551
|
## GitHub organization membership
|
|
532
552
|
|
|
533
553
|
`checkGitHubOrgMember(accessToken, org, { cacheMs, timeoutMs })` from `@vite-hub/auth` returns `[undefined, undefined]` only for an active membership. The token needs `read:org`. A pending invitation, a non-2xx response, a network error, or a timeout (default 5 seconds) returns `[error, undefined]`, so the app can say why access failed. There is no cache by default. With `cacheMs`, a successful check is kept in memory for that time per token and organization, under a SHA-256 key.
|
|
@@ -628,6 +648,10 @@ Apps that install `vite-hub` call `hub.signIn()` from `setupViteHubTest()`. In a
|
|
|
628
648
|
- Protect application routes and the Console endpoint explicitly. Authentication proves a session; application-owned `authorize` callbacks define roles and permissions.
|
|
629
649
|
- Keep automatic `/api/auth/**` exposure enabled unless the host mounts the stable handler itself, and verify the chosen `basePath` on both server and client.
|
|
630
650
|
|
|
651
|
+
## Auth outcomes in request logs
|
|
652
|
+
|
|
653
|
+
With the evlog Nitro module registered, each request's wide event gets an `auth` field: `{ outcome, path?, provider?, status?, code?, userId? }`. `outcome` is `success` for a completed sign-in or sign-up, `failure` for a Better Auth error, such as a failed OAuth callback that the browser only sees as a redirect with `?error=`, and `refused` for a refusal of an Auth guard. `code` is Better Auth's error code, the OAuth `error`, or `SIGNED_OUT` / `FORBIDDEN`. Better Auth's warnings and errors also go on the event; the app's own `logger` option still gets every message. The event never holds an email address, a token, or a URL query. Without evlog, nothing is set. See [Server API](https://vitehub.dev/docs/auth/server-api#see-auth-outcomes-on-each-request).
|
|
654
|
+
|
|
631
655
|
## Passwords in a WebContainer
|
|
632
656
|
|
|
633
657
|
In a StackBlitz WebContainer, every `node:crypto` `scrypt` call fails. There, Auth sets `emailAndPassword.password` to the scrypt of `@noble/hashes`, with Better Auth's default parameters and `salt:key` format. A hash made on another host verifies in the WebContainer, and the other way around. Auth logs one `[vitehub] Auth hashes passwords with the scrypt of @noble/hashes` line when it first builds its options. Hashing is slower (about 3 seconds per sign-up or sign-in). A `hash` or `verify` function in the Auth Definition always wins. Other hosts keep Better Auth's default.
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
//#region src/abilities.d.ts
|
|
1
|
+
import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BHSgxyvV.js";
|
|
3
2
|
/** A 4xx status that a rule can refuse with. `403` is the default. */
|
|
4
3
|
type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
|
|
5
4
|
declare const abilityDenial: unique symbol;
|
|
@@ -75,7 +74,7 @@ type RefusalOf<Verdict> = Verdict extends false ? {
|
|
|
75
74
|
details: undefined;
|
|
76
75
|
} : never;
|
|
77
76
|
/**
|
|
78
|
-
* Each way a rule can refuse, as `<
|
|
77
|
+
* Each way a rule can refuse, as `<AuthPermission>` passes it to the `#denied` slot and the server error puts it in `data`.
|
|
79
78
|
* A signed-out visitor gets `signed-out` from every rule that is not open to guests.
|
|
80
79
|
*
|
|
81
80
|
* @example
|
|
@@ -89,5 +88,4 @@ type AbilityRefusal<Name extends string = AbilityName> = (Name extends keyof Reg
|
|
|
89
88
|
type AbilityAuthorization<Name extends string> = Name extends keyof RegisteredAbilities ? RegisteredAbilities[Name] extends {
|
|
90
89
|
guest: true;
|
|
91
90
|
} ? AuthAuthorization | AuthAnonymousAuthorization : AuthAuthorization : AuthAuthorization;
|
|
92
|
-
//#endregion
|
|
93
91
|
export { AbilityRefusal as a, AbilityStatus as c, GuestAbilityRule as d, defineAbilities as f, AbilityName as i, AbilityUser as l, guest as m, AbilityAuthorization as n, AbilityRule as o, deny as p, AbilityDenial as r, AbilityRules as s, AbilityArgs as t, AbilityVerdict as u };
|
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-3L1Y5Pnw.js";
|
|
2
2
|
export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
|
package/dist/abilities.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/abilities.ts
|
|
2
2
|
/**
|
|
3
3
|
* Defines the app's rules in `shared/abilities.ts`. The server and the app run the same rules.
|
|
4
4
|
*
|
|
@@ -39,5 +39,4 @@ function guest(rule) {
|
|
|
39
39
|
Object.defineProperty(open, "guest", { value: true });
|
|
40
40
|
return open;
|
|
41
41
|
}
|
|
42
|
-
//#endregion
|
|
43
42
|
export { defineAbilities, deny, guest };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
|
|
2
2
|
import { HTTPError } from "nitro/h3";
|
|
3
|
-
|
|
3
|
+
// src/ability-check.ts
|
|
4
4
|
const signedOut = Object.freeze({
|
|
5
5
|
status: 401,
|
|
6
6
|
code: "signed-out"
|
|
@@ -39,8 +39,7 @@ function toRefusal(verdict, name) {
|
|
|
39
39
|
}
|
|
40
40
|
return { status: 403 };
|
|
41
41
|
}
|
|
42
|
-
|
|
43
|
-
//#region src/ability-error.ts
|
|
42
|
+
// src/ability-error.ts
|
|
44
43
|
const statusTexts = {
|
|
45
44
|
400: "Bad Request",
|
|
46
45
|
401: "Unauthorized",
|
|
@@ -87,5 +86,4 @@ var AbilityError = class extends HTTPError {
|
|
|
87
86
|
};
|
|
88
87
|
}
|
|
89
88
|
};
|
|
90
|
-
//#endregion
|
|
91
89
|
export { checkAbility as n, AbilityError as t };
|
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import { HTTPError } from "nitro/h3";
|
|
2
|
-
//#region src/ability-check.d.ts
|
|
3
2
|
/** Why a rule refused: the HTTP status, and the code and details for the page. */
|
|
4
3
|
interface AbilityCheckRefusal {
|
|
5
4
|
status: number;
|
|
6
5
|
code?: string;
|
|
7
6
|
details?: unknown;
|
|
8
7
|
}
|
|
9
|
-
|
|
10
|
-
//#region src/ability-error.d.ts
|
|
11
|
-
/** The code and details of a refusal, as the error body's `data` and the `#denied` slot of `<Can>` carry them. */
|
|
8
|
+
/** The code and details of a refusal, as the error body's `data` and the `#denied` slot of `<AuthPermission>` carry them. */
|
|
12
9
|
interface AbilityErrorData {
|
|
13
10
|
code?: string;
|
|
14
11
|
details?: unknown;
|
|
@@ -30,5 +27,4 @@ declare class AbilityError extends HTTPError<AbilityErrorData> {
|
|
|
30
27
|
data: AbilityErrorData;
|
|
31
28
|
};
|
|
32
29
|
}
|
|
33
|
-
//#endregion
|
|
34
30
|
export { AbilityErrorData as n, AbilityError as t };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
|
|
2
|
+
// src/shared.ts
|
|
3
|
+
const defaultAuthBasePath = "/api/auth";
|
|
4
|
+
function normalizeAuthBasePath(value) {
|
|
5
|
+
const path = value?.trim() || defaultAuthBasePath;
|
|
6
|
+
if (!path.startsWith("/")) throw authErrorDiagnostics.AUTH_R0013({ message: "`defineAuth()` basePath must start with `/`." });
|
|
7
|
+
const normalized = path.replace(/\/+$/g, "");
|
|
8
|
+
if (!normalized) throw authErrorDiagnostics.AUTH_R0013({ message: "`defineAuth()` basePath must resolve to a non-empty path." });
|
|
9
|
+
return normalized;
|
|
10
|
+
}
|
|
11
|
+
// src/access-pages.ts
|
|
12
|
+
/**
|
|
13
|
+
* Normalizes a path as Nuxt does before it matches route rules: it decodes percent-encoding and, unless the router is
|
|
14
|
+
* case sensitive, folds each UTF-16 code unit to the lower case of its upper case. That is how a Vue Router path regular
|
|
15
|
+
* expression with the `i` flag and without `u` compares characters, so `σ`, `ς`, and `Σ` match.
|
|
16
|
+
*/
|
|
17
|
+
function normalizePagePath(path, sensitive = false) {
|
|
18
|
+
const decoded = decodePath(path);
|
|
19
|
+
if (sensitive) return decoded;
|
|
20
|
+
return decoded.replace(/[A-Z]+|[^\0-\x7F]/g, (char) => {
|
|
21
|
+
if (char.charCodeAt(0) < 128) return char.toLowerCase();
|
|
22
|
+
const upper = char.toUpperCase();
|
|
23
|
+
if (upper.length !== 1 || upper.charCodeAt(0) < 128) return char;
|
|
24
|
+
const lower = upper.toLowerCase();
|
|
25
|
+
return lower.length === 1 && lower.toUpperCase() === upper ? lower : upper;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Nuxt keeps a path that `decodeURI()` rejects as it is. */
|
|
29
|
+
function decodePath(path) {
|
|
30
|
+
try {
|
|
31
|
+
return decodeURI(path);
|
|
32
|
+
} catch {
|
|
33
|
+
return path;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Nuxt orders matches by their segments from the left: a static segment, then `:name` or `*`, then `**`. */
|
|
37
|
+
function segmentRank(segment) {
|
|
38
|
+
if (segment === void 0) return 3;
|
|
39
|
+
if (segment.startsWith("**")) return 0;
|
|
40
|
+
return segment.startsWith(":") || segment === "*" ? 1 : 2;
|
|
41
|
+
}
|
|
42
|
+
/** True when the pattern `a` wins over the pattern `b` on every path that both match. */
|
|
43
|
+
function accessPageBeats(a, b) {
|
|
44
|
+
const left = a.split("/").slice(1);
|
|
45
|
+
const right = b.split("/").slice(1);
|
|
46
|
+
for (let index = 0; index < Math.max(left.length, right.length); index++) {
|
|
47
|
+
const order = segmentRank(left[index]) - segmentRank(right[index]);
|
|
48
|
+
if (order) return order > 0;
|
|
49
|
+
}
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
/** Finds the winning key in Nuxt's merge order: ordinary matches, then new matches through encoded slashes. */
|
|
53
|
+
async function createAccessPageMatcher(pages, sensitive = false) {
|
|
54
|
+
const { addRoute, createRouter, findAllRoutes } = await import("rou3");
|
|
55
|
+
const router = createRouter();
|
|
56
|
+
for (const key of Object.keys(pages)) addRoute(router, "", normalizePagePath(key, sensitive), key);
|
|
57
|
+
const match = (path) => {
|
|
58
|
+
const normalized = normalizePagePath(path, sensitive).replace(/[\0-\x20"#<>^`{}\x7F-\uFFFC]+/g, (run) => encodeURIComponent(run.replace(/[\uD800-\uDFFF]/gu, "�")));
|
|
59
|
+
return findAllRoutes(router, "", normalized, { params: false }).map((route) => route.data);
|
|
60
|
+
};
|
|
61
|
+
return (path) => {
|
|
62
|
+
const matches = match(path);
|
|
63
|
+
const split = path.replace(/%2f/gi, "/");
|
|
64
|
+
if (split !== path) matches.push(...match(split).filter((key) => !matches.includes(key)));
|
|
65
|
+
return matches.at(-1);
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** A static segment or `:name`. */
|
|
69
|
+
const pageSegment = /^(?:[^:*?+(){}/]+|:[A-Za-z_]\w*)$/;
|
|
70
|
+
/**
|
|
71
|
+
* Checks `access.pages`. The Nuxt module attaches the page guard to each pattern with an `appMiddleware` route rule,
|
|
72
|
+
* and Nuxt merges the rules of all matching patterns so that the most specific pattern wins.
|
|
73
|
+
*
|
|
74
|
+
* Nuxt orders matches by their segments from the left: a static segment wins over `:name`, which wins over `**`.
|
|
75
|
+
* Optional, repeated, and regex params and duplicate patterns break this order, because Nuxt then orders the matches by
|
|
76
|
+
* position in `routeRules`. A `*` matches one segment in the middle of a pattern but every depth at its end, so
|
|
77
|
+
* `access.pages` does not accept it. Only the patterns that keep the order pass, so a wider pattern never silently
|
|
78
|
+
* replaces a narrower one.
|
|
79
|
+
*/
|
|
80
|
+
function assertAuthPages(pages) {
|
|
81
|
+
if (typeof pages !== "object" || pages === null || Array.isArray(pages)) throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access.pages must be an object of route patterns." });
|
|
82
|
+
const shapes = /* @__PURE__ */ new Map();
|
|
83
|
+
for (const [path, mode] of Object.entries(pages)) {
|
|
84
|
+
const invalid = (reason) => authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(path)}: ${JSON.stringify(mode)}. ${reason}` });
|
|
85
|
+
if (mode !== "user" && mode !== "guest" && mode !== false) throw invalid("A value must be 'user', 'guest', or false.");
|
|
86
|
+
const segments = path.split("/").slice(1);
|
|
87
|
+
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
|
+
const shape = segments.map((segment) => segment.startsWith(":") ? ":" : normalizePagePath(segment)).join("/");
|
|
89
|
+
const same = shapes.get(shape);
|
|
90
|
+
if (same !== void 0) throw invalid(`It matches the same pages as ${JSON.stringify(same)}. Keep one of them.`);
|
|
91
|
+
shapes.set(shape, path);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export { normalizeAuthBasePath as a, normalizePagePath as i, assertAuthPages as n, createAccessPageMatcher as r, accessPageBeats as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/admin-claim-code.ts
|
|
2
2
|
/** The variable with the SHA-256 of a one-time claim code, written by `vitehub auth claim`. */
|
|
3
3
|
const adminClaimVariable = "VITEHUB_ADMIN_CLAIM";
|
|
4
4
|
/** Crockford Base32 without I, L, O, and U, so a person can read the code aloud without mistakes. */
|
|
@@ -18,5 +18,4 @@ async function adminClaimHash(code) {
|
|
|
18
18
|
const normalized = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
|
|
19
19
|
return `sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(normalized)))].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
20
20
|
}
|
|
21
|
-
//#endregion
|
|
22
21
|
export { adminClaimVariable as n, createAdminClaimCode as r, adminClaimHash as t };
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
2
|
import { AgentInvoker, AgentInvokerOptions, AgentInvokerResolveContext, AgentRuntimeConfig, MaybePromise } from "@vite-hub/agent";
|
|
3
|
-
//#region src/agent.d.ts
|
|
4
3
|
export interface AuthenticatedUser {
|
|
5
4
|
email?: string | null;
|
|
6
5
|
id: string;
|
|
@@ -49,5 +48,4 @@ export interface AgentAuth {
|
|
|
49
48
|
user(invoker: AgentInvoker | null | undefined): Promise<AuthenticatedUser | null>;
|
|
50
49
|
}
|
|
51
50
|
export declare const agentAuth: AgentAuth;
|
|
52
|
-
export declare function authenticated<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData>(options?: AuthenticatedOptions<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>): AgentInvokerOptions<TRuntimeConfig, CALL_OPTIONS>;
|
|
53
|
-
//#endregion
|
|
51
|
+
export declare function authenticated<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData>(options?: AuthenticatedOptions<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>): AgentInvokerOptions<TRuntimeConfig, CALL_OPTIONS>;
|
package/dist/agent.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import {
|
|
1
|
+
import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DkqM1kvj.js";
|
|
2
|
+
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-1FMcMnRh.js";
|
|
3
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
|
|
4
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
5
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
6
|
-
|
|
6
|
+
// src/agent.ts
|
|
7
7
|
let server;
|
|
8
8
|
const loadServer = () => server ??= import("./internal/server.js").catch((error) => {
|
|
9
9
|
server = void 0;
|
|
@@ -108,5 +108,4 @@ function normalizeMeta(value) {
|
|
|
108
108
|
function readString(value) {
|
|
109
109
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
110
110
|
}
|
|
111
|
-
//#endregion
|
|
112
111
|
export { agentAuth, authenticated };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/application-path.ts
|
|
2
2
|
/**
|
|
3
3
|
* Prefix an application path with a base URL, such as Nitro `baseURL`. A path that already starts with the base path is
|
|
4
4
|
* returned unchanged, so a caller such as Console Auth that mounts its own paths below the base path is not prefixed
|
|
@@ -58,5 +58,4 @@ function resolveAccessRoutePath(route, baseURL = authApplicationBaseURL()) {
|
|
|
58
58
|
recursive
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
|
-
//#endregion
|
|
62
61
|
export { resolveAuthMountPath as i, canonicalAccessPath as n, resolveAccessRoutePath as r, accessRouteSyntaxError as t };
|