@vite-hub/auth 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +140 -13
  2. package/dist/agent.d.ts +24 -13
  3. package/dist/agent.js +19 -5
  4. package/dist/application-path-C290OAIs.js +18 -0
  5. package/dist/cli-mgXvsBtA.d.ts +85 -0
  6. package/dist/cli.d.ts +7 -0
  7. package/dist/cli.js +68 -0
  8. package/dist/console-B7eERmGv.d.ts +180 -0
  9. package/dist/console-runtime-bZQtnX2Y.d.ts +39 -0
  10. package/dist/console-runtime.d.ts +3 -0
  11. package/dist/console-runtime.js +819 -0
  12. package/dist/console-types-CmmnKGMx.js +38 -0
  13. package/dist/console.d.ts +7 -0
  14. package/dist/console.js +15 -0
  15. package/dist/error-diagnostics-CL0yjHiM.js +79 -0
  16. package/dist/events-BkmK2dFY.d.ts +486 -0
  17. package/dist/events-P7mI4IQb.js +196 -0
  18. package/dist/events-config-CjcFOhTE.js +177 -0
  19. package/dist/host-declarations.d.ts +4 -0
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +36 -29
  22. package/dist/inspect-DPtsW8dB.d.ts +36 -0
  23. package/dist/nuxt.d.ts +27 -6
  24. package/dist/nuxt.js +35 -3
  25. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  26. package/dist/presets.d.ts +2 -0
  27. package/dist/presets.js +32 -0
  28. package/dist/runtime/console.d.ts +7 -0
  29. package/dist/runtime/console.js +42 -0
  30. package/dist/runtime/empty-definition.d.ts +1 -2
  31. package/dist/runtime/nuxt.d.ts +2 -3
  32. package/dist/runtime/nuxt.js +2 -1
  33. package/dist/runtime/vue-nuxt.d.ts +3 -0
  34. package/dist/runtime/vue-nuxt.js +8 -0
  35. package/dist/server-B7LU19dS.js +1730 -0
  36. package/dist/server-CTD_JAww.d.ts +77 -0
  37. package/dist/server.d.ts +2 -22
  38. package/dist/server.js +3 -2
  39. package/dist/set-cookie-2as_DbHe.js +75 -0
  40. package/dist/shared-DnpgYiLF.js +15 -0
  41. package/dist/vite-COWkwxsj.js +990 -0
  42. package/dist/vite.d.ts +21 -12
  43. package/dist/vite.js +2 -2
  44. package/dist/vue.d.ts +28 -11
  45. package/dist/vue.js +82 -4
  46. package/package.json +84 -24
  47. package/dist/server-BZn8iQrB.js +0 -370
  48. package/dist/shared-QSYBHaMG.js +0 -12
  49. package/dist/types-jaRlW3D1.d.ts +0 -117
  50. package/dist/vite-Cmey8ODS.js +0 -1018
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @vite-hub/auth
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Better Auth" src="https://img.shields.io/badge/Better%20Auth-powered-0f766e?style=flat-square">
7
- <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Better Auth" src="https://comark-ui.onmax.me/badge.svg?label=Better+Auth&amp;value=powered">
7
+ <img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&amp;value=discovery">
8
8
  </p>
9
9
 
10
10
  `@vite-hub/auth` defines one server-owned Auth Definition and turns it into a Better Auth server for ViteHub apps.
@@ -54,7 +54,32 @@ curl -i http://localhost:5173/api/auth/sign-up/email \
54
54
 
55
55
  Successful output has status `200`, a `better-auth.session_token` cookie, and the new user's email. `hubAuth()` discovers `server/auth.ts`, exposes `/api/auth/**`, and generates the Nitro route handler for production builds.
56
56
 
