@vite-hub/auth 0.0.3 → 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/LICENSE +201 -0
  2. package/README.md +213 -41
  3. package/dist/agent.d.ts +25 -13
  4. package/dist/agent.js +19 -5
  5. package/dist/application-path-C290OAIs.js +18 -0
  6. package/dist/cli-mgXvsBtA.d.ts +85 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.js +68 -0
  9. package/dist/console-B7eERmGv.d.ts +180 -0
  10. package/dist/console-runtime-bZQtnX2Y.d.ts +39 -0
  11. package/dist/console-runtime.d.ts +3 -0
  12. package/dist/console-runtime.js +819 -0
  13. package/dist/console-types-CmmnKGMx.js +38 -0
  14. package/dist/console.d.ts +7 -0
  15. package/dist/console.js +15 -0
  16. package/dist/error-diagnostics-CL0yjHiM.js +79 -0
  17. package/dist/events-BkmK2dFY.d.ts +486 -0
  18. package/dist/events-P7mI4IQb.js +196 -0
  19. package/dist/events-config-CjcFOhTE.js +177 -0
  20. package/dist/host-declarations.d.ts +17 -0
  21. package/dist/index.d.ts +6 -5
  22. package/dist/index.js +40 -28
  23. package/dist/inspect-DPtsW8dB.d.ts +36 -0
  24. package/dist/nuxt.d.ts +59 -0
  25. package/dist/nuxt.js +93 -0
  26. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  27. package/dist/presets.d.ts +2 -0
  28. package/dist/presets.js +32 -0
  29. package/dist/runtime/console.d.ts +7 -0
  30. package/dist/runtime/console.js +42 -0
  31. package/dist/runtime/empty-definition.d.ts +1 -2
  32. package/dist/runtime/nuxt.d.ts +3 -0
  33. package/dist/runtime/nuxt.js +9 -0
  34. package/dist/runtime/vue-nuxt.d.ts +3 -0
  35. package/dist/runtime/vue-nuxt.js +8 -0
  36. package/dist/server-B7LU19dS.js +1730 -0
  37. package/dist/server-CTD_JAww.d.ts +77 -0
  38. package/dist/server.d.ts +3 -20
  39. package/dist/server.js +3 -2
  40. package/dist/set-cookie-2as_DbHe.js +75 -0
  41. package/dist/shared-DnpgYiLF.js +15 -0
  42. package/dist/vite-COWkwxsj.js +990 -0
  43. package/dist/vite.d.ts +34 -10
  44. package/dist/vite.js +2 -995
  45. package/dist/vue.d.ts +55 -0
  46. package/dist/vue.js +112 -0
  47. package/package.json +92 -17
  48. package/dist/server-Diw3mAbX.js +0 -322
  49. package/dist/shared-QSYBHaMG.js +0 -12
  50. package/dist/types-B0fg9XFd.d.ts +0 -106
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,56 +1,96 @@
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.
11
11
 
12
+ Most applications install `vite-hub` and enable Auth through the framework preset. Install this owner package directly when a focused Vite integration, library, or manual host needs Auth without the rest of ViteHub. Better Auth still owns providers, client plugins, adapters, and sign-in UI.
13
+
12
14
  ## Install
13
15
 
14
16
  ```sh
15
17
  pnpm add @vite-hub/auth better-auth
18
+ pnpm add -D vite
16
19
  ```
17
20
 
18
- ## Minimal API
21
+ ## First local session
19
22
 
20
23
  ```ts
21
24
  // server/auth.ts
22
- import { defineAuth } from "@vite-hub/auth"
25
+ import { defineAuth } from "@vite-hub/auth";
23
26
 
24
27
  export default defineAuth({
25
28
  appName: "My app",
26
- })
29
+ emailAndPassword: { enabled: true },
30
+ });
27
31
  ```
28
32
 
29
33
  ```ts
30
34
  // vite.config.ts
31
- import { hubAuth } from "@vite-hub/auth/vite"
32
- import { defineConfig } from "vite"
35
+ import { hubAuth } from "@vite-hub/auth/vite";
36
+ import { defineConfig } from "vite";
33
37
 
34
38
  export default defineConfig({
35
39
  plugins: [hubAuth()],
36
- })
40
+ });
41
+ ```
42
+
43
+ Start the Vite Development Server, then create a local session through the mounted Better Auth route:
44
+
45
+ ```sh
46
+ pnpm vite
37
47
  ```
