@vite-hub/auth 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -7
- package/dist/{abilities-D3XlrYDw.d.ts → abilities-CfvuGrBv.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-D3-u8k1A.js → ability-error-OKoyOwPM.js} +1 -1
- package/dist/{access-pages-9aKr6z-k.js → access-pages-Bej95blM.js} +10 -3
- package/dist/agent.d.ts +2 -3
- package/dist/agent.js +25 -6
- package/dist/{auth-instance-BpI9Ps8A.js → auth-instance-5RSiFTDC.js} +151 -82
- 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-request-BzMKtfCY.js +52 -0
- package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Bg_PAl7e.js} +5 -3
- package/dist/{console-runtime-DAjLTLrN.d.ts → console-runtime-XcplYv4R.d.ts} +1 -1
- 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-B87hDU4j.js → database-options-DE9lMwu1.js} +1 -1
- package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-CCQsNhjc.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +4 -4
- package/dist/{definition-BypPLIbI.js → definition-DeEeqTLC.js} +18 -4
- package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DkzL9ltR.js} +13 -4
- package/dist/{events-BXU1_9mc.js → events-BUaoHFoC.js} +1 -1
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +5 -4
- package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-DG1jmw4o.d.ts} +1 -0
- package/dist/{mcp-token-DzGivm7f.js → mcp-token-DgveSGEl.js} +28 -8
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +4 -2
- package/dist/{members-CwPIx10t.js → members-CRlYyxVk.js} +188 -152
- package/dist/nuxt.d.ts +1 -1
- package/dist/nuxt.js +27 -14
- package/dist/{own-access-Dt-I5-PT.d.ts → own-access-BvVUjaeL.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 +1 -0
- package/dist/runtime/client-request-plugin.js +18 -0
- 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-definition.d.ts +1 -1
- package/dist/runtime/server.d.ts +2 -2
- package/dist/runtime/server.js +5 -3
- package/dist/runtime/vue-nuxt.js +27 -11
- package/dist/schema.js +1 -1
- package/dist/{server-Cun232hb.d.ts → server-1G_BbfBD.d.ts} +20 -7
- package/dist/{server-DL9MSuyj.d.ts → server-B8kTFrHP.d.ts} +3 -2
- package/dist/{server-_eUOlAJ8.js → server-iQNOXyfS.js} +50 -22
- package/dist/server.d.ts +5 -2
- package/dist/server.js +9 -3
- package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-DN0svCKj.js} +2 -2
- package/dist/{set-cookie-DVfi-nJX.js → set-cookie-CMB3t4NF.js} +1 -1
- package/dist/{table-specs-CCSY4tiS.js → table-specs-C3-bLOSF.js} +1 -1
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-BP9_XUr9.d.ts → types-BmRGse4l.d.ts} +26 -5
- package/dist/{vite-Dem1i1rL.js → vite-GRzej8Cs.js} +59 -17
- package/dist/vite.d.ts +18 -3
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +2 -2
- package/dist/vue.js +1 -1
- package/package.json +9 -8
package/README.md
CHANGED
|
@@ -72,6 +72,15 @@ export default defineAuth({
|
|
|
72
72
|
});
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
+
```bash
|
|
76
|
+
pnpm add @vite-hub/database
|
|
77
|
+
pnpm add -D drizzle-kit@1.0.0-rc.6
|
|
78
|
+
pnpm vitehub database generate
|
|
79
|
+
pnpm vitehub database migrate
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`authDatabase()` turns the Database on in `vitehub()`, as Connections does, so the app does not set `database`. `database: false` with `authDatabase()` fails the build with `AUTH_DATABASE_DISABLED`. `@vite-hub/database` stores the tables, and Drizzle Kit writes their migration. On Cloudflare, give the Database a D1 id with a Definition such as `server/databases/default.ts` = `defineDatabase({ cloudflare: { databaseId, databaseName }, schema: {} })`, or run `vitehub provision run --host cloudflare`.
|
|
83
|
+
|
|
75
84
|
`authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields when the Definition calls `admin()`, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
|
|
76
85
|
|
|
77
86
|
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
@@ -98,9 +107,9 @@ Pass `deleteAccount: { beforeDelete }` to delete the app's own rows first, or th
|
|
|
98
107
|
|
|
99
108
|
## First admin
|
|
100
109
|
|
|
101
|
-
`VITEHUB_ADMINS` is a comma-separated list of social accounts, each `<provider>:<account id>`, such as `github:22072217`. When a listed account signs in or is linked,
|
|
110
|
+
`VITEHUB_ADMINS` is a comma-separated list of social accounts, each `<provider>:<account id>`, such as `github:22072217`, and emails, such as `ada@example.com`. When a listed account signs in or is linked, or a user with a listed email signs in or verifies it, the user gets the first `adminRoles` entry of Better Auth's `admin()` plugin (`admin` by default), in place of the default role. Removing an entry does not remove the role. Without `admin()`, Auth fails with `AUTH_C0051`. The Auth Console lists the rule in its access notes. An email entry matches only a verified email (`user.emailVerified`), so a password sign-up with the admin's email gets no role until the person opens the verification link. A prefixed email, such as `email:ada@example.com`, fails with `AUTH_C0058`. The removed `VITEHUB_ADMIN_EMAILS` fails with `AUTH_C0057`.
|
|
102
111
|
|
|
103
|
-
For an app without social sign-in, `vitehub auth claim` prints a one-time code and the `VITEHUB_ADMIN_CLAIM` value (its SHA-256) to set on the host. The first signed-in user who sends it to `POST <auth base>/vitehub/admin-claim` gets the admin role. A row in the `verification` table marks the code as used. A malformed value fails with `AUTH_C0059`.
|
|
112
|
+
For an app without social sign-in or email verification, `vitehub auth claim` prints a one-time code and the `VITEHUB_ADMIN_CLAIM` value (its SHA-256) to set on the host. The first signed-in user who sends it to `POST <auth base>/vitehub/admin-claim` gets the admin role. A row in the `verification` table marks the code as used. A malformed value fails with `AUTH_C0059`.
|
|
104
113
|
|
|
105
114
|
Set `adminClaim: false` on another Auth Definition to make it ignore the host's claim value.
|
|
106
115
|
|
|
@@ -108,12 +117,14 @@ With a claim code set, Auth sets `verification.storeInDatabase: true`, including
|
|
|
108
117
|
|
|
109
118
|
## Members
|
|
110
119
|
|
|
111
|
-
`VITEHUB_MEMBERS` lets only some people sign up and sign in. It is a comma-separated list of entries: `<provider>:<account id>` (such as `github:22072217`), an email, `@<domain>`, or `github-org:<organization>`. Email and domain entries match only an email that the provider verified. An organization entry adds the `read:org` scope to the GitHub provider and checks the membership with `checkGitHubOrgMember()`. The accounts in `VITEHUB_ADMINS` and users with the admin role always get in.
|
|
120
|
+
`VITEHUB_MEMBERS` lets only some people sign up and sign in. It is a comma-separated list of entries: `<provider>:<account id>` (such as `github:22072217`), an email, `@<domain>`, or `github-org:<organization>`. Email and domain entries match only an email that the provider verified. An organization entry adds the `read:org` scope to the GitHub provider and checks the membership with `checkGitHubOrgMember()`. The accounts and verified emails in `VITEHUB_ADMINS` and users with the admin role always get in.
|
|
112
121
|
|
|
113
122
|
Auth refuses to create a user that no entry lets in, and refuses each new session. A refusal answers `403` with `AUTH_NOT_MEMBER`, or an OAuth redirect with `?error=AUTH_NOT_MEMBER`. The list runs in the same plugin as `access.policy`, so a removed person loses a running session within five minutes and their MCP access tokens stop working. It needs stored sessions (`AUTH_MEMBERS_SESSION_STORE_REQUIRED`). An invalid entry fails with `AUTH_MEMBERS_ENTRY_INVALID`. The Auth Console lists the entries in its access notes, with the number of emails in place of the emails.
|
|
114
123
|
|
|
115
124
|
`checkAuthMember(userId, event?)` from `@vite-hub/auth/server` runs the same rules for code that has a user id but no session, such as an upload ticket. It returns `[undefined, undefined]` for a member or when the variable is not set, `AUTH_NOT_MEMBER` for a refused or unknown user, and `AUTH_GITHUB_UNAVAILABLE` when GitHub cannot answer. A confirmed organization membership is reused for five minutes.
|
|
116
125
|
|
|
126
|
+
`hasAuthMembers(context)` from the same entry tells whether an Auth context applies `VITEHUB_MEMBERS`. In a route, pass `await useAuth(request).$context`. In a Better Auth hook, pass `ctx.context`.
|
|
127
|
+
|
|
117
128
|
## Sessions without a database
|
|
118
129
|
|
|
119
130
|
`stateless()` keeps each session in an encrypted cookie. Sessions survive restarts and work across replicas and Workers when every instance uses the same secret.
|
|
@@ -194,9 +205,11 @@ Behind a proxy that ends TLS, set Better Auth's `advanced.trustedProxyHeaders: t
|
|
|
194
205
|
|
|
195
206
|
Each Auth request or route guard runs its Definition callback once, then once more with the forwarded origin if the effective options trust proxy headers and that origin differs. If the second run disables trust, Auth keeps the request URL's origin and disables proxy trust. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options. Requests with equal resolved options share one Better Auth instance. Plain values compare by value. Functions, adapters, and bindings compare by identity, so an instance never keeps an object that another request created. `authDatabase()` adapters compare by Database name. A change to a variable that the instance uses, such as `VITEHUB_SECRET`, `BETTER_AUTH_SECRET`, `VITEHUB_ADMINS`, or `VITEHUB_MEMBERS`, gives a new instance on the next request. A callback that creates plugins or other adapters on each call builds a new instance on each request, so create them outside the callback when they do not depend on the request. All guards of one request share one session lookup: access routes, `requireAuth()`, `requireAuthorization()`, `withAuth()`, `withAuthorization()`, and `withAnonymousAuthorization()`.
|
|
196
207
|
|
|
208
|
+
Auth keeps the `Origin` check on in dev, in tests, and in production. A `POST` that carries the session cookie, and every sign-in or sign-up `POST` that sends an `Origin`, answers `403` with `INVALID_ORIGIN` when the `Origin` is not `baseURL` or in `trustedOrigins`. Better Auth turns this check off when `TEST` or `NODE_ENV=test` is set, but Auth does not, so a server that a Vitest run starts checks the `Origin` as production does. To turn the check off, set `advanced.disableOriginCheck: true`.
|
|
209
|
+
|
|
197
210
|
With a provider in `access.signIn`, the Auth route also answers `GET /api/auth/sign-in?redirect=/docs` and `GET /api/auth/sign-out?redirect=/`, below the Auth Base Path. The sign-in path starts `access.signIn` and comes back to `redirect` (default: `access.afterSignIn`, or `/`). A signed-in visitor goes to `redirect` at once. The sign-out path ends the session and goes to `redirect` (default `/`). It refuses a request from another site (`Sec-Fetch-Site` `cross-site` or `same-site`) and a prefetch or prerender (`Sec-Purpose`) with `403`. `redirect` must be a path of the app, below `app.baseURL` like the page guard's `?redirect=`, or the answer is `400`. Without a provider in `access.signIn`, Better Auth answers these paths with `404`.
|
|
198
211
|
|
|
199
|
-
The generated Nitro middleware starts the provider of `access.signIn` when one of the configured `access.routes` needs a browser redirect. A sign-in page, such as `signIn: "/login"`, is for the Nuxt page guard: server guards answer `401`. Route objects can add an `authorize` callback when a valid session is not sufficient:
|
|
212
|
+
The generated Nitro middleware starts the provider of `access.signIn` when one of the configured `access.routes` needs a browser redirect. A sign-in page, such as `signIn: "/login"`, is for the Nuxt page guard: server guards answer `401`. Route objects can add a `role` or an `authorize` callback when a valid session is not sufficient. `role` is a role name or a list of role names. A signed-in user without one of them gets `403`, and `authorize` runs only after the role check passes. Auth reads `user.role`, where Better Auth's `admin()` plugin stores the roles of a user separated by commas. `hasRole(user, roles)` from `@vite-hub/auth` checks the same rule in app code:
|
|
200
213
|
|
|
201
214
|
```ts
|
|
202
215
|
import { defineAuth } from "@vite-hub/auth"
|
|
@@ -208,6 +221,7 @@ export default defineAuth({
|
|
|
208
221
|
route: "/_vitehub/**",
|
|
209
222
|
authorize: ({ user }) => user.isAdmin === true,
|
|
210
223
|
},
|
|
224
|
+
{ route: "/api/dashboard/**", role: ["team", "admin"] },
|
|
211
225
|
],
|
|
212
226
|
},
|
|
213
227
|
});
|
|
@@ -284,6 +298,8 @@ export default defineHandler(async (event) => {
|
|
|
284
298
|
});
|
|
285
299
|
```
|
|
286
300
|
|
|
301
|
+
In development, `useAuth(event)` uses the request origin if no Auth URL is configured. Pass the event so that direct API calls can make absolute links, such as password reset links.
|
|
302
|
+
|
|
287
303
|
## Session refresh
|
|
288
304
|
|
|
289
305
|
Better Auth extends a stored session when the session passes `session.updateAge`. Use `session.onRefresh` to check the user again at that time, for example against a ban list.
|
|
@@ -338,9 +354,11 @@ export { default } from '#vitehub/auth/server'
|
|
|
338
354
|
|
|
339
355
|
For a manual adapter that creates plain Web `Request` objects, use `createAuthHandler(definition)` from `@vite-hub/auth/server` and call the returned handler as `handler(request, { clientAddress })`. Read `clientAddress` from the host's peer address, such as Node's `incomingMessage.socket.remoteAddress`, never from a client-sent header. Auth uses it for per-client rate limiting and `session.ipAddress`; without it, plain Web requests share an addressless rate-limit bucket. srvx requests already carry their host address as `ip`.
|
|
340
356
|
|
|
357
|
+
By default, Auth counts only requests that match a static endpoint. To limit a route with a path parameter, such as `/callback/:id`, set a wildcard in `rateLimit.customRules`, such as `/callback/*`. Each concrete path then gets its own counter.
|
|
358
|
+
|
|
341
359
|
App Auth loads Better Auth on demand. Nitro imports the Auth route on its first request. The generated access middleware imports `#vitehub/auth/server` only for a request that an access route matches. Generated app Auth startup code imports `@vite-hub/auth/runtime/server`, which has no Better Auth import. Your own code loads Better Auth when it imports `@vite-hub/auth/server`, so import it in routes, not in plugins or global middleware, to keep it out of the startup.
|
|
342
360
|
|
|
343
|
-
Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback. The callback returns all the options in one object, and Auth does not merge it with other options. `defineAuth()` rejects the removed `runtime` option with `AUTH_C0039`. `access.routes` must be static route strings or `{ authorize, method, route }` objects, and `access.public` static route strings, so the Vite Integration can register Nitro middleware.
|
|
361
|
+
Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback. The callback returns all the options in one object, and Auth does not merge it with other options. `defineAuth()` rejects the removed `runtime` option with `AUTH_C0039`. `access.routes` must be static route strings or `{ authorize, method, role, route }` objects, and `access.public` static route strings, so the Vite Integration can register Nitro middleware.
|
|
344
362
|
|
|
345
363
|
|
|
346
364
|
Each access route is a literal path, or a literal path that ends with `/**` to match the path and every path below it. Other pattern syntax (`*`, `:name`, `(`, `{`, `?`), also when percent-encoded such as `%3A`, and `.` or `..` segments fail with `AUTH_C0068`. A route with `method: "GET"` also guards `HEAD`, because H3 runs the GET handler for `HEAD`. The access middleware compares paths after the same normalization as the Nitro router: it decodes needless percent escapes and ignores one trailing slash in requests. Configured routes drop all trailing slashes, as router registration does. `access.routes` must use a dense array. Empty slots, including commented-out entries that leave commas, fail configuration.
|
|
@@ -513,6 +531,7 @@ const { data: sessions } = await useAsyncData("sessions", async () => {
|
|
|
513
531
|
| `'user'` or `true` | Visitors with a session | `access.signIn` (default `/login`), with `?redirect=<the page>`. A provider opens `<basePath>/sign-in`. |
|
|
514
532
|
| `'guest'` | Visitors without a session, such as on the login page | `access.afterSignIn` (default `/`) |
|
|
515
533
|
| `{ only, redirectTo }` | `only` is `'user'` or `'guest'` | `redirectTo` |
|
|
534
|
+
| `{ role }` | Signed-in users with one of the roles | `access.signIn` for visitors without a session. A user without the role gets a 403 error page. |
|
|
516
535
|
| `false` | Everyone | |
|
|
517
536
|
| Not set | The mode of the most specific `access.pages` pattern, or everyone if no pattern matches | |
|
|
518
537
|
|
|
@@ -525,9 +544,9 @@ export default defineAuth({
|
|
|
525
544
|
})
|
|
526
545
|
```
|
|
527
546
|
|
|
528
|
-
To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, or `
|
|
547
|
+
To guard pages from the Auth Definition, map route patterns to `'user'`, `'guest'`, `false`, or `{ role }` in `access.pages`. `{ role: ['team', 'admin'] }` works like `'user'` and shows a 403 error page to a signed-in user without one of the roles. The module attaches one `vitehub-auth-role-<i>` middleware for each distinct role. The Nuxt module reads it at build time and adds the guard to the `appMiddleware` route rule of each pattern, so the server render and navigation in the browser send the visitor to the same page. The most specific pattern wins, `false` removes the guard of a wider pattern, and `definePageMeta({ auth })` of a page wins over all patterns. A key has static segments, `:name`, and a last `/**`. Optional, repeated, and regex params stop the build with `AUTH_PAGE_ROUTES_INVALID`, because Nuxt then orders patterns by position and not by how specific they are. So do two keys that match the same pages, such as keys that differ only in param names, letter case, or percent-encoding.
|
|
529
548
|
|
|
530
|
-
The build also stops with `AUTH_PAGE_ROUTES_INVALID` when `access.pages` applies a `'user'` guard to `access.signIn` or to a `redirectTo` for signed-out visitors. A guest-only page can still redirect signed-in users to a `'user'` page.
|
|
549
|
+
An invalid `role`, on a page or a route, fails with `AUTH_ACCESS_ROLE_INVALID`. The build also stops with `AUTH_PAGE_ROUTES_INVALID` when `access.pages` applies a `'user'` or `{ role }` guard to `access.signIn` or to a `redirectTo` for signed-out visitors. A guest-only page can still redirect signed-in users to a `'user'` page.
|
|
531
550
|
|
|
532
551
|
```ts
|
|
533
552
|
// server/auth.ts
|
|
@@ -616,6 +635,8 @@ export default defineAgent({
|
|
|
616
635
|
|
|
617
636
|
By default, the Auth Package reads the same-app Better Auth session from the request and maps the Auth User to an Agent Invoker with `kind: "authUser"`. Customize `id`, `kind`, `label`, or `meta` for normal identity shaping, and use `source` or `map` when the Agent consumes JWTs, bearer tokens, OAuth/OIDC provider output, or product-specific identity.
|
|
618
637
|
|
|
638
|
+
A run without a request, such as a Schedule or Queue run, has no session. Server code names the Auth user in the input: `runAgent(agent, { prompt, context: { invoker: { id: user.id, kind: "authUser" } } }, { schedule })`. `authenticated()` accepts that Invoker only when the run has no request, and sets `meta.authUserId` from its `id`. It refuses a run without a request that names no Auth user, or another kind of Invoker. `agentAuth.user()` reads `meta.authUserId`, else the `id` of an `authUser` Invoker.
|
|
639
|
+
|
|
619
640
|
When authentication is required but unavailable, `authenticated()` throws `ViteHubError` with code `AUTHENTICATION_REQUIRED`. HTTP adapters map that code to `401`; the transport status is not part of the error object.
|
|
620
641
|
|
|
621
642
|
```ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-
|
|
1
|
+
import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BmRGse4l.js";
|
|
2
2
|
/** A 4xx status that a rule can refuse with. `403` is the default. */
|
|
3
3
|
type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
|
|
4
4
|
declare const abilityDenial: unique symbol;
|
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-CfvuGrBv.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-DkzL9ltR.js";
|
|
2
|
+
import { n as isAuthRole } from "./roles-BGi8CyBG.js";
|
|
2
3
|
// src/shared.ts
|
|
3
4
|
const defaultAuthBasePath = "/api/auth";
|
|
4
5
|
function normalizeAuthBasePath(value) {
|
|
@@ -9,6 +10,10 @@ function normalizeAuthBasePath(value) {
|
|
|
9
10
|
return normalized;
|
|
10
11
|
}
|
|
11
12
|
// src/access-pages.ts
|
|
13
|
+
/** Whether an `access.pages` value needs a signed-in user: `'user'` or `{ role }`. */
|
|
14
|
+
function isUserPage(mode) {
|
|
15
|
+
return mode === "user" || typeof mode === "object" && mode !== null;
|
|
16
|
+
}
|
|
12
17
|
/**
|
|
13
18
|
* Normalizes a path as Nuxt does before it matches route rules: it decodes percent-encoding and, unless the router is
|
|
14
19
|
* case sensitive, folds each UTF-16 code unit to the lower case of its upper case. That is how a Vue Router path regular
|
|
@@ -82,7 +87,9 @@ function assertAuthPages(pages) {
|
|
|
82
87
|
const shapes = /* @__PURE__ */ new Map();
|
|
83
88
|
for (const [path, mode] of Object.entries(pages)) {
|
|
84
89
|
const invalid = (reason) => authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(path)}: ${JSON.stringify(mode)}. ${reason}` });
|
|
85
|
-
if (mode
|
|
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-CMB3t4NF.js";
|
|
2
|
+
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DN0svCKj.js";
|
|
3
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
|
|
4
4
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
5
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
6
6
|
// src/agent.ts
|
|
@@ -9,9 +9,25 @@ const loadServer = () => server ??= import("./internal/server.js").catch((error)
|
|
|
9
9
|
server = void 0;
|
|
10
10
|
throw error;
|
|
11
11
|
});
|
|
12
|
-
|
|
12
|
+
function authUserIdOf(invoker) {
|
|
13
13
|
const meta = invoker?.meta;
|
|
14
|
-
|
|
14
|
+
return (isRecord(meta) ? readString(meta.authUserId) : void 0) ?? (invoker?.kind === "authUser" ? readString(invoker.id) : void 0);
|
|
15
|
+
}
|
|
16
|
+
function namedAuthUserInvoker(context) {
|
|
17
|
+
const inputContext = context.input?.context;
|
|
18
|
+
if (!isRecord(inputContext) || inputContext.invoker === void 0) return void 0;
|
|
19
|
+
const invoker = context.defaultInvoker;
|
|
20
|
+
const userId = invoker.kind === "authUser" ? readString(invoker.id) : void 0;
|
|
21
|
+
return userId ? {
|
|
22
|
+
...invoker,
|
|
23
|
+
meta: {
|
|
24
|
+
...invoker.meta,
|
|
25
|
+
authUserId: userId
|
|
26
|
+
}
|
|
27
|
+
} : void 0;
|
|
28
|
+
}
|
|
29
|
+
const agentAuth = { async user(invoker) {
|
|
30
|
+
const userId = authUserIdOf(invoker);
|
|
15
31
|
if (!userId) return null;
|
|
16
32
|
const { getAuth } = await loadServer();
|
|
17
33
|
let user;
|
|
@@ -31,7 +47,10 @@ function authenticated(options = {}) {
|
|
|
31
47
|
let auth;
|
|
32
48
|
let providerFields;
|
|
33
49
|
if (options.source) auth = await options.source(context);
|
|
34
|
-
else {
|
|
50
|
+
else if (!context.request) {
|
|
51
|
+
const named = namedAuthUserInvoker(context);
|
|
52
|
+
if (named) return named;
|
|
53
|
+
} else {
|
|
35
54
|
const resolved = await defaultAuthenticatedSource(context);
|
|
36
55
|
auth = resolved?.auth;
|
|
37
56
|
providerFields = resolved ?? void 0;
|