@vite-hub/auth 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +32 -8
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-3L1Y5Pnw.d.ts} +2 -4
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/abilities.js +1 -2
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-BHhPkrZd.js} +3 -5
  6. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-C1c30O6E.d.ts} +1 -5
  7. package/dist/access-pages-BwImVHN_.js +94 -0
  8. package/dist/{admin-claim-code-CDipqeAU.js → admin-claim-code-C3X_U43x.js} +1 -2
  9. package/dist/agent.d.ts +1 -3
  10. package/dist/agent.js +5 -6
  11. package/dist/{application-path-DuTpfGFj.js → application-path-zKi7NrvK.js} +1 -2
  12. package/dist/{auth-instance-CmDogt4D.js → auth-instance-_J7R9Qs1.js} +239 -50
  13. package/dist/{cli-ubYJpAL_.d.ts → cli-C5pAfY4x.d.ts} +1 -6
  14. package/dist/cli.d.ts +2 -4
  15. package/dist/cli.js +3 -4
  16. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-BP1ZKJB0.d.ts} +13 -13
  17. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-vc3JQEuq.js} +72 -40
  18. package/dist/console-runtime.d.ts +2 -2
  19. package/dist/console-runtime.js +1 -2
  20. package/dist/{console-types-CmmnKGMx.js → console-types-51lkf0lk.js} +1 -2
  21. package/dist/console.d.ts +1 -5
  22. package/dist/console.js +2 -3
  23. package/dist/{database-options-DpOVjUti.js → database-options-DQ-8qYMl.js} +2 -3
  24. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CkSeU9V3.js} +2 -3
  25. package/dist/database.d.ts +1 -3
  26. package/dist/database.js +5 -6
  27. package/dist/{definition-BCaLA9kW.js → definition-MDGMNKrK.js} +20 -18
  28. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-BssJr_2t.js} +9 -4
  29. package/dist/{events-DCfuicoo.js → events-DZqMiae_.js} +4 -6
  30. package/dist/forward.d.ts +1 -3
  31. package/dist/forward.js +2 -3
  32. package/dist/index.d.ts +4 -7
  33. package/dist/index.js +4 -3
  34. package/dist/internal/server.d.ts +4 -4
  35. package/dist/internal/server.js +5 -5
  36. package/dist/{invariant-D8_xBqmZ.js → invariant-Dj2R1eMr.js} +2 -3
  37. package/dist/{mcp-config-DRRlCAWN.js → mcp-config-C7srUMIZ.js} +2 -3
  38. package/dist/{mcp-token-CpxLyl_p.js → mcp-token--KuLYEub.js} +7 -18
  39. package/dist/mcp.d.ts +0 -4
  40. package/dist/mcp.js +4 -5
  41. package/dist/{members-DdlsS8kJ.js → members-D3_Q5XJb.js} +10 -14
  42. package/dist/nitro-kit-Bg4xUZAI.js +43 -0
  43. package/dist/{nuxt-bridge-Cl988STZ.js → nuxt-bridge-pRyfYD5c.js} +1 -2
  44. package/dist/nuxt.d.ts +31 -24
  45. package/dist/nuxt.js +336 -18
  46. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  47. package/dist/own-access-C22hSIuF.d.ts +18 -0
  48. package/dist/own-access-DQgqxTbI.js +30 -0
  49. package/dist/{page-tools-shared-l4eyj53D.js → page-tools-shared-CtoKaNQZ.js} +1 -2
  50. package/dist/{presets-CHndEv5i.d.ts → presets-C6AtiRdI.d.ts} +0 -2
  51. package/dist/presets.d.ts +1 -1
  52. package/dist/presets.js +2 -3
  53. package/dist/{request-z6DHHmrb.js → request-Dpq7GO8B.js} +2 -4
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +2 -2
  56. package/dist/runtime/empty-abilities.d.ts +1 -3
  57. package/dist/runtime/empty-abilities.js +1 -2
  58. package/dist/runtime/empty-client.d.ts +0 -2
  59. package/dist/runtime/empty-client.js +1 -2
  60. package/dist/runtime/empty-definition.d.ts +1 -3
  61. package/dist/runtime/empty-definition.js +1 -2
  62. package/dist/runtime/nuxt.d.ts +1 -3
  63. package/dist/runtime/nuxt.js +1 -2
  64. package/dist/runtime/server.d.ts +3 -2
  65. package/dist/runtime/server.js +27 -19
  66. package/dist/runtime/vue-nuxt.d.ts +0 -2
  67. package/dist/runtime/vue-nuxt.js +74 -33
  68. package/dist/{runtime-state-ojQCzKOc.js → runtime-state-DtKUfxKq.js} +1 -2
  69. package/dist/schema.d.ts +71 -23
  70. package/dist/schema.js +6 -5
  71. package/dist/{server-BM-RSf1T.d.ts → server-CFWlYQJb.d.ts} +7 -14
  72. package/dist/{server-BG_MFd4q.js → server-D4Hi4TBI.js} +51 -33
  73. package/dist/{server-C8TlOrSy.d.ts → server-DCsgxFPP.d.ts} +9 -14
  74. package/dist/server.d.ts +2 -2
  75. package/dist/server.js +2 -2
  76. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-1FMcMnRh.js} +6 -8
  77. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DkqM1kvj.js} +3 -5
  78. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BLm_Zlss.d.ts} +255 -3
  79. package/dist/{table-specs-CURphR3n.js → table-specs-jw0jjU6l.js} +43 -44
  80. package/dist/test.d.ts +2 -4
  81. package/dist/test.js +3 -4
  82. package/dist/{types-CruflEFI.d.ts → types-BHSgxyvV.d.ts} +50 -11
  83. package/dist/{vite-Dy0Xhq4H.js → vite-D1xC9n1O.js} +365 -152
  84. package/dist/vite.d.ts +7 -14
  85. package/dist/vite.js +1 -2
  86. package/dist/vue.d.ts +17 -72
  87. package/dist/vue.js +25 -73
  88. package/package.json +35 -30
  89. package/dist/shared-DRtfuFsV.js +0 -12
