@vite-hub/auth 0.5.1 → 0.6.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 (72) hide show
  1. package/README.md +2 -2
  2. package/dist/{abilities-3L1Y5Pnw.d.ts → abilities-BYOcyQ9B.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-BHhPkrZd.js → ability-error-D3-u8k1A.js} +1 -1
  5. package/dist/{access-pages-BwImVHN_.js → access-pages-9aKr6z-k.js} +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{auth-instance-_J7R9Qs1.js → auth-instance-BWiRS9QZ.js} +73 -82
  8. package/dist/cli.js +1 -1
  9. package/dist/client-request-BzMKtfCY.js +52 -0
  10. package/dist/{console-runtime-vc3JQEuq.js → console-runtime-CaIXVtB_.js} +7 -206
  11. package/dist/console-runtime-DMH1I2fl.d.ts +32 -0
  12. package/dist/console-runtime.d.ts +3 -3
  13. package/dist/console-runtime.js +1 -1
  14. package/dist/{console-types-51lkf0lk.js → console-types-NrX5TWl3.js} +2 -1
  15. package/dist/console.d.ts +3 -3
  16. package/dist/console.js +1 -1
  17. package/dist/{database-options-DQ-8qYMl.js → database-options-B87hDU4j.js} +1 -1
  18. package/dist/{database-schema-options-CkSeU9V3.js → database-schema-options-peXHNLkJ.js} +1 -1
  19. package/dist/database.d.ts +2 -2
  20. package/dist/database.js +5 -5
  21. package/dist/{definition-MDGMNKrK.js → definition-BypPLIbI.js} +3 -3
  22. package/dist/{error-diagnostics-BssJr_2t.js → error-diagnostics-CUPwukgE.js} +1 -1
  23. package/dist/{events-DZqMiae_.js → events-BXU1_9mc.js} +2 -1
  24. package/dist/forward-sign-ins-BWXPPTRz.js +4 -0
  25. package/dist/forward.d.ts +24 -0
  26. package/dist/forward.js +42 -4
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +3 -3
  29. package/dist/internal/server.d.ts +2 -2
  30. package/dist/internal/server.js +4 -4
  31. package/dist/mcp-token-CmQbXbTu.d.ts +125 -0
  32. package/dist/{mcp-token--KuLYEub.js → mcp-token-CuqdbBy8.js} +45 -18
  33. package/dist/mcp.d.ts +2 -111
  34. package/dist/mcp.js +5 -3
  35. package/dist/{members-D3_Q5XJb.js → members-CwPIx10t.js} +3 -3
  36. package/dist/{nitro-kit-Bg4xUZAI.js → nitro-kit-BumWIKa5.js} +1 -1
  37. package/dist/nuxt.d.ts +1 -1
  38. package/dist/nuxt.js +3 -3
  39. package/dist/{own-access-C22hSIuF.d.ts → own-access-BNcxKrDl.d.ts} +1 -1
  40. package/dist/{own-access-DQgqxTbI.js → own-access-CYsakJiH.js} +1 -1
  41. package/dist/presets.js +1 -1
  42. package/dist/runtime/client-request-plugin.d.ts +1 -0
  43. package/dist/runtime/client-request-plugin.js +18 -0
  44. package/dist/runtime/console.d.ts +1 -1
  45. package/dist/runtime/console.js +2 -2
  46. package/dist/runtime/empty-abilities.d.ts +1 -1
  47. package/dist/runtime/empty-definition.d.ts +1 -1
  48. package/dist/runtime/server.d.ts +2 -2
  49. package/dist/runtime/server.js +3 -3
  50. package/dist/runtime-state-C0Rd1W4m.js +15 -0
  51. package/dist/schema.d.ts +1 -1
  52. package/dist/schema.js +1 -1
  53. package/dist/{server-DCsgxFPP.d.ts → server-BHniJi2m.d.ts} +2 -2
  54. package/dist/{server-CFWlYQJb.d.ts → server-C4Kni3Vj.d.ts} +13 -8
  55. package/dist/{server-D4Hi4TBI.js → server-Iru6jcnW.js} +13 -12
  56. package/dist/server.d.ts +3 -2
  57. package/dist/server.js +2 -2
  58. package/dist/{session-cookies-1FMcMnRh.js → session-cookies-fR6Pv4kD.js} +2 -2
  59. package/dist/{set-cookie-DkqM1kvj.js → set-cookie-DVfi-nJX.js} +1 -1
  60. package/dist/{table-specs-jw0jjU6l.js → table-specs-CCSY4tiS.js} +17 -14
  61. package/dist/{table-specs-BLm_Zlss.d.ts → table-specs-P4LvbOlX.d.ts} +28 -21
  62. package/dist/test.d.ts +1 -1
  63. package/dist/test.js +2 -2
  64. package/dist/{types-BHSgxyvV.d.ts → types-DmH31d2t.d.ts} +8 -21
  65. package/dist/{vite-D1xC9n1O.js → vite-CpWhT1Wi.js} +93 -27
  66. package/dist/vite.d.ts +1 -1
  67. package/dist/vite.js +1 -1
  68. package/dist/vue.d.ts +2 -2
  69. package/dist/vue.js +1 -1
  70. package/package.json +8 -8
  71. package/dist/console-runtime-BP1ZKJB0.d.ts +0 -71
  72. package/dist/runtime-state-DtKUfxKq.js +0 -24
