@vite-hub/auth 0.0.4 → 0.3.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 (87) hide show
  1. package/README.md +443 -32
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +23 -12
  9. package/dist/agent.js +30 -8
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +7 -0
  15. package/dist/cli.js +108 -0
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -0
  19. package/dist/console-runtime.js +2 -0
  20. package/dist/console-types-CmmnKGMx.js +38 -0
  21. package/dist/console.d.ts +219 -0
  22. package/dist/console.js +15 -0
  23. package/dist/database-options-BRNef9oy.js +29 -0
  24. package/dist/database-schema-options-ENuRMduM.js +12 -0
  25. package/dist/database.d.ts +12 -0
  26. package/dist/database.js +45 -0
  27. package/dist/definition-CqQMcDEK.js +280 -0
  28. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  29. package/dist/events-ByzenEVj.js +314 -0
  30. package/dist/forward.d.ts +50 -0
  31. package/dist/forward.js +120 -0
  32. package/dist/host-declarations.d.ts +6 -1
  33. package/dist/index.d.ts +26 -5
  34. package/dist/index.js +3 -95
  35. package/dist/internal/server.d.ts +5 -0
  36. package/dist/internal/server.js +858 -0
  37. package/dist/invariant-D8_xBqmZ.js +22 -0
  38. package/dist/mcp.d.ts +187 -0
  39. package/dist/mcp.js +353 -0
  40. package/dist/members-D9lfaEO_.js +533 -0
  41. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  42. package/dist/nuxt.d.ts +36 -7
  43. package/dist/nuxt.js +116 -7
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  46. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  47. package/dist/presets.d.ts +2 -0
  48. package/dist/presets.js +32 -0
  49. package/dist/request-z6DHHmrb.js +47 -0
  50. package/dist/runtime/console.d.ts +3 -0
  51. package/dist/runtime/console.js +4 -0
  52. package/dist/runtime/empty-abilities.d.ts +5 -0
  53. package/dist/runtime/empty-abilities.js +4 -0
  54. package/dist/runtime/empty-client.d.ts +6 -0
  55. package/dist/runtime/empty-client.js +5 -0
  56. package/dist/runtime/empty-definition.d.ts +1 -2
  57. package/dist/runtime/nuxt.d.ts +2 -3
  58. package/dist/runtime/nuxt.js +3 -2
  59. package/dist/runtime/server.d.ts +2 -0
  60. package/dist/runtime/server.js +77 -0
  61. package/dist/runtime/vue-nuxt.d.ts +4 -0
  62. package/dist/runtime/vue-nuxt.js +160 -0
  63. package/dist/runtime-state-ojQCzKOc.js +25 -0
  64. package/dist/schema.d.ts +137 -0
  65. package/dist/schema.js +147 -0
  66. package/dist/server-C0qnKN2W.d.ts +143 -0
  67. package/dist/server-bQGzVQ--.d.ts +41 -0
  68. package/dist/server.d.ts +3 -22
  69. package/dist/server.js +3 -2
  70. package/dist/session-cookies-BbH3UR2m.js +227 -0
  71. package/dist/set-cookie-C8NOhdRE.js +90 -0
  72. package/dist/shared-BwcdRGxD.js +12 -0
  73. package/dist/table-specs-8gq_FCaq.js +771 -0
  74. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  75. package/dist/test.d.ts +26 -0
  76. package/dist/test.js +25 -0
  77. package/dist/types-CNaeH2Fd.d.ts +569 -0
  78. package/dist/vite-CV400XXY.js +1556 -0
  79. package/dist/vite.d.ts +145 -18
  80. package/dist/vite.js +2 -2
  81. package/dist/vue.d.ts +343 -17
  82. package/dist/vue.js +640 -15
  83. package/package.json +156 -27
  84. package/dist/server-BZn8iQrB.js +0 -370
  85. package/dist/shared-QSYBHaMG.js +0 -12
  86. package/dist/types-jaRlW3D1.d.ts +0 -117
  87. package/dist/vite-Cmey8ODS.js +0 -1018