57
- This default proves discovery and the session route locally. It is not durable storage. Configure a concrete Better Auth database adapter before relying on sessions across restarts or replicas.
57
+ This default proves discovery and the session route locally. It is not durable storage. Configure a concrete Better Auth database adapter before relying on sessions across restarts or replicas, or use the `stateless()` preset for social sign-in without a database.
58
+
59
+ ## Sessions without a database
60
+
61
+ `stateless()` keeps each session in an encrypted cookie. Sessions survive restarts and work across replicas and Workers when every instance uses the same secret.
62
+
63
+ ```ts
64
+ // server/auth.ts
65
+ import { defineAuth } from "@vite-hub/auth";
66
+ import { stateless } from "@vite-hub/auth/presets";
67
+
68
+ export default defineAuth(({ env, requestOrigin }) => ({
69
+ baseURL: requestOrigin,
70
+ preset: stateless({ maxAge: "7d" }),
71
+ socialProviders: {
72
+ github: {
73
+ clientId: env.auth.github.clientId,
74
+ clientSecret: env.auth.github.clientSecret.unseal(),
75
+ },
76
+ },
77
+ }));
78
+ ```
79
+
80
+ The preset sets `session.expiresIn`, `session.cookieCache` (`strategy: "jwe"`, `refreshCache: true`), `account.storeStateStrategy: "cookie"`, and `account.storeAccountCookie: true`. `maxAge` is seconds or a duration such as `"12h"` or `"7d"`, and defaults to 7 days. The session ends `maxAge` after sign-in. `user.id` is the first 32 hex digits of SHA-256 over the provider ID and the provider account ID, so the same provider account keeps its ID across sign-ins, instances, and restarts, and `github` account 1 differs from `discord` account 1. The preset sets it through `user.validateUserInfo` and `databaseHooks.user.create.before`, after your own hooks run. You cannot revoke one session; change `session.cookieCache.version` or rotate the secret to sign out every user.
81
+
82
+ `preset` is a ViteHub option, so Auth checks the other options against it. `database` (`AUTH_C0044`), `secondaryStorage` (`AUTH_C0045`), `emailAndPassword.enabled` (`AUTH_C0046`), plugins that store data such as `jwt()` or `magicLink()` (`AUTH_C0047`), and options that the preset sets (`AUTH_C0048`) fail when the Definition is defined or resolved.
58
83
 
59
84
  For host routes that need runtime secrets, provider credentials, request-derived origins, or route guarding, keep that policy in the Auth Definition.
60
85
 