package/README.md CHANGED
@@ -72,9 +72,9 @@ export default defineAuth({
72
72
  });
73
73
  ```
74
74
 
75
- `authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
75
+ `authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields when the Definition calls `admin()`, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
76
76
 
77
- The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
77
+ The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
78
78
 
79
79
  Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. Use `authSqliteSchema` and `authPostgresSchema` for foreign keys to core tables such as `user` and `organization`.
80
80
 
@@ -1,4 +1,4 @@
1
- import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BHSgxyvV.js";
1
+ import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-DmH31d2t.js";
2
2
  /** A 4xx status that a rule can refuse with. `403` is the default. */
3
3
  type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
4
4
  declare const abilityDenial: unique symbol;
@@ -1,2 +1,2 @@
1
- import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-3L1Y5Pnw.js";
1
+ import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-BYOcyQ9B.js";
2
2
  export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
2
  import { HTTPError } from "nitro/h3";
3
3
  // src/ability-check.ts
4
4
  const signedOut = Object.freeze({
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
2
2
  // src/shared.ts
3
3
  const defaultAuthBasePath = "/api/auth";
4
4
  function normalizeAuthBasePath(value) {
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DkqM1kvj.js";
2
- import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-1FMcMnRh.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
1
+ import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DVfi-nJX.js";
2
+ import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-fR6Pv4kD.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
4
4
  import { t as isRecord } from "./object-CAK6UYR5.js";
5
5
  import { ViteHubError } from "@vite-hub/runtime";
6
6
  // src/agent.ts
@@ -1,15 +1,17 @@
1
+ import { i as forwardedRequestOrigin, t as clientRequest } from "./client-request-BzMKtfCY.js";
1
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
3
  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";
4
+ 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-CwPIx10t.js";
5
+ import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
6
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-peXHNLkJ.js";
7
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
8
+ import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-BypPLIbI.js";
8
9
  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";
10
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BXU1_9mc.js";
11
+ import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
12
+ import { n as resetAuth, t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
13
+ import { a as normalizeAuthBasePath } from "./access-pages-9aKr6z-k.js";
14
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DVfi-nJX.js";
13
15
  import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-CtoKaNQZ.js";
14
16
  import { resolvePublicUrl } from "@vite-hub/runtime";
15
17
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
@@ -23,27 +25,6 @@ import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
23
25
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
24
26
  import { isWebContainer } from "@vite-hub/web-container/env";
25
27
  import { hkdfSync } from "node:crypto";
26
- // ../internal/src/runtime/request-origin.ts
27
- function firstHeaderValue(headers, name) {
28
- return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
29
- }
30
- /**
31
- * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
32
- * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
33
- * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
34
- */
35
- function forwardedRequestOrigin(request) {
36
- const url = new URL(request.url);
37
- const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
38
- const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
39
- const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
40
- if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
41
- try {
42
- return new URL(`${protocol}://${host}`).origin;
43
- } catch {
44
- return url.origin;
45
- }
46
- }
47
28
  // src/password.ts
