@vite-hub/auth 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -34
- package/dist/{abilities-DfAnFYwG.d.ts → abilities-CbmTAoS_.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-CqgBrBfR.js → ability-error-IeZQBr_-.js} +1 -1
- package/dist/agent.js +6 -5
- package/dist/{auth-instance-CR6b1W80.js → auth-instance-CmDogt4D.js} +20 -13
- package/dist/cli.js +1 -1
- package/dist/{console-runtime-DTopBP-x.d.ts → console-runtime-D2ai-Et5.d.ts} +1 -1
- package/dist/{console-runtime-J9_Vx9pT.js → console-runtime-_LrpyCYY.js} +2 -2
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -1
- package/dist/console.d.ts +1 -1
- package/dist/{database-options-BRNef9oy.js → database-options-DpOVjUti.js} +1 -1
- package/dist/{database-schema-options-ENuRMduM.js → database-schema-options-Sk-1Bvyu.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +3 -3
- package/dist/{definition-CqQMcDEK.js → definition-BCaLA9kW.js} +146 -8
- package/dist/{error-diagnostics-C8XtVz0i.js → error-diagnostics-Dymr-S_n.js} +40 -4
- package/dist/{events-ByzenEVj.js → events-DCfuicoo.js} +6 -14
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +3 -8
- package/dist/index.js +3 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +6 -858
- package/dist/mcp-config-DRRlCAWN.js +18 -0
- package/dist/mcp-token-CpxLyl_p.js +222 -0
- package/dist/mcp.d.ts +96 -85
- package/dist/mcp.js +3 -184
- package/dist/{members-D9lfaEO_.js → members-DdlsS8kJ.js} +5 -5
- package/dist/nuxt.d.ts +15 -2
- package/dist/nuxt.js +9 -12
- package/dist/{presets-BGZi6Dfu.d.ts → presets-CHndEv5i.d.ts} +3 -4
- package/dist/presets.d.ts +2 -2
- package/dist/presets.js +3 -13
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -1
- package/dist/runtime/empty-definition.d.ts +2 -1
- package/dist/runtime/empty-definition.js +2 -1
- package/dist/runtime/nuxt.js +2 -2
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/vue-nuxt.js +15 -7
- package/dist/schema.js +1 -1
- package/dist/server-BG_MFd4q.js +980 -0
- package/dist/{server-C0qnKN2W.d.ts → server-BM-RSf1T.d.ts} +76 -15
- package/dist/{server-bQGzVQ--.d.ts → server-C8TlOrSy.d.ts} +3 -3
- package/dist/server.d.ts +2 -2
- package/dist/server.js +3 -3
- package/dist/{session-cookies-BbH3UR2m.js → session-cookies-DVzjOKc7.js} +69 -5
- package/dist/{set-cookie-C8NOhdRE.js → set-cookie-DmqWq6kj.js} +1 -1
- package/dist/{shared-BwcdRGxD.js → shared-DRtfuFsV.js} +1 -1
- package/dist/{table-specs-8gq_FCaq.js → table-specs-CURphR3n.js} +1 -1
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-CNaeH2Fd.d.ts → types-CruflEFI.d.ts} +62 -43
- package/dist/{vite-CV400XXY.js → vite-Dy0Xhq4H.js} +195 -149
- package/dist/vite.d.ts +2 -1
- package/dist/vite.js +2 -2
- package/dist/vue.d.ts +4 -19
- package/dist/vue.js +6 -9
- package/package.json +9 -9
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
|
|
2
|
+
import { t as readSetCookies } from "./set-cookie-DmqWq6kj.js";
|
|
3
|
+
import { a as getAuthenticationSession, i as authenticationRefusalResponse, n as sendSessionCookies, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-DVzjOKc7.js";
|
|
4
|
+
import { n as authRequestEvent, r as unwrapAuthRequest } from "./request-z6DHHmrb.js";
|
|
5
|
+
import { t as createAuthConsole } from "./console-runtime-_LrpyCYY.js";
|
|
6
|
+
import { i as notMemberError, l as findAccessPolicyPlugin } from "./members-DdlsS8kJ.js";
|
|
7
|
+
import { n as getAuthRuntimeState } from "./runtime-state-ojQCzKOc.js";
|
|
8
|
+
import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-DCfuicoo.js";
|
|
9
|
+
import { a as requestProvider, c as resolveAuthOptions, d as setRequestClientAddress, f as withClientAddress, i as getAuthForDefinition, l as trustsProxyHeaders, m as forwardedRequestOrigin, n as createBetterAuthOptions, o as resolveDefaultDefinition, p as runWithAuthEvent, r as envResolverFor, s as withSessionMarker, t as authForRequest, u as eventClientAddress } from "./auth-instance-CmDogt4D.js";
|
|
10
|
+
import { i as resolveAuthMountPath, n as canonicalAccessPath } from "./application-path-DuTpfGFj.js";
|
|
11
|
+
import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
|
|
12
|
+
import { createAuthAccessRouteMatcher } from "./runtime/server.js";
|
|
13
|
+
import { n as checkAbility, t as AbilityError } from "./ability-error-IeZQBr_-.js";
|
|
14
|
+
import { n as mcpOAuthResources, t as isJwsToken } from "./mcp-config-DRRlCAWN.js";
|
|
15
|
+
import { defineErrors, toResultError } from "@vite-hub/runtime";
|
|
16
|
+
import { HTTPError } from "nitro/h3";
|
|
17
|
+
import { parseUserOutput } from "better-auth/db";
|
|
18
|
+
import abilities from "#vitehub/auth/abilities";
|
|
19
|
+
import { isRuntimeResponse } from "@vite-hub/runtime/internal/runtime-type";
|
|
20
|
+
import { betterAuth } from "better-auth";
|
|
21
|
+
//#region src/caller.ts
|
|
22
|
+
const callerErrors = /*#__PURE__*/ defineErrors({
|
|
23
|
+
docs: "https://vitehub.dev/docs/auth/diagnostics",
|
|
24
|
+
codes: { AUTH_SIGNED_OUT: {
|
|
25
|
+
why: "The request has no Auth Session and no MCP access token.",
|
|
26
|
+
fix: "Answer `401`. A person signs in and sends the session cookie. An MCP client sends `Authorization: Bearer <access token>` from `mcpOAuth()`."
|
|
27
|
+
} }
|
|
28
|
+
});
|
|
29
|
+
const signedOutError = () => callerErrors.AUTH_SIGNED_OUT();
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/internal/server.ts
|
|
32
|
+
function hasHappyDomRequestState(value) {
|
|
33
|
+
const ownSymbols = Object.getOwnPropertySymbols(value);
|
|
34
|
+
const prototypeSymbols = Object.getOwnPropertySymbols(Object.getPrototypeOf(value) ?? {});
|
|
35
|
+
return [
|
|
36
|
+
"method",
|
|
37
|
+
"body",
|
|
38
|
+
"mode",
|
|
39
|
+
"headers",
|
|
40
|
+
"redirect",
|
|
41
|
+
"referrerPolicy",
|
|
42
|
+
"signal",
|
|
43
|
+
"bodyUsed",
|
|
44
|
+
"credentials",
|
|
45
|
+
"aborted",
|
|
46
|
+
"error",
|
|
47
|
+
"contentLength",
|
|
48
|
+
"contentType",
|
|
49
|
+
"referrer",
|
|
50
|
+
"url",
|
|
51
|
+
"bodyBuffer"
|
|
52
|
+
].every((name) => ownSymbols.some((symbol) => symbol.description === name)) && prototypeSymbols.some((symbol) => symbol.description === "window");
|
|
53
|
+
}
|
|
54
|
+
function isRequestLike$1(value) {
|
|
55
|
+
try {
|
|
56
|
+
const isBrandCheckError = (error) => {
|
|
57
|
+
if (typeof error !== "object" && typeof error !== "function" || error === null) return false;
|
|
58
|
+
try {
|
|
59
|
+
if (Object.prototype.toString.call(error) !== "[object Error]") return false;
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
let name;
|
|
64
|
+
let message;
|
|
65
|
+
try {
|
|
66
|
+
name = Reflect.get(error, "name");
|
|
67
|
+
message = Reflect.get(error, "message");
|
|
68
|
+
} catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
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);
|
|
72
|
+
};
|
|
73
|
+
if (Object.prototype.toString.call(value) !== "[object Request]") return false;
|
|
74
|
+
const hasPrototypeTag = (target, tag) => {
|
|
75
|
+
let prototype = Object.getPrototypeOf(target);
|
|
76
|
+
while (prototype) {
|
|
77
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
|
|
78
|
+
if (descriptor) {
|
|
79
|
+
if (typeof descriptor.get === "function") return descriptor.get.call(target) === tag;
|
|
80
|
+
return "value" in descriptor && descriptor.value === tag;
|
|
81
|
+
}
|
|
82
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
};
|
|
86
|
+
const hasBrandedAccessor = (target, property) => {
|
|
87
|
+
let current = Object.getPrototypeOf(target);
|
|
88
|
+
while (current) {
|
|
89
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, property);
|
|
90
|
+
if (descriptor) {
|
|
91
|
+
if (typeof descriptor.get !== "function") return false;
|
|
92
|
+
try {
|
|
93
|
+
descriptor.get.call(Object.create(null));
|
|
94
|
+
if (target !== value) return false;
|
|
95
|
+
return hasHappyDomRequestState(value);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (!isBrandCheckError(error)) return false;
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
current = Object.getPrototypeOf(current);
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
};
|
|
105
|
+
if (!hasPrototypeTag(value, "Request")) return false;
|
|
106
|
+
const hasMethods = (target, methods) => methods.every((method) => {
|
|
107
|
+
return typeof Reflect.get(target, method) === "function";
|
|
108
|
+
});
|
|
109
|
+
if (hasHappyDomRequestState(value)) {
|
|
110
|
+
if (!hasMethods(value, [
|
|
111
|
+
"clone",
|
|
112
|
+
"arrayBuffer",
|
|
113
|
+
"blob",
|
|
114
|
+
"formData",
|
|
115
|
+
"json",
|
|
116
|
+
"text"
|
|
117
|
+
])) return false;
|
|
118
|
+
if (!value.headers || !hasMethods(value.headers, [
|
|
119
|
+
"get",
|
|
120
|
+
"has",
|
|
121
|
+
"set",
|
|
122
|
+
"append",
|
|
123
|
+
"delete",
|
|
124
|
+
"entries",
|
|
125
|
+
"forEach"
|
|
126
|
+
])) return false;
|
|
127
|
+
if (!value.signal || typeof value.signal.aborted !== "boolean") return false;
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
if (![
|
|
131
|
+
"body",
|
|
132
|
+
"bodyUsed",
|
|
133
|
+
"headers",
|
|
134
|
+
"method",
|
|
135
|
+
"signal",
|
|
136
|
+
"url"
|
|
137
|
+
].every((property) => hasBrandedAccessor(value, property))) return false;
|
|
138
|
+
if (!hasMethods(value, [
|
|
139
|
+
"clone",
|
|
140
|
+
"arrayBuffer",
|
|
141
|
+
"blob",
|
|
142
|
+
"formData",
|
|
143
|
+
"json",
|
|
144
|
+
"text"
|
|
145
|
+
])) return false;
|
|
146
|
+
if (!value.headers || Object.prototype.toString.call(value.headers) !== "[object Headers]" || !hasPrototypeTag(value.headers, "Headers") || !hasMethods(value.headers, [
|
|
147
|
+
"get",
|
|
148
|
+
"has",
|
|
149
|
+
"set",
|
|
150
|
+
"append",
|
|
151
|
+
"delete",
|
|
152
|
+
"entries",
|
|
153
|
+
"forEach"
|
|
154
|
+
])) return false;
|
|
155
|
+
if ([
|
|
156
|
+
"get",
|
|
157
|
+
"has",
|
|
158
|
+
"set",
|
|
159
|
+
"append",
|
|
160
|
+
"delete",
|
|
161
|
+
"entries",
|
|
162
|
+
"forEach"
|
|
163
|
+
].some((method) => Object.prototype.hasOwnProperty.call(value.headers, method))) return false;
|
|
164
|
+
const headersGet = Reflect.get(value.headers, "get");
|
|
165
|
+
if (typeof headersGet !== "function") return false;
|
|
166
|
+
try {
|
|
167
|
+
headersGet.call(Object.create(null), "");
|
|
168
|
+
return false;
|
|
169
|
+
} catch (error) {
|
|
170
|
+
if (!isBrandCheckError(error)) return false;
|
|
171
|
+
}
|
|
172
|
+
if (!value.signal || Object.prototype.toString.call(value.signal) !== "[object AbortSignal]" || !hasPrototypeTag(value.signal, "AbortSignal") || typeof value.signal.aborted !== "boolean") return false;
|
|
173
|
+
if (Object.prototype.hasOwnProperty.call(value.signal, "aborted")) return false;
|
|
174
|
+
return true;
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function isAbortSignalLike(value) {
|
|
180
|
+
if (!value || typeof value !== "object" && typeof value !== "function") return false;
|
|
181
|
+
try {
|
|
182
|
+
let prototype = Object.getPrototypeOf(value);
|
|
183
|
+
const seen = /* @__PURE__ */ new Set();
|
|
184
|
+
while (prototype && !seen.has(prototype)) {
|
|
185
|
+
seen.add(prototype);
|
|
186
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, "aborted");
|
|
187
|
+
if (descriptor?.get) return typeof Reflect.apply(descriptor.get, value, []) === "boolean";
|
|
188
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
189
|
+
}
|
|
190
|
+
} catch {
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
/** The provider sign-in of `access`, which returns to `afterSignIn`. A sign-in page has none: the page signs in. */
|
|
196
|
+
function providerSignIn(options) {
|
|
197
|
+
const access = options.access;
|
|
198
|
+
const signIn = access?.signIn;
|
|
199
|
+
return typeof signIn === "object" ? {
|
|
200
|
+
...signIn,
|
|
201
|
+
callbackURL: `${resolveAuthMountPath("/")}${(appPath(access?.afterSignIn ?? "/") ?? "/").slice(1)}`
|
|
202
|
+
} : void 0;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The Headers init of a host request. A Headers-like object without `Symbol.iterator`, from another
|
|
206
|
+
* Fetch implementation, gives its fields through `entries()`, not through its own properties.
|
|
207
|
+
*/
|
|
208
|
+
function headersInit(headers) {
|
|
209
|
+
const value = headers;
|
|
210
|
+
if (typeof value !== "object" || value === null || typeof Reflect.get(value, Symbol.iterator) === "function") return headers;
|
|
211
|
+
const entries = Reflect.get(value, "entries");
|
|
212
|
+
if (typeof entries !== "function") return headers;
|
|
213
|
+
return Array.from(Reflect.apply(entries, value, []));
|
|
214
|
+
}
|
|
215
|
+
function toRequest(request) {
|
|
216
|
+
if (request instanceof Request || isRequestLike$1(request)) return request;
|
|
217
|
+
const init = { method: request.method };
|
|
218
|
+
init.headers = new Headers(headersInit(request.headers));
|
|
219
|
+
if (isAbortSignalLike(request.signal)) init.signal = request.signal;
|
|
220
|
+
if (request.body) {
|
|
221
|
+
init.body = request.body;
|
|
222
|
+
init.duplex = "half";
|
|
223
|
+
}
|
|
224
|
+
return new Request(request.url, init);
|
|
225
|
+
}
|
|
226
|
+
function createAuthRequestRuntimeOptions(definition, request, event) {
|
|
227
|
+
return resolveAuthOptions(definition, {
|
|
228
|
+
request,
|
|
229
|
+
event,
|
|
230
|
+
env: envResolverFor(definition)
|
|
231
|
+
}).requestRuntimeOptions;
|
|
232
|
+
}
|
|
233
|
+
function createAuth(definition) {
|
|
234
|
+
return withSessionMarker(withClientAddress(betterAuth(createBetterAuthOptions(definition))));
|
|
235
|
+
}
|
|
236
|
+
function createAuthForRequest(definition, request, event) {
|
|
237
|
+
return withSessionMarker(withClientAddress(betterAuth(resolveAuthOptions(definition, {
|
|
238
|
+
request,
|
|
239
|
+
event,
|
|
240
|
+
env: envResolverFor(definition)
|
|
241
|
+
}).providerOptions)));
|
|
242
|
+
}
|
|
243
|
+
function handleAuthRequest(definition, input, event = authRequestEvent(input)) {
|
|
244
|
+
const request = unwrapAuthRequest(input);
|
|
245
|
+
const address = eventClientAddress(event);
|
|
246
|
+
const resolved = resolveAuthOptions(definition, {
|
|
247
|
+
request,
|
|
248
|
+
event,
|
|
249
|
+
env: envResolverFor(definition)
|
|
250
|
+
});
|
|
251
|
+
const auth = requestProvider(definition, resolved);
|
|
252
|
+
return runWithAuthEvent(event, () => handleSignInRoute(auth, resolved.options, request, address) ?? auth.handler(setRequestClientAddress(toRequest(request), address)));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* With a provider in `access.signIn`, the Auth route also answers `GET <basePath>/sign-in` and `GET <basePath>/sign-out`, so a link
|
|
256
|
+
* can sign in or out and come back to `?redirect=`. Better Auth has no GET endpoint at these paths.
|
|
257
|
+
*/
|
|
258
|
+
function handleSignInRoute(auth, options, request, address) {
|
|
259
|
+
const signIn = providerSignIn(options);
|
|
260
|
+
if (!signIn || request.method !== "GET") return;
|
|
261
|
+
const basePath = resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0));
|
|
262
|
+
const url = new URL(request.url);
|
|
263
|
+
const path = canonicalAccessPath(url.pathname);
|
|
264
|
+
if (path !== `${basePath}/sign-in` && path !== `${basePath}/sign-out`) return;
|
|
265
|
+
const headers = new Headers(headersInit(request.headers));
|
|
266
|
+
const query = url.searchParams.get("redirect");
|
|
267
|
+
const redirect = query === null ? void 0 : appPath(query);
|
|
268
|
+
if (redirect === null) return Promise.resolve(textResponse("The redirect must be a path of this site, such as /docs.", 400));
|
|
269
|
+
const appRoot = resolveAuthMountPath("/");
|
|
270
|
+
const destination = redirect === void 0 ? void 0 : `${appRoot}${redirect.slice(1)}`;
|
|
271
|
+
if (path === `${basePath}/sign-out`) {
|
|
272
|
+
const site = headers.get("sec-fetch-site");
|
|
273
|
+
if (site !== null && site !== "same-origin" && site !== "none") return Promise.resolve(textResponse("A sign-out from another site is not allowed.", 403));
|
|
274
|
+
if (/prefetch/i.test(`${headers.get("sec-purpose") ?? ""} ${headers.get("purpose") ?? ""}`)) return Promise.resolve(textResponse("A prefetch does not sign out.", 403));
|
|
275
|
+
return endSession(auth, headers, destination ?? appRoot);
|
|
276
|
+
}
|
|
277
|
+
return startSignIn(auth, options, headers, {
|
|
278
|
+
...signIn,
|
|
279
|
+
callbackURL: destination ?? signIn.callbackURL
|
|
280
|
+
}, address);
|
|
281
|
+
}
|
|
282
|
+
async function startSignIn(auth, options, headers, signIn, address) {
|
|
283
|
+
const { session, setCookies } = await getAuthenticationSession(auth, { headers });
|
|
284
|
+
const response = session ? new Response(null, {
|
|
285
|
+
headers: { location: (signIn.callbackURL ?? "/").replace(/[^\u0020-\u007E]+/gu, encodeURI) },
|
|
286
|
+
status: 302
|
|
287
|
+
}) : await createSignInResponse(auth, options, signIn, address);
|
|
288
|
+
const sent = new Headers();
|
|
289
|
+
for (const cookie of setCookies) sent.append("set-cookie", cookie);
|
|
290
|
+
response.headers.forEach((value, name) => {
|
|
291
|
+
if (name !== "set-cookie") sent.set(name, value);
|
|
292
|
+
});
|
|
293
|
+
for (const cookie of readSetCookies(response.headers)) sent.append("set-cookie", cookie);
|
|
294
|
+
sent.set("cache-control", "no-store");
|
|
295
|
+
return new Response(response.body, {
|
|
296
|
+
headers: sent,
|
|
297
|
+
status: response.status,
|
|
298
|
+
statusText: response.statusText
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
function textResponse(text, status) {
|
|
302
|
+
return new Response(text, {
|
|
303
|
+
headers: {
|
|
304
|
+
"cache-control": "no-store",
|
|
305
|
+
"content-type": "text/plain; charset=utf-8"
|
|
306
|
+
},
|
|
307
|
+
status
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* A path of this app, such as `/docs?tab=a`, URL-encoded for a `Location` header, or `null` for another value.
|
|
312
|
+
* `//host` and `/\\host` open another site, so they are not paths.
|
|
313
|
+
*/
|
|
314
|
+
function appPath(value) {
|
|
315
|
+
if (!value.startsWith("/") || /^\/[/\\]/.test(value) || /[\u0000-\u001F\u007F]/.test(value)) return null;
|
|
316
|
+
const url = new URL(value, "http://app.invalid");
|
|
317
|
+
if (url.pathname.startsWith("//")) return null;
|
|
318
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
319
|
+
}
|
|
320
|
+
/** Return a Web Request itself, or the request in the Standard Context of a request event. */
|
|
321
|
+
function toAuthRequest(input) {
|
|
322
|
+
return unwrapAuthRequest(input);
|
|
323
|
+
}
|
|
324
|
+
/** Create a handler whose optional host context supplies the peer address, never a client-sent header. */
|
|
325
|
+
function createAuthHandler(definition) {
|
|
326
|
+
const auth = createAuth(definition);
|
|
327
|
+
return (request, host) => auth.handler(setRequestClientAddress(request, host?.clientAddress));
|
|
328
|
+
}
|
|
329
|
+
/** The Better Auth instance of the app's Auth Definition, for sibling packages. Apps call `useAuth()`. */
|
|
330
|
+
function getAuth() {
|
|
331
|
+
return getAuthForDefinition(resolveDefaultDefinition());
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Checks `VITEHUB_MEMBERS` for a user, with the rules of sign-in, for code that has a user id but no session, such as
|
|
335
|
+
* an upload ticket or a signed link. Returns `[undefined, undefined]` when the list lets the user in, or when
|
|
336
|
+
* `VITEHUB_MEMBERS` is not set. Returns `AUTH_NOT_MEMBER` for a refused or unknown user, and `AUTH_GITHUB_UNAVAILABLE`
|
|
337
|
+
* when GitHub cannot confirm an organization membership. Pass the request event so that Auth reads the variable from
|
|
338
|
+
* the request's Cloudflare bindings.
|
|
339
|
+
*/
|
|
340
|
+
async function checkAuthMember(userId, event) {
|
|
341
|
+
const context = await useAuth(event).$context;
|
|
342
|
+
const members = findAccessPolicyPlugin(context.options.plugins)?.members;
|
|
343
|
+
if (!members) return [void 0, void 0];
|
|
344
|
+
const user = await context.internalAdapter.findUserById(userId);
|
|
345
|
+
if (!user) return [notMemberError(), void 0];
|
|
346
|
+
return await members.check(context, user);
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Return the Better Auth instance of the app's Auth Definition for a request event or a Web `Request`.
|
|
350
|
+
* The generated types give it the endpoints and fields of the Definition's plugins, so `useAuth(event).api.banUser`
|
|
351
|
+
* type-checks when `server/auth.ts` uses `admin()`.
|
|
352
|
+
*
|
|
353
|
+
* Pass the event in a route. The instance then reads the request's host and Cloudflare bindings. Leave it out only
|
|
354
|
+
* where no request exists, such as in a Schedule or a Queue job.
|
|
355
|
+
*/
|
|
356
|
+
function useAuth(event) {
|
|
357
|
+
if (!event) return getAuth();
|
|
358
|
+
return authForRequest(unwrapAuthRequest(event), authRequestEvent(event));
|
|
359
|
+
}
|
|
360
|
+
async function assertAuthOrigin(request, event) {
|
|
361
|
+
const origin = request.headers.get("origin");
|
|
362
|
+
if (!origin) throw authErrorDiagnostics.AUTH_R0006({ message: "The request origin is required." });
|
|
363
|
+
const auth = authForRequest(request, event);
|
|
364
|
+
if (!(await auth.$context).isTrustedOrigin(origin)) throw authErrorDiagnostics.AUTH_R0007({ message: "The request origin is not trusted." });
|
|
365
|
+
return auth;
|
|
366
|
+
}
|
|
367
|
+
function handleAuth(input) {
|
|
368
|
+
return handleAuthRequest(resolveDefaultDefinition(), input);
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Signs out the session of a request event or a Web `Request` from server code, such as a GET `/logout` route.
|
|
372
|
+
* Better Auth deletes the session, and the response clears its cookies. Returns a `303` redirect to `redirectTo`, or
|
|
373
|
+
* `204` without it. Provider logout uses a `303` to the provider first, with `redirectTo` as its callback.
|
|
374
|
+
* A request without a session gets the same answer. Throws `AUTH_SIGN_OUT_REDIRECT_INVALID` when
|
|
375
|
+
* `redirectTo` is not a path of the app.
|
|
376
|
+
*/
|
|
377
|
+
async function signOut(input, options = {}) {
|
|
378
|
+
const { redirectTo } = options;
|
|
379
|
+
if (redirectTo === void 0) return await endSession(useAuth(input), unwrapAuthRequest(input).headers, void 0);
|
|
380
|
+
const location = appPath(redirectTo);
|
|
381
|
+
if (location === null) throw authErrorDiagnostics.AUTH_SIGN_OUT_REDIRECT_INVALID({ redirectTo });
|
|
382
|
+
return await endSession(useAuth(input), unwrapAuthRequest(input).headers, location);
|
|
383
|
+
}
|
|
384
|
+
async function endSession(auth, requestHeaders, redirectTo) {
|
|
385
|
+
const result = await auth.api.signOut({
|
|
386
|
+
asResponse: true,
|
|
387
|
+
headers: requestHeaders,
|
|
388
|
+
body: { callbackURL: redirectTo }
|
|
389
|
+
});
|
|
390
|
+
if (!result.ok && result.status !== 400) return result;
|
|
391
|
+
const headers = new Headers({ "cache-control": "no-store" });
|
|
392
|
+
for (const cookie of readSetCookies(result.headers)) headers.append("set-cookie", cookie);
|
|
393
|
+
const location = result.ok ? result.headers.get("location") ?? redirectTo : redirectTo;
|
|
394
|
+
if (location === void 0) return new Response(null, {
|
|
395
|
+
headers,
|
|
396
|
+
status: 204
|
|
397
|
+
});
|
|
398
|
+
headers.set("location", location);
|
|
399
|
+
return new Response(null, {
|
|
400
|
+
headers,
|
|
401
|
+
status: 303
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
function wantsHtml(request) {
|
|
405
|
+
return request.method === "GET" && request.headers.get("accept")?.includes("text/html") === true;
|
|
406
|
+
}
|
|
407
|
+
const refusalCodes = /* @__PURE__ */ new WeakMap();
|
|
408
|
+
function refusal(response, code) {
|
|
409
|
+
refusalCodes.set(response, code);
|
|
410
|
+
return response;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* A refusal in H3's JSON error format, the same body that `requireAuth()` and H3 errors send. The phrase also goes on
|
|
414
|
+
* the status line.
|
|
415
|
+
*/
|
|
416
|
+
function createRefusalResponse(code) {
|
|
417
|
+
const status = code === "SIGNED_OUT" ? 401 : 403;
|
|
418
|
+
const statusText = code === "SIGNED_OUT" ? "Unauthorized" : "Forbidden";
|
|
419
|
+
return refusal(Response.json({
|
|
420
|
+
status,
|
|
421
|
+
statusText,
|
|
422
|
+
message: `${statusText}.`,
|
|
423
|
+
data: { code }
|
|
424
|
+
}, {
|
|
425
|
+
status,
|
|
426
|
+
statusText
|
|
427
|
+
}), code);
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* A text 403 for an HTML request. The phrase on the status line is also the `statusText` of the error that the inline
|
|
431
|
+
* guards throw.
|
|
432
|
+
*/
|
|
433
|
+
function createTextRefusalResponse(text, code) {
|
|
434
|
+
return refusal(new Response(text, {
|
|
435
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
436
|
+
status: 403,
|
|
437
|
+
statusText: "Forbidden"
|
|
438
|
+
}), code);
|
|
439
|
+
}
|
|
440
|
+
/** Better Auth's refusal of the credentials of the request, such as an invalid key of the API Key plugin. */
|
|
441
|
+
function createProviderRefusalResponse(provider) {
|
|
442
|
+
const response = authenticationRefusalResponse(provider);
|
|
443
|
+
if (provider.code) refusalCodes.set(response, provider.code);
|
|
444
|
+
return response;
|
|
445
|
+
}
|
|
446
|
+
function createForbiddenResponse(request) {
|
|
447
|
+
return wantsHtml(request) ? createTextRefusalResponse("Forbidden.", "FORBIDDEN") : createRefusalResponse("FORBIDDEN");
|
|
448
|
+
}
|
|
449
|
+
function authAccessRoutes(options, routeIndexes) {
|
|
450
|
+
const routes = options.access?.routes;
|
|
451
|
+
return routeIndexes.map((routeIndex) => {
|
|
452
|
+
const route = routes?.[routeIndex];
|
|
453
|
+
if (!route) throw authErrorDiagnostics.AUTH_R0008({ message: `[vitehub] Auth access route ${routeIndex} is unavailable at runtime.` });
|
|
454
|
+
return route;
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
async function createSignInResponse(auth, options, signIn, address) {
|
|
458
|
+
const origin = new URL(options.baseURL).origin;
|
|
459
|
+
const basePath = resolveAuthMountPath(normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0));
|
|
460
|
+
const response = await auth.handler(setRequestClientAddress(new Request(`${origin}${basePath}/sign-in/social`, {
|
|
461
|
+
body: JSON.stringify({
|
|
462
|
+
callbackURL: signIn.callbackURL,
|
|
463
|
+
errorCallbackURL: signIn.errorCallbackURL,
|
|
464
|
+
provider: signIn.provider,
|
|
465
|
+
requestSignUp: signIn.requestSignUp,
|
|
466
|
+
scopes: signIn.scopes
|
|
467
|
+
}),
|
|
468
|
+
headers: {
|
|
469
|
+
"content-type": "application/json",
|
|
470
|
+
"accept": "application/json",
|
|
471
|
+
"origin": origin
|
|
472
|
+
},
|
|
473
|
+
method: "POST"
|
|
474
|
+
}), address));
|
|
475
|
+
if (!response.ok) return response;
|
|
476
|
+
const body = await response.json().catch(() => void 0);
|
|
477
|
+
if (typeof body?.url !== "string") return Response.json({ error: "Auth sign-in did not return a redirect URL." }, { status: 502 });
|
|
478
|
+
const headers = new Headers(response.headers);
|
|
479
|
+
headers.delete("content-type");
|
|
480
|
+
headers.set("location", body.url);
|
|
481
|
+
return new Response(null, {
|
|
482
|
+
headers,
|
|
483
|
+
status: 302
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
const sessionReads = /* @__PURE__ */ new WeakMap();
|
|
487
|
+
async function readSession(input, auth, headers) {
|
|
488
|
+
const { refusal, session, setCookies } = await getAuthenticationSession(auth, { headers });
|
|
489
|
+
prepareSessionCookies(input, setCookies);
|
|
490
|
+
return {
|
|
491
|
+
refusal,
|
|
492
|
+
session
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
async function readRequestSession(input, definition) {
|
|
496
|
+
const request = unwrapAuthRequest(input);
|
|
497
|
+
const event = authRequestEvent(input);
|
|
498
|
+
const resolved = resolveAuthOptions(definition, {
|
|
499
|
+
request,
|
|
500
|
+
event,
|
|
501
|
+
env: envResolverFor(definition)
|
|
502
|
+
});
|
|
503
|
+
const auth = requestProvider(definition, resolved);
|
|
504
|
+
let reads = sessionReads.get(request);
|
|
505
|
+
if (!reads) sessionReads.set(request, reads = /* @__PURE__ */ new WeakMap());
|
|
506
|
+
let read = reads.get(definition);
|
|
507
|
+
if (!read) reads.set(definition, read = readSession(input, auth, request.headers));
|
|
508
|
+
const { refusal, session } = await read;
|
|
509
|
+
return {
|
|
510
|
+
auth,
|
|
511
|
+
event,
|
|
512
|
+
options: resolved.options,
|
|
513
|
+
refusal,
|
|
514
|
+
request,
|
|
515
|
+
session
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function checkedAuthorization(request, session, user) {
|
|
519
|
+
return Object.freeze({
|
|
520
|
+
request,
|
|
521
|
+
session,
|
|
522
|
+
user
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
function reject(response) {
|
|
526
|
+
return { response };
|
|
527
|
+
}
|
|
528
|
+
const nativeResponseClone = Object.getOwnPropertyDescriptor(Response.prototype, "clone")?.value;
|
|
529
|
+
/**
|
|
530
|
+
* A Response of this runtime with an own `then` would be assimilated as a thenable by the host that awaits it.
|
|
531
|
+
* Send a native clone instead, so the rejection still reaches the client as a Response.
|
|
532
|
+
*/
|
|
533
|
+
function sendableRuntimeResponse(value, request) {
|
|
534
|
+
if (!Object.prototype.hasOwnProperty.call(value, "then")) return value;
|
|
535
|
+
try {
|
|
536
|
+
return nativeResponseClone ? Reflect.apply(nativeResponseClone, value, []) : createForbiddenResponse(request);
|
|
537
|
+
} catch {
|
|
538
|
+
return createForbiddenResponse(request);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const nativePromiseThen = Object.getOwnPropertyDescriptor(Promise.prototype, "then")?.value;
|
|
542
|
+
const nativePromiseResolve = Promise.resolve;
|
|
543
|
+
function hasNativePromiseBrand(value) {
|
|
544
|
+
if (!nativePromiseThen) return false;
|
|
545
|
+
try {
|
|
546
|
+
let prototype = Object.getPrototypeOf(value);
|
|
547
|
+
const seen = /* @__PURE__ */ new Set();
|
|
548
|
+
while (prototype && !seen.has(prototype)) {
|
|
549
|
+
seen.add(prototype);
|
|
550
|
+
if (Object.prototype.hasOwnProperty.call(prototype, "then") && Object.getOwnPropertyDescriptor(prototype, "then")?.value === nativePromiseThen) return true;
|
|
551
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
552
|
+
}
|
|
553
|
+
const valueDescriptor = Object.getOwnPropertyDescriptor(value, "constructor");
|
|
554
|
+
let valueOverridden = false;
|
|
555
|
+
try {
|
|
556
|
+
if (!valueDescriptor || valueDescriptor.configurable) {
|
|
557
|
+
Object.defineProperty(value, "constructor", {
|
|
558
|
+
configurable: true,
|
|
559
|
+
writable: true,
|
|
560
|
+
value: Promise
|
|
561
|
+
});
|
|
562
|
+
valueOverridden = true;
|
|
563
|
+
} else if ("value" in valueDescriptor && valueDescriptor.writable) {
|
|
564
|
+
Object.defineProperty(value, "constructor", { value: Promise });
|
|
565
|
+
valueOverridden = true;
|
|
566
|
+
}
|
|
567
|
+
} catch {}
|
|
568
|
+
let probe;
|
|
569
|
+
try {
|
|
570
|
+
probe = Reflect.apply(nativePromiseThen, value, [() => void 0, () => void 0]);
|
|
571
|
+
} finally {
|
|
572
|
+
if (valueOverridden) {
|
|
573
|
+
if (valueDescriptor) Object.defineProperty(value, "constructor", valueDescriptor);
|
|
574
|
+
else Reflect.deleteProperty(value, "constructor");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (probe && (typeof probe === "object" || typeof probe === "function")) {
|
|
578
|
+
const descriptor = Object.getOwnPropertyDescriptor(probe, "constructor");
|
|
579
|
+
let overridden = false;
|
|
580
|
+
try {
|
|
581
|
+
if (!descriptor || descriptor.configurable) {
|
|
582
|
+
Object.defineProperty(probe, "constructor", {
|
|
583
|
+
configurable: true,
|
|
584
|
+
writable: true,
|
|
585
|
+
value: Promise
|
|
586
|
+
});
|
|
587
|
+
overridden = true;
|
|
588
|
+
} else if ("value" in descriptor && descriptor.writable) {
|
|
589
|
+
Object.defineProperty(probe, "constructor", { value: Promise });
|
|
590
|
+
overridden = true;
|
|
591
|
+
}
|
|
592
|
+
const cleanup = Reflect.apply(nativePromiseThen, probe, [() => void 0, () => void 0]);
|
|
593
|
+
if (cleanup && (typeof cleanup === "object" || typeof cleanup === "function")) {
|
|
594
|
+
const cleanupDescriptor = Object.getOwnPropertyDescriptor(cleanup, "constructor");
|
|
595
|
+
let cleanupOverridden = false;
|
|
596
|
+
try {
|
|
597
|
+
if (!cleanupDescriptor || cleanupDescriptor.configurable) {
|
|
598
|
+
Object.defineProperty(cleanup, "constructor", {
|
|
599
|
+
configurable: true,
|
|
600
|
+
writable: true,
|
|
601
|
+
value: Promise
|
|
602
|
+
});
|
|
603
|
+
cleanupOverridden = true;
|
|
604
|
+
} else if ("value" in cleanupDescriptor && cleanupDescriptor.writable) {
|
|
605
|
+
Object.defineProperty(cleanup, "constructor", { value: Promise });
|
|
606
|
+
cleanupOverridden = true;
|
|
607
|
+
}
|
|
608
|
+
const cleanupResult = Reflect.apply(nativePromiseThen, cleanup, [() => void 0, () => void 0]);
|
|
609
|
+
if (cleanupResult && (typeof cleanupResult === "object" || typeof cleanupResult === "function")) Reflect.apply(nativePromiseThen, cleanupResult, [() => void 0, () => void 0]);
|
|
610
|
+
} finally {
|
|
611
|
+
if (cleanupOverridden) {
|
|
612
|
+
if (cleanupDescriptor) Object.defineProperty(cleanup, "constructor", cleanupDescriptor);
|
|
613
|
+
else Reflect.deleteProperty(cleanup, "constructor");
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
} finally {
|
|
618
|
+
if (overridden) {
|
|
619
|
+
if (descriptor) Object.defineProperty(probe, "constructor", descriptor);
|
|
620
|
+
else Reflect.deleteProperty(probe, "constructor");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return true;
|
|
625
|
+
} catch {
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Only `true` grants access. A Response of this runtime is sent as the rejection. Every other value gets `deny()`, `403` by default.
|
|
631
|
+
*/
|
|
632
|
+
async function runAccessAuthorize(authorize, context, deny = () => createForbiddenResponse(context.request)) {
|
|
633
|
+
const result = authorize(context);
|
|
634
|
+
if (isRuntimeResponse(result)) return { response: sendableRuntimeResponse(result, context.request) };
|
|
635
|
+
let resolved;
|
|
636
|
+
if (result !== null && (typeof result === "object" || typeof result === "function") && hasNativePromiseBrand(result)) {
|
|
637
|
+
let nativePromise;
|
|
638
|
+
let constructorDescriptor;
|
|
639
|
+
let speciesDescriptor;
|
|
640
|
+
let speciesOverridden = false;
|
|
641
|
+
let constructorOverridden = false;
|
|
642
|
+
try {
|
|
643
|
+
constructorDescriptor = Object.getOwnPropertyDescriptor(result, "constructor");
|
|
644
|
+
if (!constructorDescriptor || constructorDescriptor.configurable) {
|
|
645
|
+
Object.defineProperty(result, "constructor", {
|
|
646
|
+
configurable: true,
|
|
647
|
+
writable: true,
|
|
648
|
+
value: Promise
|
|
649
|
+
});
|
|
650
|
+
constructorOverridden = true;
|
|
651
|
+
} else if (typeof constructorDescriptor.value === "function") {
|
|
652
|
+
speciesDescriptor = Object.getOwnPropertyDescriptor(constructorDescriptor.value, Symbol.species);
|
|
653
|
+
if (!speciesDescriptor || speciesDescriptor.configurable) {
|
|
654
|
+
Object.defineProperty(constructorDescriptor.value, Symbol.species, {
|
|
655
|
+
configurable: true,
|
|
656
|
+
value: Promise
|
|
657
|
+
});
|
|
658
|
+
speciesOverridden = true;
|
|
659
|
+
} else if ("value" in constructorDescriptor && constructorDescriptor.writable) {
|
|
660
|
+
Object.defineProperty(result, "constructor", { value: Promise });
|
|
661
|
+
constructorOverridden = true;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
nativePromise = new Promise((resolve, reject) => {
|
|
665
|
+
Promise.prototype.then.call(result, resolve, reject);
|
|
666
|
+
});
|
|
667
|
+
} catch (error) {
|
|
668
|
+
try {
|
|
669
|
+
nativePromise = Reflect.apply(nativePromiseResolve, Promise, [result]);
|
|
670
|
+
} catch {
|
|
671
|
+
nativePromise = Promise.reject(error);
|
|
672
|
+
}
|
|
673
|
+
} finally {
|
|
674
|
+
if (constructorOverridden) {
|
|
675
|
+
if (constructorDescriptor) Object.defineProperty(result, "constructor", constructorDescriptor);
|
|
676
|
+
else Reflect.deleteProperty(result, "constructor");
|
|
677
|
+
}
|
|
678
|
+
if (speciesOverridden && constructorDescriptor && typeof constructorDescriptor.value === "function") {
|
|
679
|
+
if (speciesDescriptor) Object.defineProperty(constructorDescriptor.value, Symbol.species, speciesDescriptor);
|
|
680
|
+
else Reflect.deleteProperty(constructorDescriptor.value, Symbol.species);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
resolved = nativePromise ? await nativePromise : void 0;
|
|
684
|
+
} else resolved = result !== null && (typeof result === "object" || typeof result === "function") ? await result : result;
|
|
685
|
+
if (resolved === true) return {};
|
|
686
|
+
if (isRuntimeResponse(resolved)) return { response: sendableRuntimeResponse(resolved, context.request) };
|
|
687
|
+
return { response: deny() };
|
|
688
|
+
}
|
|
689
|
+
async function checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes = [], redirectToSignIn = true, resolveIdentity, signInURLs) {
|
|
690
|
+
const { auth, event, options, refusal: providerRefusal, request, session } = await readRequestSession(input, definition);
|
|
691
|
+
if (providerRefusal) return reject(createProviderRefusalResponse(providerRefusal));
|
|
692
|
+
const identity = await resolveIdentity?.(toRequest(request), input, Boolean(session));
|
|
693
|
+
if (isRuntimeResponse(identity)) return reject(identity);
|
|
694
|
+
if (identity || session) {
|
|
695
|
+
const authorization = checkedAuthorization(request, identity ? {} : session.session, identity ?? session.user);
|
|
696
|
+
if (routeIndexes === void 0) return { authorization };
|
|
697
|
+
const requiredAuthorizeRoutes = new Set(requiredAuthorizeRouteIndexes);
|
|
698
|
+
const routes = authAccessRoutes(options, routeIndexes);
|
|
699
|
+
for (const [index, route] of routes.entries()) {
|
|
700
|
+
const authorize = typeof route === "object" && route !== null ? route.authorize : void 0;
|
|
701
|
+
if (!authorize && requiredAuthorizeRoutes.has(routeIndexes[index])) return reject(createForbiddenResponse(request));
|
|
702
|
+
if (!authorize) continue;
|
|
703
|
+
const rejection = await runAccessAuthorize(authorize, {
|
|
704
|
+
...authorization,
|
|
705
|
+
event
|
|
706
|
+
});
|
|
707
|
+
if (rejection.response) return reject(rejection.response);
|
|
708
|
+
}
|
|
709
|
+
return { authorization };
|
|
710
|
+
}
|
|
711
|
+
if (!wantsHtml(request)) return reject(createRefusalResponse("SIGNED_OUT"));
|
|
712
|
+
if (!redirectToSignIn) return reject(createRefusalResponse("SIGNED_OUT"));
|
|
713
|
+
if (new URL(request.url).searchParams.has("auth_error")) return reject(createTextRefusalResponse("Unauthorized.", "SIGNED_OUT"));
|
|
714
|
+
const signIn = providerSignIn(options);
|
|
715
|
+
return reject(signIn ? await createSignInResponse(auth, options, {
|
|
716
|
+
...signIn,
|
|
717
|
+
...signInURLs
|
|
718
|
+
}, eventClientAddress(event)) : createRefusalResponse("SIGNED_OUT"));
|
|
719
|
+
}
|
|
720
|
+
async function checkAuthorizeRequest(input, authorize, definition) {
|
|
721
|
+
const { refusal: providerRefusal, request, session } = await readRequestSession(input, definition);
|
|
722
|
+
if (providerRefusal) return reject(createProviderRefusalResponse(providerRefusal));
|
|
723
|
+
if (!session) return reject(createRefusalResponse("SIGNED_OUT"));
|
|
724
|
+
const authorization = checkedAuthorization(request, session.session, session.user);
|
|
725
|
+
if (authorize === true) return { authorization };
|
|
726
|
+
const rejection = await runAccessAuthorize(authorize, {
|
|
727
|
+
...authorization,
|
|
728
|
+
event: authRequestEvent(input)
|
|
729
|
+
});
|
|
730
|
+
return rejection.response ? reject(rejection.response) : { authorization };
|
|
731
|
+
}
|
|
732
|
+
function withAnonymousAuthorization(authorize, handler, definition) {
|
|
733
|
+
if (typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be a function." });
|
|
734
|
+
if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAnonymousAuthorization() requires a handler function." });
|
|
735
|
+
return async (input) => {
|
|
736
|
+
const { refusal: providerRefusal, request, session } = await readRequestSession(input, definition ?? resolveDefaultDefinition());
|
|
737
|
+
if (providerRefusal) return sendSessionCookies(input, createProviderRefusalResponse(providerRefusal));
|
|
738
|
+
const authorization = session ? checkedAuthorization(request, session.session, session.user) : Object.freeze({
|
|
739
|
+
request,
|
|
740
|
+
session: null,
|
|
741
|
+
user: null
|
|
742
|
+
});
|
|
743
|
+
const deny = session ? void 0 : () => createRefusalResponse("SIGNED_OUT");
|
|
744
|
+
const rejection = await runAccessAuthorize(authorize, {
|
|
745
|
+
...authorization,
|
|
746
|
+
event: authRequestEvent(input)
|
|
747
|
+
}, deny);
|
|
748
|
+
if (rejection.response) return sendSessionCookies(input, rejection.response);
|
|
749
|
+
return sendSessionCookies(input, await handler(input, authorization));
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
function withAuth(handler, definition) {
|
|
753
|
+
if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAuth() requires a handler function." });
|
|
754
|
+
return async (input) => {
|
|
755
|
+
const { authorization, response } = await checkAuthRequest(input, definition ?? resolveDefaultDefinition());
|
|
756
|
+
if (response) return sendSessionCookies(input, response);
|
|
757
|
+
return sendSessionCookies(input, await handler(input, authorization));
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
function withAuthorization(authorize, handler, definition) {
|
|
761
|
+
if (authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
|
|
762
|
+
if (typeof handler !== "function") throw authErrorDiagnostics.AUTH_R0015({ message: "[vitehub] withAuthorization() requires a handler function." });
|
|
763
|
+
return async (input) => {
|
|
764
|
+
const { authorization, response } = await checkAuthorizeRequest(input, authorize, definition ?? resolveDefaultDefinition());
|
|
765
|
+
if (response) return sendSessionCookies(input, response);
|
|
766
|
+
return sendSessionCookies(input, await handler(input, authorization));
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* The `HTTPError` that an inline guard throws for a rejection `Response`. It keeps the status and headers, such as
|
|
771
|
+
* `location` and `set-cookie` of a sign-in redirect. JSON object fields stay in the error body; other JSON values
|
|
772
|
+
* become `data`. Text becomes the error message, with H3's JSON content type.
|
|
773
|
+
*/
|
|
774
|
+
async function rejectionError(response, code = refusalCodes.get(response)) {
|
|
775
|
+
const headers = new Headers(response.headers);
|
|
776
|
+
headers.delete("content-length");
|
|
777
|
+
const isJson = headers.get("content-type")?.toLowerCase().includes("json") === true;
|
|
778
|
+
if (!isJson) headers.delete("content-type");
|
|
779
|
+
const text = await response.text();
|
|
780
|
+
let body;
|
|
781
|
+
if (isJson) try {
|
|
782
|
+
body = JSON.parse(text);
|
|
783
|
+
} catch {}
|
|
784
|
+
const jsonBody = body !== null && typeof body === "object" && !Array.isArray(body) ? { ...body } : void 0;
|
|
785
|
+
let message = typeof body === "string" ? body : body === void 0 ? text : void 0;
|
|
786
|
+
if (body !== null && typeof body === "object") {
|
|
787
|
+
if ("error" in body && typeof body.error === "string") message = body.error;
|
|
788
|
+
else if ("message" in body && typeof body.message === "string") message = body.message;
|
|
789
|
+
}
|
|
790
|
+
return new HTTPError({
|
|
791
|
+
body: jsonBody,
|
|
792
|
+
data: code ? { code } : jsonBody === void 0 ? body : void 0,
|
|
793
|
+
headers,
|
|
794
|
+
message: message || void 0,
|
|
795
|
+
status: response.status,
|
|
796
|
+
statusText: response.statusText || void 0
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
async function requireCheck(input, check) {
|
|
800
|
+
const { authorization, response } = await check;
|
|
801
|
+
if (response) throw await rejectionError(sendSessionCookies(input, response), refusalCodes.get(response));
|
|
802
|
+
return authorization;
|
|
803
|
+
}
|
|
804
|
+
function requireAuth(event, definition) {
|
|
805
|
+
return requireCheck(event, checkAuthRequest(event, definition ?? resolveDefaultDefinition()));
|
|
806
|
+
}
|
|
807
|
+
function requireAuthorization(event, authorize, definition) {
|
|
808
|
+
if (authorize !== true && typeof authorize !== "function") throw authErrorDiagnostics.AUTH_R0014({ message: "[vitehub] `authorize` must be true or a function." });
|
|
809
|
+
return requireCheck(event, checkAuthorizeRequest(event, authorize, definition ?? resolveDefaultDefinition()));
|
|
810
|
+
}
|
|
811
|
+
const callerReads = /* @__PURE__ */ new WeakMap();
|
|
812
|
+
function requireCaller(event, definition = resolveDefaultDefinition()) {
|
|
813
|
+
const request = unwrapAuthRequest(event);
|
|
814
|
+
let reads = callerReads.get(request);
|
|
815
|
+
if (!reads) callerReads.set(request, reads = /* @__PURE__ */ new WeakMap());
|
|
816
|
+
let read = reads.get(definition);
|
|
817
|
+
if (!read) {
|
|
818
|
+
read = readCaller(event, definition);
|
|
819
|
+
read.catch(() => reads.delete(definition));
|
|
820
|
+
reads.set(definition, read);
|
|
821
|
+
}
|
|
822
|
+
return read;
|
|
823
|
+
}
|
|
824
|
+
async function readCaller(event, definition) {
|
|
825
|
+
const request = unwrapAuthRequest(event);
|
|
826
|
+
const token = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
827
|
+
if (token) {
|
|
828
|
+
const auth = authForRequest(request, authRequestEvent(event), definition);
|
|
829
|
+
const { options } = await auth.$context;
|
|
830
|
+
if (isJwsToken(token) && mcpOAuthResources(options.plugins).length) {
|
|
831
|
+
const { verifyAppAccessToken } = await import("./mcp-token-CpxLyl_p.js").then((n) => n.i);
|
|
832
|
+
const url = new URL(request.url);
|
|
833
|
+
const [error, caller] = await verifyAppAccessToken(token, trustsProxyHeaders(options) ? forwardedRequestOrigin(request) : url.origin, url.pathname, auth);
|
|
834
|
+
if (error) return [error, void 0];
|
|
835
|
+
return [void 0, Object.freeze({
|
|
836
|
+
client: {
|
|
837
|
+
id: caller.clientId,
|
|
838
|
+
name: caller.clientName
|
|
839
|
+
},
|
|
840
|
+
kind: "agent",
|
|
841
|
+
scopes: caller.scopes,
|
|
842
|
+
user: parseUserOutput(options, caller.user)
|
|
843
|
+
})];
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
const { session } = await readRequestSession(event, definition);
|
|
847
|
+
if (!session) return [signedOutError(), void 0];
|
|
848
|
+
return [void 0, Object.freeze({
|
|
849
|
+
kind: "browser",
|
|
850
|
+
session: session.session,
|
|
851
|
+
user: session.user
|
|
852
|
+
})];
|
|
853
|
+
}
|
|
854
|
+
const abilitySessions = /* @__PURE__ */ new WeakMap();
|
|
855
|
+
function readAbilityAuthorization(input) {
|
|
856
|
+
let pending = abilitySessions.get(input);
|
|
857
|
+
if (!pending) {
|
|
858
|
+
pending = readRequestSession(input, resolveDefaultDefinition()).then(({ refusal, request, session }) => {
|
|
859
|
+
if (refusal) throw authenticationRefusalError(refusal);
|
|
860
|
+
return session ? checkedAuthorization(request, session.session, session.user) : Object.freeze({
|
|
861
|
+
request,
|
|
862
|
+
session: null,
|
|
863
|
+
user: null
|
|
864
|
+
});
|
|
865
|
+
});
|
|
866
|
+
pending.catch(() => abilitySessions.delete(input));
|
|
867
|
+
abilitySessions.set(input, pending);
|
|
868
|
+
}
|
|
869
|
+
return pending;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Checks a rule from `shared/abilities.ts` for the caller of a request. Returns the checked request, session, and user.
|
|
873
|
+
* Throws an `AbilityError` when the rule refuses: `401` for a signed-out caller, else `403` or the status of `deny()`.
|
|
874
|
+
*
|
|
875
|
+
* @example
|
|
876
|
+
* const post = await getPost(id)
|
|
877
|
+
* const { user } = await requireAbility(event, "posts.edit", post)
|
|
878
|
+
*/
|
|
879
|
+
async function requireAbility(event, name, ...args) {
|
|
880
|
+
const authorization = await readAbilityAuthorization(event);
|
|
881
|
+
const refusal = checkAbility(abilities, authorization.user, name, args);
|
|
882
|
+
if (refusal) throw new AbilityError(refusal);
|
|
883
|
+
return authorization;
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Whether a rule from `shared/abilities.ts` allows the caller of a request.
|
|
887
|
+
*
|
|
888
|
+
* @example
|
|
889
|
+
* const editable = await can(event, "posts.edit", post)
|
|
890
|
+
*/
|
|
891
|
+
async function can(event, name, ...args) {
|
|
892
|
+
const authorization = await readAbilityAuthorization(event);
|
|
893
|
+
return checkAbility(abilities, authorization.user, name, args) === null;
|
|
894
|
+
}
|
|
895
|
+
const reusableAccessChecks = /* @__PURE__ */ new WeakMap();
|
|
896
|
+
async function checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options = {}) {
|
|
897
|
+
const key = JSON.stringify([routeIndexes, requiredAuthorizeRouteIndexes]);
|
|
898
|
+
const request = unwrapAuthRequest(input);
|
|
899
|
+
let definitions = reusableAccessChecks.get(request);
|
|
900
|
+
let accepted = definitions?.get(definition);
|
|
901
|
+
const reusable = accepted?.get(key);
|
|
902
|
+
if (reusable === true || options.reuse && reusable === false) return;
|
|
903
|
+
const { response } = await checkAuthRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options.redirectToSignIn !== false, getAuthRuntimeState().accessIdentityResolvers?.get(new URL(request.url).pathname), options.signIn);
|
|
904
|
+
if (response) return sendSessionCookies(input, response);
|
|
905
|
+
if (options.reuse || options.remember) {
|
|
906
|
+
if (!definitions) reusableAccessChecks.set(request, definitions = /* @__PURE__ */ new WeakMap());
|
|
907
|
+
if (!accepted) definitions.set(definition, accepted = /* @__PURE__ */ new Map());
|
|
908
|
+
accepted.set(key, options.reuse === true);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
/** Bind discovered access routes to a Web Request or host request handler. */
|
|
912
|
+
function createAuthAccessHandler(routes, definition, publicRoutes = []) {
|
|
913
|
+
const match = createAuthAccessRouteMatcher(routes, publicRoutes);
|
|
914
|
+
return async (input) => {
|
|
915
|
+
const matched = match(input);
|
|
916
|
+
if (matched.length === 0) return;
|
|
917
|
+
return await checkAuthAccessRequest(input, definition ?? resolveDefaultDefinition(), matched.map((rule) => rule.index), matched.filter((rule) => rule.authorize).map((rule) => rule.index), { remember: true });
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
async function requireAuthAccessRoutes(input, routeIndexes, definition = resolveDefaultDefinition(), requiredAuthorizeRouteIndexes = [], options = {}) {
|
|
921
|
+
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." });
|
|
922
|
+
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." });
|
|
923
|
+
return await checkAuthAccessRequest(input, definition, routeIndexes, requiredAuthorizeRouteIndexes, options);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* The Auth route that ViteHub mounts at `/api/auth/**`, as a Fetchable. It reads the client address and the
|
|
927
|
+
* Cloudflare bindings from the Standard Context of the Request.
|
|
928
|
+
*/
|
|
929
|
+
const authRoute = { fetch(request) {
|
|
930
|
+
return handleAuth(request);
|
|
931
|
+
} };
|
|
932
|
+
/** Read the configured log from server code. Apply access checks before returning it to a caller. */
|
|
933
|
+
function getAuthEvents(definition = resolveDefaultDefinition(), request) {
|
|
934
|
+
const events = resolveAuthOptions(definition, {
|
|
935
|
+
request,
|
|
936
|
+
env: envResolverFor(definition)
|
|
937
|
+
}).options.events;
|
|
938
|
+
return events ? events.store : void 0;
|
|
939
|
+
}
|
|
940
|
+
async function readAuthEvents(definition, parse, read) {
|
|
941
|
+
const store = getAuthEvents(definition);
|
|
942
|
+
if (!store) throw authErrorDiagnostics.AUTH_R0018({ message: "Auth events are disabled. Configure events.store in defineAuth()." });
|
|
943
|
+
try {
|
|
944
|
+
parse();
|
|
945
|
+
} catch (error) {
|
|
946
|
+
const invalid = authErrorDiagnostics.AUTH_EVENT_QUERY_INVALID.is(error) ? error : authErrorDiagnostics.AUTH_EVENT_QUERY_INVALID({
|
|
947
|
+
problem: "input",
|
|
948
|
+
cause: error
|
|
949
|
+
});
|
|
950
|
+
return [Object.assign(toResultError(invalid), { status: 400 }), void 0];
|
|
951
|
+
}
|
|
952
|
+
try {
|
|
953
|
+
return [void 0, await read(store)];
|
|
954
|
+
} catch (error) {
|
|
955
|
+
return [toResultError(authErrorDiagnostics.AUTH_EVENT_READ_FAILED({ cause: error })), void 0];
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
/** Read one page of the Auth event log. Invalid filters and store failures return `[error, undefined]`. */
|
|
959
|
+
function listAuthEvents(input = {}, definition) {
|
|
960
|
+
return readAuthEvents(definition, () => parseAuthEventList(input), (store) => store.list(input));
|
|
961
|
+
}
|
|
962
|
+
/** Count the Auth events of a window. An invalid window and store failures return `[error, undefined]`. */
|
|
963
|
+
function aggregateAuthEvents(window, definition) {
|
|
964
|
+
return readAuthEvents(definition, () => parseAuthEventWindow(window), (store) => store.aggregate(window));
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Resolve the primary Definition once, with the same request context for the provider and Console policy.
|
|
968
|
+
* `host.impersonation` lets the Console start impersonation. It is off by default.
|
|
969
|
+
*/
|
|
970
|
+
function getAuthConsoleForRequest(request, event, host) {
|
|
971
|
+
const definition = resolveDefaultDefinition();
|
|
972
|
+
const resolved = resolveAuthOptions(definition, {
|
|
973
|
+
request,
|
|
974
|
+
event,
|
|
975
|
+
env: envResolverFor(definition)
|
|
976
|
+
});
|
|
977
|
+
return createAuthConsole(requestProvider(definition, resolved), resolved.options.console, resolved.options.events ? resolved.options.events.store : void 0, host);
|
|
978
|
+
}
|
|
979
|
+
//#endregion
|
|
980
|
+
export { toAuthRequest as C, withAuthorization as D, withAuth as E, signOut as S, withAnonymousAuthorization as T, requireAbility as _, checkAuthMember as a, requireAuthorization as b, createAuthForRequest as c, getAuth as d, getAuthConsoleForRequest as f, listAuthEvents as g, handleAuthRequest as h, can as i, createAuthHandler as l, handleAuth as m, assertAuthOrigin as n, createAuth as o, getAuthEvents as p, authRoute as r, createAuthAccessHandler as s, aggregateAuthEvents as t, createAuthRequestRuntimeOptions as u, requireAuth as v, useAuth as w, requireCaller as x, requireAuthAccessRoutes as y };
|