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