@vite-hub/auth 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +443 -32
- package/dist/abilities-DfAnFYwG.d.ts +93 -0
- package/dist/abilities.d.ts +2 -0
- package/dist/abilities.js +43 -0
- package/dist/ability-error-CqgBrBfR.js +91 -0
- package/dist/ability-error-DcgChwCN.d.ts +34 -0
- package/dist/admin-claim-code-CDipqeAU.js +22 -0
- package/dist/agent.d.ts +23 -12
- package/dist/agent.js +30 -8
- package/dist/application-path-DuTpfGFj.js +62 -0
- package/dist/auth-instance-CR6b1W80.js +1168 -0
- package/dist/bun-sqlite.d.ts +8 -0
- package/dist/cli-ubYJpAL_.d.ts +163 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +108 -0
- package/dist/console-runtime-DTopBP-x.d.ts +71 -0
- package/dist/console-runtime-J9_Vx9pT.js +1166 -0
- package/dist/console-runtime.d.ts +3 -0
- package/dist/console-runtime.js +2 -0
- package/dist/console-types-CmmnKGMx.js +38 -0
- package/dist/console.d.ts +219 -0
- package/dist/console.js +15 -0
- package/dist/database-options-BRNef9oy.js +29 -0
- package/dist/database-schema-options-ENuRMduM.js +12 -0
- package/dist/database.d.ts +12 -0
- package/dist/database.js +45 -0
- package/dist/definition-CqQMcDEK.js +280 -0
- package/dist/error-diagnostics-C8XtVz0i.js +138 -0
- package/dist/events-ByzenEVj.js +314 -0
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +120 -0
- package/dist/host-declarations.d.ts +6 -1
- package/dist/index.d.ts +26 -5
- package/dist/index.js +3 -95
- package/dist/internal/server.d.ts +5 -0
- package/dist/internal/server.js +858 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/mcp.d.ts +187 -0
- package/dist/mcp.js +353 -0
- package/dist/members-D9lfaEO_.js +533 -0
- package/dist/nuxt-bridge-Cl988STZ.js +44 -0
- package/dist/nuxt.d.ts +36 -7
- package/dist/nuxt.js +116 -7
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/page-tools-shared-l4eyj53D.js +19 -0
- package/dist/presets-BGZi6Dfu.d.ts +25 -0
- package/dist/presets.d.ts +2 -0
- package/dist/presets.js +32 -0
- package/dist/request-z6DHHmrb.js +47 -0
- package/dist/runtime/console.d.ts +3 -0
- package/dist/runtime/console.js +4 -0
- package/dist/runtime/empty-abilities.d.ts +5 -0
- package/dist/runtime/empty-abilities.js +4 -0
- package/dist/runtime/empty-client.d.ts +6 -0
- package/dist/runtime/empty-client.js +5 -0
- package/dist/runtime/empty-definition.d.ts +1 -2
- package/dist/runtime/nuxt.d.ts +2 -3
- package/dist/runtime/nuxt.js +3 -2
- package/dist/runtime/server.d.ts +2 -0
- package/dist/runtime/server.js +77 -0
- package/dist/runtime/vue-nuxt.d.ts +4 -0
- package/dist/runtime/vue-nuxt.js +160 -0
- package/dist/runtime-state-ojQCzKOc.js +25 -0
- package/dist/schema.d.ts +137 -0
- package/dist/schema.js +147 -0
- package/dist/server-C0qnKN2W.d.ts +143 -0
- package/dist/server-bQGzVQ--.d.ts +41 -0
- package/dist/server.d.ts +3 -22
- package/dist/server.js +3 -2
- package/dist/session-cookies-BbH3UR2m.js +227 -0
- package/dist/set-cookie-C8NOhdRE.js +90 -0
- package/dist/shared-BwcdRGxD.js +12 -0
- package/dist/table-specs-8gq_FCaq.js +771 -0
- package/dist/table-specs-DbXyaXWs.d.ts +842 -0
- package/dist/test.d.ts +26 -0
- package/dist/test.js +25 -0
- package/dist/types-CNaeH2Fd.d.ts +569 -0
- package/dist/vite-CV400XXY.js +1556 -0
- package/dist/vite.d.ts +145 -18
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +343 -17
- package/dist/vue.js +640 -15
- package/package.json +156 -27
- package/dist/server-BZn8iQrB.js +0 -370
- package/dist/shared-QSYBHaMG.js +0 -12
- package/dist/types-jaRlW3D1.d.ts +0 -117
- package/dist/vite-Cmey8ODS.js +0 -1018
|
@@ -0,0 +1,1168 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
|
|
2
|
+
import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-C8NOhdRE.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-D9lfaEO_.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-ByzenEVj.js";
|
|
8
|
+
import { i as resolveAuthMountPath } from "./application-path-DuTpfGFj.js";
|
|
9
|
+
import { t as normalizeAuthBasePath } from "./shared-BwcdRGxD.js";
|
|
10
|
+
import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-BRNef9oy.js";
|
|
11
|
+
import { t as assertAuthDatabaseNames } from "./database-schema-options-ENuRMduM.js";
|
|
12
|
+
import { a as applyAuthPreset, i as validateAuthEvents, r as validateAuthAccessPolicy, t as assertNoRuntimeOption } from "./definition-CqQMcDEK.js";
|
|
13
|
+
import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-l4eyj53D.js";
|
|
14
|
+
import { resolvePublicUrl } from "@vite-hub/runtime";
|
|
15
|
+
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
16
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
|
+
import { createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sensitiveSessionMiddleware } from "better-auth/api";
|
|
18
|
+
import { getCookies } from "better-auth/cookies";
|
|
19
|
+
import { getAuthTables } from "better-auth/db";
|
|
20
|
+
import { APIError as APIError$1, betterAuth, isRequestLike, resolveBaseURL } from "better-auth";
|
|
21
|
+
import { memoryAdapter } from "better-auth/adapters/memory";
|
|
22
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
23
|
+
import { isWebContainer } from "@vite-hub/web-container/env";
|
|
24
|
+
import { hkdfSync } from "node:crypto";
|
|
25
|
+
import discoveredDefinition from "#vitehub/auth/definition";
|
|
26
|
+
//#region ../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
|
+
//#endregion
|
|
48
|
+
//#region src/password.ts
|
|
49
|
+
const scryptOptions = {
|
|
50
|
+
N: 16384,
|
|
51
|
+
r: 16,
|
|
52
|
+
p: 1,
|
|
53
|
+
dkLen: 64,
|
|
54
|
+
maxmem: 67108864
|
|
55
|
+
};
|
|
56
|
+
let reported = false;
|
|
57
|
+
async function scryptKey(password, salt) {
|
|
58
|
+
const { scryptAsync } = await import("@noble/hashes/scrypt.js");
|
|
59
|
+
const { bytesToHex } = await import("@noble/hashes/utils.js");
|
|
60
|
+
return bytesToHex(await scryptAsync(password.normalize("NFKC"), salt, scryptOptions));
|
|
61
|
+
}
|
|
62
|
+
/** Hashes a password like Better Auth's default hasher, with the pure JavaScript scrypt of `@noble/hashes`. */
|
|
63
|
+
async function hashPasswordWithNoble(password) {
|
|
64
|
+
const salt = Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
65
|
+
return `${salt}:${await scryptKey(password, salt)}`;
|
|
66
|
+
}
|
|
67
|
+
/** Verifies a hash that Better Auth's default hasher or `hashPasswordWithNoble()` made. */
|
|
68
|
+
async function verifyPasswordWithNoble({ hash, password }) {
|
|
69
|
+
const [salt, key] = hash.split(":");
|
|
70
|
+
if (!salt || !key) throw authErrorDiagnostics.AUTH_PASSWORD_HASH_INVALID();
|
|
71
|
+
return await scryptKey(password, salt) === key;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A WebContainer has `node:crypto` `scrypt`, but every call throws `TypeError: run is not a function`.
|
|
75
|
+
* There, Auth gives Better Auth a pure JavaScript scrypt with the same output. Other hosts keep Better Auth's default.
|
|
76
|
+
* A `hash` or `verify` that the Auth Definition sets always wins.
|
|
77
|
+
*/
|
|
78
|
+
function withPasswordHasher(options) {
|
|
79
|
+
if (!isWebContainer()) return options;
|
|
80
|
+
const emailAndPassword = options.emailAndPassword;
|
|
81
|
+
const password = emailAndPassword?.password ?? {};
|
|
82
|
+
if (password.hash && password.verify) return options;
|
|
83
|
+
if (!reported) {
|
|
84
|
+
reported = true;
|
|
85
|
+
console.info("[vitehub] Auth hashes passwords with the scrypt of @noble/hashes, because node:crypto scrypt does not work in a WebContainer. Hashes stay compatible with other hosts.");
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
...options,
|
|
89
|
+
emailAndPassword: {
|
|
90
|
+
enabled: false,
|
|
91
|
+
...emailAndPassword,
|
|
92
|
+
password: {
|
|
93
|
+
...password,
|
|
94
|
+
hash: password.hash ?? hashPasswordWithNoble,
|
|
95
|
+
verify: password.verify ?? verifyPasswordWithNoble
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
new TextEncoder();
|
|
101
|
+
/** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
|
|
102
|
+
const viteHubSecretSalt = "vitehub";
|
|
103
|
+
/** Reads the root app secret, `VITEHUB_SECRET`, from an env record. Returns `undefined` when it is not a non-empty string. */
|
|
104
|
+
function readViteHubSecret(env) {
|
|
105
|
+
const value = env.VITEHUB_SECRET;
|
|
106
|
+
return typeof value === "string" && value ? value : void 0;
|
|
107
|
+
}
|
|
108
|
+
Object.freeze({ prefix: "sha256=" });
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/secret.ts
|
|
111
|
+
/** The `deriveSecret()` purpose of the Better Auth secret. `vitehub secret derive vitehub:auth` prints it. */
|
|
112
|
+
const authSecretPurpose = "vitehub:auth";
|
|
113
|
+
const betterAuthSecretNames = [
|
|
114
|
+
"BETTER_AUTH_SECRET",
|
|
115
|
+
"BETTER_AUTH_SECRETS",
|
|
116
|
+
"AUTH_SECRET"
|
|
117
|
+
];
|
|
118
|
+
let derived;
|
|
119
|
+
function hex(buffer) {
|
|
120
|
+
return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The Better Auth secret derived from the root app secret, `VITEHUB_SECRET`, equal to
|
|
124
|
+
* `deriveSecret("vitehub:auth")`. Returns `undefined` when the environment sets a Better Auth secret or no root secret.
|
|
125
|
+
* It is synchronous because Better Auth reads its options synchronously.
|
|
126
|
+
*/
|
|
127
|
+
function deriveAuthSecret(event) {
|
|
128
|
+
const env = {
|
|
129
|
+
...globalThis.process?.env,
|
|
130
|
+
...authCloudflareEnv(event)
|
|
131
|
+
};
|
|
132
|
+
if (betterAuthSecretNames.some((name) => env[name])) return void 0;
|
|
133
|
+
const root = readViteHubSecret(env);
|
|
134
|
+
if (!root) return void 0;
|
|
135
|
+
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\`.` });
|
|
136
|
+
if (derived?.root !== root) derived = {
|
|
137
|
+
root,
|
|
138
|
+
secret: hex(hkdfSync("sha256", root, viteHubSecretSalt, authSecretPurpose, 32))
|
|
139
|
+
};
|
|
140
|
+
return derived.secret;
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/event-plugin.ts
|
|
144
|
+
const authHandlerEvent = new AsyncLocalStorage();
|
|
145
|
+
/** Run a Better Auth handler with the request event that `events.authorize` gets. */
|
|
146
|
+
function runWithAuthEvent(event, run) {
|
|
147
|
+
return authHandlerEvent.run(event, run);
|
|
148
|
+
}
|
|
149
|
+
function record(value) {
|
|
150
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
151
|
+
}
|
|
152
|
+
function identifier(value) {
|
|
153
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : void 0;
|
|
154
|
+
}
|
|
155
|
+
function actor(ctx, fallback) {
|
|
156
|
+
const session = ctx?.context.session;
|
|
157
|
+
const id = identifier(session?.session.impersonatedBy) ?? session?.user.id ?? fallback;
|
|
158
|
+
return id ? `user:${id}` : "system";
|
|
159
|
+
}
|
|
160
|
+
function method(ctx) {
|
|
161
|
+
const path = ctx?.path ?? "";
|
|
162
|
+
const providers = ctx?.context.socialProviders ?? [];
|
|
163
|
+
const candidate = path.startsWith("/callback/") || path.startsWith("/oauth2/callback/") ? path.split("/").at(-1) : identifier(record(ctx?.body).provider);
|
|
164
|
+
if (candidate && providers.some((provider) => provider.id === candidate) && /^[a-zA-Z0-9_.-]+$/.test(candidate)) return `oauth:${candidate}`;
|
|
165
|
+
if (path === "/sign-in/email" || path === "/sign-up/email") return "email-password";
|
|
166
|
+
if (path.includes("/magic-link/verify")) return "magic-link";
|
|
167
|
+
if (path.includes("/passkey/verify-authentication")) return "passkey";
|
|
168
|
+
if (path.startsWith("/two-factor/")) return "two-factor";
|
|
169
|
+
if (path.includes("/siwe/")) return "siwe";
|
|
170
|
+
for (const name of [
|
|
171
|
+
"email-otp",
|
|
172
|
+
"username",
|
|
173
|
+
"phone-number",
|
|
174
|
+
"anonymous"
|
|
175
|
+
]) if (path === `/sign-in/${name}`) return name;
|
|
176
|
+
return "unknown";
|
|
177
|
+
}
|
|
178
|
+
/** Discard the raw agent string. IP addresses are never read. */
|
|
179
|
+
function authEventDevice(agent) {
|
|
180
|
+
if (!agent) return "unknown";
|
|
181
|
+
if (/bot|crawler|spider/i.test(agent)) return "bot";
|
|
182
|
+
if (/ipad|tablet/i.test(agent) || /android/i.test(agent) && !/mobile/i.test(agent)) return "tablet";
|
|
183
|
+
if (/mobi|iphone|ipod/i.test(agent)) return "mobile";
|
|
184
|
+
if (/windows|macintosh|linux|cros/i.test(agent)) return "desktop";
|
|
185
|
+
return "unknown";
|
|
186
|
+
}
|
|
187
|
+
/** Compose with Better Auth's own hook pipeline, including direct auth.api calls. */
|
|
188
|
+
function createAuthEventsPlugin(options) {
|
|
189
|
+
const deletionContext = new AsyncLocalStorage();
|
|
190
|
+
const outcomes = /* @__PURE__ */ new WeakMap();
|
|
191
|
+
const challenges = /* @__PURE__ */ new WeakSet();
|
|
192
|
+
const wrappedAdapters = /* @__PURE__ */ new WeakSet();
|
|
193
|
+
const createdSessions = /* @__PURE__ */ new WeakSet();
|
|
194
|
+
const recordedSessions = /* @__PURE__ */ new WeakSet();
|
|
195
|
+
async function append(type, userId, ctx, metadata = {}, fallback) {
|
|
196
|
+
const event = {
|
|
197
|
+
id: crypto.randomUUID(),
|
|
198
|
+
type,
|
|
199
|
+
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
200
|
+
actor: actor(ctx, fallback),
|
|
201
|
+
userId,
|
|
202
|
+
metadata
|
|
203
|
+
};
|
|
204
|
+
try {
|
|
205
|
+
await options.store.append(event);
|
|
206
|
+
} catch {
|
|
207
|
+
console.warn("[vitehub] AUTH_EVENT_WRITE_FAILED: Could not record an auth event.");
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
if (options.onEvent) await notify(options.onEvent, event, ctx);
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
/** Hand the callback to the host `waitUntil()` when it has one, so it does not delay the response. Else wait for it. */
|
|
214
|
+
async function notify(onEvent, event, ctx) {
|
|
215
|
+
const task = (async () => {
|
|
216
|
+
try {
|
|
217
|
+
await onEvent(event);
|
|
218
|
+
} catch (error) {
|
|
219
|
+
console.error(authErrorDiagnostics.AUTH_EVENT_CALLBACK_FAILED({
|
|
220
|
+
type: event.type,
|
|
221
|
+
cause: error
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
})();
|
|
225
|
+
const request = authHandlerEvent.getStore() ?? (ctx?.request ? authRequestEvent(ctx.request) : void 0);
|
|
226
|
+
const waitUntil = request ? getStandardContext(request).waitUntil : void 0;
|
|
227
|
+
if (waitUntil) try {
|
|
228
|
+
waitUntil(task);
|
|
229
|
+
return;
|
|
230
|
+
} catch {}
|
|
231
|
+
await task;
|
|
232
|
+
}
|
|
233
|
+
async function deleted(session, ctx) {
|
|
234
|
+
const type = ctx?.path === "/sign-out" ? "user.signed_out" : ctx?.path === "/admin/stop-impersonating" ? "impersonation.stopped" : "session.revoked";
|
|
235
|
+
await append(type, session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy) ?? (type === "user.signed_out" ? session.userId : void 0));
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
id: "vitehub-auth-events",
|
|
239
|
+
wrapStorage(storage) {
|
|
240
|
+
return {
|
|
241
|
+
get: (key) => storage.get(key),
|
|
242
|
+
set: (key, value, ttl) => storage.set(key, value, ttl),
|
|
243
|
+
getAndDelete: (key) => storage.getAndDelete(key),
|
|
244
|
+
increment: (key, ttl) => storage.increment(key, ttl),
|
|
245
|
+
async delete(key) {
|
|
246
|
+
const value = await storage.getAndDelete(key);
|
|
247
|
+
if (!value) return;
|
|
248
|
+
let parsed;
|
|
249
|
+
try {
|
|
250
|
+
parsed = typeof value === "string" ? JSON.parse(value) : value;
|
|
251
|
+
} catch {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const session = record(record(parsed).session);
|
|
255
|
+
const id = identifier(session.id);
|
|
256
|
+
const userId = identifier(session.userId);
|
|
257
|
+
if (id && userId && session.token === key) await deleted({
|
|
258
|
+
id,
|
|
259
|
+
userId,
|
|
260
|
+
impersonatedBy: session.impersonatedBy
|
|
261
|
+
}, deletionContext.getStore() ?? null);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
},
|
|
265
|
+
captureOutcome(ctx) {
|
|
266
|
+
const context = record(ctx).context;
|
|
267
|
+
if (context !== null && typeof context === "object") outcomes.set(context, record(context).returned);
|
|
268
|
+
},
|
|
269
|
+
init: () => ({ options: { databaseHooks: {
|
|
270
|
+
user: {
|
|
271
|
+
create: { async after(user, ctx) {
|
|
272
|
+
await append("user.signed_up", user.id, ctx, { method: method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
|
|
273
|
+
} },
|
|
274
|
+
update: { async after(user, ctx) {
|
|
275
|
+
const path = ctx?.path;
|
|
276
|
+
if (path === "/admin/ban-user") await append("user.banned", user.id, ctx);
|
|
277
|
+
else if (path === "/admin/unban-user") await append("user.unbanned", user.id, ctx);
|
|
278
|
+
else if (path === "/admin/set-role") await append("user.role_changed", user.id, ctx, { role: identifier(user.role) });
|
|
279
|
+
else if (path === "/admin/update-user") {
|
|
280
|
+
const data = record(record(ctx?.body).data);
|
|
281
|
+
const fields = Object.keys(data).filter((key) => /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/.test(key) && Object.hasOwn(user, key)).slice(0, 100);
|
|
282
|
+
await append("user.updated", user.id, ctx, { fields });
|
|
283
|
+
if (Object.hasOwn(data, "role")) await append("user.role_changed", user.id, ctx, { role: identifier(user.role) });
|
|
284
|
+
if (Object.hasOwn(data, "banned")) await append(user.banned ? "user.banned" : "user.unbanned", user.id, ctx);
|
|
285
|
+
}
|
|
286
|
+
} },
|
|
287
|
+
delete: { async after(user, ctx) {
|
|
288
|
+
await append("user.removed", user.id, ctx);
|
|
289
|
+
} }
|
|
290
|
+
},
|
|
291
|
+
session: {
|
|
292
|
+
create: { async after(session, ctx) {
|
|
293
|
+
createdSessions.add(session);
|
|
294
|
+
if (session.impersonatedBy || ctx?.path === "/admin/impersonate-user") {
|
|
295
|
+
if (await append("impersonation.started", session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy))) return;
|
|
296
|
+
await ctx?.context.internalAdapter.deleteSession(session.token);
|
|
297
|
+
throw new APIError$1("INTERNAL_SERVER_ERROR", {
|
|
298
|
+
code: "IMPERSONATION_NOT_RECORDED",
|
|
299
|
+
message: "Impersonation did not start because the auth event log could not record it."
|
|
300
|
+
});
|
|
301
|
+
} else if (!ctx) await append("user.signed_in", session.userId, ctx, {
|
|
302
|
+
method: method(ctx),
|
|
303
|
+
device: "unknown",
|
|
304
|
+
sessionId: session.id
|
|
305
|
+
});
|
|
306
|
+
} },
|
|
307
|
+
delete: { async after(session, ctx) {
|
|
308
|
+
await deleted(session, ctx);
|
|
309
|
+
} }
|
|
310
|
+
}
|
|
311
|
+
} } }),
|
|
312
|
+
hooks: {
|
|
313
|
+
before: [{
|
|
314
|
+
matcher: () => true,
|
|
315
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
316
|
+
if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
|
|
317
|
+
const cookie = ctx.context.createAuthCookie("two_factor");
|
|
318
|
+
const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
319
|
+
if (token && await ctx.context.internalAdapter.findVerificationValue(token)) challenges.add(ctx.context);
|
|
320
|
+
}
|
|
321
|
+
if (!ctx.context.options.secondaryStorage || ctx.context.options.session?.storeSessionInDatabase) return;
|
|
322
|
+
const adapter = ctx.context.internalAdapter;
|
|
323
|
+
ctx.context.internalAdapter = {
|
|
324
|
+
...adapter,
|
|
325
|
+
deleteSession: (token) => deletionContext.run(ctx, () => adapter.deleteSession(token)),
|
|
326
|
+
deleteSessions: (tokens) => deletionContext.run(ctx, () => adapter.deleteSessions(tokens)),
|
|
327
|
+
deleteUserSessions: (userId) => deletionContext.run(ctx, () => adapter.deleteUserSessions(userId))
|
|
328
|
+
};
|
|
329
|
+
})
|
|
330
|
+
}, {
|
|
331
|
+
matcher: (ctx) => Boolean(ctx.path?.startsWith("/oauth2/")),
|
|
332
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
333
|
+
const adapter = ctx.context.adapter;
|
|
334
|
+
if (wrappedAdapters.has(adapter)) return;
|
|
335
|
+
await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
336
|
+
async function consentEvent(type, value) {
|
|
337
|
+
const consent = record(value);
|
|
338
|
+
const userId = identifier(consent.userId);
|
|
339
|
+
const clientId = identifier(consent.clientId);
|
|
340
|
+
if (userId && clientId) await append(type, userId, ctx, { clientId });
|
|
341
|
+
}
|
|
342
|
+
ctx.context.adapter = {
|
|
343
|
+
...adapter,
|
|
344
|
+
async create(input) {
|
|
345
|
+
const result = await adapter.create(input);
|
|
346
|
+
if (input.model === "oauthConsent") await consentEvent("oauth.consent_granted", result);
|
|
347
|
+
return result;
|
|
348
|
+
},
|
|
349
|
+
async update(input) {
|
|
350
|
+
const result = await adapter.update(input);
|
|
351
|
+
if (input.model === "oauthConsent" && result) await consentEvent("oauth.consent_granted", result);
|
|
352
|
+
return result;
|
|
353
|
+
},
|
|
354
|
+
async delete(input) {
|
|
355
|
+
const consent = input.model === "oauthConsent" ? await adapter.findOne(input) : void 0;
|
|
356
|
+
await adapter.delete(input);
|
|
357
|
+
if (consent) await consentEvent("oauth.consent_revoked", consent);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
wrappedAdapters.add(ctx.context.adapter);
|
|
361
|
+
})
|
|
362
|
+
}],
|
|
363
|
+
after: [{
|
|
364
|
+
matcher: () => true,
|
|
365
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
366
|
+
const path = ctx.path ?? "";
|
|
367
|
+
const outcome = outcomes.get(ctx.context);
|
|
368
|
+
const value = record(outcome);
|
|
369
|
+
const signedIn = ctx.context.newSession;
|
|
370
|
+
if (signedIn && createdSessions.has(signedIn.session) && !signedIn.session.impersonatedBy && path !== "/admin/impersonate-user" && !recordedSessions.has(signedIn.session)) {
|
|
371
|
+
recordedSessions.add(signedIn.session);
|
|
372
|
+
await append("user.signed_in", signedIn.user.id, ctx, {
|
|
373
|
+
method: method(ctx),
|
|
374
|
+
device: authEventDevice(ctx.headers?.get("user-agent") ?? ctx.request?.headers.get("user-agent")),
|
|
375
|
+
sessionId: signedIn.session.id
|
|
376
|
+
}, signedIn.user.id);
|
|
377
|
+
}
|
|
378
|
+
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) });
|
|
379
|
+
if (outcome instanceof APIError$1) return;
|
|
380
|
+
if (path === "/admin/set-user-password") {
|
|
381
|
+
const userId = identifier(record(ctx.body).userId);
|
|
382
|
+
if (userId) {
|
|
383
|
+
await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
384
|
+
await append("user.updated", userId, ctx, { fields: ["password"] });
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const operationId = record(ctx).operationId;
|
|
388
|
+
const type = path === "/organization/remove-member" || path === "/organization/leave" ? "organization.member_removed" : path === "/organization/update-member-role" ? "organization.member_role_changed" : path === "/organization/accept-invitation" || operationId === "addOrganizationMember" || path === "/organization/create" ? "organization.member_added" : void 0;
|
|
389
|
+
if (!type) return;
|
|
390
|
+
if (!ctx.context.session) await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
391
|
+
const members = path === "/organization/create" && Array.isArray(value.members) ? value.members : [value.member ?? value];
|
|
392
|
+
for (const raw of members) {
|
|
393
|
+
const member = record(raw);
|
|
394
|
+
const userId = identifier(member.userId);
|
|
395
|
+
const organizationId = identifier(member.organizationId);
|
|
396
|
+
if (userId && organizationId) await append(type, userId, ctx, {
|
|
397
|
+
organizationId,
|
|
398
|
+
memberId: identifier(member.id),
|
|
399
|
+
role: identifier(member.role)
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
})
|
|
403
|
+
}]
|
|
404
|
+
},
|
|
405
|
+
endpoints: options.authorize ? { vitehubAuthEvents: createAuthEndpoint("/vitehub/events", {
|
|
406
|
+
method: "GET",
|
|
407
|
+
use: [sensitiveSessionMiddleware]
|
|
408
|
+
}, async (ctx) => {
|
|
409
|
+
if (!ctx.request) throw new APIError$1("FORBIDDEN");
|
|
410
|
+
const authorization = await options.authorize({
|
|
411
|
+
event: authHandlerEvent.getStore() ?? authRequestEvent(ctx.request),
|
|
412
|
+
request: ctx.request,
|
|
413
|
+
user: ctx.context.session.user,
|
|
414
|
+
session: ctx.context.session.session
|
|
415
|
+
});
|
|
416
|
+
if (authorization instanceof Response) return authorization;
|
|
417
|
+
if (authorization !== true) throw new APIError$1("FORBIDDEN");
|
|
418
|
+
ctx.setHeader("cache-control", "no-store");
|
|
419
|
+
const query = new URL(ctx.request.url).searchParams;
|
|
420
|
+
let list;
|
|
421
|
+
let window;
|
|
422
|
+
try {
|
|
423
|
+
if (query.get("aggregate") === "true") window = parseAuthEventWindow({
|
|
424
|
+
from: query.get("from") ?? "",
|
|
425
|
+
to: query.get("to") ?? ""
|
|
426
|
+
});
|
|
427
|
+
else {
|
|
428
|
+
const input = Object.fromEntries([...query].filter(([key]) => key !== "limit"));
|
|
429
|
+
list = parseAuthEventList({
|
|
430
|
+
...input,
|
|
431
|
+
...query.has("limit") ? { limit: Number(query.get("limit")) } : {}
|
|
432
|
+
}).query;
|
|
433
|
+
}
|
|
434
|
+
} catch {
|
|
435
|
+
throw new APIError$1("BAD_REQUEST", { message: "Invalid auth event filters." });
|
|
436
|
+
}
|
|
437
|
+
return ctx.json(window ? await options.store.aggregate(window) : await options.store.list(list));
|
|
438
|
+
}) } : {}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
//#endregion
|
|
442
|
+
//#region src/impersonation-plugin.ts
|
|
443
|
+
/**
|
|
444
|
+
* Better Auth endpoints that create a credential which outlives an impersonation session, change how the user signs
|
|
445
|
+
* in, or start another impersonation: OAuth, MCP, and device grants, API keys, passkeys, passwords, email and phone
|
|
446
|
+
* number changes, linked accounts, two-factor setup, and one-time tokens that open a new session.
|
|
447
|
+
*/
|
|
448
|
+
const credentialPaths = /* @__PURE__ */ new Set([
|
|
449
|
+
"/account-info",
|
|
450
|
+
"/admin/impersonate-user",
|
|
451
|
+
"/api-key/create",
|
|
452
|
+
"/api-key/update",
|
|
453
|
+
"/change-email",
|
|
454
|
+
"/change-password",
|
|
455
|
+
"/email-otp/change-email",
|
|
456
|
+
"/email-otp/request-email-change",
|
|
457
|
+
"/get-access-token",
|
|
458
|
+
"/link-social",
|
|
459
|
+
"/one-time-token/generate",
|
|
460
|
+
"/passkey/generate-register-options",
|
|
461
|
+
"/passkey/verify-registration",
|
|
462
|
+
"/phone-number/verify",
|
|
463
|
+
"/refresh-token",
|
|
464
|
+
"/two-factor/disable",
|
|
465
|
+
"/two-factor/enable",
|
|
466
|
+
"/two-factor/generate-backup-codes",
|
|
467
|
+
"/unlink-account"
|
|
468
|
+
]);
|
|
469
|
+
/** `/update-user` fields that change how the user signs in. The username plugin sets `username` from `displayUsername`. */
|
|
470
|
+
const identityFields = ["displayUsername", "username"];
|
|
471
|
+
const credentialPrefixes = [
|
|
472
|
+
"/device/",
|
|
473
|
+
"/mcp/",
|
|
474
|
+
"/oauth2/"
|
|
475
|
+
];
|
|
476
|
+
/** Reads below those prefixes. They show the user's grants and clients, so a support view still works. */
|
|
477
|
+
const grantReads = /^\/oauth2\/(?:get-|public-client|userinfo)|^\/mcp\/get-session$/;
|
|
478
|
+
function createsCredential(path, body) {
|
|
479
|
+
if (!path) return false;
|
|
480
|
+
if (path === "/update-user") return typeof body === "object" && body !== null && identityFields.some((field) => field in body);
|
|
481
|
+
return credentialPaths.has(path) || credentialPrefixes.some((prefix) => path.startsWith(prefix)) && !grantReads.test(path);
|
|
482
|
+
}
|
|
483
|
+
/** The current expiry of the request's impersonation session, when the update would move it later. */
|
|
484
|
+
function keptExpiry(...[data, endpoint]) {
|
|
485
|
+
const current = endpoint?.context.session?.session;
|
|
486
|
+
if (!current?.impersonatedBy || !data.expiresAt) return;
|
|
487
|
+
if (new Date(data.expiresAt).getTime() > new Date(current.expiresAt).getTime()) return current.expiresAt;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Better Auth runs the app's database hooks after plugin hooks and gives each hook the original update. An app
|
|
491
|
+
* `session.update.before` that returns `{ data: { ...data } }` would restore the refreshed expiry, so its result
|
|
492
|
+
* keeps the impersonation expiry too.
|
|
493
|
+
*/
|
|
494
|
+
function withImpersonationExpiry(hooks) {
|
|
495
|
+
const before = hooks?.session?.update?.before;
|
|
496
|
+
if (!before) return hooks;
|
|
497
|
+
return {
|
|
498
|
+
...hooks,
|
|
499
|
+
session: {
|
|
500
|
+
...hooks.session,
|
|
501
|
+
update: {
|
|
502
|
+
...hooks.session?.update,
|
|
503
|
+
async before(data, endpoint) {
|
|
504
|
+
const result = await before(data, endpoint);
|
|
505
|
+
if (typeof result !== "object") return result;
|
|
506
|
+
const expiresAt = keptExpiry({
|
|
507
|
+
...data,
|
|
508
|
+
...result.data
|
|
509
|
+
}, endpoint);
|
|
510
|
+
return expiresAt ? { data: {
|
|
511
|
+
...result.data,
|
|
512
|
+
expiresAt
|
|
513
|
+
} } : result;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Keeps a Better Auth admin impersonation session inside its bounds. The session never gets a later expiry, and it
|
|
521
|
+
* cannot create credentials, change how the user signs in, or start another impersonation. ViteHub adds this plugin
|
|
522
|
+
* with the admin plugin.
|
|
523
|
+
*/
|
|
524
|
+
function createImpersonationPlugin() {
|
|
525
|
+
return {
|
|
526
|
+
id: "vitehub-impersonation",
|
|
527
|
+
init: () => ({ options: { databaseHooks: { session: { update: { async before(data, endpoint) {
|
|
528
|
+
const expiresAt = keptExpiry(data, endpoint);
|
|
529
|
+
if (expiresAt) return { data: { expiresAt } };
|
|
530
|
+
} } } } } }),
|
|
531
|
+
hooks: { before: [{
|
|
532
|
+
matcher: (ctx) => "operationId" in ctx && ctx.operationId === "setPassword" || createsCredential(ctx.path, ctx.body),
|
|
533
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
534
|
+
if (!(await getSessionFromCtx(ctx, { disableRefresh: true }))?.session.impersonatedBy) return;
|
|
535
|
+
throw new APIError$1("FORBIDDEN", {
|
|
536
|
+
code: "IMPERSONATION_FORBIDDEN",
|
|
537
|
+
message: "An impersonation session cannot create credentials, change how the user signs in, or start another impersonation. Stop impersonating first."
|
|
538
|
+
});
|
|
539
|
+
})
|
|
540
|
+
}] }
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
//#endregion
|
|
544
|
+
//#region src/client-address.ts
|
|
545
|
+
/**
|
|
546
|
+
* Better Auth reads the client IP for its rate limiter and for `session.ipAddress` only from request headers. Auth puts
|
|
547
|
+
* the address that the host reports in this header and removes any value that a client sends, at every entry of the
|
|
548
|
+
* Better Auth instances that it creates: `handler` and each `api` endpoint.
|
|
549
|
+
*/
|
|
550
|
+
const clientAddressHeader = "x-vitehub-client-address";
|
|
551
|
+
/** The addresses that `handleAuthRequest()` read from the request event, for the Request that it passes to Better Auth. */
|
|
552
|
+
const eventAddresses = /* @__PURE__ */ new WeakMap();
|
|
553
|
+
function readString(value, path) {
|
|
554
|
+
let current = value;
|
|
555
|
+
for (const key of path) {
|
|
556
|
+
if (current === null || typeof current !== "object" && typeof current !== "function") return void 0;
|
|
557
|
+
current = Reflect.get(current, key);
|
|
558
|
+
}
|
|
559
|
+
return typeof current === "string" && current ? current : void 0;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* The client IP address that the host reports for a request event: Standard Context `runtime.clientAddress`, which is
|
|
563
|
+
* `cf-connecting-ip` on Cloudflare and the peer address on Node. Forwarding headers such as `X-Forwarded-For` are
|
|
564
|
+
* not read.
|
|
565
|
+
*/
|
|
566
|
+
function eventClientAddress(event) {
|
|
567
|
+
return readString(event, [
|
|
568
|
+
"~standard",
|
|
569
|
+
"runtime",
|
|
570
|
+
"clientAddress"
|
|
571
|
+
]);
|
|
572
|
+
}
|
|
573
|
+
/** Remember the host address of a Request that Auth passes to Better Auth. */
|
|
574
|
+
function setRequestClientAddress(request, address) {
|
|
575
|
+
if (address) eventAddresses.set(request, address);
|
|
576
|
+
return request;
|
|
577
|
+
}
|
|
578
|
+
/** Return the request with only the host address in {@link clientAddressHeader}. srvx adds that address as `ip`. */
|
|
579
|
+
function addressedRequest(request) {
|
|
580
|
+
const address = eventAddresses.get(request) ?? readString(request, ["ip"]);
|
|
581
|
+
if (request.headers.get("x-vitehub-client-address") === (address ?? null)) return request;
|
|
582
|
+
const headers = new Headers(request.headers);
|
|
583
|
+
if (address) headers.set(clientAddressHeader, address);
|
|
584
|
+
else headers.delete(clientAddressHeader);
|
|
585
|
+
const init = {
|
|
586
|
+
headers,
|
|
587
|
+
method: request.method,
|
|
588
|
+
redirect: request.redirect,
|
|
589
|
+
signal: request.signal
|
|
590
|
+
};
|
|
591
|
+
if (request.body) {
|
|
592
|
+
init.body = request.body;
|
|
593
|
+
init.duplex = "half";
|
|
594
|
+
}
|
|
595
|
+
return new Request(request.url, init);
|
|
596
|
+
}
|
|
597
|
+
/** Headers of an `api` call have no host address, so remove a value that the caller copied from client headers. */
|
|
598
|
+
function withoutClientAddress(input) {
|
|
599
|
+
if (!input || typeof input !== "object") return input;
|
|
600
|
+
let result = input;
|
|
601
|
+
if (input.headers) {
|
|
602
|
+
const headers = new Headers(input.headers);
|
|
603
|
+
if (headers.has("x-vitehub-client-address")) {
|
|
604
|
+
headers.delete(clientAddressHeader);
|
|
605
|
+
result = {
|
|
606
|
+
...result,
|
|
607
|
+
headers
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const request = input.request;
|
|
612
|
+
if (request && typeof request.url === "string" && typeof request.headers?.get === "function") {
|
|
613
|
+
const addressed = addressedRequest(request);
|
|
614
|
+
if (addressed !== request) result = {
|
|
615
|
+
...result,
|
|
616
|
+
request: addressed
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
return result;
|
|
620
|
+
}
|
|
621
|
+
/** Give Better Auth the host address of each handler request, and only that address. */
|
|
622
|
+
function withClientAddress(auth) {
|
|
623
|
+
const handler = auth.handler;
|
|
624
|
+
const addressedHandler = (request) => handler(addressedRequest(request));
|
|
625
|
+
const originalApi = Object.getOwnPropertyDescriptor(auth, "api")?.value;
|
|
626
|
+
if (originalApi) auth.api = Object.fromEntries(Object.entries(originalApi).map(([name, endpoint]) => [name, Object.assign((input, ...rest) => Reflect.apply(endpoint, originalApi, [withoutClientAddress(input), ...rest]), endpoint)]));
|
|
627
|
+
return Object.assign(auth, {
|
|
628
|
+
handler: addressedHandler,
|
|
629
|
+
fetch: addressedHandler
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
//#endregion
|
|
633
|
+
//#region src/session-refresh.ts
|
|
634
|
+
/**
|
|
635
|
+
* Runs `session.onRefresh` from the Better Auth `session.update.before` database hook.
|
|
636
|
+
* Better Auth calls `updateSession(token, { expiresAt, updatedAt })` when a stored session
|
|
637
|
+
* passes `session.updateAge`. No other built-in session update sets `expiresAt`.
|
|
638
|
+
*/
|
|
639
|
+
function createSessionRefreshPlugin(onRefresh) {
|
|
640
|
+
return {
|
|
641
|
+
id: "vitehub-session-refresh",
|
|
642
|
+
init: () => ({ options: { databaseHooks: { session: { update: { async before(data, endpoint) {
|
|
643
|
+
const current = endpoint?.context.session;
|
|
644
|
+
if (!current || !Object.hasOwn(data, "expiresAt")) return;
|
|
645
|
+
const result = { outcome: { kind: "skip" } };
|
|
646
|
+
await onRefresh({
|
|
647
|
+
session: current.session,
|
|
648
|
+
user: current.user,
|
|
649
|
+
refresh: (fields) => {
|
|
650
|
+
if (result.outcome.kind !== "clear") result.outcome = {
|
|
651
|
+
fields,
|
|
652
|
+
kind: "refresh"
|
|
653
|
+
};
|
|
654
|
+
},
|
|
655
|
+
clear: () => {
|
|
656
|
+
result.outcome = { kind: "clear" };
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
const { outcome } = result;
|
|
660
|
+
if (outcome.kind === "refresh") return outcome.fields ? { data: outcome.fields } : void 0;
|
|
661
|
+
if (outcome.kind === "skip") return { data: { expiresAt: current.session.expiresAt } };
|
|
662
|
+
await endpoint.context.internalAdapter.deleteSession(current.session.token);
|
|
663
|
+
return false;
|
|
664
|
+
} } } } } })
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/options-key.ts
|
|
669
|
+
const valueIds = /* @__PURE__ */ new WeakMap();
|
|
670
|
+
let nextValueId = 0;
|
|
671
|
+
function identityKey(value) {
|
|
672
|
+
let id = valueIds.get(value);
|
|
673
|
+
if (id === void 0) valueIds.set(value, id = nextValueId++);
|
|
674
|
+
return `#${id}`;
|
|
675
|
+
}
|
|
676
|
+
function isPlainData(value) {
|
|
677
|
+
const prototype = Object.getPrototypeOf(value);
|
|
678
|
+
return Array.isArray(value) ? prototype === Array.prototype : prototype === Object.prototype || prototype === null;
|
|
679
|
+
}
|
|
680
|
+
/** Write the key of `value` to `parts`. Returns false for a value that gives no key. */
|
|
681
|
+
function writeKey(value, parts, parents) {
|
|
682
|
+
if (typeof value === "symbol") return false;
|
|
683
|
+
if (typeof value === "string") {
|
|
684
|
+
parts.push(JSON.stringify(value));
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") {
|
|
688
|
+
parts.push(`${typeof value}:${String(value)}`);
|
|
689
|
+
return true;
|
|
690
|
+
}
|
|
691
|
+
const descriptors = isPlainData(value) && !parents.has(value) ? Object.getOwnPropertyDescriptors(value) : void 0;
|
|
692
|
+
if (!descriptors || Object.getOwnPropertySymbols(descriptors).length > 0 || Object.values(descriptors).some((descriptor) => !("value" in descriptor))) {
|
|
693
|
+
parts.push(identityKey(value));
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
parents.add(value);
|
|
697
|
+
parts.push(Array.isArray(value) ? "[" : "{");
|
|
698
|
+
for (const [name, descriptor] of Object.entries(descriptors)) {
|
|
699
|
+
parts.push(JSON.stringify(name), ":");
|
|
700
|
+
if (!writeKey(descriptor.value, parts, parents)) return false;
|
|
701
|
+
parts.push(",");
|
|
702
|
+
}
|
|
703
|
+
parts.push(Array.isArray(value) ? "]" : "}");
|
|
704
|
+
parents.delete(value);
|
|
705
|
+
return true;
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* A key that is equal only for values that Better Auth gets as equal options. Plain objects and arrays compare by
|
|
709
|
+
* value. Functions, class instances, and bindings compare by identity, so a value that one request creates, such as an
|
|
710
|
+
* adapter for its Cloudflare bindings, never gives its instance to another request. A symbol gives no key.
|
|
711
|
+
*/
|
|
712
|
+
function optionsKey(value) {
|
|
713
|
+
const parts = [];
|
|
714
|
+
return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
|
|
715
|
+
}
|
|
716
|
+
//#endregion
|
|
717
|
+
//#region src/runtime-options.ts
|
|
718
|
+
/** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
|
|
719
|
+
function isAuthDatabasePlacement(value) {
|
|
720
|
+
return typeof value === "boolean" || isRecord(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key === "dedicated" || key === "name");
|
|
721
|
+
}
|
|
722
|
+
/** `true` or `{ store }`: the removed placement form, which is not a Better Auth adapter. */
|
|
723
|
+
function isAuthSecondaryStoragePlacement(value) {
|
|
724
|
+
return typeof value === "boolean" || isRecord(value) && Object.hasOwn(value, "store") && Object.keys(value).every((key) => key === "store");
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Without a database, Better Auth keeps users and sessions in the memory of one instance. Auth creates an instance for
|
|
728
|
+
* each set of resolved options, so the instances of one Auth Definition share these tables. A restart still removes them.
|
|
729
|
+
*/
|
|
730
|
+
function sharedMemoryDatabase(definition) {
|
|
731
|
+
const state = getAuthRuntimeState();
|
|
732
|
+
const databases = getViteHubTestMode()?.backend("auth", () => /* @__PURE__ */ new WeakMap(), resetAuth) ?? (state.memoryDatabases ??= /* @__PURE__ */ new WeakMap());
|
|
733
|
+
const tables = databases.get(definition) ?? {};
|
|
734
|
+
databases.set(definition, tables);
|
|
735
|
+
const database = (options) => {
|
|
736
|
+
for (const { modelName } of Object.values(getAuthTables(options))) tables[modelName] ??= [];
|
|
737
|
+
return memoryAdapter(tables)(options);
|
|
738
|
+
};
|
|
739
|
+
return Object.assign(database, { [authProcessMemoryDatabase]: true });
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* True on a development server. The Auth Vite plugin sets `__VITEHUB_AUTH_DEV__` in the server bundle: `true` for
|
|
743
|
+
* `vite dev` and a Nitro dev server, `false` for a build. A Cloudflare Worker has no `NODE_ENV`, so the flag decides there.
|
|
744
|
+
*/
|
|
745
|
+
function isDevelopmentServer() {
|
|
746
|
+
if (typeof __VITEHUB_AUTH_DEV__ === "boolean") return __VITEHUB_AUTH_DEV__;
|
|
747
|
+
if (getViteHubTestMode()) return true;
|
|
748
|
+
const mode = globalThis.process?.env?.NODE_ENV;
|
|
749
|
+
return mode === "development" || mode === "test";
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Better Auth turns its limiter on only when `NODE_ENV` is `production`, and keeps its counters in the memory of the
|
|
753
|
+
* process unless a `secondaryStorage` is set. Auth turns it on outside a development server, and keeps the counters in
|
|
754
|
+
* the app Database of `authDatabase()`, where every instance and every Auth built for a request sees them.
|
|
755
|
+
*/
|
|
756
|
+
function withRateLimitDefaults(options, ownsDatabase) {
|
|
757
|
+
const rateLimit = options.rateLimit;
|
|
758
|
+
const database = ownsDatabase && !rateLimit?.storage && !rateLimit?.customStorage && !options.secondaryStorage;
|
|
759
|
+
return {
|
|
760
|
+
...rateLimit,
|
|
761
|
+
enabled: rateLimit?.enabled ?? !isDevelopmentServer(),
|
|
762
|
+
...database ? { storage: "database" } : {}
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* 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.
|
|
769
|
+
*/
|
|
770
|
+
function withClientAddressHeaders(advanced) {
|
|
771
|
+
if (advanced?.ipAddress?.ipAddressHeaders) return advanced;
|
|
772
|
+
const ipAddressHeaders = advanced?.trustedProxyHeaders ? ["x-forwarded-for", clientAddressHeader] : [clientAddressHeader];
|
|
773
|
+
return {
|
|
774
|
+
...advanced,
|
|
775
|
+
ipAddress: {
|
|
776
|
+
...advanced?.ipAddress,
|
|
777
|
+
ipAddressHeaders
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
const betterAuthSetupVariables = [
|
|
782
|
+
"AUTH_SECRET",
|
|
783
|
+
"BETTER_AUTH_SECRET",
|
|
784
|
+
"BETTER_AUTH_SECRETS",
|
|
785
|
+
"BETTER_AUTH_TRUSTED_ORIGINS"
|
|
786
|
+
];
|
|
787
|
+
/**
|
|
788
|
+
* The environment values that an instance for these options uses. Auth reads a value only when the options use it, so
|
|
789
|
+
* the instance key and the instance read the same values, and a value that the options replace cannot fail a request.
|
|
790
|
+
*/
|
|
791
|
+
function readProviderEnvironment(options, event) {
|
|
792
|
+
const env = {
|
|
793
|
+
...globalThis.process?.env,
|
|
794
|
+
...authCloudflareEnv(event)
|
|
795
|
+
};
|
|
796
|
+
return {
|
|
797
|
+
admins: readAdmins(event),
|
|
798
|
+
members: readMembers(event),
|
|
799
|
+
adminClaim: options.adminClaim === false ? void 0 : readAdminClaim(event),
|
|
800
|
+
secret: Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets") ? void 0 : deriveAuthSecret(event),
|
|
801
|
+
betterAuth: betterAuthSetupVariables.map((name) => env[name] ?? null)
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
function stripViteHubOptions(definition, options, environment) {
|
|
805
|
+
const { access, adminClaim: _adminClaim, console: _console, database, events, route: _route, secondaryStorage, ...rest } = applyAuthPreset(options);
|
|
806
|
+
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." });
|
|
807
|
+
if (isAuthSecondaryStoragePlacement(secondaryStorage)) throw authErrorDiagnostics.AUTH_C0062({ message: "Auth `secondaryStorage` must be a Better Auth adapter. `true` and `{ store }` do not create storage." });
|
|
808
|
+
const memory = database === "memory";
|
|
809
|
+
const storage = {
|
|
810
|
+
...database && !memory ? { database } : {},
|
|
811
|
+
...secondaryStorage ? { secondaryStorage } : {}
|
|
812
|
+
};
|
|
813
|
+
if (authDatabaseName(database) !== void 0) {
|
|
814
|
+
assertAuthDatabaseIdStrategy(rest.advanced?.database?.generateId);
|
|
815
|
+
assertAuthDatabaseNames(rest);
|
|
816
|
+
}
|
|
817
|
+
validateAuthEvents(events);
|
|
818
|
+
const sessionRefresh = withSessionRefresh(rest, Boolean(storage.database || storage.secondaryStorage));
|
|
819
|
+
if (!storage.database && options.preset === void 0) {
|
|
820
|
+
if (!memory && !isDevelopmentServer()) throw authMemoryDatabaseError();
|
|
821
|
+
storage.database = sharedMemoryDatabase(definition);
|
|
822
|
+
}
|
|
823
|
+
const policy = isRecord(access) ? access.policy : void 0;
|
|
824
|
+
validateAuthAccessPolicy(policy);
|
|
825
|
+
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." });
|
|
826
|
+
const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
|
|
827
|
+
const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
|
|
828
|
+
const { admins, adminClaim, members } = environment;
|
|
829
|
+
assertMembersSessionStore(members, Boolean(storage.database || storage.secondaryStorage));
|
|
830
|
+
const membersGate = members.length ? createMembersGate(members, admins, declaredPlugins) : void 0;
|
|
831
|
+
const adminsPlugin = admins.length ? createAdminsPlugin(admins, declaredPlugins) : void 0;
|
|
832
|
+
const adminClaimPlugin = adminClaim ? createAdminClaimPlugin(adminClaim, declaredPlugins) : void 0;
|
|
833
|
+
const plugins = [
|
|
834
|
+
...declaredPlugins,
|
|
835
|
+
...impersonation ? [createImpersonationPlugin()] : [],
|
|
836
|
+
...adminsPlugin ? [adminsPlugin] : [],
|
|
837
|
+
...adminClaimPlugin ? [adminClaimPlugin] : [],
|
|
838
|
+
...policy || membersGate ? [createAccessPolicyPlugin({
|
|
839
|
+
policy,
|
|
840
|
+
members: membersGate
|
|
841
|
+
})] : []
|
|
842
|
+
];
|
|
843
|
+
const databaseHooks = impersonation ? withImpersonationExpiry(rest.databaseHooks) : rest.databaseHooks;
|
|
844
|
+
const eventPlugin = events ? createAuthEventsPlugin(events) : void 0;
|
|
845
|
+
const rateLimit = withRateLimitDefaults({
|
|
846
|
+
rateLimit: rest.rateLimit,
|
|
847
|
+
secondaryStorage: storage.secondaryStorage
|
|
848
|
+
}, authDatabaseName(database) !== void 0);
|
|
849
|
+
if (eventPlugin && storage.secondaryStorage && !rest.session?.storeSessionInDatabase) storage.secondaryStorage = eventPlugin.wrapStorage(storage.secondaryStorage);
|
|
850
|
+
const after = rest.hooks?.after ?? createAuthMiddleware(async () => {});
|
|
851
|
+
return {
|
|
852
|
+
...rest,
|
|
853
|
+
...storage,
|
|
854
|
+
...sessionRefresh,
|
|
855
|
+
...membersGate ? { socialProviders: withMemberScopes(members, rest.socialProviders) } : {},
|
|
856
|
+
...adminClaimPlugin ? { verification: {
|
|
857
|
+
...rest.verification,
|
|
858
|
+
storeInDatabase: true
|
|
859
|
+
} } : {},
|
|
860
|
+
...databaseHooks ? { databaseHooks } : {},
|
|
861
|
+
plugins: eventPlugin ? [...plugins, eventPlugin] : plugins,
|
|
862
|
+
advanced: withClientAddressHeaders(rest.advanced),
|
|
863
|
+
rateLimit,
|
|
864
|
+
...eventPlugin ? { hooks: {
|
|
865
|
+
...rest.hooks,
|
|
866
|
+
after: Object.assign(async (...args) => {
|
|
867
|
+
eventPlugin.captureOutcome(args[0]);
|
|
868
|
+
return after(...args);
|
|
869
|
+
}, after)
|
|
870
|
+
} } : {},
|
|
871
|
+
basePath: resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0))
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
/** Moves `session.onRefresh` into a Better Auth plugin, because Better Auth does not read it. */
|
|
875
|
+
function withSessionRefresh(options, hasSessionStore) {
|
|
876
|
+
const session = options.session;
|
|
877
|
+
if (!session?.onRefresh) return {};
|
|
878
|
+
if (typeof session.onRefresh !== "function") throw authErrorDiagnostics.AUTH_C0041({ message: "`defineAuth()` session.onRefresh must be a function." });
|
|
879
|
+
if (!hasSessionStore) throw authErrorDiagnostics.AUTH_C0042({ message: "`defineAuth()` session.onRefresh needs a Better Auth `database` or `secondaryStorage` adapter. Better Auth refreshes a stateless cookie cache without a hook." });
|
|
880
|
+
const { onRefresh, ...betterAuthSession } = session;
|
|
881
|
+
return {
|
|
882
|
+
plugins: [...options.plugins ?? [], createSessionRefreshPlugin(onRefresh)],
|
|
883
|
+
session: betterAuthSession
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
/** Without a configured secret, Better Auth signs with the secret derived from `VITEHUB_SECRET`. */
|
|
887
|
+
function withDerivedSecret(options, { secret }) {
|
|
888
|
+
return secret ? {
|
|
889
|
+
...options,
|
|
890
|
+
secret
|
|
891
|
+
} : options;
|
|
892
|
+
}
|
|
893
|
+
function trustsProxyHeaders(options) {
|
|
894
|
+
return isRecord(options) && isRecord(options.advanced) && options.advanced.trustedProxyHeaders === true;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Resolves one coherent option snapshot before projecting it for Better Auth or host callers. The options come from one
|
|
898
|
+
* place: the static Definition object, or the object that the Definition callback returns.
|
|
899
|
+
*/
|
|
900
|
+
function resolveAuthOptions(definition, input = {}) {
|
|
901
|
+
const { request } = input;
|
|
902
|
+
const callback = typeof definition.options === "function";
|
|
903
|
+
const usesContext = !request || callback;
|
|
904
|
+
const env = usesContext ? input.env?.(input.event) ?? {} : {};
|
|
905
|
+
const requestUrlOrigin = request ? new URL(request.url).origin : void 0;
|
|
906
|
+
const proxiedOrigin = request ? forwardedRequestOrigin(request) : void 0;
|
|
907
|
+
const resolveAt = (origin) => {
|
|
908
|
+
const context = {
|
|
909
|
+
env,
|
|
910
|
+
...request ? { request } : {},
|
|
911
|
+
requestOrigin: usesContext && origin ? origin : "http://localhost"
|
|
912
|
+
};
|
|
913
|
+
const declared = callback ? definition.options(context) : definition.options;
|
|
914
|
+
if (callback) assertNoRuntimeOption(declared);
|
|
915
|
+
return {
|
|
916
|
+
declared,
|
|
917
|
+
trusted: trustsProxyHeaders(declared)
|
|
918
|
+
};
|
|
919
|
+
};
|
|
920
|
+
let resolved = resolveAt(requestUrlOrigin);
|
|
921
|
+
if (request && callback && resolved.trusted && proxiedOrigin !== requestUrlOrigin) {
|
|
922
|
+
const forwarded = resolveAt(proxiedOrigin);
|
|
923
|
+
resolved = forwarded.trusted ? forwarded : {
|
|
924
|
+
trusted: false,
|
|
925
|
+
declared: {
|
|
926
|
+
...resolved.declared,
|
|
927
|
+
advanced: {
|
|
928
|
+
...resolved.declared.advanced,
|
|
929
|
+
trustedProxyHeaders: false
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
const { declared, trusted } = resolved;
|
|
935
|
+
let requestRuntimeOptions = callback ? declared : {};
|
|
936
|
+
if (request) {
|
|
937
|
+
const requestOrigin = trusted && proxiedOrigin ? proxiedOrigin : request.url;
|
|
938
|
+
const baseURL = requestRuntimeOptions.baseURL || resolvePublicUrl({ request: { url: requestOrigin } });
|
|
939
|
+
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.` });
|
|
940
|
+
requestRuntimeOptions = {
|
|
941
|
+
...!Object.hasOwn(declared, "trustedOrigins") ? { trustedOrigins: [baseURL] } : {},
|
|
942
|
+
...requestRuntimeOptions,
|
|
943
|
+
baseURL
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
let snapshot;
|
|
947
|
+
const resolveSnapshot = () => snapshot ??= callback ? requestRuntimeOptions : {
|
|
948
|
+
...declared,
|
|
949
|
+
...requestRuntimeOptions
|
|
950
|
+
};
|
|
951
|
+
let environment;
|
|
952
|
+
const resolveEnvironment = () => environment ??= readProviderEnvironment(resolveSnapshot(), input.event);
|
|
953
|
+
return {
|
|
954
|
+
get options() {
|
|
955
|
+
return resolveSnapshot();
|
|
956
|
+
},
|
|
957
|
+
get providerOptions() {
|
|
958
|
+
const options = resolveSnapshot();
|
|
959
|
+
const environment = resolveEnvironment();
|
|
960
|
+
return withDerivedSecret(withPasswordHasher(stripViteHubOptions(definition, options, environment)), environment);
|
|
961
|
+
},
|
|
962
|
+
/** Equal for two resolutions of this Definition that give Better Auth equal options, else `undefined`. */
|
|
963
|
+
get providerKey() {
|
|
964
|
+
const snapshot = resolveSnapshot();
|
|
965
|
+
const database = authDatabaseName(snapshot.database);
|
|
966
|
+
return optionsKey([
|
|
967
|
+
database === void 0 ? snapshot : {
|
|
968
|
+
...snapshot,
|
|
969
|
+
database: void 0
|
|
970
|
+
},
|
|
971
|
+
database ?? null,
|
|
972
|
+
resolveEnvironment()
|
|
973
|
+
]);
|
|
974
|
+
},
|
|
975
|
+
requestRuntimeOptions
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
//#endregion
|
|
979
|
+
//#region src/session-marker.ts
|
|
980
|
+
/**
|
|
981
|
+
* Name of the cookie that tells browser code a session exists. It holds `1`, never a secret, and it is not HttpOnly,
|
|
982
|
+
* so a page script can skip a session request for a visitor who never signed in. It does not prove a session:
|
|
983
|
+
* the server still decides.
|
|
984
|
+
*/
|
|
985
|
+
const authSessionMarkerCookie = viteHubSessionMarkerCookie;
|
|
986
|
+
const markerAttributes = [
|
|
987
|
+
"domain",
|
|
988
|
+
"expires",
|
|
989
|
+
"max-age",
|
|
990
|
+
"path",
|
|
991
|
+
"samesite",
|
|
992
|
+
"partitioned"
|
|
993
|
+
];
|
|
994
|
+
function requestSource(input) {
|
|
995
|
+
if (isRequestLike(input)) return input;
|
|
996
|
+
if (isRequestLike(input?.request)) return input.request;
|
|
997
|
+
const headers = new Headers(input?.headers);
|
|
998
|
+
return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
|
|
999
|
+
}
|
|
1000
|
+
/** The value of one cookie in the request of an API call or a handler request. */
|
|
1001
|
+
function requestCookie(input, name) {
|
|
1002
|
+
const headers = isRequestLike(input) ? input.headers : input?.headers ? new Headers(input.headers) : input?.request?.headers;
|
|
1003
|
+
for (const part of headers?.get("cookie")?.split(";") ?? []) {
|
|
1004
|
+
const separator = part.indexOf("=");
|
|
1005
|
+
if (separator !== -1 && part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function readSetCookie(cookie) {
|
|
1009
|
+
const [pair = "", ...rest] = cookie.split(";").map((part) => part.trim());
|
|
1010
|
+
const separator = pair.indexOf("=");
|
|
1011
|
+
const name = separator < 0 ? pair : pair.slice(0, separator);
|
|
1012
|
+
const value = separator < 0 ? "" : pair.slice(separator + 1);
|
|
1013
|
+
const attributes = rest.filter((part) => {
|
|
1014
|
+
const key = part.split("=", 1)[0].toLowerCase();
|
|
1015
|
+
return key === "secure" || markerAttributes.includes(key);
|
|
1016
|
+
});
|
|
1017
|
+
const maxAge = rest.find((part) => part.toLowerCase().startsWith("max-age="))?.slice(8);
|
|
1018
|
+
const expires = rest.find((part) => part.toLowerCase().startsWith("expires="))?.slice(8);
|
|
1019
|
+
const expired = maxAge !== void 0 && Number(maxAge) <= 0 || maxAge === void 0 && expires !== void 0 && Date.parse(expires) <= Date.now();
|
|
1020
|
+
return {
|
|
1021
|
+
attributes,
|
|
1022
|
+
cleared: !value || expired,
|
|
1023
|
+
name,
|
|
1024
|
+
value
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Sets `vitehub_session` next to the session cookie with the same lifetime, path, domain, and SameSite, and clears it
|
|
1029
|
+
* when Better Auth clears the session cookie, such as on sign-out. When a session starts or ends, it also clears the
|
|
1030
|
+
* `vitehub-tools` hint of the page tools, so the next page asks the session route again for the new person: a person
|
|
1031
|
+
* that a page tool, such as the Console, allows gets the ViteHub tools pill right after sign-in. A session refresh
|
|
1032
|
+
* keeps the same session token and keeps the hint.
|
|
1033
|
+
*/
|
|
1034
|
+
function withSessionMarker(auth) {
|
|
1035
|
+
async function markHeaders(original, input) {
|
|
1036
|
+
const setCookies = readSetCookies(original);
|
|
1037
|
+
if (setCookies.length === 0) return;
|
|
1038
|
+
const context = await auth.$context;
|
|
1039
|
+
const options = context.options;
|
|
1040
|
+
let sessionCookie = context.authCookies.sessionToken.name;
|
|
1041
|
+
if (typeof options.baseURL === "object" && options.advanced?.crossSubDomainCookies?.enabled) {
|
|
1042
|
+
const baseURL = resolveBaseURL(options.baseURL, options.basePath || "/api/auth", requestSource(input), void 0, options.advanced.trustedProxyHeaders ?? false);
|
|
1043
|
+
sessionCookie = getCookies({
|
|
1044
|
+
...options,
|
|
1045
|
+
baseURL
|
|
1046
|
+
}).sessionToken.name;
|
|
1047
|
+
}
|
|
1048
|
+
const session = setCookies.map(readSetCookie).findLast((cookie) => cookie.name === sessionCookie);
|
|
1049
|
+
if (!session) return;
|
|
1050
|
+
const marker = [
|
|
1051
|
+
`${authSessionMarkerCookie}=${session.cleared ? "" : "1"}`,
|
|
1052
|
+
...session.attributes,
|
|
1053
|
+
...session.cleared ? ["Max-Age=0"] : []
|
|
1054
|
+
].join("; ");
|
|
1055
|
+
const changed = session.cleared || session.value !== requestCookie(input, sessionCookie);
|
|
1056
|
+
const headers = new Headers(original);
|
|
1057
|
+
headers.delete("set-cookie");
|
|
1058
|
+
for (const cookie of setCookies) if (!cookie.startsWith(`${authSessionMarkerCookie}=`) && !(changed && cookie.startsWith(`vitehub-tools=`))) headers.append("set-cookie", cookie);
|
|
1059
|
+
headers.append("set-cookie", marker);
|
|
1060
|
+
if (changed) headers.append("set-cookie", viteHubPageToolsResetCookie);
|
|
1061
|
+
return headers;
|
|
1062
|
+
}
|
|
1063
|
+
async function markResponse(response, input) {
|
|
1064
|
+
const headers = await markHeaders(response.headers, input);
|
|
1065
|
+
return headers ? new Response(response.body, {
|
|
1066
|
+
headers,
|
|
1067
|
+
status: response.status,
|
|
1068
|
+
statusText: response.statusText
|
|
1069
|
+
}) : response;
|
|
1070
|
+
}
|
|
1071
|
+
const handler = auth.handler;
|
|
1072
|
+
const markedHandler = async (request) => markResponse(await handler(request), request);
|
|
1073
|
+
const originalApi = Object.getOwnPropertyDescriptor(auth, "api")?.value;
|
|
1074
|
+
if (originalApi) auth.api = Object.fromEntries(Object.entries(originalApi).map(([name, endpoint]) => [name, Object.assign(async (input) => {
|
|
1075
|
+
const result = await Reflect.apply(endpoint, originalApi, [input]);
|
|
1076
|
+
if (result instanceof Response) return markResponse(result, input);
|
|
1077
|
+
if (input?.returnHeaders && result && typeof result === "object" && "headers" in result && result.headers instanceof Headers) {
|
|
1078
|
+
const headers = await markHeaders(result.headers, input);
|
|
1079
|
+
return headers ? {
|
|
1080
|
+
...result,
|
|
1081
|
+
headers
|
|
1082
|
+
} : result;
|
|
1083
|
+
}
|
|
1084
|
+
return result;
|
|
1085
|
+
}, endpoint)]));
|
|
1086
|
+
return Object.assign(auth, {
|
|
1087
|
+
handler: markedHandler,
|
|
1088
|
+
fetch: markedHandler
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
//#endregion
|
|
1092
|
+
//#region src/auth-instance.ts
|
|
1093
|
+
function hasRequestRuntimeOptions(definition) {
|
|
1094
|
+
return typeof definition.options === "function" || trustsProxyHeaders(definition.options);
|
|
1095
|
+
}
|
|
1096
|
+
function hasConfiguredPublicUrl() {
|
|
1097
|
+
return typeof __VITEHUB_PUBLIC_URL__ !== "undefined" && Boolean(__VITEHUB_PUBLIC_URL__?.url || Object.keys(__VITEHUB_PUBLIC_URL__?.agents ?? {}).length);
|
|
1098
|
+
}
|
|
1099
|
+
function envResolverFor(definition) {
|
|
1100
|
+
return getAuthRuntimeState().envResolvers?.get(definition) ?? getAuthRuntimeState().envResolver;
|
|
1101
|
+
}
|
|
1102
|
+
function resolveDefaultDefinition() {
|
|
1103
|
+
if (!discoveredDefinition) throw authErrorDiagnostics.AUTH_R0005({ message: "[vitehub] No Auth Definition was discovered. Add `server/auth.ts` or `server.auth.ts`." });
|
|
1104
|
+
return discoveredDefinition;
|
|
1105
|
+
}
|
|
1106
|
+
function createBetterAuthOptions(definition) {
|
|
1107
|
+
return resolveAuthOptions(definition, { env: envResolverFor(definition) }).providerOptions;
|
|
1108
|
+
}
|
|
1109
|
+
function createAuthenticationProvider(options) {
|
|
1110
|
+
try {
|
|
1111
|
+
return withSessionMarker(withClientAddress(betterAuth(options)));
|
|
1112
|
+
} catch (cause) {
|
|
1113
|
+
throwAuthenticationProviderError(cause, "get-auth-for-request");
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
function getAuthForDefinition(definition) {
|
|
1117
|
+
return cachedAuth(definition);
|
|
1118
|
+
}
|
|
1119
|
+
function cachedAuth(definition) {
|
|
1120
|
+
const state = getAuthRuntimeState();
|
|
1121
|
+
if (!state.auth || state.definition !== definition) {
|
|
1122
|
+
state.auth = createAuthenticationProvider(createBetterAuthOptions(definition));
|
|
1123
|
+
state.definition = definition;
|
|
1124
|
+
}
|
|
1125
|
+
return state.auth;
|
|
1126
|
+
}
|
|
1127
|
+
const maxRequestProviders = 16;
|
|
1128
|
+
/** The instance for these resolved options. Requests with an equal key share it; others get their own. */
|
|
1129
|
+
function requestProvider(definition, resolved) {
|
|
1130
|
+
const key = resolved.providerKey;
|
|
1131
|
+
if (key === void 0) return createAuthenticationProvider(resolved.providerOptions);
|
|
1132
|
+
const state = getAuthRuntimeState();
|
|
1133
|
+
state.providers ??= /* @__PURE__ */ new WeakMap();
|
|
1134
|
+
let providers = state.providers.get(definition);
|
|
1135
|
+
if (!providers) state.providers.set(definition, providers = /* @__PURE__ */ new Map());
|
|
1136
|
+
const cached = providers.get(key);
|
|
1137
|
+
if (cached) {
|
|
1138
|
+
providers.delete(key);
|
|
1139
|
+
providers.set(key, cached);
|
|
1140
|
+
return cached;
|
|
1141
|
+
}
|
|
1142
|
+
const auth = createAuthenticationProvider(resolved.providerOptions);
|
|
1143
|
+
providers.set(key, auth);
|
|
1144
|
+
if (providers.size > maxRequestProviders) providers.delete(providers.keys().next().value);
|
|
1145
|
+
const owner = providers;
|
|
1146
|
+
(async () => {
|
|
1147
|
+
try {
|
|
1148
|
+
await auth.$context;
|
|
1149
|
+
} catch {
|
|
1150
|
+
if (owner.get(key) === auth) owner.delete(key);
|
|
1151
|
+
}
|
|
1152
|
+
})();
|
|
1153
|
+
return auth;
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* The Better Auth instance of the app's Auth Definition for a request that can differ from the event's own. Apps call
|
|
1157
|
+
* `useAuth(event)`. The Console reads it through `@vite-hub/auth/runtime/console`.
|
|
1158
|
+
*/
|
|
1159
|
+
function authForRequest(request, event, definition = resolveDefaultDefinition()) {
|
|
1160
|
+
if (!hasRequestRuntimeOptions(definition) && !hasConfiguredPublicUrl()) return getAuthForDefinition(definition);
|
|
1161
|
+
return requestProvider(definition, resolveAuthOptions(definition, {
|
|
1162
|
+
request,
|
|
1163
|
+
event,
|
|
1164
|
+
env: envResolverFor(definition)
|
|
1165
|
+
}));
|
|
1166
|
+
}
|
|
1167
|
+
//#endregion
|
|
1168
|
+
export { requestProvider as a, resolveAuthOptions as c, withClientAddress as d, runWithAuthEvent as f, getAuthForDefinition as i, eventClientAddress as l, createBetterAuthOptions as n, resolveDefaultDefinition as o, envResolverFor as r, withSessionMarker as s, authForRequest as t, setRequestClientAddress as u };
|