@@ -1,29 +1,29 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DmqWq6kj.js";
3
- import { t as isRecord } from "./object-Da1zyPCR.js";
4
- import { n as authRequestEvent, t as authCloudflareEnv } from "./request-z6DHHmrb.js";
5
- import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-DdlsS8kJ.js";
6
- import { i as resetAuth, n as getAuthRuntimeState, t as authProcessMemoryDatabase } from "./runtime-state-ojQCzKOc.js";
7
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DCfuicoo.js";
8
- import { i as resolveAuthMountPath } from "./application-path-DuTpfGFj.js";
9
- import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
10
- import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-DpOVjUti.js";
11
- import { t as assertAuthDatabaseNames } from "./database-schema-options-Sk-1Bvyu.js";
12
- import { a as validateDeleteAccount, i as createDeleteAccount, o as validateAuthEvents, r as validateAuthAccessPolicy, s as applyAuthPreset, t as assertNoRuntimeOption } from "./definition-BCaLA9kW.js";
13
- import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-l4eyj53D.js";
1
+ import { t as isRecord } from "./object-CAK6UYR5.js";
2
+ import { i as resolveAuthMountPath } from "./application-path-zKi7NrvK.js";
3
+ import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-D3_Q5XJb.js";
4
+ import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-DQ-8qYMl.js";
5
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-CkSeU9V3.js";
6
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
7
+ import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-MDGMNKrK.js";
8
+ import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
9
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DZqMiae_.js";
10
+ import { i as resetAuth, n as getAuthRuntimeState, r as isAuthProcessMemoryDatabase, t as authProcessMemoryDatabase } from "./runtime-state-DtKUfxKq.js";
11
+ import { a as normalizeAuthBasePath } from "./access-pages-BwImVHN_.js";
12
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DkqM1kvj.js";
13
+ import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-CtoKaNQZ.js";
14
14
  import { resolvePublicUrl } from "@vite-hub/runtime";
15
15
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
16
16
  import { AsyncLocalStorage } from "node:async_hooks";
17
- import { createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sensitiveSessionMiddleware } from "better-auth/api";
17
+ import { createAuthEndpoint, createAuthMiddleware, getOAuthState, getSessionFromCtx, isAPIError, sensitiveSessionMiddleware } from "better-auth/api";
18
18
  import { getCookies } from "better-auth/cookies";
19
19
  import { getAuthTables } from "better-auth/db";
20
- import { APIError as APIError$1, betterAuth, isRequestLike, resolveBaseURL } from "better-auth";
20
+ import { APIError as APIError$1, betterAuth, createLogger, isRequestLike, resolveBaseURL } from "better-auth";
21
21
  import { memoryAdapter } from "better-auth/adapters/memory";
22
22
  import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
23
23
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
24
24
  import { isWebContainer } from "@vite-hub/web-container/env";
25
25
  import { hkdfSync } from "node:crypto";
26
- //#region ../internal/src/runtime/request-origin.ts
26
+ // ../internal/src/runtime/request-origin.ts
27
27
  function firstHeaderValue(headers, name) {
28
28
  return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
29
29
  }
@@ -44,8 +44,7 @@ function forwardedRequestOrigin(request) {
44
44
  return url.origin;
45
45
  }
46
46
  }
