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