@fedify/webfinger 2.5.0-dev.2664 → 2.5.0-dev.2710

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.
@@ -1,2504 +0,0 @@
1
- import { createTestMeterProvider, test } from "@fedify/fixture";
2
- import { FetchError, UrlError, getUserAgent } from "@fedify/vocab-runtime";
3
- import { configure, getLogger, reset } from "@logtape/logtape";
4
- import { withTimeout } from "es-toolkit";
5
- import { deepStrictEqual, ok } from "node:assert/strict";
6
- import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
8
- import { test as test$1 } from "node:test";
9
- //#region \0rolldown/runtime.js
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
- var __copyProps = (to, from, except, desc) => {
18
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
- key = keys[i];
20
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
21
- get: ((k) => from[k]).bind(null, key),
22
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
- });
24
- }
25
- return to;
26
- };
27
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
- value: mod,
29
- enumerable: true
30
- }) : target, mod));
31
- //#endregion
32
- //#region ../../node_modules/.pnpm/regexparam@3.0.0/node_modules/regexparam/dist/index.mjs
33
- var import_glob_to_regexp = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
34
- module.exports = function(glob, opts) {
35
- if (typeof glob !== "string") throw new TypeError("Expected a string");
36
- var str = String(glob);
37
- var reStr = "";
38
- var extended = opts ? !!opts.extended : false;
39
- var globstar = opts ? !!opts.globstar : false;
40
- var inGroup = false;
41
- var flags = opts && typeof opts.flags === "string" ? opts.flags : "";
42
- var c;
43
- for (var i = 0, len = str.length; i < len; i++) {
44
- c = str[i];
45
- switch (c) {
46
- case "/":
47
- case "$":
48
- case "^":
49
- case "+":
50
- case ".":
51
- case "(":
52
- case ")":
53
- case "=":
54
- case "!":
55
- case "|":
56
- reStr += "\\" + c;
57
- break;
58
- case "?": if (extended) {
59
- reStr += ".";
60
- break;
61
- }
62
- case "[":
63
- case "]": if (extended) {
64
- reStr += c;
65
- break;
66
- }
67
- case "{": if (extended) {
68
- inGroup = true;
69
- reStr += "(";
70
- break;
71
- }
72
- case "}": if (extended) {
73
- inGroup = false;
74
- reStr += ")";
75
- break;
76
- }
77
- case ",":
78
- if (inGroup) {
79
- reStr += "|";
80
- break;
81
- }
82
- reStr += "\\" + c;
83
- break;
84
- case "*":
85
- var prevChar = str[i - 1];
86
- var starCount = 1;
87
- while (str[i + 1] === "*") {
88
- starCount++;
89
- i++;
90
- }
91
- var nextChar = str[i + 1];
92
- if (!globstar) reStr += ".*";
93
- else if (starCount > 1 && (prevChar === "/" || prevChar === void 0) && (nextChar === "/" || nextChar === void 0)) {
94
- reStr += "((?:[^/]*(?:/|$))*)";
95
- i++;
96
- } else reStr += "([^/]*)";
97
- break;
98
- default: reStr += c;
99
- }
100
- }
101
- if (!flags || !~flags.indexOf("g")) reStr = "^" + reStr + "$";
102
- return new RegExp(reStr, flags);
103
- };
104
- })))(), 1);
105
- /**
106
- * @param {string|RegExp} input The route pattern
107
- * @param {boolean} [loose] Allow open-ended matching. Ignored with `RegExp` input.
108
- */
109
- function parse(input, loose) {
110
- if (input instanceof RegExp) return {
111
- keys: false,
112
- pattern: input
113
- };
114
- var c, o, tmp, ext, keys = [], pattern = "", arr = input.split("/");
115
- arr[0] || arr.shift();
116
- while (tmp = arr.shift()) {
117
- c = tmp[0];
118
- if (c === "*") {
119
- keys.push(c);
120
- pattern += tmp[1] === "?" ? "(?:/(.*))?" : "/(.*)";
121
- } else if (c === ":") {
122
- o = tmp.indexOf("?", 1);
123
- ext = tmp.indexOf(".", 1);
124
- keys.push(tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length));
125
- pattern += !!~o && !~ext ? "(?:/([^/]+?))?" : "/([^/]+?)";
126
- if (!!~ext) pattern += (!!~o ? "?" : "") + "\\" + tmp.substring(ext);
127
- } else pattern += "/" + tmp;
128
- }
129
- return {
130
- keys,
131
- pattern: new RegExp("^" + pattern + (loose ? "(?=$|/)" : "/?$"), "i")
132
- };
133
- }
134
- //#endregion
135
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/TypeDescriptor.js
136
- const valueTypes = /* @__PURE__ */ new Set([
137
- "boolean",
138
- "number",
139
- "null",
140
- "string",
141
- "undefined"
142
- ]);
143
- const referenceTypes = /* @__PURE__ */ new Set([
144
- "array",
145
- "function",
146
- "object",
147
- "symbol"
148
- ]);
149
- const detectableTypes = /* @__PURE__ */ new Set([
150
- "boolean",
151
- "function",
152
- "number",
153
- "string",
154
- "symbol"
155
- ]);
156
- const typeConstructors = /* @__PURE__ */ new Set([
157
- Boolean,
158
- Number,
159
- String
160
- ]);
161
- var TypeDescriptor = class TypeDescriptor {
162
- constructor(value) {
163
- this.name = TypeDescriptor.of(value);
164
- this.isValueType = TypeDescriptor.isValueType(value);
165
- this.isReferenceType = TypeDescriptor.isReferenceType(value);
166
- this.isArray = TypeDescriptor.isArray(value);
167
- this.isBoolean = TypeDescriptor.isBoolean(value);
168
- this.isFunction = TypeDescriptor.isFunction(value);
169
- this.isNull = TypeDescriptor.isNull(value);
170
- this.isNumber = TypeDescriptor.isNumber(value);
171
- this.isObject = TypeDescriptor.isObject(value);
172
- this.isString = TypeDescriptor.isString(value);
173
- this.isSymbol = TypeDescriptor.isSymbol(value);
174
- this.isUndefined = TypeDescriptor.isUndefined(value);
175
- }
176
- static of(value) {
177
- if (value === null) return "null";
178
- if (value === void 0) return "undefined";
179
- const detectedType = typeof value;
180
- if (detectableTypes.has(detectedType)) return detectedType;
181
- if (detectedType === "object") {
182
- if (Array.isArray(value)) return "array";
183
- if (typeConstructors.has(value.constructor)) return value.constructor.name.toLowerCase();
184
- return detectedType;
185
- }
186
- throw new Error("Failed due to an unknown type.");
187
- }
188
- static from(value) {
189
- return new TypeDescriptor(value);
190
- }
191
- static isValueType(value) {
192
- return valueTypes.has(TypeDescriptor.of(value));
193
- }
194
- static isReferenceType(value) {
195
- return referenceTypes.has(TypeDescriptor.of(value));
196
- }
197
- static isArray(value) {
198
- return TypeDescriptor.of(value) === "array";
199
- }
200
- static isBoolean(value) {
201
- return TypeDescriptor.of(value) === "boolean";
202
- }
203
- static isFunction(value) {
204
- return TypeDescriptor.of(value) === "function";
205
- }
206
- static isNull(value) {
207
- return TypeDescriptor.of(value) === "null";
208
- }
209
- static isNumber(value) {
210
- return TypeDescriptor.of(value) === "number";
211
- }
212
- static isObject(value) {
213
- return TypeDescriptor.of(value) === "object";
214
- }
215
- static isString(value) {
216
- return TypeDescriptor.of(value) === "string";
217
- }
218
- static isSymbol(value) {
219
- return TypeDescriptor.of(value) === "symbol";
220
- }
221
- static isUndefined(value) {
222
- return TypeDescriptor.of(value) === "undefined";
223
- }
224
- };
225
- //#endregion
226
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/IsSubsetOf.js
227
- const allowedTypes = /* @__PURE__ */ new Set([
228
- "array",
229
- "object",
230
- "function",
231
- "null"
232
- ]);
233
- const isSubsetOf = function(subset, superset, visited = []) {
234
- const subsetType = TypeDescriptor.of(subset);
235
- const supersetType = TypeDescriptor.of(superset);
236
- if (!allowedTypes.has(subsetType)) throw new Error(`Type '${subsetType}' is not supported.`);
237
- if (!allowedTypes.has(supersetType)) throw new Error(`Type '${supersetType}' is not supported.`);
238
- if (TypeDescriptor.isFunction(subset)) {
239
- if (!TypeDescriptor.isFunction(superset)) throw new Error(`Types '${subsetType}' and '${supersetType}' do not match.`);
240
- return subset.toString() === superset.toString();
241
- }
242
- if (TypeDescriptor.isArray(subset)) {
243
- if (!TypeDescriptor.isArray(superset)) throw new Error(`Types '${subsetType}' and '${supersetType}' do not match.`);
244
- if (subset.length > superset.length) return false;
245
- for (const subsetItem of subset) {
246
- const subsetItemType = TypeDescriptor.of(subsetItem);
247
- let isItemInSuperset;
248
- switch (subsetItemType) {
249
- case "array":
250
- case "object":
251
- case "function":
252
- if (visited.includes(subsetItem)) continue;
253
- visited.push(subsetItem);
254
- isItemInSuperset = superset.some((supersetItem) => {
255
- try {
256
- return isSubsetOf(subsetItem, supersetItem, visited);
257
- } catch {
258
- return false;
259
- }
260
- });
261
- break;
262
- default: isItemInSuperset = superset.includes(subsetItem);
263
- }
264
- if (!isItemInSuperset) return false;
265
- }
266
- return true;
267
- }
268
- if (TypeDescriptor.isObject(subset)) {
269
- if (!TypeDescriptor.isObject(superset) || TypeDescriptor.isArray(superset)) throw new Error(`Types '${subsetType}' and '${supersetType}' do not match.`);
270
- if (Object.keys(subset).length > Object.keys(superset).length) return false;
271
- for (const [subsetKey, subsetValue] of Object.entries(subset)) {
272
- const supersetValue = superset[subsetKey];
273
- switch (TypeDescriptor.of(subsetValue)) {
274
- case "array":
275
- case "object":
276
- case "function":
277
- if (visited.includes(subsetValue)) continue;
278
- visited.push(subsetValue);
279
- try {
280
- if (!isSubsetOf(subsetValue, supersetValue, visited)) return false;
281
- } catch {
282
- return false;
283
- }
284
- break;
285
- default: if (subsetValue !== supersetValue) return false;
286
- }
287
- }
288
- return true;
289
- }
290
- if (TypeDescriptor.isNull(subset)) {
291
- if (!TypeDescriptor.isNull(superset)) throw new Error(`Types '${subsetType}' and '${supersetType}' do not match.`);
292
- return true;
293
- }
294
- throw new Error("Invalid operation.");
295
- };
296
- isSubsetOf.structural = function(subset, superset, visited = []) {
297
- if (!TypeDescriptor.isObject(subset)) throw new Error(`Type '${TypeDescriptor.of(subset)}' is not supported.`);
298
- if (!TypeDescriptor.isObject(superset)) throw new Error(`Type '${TypeDescriptor.of(superset)}' is not supported.`);
299
- for (const [subsetKey, subsetValue] of Object.entries(subset)) {
300
- if (superset[subsetKey] === void 0) return false;
301
- const subsetValueType = TypeDescriptor.of(subsetValue);
302
- const supersetValue = superset[subsetKey];
303
- if (subsetValueType === "object") {
304
- if (visited.includes(subsetValue)) continue;
305
- visited.push(subsetValue);
306
- try {
307
- if (!isSubsetOf.structural(subsetValue, supersetValue, visited)) return false;
308
- } catch {
309
- return false;
310
- }
311
- }
312
- }
313
- return true;
314
- };
315
- //#endregion
316
- //#region ../../node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/dist/index.mjs
317
- var has = Object.prototype.hasOwnProperty;
318
- function find(iter, tar, key) {
319
- for (key of iter.keys()) if (dequal(key, tar)) return key;
320
- }
321
- function dequal(foo, bar) {
322
- var ctor, len, tmp;
323
- if (foo === bar) return true;
324
- if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
325
- if (ctor === Date) return foo.getTime() === bar.getTime();
326
- if (ctor === RegExp) return foo.toString() === bar.toString();
327
- if (ctor === Array) {
328
- if ((len = foo.length) === bar.length) while (len-- && dequal(foo[len], bar[len]));
329
- return len === -1;
330
- }
331
- if (ctor === Set) {
332
- if (foo.size !== bar.size) return false;
333
- for (len of foo) {
334
- tmp = len;
335
- if (tmp && typeof tmp === "object") {
336
- tmp = find(bar, tmp);
337
- if (!tmp) return false;
338
- }
339
- if (!bar.has(tmp)) return false;
340
- }
341
- return true;
342
- }
343
- if (ctor === Map) {
344
- if (foo.size !== bar.size) return false;
345
- for (len of foo) {
346
- tmp = len[0];
347
- if (tmp && typeof tmp === "object") {
348
- tmp = find(bar, tmp);
349
- if (!tmp) return false;
350
- }
351
- if (!dequal(len[1], bar.get(tmp))) return false;
352
- }
353
- return true;
354
- }
355
- if (ctor === ArrayBuffer) {
356
- foo = new Uint8Array(foo);
357
- bar = new Uint8Array(bar);
358
- } else if (ctor === DataView) {
359
- if ((len = foo.byteLength) === bar.byteLength) while (len-- && foo.getInt8(len) === bar.getInt8(len));
360
- return len === -1;
361
- }
362
- if (ArrayBuffer.isView(foo)) {
363
- if ((len = foo.byteLength) === bar.byteLength) while (len-- && foo[len] === bar[len]);
364
- return len === -1;
365
- }
366
- if (!ctor || typeof foo === "object") {
367
- len = 0;
368
- for (ctor in foo) {
369
- if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
370
- if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
371
- }
372
- return Object.keys(bar).length === len;
373
- }
374
- }
375
- return foo !== foo && bar !== bar;
376
- }
377
- //#endregion
378
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/RequestUtils.js
379
- const absoluteUrlRX = /* @__PURE__ */ new RegExp("^[a-z]+://|^data:", "i");
380
- const protocolRelativeUrlRX = /* @__PURE__ */ new RegExp("^//", "i");
381
- function hasCredentialsInUrl(url) {
382
- const urlObject = new URL(url, !absoluteUrlRX.test(url) ? "http://dummy" : void 0);
383
- return Boolean(urlObject.username || urlObject.password);
384
- }
385
- function normalizeUrl(url, allowRelativeUrls) {
386
- if (url instanceof URL) return url.href;
387
- const primitiveUrl = String(url).valueOf();
388
- if (absoluteUrlRX.test(primitiveUrl)) return new URL(primitiveUrl).href;
389
- if (protocolRelativeUrlRX.test(primitiveUrl)) return new URL(primitiveUrl, "http://dummy").href.replace(/^[a-z]+:/, "");
390
- if ("location" in globalThis) if (primitiveUrl.startsWith("/")) return `${globalThis.location.origin}${primitiveUrl}`;
391
- else return `${globalThis.location.href}/${primitiveUrl}`;
392
- else if (allowRelativeUrls) {
393
- const urlInstance = new URL(primitiveUrl, "http://dummy");
394
- return urlInstance.pathname + urlInstance.search;
395
- } else throw new Error("Relative urls are not support by default in node.js tests. Either use a utility such as jsdom to define globalThis.location or set `fetchMock.config.allowRelativeUrls = true`");
396
- }
397
- function createCallLogFromUrlAndOptions(url, options) {
398
- const pendingPromises = [];
399
- if (typeof url === "string" || url instanceof String || url instanceof URL) {
400
- const normalizedUrl = normalizeUrl(url, true);
401
- const derivedOptions = options ? { ...options } : {};
402
- if (derivedOptions.headers) derivedOptions.headers = normalizeHeaders(derivedOptions.headers);
403
- derivedOptions.method = derivedOptions.method ? derivedOptions.method.toLowerCase() : "get";
404
- return {
405
- args: [url, options],
406
- url: normalizedUrl,
407
- queryParams: new URLSearchParams(getQuery(normalizedUrl)),
408
- options: derivedOptions,
409
- signal: derivedOptions.signal,
410
- pendingPromises
411
- };
412
- }
413
- if (typeof url === "object") throw new TypeError("fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs");
414
- else throw new TypeError("fetch-mock: Invalid arguments passed to fetch");
415
- }
416
- async function createCallLogFromRequest(request, options) {
417
- const pendingPromises = [];
418
- const derivedOptions = { method: request.method };
419
- try {
420
- try {
421
- derivedOptions.body = await request.clone().formData();
422
- } catch {
423
- derivedOptions.body = await request.clone().text();
424
- }
425
- } catch {}
426
- if (request.headers) derivedOptions.headers = normalizeHeaders(request.headers);
427
- const url = normalizeUrl(request.url, true);
428
- return {
429
- args: [request, options],
430
- url,
431
- queryParams: new URLSearchParams(getQuery(url)),
432
- options: Object.assign(derivedOptions, options || {}),
433
- request,
434
- signal: options && options.signal || request.signal,
435
- pendingPromises
436
- };
437
- }
438
- function getPath(url) {
439
- return (absoluteUrlRX.test(url) ? new URL(url) : new URL(url, "http://dummy")).pathname;
440
- }
441
- function getHost(url) {
442
- if (absoluteUrlRX.test(url)) return new URL(url).host;
443
- else if ("location" in globalThis) return globalThis.location.host;
444
- return null;
445
- }
446
- function getQuery(url) {
447
- const u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, "http://dummy");
448
- return u.search ? u.search.substr(1) : "";
449
- }
450
- function normalizeHeaders(headers) {
451
- let entries;
452
- if (headers instanceof Headers) entries = [...headers.entries()];
453
- else if (Array.isArray(headers)) entries = headers;
454
- else entries = Object.entries(headers);
455
- return Object.fromEntries(entries.map(([key, val]) => [key.toLowerCase(), String(val).valueOf()]));
456
- }
457
- //#endregion
458
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/Matchers.js
459
- const isUrlMatcher = (matcher) => matcher instanceof RegExp || typeof matcher === "string" || typeof matcher === "object" && "href" in matcher;
460
- const isFunctionMatcher = (matcher) => typeof matcher === "function";
461
- const stringMatchers = {
462
- begin: (targetString) => ({ url }) => url.startsWith(targetString),
463
- end: (targetString) => ({ url }) => url.endsWith(targetString),
464
- include: (targetString) => ({ url }) => url.includes(targetString),
465
- glob: (targetString) => {
466
- const urlRX = (0, import_glob_to_regexp.default)(targetString);
467
- return ({ url }) => urlRX.test(url);
468
- },
469
- express: (targetString) => {
470
- const urlRX = parse(targetString);
471
- return (callLog) => {
472
- const vals = urlRX.pattern.exec(getPath(callLog.url));
473
- if (!vals) {
474
- callLog.expressParams = {};
475
- return false;
476
- }
477
- vals.shift();
478
- callLog.expressParams = urlRX.keys.reduce((map, paramName, i) => vals[i] ? Object.assign(map, { [paramName]: vals[i] }) : map, {});
479
- return true;
480
- };
481
- },
482
- path: (targetString) => {
483
- const dotlessTargetString = getPath(targetString);
484
- return ({ url }) => {
485
- const path = getPath(url);
486
- return path === targetString || path === dotlessTargetString;
487
- };
488
- },
489
- host: (targetString) => {
490
- return ({ url }) => targetString === getHost(url);
491
- }
492
- };
493
- const getHeaderMatcher = ({ headers: expectedHeaders }) => {
494
- if (!expectedHeaders) return;
495
- const expectation = normalizeHeaders(expectedHeaders);
496
- return ({ options: { headers = {} } }) => {
497
- const lowerCaseHeaders = normalizeHeaders(headers);
498
- return Object.keys(expectation).every((headerName) => lowerCaseHeaders[headerName] === expectation[headerName]);
499
- };
500
- };
501
- const getMissingHeaderMatcher = ({ missingHeaders: expectedMissingHeaders }) => {
502
- if (!expectedMissingHeaders) return;
503
- const expectation = expectedMissingHeaders.map((header) => header.toLowerCase());
504
- return ({ options: { headers = {} } }) => {
505
- const lowerCaseHeaders = normalizeHeaders(headers);
506
- return expectation.every((headerName) => !(headerName in lowerCaseHeaders));
507
- };
508
- };
509
- const getMethodMatcher = ({ method: expectedMethod }) => {
510
- if (!expectedMethod) return;
511
- return ({ options: { method } = {} }) => {
512
- return expectedMethod === (method ? method.toLowerCase() : "get");
513
- };
514
- };
515
- const getQueryParamsMatcher = ({ query: passedQuery }) => {
516
- if (!passedQuery) return;
517
- const expectedQuery = new URLSearchParams();
518
- for (const [key, value] of Object.entries(passedQuery)) if (Array.isArray(value)) for (const item of value) expectedQuery.append(key, typeof item === "object" || typeof item === "undefined" ? "" : item.toString());
519
- else expectedQuery.append(key, typeof value === "object" || typeof value === "undefined" ? "" : value.toString());
520
- const keys = Array.from(expectedQuery.keys());
521
- return ({ queryParams }) => {
522
- return keys.every((key) => {
523
- const expectedValues = expectedQuery.getAll(key).sort();
524
- const actualValues = queryParams.getAll(key).sort();
525
- if (expectedValues.length !== actualValues.length) return false;
526
- if (Array.isArray(passedQuery[key])) return expectedValues.every((expected, index) => expected === actualValues[index]);
527
- return dequal(actualValues, expectedValues);
528
- });
529
- };
530
- };
531
- const getExpressParamsMatcher = ({ params: expectedParams, url }) => {
532
- if (!expectedParams) return;
533
- if (!(typeof url === "string" && /express:/.test(url))) throw new Error("fetch-mock: matching on params is only possible when using an express: matcher");
534
- const expectedKeys = Object.keys(expectedParams);
535
- return ({ expressParams = {} }) => {
536
- return expectedKeys.every((key) => expressParams[key] === expectedParams[key]);
537
- };
538
- };
539
- const formDataToObject = (formData) => {
540
- const fields = [...formData];
541
- const result = {};
542
- fields.forEach(([key, value]) => {
543
- result[key] = result[key] || [];
544
- result[key].push(value);
545
- });
546
- return result;
547
- };
548
- const getBodyMatcher = (route) => {
549
- let { body: expectedBody } = route;
550
- let expectedBodyType = "json";
551
- if (!expectedBody) return;
552
- if (expectedBody instanceof FormData) {
553
- expectedBodyType = "formData";
554
- expectedBody = formDataToObject(expectedBody);
555
- }
556
- return ({ options: { body, method = "get" } }) => {
557
- if (["get", "head"].includes(method.toLowerCase())) return false;
558
- let sentBody;
559
- try {
560
- if (typeof body === "string") {
561
- sentBody = JSON.parse(body);
562
- if (expectedBodyType !== "json") return false;
563
- }
564
- } catch {}
565
- if (body instanceof FormData) {
566
- if (expectedBodyType !== "formData") return false;
567
- sentBody = formDataToObject(body);
568
- }
569
- return sentBody && (route.matchPartialBody ? isSubsetOf(expectedBody, sentBody) : dequal(expectedBody, sentBody));
570
- };
571
- };
572
- const getFunctionMatcher = ({ matcherFunction }) => matcherFunction;
573
- const getRegexpMatcher = (regexp) => ({ url }) => regexp.test(url);
574
- const getFullUrlMatcher = (route, matcherUrl, query) => {
575
- const expectedUrl = normalizeUrl(matcherUrl, route.allowRelativeUrls);
576
- if (route.url === matcherUrl) route.url = expectedUrl;
577
- return ({ url }) => {
578
- if (query && expectedUrl.indexOf("?")) return getPath(url) === getPath(expectedUrl);
579
- return normalizeUrl(url, true) === expectedUrl;
580
- };
581
- };
582
- const getUrlMatcher = (route) => {
583
- const { url: matcherUrl, query } = route;
584
- if (matcherUrl === "*") return () => true;
585
- if (matcherUrl instanceof RegExp) return getRegexpMatcher(matcherUrl);
586
- if (matcherUrl instanceof URL) {
587
- if (matcherUrl.href) return getFullUrlMatcher(route, matcherUrl.href, query);
588
- }
589
- if (typeof matcherUrl === "string") {
590
- for (const shorthand in stringMatchers) if (matcherUrl.indexOf(`${shorthand}:`) === 0) {
591
- const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), "");
592
- return stringMatchers[shorthand](urlFragment);
593
- }
594
- return getFullUrlMatcher(route, matcherUrl, query);
595
- }
596
- if (typeof matcherUrl === "object") {
597
- const matchers = Object.entries(matcherUrl).map(([key, pattern]) => {
598
- if (key === "regexp") return getRegexpMatcher(pattern);
599
- else if (key in stringMatchers) return stringMatchers[key](pattern);
600
- else throw new Error(`unrecognised url matching pattern: ${key}`);
601
- });
602
- return (route) => matchers.every((matcher) => matcher(route));
603
- }
604
- };
605
- const builtInMatchers = [
606
- {
607
- name: "url",
608
- matcher: getUrlMatcher
609
- },
610
- {
611
- name: "query",
612
- matcher: getQueryParamsMatcher
613
- },
614
- {
615
- name: "method",
616
- matcher: getMethodMatcher
617
- },
618
- {
619
- name: "headers",
620
- matcher: getHeaderMatcher
621
- },
622
- {
623
- name: "missingHeaders",
624
- matcher: getMissingHeaderMatcher
625
- },
626
- {
627
- name: "params",
628
- matcher: getExpressParamsMatcher
629
- },
630
- {
631
- name: "body",
632
- matcher: getBodyMatcher,
633
- usesBody: true
634
- },
635
- {
636
- name: "matcherFunction",
637
- matcher: getFunctionMatcher
638
- }
639
- ];
640
- //#endregion
641
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/StatusTextMap.js
642
- const statusTextMap = {
643
- 100: "Continue",
644
- 101: "Switching Protocols",
645
- 102: "Processing",
646
- 200: "OK",
647
- 201: "Created",
648
- 202: "Accepted",
649
- 203: "Non-Authoritative Information",
650
- 204: "No Content",
651
- 205: "Reset Content",
652
- 206: "Partial Content",
653
- 207: "Multi-Status",
654
- 208: "Already Reported",
655
- 226: "IM Used",
656
- 300: "Multiple Choices",
657
- 301: "Moved Permanently",
658
- 302: "Found",
659
- 303: "See Other",
660
- 304: "Not Modified",
661
- 305: "Use Proxy",
662
- 307: "Temporary Redirect",
663
- 308: "Permanent Redirect",
664
- 400: "Bad Request",
665
- 401: "Unauthorized",
666
- 402: "Payment Required",
667
- 403: "Forbidden",
668
- 404: "Not Found",
669
- 405: "Method Not Allowed",
670
- 406: "Not Acceptable",
671
- 407: "Proxy Authentication Required",
672
- 408: "Request Timeout",
673
- 409: "Conflict",
674
- 410: "Gone",
675
- 411: "Length Required",
676
- 412: "Precondition Failed",
677
- 413: "Payload Too Large",
678
- 414: "URI Too Long",
679
- 415: "Unsupported Media Type",
680
- 416: "Range Not Satisfiable",
681
- 417: "Expectation Failed",
682
- 418: "I'm a teapot",
683
- 421: "Misdirected Request",
684
- 422: "Unprocessable Entity",
685
- 423: "Locked",
686
- 424: "Failed Dependency",
687
- 425: "Unordered Collection",
688
- 426: "Upgrade Required",
689
- 428: "Precondition Required",
690
- 429: "Too Many Requests",
691
- 431: "Request Header Fields Too Large",
692
- 451: "Unavailable For Legal Reasons",
693
- 500: "Internal Server Error",
694
- 501: "Not Implemented",
695
- 502: "Bad Gateway",
696
- 503: "Service Unavailable",
697
- 504: "Gateway Timeout",
698
- 505: "HTTP Version Not Supported",
699
- 506: "Variant Also Negotiates",
700
- 507: "Insufficient Storage",
701
- 508: "Loop Detected",
702
- 509: "Bandwidth Limit Exceeded",
703
- 510: "Not Extended",
704
- 511: "Network Authentication Required"
705
- };
706
- //#endregion
707
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/Route.js
708
- var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
709
- if (kind === "m") throw new TypeError("Private method is not writable");
710
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
711
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
712
- return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
713
- };
714
- var __classPrivateFieldGet = function(receiver, state, kind, f) {
715
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
716
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
717
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
718
- };
719
- var _Route_instances;
720
- var _a;
721
- var _Route_responseSubscriptions;
722
- var _Route_validate;
723
- var _Route_sanitize;
724
- var _Route_generateMatcher;
725
- var _Route_limit;
726
- var _Route_delayResponse;
727
- var RouteConfigWrapper = class {
728
- constructor(config) {
729
- Object.assign(this, config);
730
- }
731
- };
732
- function isBodyInit(body) {
733
- return body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof DataView || body instanceof FormData || body instanceof ReadableStream || body instanceof URLSearchParams || body instanceof String || typeof body === "string" || body === null;
734
- }
735
- function sanitizeStatus(status) {
736
- if (status === 0) return 200;
737
- if (!status) return 200;
738
- if (typeof status === "number" && parseInt(String(status), 10) !== status && status >= 200 || status < 600) return status;
739
- throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object.
740
- To respond with a JSON object that has status as a property assign the object to body
741
- e.g. {"body": {"status: "registered"}}`);
742
- }
743
- var Route = class {
744
- constructor(config) {
745
- _Route_instances.add(this);
746
- _Route_responseSubscriptions.set(this, void 0);
747
- this.init(config);
748
- }
749
- init(config) {
750
- this.config = config;
751
- __classPrivateFieldSet(this, _Route_responseSubscriptions, [], "f");
752
- __classPrivateFieldGet(this, _Route_instances, "m", _Route_sanitize).call(this);
753
- __classPrivateFieldGet(this, _Route_instances, "m", _Route_validate).call(this);
754
- __classPrivateFieldGet(this, _Route_instances, "m", _Route_generateMatcher).call(this);
755
- __classPrivateFieldGet(this, _Route_instances, "m", _Route_limit).call(this);
756
- __classPrivateFieldGet(this, _Route_instances, "m", _Route_delayResponse).call(this);
757
- }
758
- reset() {}
759
- waitFor(awaitedRoutes) {
760
- const { response } = this.config;
761
- this.config.response = Promise.all(awaitedRoutes.map((awaitedRoute) => new Promise((res) => awaitedRoute.onRespond(() => {
762
- res(void 0);
763
- })))).then(() => response);
764
- }
765
- onRespond(func) {
766
- __classPrivateFieldGet(this, _Route_responseSubscriptions, "f").push(func);
767
- }
768
- constructResponse(responseInput) {
769
- const responseOptions = this.constructResponseOptions(responseInput);
770
- const body = this.constructResponseBody(responseInput, responseOptions);
771
- const responsePackage = {
772
- response: new this.config.Response(body, responseOptions),
773
- responseOptions,
774
- responseInput
775
- };
776
- __classPrivateFieldGet(this, _Route_responseSubscriptions, "f").forEach((func) => func());
777
- return responsePackage;
778
- }
779
- constructResponseOptions(responseInput) {
780
- const options = responseInput.options || {};
781
- options.status = sanitizeStatus(responseInput.status);
782
- options.statusText = statusTextMap[options.status];
783
- options.headers = new this.config.Headers(responseInput.headers);
784
- return options;
785
- }
786
- constructResponseBody(responseInput, responseOptions) {
787
- let body = responseInput.body;
788
- if (!isBodyInit(body)) if (typeof body === "undefined") body = null;
789
- else if (typeof body === "object") {
790
- body = JSON.stringify(body);
791
- if (!responseOptions.headers.has("Content-Type")) responseOptions.headers.set("Content-Type", "application/json");
792
- } else throw new TypeError("Invalid body provided to construct response");
793
- if (this.config.includeContentLength && !responseOptions.headers.has("Content-Length") && !(body instanceof ReadableStream) && !(body instanceof FormData)) {
794
- let length = 0;
795
- if (body instanceof Blob) length = body.size;
796
- else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof DataView) length = body.byteLength;
797
- else if (body instanceof URLSearchParams) length = body.toString().length;
798
- else if (typeof body === "string" || body instanceof String) length = body.length;
799
- responseOptions.headers.set("Content-Length", length.toString());
800
- }
801
- return body;
802
- }
803
- static defineMatcher(matcher) {
804
- _a.registeredMatchers.push(matcher);
805
- }
806
- };
807
- _a = Route, _Route_responseSubscriptions = /* @__PURE__ */ new WeakMap(), _Route_instances = /* @__PURE__ */ new WeakSet(), _Route_validate = function _Route_validate() {
808
- if (["matched", "unmatched"].includes(this.config.name)) throw new Error(`fetch-mock: Routes cannot use the reserved name \`${this.config.name}\``);
809
- if (!("response" in this.config)) throw new Error("fetch-mock: Each route must define a response");
810
- if (!_a.registeredMatchers.some(({ name }) => name in this.config)) throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'");
811
- }, _Route_sanitize = function _Route_sanitize() {
812
- if (this.config.method) this.config.method = this.config.method.toLowerCase();
813
- }, _Route_generateMatcher = function _Route_generateMatcher() {
814
- const activeMatchers = _a.registeredMatchers.filter(({ name }) => name in this.config).map(({ matcher, usesBody }) => ({
815
- matcher: matcher(this.config),
816
- usesBody
817
- }));
818
- this.config.usesBody = activeMatchers.some(({ usesBody }) => usesBody);
819
- this.matcher = (normalizedRequest) => activeMatchers.every(({ matcher }) => matcher(normalizedRequest));
820
- }, _Route_limit = function _Route_limit() {
821
- if (!this.config.repeat) return;
822
- const originalMatcher = this.matcher;
823
- let timesLeft = this.config.repeat;
824
- this.matcher = (callLog) => {
825
- if (timesLeft && originalMatcher(callLog)) {
826
- timesLeft--;
827
- return true;
828
- }
829
- };
830
- this.reset = () => {
831
- timesLeft = this.config.repeat;
832
- };
833
- }, _Route_delayResponse = function _Route_delayResponse() {
834
- if (this.config.delay) {
835
- const { response } = this.config;
836
- this.config.response = () => {
837
- return new Promise((res) => setTimeout(() => res(response), this.config.delay));
838
- };
839
- }
840
- };
841
- Route.registeredMatchers = [];
842
- builtInMatchers.forEach(Route.defineMatcher);
843
- //#endregion
844
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/Router.js
845
- const responseConfigProps = [
846
- "body",
847
- "headers",
848
- "throws",
849
- "status",
850
- "redirectUrl"
851
- ];
852
- function nameToOptions(options) {
853
- return typeof options === "string" ? { name: options } : options;
854
- }
855
- function isPromise(response) {
856
- return typeof response.then === "function";
857
- }
858
- function normalizeResponseInput(responseInput) {
859
- if (typeof responseInput === "number") return { status: responseInput };
860
- else if (typeof responseInput === "string" || shouldSendAsObject(responseInput)) return { body: responseInput };
861
- return responseInput;
862
- }
863
- function shouldSendAsObject(responseInput) {
864
- if (responseConfigProps.some((prop) => prop in responseInput)) {
865
- if (Object.keys(responseInput).every((key) => responseConfigProps.includes(key))) return false;
866
- return true;
867
- }
868
- return true;
869
- }
870
- function throwSpecExceptions({ url, options: { headers, method, body } }) {
871
- if (headers) Object.entries(headers).forEach(([key]) => {
872
- if (/\s/.test(key)) throw new TypeError("Invalid name");
873
- });
874
- if (hasCredentialsInUrl(url)) throw new TypeError(`Request cannot be constructed from a URL that includes credentials: ${url}`);
875
- if (["get", "head"].includes(method) && body) throw new TypeError("Request with GET/HEAD method cannot have body.");
876
- }
877
- const resolveUntilResponseConfig = async (callLog) => {
878
- let response = callLog.route.config.response;
879
- while (true) if (typeof response === "function") response = response(callLog);
880
- else if (isPromise(response)) response = await response;
881
- else return response;
882
- };
883
- var Router = class {
884
- constructor(fetchMockConfig, { routes, fallbackRoute } = {}) {
885
- this.config = fetchMockConfig;
886
- this.routes = routes || [];
887
- this.fallbackRoute = fallbackRoute;
888
- }
889
- needsToReadBody(request) {
890
- return Boolean(request && this.routes.some((route) => route.config.usesBody));
891
- }
892
- execute(callLog) {
893
- throwSpecExceptions(callLog);
894
- return new Promise(async (resolve, reject) => {
895
- const { url, options, request, pendingPromises } = callLog;
896
- let eventListenerAbortController;
897
- if (callLog.signal) {
898
- const abort = () => {
899
- const error = new DOMException("The operation was aborted.", "AbortError");
900
- const requestBody = request?.body || options?.body;
901
- if (requestBody instanceof ReadableStream) if (requestBody.locked) console.warn("fetch-mock: Locked request body can't be cancelled");
902
- else requestBody.cancel(error);
903
- if (callLog?.response?.body) if (callLog.response.body.locked) console.warn("fetch-mock: Locked response body can't be cancelled");
904
- else callLog.response.body.cancel(error);
905
- reject(error);
906
- };
907
- if (callLog.signal.aborted) abort();
908
- eventListenerAbortController = new AbortController();
909
- callLog.signal.addEventListener("abort", abort, {
910
- once: true,
911
- signal: eventListenerAbortController.signal
912
- });
913
- }
914
- if (this.needsToReadBody(request)) options.body = await options.body;
915
- const route = (this.fallbackRoute ? [...this.routes, this.fallbackRoute] : this.routes).find((route) => route.matcher(callLog));
916
- if (route) try {
917
- callLog.route = route;
918
- const { response, responseOptions, responseInput } = await this.generateResponse(callLog);
919
- const observableResponse = this.createObservableResponse(response, responseOptions, responseInput, url, pendingPromises);
920
- callLog.response = response;
921
- resolve(observableResponse);
922
- } catch (err) {
923
- reject(err);
924
- } finally {
925
- eventListenerAbortController?.abort();
926
- }
927
- else reject(/* @__PURE__ */ new Error(`fetch-mock: No response or fallback rule to cover ${options && options.method || "GET"} to ${url}`));
928
- });
929
- }
930
- async generateResponse(callLog) {
931
- const responseInput = await resolveUntilResponseConfig(callLog);
932
- if (responseInput instanceof Response) return {
933
- response: responseInput.clone(),
934
- responseOptions: {},
935
- responseInput: {}
936
- };
937
- const responseConfig = normalizeResponseInput(responseInput);
938
- if (responseConfig.throws) throw responseConfig.throws;
939
- return callLog.route.constructResponse(responseConfig);
940
- }
941
- createObservableResponse(response, responseConfig, responseInput, responseUrl, pendingPromises) {
942
- return new Proxy(response, { get: (originalResponse, name) => {
943
- if (responseInput.redirectUrl) {
944
- if (name === "url") return responseInput.redirectUrl;
945
- if (name === "redirected") return true;
946
- } else {
947
- if (name === "url") return responseUrl;
948
- if (name === "redirected") return false;
949
- }
950
- if (responseInput.status === 0) {
951
- if (name === "status") return 0;
952
- if (name === "statusText") return "";
953
- }
954
- if (typeof response[name] === "function") return new Proxy(response[name], { apply: (func, thisArg, args) => {
955
- const result = func.apply(response, args);
956
- if (result.then) pendingPromises.push(result.catch(() => void 0));
957
- return result;
958
- } });
959
- return originalResponse[name];
960
- } });
961
- }
962
- addRoute(matcher, response, nameOrOptions) {
963
- const config = {};
964
- if (matcher instanceof RouteConfigWrapper) Object.assign(config, matcher);
965
- if (isUrlMatcher(matcher)) config.url = matcher;
966
- else if (isFunctionMatcher(matcher)) config.matcherFunction = matcher;
967
- else Object.assign(config, matcher);
968
- if (typeof response !== "undefined") config.response = response;
969
- if (nameOrOptions) Object.assign(config, typeof nameOrOptions === "string" ? nameToOptions(nameOrOptions) : nameOrOptions);
970
- const route = new Route({
971
- ...this.config,
972
- ...config
973
- });
974
- if (route.config.name && this.routes.some(({ config: { name: existingName } }) => route.config.name === existingName)) throw new Error("fetch-mock: Adding route with same name as existing route.");
975
- if (route.config.waitFor) {
976
- const routeNamesToWaitFor = Array.isArray(route.config.waitFor) ? route.config.waitFor : [route.config.waitFor];
977
- const routesToAwait = [];
978
- routeNamesToWaitFor.forEach((routeName) => {
979
- const routeToAwait = this.routes.find(({ config: { name: existingName } }) => routeName === existingName);
980
- if (routeToAwait) routesToAwait.push(routeToAwait);
981
- else throw new Error(`Cannot wait for route \`${routeName}\`: route of that name does not exist`);
982
- });
983
- route.waitFor(routesToAwait);
984
- }
985
- this.routes.push(route);
986
- }
987
- setFallback(response) {
988
- if (this.fallbackRoute) console.warn("calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response");
989
- this.fallbackRoute = new Route({
990
- matcherFunction: () => true,
991
- response: response || "ok",
992
- ...this.config
993
- });
994
- this.fallbackRoute.config.isFallback = true;
995
- }
996
- removeRoutes({ names, includeSticky, includeFallback } = {}) {
997
- includeFallback = includeFallback ?? true;
998
- this.routes = this.routes.filter(({ config: { sticky, name } }) => {
999
- if (sticky && !includeSticky) return true;
1000
- if (!names) return false;
1001
- return !names.includes(name);
1002
- });
1003
- if (includeFallback) delete this.fallbackRoute;
1004
- }
1005
- modifyRoute(routeName, options) {
1006
- const route = this.routes.find(({ config: { name } }) => name === routeName);
1007
- if (!route) throw new Error(`Cannot call modifyRoute() on route \`${routeName}\`: route of that name not found`);
1008
- if (route.config.sticky) throw new Error(`Cannot call modifyRoute() on route \`${routeName}\`: route is sticky and cannot be modified`);
1009
- if ("name" in options) throw new Error(`Cannot rename the route \`${routeName}\` as \`${options.name}\`: renaming routes is not supported`);
1010
- if ("sticky" in options) throw new Error(`Altering the stickiness of route \`${routeName}\` is not supported`);
1011
- const newConfig = {
1012
- ...route.config,
1013
- ...options
1014
- };
1015
- Object.entries(options).forEach(([key, value]) => {
1016
- if (value === null) delete newConfig[key];
1017
- });
1018
- route.init(newConfig);
1019
- }
1020
- };
1021
- //#endregion
1022
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/CallHistory.js
1023
- const isName = (filter) => typeof filter === "string" && /^[\da-zA-Z-]+$/.test(filter) && !["matched", "unmatched"].includes(filter);
1024
- const isMatchedOrUnmatched = (filter) => typeof filter === "boolean" || ["matched", "unmatched"].includes(filter);
1025
- var CallHistory = class {
1026
- constructor(config, router) {
1027
- this.callLogs = [];
1028
- this.config = config;
1029
- this.router = router;
1030
- }
1031
- recordCall(callLog) {
1032
- this.callLogs.push(callLog);
1033
- }
1034
- clear() {
1035
- this.callLogs.forEach(({ route }) => {
1036
- if (route) route.reset();
1037
- });
1038
- this.callLogs = [];
1039
- }
1040
- async flush(waitForResponseMethods) {
1041
- const queuedPromises = this.callLogs.flatMap((call) => call.pendingPromises);
1042
- await Promise.allSettled(queuedPromises);
1043
- if (waitForResponseMethods) {
1044
- await Promise.resolve();
1045
- await this.flush();
1046
- }
1047
- }
1048
- calls(filter, options) {
1049
- let calls = [...this.callLogs];
1050
- if (typeof filter === "undefined" && !options) return calls;
1051
- if (isMatchedOrUnmatched(filter)) {
1052
- if ([true, "matched"].includes(filter)) calls = calls.filter(({ route }) => !route?.config || !route.config.isFallback);
1053
- else if ([false, "unmatched"].includes(filter)) calls = calls.filter(({ route }) => Boolean(route?.config && route.config.isFallback));
1054
- if (!options) return calls;
1055
- } else if (isName(filter)) {
1056
- calls = calls.filter(({ route }) => route?.config?.name === filter);
1057
- if (!options) return calls;
1058
- } else if (isUrlMatcher(filter)) options = {
1059
- url: filter,
1060
- ...options || {}
1061
- };
1062
- else options = {
1063
- ...filter,
1064
- ...options || {}
1065
- };
1066
- const { matcher } = new Route({
1067
- response: "ok",
1068
- ...options
1069
- });
1070
- calls = calls.filter(({ url, options }) => {
1071
- return matcher(createCallLogFromUrlAndOptions(url, options));
1072
- });
1073
- return calls;
1074
- }
1075
- called(filter, options) {
1076
- return Boolean(this.calls(filter, options).length);
1077
- }
1078
- lastCall(filter, options) {
1079
- return this.calls(filter, options).pop();
1080
- }
1081
- done(routeNames) {
1082
- let routesToCheck = this.router.routes;
1083
- if (routeNames) {
1084
- routeNames = Array.isArray(routeNames) ? routeNames : [routeNames];
1085
- routesToCheck = this.router.routes.filter(({ config: { name } }) => routeNames.includes(name));
1086
- }
1087
- return routesToCheck.map((route) => {
1088
- const calls = this.callLogs.filter(({ route: routeApplied }) => routeApplied === route);
1089
- if (!calls.length) {
1090
- console.warn(`Warning: ${route.config.name} not called`);
1091
- return false;
1092
- }
1093
- const expectedTimes = route.config.repeat;
1094
- if (!expectedTimes) return true;
1095
- const actualTimes = calls.length;
1096
- if (expectedTimes > actualTimes) {
1097
- console.warn(`Warning: ${route.config.name} only called ${actualTimes} times, but ${expectedTimes} expected`);
1098
- return false;
1099
- }
1100
- return true;
1101
- }).every((isDone) => isDone);
1102
- }
1103
- };
1104
- //#endregion
1105
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/FetchMock.js
1106
- const defaultFetchMockConfig = {
1107
- includeContentLength: true,
1108
- matchPartialBody: false,
1109
- Request: globalThis.Request,
1110
- Response: globalThis.Response,
1111
- Headers: globalThis.Headers,
1112
- fetch: globalThis.fetch
1113
- };
1114
- const defineShorthand = (shorthandOptions) => {
1115
- function shorthand(matcher, response, options) {
1116
- return this.route(matcher, response, Object.assign(options || {}, shorthandOptions));
1117
- }
1118
- return shorthand;
1119
- };
1120
- const defineGreedyShorthand = (shorthandOptions) => {
1121
- return function(response, options) {
1122
- return this.route("*", response, Object.assign(options || {}, shorthandOptions));
1123
- };
1124
- };
1125
- //#endregion
1126
- //#region ../../node_modules/.pnpm/fetch-mock@12.6.0/node_modules/fetch-mock/dist/esm/index.js
1127
- var esm_default = new class FetchMock {
1128
- constructor(config, router) {
1129
- this.sticky = defineShorthand({ sticky: true });
1130
- this.once = defineShorthand({ repeat: 1 });
1131
- this.any = defineGreedyShorthand({});
1132
- this.anyOnce = defineGreedyShorthand({ repeat: 1 });
1133
- this.get = defineShorthand({ method: "get" });
1134
- this.getOnce = defineShorthand({
1135
- method: "get",
1136
- repeat: 1
1137
- });
1138
- this.post = defineShorthand({ method: "post" });
1139
- this.postOnce = defineShorthand({
1140
- method: "post",
1141
- repeat: 1
1142
- });
1143
- this.put = defineShorthand({ method: "put" });
1144
- this.putOnce = defineShorthand({
1145
- method: "put",
1146
- repeat: 1
1147
- });
1148
- this.delete = defineShorthand({ method: "delete" });
1149
- this.deleteOnce = defineShorthand({
1150
- method: "delete",
1151
- repeat: 1
1152
- });
1153
- this.head = defineShorthand({ method: "head" });
1154
- this.headOnce = defineShorthand({
1155
- method: "head",
1156
- repeat: 1
1157
- });
1158
- this.patch = defineShorthand({ method: "patch" });
1159
- this.patchOnce = defineShorthand({
1160
- method: "patch",
1161
- repeat: 1
1162
- });
1163
- this.config = config;
1164
- this.router = new Router(this.config, {
1165
- routes: router ? [...router.routes] : [],
1166
- fallbackRoute: router ? router.fallbackRoute : null
1167
- });
1168
- this.callHistory = new CallHistory(this.config, this.router);
1169
- this.fetchHandler = this.fetchHandler.bind(this);
1170
- Object.assign(this.fetchHandler, { fetchMock: this });
1171
- }
1172
- createInstance() {
1173
- return new FetchMock({ ...this.config }, this.router);
1174
- }
1175
- async fetchHandler(requestInput, requestInit) {
1176
- let callLog;
1177
- if (requestInput instanceof this.config.Request) callLog = await createCallLogFromRequest(requestInput, requestInit);
1178
- else callLog = createCallLogFromUrlAndOptions(requestInput, requestInit);
1179
- this.callHistory.recordCall(callLog);
1180
- const responsePromise = this.router.execute(callLog);
1181
- callLog.pendingPromises.push(responsePromise);
1182
- return responsePromise;
1183
- }
1184
- route(matcher, response, options) {
1185
- this.router.addRoute(matcher, response, options);
1186
- return this;
1187
- }
1188
- catch(response) {
1189
- this.router.setFallback(response);
1190
- return this;
1191
- }
1192
- defineMatcher(matcher) {
1193
- Route.defineMatcher(matcher);
1194
- }
1195
- removeRoutes(options) {
1196
- this.router.removeRoutes(options);
1197
- return this;
1198
- }
1199
- removeRoute(routeName) {
1200
- this.router.removeRoutes({ names: [routeName] });
1201
- return this;
1202
- }
1203
- modifyRoute(routeName, options) {
1204
- this.router.modifyRoute(routeName, options);
1205
- return this;
1206
- }
1207
- clearHistory() {
1208
- this.callHistory.clear();
1209
- return this;
1210
- }
1211
- mockGlobal() {
1212
- globalThis.fetch = this.fetchHandler;
1213
- return this;
1214
- }
1215
- unmockGlobal() {
1216
- globalThis.fetch = this.config.fetch;
1217
- return this;
1218
- }
1219
- hardReset(options) {
1220
- this.clearHistory();
1221
- this.removeRoutes(options);
1222
- this.unmockGlobal();
1223
- return this;
1224
- }
1225
- spy(matcher, name) {
1226
- const boundFetch = this.config.fetch.bind(globalThis);
1227
- if (matcher) this.route(matcher, ({ args }) => boundFetch(...args), name);
1228
- else this.catch(({ args }) => boundFetch(...args));
1229
- return this;
1230
- }
1231
- spyGlobal() {
1232
- this.mockGlobal();
1233
- return this.spy();
1234
- }
1235
- }({ ...defaultFetchMockConfig });
1236
- //#endregion
1237
- //#region deno.json
1238
- var name = "@fedify/webfinger";
1239
- var version = "2.5.0-dev.2664+4790a72e";
1240
- //#endregion
1241
- //#region src/body.ts
1242
- /** Decoded JSON body limit: 16 MiB. @internal */
1243
- const MAX_BODY_SIZE = 16 * 1024 * 1024;
1244
- /** A body exceeded the byte limit. @internal */
1245
- var BodyTooLargeError = class extends FetchError {
1246
- /** Creates an error for a body exceeding the given limit. */
1247
- constructor(url, maxBytes) {
1248
- super(url, `Body exceeds the limit of ${maxBytes} bytes`);
1249
- this.name = "BodyTooLargeError";
1250
- }
1251
- };
1252
- /** Validates a finite, positive byte limit. @internal */
1253
- function validateBodySizeLimit(maxBytes) {
1254
- if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("The body size limit must be a positive safe integer.");
1255
- }
1256
- /**
1257
- * Reads UTF-8 text while limiting bytes received from the body stream.
1258
- * Fetch responses are already decompressed, so the stream count is authoritative.
1259
- * @param message The response or request to read.
1260
- * @param maxBytes The maximum number of decoded bytes to read.
1261
- * @param url The URL to include in errors and logs.
1262
- * @returns The decoded body text.
1263
- * @throws {BodyTooLargeError} If the body exceeds the limit.
1264
- * @internal
1265
- */
1266
- async function readBoundedText(message, maxBytes, url) {
1267
- validateBodySizeLimit(maxBytes);
1268
- const reader = message.body?.getReader();
1269
- const tooLarge = () => {
1270
- getLogger([
1271
- "fedify",
1272
- "runtime",
1273
- "body"
1274
- ]).warn("Body from {url} exceeds the limit of {maxBytes} bytes.", {
1275
- url: url.toString(),
1276
- maxBytes
1277
- });
1278
- throw new BodyTooLargeError(url, maxBytes);
1279
- };
1280
- try {
1281
- const length = message.headers.get("Content-Length");
1282
- const encoding = message.headers.get("Content-Encoding");
1283
- if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
1284
- if (reader == null) return "";
1285
- let size = 0;
1286
- const textReader = new ReadableStream({ async pull(controller) {
1287
- const { done, value } = await reader.read();
1288
- if (done) {
1289
- controller.close();
1290
- return;
1291
- }
1292
- size += value.byteLength;
1293
- if (size > maxBytes) tooLarge();
1294
- controller.enqueue(value);
1295
- } }, { highWaterMark: 0 }).pipeThrough(new TextDecoderStream()).getReader();
1296
- try {
1297
- const chunks = [];
1298
- while (true) {
1299
- const { done, value } = await textReader.read();
1300
- if (done) break;
1301
- chunks.push(value);
1302
- }
1303
- return chunks.join("");
1304
- } finally {
1305
- textReader.releaseLock();
1306
- }
1307
- } catch (error) {
1308
- if (reader != null) reader.cancel(error).catch(() => {});
1309
- throw error;
1310
- } finally {
1311
- reader?.releaseLock();
1312
- }
1313
- }
1314
- //#endregion
1315
- //#region src/lookup-impl.ts
1316
- const logger = getLogger([
1317
- "fedify",
1318
- "webfinger",
1319
- "lookup"
1320
- ]);
1321
- const DEFAULT_MAX_REDIRECTION = 5;
1322
- /**
1323
- * Looks up a WebFinger resource, opening a fetch session per hop. This is
1324
- * the implementation of {@link lookupWebFinger}, which is not exported from
1325
- * the package entry point.
1326
- * @param resource The resource URL to look up.
1327
- * @param options Extra options for looking up the resource.
1328
- * @param deps The dependencies.
1329
- * @returns The resource descriptor and terminal lookup classification.
1330
- * @internal
1331
- */
1332
- async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1333
- if (typeof resource === "string") resource = new URL(resource);
1334
- let protocol = "https:";
1335
- let server;
1336
- if (resource.protocol === "acct:" || resource.protocol === "mailto:") {
1337
- const atPos = resource.pathname.lastIndexOf("@");
1338
- if (atPos < 0) return {
1339
- resource: null,
1340
- result: "invalid"
1341
- };
1342
- server = resource.pathname.substring(atPos + 1);
1343
- if (server === "" || /[/?#]/.test(server)) return {
1344
- resource: null,
1345
- result: "invalid"
1346
- };
1347
- if (resource.protocol === "acct:" && (resource.search !== "" || resource.hash !== "")) return {
1348
- resource: null,
1349
- result: "invalid"
1350
- };
1351
- } else {
1352
- protocol = resource.protocol;
1353
- server = resource.host;
1354
- }
1355
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1356
- url.searchParams.set("resource", resource.href);
1357
- const openHop = deps.openHop ?? ((hopUrl) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: options.signal }));
1358
- let redirected = 0;
1359
- while (true) {
1360
- logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
1361
- const remoteHost = url.host;
1362
- const session = await openSession(url, openHop, options.signal);
1363
- if (session == null) return {
1364
- resource: null,
1365
- result: "network_error",
1366
- remoteHost
1367
- };
1368
- let hop;
1369
- try {
1370
- hop = await fetchHop(session, url, options);
1371
- } finally {
1372
- await session.close();
1373
- }
1374
- if ("outcome" in hop) return hop.outcome;
1375
- redirected++;
1376
- const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
1377
- if (redirected > maxRedirection) {
1378
- logger.error("Too many redirections ({redirections}) while fetching WebFinger resource descriptor.", { redirections: redirected });
1379
- return {
1380
- resource: null,
1381
- result: "invalid",
1382
- statusCode: hop.statusCode,
1383
- remoteHost
1384
- };
1385
- }
1386
- let redirectedUrl;
1387
- try {
1388
- redirectedUrl = new URL(hop.redirect, url);
1389
- } catch (error) {
1390
- logger.error("Invalid Location header while following WebFinger redirect: {error}", {
1391
- url: url.href,
1392
- error
1393
- });
1394
- return {
1395
- resource: null,
1396
- result: "invalid",
1397
- statusCode: hop.statusCode,
1398
- remoteHost
1399
- };
1400
- }
1401
- if (redirectedUrl.protocol !== url.protocol) {
1402
- logger.error("Redirected to a different protocol ({protocol} to {redirectedProtocol}) while fetching WebFinger resource descriptor.", {
1403
- protocol: url.protocol,
1404
- redirectedProtocol: redirectedUrl.protocol
1405
- });
1406
- return {
1407
- resource: null,
1408
- result: "invalid",
1409
- statusCode: hop.statusCode,
1410
- remoteHost
1411
- };
1412
- }
1413
- url = redirectedUrl;
1414
- }
1415
- }
1416
- /**
1417
- * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
1418
- * or an aborted lookup yields `null` instead of an error.
1419
- */
1420
- async function openSession(url, openHop, signal) {
1421
- try {
1422
- return await openHop(url.href);
1423
- } catch (e) {
1424
- if (e instanceof UrlError) {
1425
- if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
1426
- url: url.href,
1427
- error: e
1428
- });
1429
- else logger.error("Invalid URL for WebFinger resource descriptor: {error}", { error: e });
1430
- return null;
1431
- }
1432
- if (signal?.aborted) {
1433
- logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
1434
- url: url.href,
1435
- error: e
1436
- });
1437
- return null;
1438
- }
1439
- throw e;
1440
- }
1441
- }
1442
- /**
1443
- * Fetches a hop with the given session, and consumes the response body or
1444
- * starts cancelling it before returning. The caller closes the session.
1445
- */
1446
- async function fetchHop(session, url, options) {
1447
- let response;
1448
- try {
1449
- response = await session.fetch(url, {
1450
- headers: {
1451
- Accept: "application/jrd+json",
1452
- "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
1453
- },
1454
- redirect: "manual",
1455
- signal: options.signal
1456
- });
1457
- } catch (error) {
1458
- logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
1459
- url: url.href,
1460
- error
1461
- });
1462
- return { outcome: {
1463
- resource: null,
1464
- result: "network_error",
1465
- remoteHost: url.host
1466
- } };
1467
- }
1468
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
1469
- cancelBody(response, url);
1470
- return {
1471
- redirect: response.headers.get("Location"),
1472
- statusCode: response.status
1473
- };
1474
- }
1475
- if (!response.ok) {
1476
- logger.debug("Failed to fetch WebFinger resource descriptor: {status} {statusText}.", {
1477
- url: url.href,
1478
- status: response.status,
1479
- statusText: response.statusText
1480
- });
1481
- cancelBody(response, url);
1482
- return { outcome: {
1483
- resource: null,
1484
- result: response.status === 404 || response.status === 410 ? "not_found" : "error",
1485
- statusCode: response.status,
1486
- remoteHost: url.host
1487
- } };
1488
- }
1489
- try {
1490
- const parsed = JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url));
1491
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { outcome: {
1492
- resource: null,
1493
- result: "invalid",
1494
- statusCode: response.status,
1495
- remoteHost: url.host
1496
- } };
1497
- return { outcome: {
1498
- resource: parsed,
1499
- result: "found",
1500
- statusCode: response.status,
1501
- remoteHost: url.host
1502
- } };
1503
- } catch (e) {
1504
- if (e instanceof BodyTooLargeError) return { outcome: {
1505
- resource: null,
1506
- result: "invalid",
1507
- statusCode: response.status,
1508
- remoteHost: url.host
1509
- } };
1510
- if (e instanceof SyntaxError) {
1511
- logger.debug("Failed to parse WebFinger resource descriptor as JSON: {error}", { error: e });
1512
- return { outcome: {
1513
- resource: null,
1514
- result: "invalid",
1515
- statusCode: response.status,
1516
- remoteHost: url.host
1517
- } };
1518
- }
1519
- throw e;
1520
- }
1521
- }
1522
- /**
1523
- * Starts cancelling a response body that is not read, without waiting for it
1524
- * to settle. The cancellation of a branch of a tee (e.g., a body cloned by
1525
- * a fetch mock) settles only after the other branch is cancelled too, per
1526
- * the Streams standard, so awaiting it could block forever. A failure is
1527
- * only logged.
1528
- */
1529
- function cancelBody(response, url) {
1530
- response.body?.cancel().catch((error) => {
1531
- logger.debug("Failed to cancel the response body from {url}: {error}", {
1532
- url: url.href,
1533
- error
1534
- });
1535
- });
1536
- }
1537
- //#endregion
1538
- //#region src/lookup.ts
1539
- const WEBFINGER_HISTOGRAM_BUCKETS = [
1540
- 5,
1541
- 10,
1542
- 25,
1543
- 50,
1544
- 75,
1545
- 100,
1546
- 250,
1547
- 500,
1548
- 750,
1549
- 1e3,
1550
- 2500,
1551
- 5e3,
1552
- 7500,
1553
- 1e4
1554
- ];
1555
- const webFingerInstruments = /* @__PURE__ */ new WeakMap();
1556
- function getWebFingerInstruments(meterProvider) {
1557
- let instruments = webFingerInstruments.get(meterProvider);
1558
- if (instruments == null) {
1559
- const meter = meterProvider.getMeter(name, version);
1560
- instruments = {
1561
- lookup: meter.createCounter("webfinger.lookup", {
1562
- description: "Outgoing WebFinger lookup attempts.",
1563
- unit: "{lookup}"
1564
- }),
1565
- lookupDuration: meter.createHistogram("webfinger.lookup.duration", {
1566
- description: "Duration of outgoing WebFinger lookups.",
1567
- unit: "ms",
1568
- advice: { explicitBucketBoundaries: [...WEBFINGER_HISTOGRAM_BUCKETS] }
1569
- })
1570
- };
1571
- webFingerInstruments.set(meterProvider, instruments);
1572
- }
1573
- return instruments;
1574
- }
1575
- function getResourceScheme(resource) {
1576
- if (typeof resource === "string") {
1577
- const colon = resource.indexOf(":");
1578
- return colon > 0 ? resource.substring(0, colon).toLowerCase() : "";
1579
- }
1580
- return resource.protocol.replace(/:$/, "").toLowerCase();
1581
- }
1582
- const WEBFINGER_LOOKUP_SCHEME_WHITELIST = /* @__PURE__ */ new Set([
1583
- "acct",
1584
- "http",
1585
- "https",
1586
- "mailto"
1587
- ]);
1588
- function getMetricResourceScheme(scheme) {
1589
- return WEBFINGER_LOOKUP_SCHEME_WHITELIST.has(scheme) ? scheme : "other";
1590
- }
1591
- async function lookupWebFinger(resource, options = {}) {
1592
- return await lookupWebFingerWithDependencies(resource, options);
1593
- }
1594
- async function lookupWebFingerWithDependencies(resource, options = {}, deps = {}) {
1595
- const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
1596
- const scheme = getResourceScheme(resource);
1597
- return await tracer.startActiveSpan("webfinger.lookup", {
1598
- kind: SpanKind.CLIENT,
1599
- attributes: {
1600
- "webfinger.resource": resource.toString(),
1601
- "webfinger.resource.scheme": scheme
1602
- }
1603
- }, async (span) => {
1604
- const meterProvider = options.meterProvider;
1605
- const start = meterProvider == null ? 0 : performance.now();
1606
- let outcome = {
1607
- resource: null,
1608
- result: "error"
1609
- };
1610
- try {
1611
- outcome = await lookupWebFingerInternal(resource, options, deps);
1612
- span.setStatus({ code: outcome.resource === null ? SpanStatusCode.ERROR : SpanStatusCode.OK });
1613
- return options.withDiagnostics ? outcome : outcome.resource;
1614
- } catch (error) {
1615
- span.setStatus({
1616
- code: SpanStatusCode.ERROR,
1617
- message: String(error)
1618
- });
1619
- throw error;
1620
- } finally {
1621
- if (meterProvider != null) recordWebFingerLookup(meterProvider, Math.max(0, performance.now() - start), scheme, outcome);
1622
- span.end();
1623
- }
1624
- });
1625
- }
1626
- function recordWebFingerLookup(meterProvider, durationMs, scheme, outcome) {
1627
- const attributes = {
1628
- "webfinger.lookup.result": outcome.result,
1629
- "webfinger.resource.scheme": getMetricResourceScheme(scheme)
1630
- };
1631
- if (outcome.remoteHost != null) attributes["activitypub.remote.host"] = outcome.remoteHost;
1632
- if (outcome.statusCode != null) attributes["http.response.status_code"] = outcome.statusCode;
1633
- const instruments = getWebFingerInstruments(meterProvider);
1634
- instruments.lookup.add(1, attributes);
1635
- instruments.lookupDuration.record(durationMs, attributes);
1636
- }
1637
- //#endregion
1638
- //#region src/lookup.test.ts
1639
- function lookupMock(resource, options = {}) {
1640
- if (resource.toString().includes("fedify-test.internal")) return lookupWebFingerWithDependencies(resource, options, { openHop: (url) => Promise.resolve({
1641
- url: new URL(url),
1642
- fetch: () => Promise.reject(/* @__PURE__ */ new TypeError("Connection refused")),
1643
- close: () => Promise.resolve()
1644
- }) });
1645
- return lookupWebFingerWithDependencies(resource, options, { openHop: options.allowPrivateAddress === true ? openDirectFetch : openExampleDirectly });
1646
- }
1647
- function lookupDirect(resource, options) {
1648
- return lookupWebFingerWithDependencies(resource, options, { openHop: openDirectFetch });
1649
- }
1650
- function lookupResolving(addresses) {
1651
- return () => Promise.resolve(addresses);
1652
- }
1653
- function openExampleDirectly(url) {
1654
- return new URL(url).hostname === "example.com" ? openDirectFetch(url) : openPublicFetch(url, { lookup: lookupResolving([{
1655
- address: "93.184.215.14",
1656
- family: 4
1657
- }]) });
1658
- }
1659
- async function lookupResourceWithDependencies(resource, options, deps) {
1660
- return (await lookupWebFingerInternal(resource, options, deps)).resource;
1661
- }
1662
- test({
1663
- name: "lookupWebFinger()",
1664
- sanitizeOps: false,
1665
- sanitizeResources: false,
1666
- async fn(t) {
1667
- const responseTimers = [];
1668
- await t.step("invalid resource", async () => {
1669
- deepStrictEqual(await lookupMock("acct:johndoe"), null);
1670
- deepStrictEqual(await lookupMock(new URL("acct:johndoe")), null);
1671
- deepStrictEqual(await lookupMock("acct:johndoe@"), null);
1672
- deepStrictEqual(await lookupMock(new URL("acct:johndoe@")), null);
1673
- deepStrictEqual(await lookupMock("acct:johndoe@example.com/exploit"), null);
1674
- deepStrictEqual(await lookupMock("acct:johndoe@example.com?x=1"), null);
1675
- deepStrictEqual(await lookupMock("acct:johndoe@example.com#frag"), null);
1676
- });
1677
- await t.step("connection refused", async () => {
1678
- deepStrictEqual(await lookupMock("acct:johndoe@fedify-test.internal"), null);
1679
- deepStrictEqual(await lookupMock("https://fedify-test.internal/foo"), null);
1680
- });
1681
- esm_default.spyGlobal();
1682
- try {
1683
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 404 });
1684
- await t.step("not found", async () => {
1685
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), null);
1686
- deepStrictEqual(await lookupMock("https://example.com/foo"), null);
1687
- });
1688
- const expected = {
1689
- subject: "acct:johndoe@example.com",
1690
- links: []
1691
- };
1692
- esm_default.removeRoutes();
1693
- esm_default.get("https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com", { body: expected });
1694
- await t.step("acct", async () => {
1695
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), expected);
1696
- });
1697
- const expected2 = {
1698
- subject: "https://example.com/foo",
1699
- links: []
1700
- };
1701
- esm_default.removeRoutes();
1702
- esm_default.get("https://example.com/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%2Ffoo", { body: expected2 });
1703
- await t.step("https", async () => {
1704
- deepStrictEqual(await lookupMock("https://example.com/foo"), expected2);
1705
- });
1706
- const mailtoExpected = {
1707
- subject: "mailto:juliet@example.com",
1708
- links: []
1709
- };
1710
- esm_default.removeRoutes();
1711
- esm_default.get("https://example.com/.well-known/webfinger?resource=mailto%3Ajuliet%40example.com", { body: mailtoExpected });
1712
- await t.step("mailto", async () => {
1713
- deepStrictEqual(await lookupMock("mailto:juliet@example.com"), mailtoExpected);
1714
- });
1715
- const mailtoQueryExpected = {
1716
- subject: "mailto:juliet@example.com?subject=Hi",
1717
- links: []
1718
- };
1719
- esm_default.removeRoutes();
1720
- esm_default.get("https://example.com/.well-known/webfinger?resource=mailto%3Ajuliet%40example.com%3Fsubject%3DHi", { body: mailtoQueryExpected });
1721
- await t.step("mailto with hfields", async () => {
1722
- deepStrictEqual(await lookupMock("mailto:juliet@example.com?subject=Hi"), mailtoQueryExpected);
1723
- });
1724
- esm_default.removeRoutes();
1725
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: "not json" });
1726
- await t.step("invalid response", async () => {
1727
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), null);
1728
- });
1729
- esm_default.removeRoutes();
1730
- esm_default.get("begin:https://localhost/.well-known/webfinger?", {
1731
- subject: "acct:test@localhost",
1732
- links: [{
1733
- rel: "self",
1734
- type: "application/activity+json",
1735
- href: "https://localhost/actor"
1736
- }]
1737
- });
1738
- await t.step("private address", async () => {
1739
- deepStrictEqual(await lookupMock("acct:test@localhost"), null);
1740
- deepStrictEqual(await lookupMock("acct:test@localhost", { allowPrivateAddress: true }), {
1741
- subject: "acct:test@localhost",
1742
- links: [{
1743
- rel: "self",
1744
- type: "application/activity+json",
1745
- href: "https://localhost/actor"
1746
- }]
1747
- });
1748
- });
1749
- esm_default.removeRoutes();
1750
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
1751
- status: 302,
1752
- headers: { Location: "/.well-known/webfinger2" }
1753
- });
1754
- esm_default.get("begin:https://example.com/.well-known/webfinger2", { body: expected });
1755
- await t.step("redirection", async () => {
1756
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), expected);
1757
- });
1758
- esm_default.removeRoutes();
1759
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
1760
- status: 302,
1761
- headers: { Location: "/.well-known/webfinger" }
1762
- });
1763
- await t.step("infinite redirection", async () => {
1764
- deepStrictEqual(await withTimeout(() => lookupMock("acct:johndoe@example.com"), 2e3), null);
1765
- });
1766
- esm_default.removeRoutes();
1767
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
1768
- status: 302,
1769
- headers: { Location: "ftp://example.com/" }
1770
- });
1771
- await t.step("redirection to different protocol", async () => {
1772
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), null);
1773
- });
1774
- esm_default.removeRoutes();
1775
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
1776
- status: 302,
1777
- headers: { Location: "https://localhost/" }
1778
- });
1779
- await t.step("redirection to private address", async () => {
1780
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), null);
1781
- });
1782
- esm_default.removeRoutes();
1783
- let redirectCount = 0;
1784
- esm_default.get("begin:https://example.com/.well-known/webfinger", () => {
1785
- redirectCount++;
1786
- if (redirectCount < 3) return {
1787
- status: 302,
1788
- headers: { Location: `/.well-known/webfinger?redirect=${redirectCount}` }
1789
- };
1790
- return { body: expected };
1791
- });
1792
- await t.step("custom maxRedirection", async () => {
1793
- redirectCount = 0;
1794
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { maxRedirection: 1 }), null);
1795
- redirectCount = 0;
1796
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { maxRedirection: 2 }), expected);
1797
- redirectCount = 0;
1798
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { maxRedirection: 3 }), expected);
1799
- redirectCount = 0;
1800
- deepStrictEqual(await lookupMock("acct:johndoe@example.com"), expected);
1801
- });
1802
- await t.step("maxRedirection: 1 follows exactly one redirect", async () => {
1803
- esm_default.removeRoutes();
1804
- let count = 0;
1805
- esm_default.get("begin:https://example.com/.well-known/webfinger", () => {
1806
- count++;
1807
- return count < 2 ? {
1808
- status: 302,
1809
- headers: { Location: "/.well-known/webfinger?after=1" }
1810
- } : { body: expected };
1811
- });
1812
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { maxRedirection: 1 }), expected);
1813
- esm_default.removeRoutes();
1814
- count = 0;
1815
- esm_default.get("begin:https://example.com/.well-known/webfinger", () => {
1816
- count++;
1817
- return count < 3 ? {
1818
- status: 302,
1819
- headers: { Location: `/.well-known/webfinger?after=${count}` }
1820
- } : { body: expected };
1821
- });
1822
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { maxRedirection: 1 }), null);
1823
- });
1824
- esm_default.removeRoutes();
1825
- esm_default.get("begin:https://example.com/.well-known/webfinger?", () => new Promise((resolve) => {
1826
- const timeoutId = setTimeout(() => {
1827
- resolve({ body: expected });
1828
- }, 1e3);
1829
- responseTimers.push(timeoutId);
1830
- }));
1831
- await t.step("request cancellation", async () => {
1832
- const controller = new AbortController();
1833
- const promise = lookupMock("acct:johndoe@example.com", { signal: controller.signal });
1834
- controller.abort();
1835
- deepStrictEqual(await promise, null);
1836
- });
1837
- esm_default.removeRoutes();
1838
- let redirectCount2 = 0;
1839
- esm_default.get("begin:https://example.com/.well-known/webfinger", () => {
1840
- redirectCount2++;
1841
- if (redirectCount2 === 1) return {
1842
- status: 302,
1843
- headers: { Location: "/.well-known/webfinger2" }
1844
- };
1845
- return new Promise((resolve) => {
1846
- const timeoutId = setTimeout(() => {
1847
- resolve({ body: expected });
1848
- }, 1e3);
1849
- responseTimers.push(timeoutId);
1850
- });
1851
- });
1852
- await t.step("cancellation during redirection", async () => {
1853
- const controller = new AbortController();
1854
- const promise = lookupMock("acct:johndoe@example.com", { signal: controller.signal });
1855
- setTimeout(() => controller.abort(), 100);
1856
- deepStrictEqual(await promise, null);
1857
- });
1858
- esm_default.removeRoutes();
1859
- esm_default.get("begin:https://example.com/.well-known/webfinger?", () => new Promise((resolve) => {
1860
- const timeoutId = setTimeout(() => {
1861
- resolve({ body: expected });
1862
- }, 500);
1863
- responseTimers.push(timeoutId);
1864
- }));
1865
- await t.step("cancellation with immediate abort", async () => {
1866
- const controller = new AbortController();
1867
- controller.abort();
1868
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { signal: controller.signal }), null);
1869
- });
1870
- esm_default.removeRoutes();
1871
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: expected });
1872
- await t.step("successful request with signal", async () => {
1873
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { signal: new AbortController().signal }), expected);
1874
- });
1875
- } finally {
1876
- for (const timer of responseTimers) clearTimeout(timer);
1877
- esm_default.removeRoutes();
1878
- esm_default.hardReset();
1879
- }
1880
- }
1881
- });
1882
- test("lookupWebFinger() records webfinger.lookup counter and duration", {
1883
- sanitizeOps: false,
1884
- sanitizeResources: false
1885
- }, async (t) => {
1886
- esm_default.spyGlobal();
1887
- try {
1888
- const expected = {
1889
- subject: "acct:johndoe@example.com",
1890
- links: []
1891
- };
1892
- await t.step("records result=found for a successful acct lookup", async () => {
1893
- esm_default.removeRoutes();
1894
- esm_default.get("https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com", { body: expected });
1895
- const [meterProvider, recorder] = createTestMeterProvider();
1896
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { meterProvider }), expected);
1897
- const counters = recorder.getMeasurements("webfinger.lookup");
1898
- deepStrictEqual(counters.length, 1);
1899
- deepStrictEqual(counters[0].type, "counter");
1900
- deepStrictEqual(counters[0].value, 1);
1901
- deepStrictEqual(counters[0].attributes["webfinger.lookup.result"], "found");
1902
- deepStrictEqual(counters[0].attributes["webfinger.resource.scheme"], "acct");
1903
- deepStrictEqual(counters[0].attributes["activitypub.remote.host"], "example.com");
1904
- deepStrictEqual(counters[0].attributes["http.response.status_code"], 200);
1905
- const durations = recorder.getMeasurements("webfinger.lookup.duration");
1906
- deepStrictEqual(durations.length, 1);
1907
- deepStrictEqual(durations[0].type, "histogram");
1908
- deepStrictEqual(durations[0].attributes["webfinger.lookup.result"], "found");
1909
- deepStrictEqual(durations[0].attributes["webfinger.resource.scheme"], "acct");
1910
- ok(typeof durations[0].value === "number" && durations[0].value >= 0);
1911
- });
1912
- await t.step("records scheme=https for an https resource lookup", async () => {
1913
- esm_default.removeRoutes();
1914
- esm_default.get("https://example.com/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%2Ffoo", { body: {
1915
- subject: "https://example.com/foo",
1916
- links: []
1917
- } });
1918
- const [meterProvider, recorder] = createTestMeterProvider();
1919
- await lookupMock("https://example.com/foo", { meterProvider });
1920
- const counters = recorder.getMeasurements("webfinger.lookup");
1921
- deepStrictEqual(counters.length, 1);
1922
- deepStrictEqual(counters[0].attributes["webfinger.resource.scheme"], "https");
1923
- deepStrictEqual(counters[0].attributes["webfinger.lookup.result"], "found");
1924
- });
1925
- await t.step("records non-default ports for URL resources", async () => {
1926
- esm_default.removeRoutes();
1927
- esm_default.get("https://example.com:8443/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%3A8443%2Ffoo", { body: {
1928
- subject: "https://example.com:8443/foo",
1929
- links: []
1930
- } });
1931
- const [meterProvider, recorder] = createTestMeterProvider();
1932
- await lookupMock("https://example.com:8443/foo", { meterProvider });
1933
- const counter = recorder.getMeasurement("webfinger.lookup");
1934
- ok(counter != null);
1935
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "example.com:8443");
1936
- });
1937
- await t.step("records result=not_found with status 404", async () => {
1938
- esm_default.removeRoutes();
1939
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 404 });
1940
- const [meterProvider, recorder] = createTestMeterProvider();
1941
- deepStrictEqual(await lookupMock("acct:johndoe@example.com", { meterProvider }), null);
1942
- const counters = recorder.getMeasurements("webfinger.lookup");
1943
- deepStrictEqual(counters.length, 1);
1944
- deepStrictEqual(counters[0].attributes["webfinger.lookup.result"], "not_found");
1945
- deepStrictEqual(counters[0].attributes["http.response.status_code"], 404);
1946
- deepStrictEqual(counters[0].attributes["activitypub.remote.host"], "example.com");
1947
- const durations = recorder.getMeasurements("webfinger.lookup.duration");
1948
- deepStrictEqual(durations.length, 1);
1949
- deepStrictEqual(durations[0].attributes["webfinger.lookup.result"], "not_found");
1950
- });
1951
- await t.step("records result=not_found with status 410", async () => {
1952
- esm_default.removeRoutes();
1953
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 410 });
1954
- const [meterProvider, recorder] = createTestMeterProvider();
1955
- await lookupMock("acct:johndoe@example.com", { meterProvider });
1956
- const counter = recorder.getMeasurement("webfinger.lookup");
1957
- ok(counter != null);
1958
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "not_found");
1959
- deepStrictEqual(counter.attributes["http.response.status_code"], 410);
1960
- });
1961
- await t.step("records result=error for non-2xx, non-404/410 HTTP responses", async () => {
1962
- esm_default.removeRoutes();
1963
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 500 });
1964
- const [meterProvider, recorder] = createTestMeterProvider();
1965
- await lookupMock("acct:johndoe@example.com", { meterProvider });
1966
- const counter = recorder.getMeasurement("webfinger.lookup");
1967
- ok(counter != null);
1968
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "error");
1969
- deepStrictEqual(counter.attributes["http.response.status_code"], 500);
1970
- });
1971
- await t.step("records result=invalid for malformed JSON bodies", async () => {
1972
- esm_default.removeRoutes();
1973
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: "not json" });
1974
- const [meterProvider, recorder] = createTestMeterProvider();
1975
- await lookupMock("acct:johndoe@example.com", { meterProvider });
1976
- const counter = recorder.getMeasurement("webfinger.lookup");
1977
- ok(counter != null);
1978
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "invalid");
1979
- deepStrictEqual(counter.attributes["http.response.status_code"], 200);
1980
- });
1981
- await t.step("records result=network_error when fetch never reaches the remote", async () => {
1982
- esm_default.removeRoutes();
1983
- const [meterProvider, recorder] = createTestMeterProvider();
1984
- deepStrictEqual(await lookupMock("acct:johndoe@fedify-test.internal", { meterProvider }), null);
1985
- const counter = recorder.getMeasurement("webfinger.lookup");
1986
- ok(counter != null);
1987
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "network_error");
1988
- deepStrictEqual("http.response.status_code" in counter.attributes, false, "no HTTP response means no status code attribute");
1989
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "fedify-test.internal");
1990
- });
1991
- await t.step("records result=invalid for malformed acct: resources", async () => {
1992
- const [meterProvider, recorder] = createTestMeterProvider();
1993
- deepStrictEqual(await lookupMock("acct:johndoe", { meterProvider }), null);
1994
- const counter = recorder.getMeasurement("webfinger.lookup");
1995
- ok(counter != null);
1996
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "invalid");
1997
- deepStrictEqual(counter.attributes["webfinger.resource.scheme"], "acct");
1998
- deepStrictEqual("activitypub.remote.host" in counter.attributes, false, "a malformed acct resource has no usable remote host");
1999
- });
2000
- await t.step("records result=invalid when the redirect chain exceeds maxRedirection", async () => {
2001
- esm_default.removeRoutes();
2002
- esm_default.get("begin:https://example.com/.well-known/webfinger", {
2003
- status: 302,
2004
- headers: { Location: "/.well-known/webfinger" }
2005
- });
2006
- const [meterProvider, recorder] = createTestMeterProvider();
2007
- deepStrictEqual(await withTimeout(() => lookupMock("acct:johndoe@example.com", {
2008
- meterProvider,
2009
- maxRedirection: 3
2010
- }), 2e3), null);
2011
- const counter = recorder.getMeasurement("webfinger.lookup");
2012
- ok(counter != null);
2013
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "invalid");
2014
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
2015
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "example.com");
2016
- });
2017
- await t.step("records result=invalid for cross-protocol redirects", async () => {
2018
- esm_default.removeRoutes();
2019
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
2020
- status: 302,
2021
- headers: { Location: "ftp://example.com/" }
2022
- });
2023
- const [meterProvider, recorder] = createTestMeterProvider();
2024
- await lookupMock("acct:johndoe@example.com", { meterProvider });
2025
- const counter = recorder.getMeasurement("webfinger.lookup");
2026
- ok(counter != null);
2027
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "invalid");
2028
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
2029
- });
2030
- await t.step("records result=network_error when a redirect points to a private address", async () => {
2031
- esm_default.removeRoutes();
2032
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
2033
- status: 302,
2034
- headers: { Location: "https://localhost/" }
2035
- });
2036
- const [meterProvider, recorder] = createTestMeterProvider();
2037
- await lookupMock("acct:johndoe@example.com", { meterProvider });
2038
- const counter = recorder.getMeasurement("webfinger.lookup");
2039
- ok(counter != null);
2040
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "network_error");
2041
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "localhost", "remote.host reflects the latest URL we attempted, even after a redirect");
2042
- });
2043
- await t.step("records result=invalid for malformed Location headers", async () => {
2044
- esm_default.removeRoutes();
2045
- esm_default.get("begin:https://example.com/.well-known/webfinger?", {
2046
- status: 302,
2047
- headers: { Location: "http://[bad" }
2048
- });
2049
- const [meterProvider, recorder] = createTestMeterProvider();
2050
- await lookupMock("acct:johndoe@example.com", { meterProvider });
2051
- const counter = recorder.getMeasurement("webfinger.lookup");
2052
- ok(counter != null);
2053
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "invalid");
2054
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
2055
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "example.com");
2056
- });
2057
- await t.step("buckets unknown resource schemes as 'other' to keep metric cardinality bounded", async () => {
2058
- esm_default.removeRoutes();
2059
- const [meterProvider, recorder] = createTestMeterProvider();
2060
- await lookupMock("ssh://example.com/foo", { meterProvider });
2061
- const counter = recorder.getMeasurement("webfinger.lookup");
2062
- ok(counter != null);
2063
- deepStrictEqual(counter.attributes["webfinger.resource.scheme"], "other");
2064
- });
2065
- await t.step("omits measurements when no meterProvider is provided", async () => {
2066
- esm_default.removeRoutes();
2067
- esm_default.get("https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com", { body: expected });
2068
- const [_unused, recorder] = createTestMeterProvider();
2069
- await lookupMock("acct:johndoe@example.com");
2070
- deepStrictEqual(recorder.getMeasurements("webfinger.lookup").length, 0);
2071
- deepStrictEqual(recorder.getMeasurements("webfinger.lookup.duration").length, 0);
2072
- });
2073
- } finally {
2074
- esm_default.removeRoutes();
2075
- esm_default.hardReset();
2076
- }
2077
- });
2078
- test("lookupWebFinger() bounds resource descriptors", async () => {
2079
- esm_default.mockGlobal();
2080
- let oversized = true;
2081
- try {
2082
- esm_default.get("begin:https://example.com/.well-known/webfinger?", () => new Response("{\"subject\":\"acct:alice@example.com\"}" + (oversized ? " ".repeat(16 * 1024 * 1024) : ""), { headers: {
2083
- "Content-Type": "application/jrd+json",
2084
- "Content-Length": "1"
2085
- } }));
2086
- deepStrictEqual(await lookupMock("acct:alice@example.com", { allowPrivateAddress: true }), null);
2087
- oversized = false;
2088
- deepStrictEqual(await lookupMock("acct:alice@example.com", { allowPrivateAddress: true }), { subject: "acct:alice@example.com" });
2089
- } finally {
2090
- esm_default.hardReset();
2091
- }
2092
- });
2093
- test("lookupWebFinger() logs DNS failures as such", async (t) => {
2094
- for (const result of [
2095
- "throws",
2096
- "empty",
2097
- "private"
2098
- ]) await t.step(result, async () => {
2099
- const lookup = () => result === "throws" ? Promise.reject(/* @__PURE__ */ new Error("Resolver unavailable")) : Promise.resolve(result === "empty" ? [] : [{
2100
- address: "127.0.0.1",
2101
- family: 4
2102
- }]);
2103
- const records = [];
2104
- await configure({
2105
- sinks: { buffer: (record) => records.push(record) },
2106
- loggers: [{
2107
- category: "fedify",
2108
- sinks: ["buffer"],
2109
- lowestLevel: "debug"
2110
- }, {
2111
- category: ["logtape", "meta"],
2112
- sinks: []
2113
- }],
2114
- reset: true
2115
- });
2116
- try {
2117
- deepStrictEqual(await lookupResourceWithDependencies("acct:alice@dns-failure.invalid", {}, { openHop: (url) => openPublicFetch(url, { lookup }) }), null);
2118
- const failures = records.filter((r) => r.rawMessage !== "Fetching WebFinger resource descriptor from {url}...");
2119
- deepStrictEqual(failures.map((r) => [r.level, r.rawMessage]), [result === "private" ? ["error", "Invalid URL for WebFinger resource descriptor: {error}"] : ["debug", "DNS lookup failed for {url}"]]);
2120
- const { error } = failures[0].properties;
2121
- ok(error instanceof UrlError);
2122
- deepStrictEqual(error.reason, result === "private" ? "disallowed" : "dns");
2123
- } finally {
2124
- await reset();
2125
- }
2126
- });
2127
- });
2128
- test("lookupWebFinger() with withDiagnostics: true", {
2129
- sanitizeOps: false,
2130
- sanitizeResources: false
2131
- }, async (t) => {
2132
- await t.step("network_error", async () => {
2133
- const outcome = await lookupMock("acct:johndoe@fedify-test.internal", { withDiagnostics: true });
2134
- deepStrictEqual(outcome.resource, null);
2135
- deepStrictEqual(outcome.result, "network_error");
2136
- deepStrictEqual("statusCode" in outcome, false, "no HTTP response means no status code");
2137
- });
2138
- esm_default.spyGlobal();
2139
- try {
2140
- await t.step("found", async () => {
2141
- esm_default.removeRoutes();
2142
- const expected = {
2143
- subject: "acct:johndoe@example.com",
2144
- links: []
2145
- };
2146
- esm_default.get("https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com", { body: expected });
2147
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2148
- deepStrictEqual(outcome.resource, expected);
2149
- deepStrictEqual(outcome.result, "found");
2150
- deepStrictEqual(outcome.statusCode, 200);
2151
- deepStrictEqual(outcome.remoteHost, "example.com");
2152
- });
2153
- await t.step("not_found", async () => {
2154
- esm_default.removeRoutes();
2155
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 404 });
2156
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2157
- deepStrictEqual(outcome.resource, null);
2158
- deepStrictEqual(outcome.result, "not_found");
2159
- deepStrictEqual(outcome.statusCode, 404);
2160
- deepStrictEqual(outcome.remoteHost, "example.com");
2161
- });
2162
- await t.step("invalid", async () => {
2163
- esm_default.removeRoutes();
2164
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: "not json" });
2165
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2166
- deepStrictEqual(outcome.resource, null);
2167
- deepStrictEqual(outcome.result, "invalid");
2168
- deepStrictEqual(outcome.statusCode, 200);
2169
- deepStrictEqual(outcome.remoteHost, "example.com");
2170
- });
2171
- await t.step("invalid: a literal JSON null body is not a resource descriptor", async () => {
2172
- esm_default.removeRoutes();
2173
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: "null" });
2174
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2175
- deepStrictEqual(outcome.resource, null);
2176
- deepStrictEqual(outcome.result, "invalid");
2177
- deepStrictEqual(outcome.statusCode, 200);
2178
- deepStrictEqual(outcome.remoteHost, "example.com");
2179
- });
2180
- await t.step("invalid: a JSON array body is not a resource descriptor", async () => {
2181
- esm_default.removeRoutes();
2182
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { body: "[]" });
2183
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2184
- deepStrictEqual(outcome.resource, null);
2185
- deepStrictEqual(outcome.result, "invalid");
2186
- deepStrictEqual(outcome.statusCode, 200);
2187
- deepStrictEqual(outcome.remoteHost, "example.com");
2188
- });
2189
- await t.step("error", async () => {
2190
- esm_default.removeRoutes();
2191
- esm_default.get("begin:https://example.com/.well-known/webfinger?", { status: 500 });
2192
- const outcome = await lookupMock("acct:johndoe@example.com", { withDiagnostics: true });
2193
- deepStrictEqual(outcome.resource, null);
2194
- deepStrictEqual(outcome.result, "error");
2195
- deepStrictEqual(outcome.statusCode, 500);
2196
- deepStrictEqual(outcome.remoteHost, "example.com");
2197
- });
2198
- } finally {
2199
- esm_default.removeRoutes();
2200
- esm_default.hardReset();
2201
- }
2202
- });
2203
- test("lookupWebFinger() accepts a plain LookupWebFingerOptions-typed variable", async () => {
2204
- esm_default.spyGlobal();
2205
- try {
2206
- const expected = {
2207
- subject: "acct:johndoe@example.com",
2208
- links: []
2209
- };
2210
- esm_default.get("https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com", { body: expected });
2211
- deepStrictEqual(await lookupWebFinger("acct:johndoe@example.com", {
2212
- userAgent: "test-agent",
2213
- allowPrivateAddress: true
2214
- }), expected);
2215
- } finally {
2216
- esm_default.removeRoutes();
2217
- esm_default.hardReset();
2218
- }
2219
- });
2220
- function recordHops(respond) {
2221
- const events = [];
2222
- const unsettled = [];
2223
- let opens = 0;
2224
- let closes = 0;
2225
- let responses = 0;
2226
- return {
2227
- events,
2228
- async openHop(url) {
2229
- opens++;
2230
- events.push(`open ${url}`);
2231
- const states = [];
2232
- let closed = false;
2233
- return {
2234
- url: new URL(url),
2235
- async fetch(input) {
2236
- if (closed) throw new TypeError("The fetch session is closed.");
2237
- const target = new URL(input instanceof Request ? input.url : input);
2238
- const id = ++responses;
2239
- events.push(`fetch ${target.href} #${id}`);
2240
- const fake = respond(target);
2241
- const state = {
2242
- id,
2243
- settled: false
2244
- };
2245
- states.push(state);
2246
- let sent = false;
2247
- const body = new ReadableStream({
2248
- pull(controller) {
2249
- if (!sent && fake.body != null && fake.body !== "") {
2250
- sent = true;
2251
- controller.enqueue(new TextEncoder().encode(fake.body));
2252
- return;
2253
- }
2254
- state.settled = true;
2255
- events.push(`consumed #${id}`);
2256
- controller.close();
2257
- },
2258
- cancel() {
2259
- state.settled = true;
2260
- events.push(`cancel #${id}`);
2261
- if (fake.cancelFails) throw new Error("Cancellation failed");
2262
- if (fake.cancelNeverSettles) return new Promise(() => {});
2263
- }
2264
- }, { highWaterMark: 0 });
2265
- const response = new Response(body, {
2266
- status: fake.status ?? 200,
2267
- headers: fake.headers
2268
- });
2269
- if (fake.url != null) Object.defineProperty(response, "url", { value: fake.url });
2270
- return response;
2271
- },
2272
- async close() {
2273
- if (closed) return;
2274
- closed = true;
2275
- closes++;
2276
- for (const state of states) if (!state.settled) unsettled.push(`#${state.id}`);
2277
- events.push(`close ${url}`);
2278
- }
2279
- };
2280
- },
2281
- assertInvariants() {
2282
- deepStrictEqual(closes, opens);
2283
- deepStrictEqual(unsettled, []);
2284
- }
2285
- };
2286
- }
2287
- test("lookupWebFinger() closes each hop after cleaning up its body", async (t) => {
2288
- const descriptor = {
2289
- subject: "acct:johndoe@example.com",
2290
- links: []
2291
- };
2292
- const first = "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com";
2293
- const second = "https://example.com/.well-known/webfinger2";
2294
- await t.step("redirect", async () => {
2295
- const recorder = recordHops((url) => url.pathname === "/.well-known/webfinger" ? {
2296
- status: 302,
2297
- headers: { Location: "/.well-known/webfinger2" },
2298
- body: "redirecting",
2299
- url: url.href.replace("example.com", "93.184.215.14")
2300
- } : { body: JSON.stringify(descriptor) });
2301
- deepStrictEqual(await lookupResourceWithDependencies("acct:johndoe@example.com", {}, { openHop: recorder.openHop }), descriptor);
2302
- deepStrictEqual(recorder.events, [
2303
- `open ${first}`,
2304
- `fetch ${first} #1`,
2305
- "cancel #1",
2306
- `close ${first}`,
2307
- `open ${second}`,
2308
- `fetch ${second} #2`,
2309
- "consumed #2",
2310
- `close ${second}`
2311
- ]);
2312
- recorder.assertInvariants();
2313
- });
2314
- await t.step("non-2xx response", async () => {
2315
- const recorder = recordHops(() => ({
2316
- status: 404,
2317
- body: "not found"
2318
- }));
2319
- deepStrictEqual(await lookupResourceWithDependencies("acct:johndoe@example.com", {}, { openHop: recorder.openHop }), null);
2320
- deepStrictEqual(recorder.events, [
2321
- `open ${first}`,
2322
- `fetch ${first} #1`,
2323
- "cancel #1",
2324
- `close ${first}`
2325
- ]);
2326
- recorder.assertInvariants();
2327
- });
2328
- await t.step("too many redirections", async () => {
2329
- const recorder = recordHops(() => ({
2330
- status: 302,
2331
- headers: { Location: "/.well-known/webfinger2" },
2332
- body: "redirecting"
2333
- }));
2334
- deepStrictEqual(await lookupResourceWithDependencies("acct:johndoe@example.com", { maxRedirection: 1 }, { openHop: recorder.openHop }), null);
2335
- deepStrictEqual(recorder.events, [
2336
- `open ${first}`,
2337
- `fetch ${first} #1`,
2338
- "cancel #1",
2339
- `close ${first}`,
2340
- `open ${second}`,
2341
- `fetch ${second} #2`,
2342
- "cancel #2",
2343
- `close ${second}`
2344
- ]);
2345
- recorder.assertInvariants();
2346
- });
2347
- await t.step("failed redirect body cancellation", async () => {
2348
- const recorder = recordHops((url) => url.pathname === "/.well-known/webfinger" ? {
2349
- status: 302,
2350
- headers: { Location: "/.well-known/webfinger2" },
2351
- body: "redirecting",
2352
- cancelFails: true
2353
- } : { body: JSON.stringify(descriptor) });
2354
- const records = [];
2355
- await configure({
2356
- sinks: { buffer: (record) => records.push(record) },
2357
- loggers: [{
2358
- category: "fedify",
2359
- sinks: ["buffer"],
2360
- lowestLevel: "debug"
2361
- }, {
2362
- category: ["logtape", "meta"],
2363
- sinks: []
2364
- }],
2365
- reset: true
2366
- });
2367
- try {
2368
- deepStrictEqual(await lookupResourceWithDependencies("acct:johndoe@example.com", {}, { openHop: recorder.openHop }), descriptor);
2369
- const failures = records.filter((r) => r.rawMessage === "Failed to cancel the response body from {url}: {error}");
2370
- deepStrictEqual(failures.map((r) => [r.level, r.properties.url]), [["debug", first]]);
2371
- const { error } = failures[0].properties;
2372
- ok(error instanceof Error);
2373
- deepStrictEqual(error.message, "Cancellation failed");
2374
- } finally {
2375
- await reset();
2376
- }
2377
- deepStrictEqual(recorder.events, [
2378
- `open ${first}`,
2379
- `fetch ${first} #1`,
2380
- "cancel #1",
2381
- `close ${first}`,
2382
- `open ${second}`,
2383
- `fetch ${second} #2`,
2384
- "consumed #2",
2385
- `close ${second}`
2386
- ]);
2387
- recorder.assertInvariants();
2388
- });
2389
- await t.step("never-settling body cancellation", async () => {
2390
- const recorder = recordHops((url) => url.pathname === "/.well-known/webfinger" ? {
2391
- status: 302,
2392
- headers: { Location: "/.well-known/webfinger2" },
2393
- body: "redirecting",
2394
- cancelNeverSettles: true
2395
- } : {
2396
- status: 404,
2397
- body: "not found",
2398
- cancelNeverSettles: true
2399
- });
2400
- deepStrictEqual(await settleWithin(lookupResourceWithDependencies("acct:johndoe@example.com", {}, { openHop: recorder.openHop })), null);
2401
- deepStrictEqual(recorder.events, [
2402
- `open ${first}`,
2403
- `fetch ${first} #1`,
2404
- "cancel #1",
2405
- `close ${first}`,
2406
- `open ${second}`,
2407
- `fetch ${second} #2`,
2408
- "cancel #2",
2409
- `close ${second}`
2410
- ]);
2411
- recorder.assertInvariants();
2412
- });
2413
- });
2414
- /**
2415
- * Rejects if the given promise does not settle within the timeout, so that
2416
- * a hang fails the test instead of blocking it.
2417
- */
2418
- async function settleWithin(promise, ms = 5e3) {
2419
- let timer;
2420
- try {
2421
- return await Promise.race([promise, new Promise((_, reject) => {
2422
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Did not settle within ${ms} ms.`)), ms);
2423
- })]);
2424
- } finally {
2425
- clearTimeout(timer);
2426
- }
2427
- }
2428
- function neverCancellableResponse(init) {
2429
- return new Response(new ReadableStream({
2430
- start(controller) {
2431
- controller.enqueue(new TextEncoder().encode("never cancelled"));
2432
- },
2433
- cancel: () => new Promise(() => {})
2434
- }), init);
2435
- }
2436
- test("lookupWebFinger() does not wait for cancelling response bodies", async (t) => {
2437
- const descriptor = {
2438
- subject: "acct:johndoe@example.com",
2439
- links: []
2440
- };
2441
- esm_default.mockGlobal();
2442
- try {
2443
- await t.step("redirect", async () => {
2444
- esm_default.removeRoutes();
2445
- esm_default.get("begin:https://example.com/.well-known/webfinger?", () => neverCancellableResponse({
2446
- status: 302,
2447
- headers: { Location: "/.well-known/webfinger2" }
2448
- }));
2449
- esm_default.get("https://example.com/.well-known/webfinger2", () => new Response(JSON.stringify(descriptor), { headers: { "Content-Type": "application/jrd+json" } }));
2450
- deepStrictEqual(await settleWithin(lookupDirect("acct:johndoe@example.com")), descriptor);
2451
- });
2452
- await t.step("non-2xx response", async () => {
2453
- esm_default.removeRoutes();
2454
- esm_default.get("begin:https://example.com/.well-known/webfinger?", () => neverCancellableResponse({ status: 404 }));
2455
- deepStrictEqual(await settleWithin(lookupDirect("acct:johndoe@example.com")), null);
2456
- });
2457
- } finally {
2458
- esm_default.hardReset();
2459
- }
2460
- });
2461
- test$1("lookupWebFinger() records network_error for rejected hop addresses", async () => {
2462
- for (const lookup of [
2463
- () => Promise.reject(/* @__PURE__ */ new Error("DNS unavailable")),
2464
- () => Promise.resolve([]),
2465
- () => Promise.resolve([{
2466
- address: "127.0.0.1",
2467
- family: 4
2468
- }])
2469
- ]) {
2470
- const [meterProvider, recorder] = createTestMeterProvider();
2471
- deepStrictEqual(await lookupWebFingerWithDependencies("acct:alice@dns-failure.invalid", { meterProvider }, { openHop: (url) => openPublicFetch(url, { lookup }) }), null);
2472
- const counter = recorder.getMeasurement("webfinger.lookup");
2473
- ok(counter != null);
2474
- deepStrictEqual(counter.attributes["webfinger.lookup.result"], "network_error");
2475
- deepStrictEqual(counter.attributes["activitypub.remote.host"], "dns-failure.invalid");
2476
- deepStrictEqual("http.response.status_code" in counter.attributes, false);
2477
- }
2478
- });
2479
- test$1("WebFinger diagnostics classify non-object JSON after closing the hop", async () => {
2480
- for (const body of [
2481
- "null",
2482
- "[]",
2483
- "42",
2484
- "\"text\"",
2485
- "true"
2486
- ]) {
2487
- const hops = recordHops(() => ({ body }));
2488
- const [meterProvider, recorder] = createTestMeterProvider();
2489
- deepStrictEqual(await lookupWebFingerWithDependencies("acct:alice@example.com", {
2490
- withDiagnostics: true,
2491
- meterProvider
2492
- }, { openHop: hops.openHop }), {
2493
- resource: null,
2494
- result: "invalid",
2495
- statusCode: 200,
2496
- remoteHost: "example.com"
2497
- });
2498
- deepStrictEqual(hops.events.at(-1), "close https://example.com/.well-known/webfinger?resource=acct%3Aalice%40example.com");
2499
- hops.assertInvariants();
2500
- deepStrictEqual(recorder.getMeasurement("webfinger.lookup")?.attributes["webfinger.lookup.result"], "invalid");
2501
- }
2502
- });
2503
- //#endregion
2504
- export {};