@vite-hub/auth 0.6.1 → 0.8.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 (78) hide show
  1. package/README.md +86 -12
  2. package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +31 -12
  8. package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  15. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-Cms7BI3c.js +36 -0
  20. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +13 -8
  23. package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
  24. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
  25. package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
  26. package/dist/extension-BWmjJhoN.d.ts +59 -0
  27. package/dist/extension-mCx4TrsO.js +133 -0
  28. package/dist/forward.js +1 -1
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +5 -3
  31. package/dist/internal/server.d.ts +3 -3
  32. package/dist/internal/server.js +5 -4
  33. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  34. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
  35. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
  36. package/dist/mcp.d.ts +2 -2
  37. package/dist/mcp.js +27 -6
  38. package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
  39. package/dist/nuxt.d.ts +4 -14
  40. package/dist/nuxt.js +53 -20
  41. package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  42. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  43. package/dist/presets.js +1 -1
  44. package/dist/roles-BGi8CyBG.js +17 -0
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +7 -4
  55. package/dist/runtime/vue-nuxt.js +27 -11
  56. package/dist/schema.d.ts +32 -14
  57. package/dist/schema.js +21 -14
  58. package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
  59. package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
  60. package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
  61. package/dist/server.d.ts +6 -3
  62. package/dist/server.js +9 -3
  63. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
  64. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
  65. package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
  70. package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
  71. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  72. package/dist/vite.d.ts +41 -6
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -3
  75. package/dist/vue.js +39 -4
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-B87hDU4j.js +0 -28
@@ -1,30 +1,54 @@
1
- import { i as forwardedRequestOrigin, t as clientRequest } from "./client-request-BzMKtfCY.js";
1
+ import { t as clientRequest } from "./client-request-B1DCz3a9.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { i as resolveAuthMountPath } from "./application-path-zKi7NrvK.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";
9
- import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
10
- import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BXU1_9mc.js";
4
+ import { a as readMembers, c as createAdminClaimPlugin, f as createAdminsPlugin, h as createAccessPolicyPlugin, l as readAdminClaim, n as createMembersGate, o as withMemberScopes, p as readAdmins, t as assertMembersSessionStore } from "./members-7OMdqha_.js";
5
+ import { i as authDatabaseName, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-Cms7BI3c.js";
6
+ import { t as assertAuthDatabaseNames } from "./database-schema-options-IlHEeUBK.js";
7
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
8
+ import { a as validateAuthComponents, c as validateAuthEvents, i as validateAuthAccessRouteRoles, l as applyAuthPreset, o as createDeleteAccount, r as validateAuthAccessPolicy, s as validateDeleteAccount, t as assertNoRuntimeOption } from "./definition-EpeI5LUG.js";
9
+ import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-Cm7Iwq47.js";
11
10
  import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
11
+ import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
12
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";
15
- import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-CtoKaNQZ.js";
13
+ import { o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
14
+ import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-Bva-P-_C.js";
15
+ import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-dVJBPPTk.js";
16
16
  import { resolvePublicUrl } from "@vite-hub/runtime";
17
+ import { isRequest } from "@vite-hub/runtime/internal/response";
17
18
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
18
19
  import { AsyncLocalStorage } from "node:async_hooks";
19
20
  import { createAuthEndpoint, createAuthMiddleware, getOAuthState, getSessionFromCtx, isAPIError, sensitiveSessionMiddleware } from "better-auth/api";
20
21
  import { getCookies } from "better-auth/cookies";
21
22
  import { getAuthTables } from "better-auth/db";
22
- import { APIError as APIError$1, betterAuth, createLogger, isRequestLike, resolveBaseURL } from "better-auth";
23
+ import { APIError as APIError$1, BetterAuthError, betterAuth, createLogger, getBaseURL, isDynamicBaseURLConfig, resolveBaseURL, trimTrailingSlashes } from "better-auth";
23
24
  import { memoryAdapter } from "better-auth/adapters/memory";
24
25
  import definitionForApp, { getAuthApp } from "#vitehub/auth/definition";
26
+ import { configuredAppOrigin, configuredPublicOrigins } from "@vite-hub/runtime/internal/public-url";
25
27
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
26
28
  import { isWebContainer } from "@vite-hub/web-container/env";
27
29
  import { hkdfSync } from "node:crypto";
30
+ import { addRoute, createRouter, findRoute } from "better-auth-rou3";
31
+ // ../internal/src/runtime/request-origin.ts
32
+ function firstHeaderValue(headers, name) {
33
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
34
+ }
35
+ /**
36
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
37
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
38
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
39
+ */
40
+ function forwardedRequestOrigin(request) {
41
+ const url = new URL(request.url);
42
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
43
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
44
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
45
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
46
+ try {
47
+ return new URL(`${protocol}://${host}`).origin;
48
+ } catch {
49
+ return url.origin;
50
+ }
51
+ }
28
52
  // src/password.ts
29
53
  const scryptOptions = {
30
54
  N: 16384,
@@ -89,27 +113,44 @@ Object.freeze({ prefix: "sha256=" });
89
113
  // src/secret.ts
90
114
  /** The `deriveSecret()` purpose of the Better Auth secret. `vitehub secret derive vitehub:auth` prints it. */
91
115
  const authSecretPurpose = "vitehub:auth";
92
- const betterAuthSecretNames = [
93
- "BETTER_AUTH_SECRET",
94
- "BETTER_AUTH_SECRETS",
95
- "AUTH_SECRET"
96
- ];
116
+ const publicDefaultSecret = "better-auth-secret-12345678901234567890";
117
+ function parseVersionedSecrets(value) {
118
+ return value?.split(",").map((entry, index) => {
119
+ const separator = entry.indexOf(":");
120
+ const version = Number.parseInt(entry.slice(0, separator), 10);
121
+ const secret = entry.slice(separator + 1).trim();
122
+ if (separator === -1 || !Number.isInteger(version) || version < 0 || !secret) throw new BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry at position ${index + 1}. Expected a non-negative version and a non-empty secret: "<version>:<secret>".`);
123
+ return {
124
+ version,
125
+ value: secret
126
+ };
127
+ });
128
+ }
129
+ function resolveAuthSecrets(options, bindings, development) {
130
+ const env = globalThis.process?.env;
131
+ const readEnvSecret = (name) => {
132
+ const binding = bindings?.[name];
133
+ return typeof binding === "string" && binding || env?.[name] || void 0;
134
+ };
135
+ const secrets = options.secrets ?? parseVersionedSecrets(readEnvSecret("BETTER_AUTH_SECRETS"));
136
+ const legacySecret = options.secret || readEnvSecret("BETTER_AUTH_SECRET") || readEnvSecret("AUTH_SECRET");
137
+ const keepDevelopmentDefault = development && (Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets"));
138
+ const secret = legacySecret ?? (secrets || keepDevelopmentDefault ? void 0 : deriveAuthSecret({
139
+ ...env,
140
+ ...bindings
141
+ }));
142
+ return {
143
+ secret,
144
+ secrets,
145
+ secretMissing: !development && (!secret && !secrets || secret === publicDefaultSecret || secrets?.some((key) => key.value === publicDefaultSecret) === true)
146
+ };
147
+ }
97
148
  let derived;
98
149
  function hex(buffer) {
99
150
  return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
100
151
  }
101
- /**
102
- * The Better Auth secret derived from the root app secret, `VITEHUB_SECRET`, equal to
103
- * `deriveSecret("vitehub:auth")`. Returns `undefined` when the environment sets a Better Auth secret or no root secret.
104
- * It is synchronous because Better Auth reads its options synchronously.
105
- */
106
- function deriveAuthSecret(event) {
107
- const env = {
108
- ...globalThis.process?.env,
109
- ...authCloudflareEnv(event)
110
- };
111
- if (betterAuthSecretNames.some((name) => env[name])) return void 0;
112
- const root = readViteHubSecret(env);
152
+ function deriveAuthSecret(environment) {
153
+ const root = readViteHubSecret(environment);
113
154
  if (!root) return void 0;
114
155
  if (root.length < 32) throw authErrorDiagnostics.AUTH_R0016({ message: `[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.` });
115
156
  if (derived?.root !== root) derived = {
@@ -724,7 +765,7 @@ function createImpersonationPlugin() {
724
765
  const clientAddressHeader = "x-vitehub-client-address";
725
766
  /** The addresses that `handleAuthRequest()` read from the request event, for the Request that it passes to Better Auth. */
726
767
  const eventAddresses = /* @__PURE__ */ new WeakMap();
727
- function readString(value, path) {
768
+ function readStringAtPath(value, path) {
728
769
  let current = value;
729
770
  for (const key of path) {
730
771
  if (current === null || typeof current !== "object" && typeof current !== "function") return void 0;
@@ -738,7 +779,7 @@ function readString(value, path) {
738
779
  * not read.
739
780
  */
740
781
  function eventClientAddress(event) {
741
- return readString(event, [
782
+ return readStringAtPath(event, [
742
783
  "~standard",
743
784
  "runtime",
744
785
  "clientAddress"
@@ -751,7 +792,7 @@ function setRequestClientAddress(request, address) {
751
792
  }
752
793
  /** Return the request with only the host address in {@link clientAddressHeader}. srvx adds that address as `ip`. */
753
794
  function addressedRequest(request) {
754
- const address = eventAddresses.get(request) ?? readString(request, ["ip"]);
795
+ const address = eventAddresses.get(request) ?? readStringAtPath(request, ["ip"]);
755
796
  if (request.headers.get("x-vitehub-client-address") === (address ?? null)) return request;
756
797
  const headers = new Headers(request.headers);
757
798
  if (address) headers.set(clientAddressHeader, address);
@@ -803,6 +844,72 @@ function withClientAddress(auth) {
803
844
  fetch: addressedHandler
804
845
  });
805
846
  }
847
+ // src/rate-limit-endpoints.ts
848
+ const binders = /* @__PURE__ */ new WeakMap();
849
+ function endpointRouter(api) {
850
+ const router = createRouter();
851
+ for (const endpoint of Object.values(api)) {
852
+ const { path, options } = endpoint;
853
+ if (!path || !options) continue;
854
+ if (("metadata" in options ? options.metadata : void 0)?.SERVER_ONLY) continue;
855
+ const methods = Array.isArray(options.method) ? options.method : [options.method];
856
+ for (const method of methods) addRoute(router, method, path, path);
857
+ }
858
+ return router;
859
+ }
860
+ function matchEndpoint(auth) {
861
+ let router;
862
+ return async (request) => {
863
+ const context = await auth.$context;
864
+ const { advanced, baseURL } = context.options;
865
+ const basePath = context.options.basePath || "/api/auth";
866
+ const resolved = isDynamicBaseURLConfig(auth.options.baseURL) ? resolveBaseURL(baseURL, basePath, request, void 0, advanced?.trustedProxyHeaders ?? false) : context.baseURL || getBaseURL(void 0, basePath, request, void 0, advanced?.trustedProxyHeaders);
867
+ if (!resolved) return;
868
+ const mount = trimTrailingSlashes(new URL(resolved).pathname);
869
+ const pathname = new URL(request.url).pathname;
870
+ if (mount && !pathname.startsWith(`${mount}/`)) return;
871
+ const path = pathname.slice(mount.length);
872
+ if (!path || path.includes("//")) return;
873
+ router ??= endpointRouter(auth.api);
874
+ const route = findRoute(router, request.method, path, { params: false })?.data;
875
+ if (!route || !auth.options.advanced?.skipTrailingSlashes && path.endsWith("/") !== route.endsWith("/")) return;
876
+ return !/[:*(){\\]/.test(route) && trimTrailingSlashes(route) === trimTrailingSlashes(path) ? "static" : "pattern";
877
+ };
878
+ }
879
+ /**
880
+ * These rules count a request only when its path is a static endpoint path of the instance, so that each client
881
+ * address has a fixed set of counters. Exact rules of the app apply as declared; wildcard rules also match parameterized endpoints. Each
882
+ * wildcard rule object also stays under a key that no request path matches, because Better Auth reads the windows of
883
+ * rule objects to decide which stored counters have expired.
884
+ * {@link withEndpointRateLimits} gives the rules the endpoints of the instance; until then, every request counts.
885
+ */
886
+ function endpointRateLimitRules(rules) {
887
+ let match;
888
+ const guard = (rule) => async (request, current) => {
889
+ if (match && !await match(request)) return false;
890
+ return typeof rule === "function" ? rule(request, current) : rule;
891
+ };
892
+ const guarded = {};
893
+ for (const [path, rule] of Object.entries(rules ?? {})) {
894
+ if (!path.includes("*")) {
895
+ guarded[path] = rule;
896
+ continue;
897
+ }
898
+ guarded[path] = guard(rule);
899
+ if (rule && typeof rule === "object") guarded[`vitehub:window:${rule.window}`] = rule;
900
+ }
901
+ if (!Object.hasOwn(guarded, "**")) guarded["**"] = async (request, current) => !match || await match(request) === "static" ? current : false;
902
+ binders.set(guarded, (auth) => {
903
+ match ??= matchEndpoint(auth);
904
+ });
905
+ return guarded;
906
+ }
907
+ /** Give the rules of {@link endpointRateLimitRules} the endpoints of the instance that uses them. */
908
+ function withEndpointRateLimits(auth) {
909
+ const rules = auth.options?.rateLimit?.customRules;
910
+ if (rules) binders.get(rules)?.(auth);
911
+ return auth;
912
+ }
806
913
  // src/session-refresh.ts
807
914
  /**
808
915
  * Runs `session.onRefresh` from the Better Auth `session.update.before` database hook.
@@ -921,7 +1028,8 @@ function isDevelopmentServer() {
921
1028
  /**
922
1029
  * Better Auth turns its limiter on only when `NODE_ENV` is `production`, and keeps its counters in the memory of the
923
1030
  * process unless a `secondaryStorage` is set. Auth turns it on outside a development server, and keeps the counters in
924
- * the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them.
1031
+ * the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them. It counts
1032
+ * only requests to the endpoints of the instance.
925
1033
  */
926
1034
  function withRateLimitDefaults(options, ownsDatabase) {
927
1035
  const rateLimit = options.rateLimit;
@@ -929,6 +1037,7 @@ function withRateLimitDefaults(options, ownsDatabase) {
929
1037
  return {
930
1038
  ...rateLimit,
931
1039
  enabled: rateLimit?.enabled ?? !isDevelopmentServer(),
1040
+ customRules: endpointRateLimitRules(rateLimit?.customRules),
932
1041
  ...database ? { storage: "database" } : {}
933
1042
  };
934
1043
  }
@@ -936,38 +1045,36 @@ function withRateLimitDefaults(options, ownsDatabase) {
936
1045
  * Better Auth reads the client IP from `X-Forwarded-For` by default, which a client can set and Cloudflare does not
937
1046
  * send. Auth gives it the address that the host reports instead, also with `trustedProxyHeaders`: on the Node host behind a proxy,
938
1047
  * `vitehub({ trustProxy: true })` makes that address the last `X-Forwarded-For` value, which the proxy adds.
1048
+ * Better Auth also turns off its Origin and CSRF checks when `TEST` or `NODE_ENV=test` is set, such as in a server that
1049
+ * a Vitest run starts. Auth serves real requests, so only `advanced.disableOriginCheck` turns them off.
939
1050
  */
940
- function withClientAddressHeaders(advanced) {
941
- if (advanced?.ipAddress?.ipAddressHeaders) return advanced;
1051
+ function withAdvancedDefaults(advanced) {
1052
+ const disableOriginCheck = advanced?.disableOriginCheck ?? false;
1053
+ if (advanced?.ipAddress?.ipAddressHeaders) return {
1054
+ ...advanced,
1055
+ disableOriginCheck
1056
+ };
942
1057
  return {
943
1058
  ...advanced,
1059
+ disableOriginCheck,
944
1060
  ipAddress: {
945
1061
  ...advanced?.ipAddress,
946
1062
  ipAddressHeaders: [clientAddressHeader]
947
1063
  }
948
1064
  };
949
1065
  }
950
- const betterAuthSetupVariables = [
951
- "AUTH_SECRET",
952
- "BETTER_AUTH_SECRET",
953
- "BETTER_AUTH_SECRETS",
954
- "BETTER_AUTH_TRUSTED_ORIGINS"
955
- ];
956
1066
  /**
957
1067
  * The environment values that an instance for these options uses. Auth reads a value only when the options use it, so
958
1068
  * the instance key and the instance read the same values, and a value that the options replace cannot fail a request.
959
1069
  */
960
1070
  function readProviderEnvironment(options, event) {
961
- const env = {
962
- ...globalThis.process?.env,
963
- ...authCloudflareEnv(event)
964
- };
1071
+ const bindings = authCloudflareEnv(event);
965
1072
  return {
966
1073
  admins: readAdmins(event),
967
1074
  members: readMembers(event),
968
1075
  adminClaim: options.adminClaim === false ? void 0 : readAdminClaim(event),
969
- secret: Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets") ? void 0 : deriveAuthSecret(event),
970
- betterAuth: betterAuthSetupVariables.map((name) => env[name] ?? null)
1076
+ ...resolveAuthSecrets(options, bindings, isDevelopmentServer()),
1077
+ trustedOrigins: bindings?.BETTER_AUTH_TRUSTED_ORIGINS ?? globalThis.process?.env?.BETTER_AUTH_TRUSTED_ORIGINS
971
1078
  };
972
1079
  }
973
1080
  function stripViteHubOptions(definition, options, environment) {
@@ -993,6 +1100,7 @@ function stripViteHubOptions(definition, options, environment) {
993
1100
  }
994
1101
  const policy = isRecord(access) ? access.policy : void 0;
995
1102
  validateAuthAccessPolicy(policy);
1103
+ validateAuthAccessRouteRoles(access);
996
1104
  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." });
997
1105
  const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
998
1106
  const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
@@ -1041,7 +1149,7 @@ function stripViteHubOptions(definition, options, environment) {
1041
1149
  createRequestLogPlugin()
1042
1150
  ],
1043
1151
  logger: withRequestLogger(rest.logger),
1044
- advanced: withClientAddressHeaders(rest.advanced),
1152
+ advanced: withAdvancedDefaults(rest.advanced),
1045
1153
  rateLimit,
1046
1154
  ...eventPlugin ? { hooks: {
1047
1155
  ...rest.hooks,
@@ -1065,12 +1173,13 @@ function withSessionRefresh(options, hasSessionStore) {
1065
1173
  session: betterAuthSession
1066
1174
  };
1067
1175
  }
1068
- /** Without a configured secret, Better Auth signs with the secret derived from `VITEHUB_SECRET`. */
1069
- function withDerivedSecret(options, { secret }) {
1070
- return secret ? {
1176
+ function withResolvedSecrets(options, { secret, secrets, secretMissing }) {
1177
+ if (secretMissing) throw authErrorDiagnostics.AUTH_SECRET_MISSING();
1178
+ return {
1071
1179
  ...options,
1072
- secret
1073
- } : options;
1180
+ ...secret ? { secret } : {},
1181
+ ...secrets ? { secrets } : {}
1182
+ };
1074
1183
  }
1075
1184
  function trustsProxyHeaders(options) {
1076
1185
  return isRecord(options) && isRecord(options.advanced) && options.advanced.trustedProxyHeaders === true;
@@ -1085,8 +1194,9 @@ function resolveAuthOptions(definition, input = {}) {
1085
1194
  const usesContext = !request || callback;
1086
1195
  const env = usesContext ? input.env?.(input.event) ?? {} : {};
1087
1196
  const client = request && clientRequest(request);
1088
- const clientUrlOrigin = client ? new URL(client.url).origin : void 0;
1089
- const proxiedOrigin = client ? forwardedRequestOrigin(client) : void 0;
1197
+ const publicOrigin = client ? configuredAppOrigin(client) : void 0;
1198
+ const clientUrlOrigin = client ? publicOrigin ?? new URL(client.url).origin : void 0;
1199
+ const proxiedOrigin = client ? publicOrigin ?? forwardedRequestOrigin(client) : void 0;
1090
1200
  const resolveAt = (origin) => {
1091
1201
  const context = {
1092
1202
  env,
@@ -1118,7 +1228,7 @@ function resolveAuthOptions(definition, input = {}) {
1118
1228
  let requestRuntimeOptions = callback ? declared : {};
1119
1229
  if (client) {
1120
1230
  const requestOrigin = trusted && proxiedOrigin ? proxiedOrigin : client.url;
1121
- const baseURL = requestRuntimeOptions.baseURL || resolvePublicUrl({ request: { url: requestOrigin } });
1231
+ const baseURL = requestRuntimeOptions.baseURL || publicOrigin || resolvePublicUrl({ request: { url: requestOrigin } });
1122
1232
  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.` });
1123
1233
  requestRuntimeOptions = {
1124
1234
  ...!Object.hasOwn(declared, "trustedOrigins") ? { trustedOrigins: [baseURL] } : {},
@@ -1140,7 +1250,7 @@ function resolveAuthOptions(definition, input = {}) {
1140
1250
  get providerOptions() {
1141
1251
  const options = resolveSnapshot();
1142
1252
  const environment = resolveEnvironment();
1143
- return withDerivedSecret(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1253
+ return withResolvedSecrets(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
1144
1254
  },
1145
1255
  /** Equal for two resolutions of this Definition that give Better Auth equal options, else `undefined`. */
1146
1256
  get providerKey() {
@@ -1174,14 +1284,14 @@ const markerAttributes = [
1174
1284
  "partitioned"
1175
1285
  ];
1176
1286
  function requestSource(input) {
1177
- if (isRequestLike(input)) return input;
1178
- if (isRequestLike(input?.request)) return input.request;
1287
+ if (isRequest(input)) return input;
1288
+ if (isRequest(input?.request)) return input.request;
1179
1289
  const headers = new Headers(input?.headers);
1180
1290
  return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
1181
1291
  }
1182
1292
  /** The value of one cookie in the request of an API call or a handler request. */
1183
1293
  function requestCookie(input, name) {
1184
- const headers = isRequestLike(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1294
+ const headers = isRequest(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
1185
1295
  for (const part of headers?.get("cookie")?.split(";") ?? []) {
1186
1296
  const separator = part.indexOf("=");
1187
1297
  if (separator !== -1 && part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
@@ -1275,7 +1385,7 @@ function hasRequestRuntimeOptions(definition) {
1275
1385
  return typeof definition.options === "function" || trustsProxyHeaders(definition.options);
1276
1386
  }
1277
1387
  function hasConfiguredPublicUrl() {
1278
- return typeof __VITEHUB_PUBLIC_URL__ !== "undefined" && Boolean(__VITEHUB_PUBLIC_URL__?.url || Object.keys(__VITEHUB_PUBLIC_URL__?.agents ?? {}).length);
1388
+ return configuredPublicOrigins().length > 0;
1279
1389
  }
1280
1390
  function envResolverFor(definition) {
1281
1391
  return getAuthRuntimeState().envResolvers?.get(definition) ?? getAuthRuntimeState().envResolver;
@@ -1296,7 +1406,7 @@ function createBetterAuthOptions(definition) {
1296
1406
  }
1297
1407
  function createAuthenticationProvider(options) {
1298
1408
  try {
1299
- return withSessionMarker(withClientAddress(betterAuth(options)));
1409
+ return withSessionMarker(withEndpointRateLimits(withClientAddress(betterAuth(options))));
1300
1410
  } catch (cause) {
1301
1411
  throwAuthenticationProviderError(cause, "get-auth-for-request");
1302
1412
  }
@@ -1345,11 +1455,11 @@ function requestProvider(definition, resolved) {
1345
1455
  * `useAuth(event)`. The Console reads it through `@vite-hub/auth/runtime/console`.
1346
1456
  */
1347
1457
  function authForRequest(request, event, definition = resolveDefaultDefinition()) {
1348
- if (!hasRequestRuntimeOptions(definition) && !hasConfiguredPublicUrl()) return getAuthForDefinition(definition);
1458
+ if (!hasRequestRuntimeOptions(definition) && !hasConfiguredPublicUrl() && (!isDevelopmentServer() || getBaseURL())) return getAuthForDefinition(definition);
1349
1459
  return requestProvider(definition, resolveAuthOptions(definition, {
1350
1460
  request,
1351
1461
  event,
1352
1462
  env: envResolverFor(definition)
1353
1463
  }));
1354
1464
  }
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 };
1465
+ export { setAuthResponseOutcome as _, getAuthForDefinition as a, withSessionMarker as c, withEndpointRateLimits as d, eventClientAddress as f, setAuthOutcome as g, runWithAuthEvent as h, findVerifiedAuthUserId as i, resolveAuthOptions as l, withClientAddress as m, createBetterAuthOptions as n, requestProvider as o, setRequestClientAddress as p, envResolverFor as r, resolveDefaultDefinition as s, authForRequest as t, trustsProxyHeaders as u, forwardedRequestOrigin as v };
@@ -58,6 +58,7 @@ interface ProvisionStep {
58
58
  id: string;
59
59
  provider: ProvisionProvider;
60
60
  plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
61
+ hasResources?: (context: Pick<ProvisionContext, "env">) => boolean;
61
62
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
62
63
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
63
64
  }
@@ -74,10 +75,13 @@ interface ViteHubCliSpawnResult {
74
75
  signal?: NodeJS.Signals | null;
75
76
  /** The output of the child when `stdout` is `pipe`. */
76
77
  stdout?: string;
78
+ /** The error output of the child when `stderr` is `pipe`. */
79
+ stderr?: string;
77
80
  }
78
81
  interface ViteHubCliSpawnOptions {
79
82
  cwd?: string;
80
83
  env?: NodeJS.ProcessEnv;
84
+ onOutput?: (text: string, stream: "stdout" | "stderr") => void;
81
85
  stderr?: "inherit" | "pipe";
82
86
  /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
83
87
  stdin?: "ignore" | "inherit";
@@ -85,7 +89,17 @@ interface ViteHubCliSpawnOptions {
85
89
  stdout?: "inherit" | "pipe" | "stderr";
86
90
  }
87
91
  type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
92
+ /** Where a call to an app goes through the Console: the operation endpoint of the app's Console project, and the token of `vitehub login`. */
93
+ interface ViteHubCliConsoleRoute {
94
+ authorization: string;
95
+ target: string;
96
+ }
88
97
  interface ViteHubCliContext extends ViteHubCliStreams {
98
+ /**
99
+ * Finds the app at `url` in the Console of `vitehub login` and returns the route that lets the Console sign the call.
100
+ * Returns nothing when the command must call the app directly, such as when a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` is set.
101
+ */
102
+ consoleRoute?: (url: string, signal: AbortSignal) => Promise<ViteHubCliConsoleRoute | undefined>;
89
103
  cwd: string;
90
104
  env: NodeJS.ProcessEnv;
91
105
  /** Replaces `fetch` for commands that call a running app, so tests need no server. */
@@ -104,6 +118,7 @@ interface ViteHubCliContext extends ViteHubCliStreams {
104
118
  spawn: ViteHubCliSpawn;
105
119
  }
106
120
  interface ViteHubCliProvision {
121
+ env?: NodeJS.ProcessEnv;
107
122
  rootDir: string;
108
123
  steps: readonly ProvisionStep[];
109
124
  }
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as ViteHubCliContributor } from "./cli-C5pAfY4x.js";
1
+ import { t as ViteHubCliContributor } from "./cli-DL7uCAvz.js";
2
2
  /** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
3
3
  export declare function createAuthCliContributor(options?: {
4
4
  fetch?: typeof fetch;
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-CUPwukgE.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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,33 @@
1
+ import { i as OnlyKeys } from "./extension-BWmjJhoN.js";
2
+ import { BetterAuthClientOptions } from "better-auth";
3
+ /** What a part of the Auth client options can add. Every other option stays in `defineAuthClient()`. */
4
+ interface AuthClientExtensionOptions {
5
+ /** Better Auth client plugins, added after the plugins of `auth.client.ts`. */
6
+ plugins?: NonNullable<BetterAuthClientOptions["plugins"]>;
7
+ }
8
+ /** A part of the Auth client options, from `extendAuthClient()` in `auth.client.extend.ts`. */
9
+ interface AuthClientExtension<TOptions extends AuthClientExtensionOptions = AuthClientExtensionOptions> {
10
+ extension: TOptions;
11
+ }
12
+ /**
13
+ * A part of the Auth client options: Better Auth client plugins that a Nuxt layer, or the app, adds to the options of
14
+ * `auth.client.ts`. Export it as the default export of `auth.client.extend.ts`, which is in `app/` in a Nuxt app.
15
+ */
16
+ declare function extendAuthClient<const TOptions extends AuthClientExtensionOptions>(options: OnlyKeys<TOptions, "plugins">): AuthClientExtension<TOptions>;
17
+ /** A part with the file that exports it, as the generated client module lists them. */
18
+ interface AuthClientExtensionSource {
19
+ file: string;
20
+ extension: AuthClientExtension;
21
+ }
22
+ type ClientPluginsOf<TOptions> = TOptions extends {
23
+ plugins: infer TPlugins extends readonly unknown[];
24
+ } ? TPlugins : [];
25
+ type ClientExtensionPlugins<TExtensions extends readonly unknown[]> = TExtensions extends readonly [AuthClientExtension<infer TOptions>, ...infer TRest] ? [...ClientPluginsOf<TOptions>, ...ClientExtensionPlugins<TRest>] : [];
26
+ /**
27
+ * The type of the client options with their parts, which generated declarations register. `TExtensions` is the tuple of
28
+ * the default exports of the `auth.client.extend.ts` files, in merge order.
29
+ */
30
+ type ExtendedAuthClientOptions<TOptions, TExtensions extends readonly unknown[]> = Omit<TOptions, "plugins"> & {
31
+ plugins: [...ClientPluginsOf<TOptions>, ...ClientExtensionPlugins<TExtensions>];
32
+ };
33
+ export { extendAuthClient as a, ExtendedAuthClientOptions as i, AuthClientExtensionOptions as n, AuthClientExtensionSource as r, AuthClientExtension as t };
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // ../internal/src/runtime/client-request.ts
3
+ const storageKey = Symbol.for("vitehub.client-request");
4
+ const runtimeGlobal = globalThis;
5
+ const clientRequests = runtimeGlobal[storageKey] ||= new AsyncLocalStorage();
6
+ function isRelativeInProcessRequest(request, client) {
7
+ const url = new URL(request.url);
8
+ if (url.protocol !== "http:") return false;
9
+ if (url.host === "localhost") return true;
10
+ const clientUrl = new URL(client.url);
11
+ url.protocol = clientUrl.protocol;
12
+ return url.host === clientUrl.host || url.host === client.headers.get("host");
13
+ }
14
+ /** Runs `next` with `request` as the client request, unless `request` is a relative request inside a client request. */
15
+ function runWithClientRequest(request, next) {
16
+ const client = clientRequests.getStore();
17
+ return client && isRelativeInProcessRequest(request, client) ? next() : clientRequests.run(request, next);
18
+ }
19
+ /**
20
+ * The request that the client sent. Nitro builds a relative request that the server sends to itself, such as a Nuxt
21
+ * `useFetch()` during server rendering or `serverFetch("/api/...")`, at `http://localhost` or `http://<forwarded Host>`,
22
+ * so the URL of that request does not show the origin of the page. Read origins from this request instead. It needs
23
+ * the Nitro plugin that `clientRequestPlugin()` of `@vite-hub/internal/nitro-kit` gives.
24
+ */
25
+ function clientRequest(request) {
26
+ const client = clientRequests.getStore();
27
+ return client && isRelativeInProcessRequest(request, client) ? client : request;
28
+ }
29
+ export { runWithClientRequest as n, clientRequest as t };
@@ -1,4 +1,4 @@
1
- import { Ft as AuthEventStore, J as AuthConsoleAgent, K as AuthConsoleActivity, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, ct as AuthConsoleOptions, dt as AuthConsoleOverview, gt as AuthConsoleSession, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, ot as AuthConsoleList, q as AuthConsoleActivityQuery, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, yt as AuthConsoleUserDetail } from "./types-DmH31d2t.js";
1
+ import { J as AuthConsoleActivityQuery, Q as AuthConsoleDescription, Rt as AuthEventStore, Y as AuthConsoleAgent, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, ft as AuthConsoleOverview, ht as AuthConsoleQuery, lt as AuthConsoleOptions, nt as AuthConsoleField, q as AuthConsoleActivity, st as AuthConsoleList, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
4
4
  interface AuthConsole {
@@ -1,7 +1,7 @@
1
- import { m as adminsVariable, p as adminsPluginId, r as membersVariable, s as accessPolicyPluginId, u as adminClaimPluginId } from "./members-CwPIx10t.js";
1
+ import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-7OMdqha_.js";
2
2
  import { n as adminClaimVariable } from "./admin-claim-code-C3X_U43x.js";
3
3
  import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
4
- import { r as parseAuthEventList } from "./events-BXU1_9mc.js";
4
+ import { r as parseAuthEventList } from "./events-Cm7Iwq47.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
6
6
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
7
7
  // ../internal/src/runtime/user-agent.ts
@@ -194,7 +194,9 @@ function adminsAccess(plugins) {
194
194
  const admins = Reflect.get(options, "admins");
195
195
  const role = Reflect.get(options, "role");
196
196
  if (!Array.isArray(admins) || typeof role !== "string") return [];
197
- return [`${adminsVariable} gives the ${role} role to ${admins.join(", ")} on sign-in.`];
197
+ const emails = admins.filter((entry) => typeof entry === "string" && entry.includes("@")).length;
198
+ const listed = [...admins.filter((entry) => typeof entry === "string" && !entry.includes("@")), ...emails ? [`${emails} verified ${emails === 1 ? "email" : "emails"}`] : []];
199
+ return [`${adminsVariable} gives the ${role} role to ${listed.join(", ")} on sign-in.`];
198
200
  }
199
201
  /** The `VITEHUB_MEMBERS` rule as an access note, so the Console shows who may sign in. */
200
202
  function membersAccess(plugins) {
@@ -1,3 +1,3 @@
1
- import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-DmH31d2t.js";
2
- import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-DMH1I2fl.js";
1
+ import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
2
+ import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-C71weVrt.js";
3
3
  export { AuthConsole, type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, AuthConsoleErrorCode, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type AuthConsoleImpersonation, type AuthConsoleList, type AuthConsoleMutation, type AuthConsoleOptions, type AuthConsoleOrganization, type AuthConsoleOrganizationDetail, type AuthConsoleOverview, type AuthConsolePage, type AuthConsolePolicy, type AuthConsoleQuery, type AuthConsoleRoles, type AuthConsoleSession, type AuthConsoleSessionUser, type AuthConsoleUser, type AuthConsoleUserDetail, type AuthConsoleValue, type authConsoleActionNames, type authConsoleEventGroups, createAuthConsole, describeAuthConsoleFields };
@@ -1 +1 @@
1
- export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-CaIXVtB_.js";
1
+ export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-Dk3j4Jmz.js";
package/dist/console.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-DmH31d2t.js";
1
+ import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-CnO5bHEF.js";
2
2
  /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
3
3
  interface ViteHubConsoleDefinitionCatalogView {
4
4
  kind: "definition-catalog";
@@ -0,0 +1,36 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
2
+ // src/database-options.ts
3
+ /** Reads the adapter's target without loading Better Auth or the Database runtime. */
4
+ function authDatabaseName(database) {
5
+ if (typeof database !== "function") return;
6
+ const name = Reflect.get(database, "vitehubDatabase");
7
+ return typeof name === "string" ? name : void 0;
8
+ }
9
+ /**
10
+ * The owned tables have text IDs that Better Auth makes, or `uuid` IDs on Postgres. `serial` needs integer IDs, and
11
+ * `false` needs a database default that a text ID does not have.
12
+ */
13
+ function assertAuthDatabaseIdStrategy(generateId) {
14
+ if (generateId === "serial" || generateId === false) throw authErrorDiagnostics.AUTH_C0053({ message: "`authDatabase()` owns tables with text IDs, or `uuid` IDs on Postgres. Use Better Auth's default ID generator, `uuid`, or a custom function returning strings; `advanced.database.generateId` cannot be `serial` or `false`. Use another Better Auth adapter to own a different ID schema." });
15
+ }
16
+ /** The ID columns of a Postgres Database and the `generateId` of the running options do not agree, so no insert can work. */
17
+ function authDatabaseIdColumnError(database, model, uuidColumn) {
18
+ const detail = uuidColumn ? "has a `uuid` ID, but `advanced.database.generateId` is not `\"uuid\"`, so Better Auth would write a text ID" : "has no `uuid` ID, but `advanced.database.generateId` is `\"uuid\"`, so Better Auth would leave the ID to a database default";
19
+ return authErrorDiagnostics.AUTH_C0053({ message: `The \`${model}\` table of the ${JSON.stringify(database)} Database of \`authDatabase()\` ${detail}. Write \`advanced: { database: { generateId: "uuid" } }\` inline in the Auth Definition so that the Auth Vite plugin can read it, then run \`vitehub database generate\` and apply the migration.` });
20
+ }
21
+ /** The Auth Vite plugin reads `additionalFields` from the Definition to add their columns, so they must be static. */
22
+ function authDatabaseAdditionalFieldsError(detail) {
23
+ return authErrorDiagnostics.AUTH_C0055({ message: `\`authDatabase()\` adds a column for each additional field, but ${detail}.` });
24
+ }
25
+ /** The Better Auth options need a table, a column, or a name that the Database of `authDatabase()` does not have. */
26
+ function authDatabaseSchemaError(detail) {
27
+ return authErrorDiagnostics.AUTH_C0056({ message: `\`authDatabase()\` cannot store the Better Auth options: ${detail}.` });
28
+ }
29
+ function authDatabasePlacementError() {
30
+ return authErrorDiagnostics.AUTH_C0054({ message: "`authDatabase()` needs one statically invariant Database: call it inline as `defineAuth()`'s `database`, in an object or a callback's single unconditional returned object. Do not select it in branches." });
31
+ }
32
+ /** Outside a development server, Auth keeps users in memory only when the Definition asks for it. */
33
+ function authMemoryDatabaseError() {
34
+ return authErrorDiagnostics.AUTH_C0063({ message: "`defineAuth()` has no `database` or `preset`. Auth keeps users and sessions in memory only on a development server, because a restart or a second instance loses them." });
35
+ }
36
+ export { authDatabasePlacementError as a, authDatabaseName as i, authDatabaseAdditionalFieldsError as n, authDatabaseSchemaError as o, authDatabaseIdColumnError as r, authMemoryDatabaseError as s, assertAuthDatabaseIdStrategy as t };