38
48
 
39
- `hubAuth()` discovers `server/auth.ts`, exposes `/api/auth/**`, and generates the Nitro route handler for production builds.
49
+ ```sh
50
+ curl -i http://localhost:5173/api/auth/sign-up/email \
51
+ -H 'content-type: application/json' \
52
+ --data '{"name":"Local User","email":"local@example.com","password":"passwordpassword"}'
53
+ ```
54
+
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
+
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.
40
83
 
41
84
  For host routes that need runtime secrets, provider credentials, request-derived origins, or route guarding, keep that policy in the Auth Definition.
42
85
 
43
86
  ```ts
44
87
  // vite.config.ts
45
- import { hubAuth } from "@vite-hub/auth/vite"
46
- import { env, hubEnv } from "@vite-hub/env/vite"
47
- import { defineConfig } from "vite"
88
+ import { hubAuth } from "@vite-hub/auth/vite";
89
+ import { env, hubEnv } from "@vite-hub/env/vite";
90
+ import { defineConfig } from "vite";
48
91
 
49
92
  export default defineConfig({
50
- plugins: [
51
- hubEnv(),
52
- hubAuth(),
53
- ],
93
+ plugins: [hubEnv(), hubAuth()],
54
94
  env: {
55
95
  server: {
56
96
  auth: {
@@ -62,12 +102,12 @@ export default defineConfig({
62
102
  },
63
103
  },
64
104
  },
65
- })
105
+ });
66
106
  ```
67
107
 
68
108
  ```ts
69
109
  // server/auth.ts
70
- import { defineAuth } from "@vite-hub/auth"
110
+ import { defineAuth } from "@vite-hub/auth";
71
111
 
72
112
  export default defineAuth(({ env, requestOrigin }) => ({
73
113
  appName: "My app",
@@ -87,12 +127,97 @@ export default defineAuth(({ env, requestOrigin }) => ({
87
127
  clientSecret: env.auth.github.clientSecret.unseal(),
88
128
  },
89
129
  },
90
- }))
130
+ }));
91
131
  ```
92
132
 
93
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.
94
134
 
95
- The generated Nitro middleware uses `access.signIn` when one of the configured `access.routes` needs a browser redirect.
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
+
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:
138
+
139
+ ```ts
140
+ export default defineAuth({
141
+ access: {
142
+ routes: [
143
+ {
144
+ route: "/_vitehub/**",
145
+ authorize: ({ user }) => user.isAdmin === true,
146
+ },
147
+ {
148
+ route: "/api/_vitehub/console/**",
149
+ authorize: ({ user }) => user.isAdmin === true,
150
+ },
151
+ ],
152
+ },
153
+ });
154
+ ```
155
+
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.
96
221
 
97
222
  ## Vite Integration
98
223
 
@@ -103,58 +228,73 @@ Set `route: false` only when a host integration mounts Auth itself.
103
228
  ```ts
104
229
  export default defineAuth({
105
230
  route: false,
106
- })
231
+ });
107
232
  ```
108
233
 
109
234
  Manual hosts can mount the stable `#vitehub/auth/server` handler directly.
110
235
 
111
- 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 `{ 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.
112
241
 
113
242
  ```ts
114
243
  export default defineAuth({
115
244
  basePath: "/auth",
116
245
  database: { name: "auth", dedicated: true },
117
246
  secondaryStorage: { store: "auth" },
118
- })
247
+ });
119
248
  ```
120
249
 
121
250
  `database` and `secondaryStorage` are placement metadata. ViteHub removes metadata-shaped values before calling `betterAuth()`, so they do not create Database or KV adapters. When Better Auth needs persistent storage, return its concrete `database` or `secondaryStorage` adapter from the Definition callback or `runtime`.
122
251
 
123
252
  ## Client-side Auth
124
253
 
125
- Use Better Auth's client libraries from application code. ViteHub exposes the Auth route in local Vite development and provides the handler for hosts that mount it manually; Better Auth owns framework clients, hooks, client plugins, sign-in actions, and session state.
254
+ Vue apps can use ViteHub's Better Auth client and normalized session composable directly. `useUserSession()` exposes the current `user` and `session`, sign-in and sign-out actions, and `loggedIn`, `pending`, and `ready` computed refs.
126
255
 
127
256
  ```ts