47
- //#endregion
48
- //#region src/password.ts
47
+ // src/password.ts
49
48
  const scryptOptions = {
50
49
  N: 16384,
51
50
  r: 16,
@@ -106,8 +105,7 @@ function readViteHubSecret(env) {
106
105
  return typeof value === "string" && value ? value : void 0;
107
106
  }
108
107
  Object.freeze({ prefix: "sha256=" });
109
- //#endregion
110
- //#region src/secret.ts
108
+ // src/secret.ts
111
109
  /** The `deriveSecret()` purpose of the Better Auth secret. `vitehub secret derive vitehub:auth` prints it. */
112
110
  const authSecretPurpose = "vitehub:auth";
113
111
  const betterAuthSecretNames = [
@@ -139,13 +137,177 @@ function deriveAuthSecret(event) {
139
137
  };
140
138
  return derived.secret;
141
139
  }
142
- //#endregion
143
- //#region src/event-plugin.ts
140
+ // ../internal/src/runtime/request-log.ts
141
+ function isRequestLog(value) {
142
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
143
+ }
144
+ function contextLog(value) {
145
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
146
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
147
+ }
148
+ /**
149
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
150
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
151
+ */
152
+ function requestLog(input) {
153
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
154
+ return isRequestLog(log) ? log : void 0;
155
+ }
156
+ // src/request-log.ts
144
157
  const authHandlerEvent = new AsyncLocalStorage();
145
- /** Run a Better Auth handler with the request event that `events.authorize` gets. */
158
+ const recorded = /* @__PURE__ */ new WeakSet();
159
+ /** Run a Better Auth handler with the request event that endpoints, hooks, and the logger get. */
146
160
  function runWithAuthEvent(event, run) {
147
161
  return authHandlerEvent.run(event, run);
148
162
  }
163
+ /** The request event of the running `handleAuthRequest()`. */
164
+ function currentAuthEvent() {
165
+ return authHandlerEvent.getStore();
166
+ }
167
+ function requestOf(ctx) {
168
+ return currentAuthEvent() ?? ctx?.request;
169
+ }
170
+ /** The evlog request logger of the running Auth request, or of the endpoint's Request. */
171
+ function authRequestLog(ctx) {
172
+ return requestLog(requestOf(ctx));
173
+ }
174
+ /** Sets the `auth` field of a request's wide event. Without evlog, it does nothing. */
175
+ function setAuthOutcome(request, outcome) {
176
+ const log = requestLog(request);
177
+ if (!log || !request) return;
178
+ recorded.add(request);
179
+ log.set({ auth: outcome });
180
+ }
181
+ /**
182
+ * Sets `auth` from a Better Auth response when no endpoint set it, such as a refusal of Better Auth's rate limit or
183
+ * origin check. The code comes from the JSON error body: Better Auth's `code`, else an OAuth `error` such as `invalid_grant`.
184
+ */
185
+ async function setAuthResponseOutcome(request, response) {
186
+ if (response.status < 400 || recorded.has(request) || !requestLog(request)) return;
187
+ let code;
188
+ if (response.headers.get("content-type")?.includes("json")) code = bodyCode(await response.clone().json().catch(() => void 0));
189
+ setAuthOutcome(request, {
190
+ outcome: "failure",
191
+ status: response.status,
192
+ ...code ? { code } : {}
193
+ });
194
+ }
195
+ function errorCode(value) {
196
+ return typeof value === "string" && /^[\w.-]{1,100}$/.test(value) ? value : void 0;
197
+ }
198
+ function bodyCode(body) {
199
+ if (body === null || typeof body !== "object") return void 0;
200
+ return errorCode(Reflect.get(body, "code")) ?? errorCode(Reflect.get(body, "error"));
201
+ }
202
+ const signInPath = /^\/(?:sign-in|sign-up|callback|oauth2\/callback|magic-link\/verify|passkey\/verify-authentication|siwe\/verify|two-factor\/verify-|email-otp\/verify-email)/;
203
+ function provider(ctx) {
204
+ const path = ctx.path ?? "";
205
+ const value = path.startsWith("/callback/") || path.startsWith("/oauth2/callback/") ? ctx.params?.id ?? ctx.params?.providerId : ctx.body !== null && typeof ctx.body === "object" ? Reflect.get(ctx.body, "provider") : void 0;
206
+ return typeof value === "string" && ctx.context.socialProviders.some((entry) => entry.id === value) ? value : void 0;
207
+ }
208
+ async function redirectError(ctx, headers) {
209
+ if (ctx.path !== "/callback/:id" && ctx.path !== "/oauth2/callback/:providerId") return void 0;
210
+ if (ctx.path === "/callback/:id" && ctx.method === "POST") return void 0;
211
+ const location = headers ? new Headers(headers).get("location") : null;
212
+ if (!location) return void 0;
213
+ const { baseURL, options } = ctx.context;
214
+ const state = await getOAuthState();
215
+ try {
216
+ const target = new URL(location, baseURL);
217
+ if (state && [state.callbackURL, state.newUserURL].some((url) => url && new URL(url, baseURL).href === target.href)) return void 0;
218
+ const errorPage = new URL(state?.errorURL || options.onAPIError?.errorURL || `${baseURL}/error`, baseURL);
219
+ const prefix = errorPage.search.endsWith("&") || !errorPage.search ? errorPage.search || "?" : `${errorPage.search}&`;
220
+ if (target.origin !== errorPage.origin || target.pathname !== errorPage.pathname || !target.search.startsWith(`${prefix}error=`)) return void 0;
221
+ return errorCode(new URLSearchParams(target.search.slice(prefix.length)).get("error"));
222
+ } catch {
223
+ return;
224
+ }
225
+ }
226
+ async function endpointOutcome(ctx, createdUserId) {
227
+ const path = ctx.path ?? "";
228
+ const oauthProvider = provider(ctx);
229
+ const fields = {
230
+ path,
231
+ ...oauthProvider ? { provider: oauthProvider } : {}
232
+ };
233
+ const returned = Reflect.get(ctx.context, "returned");
234
+ const redirect = isAPIError(returned) && returned.status === "FOUND";
235
+ if (isAPIError(returned) && !redirect) {
236
+ const code = bodyCode(returned.body);
237
+ return {
238
+ ...fields,
239
+ outcome: "failure",
240
+ status: returned.statusCode,
241
+ ...code ? { code } : {}
242
+ };
243
+ }
244
+ const session = ctx.context.newSession;
245
+ if (session && signInPath.test(path)) return {
246
+ ...fields,
247
+ outcome: "success",
248
+ userId: session.user.id
249
+ };
250
+ const oauthError = redirect ? await redirectError(ctx, returned.headers) : void 0;
251
+ if (oauthError) return {
252
+ ...fields,
253
+ outcome: "failure",
254
+ status: 302,
255
+ code: oauthError
256
+ };
257
+ if (createdUserId && !redirect) return {
258
+ ...fields,
259
+ outcome: "success",
260
+ userId: createdUserId
261
+ };
262
+ }
263
+ /** Sets the outcome of each Better Auth endpoint on the request's wide event. */
264
+ function createRequestLogPlugin() {
265
+ const signUps = /* @__PURE__ */ new WeakMap();
266
+ return {
267
+ id: "vitehub-request-log",
268
+ init: () => ({ options: { databaseHooks: { user: { create: { async after(user, ctx) {
269
+ const request = requestOf(ctx);
270
+ if (ctx?.path === "/sign-up/email" && request && requestLog(request)) signUps.set(request, user.id);
271
+ } } } } } }),
272
+ hooks: { after: [{
273
+ matcher: () => true,
274
+ handler: createAuthMiddleware(async (ctx) => {
275
+ const request = requestOf(ctx);
276
+ if (!requestLog(request)) return;
277
+ const outcome = await endpointOutcome(ctx, request && signUps.get(request));
278
+ if (outcome) setAuthOutcome(request, outcome);
279
+ })
280
+ }] }
281
+ };
282
+ }
283
+ function scrub(text) {
284
+ return /^(Invalid (?:origin|callbackURL|redirectURL|errorCallbackURL|newUserCallbackURL|redirect URL)):/i.exec(text)?.[1] ?? text.replace(/\bhttps?:\/\/[^\s"'`<>]+/gi, "[url]").replace(/[?#][^\s"'`<>]*/g, "").replace(/[^\s"'`<>@]+(?:@|%40)[^\s"'`<>@]+\.[a-z]{2,}/gi, "[email]").slice(0, 500);
285
+ }
286
+ /**
287
+ * Better Auth's `logger` that also writes warnings and errors to the request's wide event. The app's own `log`, or
288
+ * Better Auth's console output, still gets every message. Only the message goes on the event: the other arguments can
289
+ * hold provider responses.
290
+ */
291
+ function withRequestLogger(logger) {
292
+ let fallback;
293
+ return {
294
+ ...logger,
295
+ log(level, message, ...args) {
296
+ const log = level === "warn" || level === "error" ? authRequestLog() : void 0;
297
+ if (log) {
298
+ const text = `[Better Auth] ${scrub(message)}`;
299
+ if (level === "warn") log.warn(text);
300
+ else log.error(text);
301
+ }
302
+ if (logger?.log) logger.log(level, message, ...args);
303
+ else (fallback ??= createLogger({
304
+ ...logger,
305
+ log: void 0
306
+ }))[level](message, ...args);
307
+ }
308
+ };
309
+ }
310
+ // src/event-plugin.ts
149
311
  function record(value) {
150
312
  return value !== null && typeof value === "object" ? value : {};
151
313
  }
@@ -204,7 +366,10 @@ function createAuthEventsPlugin(options) {
204
366
  try {
205
367
  await options.store.append(event);
206
368
  } catch {
207
- console.warn("[vitehub] AUTH_EVENT_WRITE_FAILED: Could not record an auth event.");
369
+ const message = "AUTH_EVENT_WRITE_FAILED: Could not record an auth event.";
370
+ const log = authRequestLog(ctx);
371
+ if (log) log.warn(`[vitehub] ${message}`, { authEvent: { type } });
372
+ else console.warn(`[vitehub] ${message}`);
208
373
  return false;
209
374
  }
210
375
  if (options.onEvent) await notify(options.onEvent, event, ctx);
@@ -212,18 +377,20 @@ function createAuthEventsPlugin(options) {
212
377
  }
213
378
  /** Hand the callback to the host `waitUntil()` when it has one, so it does not delay the response. Else wait for it. */
214
379
  async function notify(onEvent, event, ctx) {
380
+ const request = currentAuthEvent() ?? (ctx?.request ? authRequestEvent(ctx.request) : void 0);
381
+ const waitUntil = request ? getStandardContext(request).waitUntil : void 0;
382
+ const log = waitUntil ? void 0 : authRequestLog(ctx);
215
383
  const task = (async () => {
216
384
  try {
217
385
  await onEvent(event);
218
386
  } catch (error) {
219
- console.error(authErrorDiagnostics.AUTH_EVENT_CALLBACK_FAILED({
387
+ if (log) log.error("AUTH_EVENT_CALLBACK_FAILED: Auth event callback failed.", { authEvent: { type: event.type } });
388
+ else console.error(authErrorDiagnostics.AUTH_EVENT_CALLBACK_FAILED({
220
389
  type: event.type,
221
390
  cause: error
222
391
  }));
223
392
  }
224
393
  })();
225
- const request = authHandlerEvent.getStore() ?? (ctx?.request ? authRequestEvent(ctx.request) : void 0);
226
- const waitUntil = request ? getStandardContext(request).waitUntil : void 0;
227
394
  if (waitUntil) try {
228
395
  waitUntil(task);
229
396
  return;
@@ -408,7 +575,7 @@ function createAuthEventsPlugin(options) {
408
575
  }, async (ctx) => {
409
576
  if (!ctx.request) throw new APIError$1("FORBIDDEN");
410
577
  const authorization = await options.authorize({
411
- event: authHandlerEvent.getStore() ?? authRequestEvent(ctx.request),
578
+ event: currentAuthEvent() ?? authRequestEvent(ctx.request),
412
579
  request: ctx.request,
413
580
  user: ctx.context.session.user,
414
581
  session: ctx.context.session.session
@@ -438,8 +605,7 @@ function createAuthEventsPlugin(options) {
438
605
  }) } : {}
439
606
  };
440
607
  }
441
- //#endregion
442
- //#region src/impersonation-plugin.ts
608
+ // src/impersonation-plugin.ts
443
609
  /**
444
610
  * Better Auth endpoints that create a credential which outlives an impersonation session, change how the user signs
445
611
  * in, or start another impersonation: OAuth, MCP, and device grants, API keys, passkeys, passwords, email and phone
@@ -540,8 +706,7 @@ function createImpersonationPlugin() {
540
706
  }] }
541
707
  };
542
708
  }
543
- //#endregion
544
- //#region src/client-address.ts
709
+ // src/client-address.ts
545
710
  /**
546
711
  * Better Auth reads the client IP for its rate limiter and for `session.ipAddress` only from request headers. Auth puts
547
712
  * the address that the host reports in this header and removes any value that a client sends, at every entry of the
@@ -629,8 +794,7 @@ function withClientAddress(auth) {
629
794
  fetch: addressedHandler
630
795
  });
631
796
  }
632
- //#endregion
633
- //#region src/session-refresh.ts
797
+ // src/session-refresh.ts
634
798
  /**
635
799
  * Runs `session.onRefresh` from the Better Auth `session.update.before` database hook.
636
800
  * Better Auth calls `updateSession(token, { expiresAt, updatedAt })` when a stored session
@@ -664,8 +828,7 @@ function createSessionRefreshPlugin(onRefresh) {
664
828
  } } } } } })
665
829
  };
666
830
  }
667
- //#endregion
668
- //#region src/options-key.ts
831
+ // src/options-key.ts
669
832
  const valueIds = /* @__PURE__ */ new WeakMap();
670
833
  let nextValueId = 0;
671
834
  function identityKey(value) {
@@ -713,8 +876,23 @@ function optionsKey(value) {
713
876
  const parts = [];
714
877
  return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
715
878
  }
716
- //#endregion
717
- //#region src/runtime-options.ts
879
+ // src/site-roles.ts
880
+ /**
881
+ * The `user.role` field of Better Auth's `admin()` plugin, without its endpoints. Site access keeps the roles it gives in
882
+ * this field, and Comments and the Console page tool read them from the session user. Users cannot set it.
883
+ *
884
+ * Auth adds it without `admin()` only where Auth owns the user table, `authDatabase()` and the memory database, because
885
+ * Better Auth refuses every request when a declared field has no column.
886
+ */
887
+ const siteRolesPlugin = {
888
+ id: "vitehub-site-roles",
889
+ schema: { user: { fields: { role: {
890
+ type: "string",
891
+ required: false,
892
+ input: false
893
+ } } } }
894
+ };
895
+ // src/runtime-options.ts
718
896
  /** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
719
897
  function isAuthDatabasePlacement(value) {
720
898
  return typeof value === "boolean" || isRecord(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key === "dedicated" || key === "name");
@@ -764,17 +942,16 @@ function withRateLimitDefaults(options, ownsDatabase) {
764
942
  }
765
943
  /**
766
944
  * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
767
- * send. Auth gives it the address that the host reports instead. With `trustedProxyHeaders`, the proxy address is the
768
- * peer, so `X-Forwarded-For` comes first.
945
+ * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
946
+ * `vitehub({ trustProxy: true })` makes that address the last `X-Forwarded-For` value, which the proxy adds.
769
947
  */
770
948
  function withClientAddressHeaders(advanced) {
771
949
  if (advanced?.ipAddress?.ipAddressHeaders) return advanced;
772
- const ipAddressHeaders = advanced?.trustedProxyHeaders ? ["x-forwarded-for", clientAddressHeader] : [clientAddressHeader];
773
950
  return {
774
951
  ...advanced,
775
952
  ipAddress: {
776
953
  ...advanced?.ipAddress,
777
- ipAddressHeaders
954
+ ipAddressHeaders: [clientAddressHeader]
778
955
  }
779
956
  };
780
957
  }
@@ -803,7 +980,7 @@ function readProviderEnvironment(options, event) {
803
980
  }
804
981
  function stripViteHubOptions(definition, options, environment) {
805
982
  validateDeleteAccount(options);
806
- const { access, adminClaim: _adminClaim, console: _console, database, deleteAccount, events, route: _route, secondaryStorage, ...rest } = applyAuthPreset(options);
983
+ const { access, adminClaim: _adminClaim, components, console: _console, database, deleteAccount, events, route: _route, secondaryStorage, ...rest } = applyAuthPreset(options);
807
984
  if (isAuthDatabasePlacement(database)) throw authErrorDiagnostics.AUTH_C0061({ message: "Auth `database` must be a Better Auth adapter, such as `authDatabase()`. `true` and `{ name }` do not create storage, so users and sessions would stay in memory." });
808
985
  if (isAuthSecondaryStoragePlacement(secondaryStorage)) throw authErrorDiagnostics.AUTH_C0062({ message: "Auth `secondaryStorage` must be a Better Auth adapter. `true` and `{ store }` do not create storage." });
809
986
  const memory = database === "memory";
@@ -816,6 +993,7 @@ function stripViteHubOptions(definition, options, environment) {
816
993
  assertAuthDatabaseNames(rest);
817
994
  }
818
995
  validateAuthEvents(events);
996
+ validateAuthComponents(components);
819
997
  const sessionRefresh = withSessionRefresh(rest, Boolean(storage.database || storage.secondaryStorage));
820
998
  if (!storage.database && options.preset === void 0) {
821
999
  if (!memory && !isDevelopmentServer()) throw authMemoryDatabaseError();
@@ -826,6 +1004,7 @@ function stripViteHubOptions(definition, options, environment) {
826
1004
  if (policy && !storage.database && !storage.secondaryStorage) throw authErrorDiagnostics.AUTH_C0066({ message: "`defineAuth()` access.policy needs a Better Auth `database` or `secondaryStorage` adapter. A session that lives only in a cookie cannot be ended." });
827
1005
  const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
828
1006
  const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
1007
+ const siteRoles = !impersonation && !Object.hasOwn(rest.user?.additionalFields ?? {}, "role") && !declaredPlugins.some((plugin) => Object.hasOwn(plugin.schema?.user?.fields ?? {}, "role")) && (authDatabaseName(database) !== void 0 || isAuthProcessMemoryDatabase(storage.database));
829
1008
  const { admins, adminClaim, members } = environment;
830
1009
  assertMembersSessionStore(members, Boolean(storage.database || storage.secondaryStorage));
831
1010
  const membersGate = members.length ? createMembersGate(members, admins, declaredPlugins) : void 0;
@@ -836,6 +1015,7 @@ function stripViteHubOptions(definition, options, environment) {
836
1015
  ...declaredPlugins,
837
1016
  ...accountDeletion ? [accountDeletion.plugin] : [],
838
1017
  ...impersonation ? [createImpersonationPlugin()] : [],
1018
+ ...siteRoles ? [siteRolesPlugin] : [],
839
1019
  ...adminsPlugin ? [adminsPlugin] : [],
840
1020
  ...adminClaimPlugin ? [adminClaimPlugin] : [],
841
1021
  ...policy || membersGate ? [createAccessPolicyPlugin({
@@ -865,7 +1045,12 @@ function stripViteHubOptions(definition, options, environment) {
865
1045
  storeInDatabase: true
866
1046
  } } : {},
867
1047
  ...databaseHooks ? { databaseHooks } : {},
868
- plugins: eventPlugin ? [...plugins, eventPlugin] : plugins,
1048
+ plugins: [
1049
+ ...plugins,
1050
+ ...eventPlugin ? [eventPlugin] : [],
1051
+ createRequestLogPlugin()
1052
+ ],
1053
+ logger: withRequestLogger(rest.logger),
869
1054
  advanced: withClientAddressHeaders(rest.advanced),
870
1055
  rateLimit,
871
1056
  ...eventPlugin ? { hooks: {
@@ -982,8 +1167,7 @@ function resolveAuthOptions(definition, input = {}) {
982
1167
  requestRuntimeOptions
983
1168
  };
984
1169
  }
985
- //#endregion
986
- //#region src/session-marker.ts
1170
+ // src/session-marker.ts
987
1171
  /**
988
1172
  * Name of the cookie that tells browser code a session exists. It holds `1`, never a secret, and it is not HttpOnly,
989
1173
  * so a page script can skip a session request for a visitor who never signed in. It does not prove a session:
@@ -1095,8 +1279,7 @@ function withSessionMarker(auth) {
1095
1279
  fetch: markedHandler
1096
1280
  });
1097
1281
  }
1098
- //#endregion
1099
- //#region src/auth-instance.ts
1282
+ // src/auth-instance.ts
1100
1283
  function hasRequestRuntimeOptions(definition) {
1101
1284
  return typeof definition.options === "function" || trustsProxyHeaders(definition.options);
1102
1285
  }
@@ -1110,6 +1293,13 @@ function resolveDefaultDefinition() {
1110
1293
  if (!definitionForApp) throw authErrorDiagnostics.AUTH_R0005({ message: "[vitehub] No Auth Definition was discovered. Add `server/auth.ts` or `server.auth.ts`." });
1111
1294
  return definitionForApp;
1112
1295
  }
1296
+ async function findVerifiedAuthUserId(email, request) {
1297
+ if (!definitionForApp) return void 0;
1298
+ const context = await authForRequest(request, authRequestEvent(request), definitionForApp).$context;
1299
+ if (!context.options.database) return void 0;
1300
+ const found = await context.internalAdapter.findUserByEmail(email);
1301
+ return found?.user.emailVerified === true && found.user.email.trim().toLowerCase() === email ? found.user.id : void 0;
1302
+ }
1113
1303
  function createBetterAuthOptions(definition) {
1114
1304
  return resolveAuthOptions(definition, { env: envResolverFor(definition) }).providerOptions;
1115
1305
  }
@@ -1171,5 +1361,4 @@ function authForRequest(request, event, definition = resolveDefaultDefinition())
1171
1361
  env: envResolverFor(definition)
1172
1362
  }));
1173
1363
  }
1174
- //#endregion
1175
- export { requestProvider as a, resolveAuthOptions as c, setRequestClientAddress as d, withClientAddress as f, getAuthForDefinition as i, trustsProxyHeaders as l, forwardedRequestOrigin as m, createBetterAuthOptions as n, resolveDefaultDefinition as o, runWithAuthEvent as p, envResolverFor as r, withSessionMarker as s, authForRequest as t, eventClientAddress as u };
1364
+ export { forwardedRequestOrigin as _, getAuthForDefinition as a, withSessionMarker as c, eventClientAddress as d, setRequestClientAddress as f, setAuthResponseOutcome as g, setAuthOutcome as h, findVerifiedAuthUserId as i, resolveAuthOptions as l, runWithAuthEvent as m, createBetterAuthOptions as n, requestProvider as o, withClientAddress as p, envResolverFor as r, resolveDefaultDefinition as s, authForRequest as t, trustsProxyHeaders as u };
@@ -1,8 +1,8 @@
1
1
  import "nostics";
2
- //#region ../internal/src/host-credentials.d.ts
3
2
  interface HostCliRunResult {
4
3
  exitCode: number | null;
5
4
  stdout: string;
5
+ stderr?: string;
6
6
  }
7
7
  /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
8
  type HostCliRun = (command: string, args: readonly string[], options: {
@@ -10,8 +10,6 @@ type HostCliRun = (command: string, args: readonly string[], options: {
10
10
  env: NodeJS.ProcessEnv;
11
11
  signal?: AbortSignal;
12
12
  }) => Promise<HostCliRunResult>;
13
- //#endregion
14
- //#region ../internal/src/provision.d.ts
15
13
  type ProvisionProvider = "cloudflare" | "vercel";
16
14
  interface ProvisionLogger {
17
15
  log: (message: string) => void;
@@ -63,8 +61,6 @@ interface ProvisionStep {
63
61
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
64
62
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
65
63
  }
66
- //#endregion
67
- //#region ../internal/src/cli.d.ts
68
64
  interface ViteHubCliStreams {
69
65
  stderr: {
70
66
  write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
@@ -159,5 +155,4 @@ interface ViteHubCliPluginMetadata {
159
155
  cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
160
156
  }
161
157
  type StdoutWriteCallback = (error?: Error | null) => void;
162
- //#endregion
163
158
  export { ViteHubCliPluginMetadata as n, ViteHubCliContributor as t };
package/dist/cli.d.ts CHANGED
@@ -1,7 +1,5 @@
1
- import { t as ViteHubCliContributor } from "./cli-ubYJpAL_.js";
2
- //#region src/cli.d.ts
1
+ import { t as ViteHubCliContributor } from "./cli-C5pAfY4x.js";
3
2
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
4
3
  export declare function createAuthCliContributor(options?: {
5
4
  fetch?: typeof fetch;
6
- }): ViteHubCliContributor;
7
- //#endregion
5
+ }): ViteHubCliContributor;
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-CDipqeAU.js";
3
- //#region src/cli.ts
1
+ import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
3
+ // src/cli.ts
4
4
  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]";
5
5
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
6
6
  function createAuthCliContributor(options = {}) {
@@ -104,5 +104,4 @@ function createAuthCliContributor(options = {}) {
104
104
  }]
105
105
  }] };
106
106
  }
107
- //#endregion
108
107
  export { createAuthCliContributor };
@@ -1,7 +1,6 @@
1
- import { G as AuthConsoleActivity, K as AuthConsoleActivityQuery, Nt as AuthEventStore, X as AuthConsoleDescription, _t as AuthConsoleSession, at as AuthConsoleHostUserInput, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleField, ft as AuthConsoleOverview, ht as AuthConsoleQuery, it as AuthConsoleHostSession, lt as AuthConsoleOptions, q as AuthConsoleAgent, rt as AuthConsoleHostOptions, st as AuthConsoleList, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, yt as AuthConsoleUser } from "./types-CruflEFI.js";
1
+ import { J as AuthConsoleAgent, K as AuthConsoleActivity, Lt as AuthEventStore, Z as AuthConsoleDescription, at as AuthConsoleHostSession, bt as AuthConsoleUser, ct as AuthConsoleList, dt as AuthConsoleOrganization, ft as AuthConsoleOrganizationDetail, gt as AuthConsoleQuery, it as AuthConsoleHostOptions, lt as AuthConsoleMutation, ot as AuthConsoleHostUserInput, pt as AuthConsoleOverview, q as AuthConsoleActivityQuery, tt as AuthConsoleField, ut as AuthConsoleOptions, vt as AuthConsoleSession, xt as AuthConsoleUserDetail, yt as AuthConsoleSessionUser } from "./types-BHSgxyvV.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
4
- //#region src/console-runtime.d.ts
5
4
  interface AuthConsole {
6
5
  describe(request?: Request): Promise<Result<AuthConsoleDescription, AuthConsoleErrorCode>>;
7
6
  overview(): Promise<Result<AuthConsoleOverview, AuthConsoleErrorCode>>;
@@ -35,26 +34,28 @@ interface AuthConsole {
35
34
  deleteVerification(identifier: string): Promise<Result<void, AuthConsoleErrorCode>>;
36
35
  /**
37
36
  * The user that a host signs in without a password, such as a Console member or a guest that a member invited, with
38
- * `roles` added to the comma-separated `user.role` of Better Auth's `admin()` plugin. With `email`, an existing user
39
- * with that verified email keeps their account and gets the roles, and an unverified one is refused; without it, a new
40
- * user gets a placeholder email. Needs `admin()` and a
41
- * database. Better Auth runs the app's `databaseHooks.user.create` for a new user.
37
+ * `roles` added to the comma-separated `user.role`. With `email`, an existing user with that verified email keeps
38
+ * their account and gets the roles, and an unverified one is refused; without it, a new user gets a placeholder email.
39
+ * Needs a database and a `user.role` field that users cannot set: `authDatabase()` and `admin()` add one. Better Auth
40
+ * runs the app's `databaseHooks.user.create` for a new user.
42
41
  */
43
42
  hostUser(input: AuthConsoleHostUserInput): Promise<Result<{
44
43
  id: string;
45
44
  roles: string[];
46
45
  }, AuthConsoleErrorCode>>;
46
+ /**
47
+ * Check the Auth configuration without writing: a database and a `user.role` field that users cannot set and that
48
+ * sessions return. `hostUser()` and `hostSession()` still check the account and session when the link is redeemed.
49
+ */
50
+ checkHost(): Promise<Result<void, AuthConsoleErrorCode>>;
47
51
  /** Start a Better Auth session for a user, and return the `Set-Cookie` headers that sign the browser in. */
48
52
  hostSession(userId: string, request: Request): Promise<Result<Headers, AuthConsoleErrorCode>>;
49
- /** The live sessions of the users that hold one of `roles`, newest first. */
53
+ /** Live sessions matching `roles`, newest first. `guest` matches only users created as guests by the host. */
50
54
  hostSessions(roles: readonly string[]): Promise<Result<AuthConsoleHostSession[], AuthConsoleErrorCode>>;
51
- /** End one session. Answers its user, or a 404 for a session that is gone. */
55
+ /** End one session and delete its user only if the host created it as a guest. */
52
56
  revokeHostSession(id: string): Promise<Result<{
53
- userId: string;
54
- roles: string[];
57
+ removedUser: boolean;
55
58
  }, AuthConsoleErrorCode>>;
56
- /** Delete a user with their sessions and accounts. */
57
- removeHostUser(userId: string): Promise<Result<void, AuthConsoleErrorCode>>;
58
59
  }
59
60
  type ConsoleAdapter = Pick<DBAdapter, "findMany" | "findOne" | "count">;
60
61
  type AuthConsoleErrorCode = "AUTH_CONSOLE_INVALID_REQUEST" | "AUTH_CONSOLE_FORBIDDEN" | "AUTH_CONSOLE_NOT_FOUND" | "AUTH_CONSOLE_UNAVAILABLE" | "AUTH_CONSOLE_PROVIDER_FAILED";
@@ -67,5 +68,4 @@ declare function createAuthConsole(auth: {
67
68
  options: BetterAuthOptions;
68
69
  } & Partial<Pick<AuthContext, "authCookies" | "internalAdapter" | "secret" | "sessionConfig">>>;
69
70
  }, policy?: AuthConsoleOptions, events?: AuthEventStore, host?: AuthConsoleHostOptions): AuthConsole;
70
- //#endregion
71
71
  export { describeAuthConsoleFields as i, AuthConsoleErrorCode as n, createAuthConsole as r, AuthConsole as t };