@vite-hub/auth 0.0.3 → 0.1.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/LICENSE +201 -0
- package/README.md +213 -41
- package/dist/agent.d.ts +25 -13
- package/dist/agent.js +19 -5
- package/dist/application-path-C290OAIs.js +18 -0
- package/dist/cli-mgXvsBtA.d.ts +85 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +68 -0
- package/dist/console-B7eERmGv.d.ts +180 -0
- package/dist/console-runtime-bZQtnX2Y.d.ts +39 -0
- package/dist/console-runtime.d.ts +3 -0
- package/dist/console-runtime.js +819 -0
- package/dist/console-types-CmmnKGMx.js +38 -0
- package/dist/console.d.ts +7 -0
- package/dist/console.js +15 -0
- package/dist/error-diagnostics-CL0yjHiM.js +79 -0
- package/dist/events-BkmK2dFY.d.ts +486 -0
- package/dist/events-P7mI4IQb.js +196 -0
- package/dist/events-config-CjcFOhTE.js +177 -0
- package/dist/host-declarations.d.ts +17 -0
- package/dist/index.d.ts +6 -5
- package/dist/index.js +40 -28
- package/dist/inspect-DPtsW8dB.d.ts +36 -0
- package/dist/nuxt.d.ts +59 -0
- package/dist/nuxt.js +93 -0
- package/dist/presets-BGZi6Dfu.d.ts +25 -0
- package/dist/presets.d.ts +2 -0
- package/dist/presets.js +32 -0
- package/dist/runtime/console.d.ts +7 -0
- package/dist/runtime/console.js +42 -0
- package/dist/runtime/empty-definition.d.ts +1 -2
- package/dist/runtime/nuxt.d.ts +3 -0
- package/dist/runtime/nuxt.js +9 -0
- package/dist/runtime/vue-nuxt.d.ts +3 -0
- package/dist/runtime/vue-nuxt.js +8 -0
- package/dist/server-B7LU19dS.js +1730 -0
- package/dist/server-CTD_JAww.d.ts +77 -0
- package/dist/server.d.ts +3 -20
- package/dist/server.js +3 -2
- package/dist/set-cookie-2as_DbHe.js +75 -0
- package/dist/shared-DnpgYiLF.js +15 -0
- package/dist/vite-COWkwxsj.js +990 -0
- package/dist/vite.d.ts +34 -10
- package/dist/vite.js +2 -995
- package/dist/vue.d.ts +55 -0
- package/dist/vue.js +112 -0
- package/package.json +92 -17
- package/dist/server-Diw3mAbX.js +0 -322
- package/dist/shared-QSYBHaMG.js +0 -12
- package/dist/types-B0fg9XFd.d.ts +0 -106
|
@@ -0,0 +1,1730 @@
|
|
|
1
|
+
import { a as parseAuthEventWindow, i as parseAuthEventList } from "./events-P7mI4IQb.js";
|
|
2
|
+
import { createAuthConsole } from "./console-runtime.js";
|
|
3
|
+
import { t as resolveAuthMountPath } from "./application-path-C290OAIs.js";
|
|
4
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
|
|
5
|
+
import { n as normalizeAuthBasePath } from "./shared-DnpgYiLF.js";
|
|
6
|
+
import { n as applyAuthPreset, t as validateAuthEvents } from "./events-config-CjcFOhTE.js";
|
|
7
|
+
import { n as getAuthRuntimeState, t as readSetCookies } from "./set-cookie-2as_DbHe.js";
|
|
8
|
+
import { ViteHubError, isViteHubError, resolvePublicUrl } from "@vite-hub/runtime";
|
|
9
|
+
import { defineGrant } from "@vite-hub/runtime/internal/grant";
|
|
10
|
+
import discoveredDefinition from "#vitehub/auth/definition";
|
|
11
|
+
import { APIError, betterAuth, isRequestLike, resolveBaseURL } from "better-auth";
|
|
12
|
+
import { createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sensitiveSessionMiddleware } from "better-auth/api";
|
|
13
|
+
import { hkdfSync } from "node:crypto";
|
|
14
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
|
+
import { getCookies } from "better-auth/cookies";
|
|
16
|
+
//#region ../internal/src/runtime/h3-v1-request.ts
|
|
17
|
+
const payloadMethods = /* @__PURE__ */ new Set([
|
|
18
|
+
"DELETE",
|
|
19
|
+
"PATCH",
|
|
20
|
+
"POST",
|
|
21
|
+
"PUT"
|
|
22
|
+
]);
|
|
23
|
+
const rawBodySymbol = Symbol.for("h3RawBody");
|
|
24
|
+
const nodeEventRequests = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
/** Return true for an event with an own `node.req` object, such as an H3 1 event. */
|
|
26
|
+
function isH3V1Event(input) {
|
|
27
|
+
if (!Object.hasOwn(input, "node")) return false;
|
|
28
|
+
const node = Reflect.get(input, "node");
|
|
29
|
+
return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
|
|
30
|
+
}
|
|
31
|
+
function isObjectLike(value) {
|
|
32
|
+
return value !== null && (typeof value === "object" || typeof value === "function");
|
|
33
|
+
}
|
|
34
|
+
function isWebRequest(value) {
|
|
35
|
+
if (!isObjectLike(value)) return false;
|
|
36
|
+
const headers = Reflect.get(value, "headers");
|
|
37
|
+
return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
|
|
38
|
+
}
|
|
39
|
+
function firstHeader(value) {
|
|
40
|
+
return Array.isArray(value) ? value[0] : value;
|
|
41
|
+
}
|
|
42
|
+
function readNodeRequestHeaders(request) {
|
|
43
|
+
const headers = new Headers();
|
|
44
|
+
for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
45
|
+
else if (value !== void 0) headers.set(name, value);
|
|
46
|
+
return headers;
|
|
47
|
+
}
|
|
48
|
+
/** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
|
|
49
|
+
function readNodeRequestURL(request) {
|
|
50
|
+
const host = firstHeader(request.headers.host) || "localhost";
|
|
51
|
+
const encrypted = request.socket?.encrypted || request.connection?.encrypted;
|
|
52
|
+
const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
|
|
53
|
+
const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
|
|
54
|
+
return new URL(path, `${protocol}://${host}`);
|
|
55
|
+
}
|
|
56
|
+
function toBodyStream(value) {
|
|
57
|
+
if (value instanceof ReadableStream) return value;
|
|
58
|
+
if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
|
|
59
|
+
controller.enqueue(value);
|
|
60
|
+
controller.close();
|
|
61
|
+
} });
|
|
62
|
+
if (typeof value === "string") return new Blob([value]).stream();
|
|
63
|
+
if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
|
|
64
|
+
if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
|
|
65
|
+
}
|
|
66
|
+
async function openNodeRequestBody(event) {
|
|
67
|
+
const request = event.node.req;
|
|
68
|
+
const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
|
|
69
|
+
if (stored !== void 0 && stored !== null) {
|
|
70
|
+
const stream = toBodyStream(await stored);
|
|
71
|
+
if (stream) {
|
|
72
|
+
const reader = stream.getReader();
|
|
73
|
+
return () => reader.read();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const iterator = request[Symbol.asyncIterator]?.();
|
|
77
|
+
if (!iterator) return void 0;
|
|
78
|
+
const chunks = [];
|
|
79
|
+
const collected = [];
|
|
80
|
+
let total = 0;
|
|
81
|
+
let ended = false;
|
|
82
|
+
let failed = false;
|
|
83
|
+
let failure;
|
|
84
|
+
let waiting;
|
|
85
|
+
const produce = async () => {
|
|
86
|
+
try {
|
|
87
|
+
for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
|
|
88
|
+
let bytes;
|
|
89
|
+
if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
|
|
90
|
+
else if (chunk instanceof Uint8Array) bytes = chunk;
|
|
91
|
+
else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
|
|
92
|
+
collected.push(bytes);
|
|
93
|
+
total += bytes.byteLength;
|
|
94
|
+
if (waiting) {
|
|
95
|
+
waiting.resolve({ value: bytes });
|
|
96
|
+
waiting = void 0;
|
|
97
|
+
} else chunks.push(bytes);
|
|
98
|
+
}
|
|
99
|
+
ended = true;
|
|
100
|
+
waiting?.resolve({ done: true });
|
|
101
|
+
waiting = void 0;
|
|
102
|
+
} catch (error) {
|
|
103
|
+
failed = true;
|
|
104
|
+
failure = error;
|
|
105
|
+
ended = true;
|
|
106
|
+
waiting?.reject(error);
|
|
107
|
+
waiting = void 0;
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
const bytes = new Uint8Array(total);
|
|
111
|
+
let offset = 0;
|
|
112
|
+
for (const chunk of collected) {
|
|
113
|
+
bytes.set(chunk, offset);
|
|
114
|
+
offset += chunk.byteLength;
|
|
115
|
+
}
|
|
116
|
+
return bytes;
|
|
117
|
+
};
|
|
118
|
+
let body;
|
|
119
|
+
const start = () => body ??= produce();
|
|
120
|
+
event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
|
|
121
|
+
return async () => {
|
|
122
|
+
start();
|
|
123
|
+
body?.catch(() => {});
|
|
124
|
+
if (failed) throw failure;
|
|
125
|
+
if (chunks.length) return { value: chunks.shift() };
|
|
126
|
+
if (ended) return { done: true };
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
waiting = {
|
|
129
|
+
resolve,
|
|
130
|
+
reject
|
|
131
|
+
};
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Read the body lazily, from a value a host already read or from the Node request stream. */
|
|
136
|
+
function readNodeRequestBody(event) {
|
|
137
|
+
let reader;
|
|
138
|
+
return new ReadableStream({ async pull(controller) {
|
|
139
|
+
const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
|
|
140
|
+
if (!chunk || chunk.done) {
|
|
141
|
+
controller.close();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const value = chunk.value;
|
|
145
|
+
if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
|
|
146
|
+
else if (value instanceof Uint8Array) controller.enqueue(value);
|
|
147
|
+
else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
|
|
148
|
+
} }, { highWaterMark: 0 });
|
|
149
|
+
}
|
|
150
|
+
/** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
|
|
151
|
+
function toH3V1Request(event) {
|
|
152
|
+
const cached = nodeEventRequests.get(event);
|
|
153
|
+
if (cached) return cached;
|
|
154
|
+
if (isWebRequest(event.web?.request)) return event.web.request;
|
|
155
|
+
const request = event.node.req;
|
|
156
|
+
const method = (request.method || "GET").toUpperCase();
|
|
157
|
+
const init = {
|
|
158
|
+
headers: readNodeRequestHeaders(request),
|
|
159
|
+
method
|
|
160
|
+
};
|
|
161
|
+
if (payloadMethods.has(method)) {
|
|
162
|
+
init.body = readNodeRequestBody(event);
|
|
163
|
+
init.duplex = "half";
|
|
164
|
+
}
|
|
165
|
+
const webRequest = new Request(readNodeRequestURL(request), init);
|
|
166
|
+
nodeEventRequests.set(event, webRequest);
|
|
167
|
+
return webRequest;
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/request.ts
|
|
171
|
+
/**
|
|
172
|
+
* Return the request of a Web Request, an event with an own `req` request such as H3 2,
|
|
173
|
+
* or an event with an own `node.req` Node request such as H3 1 in Nuxt 4.
|
|
174
|
+
*/
|
|
175
|
+
function unwrapAuthRequest(input) {
|
|
176
|
+
if (Object.hasOwn(input, "req")) return input.req;
|
|
177
|
+
if (isH3V1Event(input)) return toH3V1Request(input);
|
|
178
|
+
return input;
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
182
|
+
let activeEnv;
|
|
183
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
184
|
+
const runtimeGlobal = globalThis;
|
|
185
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
186
|
+
function getActiveCloudflareEnv() {
|
|
187
|
+
const scoped = activeEnvStorage.getStore();
|
|
188
|
+
if (scoped) return scoped.env;
|
|
189
|
+
const host = globalThis;
|
|
190
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
191
|
+
}
|
|
192
|
+
function ownValue(value, key) {
|
|
193
|
+
if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
|
|
194
|
+
return Reflect.get(value, key);
|
|
195
|
+
}
|
|
196
|
+
function ownObject(value) {
|
|
197
|
+
return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
|
|
198
|
+
}
|
|
199
|
+
/** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
|
|
200
|
+
function cloudflareOwners(target) {
|
|
201
|
+
const context = ownObject(ownValue(target, "context"));
|
|
202
|
+
const platform = ownObject(ownValue(context, "_platform"));
|
|
203
|
+
const req = ownObject(ownValue(target, "req"));
|
|
204
|
+
const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
|
|
205
|
+
return [
|
|
206
|
+
ownObject(ownValue(context, "cloudflare")),
|
|
207
|
+
ownObject(ownValue(platform, "cloudflare")),
|
|
208
|
+
ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
|
|
209
|
+
ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
|
|
210
|
+
];
|
|
211
|
+
}
|
|
212
|
+
function getCloudflareEnv(event, options = {}) {
|
|
213
|
+
const target = ownObject(event);
|
|
214
|
+
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
215
|
+
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
216
|
+
}
|
|
217
|
+
new TextEncoder();
|
|
218
|
+
/** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
|
|
219
|
+
const viteHubSecretSalt = "vitehub";
|
|
220
|
+
/**
|
|
221
|
+
* Reads the root app secret from an env record: `VITEHUB_SECRET`, then `NUXT_APP_SECRET`, so a Nuxt app needs only one
|
|
222
|
+
* secret. Returns `undefined` when neither is a non-empty string.
|
|
223
|
+
*/
|
|
224
|
+
function readViteHubSecret(env) {
|
|
225
|
+
for (const name of ["VITEHUB_SECRET", "NUXT_APP_SECRET"]) {
|
|
226
|
+
const value = env[name];
|
|
227
|
+
if (typeof value === "string" && value) return value;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
//#endregion
|
|
231
|
+
//#region src/secret.ts
|
|
232
|
+
/** The `deriveSecret()` purpose of the Better Auth secret. `vitehub secret derive vitehub:auth` prints it. */
|
|
233
|
+
const authSecretPurpose = "vitehub:auth";
|
|
234
|
+
const betterAuthSecretNames = [
|
|
235
|
+
"BETTER_AUTH_SECRET",
|
|
236
|
+
"BETTER_AUTH_SECRETS",
|
|
237
|
+
"AUTH_SECRET"
|
|
238
|
+
];
|
|
239
|
+
let derived;
|
|
240
|
+
function hex(buffer) {
|
|
241
|
+
return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The Better Auth secret derived from the root app secret (`VITEHUB_SECRET`, or `NUXT_APP_SECRET`), equal to
|
|
245
|
+
* `deriveSecret("vitehub:auth")`. Returns `undefined` when the environment sets a Better Auth secret or no root secret.
|
|
246
|
+
* It is synchronous because Better Auth reads its options synchronously.
|
|
247
|
+
*/
|
|
248
|
+
function deriveAuthSecret(event) {
|
|
249
|
+
const env = {
|
|
250
|
+
...globalThis.process?.env,
|
|
251
|
+
...getCloudflareEnv(event)
|
|
252
|
+
};
|
|
253
|
+
if (betterAuthSecretNames.some((name) => env[name])) return void 0;
|
|
254
|
+
const root = readViteHubSecret(env);
|
|
255
|
+
if (!root) return void 0;
|
|
256
|
+
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\`.` });
|
|
257
|
+
if (derived?.root !== root) derived = {
|
|
258
|
+
root,
|
|
259
|
+
secret: hex(hkdfSync("sha256", root, viteHubSecretSalt, authSecretPurpose, 32))
|
|
260
|
+
};
|
|
261
|
+
return derived.secret;
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region src/event-plugin.ts
|
|
265
|
+
function record(value) {
|
|
266
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
267
|
+
}
|
|
268
|
+
function identifier(value) {
|
|
269
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : void 0;
|
|
270
|
+
}
|
|
271
|
+
function actor(ctx, fallback) {
|
|
272
|
+
const session = ctx?.context.session;
|
|
273
|
+
const id = identifier(session?.session.impersonatedBy) ?? session?.user.id ?? fallback;
|
|
274
|
+
return id ? `user:${id}` : "system";
|
|
275
|
+
}
|
|
276
|
+
function method(ctx) {
|
|
277
|
+
const path = ctx?.path ?? "";
|
|
278
|
+
const providers = ctx?.context.socialProviders ?? [];
|
|
279
|
+
const candidate = path.startsWith("/callback/") || path.startsWith("/oauth2/callback/") ? path.split("/").at(-1) : identifier(record(ctx?.body).provider);
|
|
280
|
+
if (candidate && providers.some((provider) => provider.id === candidate) && /^[a-zA-Z0-9_.-]+$/.test(candidate)) return `oauth:${candidate}`;
|
|
281
|
+
if (path === "/sign-in/email" || path === "/sign-up/email") return "email-password";
|
|
282
|
+
if (path.includes("/magic-link/verify")) return "magic-link";
|
|
283
|
+
if (path.includes("/passkey/verify-authentication")) return "passkey";
|
|
284
|
+
if (path.startsWith("/two-factor/")) return "two-factor";
|
|
285
|
+
if (path.includes("/siwe/")) return "siwe";
|
|
286
|
+
for (const name of [
|
|
287
|
+
"email-otp",
|
|
288
|
+
"username",
|
|
289
|
+
"phone-number",
|
|
290
|
+
"anonymous"
|
|
291
|
+
]) if (path === `/sign-in/${name}`) return name;
|
|
292
|
+
return "unknown";
|
|
293
|
+
}
|
|
294
|
+
/** Discard the raw agent string. IP addresses are never read. */
|
|
295
|
+
function authEventDevice(agent) {
|
|
296
|
+
if (!agent) return "unknown";
|
|
297
|
+
if (/bot|crawler|spider/i.test(agent)) return "bot";
|
|
298
|
+
if (/ipad|tablet/i.test(agent) || /android/i.test(agent) && !/mobile/i.test(agent)) return "tablet";
|
|
299
|
+
if (/mobi|iphone|ipod/i.test(agent)) return "mobile";
|
|
300
|
+
if (/windows|macintosh|linux|cros/i.test(agent)) return "desktop";
|
|
301
|
+
return "unknown";
|
|
302
|
+
}
|
|
303
|
+
/** Compose with Better Auth's own hook pipeline, including direct auth.api calls. */
|
|
304
|
+
function createAuthEventsPlugin(options) {
|
|
305
|
+
const deletionContext = new AsyncLocalStorage();
|
|
306
|
+
const outcomes = /* @__PURE__ */ new WeakMap();
|
|
307
|
+
const challenges = /* @__PURE__ */ new WeakSet();
|
|
308
|
+
const wrappedAdapters = /* @__PURE__ */ new WeakSet();
|
|
309
|
+
const createdSessions = /* @__PURE__ */ new WeakSet();
|
|
310
|
+
const recordedSessions = /* @__PURE__ */ new WeakSet();
|
|
311
|
+
async function append(type, userId, ctx, metadata = {}, fallback) {
|
|
312
|
+
try {
|
|
313
|
+
await options.store.append({
|
|
314
|
+
id: crypto.randomUUID(),
|
|
315
|
+
type,
|
|
316
|
+
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
317
|
+
actor: actor(ctx, fallback),
|
|
318
|
+
userId,
|
|
319
|
+
metadata
|
|
320
|
+
});
|
|
321
|
+
return true;
|
|
322
|
+
} catch {
|
|
323
|
+
console.warn("[vitehub] AUTH_EVENT_WRITE_FAILED: Could not record an auth event.");
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async function deleted(session, ctx) {
|
|
328
|
+
const type = ctx?.path === "/sign-out" ? "user.signed_out" : ctx?.path === "/admin/stop-impersonating" ? "impersonation.stopped" : "session.revoked";
|
|
329
|
+
await append(type, session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy) ?? (type === "user.signed_out" ? session.userId : void 0));
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
id: "vitehub-auth-events",
|
|
333
|
+
wrapStorage(storage) {
|
|
334
|
+
return {
|
|
335
|
+
get: (key) => storage.get(key),
|
|
336
|
+
set: (key, value, ttl) => storage.set(key, value, ttl),
|
|
337
|
+
getAndDelete: (key) => storage.getAndDelete(key),
|
|
338
|
+
increment: (key, ttl) => storage.increment(key, ttl),
|
|
339
|
+
async delete(key) {
|
|
340
|
+
const value = await storage.getAndDelete(key);
|
|
341
|
+
if (!value) return;
|
|
342
|
+
let parsed;
|
|
343
|
+
try {
|
|
344
|
+
parsed = typeof value === "string" ? JSON.parse(value) : value;
|
|
345
|
+
} catch {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const session = record(record(parsed).session);
|
|
349
|
+
const id = identifier(session.id);
|
|
350
|
+
const userId = identifier(session.userId);
|
|
351
|
+
if (id && userId && session.token === key) await deleted({
|
|
352
|
+
id,
|
|
353
|
+
userId,
|
|
354
|
+
impersonatedBy: session.impersonatedBy
|
|
355
|
+
}, deletionContext.getStore() ?? null);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
},
|
|
359
|
+
captureOutcome(ctx) {
|
|
360
|
+
const context = record(ctx).context;
|
|
361
|
+
if (context !== null && typeof context === "object") outcomes.set(context, record(context).returned);
|
|
362
|
+
},
|
|
363
|
+
init: () => ({ options: { databaseHooks: {
|
|
364
|
+
user: {
|
|
365
|
+
create: { async after(user, ctx) {
|
|
366
|
+
await append("user.signed_up", user.id, ctx, { method: method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
|
|
367
|
+
} },
|
|
368
|
+
update: { async after(user, ctx) {
|
|
369
|
+
const path = ctx?.path;
|
|
370
|
+
if (path === "/admin/ban-user") await append("user.banned", user.id, ctx);
|
|
371
|
+
else if (path === "/admin/unban-user") await append("user.unbanned", user.id, ctx);
|
|
372
|
+
else if (path === "/admin/set-role") await append("user.role_changed", user.id, ctx, { role: identifier(user.role) });
|
|
373
|
+
else if (path === "/admin/update-user") {
|
|
374
|
+
const data = record(record(ctx?.body).data);
|
|
375
|
+
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);
|
|
376
|
+
await append("user.updated", user.id, ctx, { fields });
|
|
377
|
+
if (Object.hasOwn(data, "role")) await append("user.role_changed", user.id, ctx, { role: identifier(user.role) });
|
|
378
|
+
if (Object.hasOwn(data, "banned")) await append(user.banned ? "user.banned" : "user.unbanned", user.id, ctx);
|
|
379
|
+
}
|
|
380
|
+
} },
|
|
381
|
+
delete: { async after(user, ctx) {
|
|
382
|
+
await append("user.removed", user.id, ctx);
|
|
383
|
+
} }
|
|
384
|
+
},
|
|
385
|
+
session: {
|
|
386
|
+
create: { async after(session, ctx) {
|
|
387
|
+
createdSessions.add(session);
|
|
388
|
+
if (session.impersonatedBy || ctx?.path === "/admin/impersonate-user") {
|
|
389
|
+
if (await append("impersonation.started", session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy))) return;
|
|
390
|
+
await ctx?.context.internalAdapter.deleteSession(session.token);
|
|
391
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
392
|
+
code: "IMPERSONATION_NOT_RECORDED",
|
|
393
|
+
message: "Impersonation did not start because the auth event log could not record it."
|
|
394
|
+
});
|
|
395
|
+
} else if (!ctx) await append("user.signed_in", session.userId, ctx, {
|
|
396
|
+
method: method(ctx),
|
|
397
|
+
device: "unknown",
|
|
398
|
+
sessionId: session.id
|
|
399
|
+
});
|
|
400
|
+
} },
|
|
401
|
+
delete: { async after(session, ctx) {
|
|
402
|
+
await deleted(session, ctx);
|
|
403
|
+
} }
|
|
404
|
+
}
|
|
405
|
+
} } }),
|
|
406
|
+
hooks: {
|
|
407
|
+
before: [{
|
|
408
|
+
matcher: () => true,
|
|
409
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
410
|
+
if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
|
|
411
|
+
const cookie = ctx.context.createAuthCookie("two_factor");
|
|
412
|
+
const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
413
|
+
if (token && await ctx.context.internalAdapter.findVerificationValue(token)) challenges.add(ctx.context);
|
|
414
|
+
}
|
|
415
|
+
if (!ctx.context.options.secondaryStorage || ctx.context.options.session?.storeSessionInDatabase) return;
|
|
416
|
+
const adapter = ctx.context.internalAdapter;
|
|
417
|
+
ctx.context.internalAdapter = {
|
|
418
|
+
...adapter,
|
|
419
|
+
deleteSession: (token) => deletionContext.run(ctx, () => adapter.deleteSession(token)),
|
|
420
|
+
deleteSessions: (tokens) => deletionContext.run(ctx, () => adapter.deleteSessions(tokens)),
|
|
421
|
+
deleteUserSessions: (userId) => deletionContext.run(ctx, () => adapter.deleteUserSessions(userId))
|
|
422
|
+
};
|
|
423
|
+
})
|
|
424
|
+
}, {
|
|
425
|
+
matcher: (ctx) => Boolean(ctx.path?.startsWith("/oauth2/")),
|
|
426
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
427
|
+
const adapter = ctx.context.adapter;
|
|
428
|
+
if (wrappedAdapters.has(adapter)) return;
|
|
429
|
+
await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
430
|
+
async function consentEvent(type, value) {
|
|
431
|
+
const consent = record(value);
|
|
432
|
+
const userId = identifier(consent.userId);
|
|
433
|
+
const clientId = identifier(consent.clientId);
|
|
434
|
+
if (userId && clientId) await append(type, userId, ctx, { clientId });
|
|
435
|
+
}
|
|
436
|
+
ctx.context.adapter = {
|
|
437
|
+
...adapter,
|
|
438
|
+
async create(input) {
|
|
439
|
+
const result = await adapter.create(input);
|
|
440
|
+
if (input.model === "oauthConsent") await consentEvent("oauth.consent_granted", result);
|
|
441
|
+
return result;
|
|
442
|
+
},
|
|
443
|
+
async update(input) {
|
|
444
|
+
const result = await adapter.update(input);
|
|
445
|
+
if (input.model === "oauthConsent" && result) await consentEvent("oauth.consent_granted", result);
|
|
446
|
+
return result;
|
|
447
|
+
},
|
|
448
|
+
async delete(input) {
|
|
449
|
+
const consent = input.model === "oauthConsent" ? await adapter.findOne(input) : void 0;
|
|
450
|
+
await adapter.delete(input);
|
|
451
|
+
if (consent) await consentEvent("oauth.consent_revoked", consent);
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
wrappedAdapters.add(ctx.context.adapter);
|
|
455
|
+
})
|
|
456
|
+
}],
|
|
457
|
+
after: [{
|
|
458
|
+
matcher: () => true,
|
|
459
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
460
|
+
const path = ctx.path ?? "";
|
|
461
|
+
const outcome = outcomes.get(ctx.context);
|
|
462
|
+
const value = record(outcome);
|
|
463
|
+
const signedIn = ctx.context.newSession;
|
|
464
|
+
if (signedIn && createdSessions.has(signedIn.session) && !signedIn.session.impersonatedBy && path !== "/admin/impersonate-user" && !recordedSessions.has(signedIn.session)) {
|
|
465
|
+
recordedSessions.add(signedIn.session);
|
|
466
|
+
await append("user.signed_in", signedIn.user.id, ctx, {
|
|
467
|
+
method: method(ctx),
|
|
468
|
+
device: authEventDevice(ctx.headers?.get("user-agent") ?? ctx.request?.headers.get("user-agent")),
|
|
469
|
+
sessionId: signedIn.session.id
|
|
470
|
+
}, signedIn.user.id);
|
|
471
|
+
}
|
|
472
|
+
if (!signedIn && outcome instanceof APIError && (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) });
|
|
473
|
+
if (outcome instanceof APIError) return;
|
|
474
|
+
if (path === "/admin/set-user-password") {
|
|
475
|
+
const userId = identifier(record(ctx.body).userId);
|
|
476
|
+
if (userId) {
|
|
477
|
+
await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
478
|
+
await append("user.updated", userId, ctx, { fields: ["password"] });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const operationId = record(ctx).operationId;
|
|
482
|
+
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;
|
|
483
|
+
if (!type) return;
|
|
484
|
+
if (!ctx.context.session) await getSessionFromCtx(ctx, { disableRefresh: true });
|
|
485
|
+
const members = path === "/organization/create" && Array.isArray(value.members) ? value.members : [value.member ?? value];
|
|
486
|
+
for (const raw of members) {
|
|
487
|
+
const member = record(raw);
|
|
488
|
+
const userId = identifier(member.userId);
|
|
489
|
+
const organizationId = identifier(member.organizationId);
|
|
490
|
+
if (userId && organizationId) await append(type, userId, ctx, {
|
|
491
|
+
organizationId,
|
|
492
|
+
memberId: identifier(member.id),
|
|
493
|
+
role: identifier(member.role)
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
})
|
|
497
|
+
}]
|
|
498
|
+
},
|
|
499
|
+
endpoints: options.authorize ? { vitehubAuthEvents: createAuthEndpoint("/vitehub/events", {
|
|
500
|
+
method: "GET",
|
|
501
|
+
use: [sensitiveSessionMiddleware]
|
|
502
|
+
}, async (ctx) => {
|
|
503
|
+
if (!ctx.request) throw new APIError("FORBIDDEN");
|
|
504
|
+
const authorization = await options.authorize({
|
|
505
|
+
request: ctx.request,
|
|
506
|
+
user: ctx.context.session.user,
|
|
507
|
+
session: ctx.context.session.session
|
|
508
|
+
});
|
|
509
|
+
if (authorization instanceof Response) return authorization;
|
|
510
|
+
if (authorization !== true) throw new APIError("FORBIDDEN");
|
|
511
|
+
ctx.setHeader("cache-control", "no-store");
|
|
512
|
+
const query = new URL(ctx.request.url).searchParams;
|
|
513
|
+
let list;
|
|
514
|
+
let window;
|
|
515
|
+
try {
|
|
516
|
+
if (query.get("aggregate") === "true") window = parseAuthEventWindow({
|
|
517
|
+
from: query.get("from") ?? "",
|
|
518
|
+
to: query.get("to") ?? ""
|
|
519
|
+
});
|
|
520
|
+
else {
|
|
521
|
+
const input = Object.fromEntries([...query].filter(([key]) => key !== "limit"));
|
|
522
|
+
list = parseAuthEventList({
|
|
523
|
+
...input,
|
|
524
|
+
...query.has("limit") ? { limit: Number(query.get("limit")) } : {}
|
|
525
|
+
}).query;
|
|
526
|
+
}
|
|
527
|
+
} catch {
|
|
528
|
+
throw new APIError("BAD_REQUEST", { message: "Invalid auth event filters." });
|
|
529
|
+
}
|
|
530
|
+
return ctx.json(window ? await options.store.aggregate(window) : await options.store.list(list));
|
|
531
|
+
}) } : {}
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
//#endregion
|
|
535
|
+
//#region src/impersonation-plugin.ts
|
|
536
|
+
/**
|
|
537
|
+
* Better Auth endpoints that create a credential which outlives an impersonation session, change how the user signs
|
|
538
|
+
* in, or start another impersonation: OAuth, MCP, and device grants, API keys, passkeys, passwords, email and phone
|
|
539
|
+
* number changes, linked accounts, two-factor setup, and one-time tokens that open a new session.
|
|
540
|
+
*/
|
|
541
|
+
const credentialPaths = /* @__PURE__ */ new Set([
|
|
542
|
+
"/account-info",
|
|
543
|
+
"/admin/impersonate-user",
|
|
544
|
+
"/api-key/create",
|
|
545
|
+
"/api-key/update",
|
|
546
|
+
"/change-email",
|
|
547
|
+
"/change-password",
|
|
548
|
+
"/email-otp/change-email",
|
|
549
|
+
"/email-otp/request-email-change",
|
|
550
|
+
"/get-access-token",
|
|
551
|
+
"/link-social",
|
|
552
|
+
"/one-time-token/generate",
|
|
553
|
+
"/passkey/generate-register-options",
|
|
554
|
+
"/passkey/verify-registration",
|
|
555
|
+
"/phone-number/verify",
|
|
556
|
+
"/refresh-token",
|
|
557
|
+
"/two-factor/disable",
|
|
558
|
+
"/two-factor/enable",
|
|
559
|
+
"/two-factor/generate-backup-codes",
|
|
560
|
+
"/unlink-account"
|
|
561
|
+
]);
|
|
562
|
+
/** `/update-user` fields that change how the user signs in. The username plugin sets `username` from `displayUsername`. */
|
|
563
|
+
const identityFields = ["displayUsername", "username"];
|
|
564
|
+
const credentialPrefixes = [
|
|
565
|
+
"/device/",
|
|
566
|
+
"/mcp/",
|
|
567
|
+
"/oauth2/"
|
|
568
|
+
];
|
|
569
|
+
/** Reads below those prefixes. They show the user's grants and clients, so a support view still works. */
|
|
570
|
+
const grantReads = /^\/oauth2\/(?:get-|public-client|userinfo)|^\/mcp\/get-session$/;
|
|
571
|
+
function createsCredential(path, body) {
|
|
572
|
+
if (!path) return false;
|
|
573
|
+
if (path === "/update-user") return typeof body === "object" && body !== null && identityFields.some((field) => field in body);
|
|
574
|
+
return credentialPaths.has(path) || credentialPrefixes.some((prefix) => path.startsWith(prefix)) && !grantReads.test(path);
|
|
575
|
+
}
|
|
576
|
+
/** The current expiry of the request's impersonation session, when the update would move it later. */
|
|
577
|
+
function keptExpiry(...[data, endpoint]) {
|
|
578
|
+
const current = endpoint?.context.session?.session;
|
|
579
|
+
if (!current?.impersonatedBy || !data.expiresAt) return;
|
|
580
|
+
if (new Date(data.expiresAt).getTime() > new Date(current.expiresAt).getTime()) return current.expiresAt;
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Better Auth runs the app's database hooks after plugin hooks and gives each hook the original update. An app
|
|
584
|
+
* `session.update.before` that returns `{ data: { ...data } }` would restore the refreshed expiry, so its result
|
|
585
|
+
* keeps the impersonation expiry too.
|
|
586
|
+
*/
|
|
587
|
+
function withImpersonationExpiry(hooks) {
|
|
588
|
+
const before = hooks?.session?.update?.before;
|
|
589
|
+
if (!before) return hooks;
|
|
590
|
+
return {
|
|
591
|
+
...hooks,
|
|
592
|
+
session: {
|
|
593
|
+
...hooks.session,
|
|
594
|
+
update: {
|
|
595
|
+
...hooks.session?.update,
|
|
596
|
+
async before(data, endpoint) {
|
|
597
|
+
const result = await before(data, endpoint);
|
|
598
|
+
if (typeof result !== "object") return result;
|
|
599
|
+
const expiresAt = keptExpiry({
|
|
600
|
+
...data,
|
|
601
|
+
...result.data
|
|
602
|
+
}, endpoint);
|
|
603
|
+
return expiresAt ? { data: {
|
|
604
|
+
...result.data,
|
|
605
|
+
expiresAt
|
|
606
|
+
} } : result;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Keeps a Better Auth admin impersonation session inside its bounds. The session never gets a later expiry, and it
|
|
614
|
+
* cannot create credentials, change how the user signs in, or start another impersonation. ViteHub adds this plugin
|
|
615
|
+
* with the admin plugin.
|
|
616
|
+
*/
|
|
617
|
+
function createImpersonationPlugin() {
|
|
618
|
+
return {
|
|
619
|
+
id: "vitehub-impersonation",
|
|
620
|
+
init: () => ({ options: { databaseHooks: { session: { update: { async before(data, endpoint) {
|
|
621
|
+
const expiresAt = keptExpiry(data, endpoint);
|
|
622
|
+
if (expiresAt) return { data: { expiresAt } };
|
|
623
|
+
} } } } } }),
|
|
624
|
+
hooks: { before: [{
|
|
625
|
+
matcher: (ctx) => "operationId" in ctx && ctx.operationId === "setPassword" || createsCredential(ctx.path, ctx.body),
|
|
626
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
627
|
+
if (!(await getSessionFromCtx(ctx, { disableRefresh: true }))?.session.impersonatedBy) return;
|
|
628
|
+
throw new APIError("FORBIDDEN", {
|
|
629
|
+
code: "IMPERSONATION_FORBIDDEN",
|
|
630
|
+
message: "An impersonation session cannot create credentials, change how the user signs in, or start another impersonation. Stop impersonating first."
|
|
631
|
+
});
|
|
632
|
+
})
|
|
633
|
+
}] }
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region src/session-refresh.ts
|
|
638
|
+
/**
|
|
639
|
+
* Runs `session.onRefresh` from the Better Auth `session.update.before` database hook.
|
|
640
|
+
* Better Auth calls `updateSession(token, { expiresAt, updatedAt })` when a stored session
|
|
641
|
+
* passes `session.updateAge`. No other built-in session update sets `expiresAt`.
|
|
642
|
+
*/
|
|
643
|
+
function createSessionRefreshPlugin(onRefresh) {
|
|
644
|
+
return {
|
|
645
|
+
id: "vitehub-session-refresh",
|
|
646
|
+
init: () => ({ options: { databaseHooks: { session: { update: { async before(data, endpoint) {
|
|
647
|
+
const current = endpoint?.context.session;
|
|
648
|
+
if (!current || !Object.hasOwn(data, "expiresAt")) return;
|
|
649
|
+
const result = { outcome: { kind: "skip" } };
|
|
650
|
+
await onRefresh({
|
|
651
|
+
session: current.session,
|
|
652
|
+
user: current.user,
|
|
653
|
+
refresh: (fields) => {
|
|
654
|
+
if (result.outcome.kind !== "clear") result.outcome = {
|
|
655
|
+
fields,
|
|
656
|
+
kind: "refresh"
|
|
657
|
+
};
|
|
658
|
+
},
|
|
659
|
+
clear: () => {
|
|
660
|
+
result.outcome = { kind: "clear" };
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
const { outcome } = result;
|
|
664
|
+
if (outcome.kind === "refresh") return outcome.fields ? { data: outcome.fields } : void 0;
|
|
665
|
+
if (outcome.kind === "skip") return { data: { expiresAt: current.session.expiresAt } };
|
|
666
|
+
await endpoint.context.internalAdapter.deleteSession(current.session.token);
|
|
667
|
+
return false;
|
|
668
|
+
} } } } } })
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/runtime-options.ts
|
|
673
|
+
function isPlainObject(value) {
|
|
674
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
675
|
+
}
|
|
676
|
+
function isAuthDatabaseMetadata(value) {
|
|
677
|
+
return value === true || isPlainObject(value) && Object.hasOwn(value, "name") && typeof value.name === "string" && Object.keys(value).every((key) => key === "dedicated" || key === "name");
|
|
678
|
+
}
|
|
679
|
+
function isAuthSecondaryStorageMetadata(value) {
|
|
680
|
+
return value === true || isPlainObject(value) && Object.hasOwn(value, "store") && typeof value.store === "string" && Object.keys(value).every((key) => key === "store");
|
|
681
|
+
}
|
|
682
|
+
function stripViteHubOptions(options) {
|
|
683
|
+
const { access: _access, console: _console, database, events, route: _route, runtime: _runtime, secondaryStorage, ...rest } = applyAuthPreset(options);
|
|
684
|
+
const storage = {
|
|
685
|
+
...!isAuthDatabaseMetadata(database) ? { database } : {},
|
|
686
|
+
...!isAuthSecondaryStorageMetadata(secondaryStorage) ? { secondaryStorage } : {}
|
|
687
|
+
};
|
|
688
|
+
validateAuthEvents(events);
|
|
689
|
+
const sessionRefresh = withSessionRefresh(rest, Boolean(storage.database || storage.secondaryStorage));
|
|
690
|
+
const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
|
|
691
|
+
const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
|
|
692
|
+
const plugins = impersonation ? [...declaredPlugins, createImpersonationPlugin()] : declaredPlugins;
|
|
693
|
+
const eventPlugin = events ? createAuthEventsPlugin(events) : void 0;
|
|
694
|
+
if (eventPlugin && storage.secondaryStorage && !rest.session?.storeSessionInDatabase) storage.secondaryStorage = eventPlugin.wrapStorage(storage.secondaryStorage);
|
|
695
|
+
const after = rest.hooks?.after ?? createAuthMiddleware(async () => {});
|
|
696
|
+
return {
|
|
697
|
+
...rest,
|
|
698
|
+
...storage,
|
|
699
|
+
...sessionRefresh,
|
|
700
|
+
...impersonation && rest.databaseHooks ? { databaseHooks: withImpersonationExpiry(rest.databaseHooks) } : {},
|
|
701
|
+
plugins: eventPlugin ? [...plugins, eventPlugin] : plugins,
|
|
702
|
+
...eventPlugin ? { hooks: {
|
|
703
|
+
...rest.hooks,
|
|
704
|
+
after: Object.assign(async (...args) => {
|
|
705
|
+
eventPlugin.captureOutcome(args[0]);
|
|
706
|
+
return after(...args);
|
|
707
|
+
}, after)
|
|
708
|
+
} } : {},
|
|
709
|
+
basePath: resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0))
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
/** Moves `session.onRefresh` into a Better Auth plugin, because Better Auth does not read it. */
|
|
713
|
+
function withSessionRefresh(options, hasSessionStore) {
|
|
714
|
+
const session = options.session;
|
|
715
|
+
if (!session?.onRefresh) return {};
|
|
716
|
+
if (typeof session.onRefresh !== "function") throw authErrorDiagnostics.AUTH_C0041({ message: "`defineAuth()` session.onRefresh must be a function." });
|
|
717
|
+
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." });
|
|
718
|
+
const { onRefresh, ...betterAuthSession } = session;
|
|
719
|
+
return {
|
|
720
|
+
plugins: [...options.plugins ?? [], createSessionRefreshPlugin(onRefresh)],
|
|
721
|
+
session: betterAuthSession
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
/** Without a configured secret, Better Auth signs with the secret derived from `VITEHUB_SECRET`. */
|
|
725
|
+
function withDerivedSecret(options, event) {
|
|
726
|
+
if (Object.hasOwn(options, "secret") || Object.hasOwn(options, "secrets")) return options;
|
|
727
|
+
const secret = deriveAuthSecret(event);
|
|
728
|
+
return secret ? {
|
|
729
|
+
...options,
|
|
730
|
+
secret
|
|
731
|
+
} : options;
|
|
732
|
+
}
|
|
733
|
+
/** Resolves one coherent option snapshot before projecting it for Better Auth or host callers. */
|
|
734
|
+
function resolveAuthOptions(definition, input = {}) {
|
|
735
|
+
const { request } = input;
|
|
736
|
+
const callback = typeof definition.options === "function";
|
|
737
|
+
const staticRequestRuntime = request && typeof definition.options !== "function" ? definition.options.runtime : void 0;
|
|
738
|
+
const usesContext = !request || callback || Boolean(staticRequestRuntime);
|
|
739
|
+
const context = {
|
|
740
|
+
env: usesContext ? input.env?.(input.event ?? request) ?? {} : {},
|
|
741
|
+
...request ? { request } : {},
|
|
742
|
+
requestOrigin: usesContext && request ? new URL(request.url).origin : "http://localhost"
|
|
743
|
+
};
|
|
744
|
+
const declared = callback ? definition.options(context) : definition.options;
|
|
745
|
+
const runtime = request && !callback ? staticRequestRuntime : declared.runtime;
|
|
746
|
+
const resolvedRuntime = !runtime ? {} : typeof runtime === "function" ? runtime(context) : runtime;
|
|
747
|
+
let requestRuntimeOptions = {
|
|
748
|
+
...callback ? declared : {},
|
|
749
|
+
...resolvedRuntime,
|
|
750
|
+
...input.runtimeOptions
|
|
751
|
+
};
|
|
752
|
+
if (request) {
|
|
753
|
+
const baseURL = requestRuntimeOptions.baseURL || resolvePublicUrl({ request });
|
|
754
|
+
const staticTrustedOrigins = !callback && Object.hasOwn(declared, "trustedOrigins");
|
|
755
|
+
requestRuntimeOptions = {
|
|
756
|
+
...!Object.hasOwn(requestRuntimeOptions, "trustedOrigins") && !staticTrustedOrigins ? { trustedOrigins: [baseURL] } : {},
|
|
757
|
+
...requestRuntimeOptions,
|
|
758
|
+
baseURL
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
let snapshot;
|
|
762
|
+
const resolveSnapshot = () => snapshot ??= callback ? requestRuntimeOptions : {
|
|
763
|
+
...declared,
|
|
764
|
+
...requestRuntimeOptions
|
|
765
|
+
};
|
|
766
|
+
return {
|
|
767
|
+
get options() {
|
|
768
|
+
return resolveSnapshot();
|
|
769
|
+
},
|
|
770
|
+
get providerOptions() {
|
|
771
|
+
return withDerivedSecret(stripViteHubOptions(resolveSnapshot()), input.event ?? request);
|
|
772
|
+
},
|
|
773
|
+
requestRuntimeOptions
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
//#endregion
|
|
777
|
+
//#region src/errors.ts
|
|
778
|
+
function invalidAuthenticationErrorOptions() {
|
|
779
|
+
throw authErrorDiagnostics.AUTH_R0004({ message: "[vitehub] Invalid authentication error options." });
|
|
780
|
+
}
|
|
781
|
+
function readAuthenticationErrorOption(value, key) {
|
|
782
|
+
if (typeof value !== "object" || value === null) invalidAuthenticationErrorOptions();
|
|
783
|
+
try {
|
|
784
|
+
if (Array.isArray(value)) invalidAuthenticationErrorOptions();
|
|
785
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
786
|
+
if (descriptor === void 0) return void 0;
|
|
787
|
+
if (!("value" in descriptor)) invalidAuthenticationErrorOptions();
|
|
788
|
+
return descriptor.value;
|
|
789
|
+
} catch {
|
|
790
|
+
invalidAuthenticationErrorOptions();
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
function createAuthenticationProviderError(options) {
|
|
794
|
+
const cause = readAuthenticationErrorOption(options, "cause");
|
|
795
|
+
const operation = readAuthenticationErrorOption(options, "operation");
|
|
796
|
+
if (operation !== "get-auth-for-request" && operation !== "get-session" && operation !== "get-user") invalidAuthenticationErrorOptions();
|
|
797
|
+
return new ViteHubError("AUTH_PROVIDER_OPERATION_FAILED", "[vitehub] Authentication provider operation failed.", {
|
|
798
|
+
cause,
|
|
799
|
+
details: {
|
|
800
|
+
operation,
|
|
801
|
+
provider: "better-auth"
|
|
802
|
+
}
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
function throwAuthenticationProviderError(cause, operation) {
|
|
806
|
+
if (isViteHubError(cause) || isAuthenticationAbortError(cause)) throw cause;
|
|
807
|
+
throw createAuthenticationProviderError({
|
|
808
|
+
cause,
|
|
809
|
+
operation
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
function isAuthenticationAbortError(error) {
|
|
813
|
+
if (typeof error !== "object" || error === null) return false;
|
|
814
|
+
try {
|
|
815
|
+
return Reflect.get(error, "name") === "AbortError";
|
|
816
|
+
} catch {
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
//#endregion
|
|
821
|
+
//#region src/session.ts
|
|
822
|
+
async function getAuthenticationSession(auth, input) {
|
|
823
|
+
const [api, getSession] = await readProvider(() => {
|
|
824
|
+
const api = readRecordProperty(auth, "api");
|
|
825
|
+
return [api, api && readProperty(api, "getSession")];
|
|
826
|
+
});
|
|
827
|
+
if (typeof getSession !== "function") throw authErrorDiagnostics.AUTH_R0011({ message: "Better Auth did not expose api.getSession()." });
|
|
828
|
+
const value = await readProvider(async () => {
|
|
829
|
+
try {
|
|
830
|
+
return await Reflect.apply(getSession, api, [input]);
|
|
831
|
+
} catch (cause) {
|
|
832
|
+
if (isUnauthorizedApiError(cause)) return null;
|
|
833
|
+
throw cause;
|
|
834
|
+
}
|
|
835
|
+
});
|
|
836
|
+
if (value === null) return null;
|
|
837
|
+
const session = await readProvider(() => resolveAuthenticationSession(value));
|
|
838
|
+
if (!session) throw authErrorDiagnostics.AUTH_R0012({ message: "Better Auth returned an invalid session response." });
|
|
839
|
+
return session;
|
|
840
|
+
}
|
|
841
|
+
async function readProvider(read) {
|
|
842
|
+
try {
|
|
843
|
+
return await read();
|
|
844
|
+
} catch (cause) {
|
|
845
|
+
throwAuthenticationProviderError(cause, "get-session");
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
function readRecordProperty(value, property) {
|
|
849
|
+
if (!isRecord(value)) return;
|
|
850
|
+
const nested = readProperty(value, property);
|
|
851
|
+
return isRecord(nested) ? nested : void 0;
|
|
852
|
+
}
|
|
853
|
+
function resolveAuthenticationSession(value) {
|
|
854
|
+
if (!isRecord(value)) return;
|
|
855
|
+
const session = value.session;
|
|
856
|
+
const user = value.user;
|
|
857
|
+
if (!isRecord(session) || !isRecord(user)) return;
|
|
858
|
+
const userId = user.id;
|
|
859
|
+
if (typeof userId !== "string" || userId.length === 0) return;
|
|
860
|
+
return {
|
|
861
|
+
auth: value,
|
|
862
|
+
session,
|
|
863
|
+
user,
|
|
864
|
+
userId
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
function isUnauthorizedApiError(error) {
|
|
868
|
+
if (typeof error !== "object" || error === null) return false;
|
|
869
|
+
try {
|
|
870
|
+
if (Reflect.get(error, "name") !== "APIError" || Reflect.get(error, "statusCode") !== 401) return false;
|
|
871
|
+
const body = Reflect.get(error, "body");
|
|
872
|
+
return typeof body === "object" && body !== null && Reflect.get(body, "code") === "FAILED_TO_GET_SESSION";
|
|
873
|
+
} catch {
|
|
874
|
+
return false;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
function readProperty(value, property) {
|
|
878
|
+
return value[property];
|
|
879
|
+
}
|
|
880
|
+
function isRecord(value) {
|
|
881
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
882
|
+
}
|
|
883
|
+
//#endregion
|
|
884
|
+
//#region src/session-marker.ts
|
|
885
|
+
/**
|
|
886
|
+
* Name of the cookie that tells browser code a session exists. It holds `1`, never a secret, and it is not HttpOnly,
|
|
887
|
+
* so a page script can skip a session request for a visitor who never signed in. It does not prove a session:
|
|
888
|
+
* the server still decides.
|
|
889
|
+
*/
|
|
890
|
+
const authSessionMarkerCookie = "vitehub_session";
|
|
891
|
+
const markerAttributes = [
|
|
892
|
+
"domain",
|
|
893
|
+
"expires",
|
|
894
|
+
"max-age",
|
|
895
|
+
"path",
|
|
896
|
+
"samesite",
|
|
897
|
+
"partitioned"
|
|
898
|
+
];
|
|
899
|
+
function requestSource(input) {
|
|
900
|
+
if (isRequestLike(input)) return input;
|
|
901
|
+
if (isRequestLike(input?.request)) return input.request;
|
|
902
|
+
const headers = new Headers(input?.headers);
|
|
903
|
+
return headers.has("host") || headers.has("x-forwarded-host") ? headers : void 0;
|
|
904
|
+
}
|
|
905
|
+
function readSetCookie(cookie) {
|
|
906
|
+
const [pair = "", ...rest] = cookie.split(";").map((part) => part.trim());
|
|
907
|
+
const separator = pair.indexOf("=");
|
|
908
|
+
const name = separator < 0 ? pair : pair.slice(0, separator);
|
|
909
|
+
const value = separator < 0 ? "" : pair.slice(separator + 1);
|
|
910
|
+
const attributes = rest.filter((part) => {
|
|
911
|
+
const key = part.split("=", 1)[0].toLowerCase();
|
|
912
|
+
return key === "secure" || markerAttributes.includes(key);
|
|
913
|
+
});
|
|
914
|
+
const maxAge = rest.find((part) => part.toLowerCase().startsWith("max-age="))?.slice(8);
|
|
915
|
+
const expires = rest.find((part) => part.toLowerCase().startsWith("expires="))?.slice(8);
|
|
916
|
+
const expired = maxAge !== void 0 && Number(maxAge) <= 0 || maxAge === void 0 && expires !== void 0 && Date.parse(expires) <= Date.now();
|
|
917
|
+
return {
|
|
918
|
+
attributes,
|
|
919
|
+
cleared: !value || expired,
|
|
920
|
+
name
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Sets `vitehub_session` next to the session cookie with the same lifetime, path, domain, and SameSite, and clears it
|
|
925
|
+
* when Better Auth clears the session cookie, such as on sign-out.
|
|
926
|
+
*/
|
|
927
|
+
function withSessionMarker(auth) {
|
|
928
|
+
async function markHeaders(original, input) {
|
|
929
|
+
const setCookies = readSetCookies(original);
|
|
930
|
+
if (setCookies.length === 0) return;
|
|
931
|
+
const context = await auth.$context;
|
|
932
|
+
const options = context.options;
|
|
933
|
+
let sessionCookie = context.authCookies.sessionToken.name;
|
|
934
|
+
if (typeof options.baseURL === "object" && options.advanced?.crossSubDomainCookies?.enabled) {
|
|
935
|
+
const baseURL = resolveBaseURL(options.baseURL, options.basePath || "/api/auth", requestSource(input), void 0, options.advanced.trustedProxyHeaders ?? false);
|
|
936
|
+
sessionCookie = getCookies({
|
|
937
|
+
...options,
|
|
938
|
+
baseURL
|
|
939
|
+
}).sessionToken.name;
|
|
940
|
+
}
|
|
941
|
+
const session = setCookies.map(readSetCookie).findLast((cookie) => cookie.name === sessionCookie);
|
|
942
|
+
if (!session) return;
|
|
943
|
+
const marker = [
|
|
944
|
+
`${authSessionMarkerCookie}=${session.cleared ? "" : "1"}`,
|
|
945
|
+
...session.attributes,
|
|
946
|
+
...session.cleared ? ["Max-Age=0"] : []
|
|
947
|
+
].join("; ");
|
|
948
|
+
const headers = new Headers(original);
|
|
949
|
+
headers.delete("set-cookie");
|
|
950
|
+
for (const cookie of setCookies) if (!cookie.startsWith(`vitehub_session=`)) headers.append("set-cookie", cookie);
|
|
951
|
+
headers.append("set-cookie", marker);
|
|
952
|
+
return headers;
|
|
953
|
+
}
|
|
954
|
+
async function markResponse(response, input) {
|
|
955
|
+
const headers = await markHeaders(response.headers, input);
|
|
956
|
+
return headers ? new Response(response.body, {
|
|
957
|
+
headers,
|
|
958
|
+
status: response.status,
|
|
959
|
+
statusText: response.statusText
|
|
960
|
+
}) : response;
|
|
961
|
+
}
|
|
962
|
+
const handler = auth.handler;
|
|
963
|
+
const markedHandler = async (request) => markResponse(await handler(request), request);
|
|
964
|
+
const originalApi = Object.getOwnPropertyDescriptor(auth, "api")?.value;
|
|
965
|
+
if (originalApi) auth.api = Object.fromEntries(Object.entries(originalApi).map(([name, endpoint]) => [name, Object.assign(async (input) => {
|
|
966
|
+
const result = await Reflect.apply(endpoint, originalApi, [input]);
|
|
967
|
+
if (result instanceof Response) return markResponse(result, input);
|
|
968
|
+
if (input?.returnHeaders && result && typeof result === "object" && "headers" in result && result.headers instanceof Headers) {
|
|
969
|
+
const headers = await markHeaders(result.headers, input);
|
|
970
|
+
return headers ? {
|
|
971
|
+
...result,
|
|
972
|
+
headers
|
|
973
|
+
} : result;
|
|
974
|
+
}
|
|
975
|
+
return result;
|
|
976
|
+
}, endpoint)]));
|
|
977
|
+
return Object.assign(auth, {
|
|
978
|
+
handler: markedHandler,
|
|
979
|
+
fetch: markedHandler
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
//#endregion
|
|
983
|
+
//#region src/server.ts
|
|
984
|
+
function hasRuntimeOptions(options) {
|
|
985
|
+
return Boolean(options && Object.keys(options).length > 0);
|
|
986
|
+
}
|
|
987
|
+
function hasRequestRuntimeOptions(definition) {
|
|
988
|
+
if (typeof definition.options === "function") return true;
|
|
989
|
+
return typeof definition.options.runtime === "function";
|
|
990
|
+
}
|
|
991
|
+
function hasConfiguredPublicUrl() {
|
|
992
|
+
return typeof __VITEHUB_PUBLIC_URL__ !== "undefined" && Boolean(__VITEHUB_PUBLIC_URL__?.url || Object.keys(__VITEHUB_PUBLIC_URL__?.agents ?? {}).length);
|
|
993
|
+
}
|
|
994
|
+
function setAuthRuntimeEnvResolver(resolver, definition) {
|
|
995
|
+
const state = getAuthRuntimeState();
|
|
996
|
+
if (definition) state.envResolvers?.set(definition, resolver);
|
|
997
|
+
else state.envResolver = resolver;
|
|
998
|
+
}
|
|
999
|
+
function envResolverFor(definition) {
|
|
1000
|
+
return getAuthRuntimeState().envResolvers?.get(definition) ?? getAuthRuntimeState().envResolver;
|
|
1001
|
+
}
|
|
1002
|
+
function isRequestLike$1(value) {
|
|
1003
|
+
try {
|
|
1004
|
+
const isBrandCheckError = (error) => {
|
|
1005
|
+
if (typeof error !== "object" && typeof error !== "function" || error === null) return false;
|
|
1006
|
+
try {
|
|
1007
|
+
if (Object.prototype.toString.call(error) !== "[object Error]") return false;
|
|
1008
|
+
} catch {
|
|
1009
|
+
return false;
|
|
1010
|
+
}
|
|
1011
|
+
let name;
|
|
1012
|
+
let message;
|
|
1013
|
+
try {
|
|
1014
|
+
name = Reflect.get(error, "name");
|
|
1015
|
+
message = Reflect.get(error, "message");
|
|
1016
|
+
} catch {
|
|
1017
|
+
return false;
|
|
1018
|
+
}
|
|
1019
|
+
return name === "TypeError" && typeof message === "string" && /illegal invocation|invalid (this|receiver)|brand|cannot read properties of (?:null|undefined)|must be (?:an? )?instance/i.test(message);
|
|
1020
|
+
};
|
|
1021
|
+
if (Object.prototype.toString.call(value) !== "[object Request]") return false;
|
|
1022
|
+
const hasPrototypeTag = (target, tag) => {
|
|
1023
|
+
let prototype = Object.getPrototypeOf(target);
|
|
1024
|
+
while (prototype) {
|
|
1025
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
|
|
1026
|
+
if (descriptor) {
|
|
1027
|
+
if (typeof descriptor.get === "function") return descriptor.get.call(target) === tag;
|
|
1028
|
+
return "value" in descriptor && descriptor.value === tag;
|
|
1029
|
+
}
|
|
1030
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
1031
|
+
}
|
|
1032
|
+
return false;
|
|
1033
|
+
};
|
|
1034
|
+
const hasBrandedAccessor = (target, property) => {
|
|
1035
|
+
let current = Object.getPrototypeOf(target);
|
|
1036
|
+
while (current) {
|
|
1037
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, property);
|
|
1038
|
+
if (descriptor) {
|
|
1039
|
+
if (typeof descriptor.get !== "function") return false;
|
|
1040
|
+
try {
|
|
1041
|
+
descriptor.get.call(Object.create(null));
|
|
1042
|
+
if (target !== value) return false;
|
|
1043
|
+
const ownSymbols = Object.getOwnPropertySymbols(value);
|
|
1044
|
+
const prototypeSymbols = Object.getOwnPropertySymbols(Object.getPrototypeOf(value) ?? {});
|
|
1045
|
+
if (!([
|
|
1046
|
+
"method",
|
|
1047
|
+
"body",
|
|
1048
|
+
"mode",
|
|
1049
|
+
"headers",
|
|
1050
|
+
"redirect",
|
|
1051
|
+
"referrerPolicy",
|
|
1052
|
+
"signal",
|
|
1053
|
+
"bodyUsed",
|
|
1054
|
+
"credentials",
|
|
1055
|
+
"aborted",
|
|
1056
|
+
"error",
|
|
1057
|
+
"contentLength",
|
|
1058
|
+
"contentType",
|
|
1059
|
+
"referrer",
|
|
1060
|
+
"url",
|
|
1061
|
+
"bodyBuffer"
|
|
1062
|
+
].every((name) => ownSymbols.some((symbol) => symbol.description === name)) && prototypeSymbols.some((symbol) => symbol.description === "window"))) return false;
|
|
1063
|
+
return true;
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
if (!isBrandCheckError(error)) return false;
|
|
1066
|
+
return true;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
current = Object.getPrototypeOf(current);
|
|
1070
|
+
}
|
|
1071
|
+
return false;
|
|
1072
|
+
};
|
|
1073
|
+
if (!hasPrototypeTag(value, "Request")) return false;
|
|
1074
|
+
const hasMethods = (target, methods) => methods.every((method) => {
|
|
1075
|
+
return typeof Reflect.get(target, method) === "function";
|
|
1076
|
+
});
|
|
1077
|
+
const ownSymbols = Object.getOwnPropertySymbols(value);
|
|
1078
|
+
const prototypeSymbols = Object.getOwnPropertySymbols(Object.getPrototypeOf(value) ?? {});
|
|
1079
|
+
if ([
|
|
1080
|
+
"method",
|
|
1081
|
+
"body",
|
|
1082
|
+
"mode",
|
|
1083
|
+
"headers",
|
|
1084
|
+
"redirect",
|
|
1085
|
+
"referrerPolicy",
|
|
1086
|
+
"signal",
|
|
1087
|
+
"bodyUsed",
|
|
1088
|
+
"credentials",
|
|
1089
|
+
"aborted",
|
|
1090
|
+
"error",
|
|
1091
|
+
"contentLength",
|
|
1092
|
+
"contentType",
|
|
1093
|
+
"referrer",
|
|
1094
|
+
"url",
|
|
1095
|
+
"bodyBuffer"
|
|
1096
|
+
].every((name) => ownSymbols.some((symbol) => symbol.description === name)) && prototypeSymbols.some((symbol) => symbol.description === "window")) {
|
|
1097
|
+
if (!hasMethods(value, [
|
|
1098
|
+
"clone",
|
|
1099
|
+
"arrayBuffer",
|
|
1100
|
+
"blob",
|
|
1101
|
+
"formData",
|
|
1102
|
+
"json",
|
|
1103
|
+
"text"
|
|
1104
|
+
])) return false;
|
|
1105
|
+
if (!value.headers || !hasMethods(value.headers, [
|
|
1106
|
+
"get",
|
|
1107
|
+
"has",
|
|
1108
|
+
"set",
|
|
1109
|
+
"append",
|
|
1110
|
+
"delete",
|
|
1111
|
+
"entries",
|
|
1112
|
+
"forEach"
|
|
1113
|
+
])) return false;
|
|
1114
|
+
if (!value.signal || typeof value.signal.aborted !== "boolean") return false;
|
|
1115
|
+
return true;
|
|
1116
|
+
}
|
|
1117
|
+
if (![
|
|
1118
|
+
"body",
|
|
1119
|
+
"bodyUsed",
|
|
1120
|
+
"headers",
|
|
1121
|
+
"method",
|
|
1122
|
+
"signal",
|
|
1123
|
+
"url"
|
|
1124
|
+
].every((property) => hasBrandedAccessor(value, property))) return false;
|
|
1125
|
+
if (!hasMethods(value, [
|
|
1126
|
+
"clone",
|
|
1127
|
+
"arrayBuffer",
|
|
1128
|
+
"blob",
|
|
1129
|
+
"formData",
|
|
1130
|
+
"json",
|
|
1131
|
+
"text"
|
|
1132
|
+
])) return false;
|
|
1133
|
+
if (!value.headers || Object.prototype.toString.call(value.headers) !== "[object Headers]" || !hasPrototypeTag(value.headers, "Headers") || !hasMethods(value.headers, [
|
|
1134
|
+
"get",
|
|
1135
|
+
"has",
|
|
1136
|
+
"set",
|
|
1137
|
+
"append",
|
|
1138
|
+
"delete",
|
|
1139
|
+
"entries",
|
|
1140
|
+
"forEach"
|
|
1141
|
+
])) return false;
|
|
1142
|
+
if ([
|
|
1143
|
+
"get",
|
|
1144
|
+
"has",
|
|
1145
|
+
"set",
|
|
1146
|
+
"append",
|
|
1147
|
+
"delete",
|
|
1148
|
+
"entries",
|
|
1149
|
+
"forEach"
|
|
1150
|
+
].some((method) => Object.prototype.hasOwnProperty.call(value.headers, method))) return false;
|
|
1151
|
+
const headersGet = Reflect.get(value.headers, "get");
|
|
1152
|
+
if (typeof headersGet !== "function") return false;
|
|
1153
|
+
try {
|
|
1154
|
+
headersGet.call(Object.create(null), "");
|
|
1155
|
+
return false;
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
if (!isBrandCheckError(error)) return false;
|
|
1158
|
+
}
|
|
1159
|
+
if (!value.signal || Object.prototype.toString.call(value.signal) !== "[object AbortSignal]" || !hasPrototypeTag(value.signal, "AbortSignal") || typeof value.signal.aborted !== "boolean") return false;
|
|
1160
|
+
if (Object.prototype.hasOwnProperty.call(value.signal, "aborted")) return false;
|
|
1161
|
+
return true;
|
|
1162
|
+
} catch {
|
|
1163
|
+
return false;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
function isAbortSignalLike(value) {
|
|
1167
|
+
if (!value || typeof value !== "object" && typeof value !== "function") return false;
|
|
1168
|
+
try {
|
|
1169
|
+
let prototype = Object.getPrototypeOf(value);
|
|
1170
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1171
|
+
while (prototype && !seen.has(prototype)) {
|
|
1172
|
+
seen.add(prototype);
|
|
1173
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, "aborted");
|
|
1174
|
+
if (descriptor?.get) return typeof Reflect.apply(descriptor.get, value, []) === "boolean";
|
|
1175
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
1176
|
+
}
|
|
1177
|
+
} catch {
|
|
1178
|
+
return false;
|
|
1179
|
+
}
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* The Headers init of a host request. A Headers-like object without `Symbol.iterator`, from another
|
|
1184
|
+
* Fetch implementation, gives its fields through `entries()`, not through its own properties.
|
|
1185
|
+
*/
|
|
1186
|
+
function headersInit(headers) {
|
|
1187
|
+
const value = headers;
|
|
1188
|
+
if (typeof value !== "object" || value === null || typeof Reflect.get(value, Symbol.iterator) === "function") return headers;
|
|
1189
|
+
const entries = Reflect.get(value, "entries");
|
|
1190
|
+
if (typeof entries !== "function") return headers;
|
|
1191
|
+
return Array.from(Reflect.apply(entries, value, []));
|
|
1192
|
+
}
|
|
1193
|
+
function toRequest(request) {
|
|
1194
|
+
if (request instanceof Request || isRequestLike$1(request)) return request;
|
|
1195
|
+
const init = { method: request.method };
|
|
1196
|
+
init.headers = new Headers(headersInit(request.headers));
|
|
1197
|
+
if (isAbortSignalLike(request.signal)) init.signal = request.signal;
|
|
1198
|
+
if (request.body) {
|
|
1199
|
+
init.body = request.body;
|
|
1200
|
+
init.duplex = "half";
|
|
1201
|
+
}
|
|
1202
|
+
return new Request(request.url, init);
|
|
1203
|
+
}
|
|
1204
|
+
function createAuthRequestRuntimeOptions(definition, request, runtimeOptions = {}, event) {
|
|
1205
|
+
return resolveAuthOptions(definition, {
|
|
1206
|
+
request,
|
|
1207
|
+
runtimeOptions,
|
|
1208
|
+
event,
|
|
1209
|
+
env: envResolverFor(definition)
|
|
1210
|
+
}).requestRuntimeOptions;
|
|
1211
|
+
}
|
|
1212
|
+
function resolveDefaultDefinition() {
|
|
1213
|
+
if (!discoveredDefinition) throw authErrorDiagnostics.AUTH_R0005({ message: "[vitehub] No Auth Definition was discovered. Add `server/auth.ts` or `server.auth.ts`." });
|
|
1214
|
+
return discoveredDefinition;
|
|
1215
|
+
}
|
|
1216
|
+
function createBetterAuthOptions(definition, runtimeOptions = {}) {
|
|
1217
|
+
return resolveAuthOptions(definition, {
|
|
1218
|
+
runtimeOptions,
|
|
1219
|
+
env: envResolverFor(definition)
|
|
1220
|
+
}).providerOptions;
|
|
1221
|
+
}
|
|
1222
|
+
function createAuthenticationProvider(options) {
|
|
1223
|
+
try {
|
|
1224
|
+
return withSessionMarker(betterAuth(options));
|
|
1225
|
+
} catch (cause) {
|
|
1226
|
+
throwAuthenticationProviderError(cause, "get-auth-for-request");
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
function createAuth(definition, runtimeOptions) {
|
|
1230
|
+
return withSessionMarker(betterAuth(createBetterAuthOptions(definition, runtimeOptions)));
|
|
1231
|
+
}
|
|
1232
|
+
function createAuthForRequest(definition, request, runtimeOptions, event) {
|
|
1233
|
+
return withSessionMarker(betterAuth(resolveAuthOptions(definition, {
|
|
1234
|
+
request,
|
|
1235
|
+
runtimeOptions,
|
|
1236
|
+
event,
|
|
1237
|
+
env: envResolverFor(definition)
|
|
1238
|
+
}).providerOptions));
|
|
1239
|
+
}
|
|
1240
|
+
function handleAuthRequest(definition, input, runtimeOptions, event = input) {
|
|
1241
|
+
const request = unwrapAuthRequest(input);
|
|
1242
|
+
return createAuthForRequest(definition, request, runtimeOptions, event).handler(toRequest(request));
|
|
1243
|
+
}
|
|
1244
|
+
/** Return the request of a Web Request or a host server event, including an H3 1 event in Nuxt 4. */
|
|
1245
|
+
function toAuthRequest(input) {
|
|
1246
|
+
return unwrapAuthRequest(input);
|
|
1247
|
+
}
|
|
1248
|
+
function createAuthHandler(definition, runtimeOptions) {
|
|
1249
|
+
return createAuth(definition, runtimeOptions).handler;
|
|
1250
|
+
}
|
|
1251
|
+
function getAuthForDefinition(definition, runtimeOptions) {
|
|
1252
|
+
if (hasRuntimeOptions(runtimeOptions)) return createAuthenticationProvider(createBetterAuthOptions(definition, runtimeOptions));
|
|
1253
|
+
return cachedAuth(definition);
|
|
1254
|
+
}
|
|
1255
|
+
function cachedAuth(definition) {
|
|
1256
|
+
const state = getAuthRuntimeState();
|
|
1257
|
+
if (!state.auth || state.definition !== definition) {
|
|
1258
|
+
state.auth = createAuthenticationProvider(createBetterAuthOptions(definition));
|
|
1259
|
+
state.definition = definition;
|
|
1260
|
+
}
|
|
1261
|
+
return state.auth;
|
|
1262
|
+
}
|
|
1263
|
+
function getAuth(runtimeOptions) {
|
|
1264
|
+
return getAuthForDefinition(resolveDefaultDefinition(), runtimeOptions);
|
|
1265
|
+
}
|
|
1266
|
+
/** Return the Better Auth instance of the app's Auth Definition, typed with its plugins by the generated types. */
|
|
1267
|
+
function getAuthForRequest(request, runtimeOptions, event) {
|
|
1268
|
+
const definition = resolveDefaultDefinition();
|
|
1269
|
+
if (!hasRequestRuntimeOptions(definition) && !hasRuntimeOptions(runtimeOptions) && !hasConfiguredPublicUrl()) return getAuthForDefinition(definition);
|
|
1270
|
+
return createAuthenticationProvider(resolveAuthOptions(definition, {
|
|
1271
|
+
request,
|
|
1272
|
+
runtimeOptions,
|
|
1273
|
+
event,
|
|
1274
|
+
env: envResolverFor(definition)
|
|
1275
|
+
}).providerOptions);
|
|
1276
|
+
}
|
|
1277
|
+
async function assertAuthOrigin(request, event) {
|
|
1278
|
+
const origin = request.headers.get("origin");
|
|
1279
|
+
if (!origin) throw authErrorDiagnostics.AUTH_R0006({ message: "The request origin is required." });
|
|
1280
|
+
const auth = getAuthForRequest(request, void 0, event);
|
|
1281
|
+
if (!(await auth.$context).isTrustedOrigin(origin)) throw authErrorDiagnostics.AUTH_R0007({ message: "The request origin is not trusted." });
|
|
1282
|
+
return auth;
|
|
1283
|
+
}
|
|
1284
|
+
function handleAuth(input, runtimeOptions) {
|
|
1285
|
+
return handleAuthRequest(resolveDefaultDefinition(), input, runtimeOptions, input);
|
|
1286
|
+
}
|
|
1287
|
+
function wantsHtml(request) {
|
|
1288
|
+
return request.method === "GET" && request.headers.get("accept")?.includes("text/html") === true;
|
|
1289
|
+
}
|
|
1290
|
+
function createForbiddenResponse(request) {
|
|
1291
|
+
return wantsHtml(request) ? new Response("Forbidden.", {
|
|
1292
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
1293
|
+
status: 403
|
|
1294
|
+
}) : Response.json({ error: "Forbidden." }, { status: 403 });
|
|
1295
|
+
}
|
|
1296
|
+
function authAccessRoutes(options, routeIndexes) {
|
|
1297
|
+
const routes = options.access?.routes;
|
|
1298
|
+
return routeIndexes.map((routeIndex) => {
|
|
1299
|
+
const route = routes?.[routeIndex];
|
|
1300
|
+
if (!route) throw authErrorDiagnostics.AUTH_R0008({ message: `[vitehub] Auth access route ${routeIndex} is unavailable at runtime.` });
|
|
1301
|
+
return route;
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
async function createSignInResponse(auth, options, signIn) {
|
|
1305
|
+
const origin = new URL(options.baseURL).origin;
|
|
1306
|
+
const basePath = resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0));
|
|
1307
|
+
const response = await auth.handler(new Request(`${origin}${basePath}/sign-in/social`, {
|
|
1308
|
+
body: JSON.stringify({
|
|
1309
|
+
callbackURL: signIn.callbackURL,
|
|
1310
|
+
errorCallbackURL: signIn.errorCallbackURL,
|
|
1311
|
+
provider: signIn.provider,
|
|
1312
|
+
requestSignUp: signIn.requestSignUp,
|
|
1313
|
+
scopes: signIn.scopes
|
|
1314
|
+
}),
|
|
1315
|
+
headers: {
|
|
1316
|
+
"content-type": "application/json",
|
|
1317
|
+
"accept": "application/json",
|
|
1318
|
+
"origin": origin
|
|
1319
|
+
},
|
|
1320
|
+
method: "POST"
|
|
1321
|
+
}));
|
|
1322
|
+
if (!response.ok) return response;
|
|
1323
|
+
const body = await response.json().catch(() => void 0);
|
|
1324
|
+
if (typeof body?.url !== "string") return Response.json({ error: "Auth sign-in did not return a redirect URL." }, { status: 502 });
|
|
1325
|
+
const headers = new Headers(response.headers);
|
|
1326
|
+
headers.delete("content-type");
|
|
1327
|
+
headers.set("location", body.url);
|
|
1328
|
+
return new Response(null, {
|
|
1329
|
+
headers,
|
|
1330
|
+
status: 302
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
async function readRequestSession(input, definition) {
|
|
1334
|
+
const request = unwrapAuthRequest(input);
|
|
1335
|
+
const { options, providerOptions } = resolveAuthOptions(definition, {
|
|
1336
|
+
request,
|
|
1337
|
+
event: input,
|
|
1338
|
+
env: envResolverFor(definition)
|
|
1339
|
+
});
|
|
1340
|
+
const auth = createAuthenticationProvider(providerOptions);
|
|
1341
|
+
return {
|
|
1342
|
+
auth,
|
|
1343
|
+
options,
|
|
1344
|
+
request,
|
|
1345
|
+
session: await getAuthenticationSession(auth, { headers: request.headers })
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
function reject(response) {
|
|
1349
|
+
return { response };
|
|
1350
|
+
}
|
|
1351
|
+
const nativeResponseStatus = Object.getOwnPropertyDescriptor(Response.prototype, "status")?.get;
|
|
1352
|
+
const nativeResponseClone = Object.getOwnPropertyDescriptor(Response.prototype, "clone")?.value;
|
|
1353
|
+
/**
|
|
1354
|
+
* Return whether `value` is a Response of this runtime.
|
|
1355
|
+
* The native `status` getter checks the internal Response slot, so a proxy, a copied prototype, an object tagged `Response`,
|
|
1356
|
+
* and a Response from another Fetch implementation all fail. The check reads no property of `value`.
|
|
1357
|
+
*/
|
|
1358
|
+
function isRuntimeResponse(value) {
|
|
1359
|
+
if (!nativeResponseStatus || value === null || typeof value !== "object") return false;
|
|
1360
|
+
try {
|
|
1361
|
+
Reflect.apply(nativeResponseStatus, value, []);
|
|
1362
|
+
return true;
|
|
1363
|
+
} catch {
|
|
1364
|
+
return false;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* A Response of this runtime with an own `then` would be assimilated as a thenable by the host that awaits it.
|
|
1369
|
+
* Send a native clone instead, so the rejection still reaches the client as a Response.
|
|
1370
|
+
*/
|
|
1371
|
+
function sendableRuntimeResponse(value, request) {
|
|
1372
|
+
if (!Object.prototype.hasOwnProperty.call(value, "then")) return value;
|
|
1373
|
+
try {
|
|
1374
|
+
return nativeResponseClone ? Reflect.apply(nativeResponseClone, value, []) : createForbiddenResponse(request);
|
|
1375
|
+
} catch {
|
|
1376
|
+
return createForbiddenResponse(request);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
const nativePromiseThen = Object.getOwnPropertyDescriptor(Promise.prototype, "then")?.value;
|
|
1380
|
+
const nativePromiseResolve = Promise.resolve;
|
|
1381
|
+
function hasNativePromiseBrand(value) {
|
|
1382
|
+
if (!nativePromiseThen) return false;
|
|
1383
|
+
try {
|
|
1384
|
+
let prototype = Object.getPrototypeOf(value);
|
|
1385
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1386
|
+
while (prototype && !seen.has(prototype)) {
|
|
1387
|
+
seen.add(prototype);
|
|
1388
|
+
if (Object.prototype.hasOwnProperty.call(prototype, "then") && Object.getOwnPropertyDescriptor(prototype, "then")?.value === nativePromiseThen) return true;
|
|
1389
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
1390
|
+
}
|
|
1391
|
+
const valueDescriptor = Object.getOwnPropertyDescriptor(value, "constructor");
|
|
1392
|
+
let valueOverridden = false;
|
|
1393
|
+
try {
|
|
1394
|
+
if (!valueDescriptor || valueDescriptor.configurable) {
|
|
1395
|
+
Object.defineProperty(value, "constructor", {
|
|
1396
|
+
configurable: true,
|
|
1397
|
+
writable: true,
|
|
1398
|
+
value: Promise
|
|
1399
|
+
});
|
|
1400
|
+
valueOverridden = true;
|
|
1401
|
+
} else if ("value" in valueDescriptor && valueDescriptor.writable) {
|
|
1402
|
+
Object.defineProperty(value, "constructor", { value: Promise });
|
|
1403
|
+
valueOverridden = true;
|
|
1404
|
+
}
|
|
1405
|
+
} catch {}
|
|
1406
|
+
let probe;
|
|
1407
|
+
try {
|
|
1408
|
+
probe = Reflect.apply(nativePromiseThen, value, [() => void 0, () => void 0]);
|
|
1409
|
+
} finally {
|
|
1410
|
+
if (valueOverridden) {
|
|
1411
|
+
if (valueDescriptor) Object.defineProperty(value, "constructor", valueDescriptor);
|
|
1412
|
+
else Reflect.deleteProperty(value, "constructor");
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
if (probe && (typeof probe === "object" || typeof probe === "function")) {
|
|
1416
|
+
const descriptor = Object.getOwnPropertyDescriptor(probe, "constructor");
|
|
1417
|
+
let overridden = false;
|
|
1418
|
+
try {
|
|
1419
|
+
if (!descriptor || descriptor.configurable) {
|
|
1420
|
+
Object.defineProperty(probe, "constructor", {
|
|
1421
|
+
configurable: true,
|
|
1422
|
+
writable: true,
|
|
1423
|
+
value: Promise
|
|
1424
|
+
});
|
|
1425
|
+
overridden = true;
|
|
1426
|
+
} else if ("value" in descriptor && descriptor.writable) {
|
|
1427
|
+
Object.defineProperty(probe, "constructor", { value: Promise });
|
|
1428
|
+
overridden = true;
|
|
1429
|
+
}
|
|
1430
|
+
const cleanup = Reflect.apply(nativePromiseThen, probe, [() => void 0, () => void 0]);
|
|
1431
|
+
if (cleanup && (typeof cleanup === "object" || typeof cleanup === "function")) {
|
|
1432
|
+
const cleanupDescriptor = Object.getOwnPropertyDescriptor(cleanup, "constructor");
|
|
1433
|
+
let cleanupOverridden = false;
|
|
1434
|
+
try {
|
|
1435
|
+
if (!cleanupDescriptor || cleanupDescriptor.configurable) {
|
|
1436
|
+
Object.defineProperty(cleanup, "constructor", {
|
|
1437
|
+
configurable: true,
|
|
1438
|
+
writable: true,
|
|
1439
|
+
value: Promise
|
|
1440
|
+
});
|
|
1441
|
+
cleanupOverridden = true;
|
|
1442
|
+
} else if ("value" in cleanupDescriptor && cleanupDescriptor.writable) {
|
|
1443
|
+
Object.defineProperty(cleanup, "constructor", { value: Promise });
|
|
1444
|
+
cleanupOverridden = true;
|
|
1445
|
+
}
|
|
1446
|
+
const cleanupResult = Reflect.apply(nativePromiseThen, cleanup, [() => void 0, () => void 0]);
|
|
1447
|
+
if (cleanupResult && (typeof cleanupResult === "object" || typeof cleanupResult === "function")) Reflect.apply(nativePromiseThen, cleanupResult, [() => void 0, () => void 0]);
|
|
1448
|
+
} finally {
|
|
1449
|
+
if (cleanupOverridden) {
|
|
1450
|
+
if (cleanupDescriptor) Object.defineProperty(cleanup, "constructor", cleanupDescriptor);
|
|
1451
|
+
else Reflect.deleteProperty(cleanup, "constructor");
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
} finally {
|
|
1456
|
+
if (overridden) {
|
|
1457
|
+
if (descriptor) Object.defineProperty(probe, "constructor", descriptor);
|
|
1458
|
+
else Reflect.deleteProperty(probe, "constructor");
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
return true;
|
|
1463
|
+
} catch {
|
|
1464
|
+
return false;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Only `true` grants access. A Response of this runtime is sent as the rejection. Every other value gets `403`.
|
|
1469
|
+
*/
|
|
1470
|
+
async function runAccessAuthorize(authorize, context) {
|
|
1471
|
+
const result = authorize(context);
|
|
1472
|
+
if (isRuntimeResponse(result)) return { response: sendableRuntimeResponse(result, context.request) };
|
|
1473
|
+
let resolved;
|
|
1474
|
+
if (result !== null && (typeof result === "object" || typeof result === "function") && hasNativePromiseBrand(result)) {
|
|
1475
|
+
let nativePromise;
|
|
1476
|
+
let constructorDescriptor;
|
|
1477
|
+
let speciesDescriptor;
|
|
1478
|
+
let speciesOverridden = false;
|
|
1479
|
+
let constructorOverridden = false;
|
|
1480
|
+
try {
|
|
1481
|
+
constructorDescriptor = Object.getOwnPropertyDescriptor(result, "constructor");
|
|
1482
|
+
if (!constructorDescriptor || constructorDescriptor.configurable) {
|
|
1483
|
+
Object.defineProperty(result, "constructor", {
|
|
1484
|
+
configurable: true,
|
|
1485
|
+
writable: true,
|
|
1486
|
+
value: Promise
|
|
1487
|
+
});
|
|
1488
|
+
constructorOverridden = true;
|
|
1489
|
+
} else if (typeof constructorDescriptor.value === "function") {
|
|
1490
|
+
speciesDescriptor = Object.getOwnPropertyDescriptor(constructorDescriptor.value, Symbol.species);
|
|
1491
|
+
if (!speciesDescriptor || speciesDescriptor.configurable) {
|
|
1492
|
+
Object.defineProperty(constructorDescriptor.value, Symbol.species, {
|
|
1493
|
+
configurable: true,
|
|
1494
|
+
value: Promise
|
|
1495
|
+
});
|
|
1496
|
+
speciesOverridden = true;
|
|
1497
|
+
} else if ("value" in constructorDescriptor && constructorDescriptor.writable) {
|
|
1498
|
+
Object.defineProperty(result, "constructor", { value: Promise });
|
|
1499
|
+
constructorOverridden = true;
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
nativePromise = new Promise((resolve, reject) => {
|
|
1503
|
+
Promise.prototype.then.call(result, resolve, reject);
|
|
1504
|
+
});
|
|
1505
|
+
} catch (error) {
|
|
1506
|
+
try {
|
|
1507
|
+
nativePromise = Reflect.apply(nativePromiseResolve, Promise, [result]);
|
|
1508
|
+
} catch {
|
|
1509
|
+
nativePromise = Promise.reject(error);
|
|
1510
|
+
}
|
|
1511
|
+
} finally {
|
|
1512
|
+
if (constructorOverridden) {
|
|
1513
|
+
if (constructorDescriptor) Object.defineProperty(result, "constructor", constructorDescriptor);
|
|
1514
|
+
else Reflect.deleteProperty(result, "constructor");
|
|
1515
|
+
}
|
|
1516
|
+
if (speciesOverridden && constructorDescriptor && typeof constructorDescriptor.value === "function") {
|
|
1517
|
+
if (speciesDescriptor) Object.defineProperty(constructorDescriptor.value, Symbol.species, speciesDescriptor);
|
|
1518
|
+
else Reflect.deleteProperty(constructorDescriptor.value, Symbol.species);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
resolved = nativePromise ? await nativePromise : void 0;
|
|
1522
|
+
} else resolved = result !== null && (typeof result === "object" || typeof result === "function") ? await result : result;
|
|
1523
|
+
if (resolved === true) return {};
|
|
1524
|
+
if (isRuntimeResponse(resolved)) return { response: sendableRuntimeResponse(resolved, context.request) };
|
|
1525
|
+
return { response: createForbiddenResponse(context.request) };
|
|
1526
|
+
}
|
|
1527
|
+
async function checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes = [], redirectToSignIn = true, resolveIdentity) {
|
|
1528
|
+
const { auth, options, request, session } = await readRequestSession(input, definition);
|
|
1529
|
+
const identity = await resolveIdentity?.(toRequest(request), input, Boolean(session));
|
|
1530
|
+
if (isRuntimeResponse(identity)) return reject(identity);
|
|
1531
|
+
if (identity || session) {
|
|
1532
|
+
const authorization = Object.freeze({
|
|
1533
|
+
request,
|
|
1534
|
+
session: identity ? {} : session.session,
|
|
1535
|
+
user: identity ?? session.user
|
|
1536
|
+
});
|
|
1537
|
+
if (routeIndexes === void 0) return { authorization };
|
|
1538
|
+
const requiredAuthorizeRoutes = new Set(requiredAuthorizeRouteIndexes);
|
|
1539
|
+
const routes = authAccessRoutes(options, routeIndexes);
|
|
1540
|
+
for (const [index, route] of routes.entries()) {
|
|
1541
|
+
const authorize = typeof route === "object" && route !== null ? route.authorize : void 0;
|
|
1542
|
+
if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index])) return reject(createForbiddenResponse(request));
|
|
1543
|
+
if (!authorize) continue;
|
|
1544
|
+
const rejection = await runAccessAuthorize(authorize, authorization);
|
|
1545
|
+
if (rejection.response) return reject(rejection.response);
|
|
1546
|
+
}
|
|
1547
|
+
return { authorization };
|
|
1548
|
+
}
|
|
1549
|
+
if (!wantsHtml(request)) return reject(Response.json({ error: "Unauthorized." }, { status: 401 }));
|
|
1550
|
+
if (!redirectToSignIn) return reject(Response.json({ error: "Unauthorized." }, { status: 401 }));
|
|
1551
|
+
if (new URL(request.url).searchParams.has("auth_error")) return reject(new Response("Unauthorized.", {
|
|
1552
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
1553
|
+
status: 403
|
|
1554
|
+
}));
|
|
1555
|
+
const signIn = options.access?.signIn;
|
|
1556
|
+
return reject(signIn ? await createSignInResponse(auth, options, signIn) : Response.json({ error: "Unauthorized." }, { status: 401 }));
|
|
1557
|
+
}
|
|
1558
|
+
async function checkAuthorizeRequest(input, authorize, definition) {
|
|
1559
|
+
const { request, session } = await readRequestSession(input, definition);
|
|
1560
|
+
if (!session) return reject(Response.json({ error: "Unauthorized." }, { status: 401 }));
|
|
1561
|
+
const authorization = Object.freeze({
|
|
1562
|
+
request,
|
|
1563
|
+
session: session.session,
|
|
1564
|
+
user: session.user
|
|
1565
|
+
});
|
|
1566
|
+
if (authorize === true) return { authorization };
|
|
1567
|
+
const rejection = await runAccessAuthorize(authorize, authorization);
|
|
1568
|
+
return rejection.response ? reject(rejection.response) : { authorization };
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Wraps a server handler so it runs only with a signed-in Auth Session.
|
|
1572
|
+
* The handler receives the checked `authorization`. Otherwise the wrapper returns `401`, or starts `access.signIn` for HTML requests.
|
|
1573
|
+
*/
|
|
1574
|
+
function withAuth(handler, definition) {
|
|
1575
|
+
if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAuth() requires a handler function." });
|
|
1576
|
+
return async (input) => {
|
|
1577
|
+
const check = await checkAuthRequest(input, definition ?? resolveDefaultDefinition());
|
|
1578
|
+
if (check.response) return check.response;
|
|
1579
|
+
return handler(input, check.authorization);
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Wraps a resource handler, such as a Blob serve route or a Collection, so it runs only after `authorize` accepts the request.
|
|
1584
|
+
* Returns `401` without a session, `403` when `authorize` returns `false`, and a custom `Response` as-is.
|
|
1585
|
+
* It never redirects to sign-in, so image and fetch requests receive a status code.
|
|
1586
|
+
*/
|
|
1587
|
+
function withAuthorization(authorize, handler, definition) {
|
|
1588
|
+
if (authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
|
|
1589
|
+
if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAuthorization() requires a handler function." });
|
|
1590
|
+
return async (input) => {
|
|
1591
|
+
const check = await checkAuthorizeRequest(input, authorize, definition ?? resolveDefaultDefinition());
|
|
1592
|
+
if (check.response) return check.response;
|
|
1593
|
+
return handler(input, check.authorization);
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
const authorizationGrant = defineGrant("vitehub.auth.authorization", (authorization) => authorization);
|
|
1597
|
+
function authMiddleware(check) {
|
|
1598
|
+
return async (event, next) => {
|
|
1599
|
+
const result = await check(event);
|
|
1600
|
+
if (result.response) return result.response;
|
|
1601
|
+
authorizationGrant.attach(event, authorizationGrant.issue(result.authorization));
|
|
1602
|
+
return next();
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* Route middleware for H3 2 that lets the request continue only with a signed-in Auth Session.
|
|
1607
|
+
* It rejects like `withAuth()`: `401`, or the `access.signIn` redirect for HTML requests.
|
|
1608
|
+
* The route handler reads the checked authorization with `getAuthorization(event)`.
|
|
1609
|
+
*/
|
|
1610
|
+
function requireAuth(definition) {
|
|
1611
|
+
return authMiddleware((event) => checkAuthRequest(event, definition ?? resolveDefaultDefinition()));
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Route middleware for H3 2 that lets the request continue only after `authorize` accepts it.
|
|
1615
|
+
* It rejects like `withAuthorization()`: `401` without a session, `403` when `authorize` returns `false`,
|
|
1616
|
+
* or the callback's `Response`. It never redirects to sign-in.
|
|
1617
|
+
* The route handler reads the checked authorization with `getAuthorization(event)`.
|
|
1618
|
+
*/
|
|
1619
|
+
function requireAuthorization(authorize, definition) {
|
|
1620
|
+
if (authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
|
|
1621
|
+
return authMiddleware((event) => checkAuthorizeRequest(event, authorize, definition ?? resolveDefaultDefinition()));
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Return the checked request, Session, and user that `requireAuth()` or `requireAuthorization()` attached to `event`.
|
|
1625
|
+
* Throws when no Auth middleware accepted this event, so a route without the middleware fails closed.
|
|
1626
|
+
*/
|
|
1627
|
+
function getAuthorization(event) {
|
|
1628
|
+
const grant = authorizationGrant.attached(event);
|
|
1629
|
+
if (!grant) throw authErrorDiagnostics.AUTH_R0017({ message: "[vitehub] getAuthorization() found no checked Auth Session for this event. Add requireAuth() or requireAuthorization() to the route middleware." });
|
|
1630
|
+
return authorizationGrant.verify(grant);
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Let a trusted server integration authenticate one exact mounted path without a browser session.
|
|
1634
|
+
* Resolved users still pass every matching Auth access route's authorize callback, with an empty session.
|
|
1635
|
+
*/
|
|
1636
|
+
function setAuthAccessIdentityResolver(path, resolver) {
|
|
1637
|
+
const state = getAuthRuntimeState();
|
|
1638
|
+
state.accessIdentityResolvers ??= /* @__PURE__ */ new Map();
|
|
1639
|
+
if (resolver) state.accessIdentityResolvers.set(path, resolver);
|
|
1640
|
+
else state.accessIdentityResolvers.delete(path);
|
|
1641
|
+
}
|
|
1642
|
+
const reusableAccessChecks = /* @__PURE__ */ new WeakMap();
|
|
1643
|
+
async function checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options = {}) {
|
|
1644
|
+
const key = JSON.stringify([routeIndexes, requiredAuthorizeRouteIndexes]);
|
|
1645
|
+
let definitions = reusableAccessChecks.get(input);
|
|
1646
|
+
let accepted = definitions?.get(definition);
|
|
1647
|
+
const reusable = accepted?.get(key);
|
|
1648
|
+
if (reusable === true || options.reuse && reusable === false) return;
|
|
1649
|
+
const { response } = await checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options.redirectToSignIn !== false, getAuthRuntimeState().accessIdentityResolvers?.get(new URL(unwrapAuthRequest(input).url).pathname));
|
|
1650
|
+
if (!response && (options.reuse || options.remember)) {
|
|
1651
|
+
if (!definitions) reusableAccessChecks.set(input, definitions = /* @__PURE__ */ new WeakMap());
|
|
1652
|
+
if (!accepted) definitions.set(definition, accepted = /* @__PURE__ */ new Map());
|
|
1653
|
+
accepted.set(key, options.reuse === true);
|
|
1654
|
+
}
|
|
1655
|
+
return response;
|
|
1656
|
+
}
|
|
1657
|
+
/** Bind discovered access routes to a Web Request or host request handler. */
|
|
1658
|
+
function createAuthAccessHandler(routes, definition) {
|
|
1659
|
+
const rules = routes.map((route, index) => ({
|
|
1660
|
+
index,
|
|
1661
|
+
authorize: route.authorize === true,
|
|
1662
|
+
method: route.method?.toUpperCase(),
|
|
1663
|
+
path: (() => {
|
|
1664
|
+
const recursive = route.route.endsWith("/**");
|
|
1665
|
+
const resolved = resolveAuthMountPath(recursive ? route.route.slice(0, -3) : route.route);
|
|
1666
|
+
return recursive ? resolved === "/" ? "" : resolved.replace(/\/$/, "") : resolved;
|
|
1667
|
+
})(),
|
|
1668
|
+
recursive: route.route.endsWith("/**")
|
|
1669
|
+
}));
|
|
1670
|
+
return async (input) => {
|
|
1671
|
+
const request = unwrapAuthRequest(input);
|
|
1672
|
+
const pathname = new URL(request.url).pathname;
|
|
1673
|
+
const method = request.method.toUpperCase();
|
|
1674
|
+
const matched = rules.filter((rule) => (!rule.method || rule.method === method) && (pathname === rule.path || rule.recursive && (rule.path === "" || pathname.startsWith(`${rule.path}/`))));
|
|
1675
|
+
if (matched.length === 0) return;
|
|
1676
|
+
return await checkAuthAccessRequest(input, definition ?? resolveDefaultDefinition(), matched.map((rule) => rule.index), matched.filter((rule) => rule.authorize).map((rule) => rule.index), { remember: true });
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
async function requireAuthAccessRoutes(input, routeIndexes, definition = resolveDefaultDefinition(), requiredAuthorizeRouteIndexes = [], options = {}) {
|
|
1680
|
+
if (!Array.isArray(routeIndexes) || routeIndexes.length === 0 || routeIndexes.some((routeIndex) => !Number.isSafeInteger(routeIndex) || routeIndex < 0)) throw authErrorDiagnostics.AUTH_R0009({ message: "[vitehub] Auth access route indexes must be a non-empty array of non-negative integers." });
|
|
1681
|
+
if (!Array.isArray(requiredAuthorizeRouteIndexes) || requiredAuthorizeRouteIndexes.some((routeIndex) => !Number.isSafeInteger(routeIndex) || routeIndex < 0)) throw authErrorDiagnostics.AUTH_R0010({ message: "[vitehub] Required Auth authorize route indexes must be an array of non-negative integers." });
|
|
1682
|
+
return await checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options);
|
|
1683
|
+
}
|
|
1684
|
+
const auth = new Proxy({}, {
|
|
1685
|
+
get(_target, property, receiver) {
|
|
1686
|
+
return Reflect.get(getAuth(), property, receiver);
|
|
1687
|
+
},
|
|
1688
|
+
getOwnPropertyDescriptor(_target, property) {
|
|
1689
|
+
return Reflect.getOwnPropertyDescriptor(getAuth(), property);
|
|
1690
|
+
},
|
|
1691
|
+
has(_target, property) {
|
|
1692
|
+
return Reflect.has(getAuth(), property);
|
|
1693
|
+
},
|
|
1694
|
+
ownKeys() {
|
|
1695
|
+
return Reflect.ownKeys(getAuth());
|
|
1696
|
+
}
|
|
1697
|
+
});
|
|
1698
|
+
/** Read the configured log from server code. Apply access checks before returning it to a caller. */
|
|
1699
|
+
function getAuthEvents(definition = resolveDefaultDefinition(), request) {
|
|
1700
|
+
const events = resolveAuthOptions(definition, {
|
|
1701
|
+
request,
|
|
1702
|
+
env: envResolverFor(definition)
|
|
1703
|
+
}).options.events;
|
|
1704
|
+
return events ? events.store : void 0;
|
|
1705
|
+
}
|
|
1706
|
+
async function listAuthEvents(input = {}, definition) {
|
|
1707
|
+
const store = getAuthEvents(definition);
|
|
1708
|
+
if (!store) throw authErrorDiagnostics.AUTH_R0018({ message: "Auth events are disabled. Configure events.store in defineAuth()." });
|
|
1709
|
+
return store.list(input);
|
|
1710
|
+
}
|
|
1711
|
+
async function aggregateAuthEvents(window, definition) {
|
|
1712
|
+
const store = getAuthEvents(definition);
|
|
1713
|
+
if (!store) throw authErrorDiagnostics.AUTH_R0018({ message: "Auth events are disabled. Configure events.store in defineAuth()." });
|
|
1714
|
+
return store.aggregate(window);
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Resolve the primary Definition once, with the same request context for the provider and Console policy.
|
|
1718
|
+
* `host.impersonation` lets the Console start impersonation. It is off by default.
|
|
1719
|
+
*/
|
|
1720
|
+
function getAuthConsoleForRequest(request, event, host) {
|
|
1721
|
+
const definition = resolveDefaultDefinition();
|
|
1722
|
+
const resolved = resolveAuthOptions(definition, {
|
|
1723
|
+
request,
|
|
1724
|
+
event,
|
|
1725
|
+
env: envResolverFor(definition)
|
|
1726
|
+
});
|
|
1727
|
+
return createAuthConsole(createAuthenticationProvider(resolved.providerOptions), resolved.options.console, resolved.options.events ? resolved.options.events.store : void 0, host);
|
|
1728
|
+
}
|
|
1729
|
+
//#endregion
|
|
1730
|
+
export { setAuthRuntimeEnvResolver as C, getAuthenticationSession as D, withAuthorization as E, invalidAuthenticationErrorOptions as O, setAuthAccessIdentityResolver as S, withAuth as T, handleAuthRequest as _, createAuthAccessHandler as a, requireAuthAccessRoutes as b, createAuthRequestRuntimeOptions as c, getAuthConsoleForRequest as d, getAuthEvents as f, handleAuth as g, getAuthorization as h, createAuth as i, throwAuthenticationProviderError as k, createBetterAuthOptions as l, getAuthForRequest as m, assertAuthOrigin as n, createAuthForRequest as o, getAuthForDefinition as p, auth as r, createAuthHandler as s, aggregateAuthEvents as t, getAuth as u, listAuthEvents as v, toAuthRequest as w, requireAuthorization as x, requireAuth as y };
|