128
257
  // lib/auth-client.ts
129
- import { createAuthClient } from "better-auth/client"
258
+ import { useUserSession } from "@vite-hub/auth/vue";
130
259
 
131
- export const authClient = createAuthClient()
260
+ export const session = useUserSession();
132
261
  ```
133
262
 
134
- 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.
135
264
 
136
265
  ```ts
137
266
  // server/auth.ts
138
- import { defineAuth } from "@vite-hub/auth"
267
+ import { defineAuth } from "@vite-hub/auth";
139
268
 
140
269
  export default defineAuth({
141
270
  appName: "My app",
142
271
  basePath: "/auth",
143
- })
272
+ });
144
273
  ```
145
274
 
146
275
  ```ts
147
276
  // lib/auth-client.ts
148
- import { createAuthClient } from "better-auth/client"
277
+ import { createAuthClient, useUserSession } from "@vite-hub/auth/vue";
149
278
 
150
279
  export const authClient = createAuthClient({
151
280
  basePath: "/auth",
152
- })
281
+ });
282
+ export const userSession = useUserSession(authClient);
153
283
  ```
154
284
 
155
- Use Better Auth's framework entrypoints when you want React, Vue, Svelte, Solid, or other framework-specific client behavior. ViteHub does not provide `@vite-hub/auth/client` or a separate Auth Client Definition.
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.
286
+
287
+ The client loads `better-auth/vue` the first time you use it, not when you create it. An app can create its client in a plugin, and only the pages that sign in or read the session download Better Auth. Calls such as `signIn.social()` wait for the load. `useSession()` and `useUserSession()` return their refs at once: they are pending until the client loads in the browser, and stay pending during server rendering. For a member that is not a call or a hook, such as `$store`, get Better Auth's own client with `loadAuthClient()`:
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
+ ```
156
296
 
157
- Read [Better Auth's client docs](https://www.better-auth.com/docs/concepts/client) for framework entrypoints and session helpers.
297
+ Read [Better Auth's client docs](https://www.better-auth.com/docs/getting-started/concepts/client) for framework entrypoints and session helpers.
158
298
 
159
299
  ## Authenticated Agents
160
300
 
@@ -162,15 +302,15 @@ Use `authenticated()` when an Agent should derive its Agent Invoker from the cur
162
302
 
163
303
  ```ts
164
304
  // server/support.agent.ts
165
- import { defineAgent } from "@vite-hub/agent"
166
- import { authenticated } from "@vite-hub/auth/agent"
305
+ import { defineAgent } from "@vite-hub/agent";
306
+ import { authenticated } from "@vite-hub/auth/agent";
167
307
 
168
308
  export default defineAgent({
169
309
  invoker: authenticated(),
170
310
  driver: {
171
311
  run: ({ invoker }) => ({ invoker }),
172
312
  },
173
- })
313
+ });
174
314
  ```
175
315
 
176
316
  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.
@@ -178,9 +318,41 @@ By default, the Auth Package reads the same-app Better Auth session from the req
178
318
  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.
179
319
 
180
320
  ```ts
181
- import { ViteHubError } from "@vite-hub/runtime"
321
+ import { ViteHubError } from "@vite-hub/runtime";
182
322
 
183
- const error = new ViteHubError("AUTHENTICATION_REQUIRED", "Sign in to use this Agent.")
323
+ const error = new ViteHubError("AUTHENTICATION_REQUIRED", "Sign in to use this Agent.");
184
324
  ```
185
325
 
186
- `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.
327
+
328
+ ## Production checks
329
+
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`).
331
+ - Set request-aware `baseURL` or use `requestOrigin` so callback and cookie origins match the deployed host.
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.
333
+ - Protect application and Console page/API routes explicitly. Authentication proves a session; application-owned `authorize` callbacks define roles and permissions.
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.
335
+
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)`.