@finueva/auth 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +50 -0
- package/THIRD_PARTY_NOTICES.md +100 -0
- package/dist/errors-C-cHFWC7.d.ts +55 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +2438 -0
- package/dist/server.d.ts +21 -0
- package/dist/server.js +711 -0
- package/package.json +57 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
const messages = {
|
|
3
|
+
invalid_credentials: "The credentials are invalid.",
|
|
4
|
+
authentication_required: "Authentication is required.",
|
|
5
|
+
request_origin_denied: "The request origin is not allowed.",
|
|
6
|
+
invalid_workspace_selection: "The workspace selection is invalid.",
|
|
7
|
+
credential_rate_limited: "Credential requests are temporarily limited.",
|
|
8
|
+
state_conflict: "The authentication state conflicts with the request.",
|
|
9
|
+
access_denied: "Access is denied.",
|
|
10
|
+
identity_authority_unavailable: "Authentication is temporarily unavailable."
|
|
11
|
+
};
|
|
12
|
+
var AuthError = class extends Error {
|
|
13
|
+
code;
|
|
14
|
+
status;
|
|
15
|
+
retryAfterSeconds;
|
|
16
|
+
constructor(code, status, retryAfterSeconds) {
|
|
17
|
+
super(messages[code]);
|
|
18
|
+
this.name = "AuthError";
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
String.fromCharCode;
|
|
25
|
+
const HASH_RE = /#/g;
|
|
26
|
+
const AMPERSAND_RE = /&/g;
|
|
27
|
+
const SLASH_RE = /\//g;
|
|
28
|
+
const EQUAL_RE = /=/g;
|
|
29
|
+
const PLUS_RE = /\+/g;
|
|
30
|
+
const ENC_CARET_RE = /%5e/gi;
|
|
31
|
+
const ENC_BACKTICK_RE = /%60/gi;
|
|
32
|
+
const ENC_PIPE_RE = /%7c/gi;
|
|
33
|
+
const ENC_SPACE_RE = /%20/gi;
|
|
34
|
+
function encode(text) {
|
|
35
|
+
return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
|
|
36
|
+
}
|
|
37
|
+
function encodeQueryValue(input) {
|
|
38
|
+
return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
|
|
39
|
+
}
|
|
40
|
+
function encodeQueryKey(text) {
|
|
41
|
+
return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
|
|
42
|
+
}
|
|
43
|
+
function decode(text = "") {
|
|
44
|
+
try {
|
|
45
|
+
return decodeURIComponent("" + text);
|
|
46
|
+
} catch {
|
|
47
|
+
return "" + text;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function decodeQueryKey(text) {
|
|
51
|
+
return decode(text.replace(PLUS_RE, " "));
|
|
52
|
+
}
|
|
53
|
+
function decodeQueryValue(text) {
|
|
54
|
+
return decode(text.replace(PLUS_RE, " "));
|
|
55
|
+
}
|
|
56
|
+
function parseQuery(parametersString = "") {
|
|
57
|
+
const object = Object.create(null);
|
|
58
|
+
if (parametersString[0] === "?") parametersString = parametersString.slice(1);
|
|
59
|
+
for (const parameter of parametersString.split("&")) {
|
|
60
|
+
const s = parameter.match(/([^=]+)=?(.*)/) || [];
|
|
61
|
+
if (s.length < 2) continue;
|
|
62
|
+
const key = decodeQueryKey(s[1]);
|
|
63
|
+
if (key === "__proto__" || key === "constructor") continue;
|
|
64
|
+
const value = decodeQueryValue(s[2] || "");
|
|
65
|
+
if (object[key] === void 0) object[key] = value;
|
|
66
|
+
else if (Array.isArray(object[key])) object[key].push(value);
|
|
67
|
+
else object[key] = [object[key], value];
|
|
68
|
+
}
|
|
69
|
+
return object;
|
|
70
|
+
}
|
|
71
|
+
function encodeQueryItem(key, value) {
|
|
72
|
+
if (typeof value === "number" || typeof value === "boolean") value = String(value);
|
|
73
|
+
if (!value) return encodeQueryKey(key);
|
|
74
|
+
if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
|
|
75
|
+
return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
|
|
76
|
+
}
|
|
77
|
+
function stringifyQuery(query) {
|
|
78
|
+
return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
|
|
79
|
+
}
|
|
80
|
+
const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
|
|
81
|
+
const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
|
|
82
|
+
const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
|
|
83
|
+
const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
|
|
84
|
+
const JOIN_LEADING_SLASH_RE = /^\.?\//;
|
|
85
|
+
function hasProtocol(inputString, opts = {}) {
|
|
86
|
+
if (typeof opts === "boolean") opts = { acceptRelative: opts };
|
|
87
|
+
if (opts.strict) return PROTOCOL_STRICT_REGEX.test(inputString);
|
|
88
|
+
return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
|
|
89
|
+
}
|
|
90
|
+
function hasTrailingSlash(input = "", respectQueryAndFragment) {
|
|
91
|
+
if (!respectQueryAndFragment) return input.endsWith("/");
|
|
92
|
+
return TRAILING_SLASH_RE.test(input);
|
|
93
|
+
}
|
|
94
|
+
function withoutTrailingSlash(input = "", respectQueryAndFragment) {
|
|
95
|
+
if (!respectQueryAndFragment) return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
|
|
96
|
+
if (!hasTrailingSlash(input, true)) return input || "/";
|
|
97
|
+
let path = input;
|
|
98
|
+
let fragment = "";
|
|
99
|
+
const fragmentIndex = input.indexOf("#");
|
|
100
|
+
if (fragmentIndex !== -1) {
|
|
101
|
+
path = input.slice(0, fragmentIndex);
|
|
102
|
+
fragment = input.slice(fragmentIndex);
|
|
103
|
+
}
|
|
104
|
+
const [s0, ...s] = path.split("?");
|
|
105
|
+
return ((s0.endsWith("/") ? s0.slice(0, -1) : s0) || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
|
|
106
|
+
}
|
|
107
|
+
function withTrailingSlash(input = "", respectQueryAndFragment) {
|
|
108
|
+
if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
|
|
109
|
+
if (hasTrailingSlash(input, true)) return input || "/";
|
|
110
|
+
let path = input;
|
|
111
|
+
let fragment = "";
|
|
112
|
+
const fragmentIndex = input.indexOf("#");
|
|
113
|
+
if (fragmentIndex !== -1) {
|
|
114
|
+
path = input.slice(0, fragmentIndex);
|
|
115
|
+
fragment = input.slice(fragmentIndex);
|
|
116
|
+
if (!path) return fragment;
|
|
117
|
+
}
|
|
118
|
+
const [s0, ...s] = path.split("?");
|
|
119
|
+
return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
|
|
120
|
+
}
|
|
121
|
+
function withBase(input, base) {
|
|
122
|
+
if (isEmptyURL(base) || hasProtocol(input)) return input;
|
|
123
|
+
const _base = withoutTrailingSlash(base);
|
|
124
|
+
if (input.startsWith(_base)) {
|
|
125
|
+
const nextChar = input[_base.length];
|
|
126
|
+
if (!nextChar || nextChar === "/" || nextChar === "?") return input;
|
|
127
|
+
}
|
|
128
|
+
return joinURL(_base, input);
|
|
129
|
+
}
|
|
130
|
+
function withQuery(input, query) {
|
|
131
|
+
const parsed = parseURL(input);
|
|
132
|
+
parsed.search = stringifyQuery({
|
|
133
|
+
...parseQuery(parsed.search),
|
|
134
|
+
...query
|
|
135
|
+
});
|
|
136
|
+
return stringifyParsedURL(parsed);
|
|
137
|
+
}
|
|
138
|
+
function isEmptyURL(url) {
|
|
139
|
+
return !url || url === "/";
|
|
140
|
+
}
|
|
141
|
+
function isNonEmptyURL(url) {
|
|
142
|
+
return url && url !== "/";
|
|
143
|
+
}
|
|
144
|
+
function joinURL(base, ...input) {
|
|
145
|
+
let url = base || "";
|
|
146
|
+
for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
|
|
147
|
+
const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
|
|
148
|
+
url = withTrailingSlash(url) + _segment;
|
|
149
|
+
} else url = segment;
|
|
150
|
+
return url;
|
|
151
|
+
}
|
|
152
|
+
const protocolRelative = Symbol.for("ufo:protocolRelative");
|
|
153
|
+
function parseURL(input = "", defaultProto) {
|
|
154
|
+
const _specialProtoMatch = input.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);
|
|
155
|
+
if (_specialProtoMatch) {
|
|
156
|
+
const [, _proto, _pathname = ""] = _specialProtoMatch;
|
|
157
|
+
return {
|
|
158
|
+
protocol: _proto.toLowerCase(),
|
|
159
|
+
pathname: _pathname,
|
|
160
|
+
href: _proto + _pathname,
|
|
161
|
+
auth: "",
|
|
162
|
+
host: "",
|
|
163
|
+
search: "",
|
|
164
|
+
hash: ""
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
if (!hasProtocol(input, { acceptRelative: true })) return defaultProto ? parseURL(defaultProto + input) : parsePath(input);
|
|
168
|
+
const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [];
|
|
169
|
+
let [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || [];
|
|
170
|
+
if (protocol === "file:") path = path.replace(/\/(?=[A-Za-z]:)/, "");
|
|
171
|
+
const { pathname, search, hash } = parsePath(path);
|
|
172
|
+
return {
|
|
173
|
+
protocol: protocol.toLowerCase(),
|
|
174
|
+
auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
|
|
175
|
+
host,
|
|
176
|
+
pathname,
|
|
177
|
+
search,
|
|
178
|
+
hash,
|
|
179
|
+
[protocolRelative]: !protocol
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function parsePath(input = "") {
|
|
183
|
+
const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
|
|
184
|
+
return {
|
|
185
|
+
pathname,
|
|
186
|
+
search,
|
|
187
|
+
hash
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function stringifyParsedURL(parsed) {
|
|
191
|
+
const pathname = parsed.pathname || "";
|
|
192
|
+
const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "";
|
|
193
|
+
const hash = parsed.hash || "";
|
|
194
|
+
const auth = parsed.auth ? parsed.auth + "@" : "";
|
|
195
|
+
const host = parsed.host || "";
|
|
196
|
+
return (parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : "") + auth + host + pathname + search + hash;
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs
|
|
200
|
+
const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
|
|
201
|
+
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
202
|
+
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
|
|
203
|
+
function jsonParseTransform(key, value) {
|
|
204
|
+
if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
|
|
205
|
+
warnKeyDropped(key);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
return value;
|
|
209
|
+
}
|
|
210
|
+
function warnKeyDropped(key) {
|
|
211
|
+
console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
|
|
212
|
+
}
|
|
213
|
+
function destr(value, options = {}) {
|
|
214
|
+
if (typeof value !== "string") return value;
|
|
215
|
+
if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
|
|
216
|
+
const _value = value.trim();
|
|
217
|
+
if (_value.length <= 9) switch (_value.toLowerCase()) {
|
|
218
|
+
case "true": return true;
|
|
219
|
+
case "false": return false;
|
|
220
|
+
case "undefined": return;
|
|
221
|
+
case "null": return null;
|
|
222
|
+
case "nan": return NaN;
|
|
223
|
+
case "infinity": return Number.POSITIVE_INFINITY;
|
|
224
|
+
case "-infinity": return Number.NEGATIVE_INFINITY;
|
|
225
|
+
}
|
|
226
|
+
if (!JsonSigRx.test(value)) {
|
|
227
|
+
if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
|
|
232
|
+
if (options.strict) throw new Error("[destr] Possible prototype pollution");
|
|
233
|
+
return JSON.parse(value, jsonParseTransform);
|
|
234
|
+
}
|
|
235
|
+
return JSON.parse(value);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
if (options.strict) throw error;
|
|
238
|
+
return value;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region ../../node_modules/.pnpm/ofetch@1.5.1/node_modules/ofetch/dist/shared/ofetch.CWycOUEr.mjs
|
|
243
|
+
var FetchError = class extends Error {
|
|
244
|
+
constructor(message, opts) {
|
|
245
|
+
super(message, opts);
|
|
246
|
+
this.name = "FetchError";
|
|
247
|
+
if (opts?.cause && !this.cause) this.cause = opts.cause;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
function createFetchError(ctx) {
|
|
251
|
+
const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
|
|
252
|
+
const method = ctx.request?.method || ctx.options?.method || "GET";
|
|
253
|
+
const url = ctx.request?.url || String(ctx.request) || "/";
|
|
254
|
+
const fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>"}${errorMessage ? ` ${errorMessage}` : ""}`, ctx.error ? { cause: ctx.error } : void 0);
|
|
255
|
+
for (const key of [
|
|
256
|
+
"request",
|
|
257
|
+
"options",
|
|
258
|
+
"response"
|
|
259
|
+
]) Object.defineProperty(fetchError, key, { get() {
|
|
260
|
+
return ctx[key];
|
|
261
|
+
} });
|
|
262
|
+
for (const [key, refKey] of [
|
|
263
|
+
["data", "_data"],
|
|
264
|
+
["status", "status"],
|
|
265
|
+
["statusCode", "status"],
|
|
266
|
+
["statusText", "statusText"],
|
|
267
|
+
["statusMessage", "statusText"]
|
|
268
|
+
]) Object.defineProperty(fetchError, key, { get() {
|
|
269
|
+
return ctx.response && ctx.response[refKey];
|
|
270
|
+
} });
|
|
271
|
+
return fetchError;
|
|
272
|
+
}
|
|
273
|
+
const payloadMethods = new Set(Object.freeze([
|
|
274
|
+
"PATCH",
|
|
275
|
+
"POST",
|
|
276
|
+
"PUT",
|
|
277
|
+
"DELETE"
|
|
278
|
+
]));
|
|
279
|
+
function isPayloadMethod(method = "GET") {
|
|
280
|
+
return payloadMethods.has(method.toUpperCase());
|
|
281
|
+
}
|
|
282
|
+
function isJSONSerializable(value) {
|
|
283
|
+
if (value === void 0) return false;
|
|
284
|
+
const t = typeof value;
|
|
285
|
+
if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
|
|
286
|
+
if (t !== "object") return false;
|
|
287
|
+
if (Array.isArray(value)) return true;
|
|
288
|
+
if (value.buffer) return false;
|
|
289
|
+
if (value instanceof FormData || value instanceof URLSearchParams) return false;
|
|
290
|
+
return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
|
|
291
|
+
}
|
|
292
|
+
const textTypes = new Set([
|
|
293
|
+
"image/svg",
|
|
294
|
+
"application/xml",
|
|
295
|
+
"application/xhtml",
|
|
296
|
+
"application/html"
|
|
297
|
+
]);
|
|
298
|
+
const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
|
|
299
|
+
function detectResponseType(_contentType = "") {
|
|
300
|
+
if (!_contentType) return "json";
|
|
301
|
+
const contentType = _contentType.split(";").shift() || "";
|
|
302
|
+
if (JSON_RE.test(contentType)) return "json";
|
|
303
|
+
if (contentType === "text/event-stream") return "stream";
|
|
304
|
+
if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
|
|
305
|
+
return "blob";
|
|
306
|
+
}
|
|
307
|
+
function resolveFetchOptions(request, input, defaults, Headers) {
|
|
308
|
+
const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers);
|
|
309
|
+
let query;
|
|
310
|
+
if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
|
|
311
|
+
...defaults?.params,
|
|
312
|
+
...defaults?.query,
|
|
313
|
+
...input?.params,
|
|
314
|
+
...input?.query
|
|
315
|
+
};
|
|
316
|
+
return {
|
|
317
|
+
...defaults,
|
|
318
|
+
...input,
|
|
319
|
+
query,
|
|
320
|
+
params: query,
|
|
321
|
+
headers
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function mergeHeaders(input, defaults, Headers) {
|
|
325
|
+
if (!defaults) return new Headers(input);
|
|
326
|
+
const headers = new Headers(defaults);
|
|
327
|
+
if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers(input)) headers.set(key, value);
|
|
328
|
+
return headers;
|
|
329
|
+
}
|
|
330
|
+
async function callHooks(context, hooks) {
|
|
331
|
+
if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
|
|
332
|
+
else await hooks(context);
|
|
333
|
+
}
|
|
334
|
+
const retryStatusCodes = new Set([
|
|
335
|
+
408,
|
|
336
|
+
409,
|
|
337
|
+
425,
|
|
338
|
+
429,
|
|
339
|
+
500,
|
|
340
|
+
502,
|
|
341
|
+
503,
|
|
342
|
+
504
|
|
343
|
+
]);
|
|
344
|
+
const nullBodyResponses = new Set([
|
|
345
|
+
101,
|
|
346
|
+
204,
|
|
347
|
+
205,
|
|
348
|
+
304
|
|
349
|
+
]);
|
|
350
|
+
function createFetch(globalOptions = {}) {
|
|
351
|
+
const { fetch = globalThis.fetch, Headers = globalThis.Headers, AbortController = globalThis.AbortController } = globalOptions;
|
|
352
|
+
async function onError(context) {
|
|
353
|
+
const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
|
|
354
|
+
if (context.options.retry !== false && !isAbort) {
|
|
355
|
+
let retries;
|
|
356
|
+
if (typeof context.options.retry === "number") retries = context.options.retry;
|
|
357
|
+
else retries = isPayloadMethod(context.options.method) ? 0 : 1;
|
|
358
|
+
const responseCode = context.response && context.response.status || 500;
|
|
359
|
+
if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
|
|
360
|
+
const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
|
|
361
|
+
if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
362
|
+
return $fetchRaw(context.request, {
|
|
363
|
+
...context.options,
|
|
364
|
+
retry: retries - 1
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const error = createFetchError(context);
|
|
369
|
+
if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
|
|
373
|
+
const context = {
|
|
374
|
+
request: _request,
|
|
375
|
+
options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
|
|
376
|
+
response: void 0,
|
|
377
|
+
error: void 0
|
|
378
|
+
};
|
|
379
|
+
if (context.options.method) context.options.method = context.options.method.toUpperCase();
|
|
380
|
+
if (context.options.onRequest) {
|
|
381
|
+
await callHooks(context, context.options.onRequest);
|
|
382
|
+
if (!(context.options.headers instanceof Headers)) context.options.headers = new Headers(context.options.headers || {});
|
|
383
|
+
}
|
|
384
|
+
if (typeof context.request === "string") {
|
|
385
|
+
if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
|
|
386
|
+
if (context.options.query) {
|
|
387
|
+
context.request = withQuery(context.request, context.options.query);
|
|
388
|
+
delete context.options.query;
|
|
389
|
+
}
|
|
390
|
+
if ("query" in context.options) delete context.options.query;
|
|
391
|
+
if ("params" in context.options) delete context.options.params;
|
|
392
|
+
}
|
|
393
|
+
if (context.options.body && isPayloadMethod(context.options.method)) {
|
|
394
|
+
if (isJSONSerializable(context.options.body)) {
|
|
395
|
+
const contentType = context.options.headers.get("content-type");
|
|
396
|
+
if (typeof context.options.body !== "string") context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);
|
|
397
|
+
if (!contentType) context.options.headers.set("content-type", "application/json");
|
|
398
|
+
if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
|
|
399
|
+
} else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
|
|
400
|
+
if (!("duplex" in context.options)) context.options.duplex = "half";
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
let abortTimeout;
|
|
404
|
+
if (!context.options.signal && context.options.timeout) {
|
|
405
|
+
const controller = new AbortController();
|
|
406
|
+
abortTimeout = setTimeout(() => {
|
|
407
|
+
const error = new Error("[TimeoutError]: The operation was aborted due to timeout");
|
|
408
|
+
error.name = "TimeoutError";
|
|
409
|
+
error.code = 23;
|
|
410
|
+
controller.abort(error);
|
|
411
|
+
}, context.options.timeout);
|
|
412
|
+
context.options.signal = controller.signal;
|
|
413
|
+
}
|
|
414
|
+
try {
|
|
415
|
+
context.response = await fetch(context.request, context.options);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
context.error = error;
|
|
418
|
+
if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
|
|
419
|
+
return await onError(context);
|
|
420
|
+
} finally {
|
|
421
|
+
if (abortTimeout) clearTimeout(abortTimeout);
|
|
422
|
+
}
|
|
423
|
+
if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
|
|
424
|
+
const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
|
|
425
|
+
switch (responseType) {
|
|
426
|
+
case "json": {
|
|
427
|
+
const data = await context.response.text();
|
|
428
|
+
const parseFunction = context.options.parseResponse || destr;
|
|
429
|
+
context.response._data = parseFunction(data);
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
case "stream":
|
|
433
|
+
context.response._data = context.response.body || context.response._bodyInit;
|
|
434
|
+
break;
|
|
435
|
+
default: context.response._data = await context.response[responseType]();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (context.options.onResponse) await callHooks(context, context.options.onResponse);
|
|
439
|
+
if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
|
|
440
|
+
if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
|
|
441
|
+
return await onError(context);
|
|
442
|
+
}
|
|
443
|
+
return context.response;
|
|
444
|
+
};
|
|
445
|
+
const $fetch = async function $fetch2(request, options) {
|
|
446
|
+
return (await $fetchRaw(request, options))._data;
|
|
447
|
+
};
|
|
448
|
+
$fetch.raw = $fetchRaw;
|
|
449
|
+
$fetch.native = (...args) => fetch(...args);
|
|
450
|
+
$fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
|
|
451
|
+
...globalOptions,
|
|
452
|
+
...customGlobalOptions,
|
|
453
|
+
defaults: {
|
|
454
|
+
...globalOptions.defaults,
|
|
455
|
+
...customGlobalOptions.defaults,
|
|
456
|
+
...defaultOptions
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
return $fetch;
|
|
460
|
+
}
|
|
461
|
+
//#endregion
|
|
462
|
+
//#region src/shared.ts
|
|
463
|
+
const id = /^[A-Za-z0-9_-]{1,128}$/;
|
|
464
|
+
const email = /^[^\s@]+@[^\s@]+$/;
|
|
465
|
+
function normalizeOrigin(value, name) {
|
|
466
|
+
if (value.length === 0 || value.length > 2048 || /[^\x20-\x7e]/.test(value)) throw new TypeError(`${name} must be an ASCII HTTP origin`);
|
|
467
|
+
let url;
|
|
468
|
+
try {
|
|
469
|
+
url = new URL(value);
|
|
470
|
+
} catch {
|
|
471
|
+
throw new TypeError(`${name} must be an ASCII HTTP origin`);
|
|
472
|
+
}
|
|
473
|
+
const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost") || url.hostname === "127.0.0.1";
|
|
474
|
+
if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.pathname !== "/" || url.search || url.hash || url.origin !== value) throw new TypeError(`${name} must be an ASCII HTTP origin`);
|
|
475
|
+
return url.origin;
|
|
476
|
+
}
|
|
477
|
+
function normalizeTimeout(value) {
|
|
478
|
+
const timeout = value ?? 1e4;
|
|
479
|
+
if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new TypeError("timeoutMs must be an integer from 1 to 60000");
|
|
480
|
+
return timeout;
|
|
481
|
+
}
|
|
482
|
+
function normalizeSession(value) {
|
|
483
|
+
if (value === null) return null;
|
|
484
|
+
if (!isObject(value) || !isObject(value.session) || !isObject(value.user)) throw authorityUnavailable();
|
|
485
|
+
const expiresAt = toDate(value.session.expiresAt);
|
|
486
|
+
const image = value.user.image;
|
|
487
|
+
if (!isId(value.session.id) || !expiresAt || !isId(value.user.id) || typeof value.user.name !== "string" || value.user.name.length > 256 || typeof value.user.email !== "string" || value.user.email.length > 320 || !email.test(value.user.email) || typeof value.user.emailVerified !== "boolean" || image !== null && image !== void 0 && (typeof image !== "string" || image.length > 2048)) throw authorityUnavailable();
|
|
488
|
+
return {
|
|
489
|
+
id: value.session.id,
|
|
490
|
+
expiresAt,
|
|
491
|
+
user: {
|
|
492
|
+
id: value.user.id,
|
|
493
|
+
name: value.user.name,
|
|
494
|
+
email: value.user.email,
|
|
495
|
+
emailVerified: value.user.emailVerified,
|
|
496
|
+
image: image ?? null
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
function normalizeDriveCredential(value, now) {
|
|
501
|
+
if (!isObject(value) || value.tokenType !== "Bearer" || value.expiresIn !== 900 || typeof value.token !== "string" || value.token.length === 0 || value.token.length + 7 > 16 * 1024) throw authorityUnavailable();
|
|
502
|
+
return {
|
|
503
|
+
tokenType: "Bearer",
|
|
504
|
+
token: value.token,
|
|
505
|
+
expiresAt: new Date(now + value.expiresIn * 1e3)
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function fromAuthorityError(value, fallbackStatus, retryAfter) {
|
|
509
|
+
const mapped = mapError(isObject(value) && typeof value.code === "string" ? value.code : void 0, fallbackStatus);
|
|
510
|
+
return new AuthError(mapped.code, mapped.status, parseRetryAfter(retryAfter));
|
|
511
|
+
}
|
|
512
|
+
function authorityUnavailable() {
|
|
513
|
+
return new AuthError("identity_authority_unavailable", 503);
|
|
514
|
+
}
|
|
515
|
+
function mapError(code, status) {
|
|
516
|
+
if (code === "authentication_required") return {
|
|
517
|
+
code,
|
|
518
|
+
status: 401
|
|
519
|
+
};
|
|
520
|
+
if (code === "request_origin_denied") return {
|
|
521
|
+
code,
|
|
522
|
+
status: 403
|
|
523
|
+
};
|
|
524
|
+
if (code === "invalid_workspace_selection") return {
|
|
525
|
+
code,
|
|
526
|
+
status: 422
|
|
527
|
+
};
|
|
528
|
+
if (code === "credential_rate_limited") return {
|
|
529
|
+
code,
|
|
530
|
+
status: 429
|
|
531
|
+
};
|
|
532
|
+
if (code === "identity_authority_unavailable") return {
|
|
533
|
+
code,
|
|
534
|
+
status: 503
|
|
535
|
+
};
|
|
536
|
+
if (status === 401 || status === 400) return {
|
|
537
|
+
code: "invalid_credentials",
|
|
538
|
+
status: 401
|
|
539
|
+
};
|
|
540
|
+
if (status === 403) return {
|
|
541
|
+
code: "access_denied",
|
|
542
|
+
status: 403
|
|
543
|
+
};
|
|
544
|
+
if (status === 409) return {
|
|
545
|
+
code: "state_conflict",
|
|
546
|
+
status: 409
|
|
547
|
+
};
|
|
548
|
+
if (status === 422) return {
|
|
549
|
+
code: "invalid_workspace_selection",
|
|
550
|
+
status: 422
|
|
551
|
+
};
|
|
552
|
+
if (status === 429) return {
|
|
553
|
+
code: "credential_rate_limited",
|
|
554
|
+
status: 429
|
|
555
|
+
};
|
|
556
|
+
return {
|
|
557
|
+
code: "identity_authority_unavailable",
|
|
558
|
+
status: 503
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function parseRetryAfter(value) {
|
|
562
|
+
if (!value || !/^\d+$/.test(value)) return void 0;
|
|
563
|
+
const seconds = Number(value);
|
|
564
|
+
return Number.isSafeInteger(seconds) && seconds >= 1 && seconds <= 3600 ? seconds : void 0;
|
|
565
|
+
}
|
|
566
|
+
function toDate(value) {
|
|
567
|
+
const result = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
|
|
568
|
+
return result && Number.isFinite(result.getTime()) ? result : void 0;
|
|
569
|
+
}
|
|
570
|
+
function isId(value) {
|
|
571
|
+
return typeof value === "string" && id.test(value);
|
|
572
|
+
}
|
|
573
|
+
function isObject(value) {
|
|
574
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
575
|
+
}
|
|
576
|
+
//#endregion
|
|
577
|
+
//#region src/http.ts
|
|
578
|
+
const MAX_RESPONSE_BYTES = 64 * 1024;
|
|
579
|
+
async function requestJson(url, options) {
|
|
580
|
+
let response;
|
|
581
|
+
try {
|
|
582
|
+
response = await createFetch({ fetch: options.fetch }).raw(url, {
|
|
583
|
+
method: options.method,
|
|
584
|
+
headers: options.headers,
|
|
585
|
+
body: options.body,
|
|
586
|
+
credentials: "include",
|
|
587
|
+
retry: 0,
|
|
588
|
+
timeout: options.timeoutMs,
|
|
589
|
+
redirect: "manual",
|
|
590
|
+
responseType: "stream",
|
|
591
|
+
ignoreResponseError: true
|
|
592
|
+
});
|
|
593
|
+
} catch {
|
|
594
|
+
throw authorityUnavailable();
|
|
595
|
+
}
|
|
596
|
+
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
597
|
+
if (response.status >= 300 || response.status < 200 || contentType !== "application/json") {
|
|
598
|
+
const body = contentType === "application/json" ? await readJson(response) : void 0;
|
|
599
|
+
await response.body?.cancel();
|
|
600
|
+
throw fromAuthorityError(body, response.status, response.headers.get("retry-after"));
|
|
601
|
+
}
|
|
602
|
+
return readJson(response);
|
|
603
|
+
}
|
|
604
|
+
async function readJson(response) {
|
|
605
|
+
const length = response.headers.get("content-length");
|
|
606
|
+
if (length && (!/^\d+$/.test(length) || Number(length) > MAX_RESPONSE_BYTES)) {
|
|
607
|
+
await response.body?.cancel();
|
|
608
|
+
throw authorityUnavailable();
|
|
609
|
+
}
|
|
610
|
+
if (!response.body) throw authorityUnavailable();
|
|
611
|
+
const reader = response.body.getReader();
|
|
612
|
+
const chunks = [];
|
|
613
|
+
let size = 0;
|
|
614
|
+
try {
|
|
615
|
+
while (true) {
|
|
616
|
+
const { done, value } = await reader.read();
|
|
617
|
+
if (done) break;
|
|
618
|
+
size += value.byteLength;
|
|
619
|
+
if (size > MAX_RESPONSE_BYTES) throw authorityUnavailable();
|
|
620
|
+
chunks.push(value);
|
|
621
|
+
}
|
|
622
|
+
} catch (error) {
|
|
623
|
+
await reader.cancel();
|
|
624
|
+
throw error;
|
|
625
|
+
} finally {
|
|
626
|
+
reader.releaseLock();
|
|
627
|
+
}
|
|
628
|
+
const bytes = new Uint8Array(size);
|
|
629
|
+
let offset = 0;
|
|
630
|
+
for (const chunk of chunks) {
|
|
631
|
+
bytes.set(chunk, offset);
|
|
632
|
+
offset += chunk.byteLength;
|
|
633
|
+
}
|
|
634
|
+
try {
|
|
635
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
636
|
+
} catch {
|
|
637
|
+
throw authorityUnavailable();
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
//#endregion
|
|
641
|
+
//#region src/server.ts
|
|
642
|
+
function createServerAuth(options) {
|
|
643
|
+
const authOrigin = normalizeOrigin(options.authOrigin, "authOrigin");
|
|
644
|
+
const appOrigin = normalizeOrigin(options.appOrigin, "appOrigin");
|
|
645
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
646
|
+
if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
|
|
647
|
+
const now = options.now ?? Date.now;
|
|
648
|
+
const timeoutMs = normalizeTimeout(options.timeoutMs);
|
|
649
|
+
const cookie = authCookieHeader(options.request.headers.get("cookie"));
|
|
650
|
+
const authHeaders = () => ({
|
|
651
|
+
cookie,
|
|
652
|
+
origin: appOrigin
|
|
653
|
+
});
|
|
654
|
+
return {
|
|
655
|
+
async getSession() {
|
|
656
|
+
return normalizeSession(await requestJson(joinURL(authOrigin, "api/v1/auth/get-session"), {
|
|
657
|
+
fetch: fetchImpl,
|
|
658
|
+
timeoutMs,
|
|
659
|
+
method: "GET",
|
|
660
|
+
headers: { cookie }
|
|
661
|
+
}));
|
|
662
|
+
},
|
|
663
|
+
async getDriveCredential(input) {
|
|
664
|
+
if (input.workspace.type !== "personal") throw new AuthError("invalid_workspace_selection", 422);
|
|
665
|
+
return normalizeDriveCredential(await requestJson(joinURL(authOrigin, "api/v1/auth/drive-credential"), {
|
|
666
|
+
fetch: fetchImpl,
|
|
667
|
+
timeoutMs,
|
|
668
|
+
method: "POST",
|
|
669
|
+
headers: {
|
|
670
|
+
...authHeaders(),
|
|
671
|
+
"content-type": "application/json; charset=utf-8"
|
|
672
|
+
},
|
|
673
|
+
body: { workspace: { type: "personal" } }
|
|
674
|
+
}), now());
|
|
675
|
+
},
|
|
676
|
+
async signOut() {
|
|
677
|
+
let response;
|
|
678
|
+
try {
|
|
679
|
+
response = await fetchImpl(joinURL(authOrigin, "api/v1/auth/sign-out"), {
|
|
680
|
+
method: "POST",
|
|
681
|
+
headers: authHeaders(),
|
|
682
|
+
redirect: "manual",
|
|
683
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
684
|
+
});
|
|
685
|
+
} catch {
|
|
686
|
+
throw authorityUnavailable();
|
|
687
|
+
}
|
|
688
|
+
if (!response.ok) {
|
|
689
|
+
await response.body?.cancel();
|
|
690
|
+
throw authorityUnavailable();
|
|
691
|
+
}
|
|
692
|
+
const getSetCookie = response.headers.getSetCookie;
|
|
693
|
+
const cookies = getSetCookie ? getSetCookie.call(response.headers) : [response.headers.get("set-cookie")].filter(Boolean);
|
|
694
|
+
await response.body?.cancel();
|
|
695
|
+
return { applyCookies(headers) {
|
|
696
|
+
for (const value of cookies) headers.append("set-cookie", value);
|
|
697
|
+
} };
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function authCookieHeader(value) {
|
|
702
|
+
if (!value) return "";
|
|
703
|
+
return value.split(";").map((cookie) => cookie.trim()).filter((cookie) => {
|
|
704
|
+
const separator = cookie.indexOf("=");
|
|
705
|
+
if (separator <= 0) return false;
|
|
706
|
+
const name = cookie.slice(0, separator);
|
|
707
|
+
return name.startsWith("better-auth.") || name.startsWith("__Secure-better-auth.");
|
|
708
|
+
}).join("; ");
|
|
709
|
+
}
|
|
710
|
+
//#endregion
|
|
711
|
+
export { AuthError, createServerAuth };
|