48
29
  const scryptOptions = {
49
30
  N: 16384,
@@ -315,6 +296,7 @@ function identifier(value) {
315
296
  return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : void 0;
316
297
  }
317
298
  function actor(ctx, fallback) {
299
+ if (fallback === null) return "system";
318
300
  const session = ctx?.context.session;
319
301
  const id = identifier(session?.session.impersonatedBy) ?? session?.user.id ?? fallback;
320
302
  return id ? `user:${id}` : "system";
@@ -354,6 +336,9 @@ function createAuthEventsPlugin(options) {
354
336
  const wrappedAdapters = /* @__PURE__ */ new WeakSet();
355
337
  const createdSessions = /* @__PURE__ */ new WeakSet();
356
338
  const recordedSessions = /* @__PURE__ */ new WeakSet();
339
+ const forwardSessions = /* @__PURE__ */ new WeakSet();
340
+ const forwardedByRequest = /* @__PURE__ */ new WeakMap();
341
+ const expiredLookups = /* @__PURE__ */ new WeakMap();
357
342
  async function append(type, userId, ctx, metadata = {}, fallback) {
358
343
  const event = {
359
344
  id: crypto.randomUUID(),
@@ -398,8 +383,11 @@ function createAuthEventsPlugin(options) {
398
383
  await task;
399
384
  }
400
385
  async function deleted(session, ctx) {
401
- const type = ctx?.path === "/sign-out" ? "user.signed_out" : ctx?.path === "/admin/stop-impersonating" ? "impersonation.stopped" : "session.revoked";
402
- await append(type, session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy) ?? (type === "user.signed_out" ? session.userId : void 0));
386
+ if (ctx && forwardedByRequest.get(ctx.context)?.id === session.id) forwardedByRequest.delete(ctx.context);
387
+ const expired = typeof session.token === "string" && ctx?.context !== void 0 && expiredLookups.get(ctx.context)?.has(session.token) === true;
388
+ const type = ctx?.path === "/sign-out" ? "user.signed_out" : ctx?.path === "/admin/stop-impersonating" ? "impersonation.stopped" : expired ? "session.expired" : "session.revoked";
389
+ const fallback = type === "session.expired" ? null : identifier(session.impersonatedBy) ?? (type === "user.signed_out" ? session.userId : void 0);
390
+ await append(type, session.userId, ctx, { sessionId: session.id }, fallback);
403
391
  }
404
392
  return {
405
393
  id: "vitehub-auth-events",
@@ -424,6 +412,7 @@ function createAuthEventsPlugin(options) {
424
412
  if (id && userId && session.token === key) await deleted({
425
413
  id,
426
414
  userId,
415
+ token: key,
427
416
  impersonatedBy: session.impersonatedBy
428
417
  }, deletionContext.getStore() ?? null);
429
418
  }
@@ -436,7 +425,7 @@ function createAuthEventsPlugin(options) {
436
425
  init: () => ({ options: { databaseHooks: {
437
426
  user: {
438
427
  create: { async after(user, ctx) {
439
- await append("user.signed_up", user.id, ctx, { method: method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
428
+ await append("user.signed_up", user.id, ctx, { method: forwardSignIns.getStore() ? "forward" : method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
440
429
  } },
441
430
  update: { async after(user, ctx) {
442
431
  const path = ctx?.path;
@@ -458,6 +447,10 @@ function createAuthEventsPlugin(options) {
458
447
  session: {
459
448
  create: { async after(session, ctx) {
460
449
  createdSessions.add(session);
450
+ if (forwardSignIns.getStore()) {
451
+ forwardSessions.add(session);
452
+ if (ctx) forwardedByRequest.set(ctx.context, session);
453
+ }
461
454
  if (session.impersonatedBy || ctx?.path === "/admin/impersonate-user") {
462
455
  if (await append("impersonation.started", session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy))) return;
463
456
  await ctx?.context.internalAdapter.deleteSession(session.token);
@@ -465,11 +458,14 @@ function createAuthEventsPlugin(options) {
465
458
  code: "IMPERSONATION_NOT_RECORDED",
466
459
  message: "Impersonation did not start because the auth event log could not record it."
467
460
  });
468
- } else if (!ctx) await append("user.signed_in", session.userId, ctx, {
469
- method: method(ctx),
470
- device: "unknown",
471
- sessionId: session.id
472
- });
461
+ } else if (!ctx) {
462
+ recordedSessions.add(session);
463
+ await append("user.signed_in", session.userId, ctx, {
464
+ method: forwardSessions.has(session) ? "forward" : method(ctx),
465
+ device: "unknown",
466
+ sessionId: session.id
467
+ });
468
+ }
473
469
  } },
474
470
  delete: { async after(session, ctx) {
475
471
  await deleted(session, ctx);
@@ -480,19 +476,30 @@ function createAuthEventsPlugin(options) {
480
476
  before: [{
481
477
  matcher: () => true,
482
478
  handler: createAuthMiddleware(async (ctx) => {
483
- if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
484
- const cookie = ctx.context.createAuthCookie("two_factor");
485
- const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
486
- if (token && await ctx.context.internalAdapter.findVerificationValue(token)) challenges.add(ctx.context);
487
- }
488
- if (!ctx.context.options.secondaryStorage || ctx.context.options.session?.storeSessionInDatabase) return;
489
479
  const adapter = ctx.context.internalAdapter;
480
+ const findSession = async (...args) => {
481
+ const found = await adapter.findSession(...args);
482
+ if (found && new Date(found.session.expiresAt).getTime() <= Date.now() && await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret) === found.session.token) {
483
+ const tokens = expiredLookups.get(ctx.context) ?? /* @__PURE__ */ new Set();
484
+ expiredLookups.set(ctx.context, tokens.add(found.session.token));
485
+ }
486
+ return found;
487
+ };
488
+ const storageOnly = ctx.context.options.secondaryStorage && !ctx.context.options.session?.storeSessionInDatabase;
490
489
  ctx.context.internalAdapter = {
491
490
  ...adapter,
492
- deleteSession: (token) => deletionContext.run(ctx, () => adapter.deleteSession(token)),
493
- deleteSessions: (tokens) => deletionContext.run(ctx, () => adapter.deleteSessions(tokens)),
494
- deleteUserSessions: (userId) => deletionContext.run(ctx, () => adapter.deleteUserSessions(userId))
491
+ findSession,
492
+ ...storageOnly ? {
493
+ deleteSession: (token) => deletionContext.run(ctx, () => adapter.deleteSession(token)),
494
+ deleteSessions: (tokens) => deletionContext.run(ctx, () => adapter.deleteSessions(tokens)),
495
+ deleteUserSessions: (userId) => deletionContext.run(ctx, () => adapter.deleteUserSessions(userId))
496
+ } : {}
495
497
  };
498
+ if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
499
+ const cookie = ctx.context.createAuthCookie("two_factor");
500
+ const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
501
+ if (token && await adapter.findVerificationValue(token)) challenges.add(ctx.context);
502
+ }
496
503
  })
497
504
  }, {
498
505
  matcher: (ctx) => Boolean(ctx.path?.startsWith("/oauth2/")),
@@ -533,16 +540,18 @@ function createAuthEventsPlugin(options) {
533
540
  const path = ctx.path ?? "";
534
541
  const outcome = outcomes.get(ctx.context);
535
542
  const value = record(outcome);
536
- const signedIn = ctx.context.newSession;
537
- if (signedIn && createdSessions.has(signedIn.session) && !signedIn.session.impersonatedBy && path !== "/admin/impersonate-user" && !recordedSessions.has(signedIn.session)) {
538
- recordedSessions.add(signedIn.session);
539
- await append("user.signed_in", signedIn.user.id, ctx, {
540
- method: method(ctx),
543
+ const signedIn = ctx.context.newSession?.session;
544
+ const forwarded = forwardedByRequest.get(ctx.context);
545
+ for (const session of [forwarded, signedIn]) {
546
+ if (!session || !createdSessions.has(session) || session.impersonatedBy || path === "/admin/impersonate-user" || recordedSessions.has(session)) continue;
547
+ recordedSessions.add(session);
548
+ await append("user.signed_in", session.userId, ctx, {
549
+ method: forwardSessions.has(session) ? "forward" : method(ctx),
541
550
  device: authEventDevice(ctx.headers?.get("user-agent") ?? ctx.request?.headers.get("user-agent")),
542
- sessionId: signedIn.session.id
543
- }, signedIn.user.id);
551
+ sessionId: session.id
552
+ }, session.userId);
544
553
  }
545
- if (!signedIn && outcome instanceof APIError$1 && (path.startsWith("/sign-in/") || path === "/magic-link/verify" || path === "/passkey/verify-authentication" || path === "/siwe/verify" || challenges.has(ctx.context))) await append("sign_in.failed", null, ctx, { method: method(ctx) });
554
+ if ((!signedIn || forwardSessions.has(signedIn)) && outcome instanceof APIError$1 && (path.startsWith("/sign-in/") || path === "/magic-link/verify" || path === "/passkey/verify-authentication" || path === "/siwe/verify" || challenges.has(ctx.context))) await append("sign_in.failed", null, ctx, { method: method(ctx) });
546
555
  if (outcome instanceof APIError$1) return;
547
556
  if (path === "/admin/set-user-password") {
548
557
  const userId = identifier(record(ctx.body).userId);
@@ -876,22 +885,6 @@ function optionsKey(value) {
876
885
  const parts = [];
877
886
  return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
878
887
  }
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
888
  // src/runtime-options.ts
896
889
  /** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
897
890
  function isAuthDatabasePlacement(value) {
@@ -910,11 +903,10 @@ function sharedMemoryDatabase(definition) {
910
903
  const databases = getViteHubTestMode()?.backend("auth", () => /* @__PURE__ */ new WeakMap(), resetAuth) ?? (state.memoryDatabases ??= /* @__PURE__ */ new WeakMap());
911
904
  const tables = databases.get(definition) ?? {};
912
905
  databases.set(definition, tables);
913
- const database = (options) => {
906
+ return (options) => {
914
907
  for (const { modelName } of Object.values(getAuthTables(options))) tables[modelName] ??= [];
915
908
  return memoryAdapter(tables)(options);
916
909
  };
917
- return Object.assign(database, { [authProcessMemoryDatabase]: true });
918
910
  }
919
911
  /**
920
912
  * True on a development server. The Auth Vite plugin sets `__VITEHUB_AUTH_DEV__` in the server bundle: `true` for
@@ -1004,7 +996,6 @@ function stripViteHubOptions(definition, options, environment) {
1004
996
  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." });
1005
997
  const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
1006
998
  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));
1008
999
  const { admins, adminClaim, members } = environment;
1009
1000
  assertMembersSessionStore(members, Boolean(storage.database || storage.secondaryStorage));
1010
1001
  const membersGate = members.length ? createMembersGate(members, admins, declaredPlugins) : void 0;
@@ -1015,7 +1006,6 @@ function stripViteHubOptions(definition, options, environment) {
1015
1006
  ...declaredPlugins,
1016
1007
  ...accountDeletion ? [accountDeletion.plugin] : [],
1017
1008
  ...impersonation ? [createImpersonationPlugin()] : [],
1018
- ...siteRoles ? [siteRolesPlugin] : [],
1019
1009
  ...adminsPlugin ? [adminsPlugin] : [],
1020
1010
  ...adminClaimPlugin ? [adminClaimPlugin] : [],
1021
1011
  ...policy || membersGate ? [createAccessPolicyPlugin({
@@ -1094,8 +1084,9 @@ function resolveAuthOptions(definition, input = {}) {
1094
1084
  const callback = typeof definition.options === "function";
1095
1085
  const usesContext = !request || callback;
1096
1086
  const env = usesContext ? input.env?.(input.event) ?? {} : {};
1097
- const requestUrlOrigin = request ? new URL(request.url).origin : void 0;
1098
- const proxiedOrigin = request ? forwardedRequestOrigin(request) : void 0;
1087
+ const client = request && clientRequest(request);
1088
+ const clientUrlOrigin = client ? new URL(client.url).origin : void 0;
1089
+ const proxiedOrigin = client ? forwardedRequestOrigin(client) : void 0;
1099
1090
  const resolveAt = (origin) => {
1100
1091
  const context = {
1101
1092
  env,
@@ -1109,8 +1100,8 @@ function resolveAuthOptions(definition, input = {}) {
1109
1100
  trusted: trustsProxyHeaders(declared)
1110
1101
  };
1111
1102
  };
1112
- let resolved = resolveAt(requestUrlOrigin);
1113
- if (request && callback && resolved.trusted && proxiedOrigin !== requestUrlOrigin) {
1103
+ let resolved = resolveAt(clientUrlOrigin);
1104
+ if (request && callback && resolved.trusted && proxiedOrigin !== clientUrlOrigin) {
1114
1105
  const forwarded = resolveAt(proxiedOrigin);
1115
1106
  resolved = forwarded.trusted ? forwarded : {
1116
1107
  trusted: false,
@@ -1125,8 +1116,8 @@ function resolveAuthOptions(definition, input = {}) {
1125
1116
  }
1126
1117
  const { declared, trusted } = resolved;
1127
1118
  let requestRuntimeOptions = callback ? declared : {};
1128
- if (request) {
1129
- const requestOrigin = trusted && proxiedOrigin ? proxiedOrigin : request.url;
1119
+ if (client) {
1120
+ const requestOrigin = trusted && proxiedOrigin ? proxiedOrigin : client.url;
1130
1121
  const baseURL = requestRuntimeOptions.baseURL || resolvePublicUrl({ request: { url: requestOrigin } });
1131
1122
  if (!baseURL) throw authErrorDiagnostics.AUTH_R0022({ message: `[vitehub] The request host ${new URL(requestOrigin).host} is not an origin of vitehub({ publicUrl }), so Auth has no base URL.` });
1132
1123
  requestRuntimeOptions = {
@@ -1361,4 +1352,4 @@ function authForRequest(request, event, definition = resolveDefaultDefinition())
1361
1352
  env: envResolverFor(definition)
1362
1353
  }));
1363
1354
  }
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 };
1355
+ export { 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 };
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
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";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
3
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. */
@@ -0,0 +1,52 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // ../internal/src/runtime/request-origin.ts
3
+ function firstHeaderValue(headers, name) {
4
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
5
+ }
6
+ /**
7
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
8
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
9
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
10
+ */
11
+ function forwardedRequestOrigin(request) {
12
+ const url = new URL(request.url);
13
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
14
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
15
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
16
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
17
+ try {
18
+ return new URL(`${protocol}://${host}`).origin;
19
+ } catch {
20
+ return url.origin;
21
+ }
22
+ }
23
+ // src/client-request.ts
24
+ const storageKey = Symbol.for("vitehub.auth.client-request");
25
+ const runtimeGlobal = globalThis;
26
+ const clientRequests = runtimeGlobal[storageKey] ||= new AsyncLocalStorage();
27
+ function isRelativeInProcessRequest(request, client) {
28
+ const url = new URL(request.url);
29
+ if (url.protocol !== "http:") return false;
30
+ if (url.host === "localhost") return true;
31
+ const clientUrl = new URL(client.url);
32
+ url.protocol = clientUrl.protocol;
33
+ return url.host === clientUrl.host;
34
+ }
35
+ function runWithClientRequest(request, next) {
36
+ const client = clientRequests.getStore();
37
+ return client && isRelativeInProcessRequest(request, client) ? next() : clientRequests.run(request, next);
38
+ }
39
+ /**
40
+ * Nitro builds a relative request that the server sends to itself, such as a Nuxt `useFetch()` during server rendering
41
+ * or `serverFetch("/api/...")`, at `http://localhost` or `http://<forwarded Host>`, so the URL of that request does not
42
+ * show the origin of the page.
43
+ */
44
+ function clientRequest(request) {
45
+ const client = clientRequests.getStore();
46
+ return client && isRelativeInProcessRequest(request, client) ? client : request;
47
+ }
48
+ function clientRequestOrigin(request, trustProxyHeaders = false) {
49
+ const client = clientRequest(request);
50
+ return trustProxyHeaders ? forwardedRequestOrigin(client) : new URL(client.url).origin;
51
+ }
52
+ export { forwardedRequestOrigin as i, clientRequestOrigin as n, runWithClientRequest as r, clientRequest as t };