@@ -107,6 +132,8 @@ export default defineAuth(({ env, requestOrigin }) => ({
107
132
 
108
133
  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.
109
134
 
135
+ Each Auth request or route guard resolves its Definition and `runtime` callbacks once. The guard uses the same resolved options for session lookup, route authorization, and automatic provider sign-in. A later request resolves fresh options.
136
+
110
137
  The generated Nitro middleware uses `access.signIn` when one of the configured `access.routes` needs a browser redirect. Route objects can add an `authorize` callback when a valid session is not sufficient:
111
138
 
112
139
  ```ts
@@ -126,7 +153,71 @@ export default defineAuth({
126
153
  });
127
154
  ```
128
155
 
129
- ViteHub runs `authorize` only after authentication. Return `true` to allow the request, `false` for a `403`, or a `Response` for a custom result. The callback receives the authenticated `user`, `session`, and request; role semantics remain owned by the host.
156
+ Generated route middleware uses `createAuthAccessHandler(routes, definition?)` from `@vite-hub/auth/server`. The handler owns path and method matching, overlapping rules, and required authorization callbacks. Manual hosts can use the same handler with a Web `Request`, `{ req: Request }`, or an H3 1 event such as a Nuxt 4 server event. Its route metadata must follow the Definition's `access.routes` order; set `authorize: true` for each route that requires a callback so a missing runtime callback returns `403`. Unmatched requests do not resolve Auth.
157
+
158
+ ViteHub runs `authorize` only after authentication. Return `true` to allow the request, `false` for a `403`, or a `Response` for a custom result. The callback receives the authenticated `user`, `session`, and request; role semantics remain owned by the host. Only `true` grants access. ViteHub sends a `Response` unchanged when it is a Response of this runtime: the native `Response.prototype.status` getter accepts it. Create it with the global `Response`. Every other value gets `403`, including a Response from another Fetch implementation such as the `undici` package, a proxy, and an object shaped like a Response.
159
+
160
+ Guard your own server handlers with `withAuth(handler, definition?)` or `withAuthorization(authorize, handler, definition?)` from `@vite-hub/auth/server`. The guard returns a new handler. That handler checks the request first and calls your handler only when the check passes. Your handler receives the input and a frozen `authorization` with the checked `request`, `session`, and `user`. Otherwise the guard returns the rejection `Response`, so a missed `if` cannot run the protected action.
161
+
162
+ ```ts
163
+ import { withAuth, withAuthorization } from "@vite-hub/auth/server";
164
+ import type { H3Event } from "h3";
165
+
166
+ export const me = withAuth((event: H3Event, { user }) => ({ id: user.id }));
167
+
168
+ export const photo = withAuthorization(
169
+ ({ request, user }) => new URL(request.url).pathname.startsWith(`/photos/${user.id}/`),
170
+ (event: H3Event) => readPhoto(event),
171
+ );
172
+ ```
173
+
174
+ Annotate the input type when the host does not infer it, for example inside `defineEventHandler()`.
175
+
176
+ `withAuth()` returns JSON `401` without a session and starts the `access.signIn` redirect for HTML requests. `withAuthorization()` applies one `authorize` rule: `true` for any session or a callback. It returns JSON `401` without a session, `403` when the callback returns `false`, or the callback's `Response`. It never redirects to sign-in. Blob serve routes and Source Collections use it for their `authorize` option.
177
+
178
+ ## Session refresh
179
+
180
+ Better Auth extends a stored session when the session passes `session.updateAge`. Use `session.onRefresh` to check the user again at that time, for example against a ban list.
181
+
182
+ ```ts
183
+ export default defineAuth({
184
+ session: {
185
+ updateAge: 60 * 60,
186
+ async onRefresh({ session, user, refresh, clear }) {
187
+ const account = await findAccount(user.id)
188
+ if (account.banned) return clear()
189
+ refresh()
190
+ },
191
+ },
192
+ });
193
+ ```
194
+
195
+ | Call | Result |
196
+ | --- | --- |
197
+ | `refresh()` | Better Auth extends the session by `session.expiresIn`. |
198
+ | `refresh(fields)` | Better Auth extends the session and writes `fields` to it, for example session `additionalFields`. The response and the cookie cache contain them. |
199
+ | Neither | The session keeps its current expiry. The next request that reaches the refresh runs the hook again. |
200
+ | `clear()` | Better Auth deletes the session, removes its cookies, and answers `401`. `withAuth()` and route guards treat it as no session. `clear()` wins over `refresh()`. |
201
+
202
+ The hook receives the `session` and `user` as stored before the refresh. To change user fields, update them in your own store: the current response still contains the user that Better Auth read before the refresh.
203
+
204
+ `onRefresh` needs a Better Auth `database` or `secondaryStorage` adapter. Without one, Auth fails with `AUTH_C0042`, because Better Auth refreshes a stateless cookie cache (`session.cookieCache.refreshCache`) without a hook. With a cookie cache in front of a database, the hook runs only when Better Auth reads the database. It does not run when `session.disableSessionRefresh` is set or for a session created without "remember me". With `session.deferSessionRefresh`, it runs on the `POST` that writes the refresh.
205
+ On H3 2, you can guard a route with middleware instead. `requireAuth(definition?)` rejects like `withAuth()`, and `requireAuthorization(authorize, definition?)` rejects like `withAuthorization()`. When the check passes, the middleware calls `next()`. The route handler reads the checked `request`, `session`, and `user` with `getAuthorization(event)`.
206
+
207
+ ```ts
208
+ import { getAuthorization, requireAuth, requireAuthorization } from "@vite-hub/auth/server";
209
+ import { H3 } from "h3";
210
+
211
+ const app = new H3()
212
+ .get("/me", event => ({ id: getAuthorization(event).user.id }), {
213
+ middleware: [requireAuth()],
214
+ })
215
+ .delete("/posts/:id", event => deletePost(event), {
216
+ middleware: [requireAuthorization(({ user }) => user.role === "admin")],
217
+ });
218
+ ```
219
+
220
+ `getAuthorization(event)` returns only what the Auth middleware attached to that event. It does not read `event.context`, so other code cannot set it. On a route without the middleware, it throws `AUTH_R0017`, so the handler fails closed. The middleware accepts any host with the same `(event, next)` contract and an event with an own `req` request.
130
221
 
131
222
  ## Vite Integration
132
223
 
@@ -142,7 +233,11 @@ export default defineAuth({
142
233
 
143
234
  Manual hosts can mount the stable `#vitehub/auth/server` handler directly.
144
235
 
145
- Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `route`, and `runtime`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback or place them under `runtime`. `access.routes` must be static route strings or `{ authorize, method, route }` objects so the Vite Integration can register Nitro middleware.
236
+ Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, `runtime`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback or place them under `runtime`. `access.routes` must be static route strings or `{ authorize, method, route }` objects so the Vite Integration can register Nitro middleware.
237
+ Better Auth options stay top-level. ViteHub-owned wiring reserves `access`, `database`, `secondaryStorage`, `basePath`, `preset`, `route`, `runtime`, and `session.onRefresh`. The Better Auth fields `baseURL`, `secret`, and `secrets` are runtime-only: return them from the Definition callback or place them under `runtime`. `access.routes` must be static route strings or `{ authorize, method, route }` objects so the Vite Integration can register Nitro middleware.
238
+
239
+
240
+ `access.routes` must use a dense array. Empty slots, including commented-out entries that leave commas, fail configuration.
146
241
 
147
242
  ```ts
148
243
  export default defineAuth({
@@ -165,7 +260,7 @@ import { useUserSession } from "@vite-hub/auth/vue";
165
260
  export const session = useUserSession();
166
261
  ```
167
262
 
168
- That default talks to `/api/auth` on the same origin. If the Auth Definition uses a custom `basePath`, pass the same path to the Better Auth client.
263
+ That default talks to `/api/auth` on the same origin. In a Nuxt app below `app.baseURL`, such as `/app/`, it talks to `/app/api/auth`, and the server serves Auth routes and OAuth callbacks below the same path. If the Auth Definition uses a custom `basePath`, pass the same path to the Better Auth client, below the app base path.
169
264
 
170
265
  ```ts
171
266
  // server/auth.ts
@@ -189,7 +284,17 @@ export const userSession = useUserSession(authClient);
189
284
 
190
285
  The exported `createAuthClient` keeps Better Auth's option and plugin inference for custom base paths and client plugins. The zero-config composables use ViteHub's shared default client. React, Svelte, Solid, and other framework clients remain available from Better Auth's framework entrypoints.
191
286
 
192
- Read [Better Auth's client docs](https://www.better-auth.com/docs/concepts/client) for framework entrypoints and session helpers.
287
+ The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useSession()` and `useUserSession()` return their refs at once: they are pending until the client loads in the browser, and stay pending during server rendering. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
288
+
289
+ ```ts
290
+ import { loadAuthClient } from "@vite-hub/auth/vue";
291
+ import { authClient } from "./auth-client";
292
+
293
+ const client = await loadAuthClient(authClient);
294
+ client.$store.listen("$sessionSignal", () => {});
295
+ ```
296
+
297
+ Read [Better Auth's client docs](https://www.better-auth.com/docs/getting-started/concepts/client) for framework entrypoints and session helpers.
193
298
 
194
299
  ## Authenticated Agents
195
300
 
@@ -218,14 +323,36 @@ import { ViteHubError } from "@vite-hub/runtime";
218
323
  const error = new ViteHubError("AUTHENTICATION_REQUIRED", "Sign in to use this Agent.");
219
324
  ```
220
325
 
221
- `error.toJSON()` includes `name`, `code`, and `message`, while omitting `cause` and stack data. If a default Better Auth request or session operation fails, `authenticated()` and `requireAuth()` throw the same shared error with code `AUTH_PROVIDER_OPERATION_FAILED` and safe operation details; raw provider diagnostics remain available only through `cause`. Existing ViteHub errors and structural `AbortError` objects keep their identity. Missing APIs, malformed responses, invalid Auth configuration, and invalid custom callback results are programmer or provider-contract defects, so ViteHub keeps those `TypeError`s outside the operational provider boundary.
326
+ `error.toJSON()` includes `name`, `code`, and `message`, while omitting `cause` and stack data. If a default Better Auth request or session operation fails, `authenticated()`, `withAuth()`, and `withAuthorization()` throw the same shared error with code `AUTH_PROVIDER_OPERATION_FAILED` and safe operation details; raw provider diagnostics remain available only through `cause`. Existing ViteHub errors and structural `AbortError` objects keep their identity. Missing APIs, malformed responses, invalid Auth configuration, and invalid custom callback results use package-owned `AUTH_C####`, `AUTH_B####`, or `AUTH_R####` Nostics codes.
222
327
 
223
328
  ## Production checks
224
329
 
225
- - Supply a strong Better Auth secret from Server Env at request time; never put it in Public Env, client code, Agent input, logs, or traces.
330
+ - Supply a strong Better Auth secret from Server Env at request time; never put it in Public Env, client code, Agent input, logs, or traces. Without `secret`, `secrets`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_SECRETS`, or `AUTH_SECRET`, Auth uses `deriveSecret("vitehub:auth")` from `VITEHUB_SECRET` (or `NUXT_APP_SECRET`).
226
331
  - Set request-aware `baseURL` or use `requestOrigin` so callback and cookie origins match the deployed host.
227
- - Configure a concrete Better Auth database adapter and migrations. ViteHub `database` and `secondaryStorage` fields are placement metadata, not adapters.
332
+ - Configure a concrete Better Auth database adapter and migrations, or use `stateless()` for social sign-in without a database. ViteHub `database` and `secondaryStorage` fields are placement metadata, not adapters.
228
333
  - Protect application and Console page/API routes explicitly. Authentication proves a session; application-owned `authorize` callbacks define roles and permissions.
229
334
  - Keep automatic `/api/auth/**` exposure enabled unless the host mounts the stable handler itself, and verify the chosen `basePath` on both server and client.
230
335
 
231
- Read the complete [Auth guide](https://vitehub.dev/docs/server-primitives/auth), [Auth Users and Agent Invokers](https://vitehub.dev/docs/concepts/auth-users-and-agent-invokers), the [host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix), and the project's [pre-1.0 security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md).
336
+ Read the complete [Auth guide](https://vitehub.dev/docs/auth), [Auth Users and Agent Invokers](https://vitehub.dev/docs/agents/invokers), the [host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix), and the project's [pre-1.0 security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md).
337
+
338
+ ## Auth event log
339
+
340
+ Opt in with `events: { store: createDatabaseAuthEventStore({ db }) }` in `defineAuth()`. The store uses the existing SQLite Drizzle `run` and `all` contract. Node SQLite and Cloudflare D1 use the same table and queries. No event database is needed when the option is absent or `false`.
341
+
342
+ The default retention is 90 days and 100,000 records, with cleanup after each append. Override `retention.maxAgeMs` or `retention.maxRecords`, or use `retention: false`. IP addresses are discarded. User agents become a coarse device class. Admin updates store field names, not secret values.
343
+
344
+ Use `listAuthEvents(filters)` and `aggregateAuthEvents({ from, to })` from `@vite-hub/auth/server`, or use the store directly. Lists use cursor pagination and one SQL query after initialization. Aggregates use one statement for a consistent snapshot and count distinct users over the whole window. `@vite-hub/auth/runtime/console` exports these readers and `readAuthEventConsoleRecords` for the Console. No Console UI is added.
345
+
346
+ For `vitehub auth events`, configure `events.authorize`. The read endpoint requires a session and an explicit `true` result. Give the CLI the Auth base URL with `--url`, and the session cookie through `VITEHUB_AUTH_COOKIE`.
347
+
348
+ Event writes are separate from auth mutations. Storage failures warn with `AUTH_EVENT_WRITE_FAILED` and do not reject a completed auth action. `impersonation.started` is the exception: without its record, the impersonation does not start. Read [Auth event log](https://vitehub.dev/docs/auth/events) for the event list, metric definitions, privacy rules, retention, and coverage limits.
349
+
350
+ ## Auth Console
351
+
352
+ The primary Auth Definition adds `/_vitehub/auth` to the ViteHub Console. It lists users, active sessions, organizations, and approved OAuth clients. Better Auth additional fields become columns. Set `console.fields.<name>.editable` to allow edits, `console.columns` for batch computed values, and `console.roles` or `console.actions` for read-only policy with a reason. `console.access` holds short descriptions of the app's sign-in rules.
353
+
354
+ `getAuthConsoleForRequest(request)` from `@vite-hub/auth/server` exposes the same inspection API to trusted server code. Changes use Better Auth's plugin APIs. Impersonation is off unless the host passes `{ impersonation: true }` as the third argument, as `console.impersonation` does, and it needs `events.store`.
355
+
356
+ With Better Auth's admin plugin, Auth bounds every impersonation session. It never refreshes past `impersonationSessionDuration`, and it cannot create OAuth, MCP, or device grants, API keys, passkeys, passwords, email or phone number changes, username changes, linked accounts, two-factor settings, one-time tokens, or another impersonation. It also cannot unlink an account, or read or refresh a linked account's provider tokens (`403`, `IMPERSONATION_FORBIDDEN`). Server code reads `session.impersonatedBy`; `useUserSession()` gives `impersonatedBy` and `stopImpersonating()`. Read [Auth Console](https://vitehub.dev/docs/auth/console) for the full contract and the OAuth grant revocation limit.
357
+
358
+ Overview shows database totals and, with `events.store`, active users, a 30-day chart, sign-in methods, and recent events. Activity filters event groups and subject users before cursor pagination. User panels include recent events. Both pages show the `events.store` setup when recording is disabled. Server callers use `inspect.overview()` and `inspect.activity({ group, userId, cursor, limit })`. Manual hosts pass their event store as the third argument to `createAuthConsole(auth, consoleOptions, eventStore)`.
package/dist/agent.d.ts CHANGED
@@ -1,33 +1,32 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { AgentInvoker, AgentInvokerOptions, AgentInvokerResolveContext, AgentRuntimeConfig, MaybePromise } from "@vite-hub/agent";
3
-
2
+ import { AgentActor, AgentInvoker, AgentInvokerOptions, AgentInvokerResolveContext, AgentRuntimeConfig, MaybePromise } from "@vite-hub/agent";
4
3
  //#region src/agent.d.ts
5
- interface AuthenticatedUser {
4
+ export interface AuthenticatedUser {
6
5
  email?: string | null;
7
6
  id: string;
8
7
  image?: string | null;
9
8
  name?: string | null;
10
9
  [key: string]: unknown;
11
10
  }
12
- interface AuthenticatedSessionData {
11
+ export interface AuthenticatedSessionData {
13
12
  id?: string;
14
13
  token?: string;
15
14
  userId?: string;
16
15
  [key: string]: unknown;
17
16
  }
18
- interface AuthenticatedSession<TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
17
+ export interface AuthenticatedSession<TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
19
18
  session: TSession;
20
19
  user: TUser;
21
20
  }
22
- interface AuthenticatedContext<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> extends AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS> {
21
+ export interface AuthenticatedContext<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> extends AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS> {
23
22
  auth: AuthenticatedSession<TUser, TSession>;
24
23
  session: TSession;
25
24
  user: TUser;
26
25
  }
27
- type AuthenticatedSource<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS>) => MaybePromise<AuthenticatedSession<TUser, TSession> | null | undefined>;
28
- type AuthenticatedValue<TValue, TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = TValue | ((context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<TValue>);
29
- type AuthenticatedMapper<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<AgentInvoker>;
30
- interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
26
+ export type AuthenticatedSource<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AgentInvokerResolveContext<TRuntimeConfig, CALL_OPTIONS>) => MaybePromise<AuthenticatedSession<TUser, TSession> | null | undefined>;
27
+ export type AuthenticatedValue<TValue, TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = TValue | ((context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<TValue>);
28
+ export type AuthenticatedMapper<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> = (context: AuthenticatedContext<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>) => MaybePromise<AgentInvoker>;
29
+ export interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig = AgentRuntimeConfig, CALL_OPTIONS = unknown, TUser extends AuthenticatedUser = AuthenticatedUser, TSession extends AuthenticatedSessionData = AuthenticatedSessionData> {
31
30
  id?: AuthenticatedValue<string | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
32
31
  kind?: AuthenticatedValue<AgentInvoker["kind"] | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
33
32
  label?: AuthenticatedValue<string | null | undefined, TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
@@ -37,6 +36,18 @@ interface AuthenticatedOptions<TRuntimeConfig extends AgentRuntimeConfig = Agent
37
36
  required?: boolean;
38
37
  source?: AuthenticatedSource<TRuntimeConfig, CALL_OPTIONS, TUser, TSession>;
39
38
  }
40
- 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>;
41
- //#endregion
42
- export { AuthenticatedContext, AuthenticatedMapper, AuthenticatedOptions, AuthenticatedSession, AuthenticatedSessionData, AuthenticatedSource, AuthenticatedUser, AuthenticatedValue, authenticated };
39
+ /**
40
+ * The `auth` primitive that Agent Capabilities receive when Auth is configured. Generated Agent routes and Schedules
41
+ * pass it, so a Capability can act for the Auth user behind an Agent Actor.
42
+ */
43
+ export interface AgentAuth {
44
+ /**
45
+ * The Auth user an Actor stands for. `authenticated()` records the user id as `actor.meta.authUserId`, and this reads
46
+ * that user from the Auth database again, so it also works when an approved tool call runs later. Null for an Actor
47
+ * without `authUserId`, or when the user no longer exists.
48
+ */
49
+ user(actor: AgentActor | null | undefined): Promise<AuthenticatedUser | null>;
50
+ }
51
+ 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
package/dist/agent.js CHANGED
@@ -1,6 +1,19 @@
1
- import { _ as getAuthenticationSession, u as getAuthForRequest, v as invalidAuthenticationErrorOptions, y as throwAuthenticationProviderError } from "./server-BZn8iQrB.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
2
+ import { D as getAuthenticationSession, O as invalidAuthenticationErrorOptions, k as throwAuthenticationProviderError, m as getAuthForRequest, u as getAuth } from "./server-B7LU19dS.js";
2
3
  import { ViteHubError } from "@vite-hub/runtime";
3
4
  //#region src/agent.ts
5
+ const agentAuth = { async user(actor) {
6
+ const meta = actor?.meta;
7
+ const userId = isRecord(meta) ? readString(meta.authUserId) : void 0;
8
+ if (!userId) return null;
9
+ let user;
10
+ try {
11
+ user = await (await getAuth().$context).internalAdapter.findUserById(userId);
12
+ } catch (cause) {
13
+ throwAuthenticationProviderError(cause, "get-user");
14
+ }
15
+ return isRecord(user) && readString(user.id) ? user : null;
16
+ } };
4
17
  function authenticationRequired(message = "[vitehub] Authentication required.") {
5
18
  if (!message || message.length > 16384) invalidAuthenticationErrorOptions();
6
19
  return new ViteHubError("AUTHENTICATION_REQUIRED", message);
@@ -27,7 +40,7 @@ function authenticated(options = {}) {
27
40
  };
28
41
  if (options.map) {
29
42
  const invoker = await options.map(authenticatedContext);
30
- if (!invoker) throw new TypeError("[vitehub] authenticated({ map }) must return an Agent Invoker.");
43
+ if (!invoker) throw authErrorDiagnostics.AUTH_R0001({ message: "[vitehub] authenticated({ map }) must return an Agent Invoker." });
31
44
  return invoker;
32
45
  }
33
46
  return createDefaultInvoker(options, authenticatedContext, providerFields);
@@ -35,7 +48,8 @@ function authenticated(options = {}) {
35
48
  }
36
49
  async function defaultAuthenticatedSource(context) {
37
50
  if (!context.request) return void 0;
38
- return await getAuthenticationSession(getAuthForRequest(context.request), {
51
+ const auth = getAuthForRequest(context.request);
52
+ return await getAuthenticationSession(auth, {
39
53
  headers: context.request.headers,
40
54
  query: {
41
55
  disableCookieCache: true,
@@ -76,7 +90,7 @@ function defaultLabel(user, fallbackId = user.id) {
76
90
  }
77
91
  function normalizeMeta(value) {
78
92
  if (!value) return {};
79
- if (!isRecord(value)) throw new TypeError("[vitehub] authenticated({ meta }) must resolve to an object.");
93
+ if (!isRecord(value)) throw authErrorDiagnostics.AUTH_R0002({ message: "[vitehub] authenticated({ meta }) must resolve to an object." });
80
94
  return value;
81
95
  }
82
96
  function readString(value) {
@@ -86,4 +100,4 @@ function isRecord(value) {
86
100
  return typeof value === "object" && value !== null && !Array.isArray(value);
87
101
  }
88
102
  //#endregion
89
- export { authenticated };
103
+ export { agentAuth, authenticated };
@@ -0,0 +1,18 @@
1
+ //#region src/application-path.ts
2
+ /** Return the application base path without a trailing slash, or an empty string at the root. */
3
+ function authApplicationBasePath() {
4
+ const segments = (typeof __VITEHUB_AUTH_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_AUTH_APP_BASE_URL__).split("/").filter(Boolean);
5
+ return segments.length ? `/${segments.join("/")}` : "";
6
+ }
7
+ /**
8
+ * Prefix an application path, such as the Auth Base Path, with the application base path.
9
+ * A path that already starts with the base path is returned unchanged, so a caller such as Console Auth
10
+ * that mounts its own paths below the base path is not prefixed twice.
11
+ */
12
+ function resolveAuthMountPath(path) {
13
+ const base = authApplicationBasePath();
14
+ if (!base || path === base || path.startsWith(`${base}/`)) return path;
15
+ return `${base}${path}`;
16
+ }
17
+ //#endregion
18
+ export { resolveAuthMountPath as t };
@@ -0,0 +1,85 @@
1
+ import "nostics";
2
+ //#region ../internal/src/provision.d.ts
3
+ type ProvisionProvider = "cloudflare" | "vercel";
4
+ interface ProvisionLogger {
5
+ log: (message: string) => void;
6
+ warn: (message: string) => void;
7
+ }
8
+ interface ProvisionContext {
9
+ env: Record<string, string | undefined>;
10
+ fetch: typeof globalThis.fetch;
11
+ logger: ProvisionLogger;
12
+ markPlanUnchecked?: () => void;
13
+ }
14
+ interface ProvisionState {
15
+ cloudflare?: Record<string, Record<string, string>>;
16
+ vercel?: Record<string, Record<string, string>>;
17
+ }
18
+ interface ProvisionResult {
19
+ ids?: ProvisionState;
20
+ }
21
+ interface ProvisionAction {
22
+ kind: string;
23
+ name: string;
24
+ exists: boolean;
25
+ pending?: boolean;
26
+ apply: () => Promise<ProvisionResult>;
27
+ }
28
+ interface ProvisionStep {
29
+ id: string;
30
+ provider: ProvisionProvider;
31
+ plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
32
+ }
33
+ //#endregion
34
+ //#region ../internal/src/cli.d.ts
35
+ interface ViteHubCliStreams {
36
+ stderr: {
37
+ write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
38
+ };
39
+ stdout: {
40
+ write: (chunk: string | Uint8Array) => unknown;
41
+ };
42
+ }
43
+ interface ViteHubCliSpawnResult {
44
+ exitCode: number | null;
45
+ signal?: NodeJS.Signals | null;
46
+ }
47
+ interface ViteHubCliSpawnOptions {
48
+ cwd?: string;
49
+ env?: NodeJS.ProcessEnv;
50
+ stderr?: "inherit" | "pipe";
51
+ stdout?: "inherit" | "pipe";
52
+ }
53
+ type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
54
+ interface ViteHubCliContext extends ViteHubCliStreams {
55
+ cwd: string;
56
+ env: NodeJS.ProcessEnv;
57
+ /** Replaces `fetch` for commands that call a running app, so tests need no server. */
58
+ fetch?: typeof fetch;
59
+ rootDir: string;
60
+ spawn: ViteHubCliSpawn;
61
+ }
62
+ interface ViteHubCliFeature {
63
+ description?: string;
64
+ name: string;
65
+ run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
66
+ usage?: string;
67
+ }
68
+ interface ViteHubCliCommandNamespace {
69
+ /** The feature that `vitehub <name>` runs when no feature is named. */
70
+ defaultFeature?: string;
71
+ description?: string;
72
+ features: ViteHubCliFeature[];
73
+ name: string;
74
+ }
75
+ interface ViteHubCliContributor {
76
+ namespaces: ViteHubCliCommandNamespace[];
77
+ provision?: ProvisionStep[];
78
+ }
79
+ type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
80
+ interface ViteHubCliPluginMetadata {
81
+ cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
82
+ }
83
+ type StdoutWriteCallback = (error?: Error | null) => void;
84
+ //#endregion
85
+ export { ViteHubCliPluginMetadata as n, ViteHubCliContributor as t };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { t as ViteHubCliContributor } from "./cli-mgXvsBtA.js";
2
+ //#region src/cli.d.ts
3
+ /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
4
+ export declare function createAuthCliContributor(options?: {
5
+ fetch?: typeof fetch;
6
+ }): ViteHubCliContributor;
7
+ //#endregion
package/dist/cli.js ADDED
@@ -0,0 +1,68 @@
1
+ //#region src/cli.ts
2
+ const usage = "vitehub auth events --url <auth-base-url> [--type <type>] [--user <id>] [--actor <actor>] [--from <ISO>] [--to <ISO>] [--cursor <cursor>] [--limit <1-200>] [--aggregate]";
3
+ /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
4
+ function createAuthCliContributor(options = {}) {
5
+ return { namespaces: [{
6
+ name: "auth",
7
+ description: "Inspect auth events.",
8
+ features: [{
9
+ name: "events",
10
+ description: "List auth events or daily aggregates as JSON.",
11
+ usage,
12
+ async run(args, context) {
13
+ try {
14
+ if (args.includes("--help") || args.includes("-h")) {
15
+ context.stdout.write(`${usage}\n\nSet VITEHUB_AUTH_COOKIE to an authorized session cookie. VITEHUB_AUTH_URL supplies the default URL. Output is JSON.\n`);
16
+ return 0;
17
+ }
18
+ const query = new URLSearchParams();
19
+ let url = context.env.VITEHUB_AUTH_URL;
20
+ const cookie = context.env.VITEHUB_AUTH_COOKIE;
21
+ const filters = {
22
+ "--type": "type",
23
+ "--user": "userId",
24
+ "--actor": "actor",
25
+ "--from": "from",
26
+ "--to": "to",
27
+ "--cursor": "cursor",
28
+ "--limit": "limit"
29
+ };
30
+ for (let index = 0; index < args.length; index++) {
31
+ const arg = args[index];
32
+ if (arg === "--aggregate") {
33
+ query.set("aggregate", "true");
34
+ continue;
35
+ }
36
+ if (arg === "--json") continue;
37
+ if (arg !== "--url" && !Object.hasOwn(filters, arg)) throw new Error(`Unknown auth events option: ${arg}`);
38
+ const value = args[++index];
39
+ if (!value || value.startsWith("--")) throw new Error(`Missing value for ${arg}.`);
40
+ if (arg === "--url") url = value;
41
+ else query.set(filters[arg], value);
42
+ }
43
+ if (!url) throw new Error("Set --url to the Auth base URL, such as http://localhost:5173/api/auth. Set VITEHUB_AUTH_COOKIE to a permitted session cookie.");
44
+ const endpoint = new URL(`${url.replace(/\/$/, "")}/vitehub/events`);
45
+ if (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && [
46
+ "localhost",
47
+ "127.0.0.1",
48
+ "[::1]"
49
+ ].includes(endpoint.hostname))) throw new Error("Auth events requires HTTPS or a loopback HTTP URL.");
50
+ endpoint.search = query.toString();
51
+ const response = await (options.fetch ?? fetch)(endpoint, {
52
+ redirect: "error",
53
+ headers: cookie ? { cookie } : {},
54
+ signal: AbortSignal.timeout(3e4)
55
+ });
56
+ if (!response.ok) throw new Error(`Auth events returned HTTP ${response.status}. Configure events.authorize and use a permitted session.`);
57
+ context.stdout.write(`${JSON.stringify(await response.json(), null, 2)}\n`);
58
+ return 0;
59
+ } catch (error) {
60
+ context.stderr.write(`${error instanceof Error ? error.message : "Could not read auth events."}\n`);
61
+ return 1;
62
+ }
63
+ }
64
+ }]
65
+ }] };
66
+ }
67
+ //#endregion
68
+ export { createAuthCliContributor };