@@ -0,0 +1,280 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { t as isRecord } from "./object-Da1zyPCR.js";
3
+ import { t as accessRouteSyntaxError } from "./application-path-DuTpfGFj.js";
4
+ import { t as normalizeAuthBasePath } from "./shared-BwcdRGxD.js";
5
+ import { r as authDatabaseName } from "./database-options-BRNef9oy.js";
6
+ //#region src/stateless-user-id.ts
7
+ const pendingUserIds = /* @__PURE__ */ new WeakMap();
8
+ /** The user ID of one provider account: the first 32 hex digits of SHA-256 over the provider ID and the account ID. */
9
+ async function statelessUserId(providerId, accountId) {
10
+ const input = new TextEncoder().encode(JSON.stringify([
11
+ "vitehub:auth:user",
12
+ providerId,
13
+ accountId
14
+ ]));
15
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input));
16
+ return Array.from(digest.slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
17
+ }
18
+ /** The account ID that Better Auth stores for this provider profile, from the provider's own `accountSubject`. */
19
+ async function accountSubject(context, providerId, profile) {
20
+ const subject = await context.context.socialProviders.find((candidate) => candidate.id === providerId)?.accountSubject({
21
+ profile,
22
+ tokens: {}
23
+ });
24
+ return subject === void 0 || subject === null || String(subject).trim() === "" ? void 0 : String(subject);
25
+ }
26
+ /**
27
+ * Without a database, Better Auth creates a new user at each sign-in. These hooks give that user an ID derived from
28
+ * the provider account, so the same account gets the same `user.id` on every sign-in, instance, and restart.
29
+ * They wrap the application's own `user.validateUserInfo` and `databaseHooks.user.create.before`.
30
+ */
31
+ function withStatelessUserId(options) {
32
+ const user = options.user ?? {};
33
+ const databaseHooks = options.databaseHooks ?? {};
34
+ const validateUserInfo = user.validateUserInfo;
35
+ const createBefore = databaseHooks.user?.create?.before;
36
+ const validate = async (data, context) => {
37
+ const { source } = data;
38
+ if (source.action === "create-user" && source.method === "oauth" && source.oauth) {
39
+ const accountId = await accountSubject(context, source.oauth.providerId, source.oauth.profile ?? {});
40
+ if (accountId === void 0) return {
41
+ error: "vitehub_account_subject_missing",
42
+ errorDescription: "The provider did not return an account ID."
43
+ };
44
+ pendingUserIds.set(context, await statelessUserId(source.oauth.providerId, accountId));
45
+ }
46
+ return validateUserInfo?.(data, context);
47
+ };
48
+ const before = async (data, context) => {
49
+ const result = createBefore ? await createBefore(data, context) : void 0;
50
+ const id = context ? pendingUserIds.get(context) : void 0;
51
+ if (result === false || id === void 0) return result;
52
+ if (context) pendingUserIds.delete(context);
53
+ return { data: {
54
+ ...typeof result === "object" ? result.data : {},
55
+ id
56
+ } };
57
+ };
58
+ return {
59
+ databaseHooks: {
60
+ ...databaseHooks,
61
+ user: {
62
+ ...databaseHooks.user,
63
+ create: {
64
+ ...databaseHooks.user?.create,
65
+ before
66
+ }
67
+ }
68
+ },
69
+ user: {
70
+ ...user,
71
+ validateUserInfo: validate
72
+ }
73
+ };
74
+ }
75
+ //#endregion
76
+ //#region src/preset-options.ts
77
+ const verificationPluginIds = /* @__PURE__ */ new Set([
78
+ "email-otp",
79
+ "magic-link",
80
+ "one-time-token"
81
+ ]);
82
+ const statelessOwnedOptions = [
83
+ ["session", "expiresIn"],
84
+ [
85
+ "session",
86
+ "cookieCache",
87
+ "enabled"
88
+ ],
89
+ [
90
+ "session",
91
+ "cookieCache",
92
+ "maxAge"
93
+ ],
94
+ [
95
+ "session",
96
+ "cookieCache",
97
+ "refreshCache"
98
+ ],
99
+ [
100
+ "session",
101
+ "cookieCache",
102
+ "strategy"
103
+ ],
104
+ ["account", "storeAccountCookie"],
105
+ ["account", "storeStateStrategy"]
106
+ ];
107
+ function readPath(value, path) {
108
+ let current = value;
109
+ for (const key of path) {
110
+ if (!isRecord(current) || !Object.hasOwn(current, key)) return void 0;
111
+ current = current[key];
112
+ }
113
+ return current;
114
+ }
115
+ function readStatelessPreset(value) {
116
+ if (isRecord(value) && value.name === "stateless" && typeof value.maxAge === "number" && Number.isSafeInteger(value.maxAge) && value.maxAge > 0) return {
117
+ name: "stateless",
118
+ maxAge: value.maxAge
119
+ };
120
+ throw authErrorDiagnostics.AUTH_C0043({ message: "`defineAuth()` preset must be a preset such as `stateless()` from `vite-hub/auth/presets`." });
121
+ }
122
+ function storedPluginId(plugin) {
123
+ if (!isRecord(plugin)) return;
124
+ const id = typeof plugin.id === "string" ? plugin.id : "unknown";
125
+ if (isRecord(plugin.schema) && Object.keys(plugin.schema).length > 0) return id;
126
+ if (verificationPluginIds.has(id)) return id;
127
+ }
128
+ /** Checks that the options can run with `stateless()` and returns the Better Auth options it sets. */
129
+ function applyStatelessPreset(preset, options) {
130
+ if (options.database !== void 0) throw authErrorDiagnostics.AUTH_C0044({ message: "`stateless()` keeps sessions in cookies and cannot use `database`. Remove `database`, or remove the preset to store sessions in a database." });
131
+ if (options.secondaryStorage !== void 0) throw authErrorDiagnostics.AUTH_C0045({ message: "`stateless()` keeps sessions in cookies and cannot use `secondaryStorage`. Remove `secondaryStorage`, or remove the preset to store sessions on the server." });
132
+ if (readPath(options, ["emailAndPassword", "enabled"]) === true) throw authErrorDiagnostics.AUTH_C0046({ message: "`stateless()` has no database to store users and passwords, so `emailAndPassword` cannot be enabled. Use `socialProviders`, or remove the preset and configure a database." });
133
+ const plugin = Array.isArray(options.plugins) ? options.plugins.map(storedPluginId).find(Boolean) : void 0;
134
+ if (plugin) throw authErrorDiagnostics.AUTH_C0047({ message: `\`stateless()\` has no database, and the Better Auth plugin "${plugin}" stores data in one. Remove the plugin, or remove the preset and configure a database.` });
135
+ const owned = statelessOwnedOptions.find((path) => readPath(options, path) !== void 0);
136
+ if (owned) throw authErrorDiagnostics.AUTH_C0048({ message: `\`stateless()\` sets \`${owned.join(".")}\`. Remove it from the Auth Definition, and pass \`maxAge\` to \`stateless()\` to change the session lifetime.` });
137
+ const session = isRecord(options.session) ? options.session : {};
138
+ const cookieCache = isRecord(session.cookieCache) ? session.cookieCache : {};
139
+ const account = isRecord(options.account) ? options.account : {};
140
+ return {
141
+ ...options,
142
+ ...withStatelessUserId(options),
143
+ account: {
144
+ ...account,
145
+ storeAccountCookie: true,
146
+ storeStateStrategy: "cookie"
147
+ },
148
+ session: {
149
+ ...session,
150
+ cookieCache: {
151
+ ...cookieCache,
152
+ enabled: true,
153
+ maxAge: preset.maxAge,
154
+ refreshCache: true,
155
+ strategy: "jwe"
156
+ },
157
+ expiresIn: preset.maxAge
158
+ }
159
+ };
160
+ }
161
+ /** Validates the `preset` option and returns the options with the preset's Better Auth options applied. */
162
+ function applyAuthPreset(options) {
163
+ if (options.preset === void 0) return options;
164
+ const { preset, ...rest } = options;
165
+ return applyStatelessPreset(readStatelessPreset(preset), rest);
166
+ }
167
+ //#endregion
168
+ //#region src/events-config.ts
169
+ function validateAuthEvents(value) {
170
+ if (value === void 0 || value === false) return;
171
+ if (!value || typeof value !== "object" || !("store" in value) || !value.store || typeof value.store !== "object" || ![
172
+ "append",
173
+ "list",
174
+ "aggregate"
175
+ ].every((key) => typeof Reflect.get(value.store, key) === "function") || "authorize" in value && value.authorize !== void 0 && typeof value.authorize !== "function" || "onEvent" in value && value.onEvent !== void 0 && typeof value.onEvent !== "function") throw authErrorDiagnostics.AUTH_C0050({ message: "`defineAuth()` events needs a store with append, list, and aggregate methods. events.authorize and events.onEvent must be functions. Set events to false to disable the log." });
176
+ }
177
+ //#endregion
178
+ //#region src/definition.ts
179
+ const authRuntimeOptionNames = /* @__PURE__ */ new Set([
180
+ "baseURL",
181
+ "secret",
182
+ "secrets"
183
+ ]);
184
+ const accessRouteKeys = /* @__PURE__ */ new Set([
185
+ "authorize",
186
+ "method",
187
+ "route"
188
+ ]);
189
+ function validateAuthDatabase(value) {
190
+ if (typeof value === "undefined" || value === "memory" || authDatabaseName(value) !== void 0) return;
191
+ throw authErrorDiagnostics.AUTH_C0021({ message: "`defineAuth()` database must be `authDatabase()` from `vite-hub/auth/database` or `\"memory\"`. `true` and `{ name }` do not create storage. Return another Better Auth adapter from the Definition callback." });
192
+ }
193
+ /** `runtime` was a second way to resolve options. Its shallow merge replaced whole objects such as `advanced`. */
194
+ function assertNoRuntimeOption(options) {
195
+ if (!Object.hasOwn(options, "runtime")) return;
196
+ throw authErrorDiagnostics.AUTH_C0039({ message: "`defineAuth()` no longer takes `runtime`. Pass one callback that returns all options, so no option replaces another." });
197
+ }
198
+ function validateAuthSecondaryStorage(value) {
199
+ if (typeof value === "undefined") return;
200
+ throw authErrorDiagnostics.AUTH_C0024({ message: "`defineAuth()` secondaryStorage takes only a Better Auth adapter, from the Definition callback. `true` and `{ store }` do not create storage." });
201
+ }
202
+ function validateStringValue(value, label) {
203
+ if (typeof value !== "string" || value.trim().length === 0) throw authErrorDiagnostics.AUTH_C0026({ message: `\`defineAuth()\` ${label} must be a non-empty string.` });
204
+ }
205
+ function validateRouteValue(value, label) {
206
+ validateStringValue(value, label);
207
+ if (typeof value !== "string") return;
208
+ if (!value.startsWith("/")) throw authErrorDiagnostics.AUTH_C0027({ message: `\`defineAuth()\` ${label} must start with \`/\`.` });
209
+ const syntaxError = accessRouteSyntaxError(value, label);
210
+ if (syntaxError) throw authErrorDiagnostics.AUTH_C0068({ message: syntaxError });
211
+ }
212
+ function validateAuthSignIn(value) {
213
+ if (typeof value === "undefined") return;
214
+ if (!isRecord(value)) throw authErrorDiagnostics.AUTH_C0028({ message: "`defineAuth()` access.signIn must be an object." });
215
+ validateStringValue(value.provider, "access.signIn.provider");
216
+ if (typeof value.callbackURL !== "undefined") validateStringValue(value.callbackURL, "access.signIn.callbackURL");
217
+ if (typeof value.errorCallbackURL !== "undefined") validateStringValue(value.errorCallbackURL, "access.signIn.errorCallbackURL");
218
+ if (typeof value.requestSignUp !== "undefined" && typeof value.requestSignUp !== "boolean") throw authErrorDiagnostics.AUTH_C0029({ message: "`defineAuth()` access.signIn.requestSignUp must be a boolean." });
219
+ if (typeof value.scopes !== "undefined" && (!Array.isArray(value.scopes) || value.scopes.some((scope) => typeof scope !== "string"))) throw authErrorDiagnostics.AUTH_C0030({ message: "`defineAuth()` access.signIn.scopes must be an array of strings." });
220
+ }
221
+ function validateAuthAccessRoute(value, label) {
222
+ if (typeof value === "string") {
223
+ validateRouteValue(value, label);
224
+ return;
225
+ }
226
+ if (!isRecord(value)) throw authErrorDiagnostics.AUTH_C0031({ message: `\`defineAuth()\` ${label} must be a route string or route object.` });
227
+ const unknownKey = Object.keys(value).find((key) => !accessRouteKeys.has(key));
228
+ if (unknownKey) throw authErrorDiagnostics.AUTH_C0032({ message: `\`defineAuth()\` ${label} does not support the "${unknownKey}" option.` });
229
+ validateRouteValue(value.route, `${label}.route`);
230
+ if (typeof value.authorize !== "undefined" && typeof value.authorize !== "function") throw authErrorDiagnostics.AUTH_C0033({ message: `\`defineAuth()\` ${label}.authorize must be a function.` });
231
+ if (typeof value.method !== "undefined") validateStringValue(value.method, `${label}.method`);
232
+ }
233
+ function validateAuthAccess(value) {
234
+ if (typeof value === "undefined") return;
235
+ if (!isRecord(value)) throw authErrorDiagnostics.AUTH_C0034({ message: "`defineAuth()` access must be an object." });
236
+ const access = value;
237
+ if (typeof access.routes !== "undefined") {
238
+ if (!Array.isArray(access.routes)) throw authErrorDiagnostics.AUTH_C0035({ message: "`defineAuth()` access.routes must be an array." });
239
+ access.routes.forEach((route, index) => validateAuthAccessRoute(route, `access.routes[${index}]`));
240
+ }
241
+ validateAuthAccessPublic(access.public);
242
+ validateAuthAccessPolicy(access.policy);
243
+ validateAuthSignIn(access.signIn);
244
+ }
245
+ function validateAuthAccessPublic(value) {
246
+ if (typeof value === "undefined") return;
247
+ if (!Array.isArray(value) || Array.from(value).some((route) => typeof route !== "string" || !route.startsWith("/"))) throw authErrorDiagnostics.AUTH_C0064({ message: "`defineAuth()` access.public must be an array of routes that start with `/`." });
248
+ }
249
+ /** Also checked when a Definition callback returns the options. */
250
+ function validateAuthAccessPolicy(value) {
251
+ if (typeof value === "undefined") return;
252
+ const recheck = isRecord(value) ? value.recheck : void 0;
253
+ if (!isRecord(value) || typeof value.allow !== "function" || typeof recheck !== "undefined" && (typeof recheck !== "number" || !Number.isFinite(recheck) || recheck < 0)) throw authErrorDiagnostics.AUTH_C0065({ message: "`defineAuth()` access.policy must be an object with an `allow` function and an optional `recheck` of 0 or more milliseconds." });
254
+ }
255
+ function defineAuth(options) {
256
+ return defineAuthOptions(options);
257
+ }
258
+ function defineAuthOptions(options) {
259
+ if (typeof options === "function") return { options };
260
+ if (!isRecord(options)) throw authErrorDiagnostics.AUTH_C0036({ message: "`defineAuth()` expects an object or a callback." });
261
+ const viteHubOptions = options;
262
+ const runtimeOption = Object.keys(options).find((key) => authRuntimeOptionNames.has(key));
263
+ if (runtimeOption) throw authErrorDiagnostics.AUTH_C0037({ message: `\`defineAuth()\` ${runtimeOption} is resolved at runtime and cannot be defined in the Auth Definition.` });
264
+ if (typeof viteHubOptions.route !== "undefined" && viteHubOptions.route !== false) throw authErrorDiagnostics.AUTH_C0038({ message: "`defineAuth()` route can only be `false` when provided." });
265
+ assertNoRuntimeOption(options);
266
+ if (typeof viteHubOptions.basePath !== "undefined") {
267
+ if (typeof viteHubOptions.basePath !== "string") throw authErrorDiagnostics.AUTH_C0040({ message: "`defineAuth()` basePath must be a string." });
268
+ normalizeAuthBasePath(viteHubOptions.basePath);
269
+ }
270
+ const session = options.session;
271
+ if (isRecord(session) && typeof session.onRefresh !== "undefined" && typeof session.onRefresh !== "function") throw authErrorDiagnostics.AUTH_C0041({ message: "`defineAuth()` session.onRefresh must be a function." });
272
+ validateAuthEvents(options.events);
273
+ validateAuthDatabase(viteHubOptions.database);
274
+ validateAuthSecondaryStorage(viteHubOptions.secondaryStorage);
275
+ validateAuthAccess(viteHubOptions.access);
276
+ applyAuthPreset(options);
277
+ return { options };
278
+ }
279
+ //#endregion
280
+ export { applyAuthPreset as a, validateAuthEvents as i, defineAuth as n, validateAuthAccessPolicy as r, assertNoRuntimeOption as t };
@@ -0,0 +1,138 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ /** A code whose call site passes the message as `why`, with the fix that the reader applies. */
5
+ const withFix = (fix) => ({
6
+ ...dynamicError,
7
+ fix
8
+ });
9
+ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
10
+ docsBase: "https://vitehub.dev/docs/auth/diagnostics",
11
+ codes: {
12
+ AUTH_EVENT_CALLBACK_FAILED: {
13
+ why: ({ type }) => `\`events.onEvent\` failed for the ${JSON.stringify(type)} auth event. Auth kept the change and the stored event.`,
14
+ fix: "Read `error.cause` for the error of your callback. Catch errors inside `events.onEvent`, and retry the outside call there if it can fail."
15
+ },
16
+ AUTH_EVENT_QUERY_INVALID: {
17
+ why: ({ problem }) => problem === "order" ? "Auth event from must be before to." : "Auth event windows must be positive and at most 366 days.",
18
+ fix: "Pass `from` before `to`, as ISO timestamps, and keep an aggregate window at most 366 days long."
19
+ },
20
+ AUTH_EVENT_RETENTION_INVALID: {
21
+ why: "Auth event retention limits must be positive integers.",
22
+ fix: "Pass `retention: { maxAgeMs, maxRecords }` to `createDatabaseAuthEventStore()` with positive whole numbers, or `retention: false` to keep every event."
23
+ },
24
+ AUTH_PASSWORD_HASH_INVALID: {
25
+ why: "Invalid password hash",
26
+ fix: "The stored password hash is not `<salt>:<key>`. Hash new passwords with `hashPasswordWithNoble()` or the Better Auth hasher, and reset the password of the user whose hash is broken."
27
+ },
28
+ AUTH_SIGN_OUT_REDIRECT_INVALID: {
29
+ why: ({ redirectTo }) => `\`signOut()\` redirects only to a path of the app, not to ${JSON.stringify(redirectTo)}.`,
30
+ fix: "Pass a path that starts with one `/`, for example `signOut(event, { redirectTo: '/login' })`. A value from the query string can point to another site, so check it against your own pages first."
31
+ },
32
+ AUTH_TEST_SIGN_IN_STATELESS: {
33
+ why: "`signIn()` writes the user and the session to the Auth database, and a Definition with the `stateless()` preset has none.",
34
+ fix: "Test the routes of a `stateless()` Definition through its social sign-in flow, or give the test app `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`."
35
+ },
36
+ AUTH_R0001: withFix("Return an Agent Invoker from the `map` callback of `authenticated()` for each request. Remove `map` to use the default Invoker."),
37
+ AUTH_R0002: withFix("Make `meta` of `authenticated()` return a plain object, `null`, or `undefined`, for example `meta: ({ user }) => ({ plan: user.plan })`."),
38
+ AUTH_C0001: withFix("Write the value as a string literal in `defineAuth()`, for example `basePath: '/auth'`. The Vite plugin reads it at build time, so it cannot use a variable or an expression."),
39
+ AUTH_C0002: withFix("Remove the spaces at the start and end of the value, for example `basePath: '/auth'` or `method: 'POST'`."),
40
+ AUTH_C0003: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
41
+ AUTH_C0005: withFix("Write each key as a plain name in the object, for example `{ route: '/admin/**' }`. Do not use computed keys or spreads."),
42
+ AUTH_C0006: withFix("Remove the option. A route object takes only `route`, `method`, and `authorize`."),
43
+ AUTH_C0007: withFix("Write each key as a plain name in the object, for example `{ route: '/admin/**' }`. Do not use computed keys or spreads."),
44
+ AUTH_C0008: withFix("Set `route: false` to stop the automatic `/api/auth/**` route, or remove `route`. Use `basePath` to move the route."),
45
+ AUTH_C0009: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
46
+ AUTH_C0010: withFix("Write each entry of `access.routes` inline as a route string or an object, for example `'/admin/**'` or `{ route: '/api/admin/**', method: 'POST' }`."),
47
+ AUTH_C0011: withFix("Add `route` to the route object, for example `{ route: '/admin/**', authorize: isAdmin }`."),
48
+ AUTH_C0012: withFix("Write `access.routes` as an array literal in `defineAuth()`, for example `access: { routes: ['/admin/**'] }`. The Vite plugin reads it at build time."),
49
+ AUTH_C0014: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Return another Better Auth adapter from the Definition callback. Set `database: \"memory\"` to keep sessions in the memory of one server process."),
50
+ AUTH_C0017: withFix("Remove `secondaryStorage` from the static options. Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, from the Definition callback."),
51
+ AUTH_C0019: withFix("Pass an object literal to `defineAuth()` in `server/auth.ts`, or a callback that returns one, for example `export default defineAuth({ basePath: '/auth' })`. Do not pass a variable."),
52
+ AUTH_C0021: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Return another Better Auth adapter from the Definition callback. Set `database: \"memory\"` to keep sessions in the memory of one server process."),
53
+ AUTH_C0024: withFix("Remove `secondaryStorage` from the static options. Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, from the Definition callback."),
54
+ AUTH_C0026: withFix("Set the option to a non-empty string, for example `provider: 'github'` or `method: 'GET'`."),
55
+ AUTH_C0027: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
56
+ AUTH_C0028: withFix("Set `access.signIn` to an object, for example `signIn: { provider: 'github' }`."),
57
+ AUTH_C0029: withFix("Set `access.signIn.requestSignUp` to `true` or `false`, or remove it."),
58
+ AUTH_C0030: withFix("Set `access.signIn.scopes` to an array of strings, for example `scopes: ['read:org']`."),
59
+ AUTH_C0031: withFix("Write each entry of `access.routes` as a route string or an object, for example `'/admin/**'` or `{ route: '/api/admin/**', authorize }`."),
60
+ AUTH_C0032: withFix("Remove the option. A route object takes only `route`, `method`, and `authorize`."),
61
+ AUTH_C0033: withFix("Set `authorize` to a function that returns `true`, `false`, or a `Response`, for example `authorize: ({ user }) => user.role === 'admin'`."),
62
+ AUTH_C0034: withFix("Set `access` to an object, for example `access: { routes: ['/admin/**'] }`."),
63
+ AUTH_C0035: withFix("Set `access.routes` to an array, for example `routes: ['/admin/**']`."),
64
+ AUTH_C0036: withFix("Pass an options object or a callback that returns one to `defineAuth()`, for example `defineAuth({ emailAndPassword: { enabled: true } })`."),
65
+ AUTH_C0037: withFix("Return the option from the Definition callback, for example `defineAuth(({ env }) => ({ secret: env.auth.secret.unseal() }))`."),
66
+ AUTH_C0038: withFix("Set `route: false` to stop the automatic `/api/auth/**` route, or remove `route`. Use `basePath` to move the route."),
67
+ AUTH_C0039: withFix("Remove `runtime` and pass one callback that returns all options, for example `defineAuth(({ env }) => ({ advanced: { cookiePrefix: 'acme', trustedProxyHeaders: true }, secret: env.auth.secret.unseal() }))`. Keep `authDatabase()` inline in the returned object."),
68
+ AUTH_C0040: withFix("Set `basePath` to a string that starts with `/`, for example `basePath: '/auth'`."),
69
+ AUTH_C0041: withFix("Set `session.onRefresh` to a function, for example `onRefresh: async ({ session }) => {}`, or remove it."),
70
+ AUTH_C0042: withFix("Set `database: authDatabase()` or return a Better Auth `database` or `secondaryStorage` adapter. Or remove `session.onRefresh`."),
71
+ AUTH_C0043: withFix("Import the preset and call it, for example `preset: stateless()` with `import { stateless } from 'vite-hub/auth/presets'`."),
72
+ AUTH_C0044: withFix("Remove the option from the Auth Definition, or remove `preset: stateless()` and configure a Better Auth database."),
73
+ AUTH_C0045: withFix("Remove the option from the Auth Definition, or remove `preset: stateless()` and configure a Better Auth database."),
74
+ AUTH_C0046: withFix("Remove `emailAndPassword` and use `socialProviders`, or remove `preset: stateless()` and configure a Better Auth database."),
75
+ AUTH_C0047: withFix("Remove the plugin that the message names, or remove `preset: stateless()` and configure a Better Auth database."),
76
+ AUTH_C0048: withFix("Remove the option that the message names. Pass `maxAge` to `stateless()` to change the session lifetime, for example `stateless({ maxAge: '12h' })`."),
77
+ AUTH_C0049: withFix("Pass a positive whole number of seconds or a duration, for example `stateless({ maxAge: '7d' })` or `stateless({ maxAge: 3600 })`."),
78
+ AUTH_C0050: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }`, or `events: false` to disable the log. `events.authorize` and `events.onEvent` must be functions."),
79
+ AUTH_C0051: withFix("Add `admin()` from `better-auth/plugins` to the `plugins` of `defineAuth()`, or unset the variable that the message names."),
80
+ AUTH_C0052: withFix("Pass the Database name as one string literal, for example `authDatabase('content')`, or no argument for the `default` Database."),
81
+ AUTH_C0053: withFix("Remove `advanced.database.generateId`, or set it to a function that returns strings. Use another Better Auth adapter for numeric or UUID IDs."),
82
+ AUTH_C0054: withFix("Call `authDatabase()` inline as `database` in the object of `defineAuth()`, or in the one object that its callback returns. Do not select it in a branch."),
83
+ AUTH_C0055: withFix("Write `additionalFields` inline in `server/auth.ts`, with a literal `type` for each field, for example `user: { additionalFields: { login: { type: 'string', required: false } } }`."),
84
+ AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, call it in `server/auth.ts` so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
85
+ AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217`."),
86
+ AUTH_C0058: withFix("Write each `VITEHUB_ADMINS` entry as `<provider>:<account id>`, for example `github:22072217`. Run `gh api users/<login> --jq .id` to get a GitHub account id. For an app with only email sign-in, remove `VITEHUB_ADMINS`, then run `vitehub auth claim`."),
87
+ AUTH_C0059: withFix("Run `vitehub auth claim` and set `VITEHUB_ADMIN_CLAIM` to the `sha256:` value that it prints. Do not set the code itself."),
88
+ AUTH_R0018: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }` in `defineAuth()`."),
89
+ AUTH_R0003: withFix("Keep one of `server/auth.ts` and `server.auth.ts` and delete the others that the message lists. For Nuxt layers, add `server/auth.ts` to the app to select the Definition."),
90
+ AUTH_R0004: withFix("Pass a non-empty `message` of at most 16,384 characters to `authenticated()`, or remove `message`."),
91
+ AUTH_C0060: withFix("Keep one abilities file at `shared/abilities.ts`. Remove the other files listed in the message, or add the app file to replace layer rules."),
92
+ AUTH_C0061: withFix("Return `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or `authDatabase('auth')` for the Named Database `auth`. Or return another Better Auth adapter."),
93
+ AUTH_C0062: withFix("Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, or remove `secondaryStorage`."),
94
+ AUTH_C0063: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'` to keep users in the app Database. Use `preset: stateless()` for social sign-in without a database. Set `database: \"memory\"` only when one server process may keep users until it restarts."),
95
+ AUTH_C0064: withFix("Write `access.public` as an inline array of route strings, for example `public: ['/', '/login', '/api/health']`. The Vite plugin reads it at build time."),
96
+ AUTH_C0065: withFix("Set `access.policy` to an object with an `allow` function, for example `policy: { allow: ({ user }) => user.emailVerified === true, recheck: 300_000 }`. `recheck` is a number of milliseconds, 0 or more."),
97
+ AUTH_C0066: withFix("Return `database: authDatabase()` or another Better Auth adapter, or a `secondaryStorage` adapter. `access.policy` ends sessions, so Auth must store them."),
98
+ AUTH_C0067: withFix("Pass both options, for example `forwardAuth({ header: 'x-auth-request-access-token', verify: async ({ value }) => lookUpIdentity(value) })`. `verify` must prove the header, for example with the provider or a secret that only the proxy sends."),
99
+ AUTH_C0068: withFix("Write each access route as a literal path, without percent-encoded pattern syntax or `.` and `..` segments. To guard a path and every path below it, end the route with `/**`, for example `/api/users/**` in place of `/api/users/:id` or `/api/admin/*`. Check the parameter in the handler."),
100
+ AUTH_B0001: withFix("Set `env.projectRoot` of `@vite-hub/auth/nuxt` to the `projectRoot` of the `hubEnv()` plugin, or remove `env.projectRoot`."),
101
+ AUTH_B0002: withFix("Remove `swr`, `cache`, `isr`, `prerender`, or `static` from the route rule that the message names. Or add a rule for the guarded path that turns the cache off, for example `routeRules: { '/dashboard/**': { cache: false, prerender: false } }`. If the page is public, remove the route from `access.routes`."),
102
+ AUTH_R0005: withFix("Add `server/auth.ts` with `export default defineAuth({})`. For a Nuxt layer, add it to the app."),
103
+ AUTH_R0006: withFix("Send the `Origin` header with the request. Browsers send it. A server-side caller must set it, for example `headers: { origin: 'https://app.example.com' }`."),
104
+ AUTH_R0007: withFix("Add the origin to Better Auth's `trustedOrigins` in the Auth Definition, for example `trustedOrigins: ['https://app.example.com']`. Or send the request from the app origin."),
105
+ AUTH_R0008: withFix("Restart the dev server or rebuild the app after you change `access.routes`, so that the generated middleware and the Auth Definition list the same routes. With `createAuthAccessHandler()`, list the routes in the order of `access.routes`."),
106
+ AUTH_R0009: withFix("Pass the indexes of the matched `access.routes`, for example `requireAuthAccessRoutes(event, [0])`. Or use `createAuthAccessHandler()`, which finds them."),
107
+ AUTH_R0010: withFix("Pass the indexes of the matched routes that have `authorize` as the fourth argument of `requireAuthAccessRoutes()`, for example `[0]`, or `[]` for none."),
108
+ AUTH_R0011: withFix("Install the `better-auth` version that `@vite-hub/auth` depends on. If the versions match, this is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message."),
109
+ AUTH_R0012: withFix("Install the `better-auth` version that `@vite-hub/auth` depends on. If the versions match, this is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message."),
110
+ AUTH_R0013: withFix("Set `basePath` to a path that starts with `/` and is not only `/`, for example `basePath: '/auth'`."),
111
+ AUTH_R0014: withFix("Pass a function that returns `true`, `false`, or a `Response`, for example `withAuthorization(({ user }) => user.role === 'admin', handler)`. `withAuthorization()` and `requireAuthorization()` also take `true` for any signed-in user. `withAnonymousAuthorization()` takes only a function."),
112
+ AUTH_R0015: withFix("Pass your handler function, for example `withAuth((event, { user }) => ({ id: user.id }))`."),
113
+ AUTH_R0016: withFix("Set `VITEHUB_SECRET` to at least 32 random characters. Run `openssl rand -base64 32` to make one."),
114
+ AUTH_R0019: withFix("Pass `authDatabase()` inline as `database` of `defineAuth()`, enable the Database integration, and run `vitehub database generate`. Run `vitehub inspect definitions --kind database` to list the tables."),
115
+ AUTH_R0020: withFix("Add the named rule to `shared/abilities.ts` with `defineAbilities()`, or use an existing ability name."),
116
+ AUTH_R0021: withFix("Return the result at once. Load data before the ability check and pass it as a rule argument; remove `async` from the rule."),
117
+ AUTH_R0022: withFix("Send the request to an origin that `vitehub({ publicUrl })` returns for one of your Agents, or set `baseURL` in the Auth Definition. The request Host cannot choose the Auth origin."),
118
+ AUTH_R0023: withFix("Return `null` from `verify` to ignore the header, or an object with `providerId`, `accountId`, `email`, `name`, and `emailVerified`, for example `{ providerId: 'github', accountId: String(user.id), email, name: user.login, emailVerified: true }`."),
119
+ AUTH_EVENTS_OPTION_INVALID: {
120
+ why: ({ option, problem }) => problem === "unknown" ? `[vitehub] Unknown auth events option: ${option}` : `[vitehub] Missing value for ${option}.`,
121
+ fix: "Pass only the options that `vitehub auth events --help` lists, each followed by its value."
122
+ },
123
+ AUTH_EVENTS_REQUEST_FAILED: {
124
+ why: ({ status }) => `[vitehub] Auth events returned HTTP ${status}.`,
125
+ fix: "Return true from `events.authorize` in `defineAuth()` for your user, and set VITEHUB_AUTH_COOKIE to the cookie of a session of that user."
126
+ },
127
+ AUTH_EVENTS_URL_INSECURE: {
128
+ why: "[vitehub] Auth events requires HTTPS or a loopback HTTP URL.",
129
+ fix: "Pass an `https://` Auth base URL to `--url`, or `http://localhost` for a dev server."
130
+ },
131
+ AUTH_EVENTS_URL_MISSING: {
132
+ why: "[vitehub] `vitehub auth events` has no Auth base URL.",
133
+ fix: "Pass `--url` with the Auth base URL, such as `--url http://localhost:5173/api/auth`, or set VITEHUB_AUTH_URL."
134
+ }
135
+ }
136
+ });
137
+ //#endregion
138
+ export { authErrorDiagnostics as t };