@fedify/webfinger 2.4.6-dev.2837 → 2.4.6

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.
@@ -1236,7 +1236,7 @@ var esm_default = new class FetchMock {
1236
1236
  //#endregion
1237
1237
  //#region deno.json
1238
1238
  var name = "@fedify/webfinger";
1239
- var version = "2.4.6-dev.2837+bb303087";
1239
+ var version = "2.4.6";
1240
1240
  //#endregion
1241
1241
  //#region src/body.ts
1242
1242
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -1259,13 +1259,18 @@ function validateBodySizeLimit(maxBytes) {
1259
1259
  * @param message The response or request to read.
1260
1260
  * @param maxBytes The maximum number of decoded bytes to read.
1261
1261
  * @param url The URL to include in errors and logs.
1262
+ * @param signal The signal that cancels an in-progress body read.
1262
1263
  * @returns The decoded body text.
1263
1264
  * @throws {BodyTooLargeError} If the body exceeds the limit.
1264
1265
  * @internal
1265
1266
  */
1266
- async function readBoundedText(message, maxBytes, url) {
1267
+ async function readBoundedText(message, maxBytes, url, signal) {
1267
1268
  validateBodySizeLimit(maxBytes);
1268
1269
  const reader = message.body?.getReader();
1270
+ const cancelOnAbort = () => {
1271
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
1272
+ };
1273
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
1269
1274
  const tooLarge = () => {
1270
1275
  getLogger([
1271
1276
  "fedify",
@@ -1278,6 +1283,7 @@ async function readBoundedText(message, maxBytes, url) {
1278
1283
  throw new BodyTooLargeError(url, maxBytes);
1279
1284
  };
1280
1285
  try {
1286
+ signal?.throwIfAborted();
1281
1287
  const length = message.headers.get("Content-Length");
1282
1288
  const encoding = message.headers.get("Content-Encoding");
1283
1289
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -1285,6 +1291,7 @@ async function readBoundedText(message, maxBytes, url) {
1285
1291
  let size = 0;
1286
1292
  const textReader = new ReadableStream({ async pull(controller) {
1287
1293
  const { done, value } = await reader.read();
1294
+ signal?.throwIfAborted();
1288
1295
  if (done) {
1289
1296
  controller.close();
1290
1297
  return;
@@ -1297,9 +1304,11 @@ async function readBoundedText(message, maxBytes, url) {
1297
1304
  const chunks = [];
1298
1305
  while (true) {
1299
1306
  const { done, value } = await textReader.read();
1307
+ signal?.throwIfAborted();
1300
1308
  if (done) break;
1301
1309
  chunks.push(value);
1302
1310
  }
1311
+ signal?.throwIfAborted();
1303
1312
  return chunks.join("");
1304
1313
  } finally {
1305
1314
  textReader.releaseLock();
@@ -1308,6 +1317,7 @@ async function readBoundedText(message, maxBytes, url) {
1308
1317
  if (reader != null) reader.cancel(error).catch(() => {});
1309
1318
  throw error;
1310
1319
  } finally {
1320
+ signal?.removeEventListener("abort", cancelOnAbort);
1311
1321
  reader?.releaseLock();
1312
1322
  }
1313
1323
  }
@@ -1319,6 +1329,7 @@ const logger = getLogger([
1319
1329
  "lookup"
1320
1330
  ]);
1321
1331
  const DEFAULT_MAX_REDIRECTION = 5;
1332
+ const DEFAULT_TIMEOUT_MS = 1e4;
1322
1333
  /**
1323
1334
  * Looks up a WebFinger resource, opening a fetch session per hop. This is
1324
1335
  * the implementation of {@link lookupWebFinger}, which is not exported from
@@ -1352,14 +1363,67 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1352
1363
  protocol = resource.protocol;
1353
1364
  server = resource.host;
1354
1365
  }
1355
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1366
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1356
1367
  url.searchParams.set("resource", resource.href);
1357
- const openHop = deps.openHop ?? ((hopUrl) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: options.signal }));
1368
+ const controller = new AbortController();
1369
+ const signal = controller.signal;
1370
+ let timedOut = false;
1371
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1372
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
1373
+ const timeout = setTimeout(() => {
1374
+ timedOut = true;
1375
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
1376
+ }, timeoutMs);
1377
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
1378
+ if (options.signal?.aborted) abortFromCaller();
1379
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
1380
+ let stopWaiting = () => {};
1381
+ const cancelledOutcome = () => ({
1382
+ resource: null,
1383
+ result: "network_error",
1384
+ remoteHost: url.host
1385
+ });
1386
+ const aborted = new Promise((resolve) => {
1387
+ if (signal.aborted) resolve(cancelledOutcome());
1388
+ else {
1389
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
1390
+ const onAbort = () => resolve(cancelledOutcome());
1391
+ signal.addEventListener("abort", onAbort, { once: true });
1392
+ }
1393
+ });
1394
+ const work = lookupHops(url, options, deps.openHop ?? ((hopUrl, hopSignal) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: hopSignal })), signal);
1395
+ try {
1396
+ const result = await Promise.race([work, aborted]);
1397
+ if (signal.aborted) {
1398
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
1399
+ url: url.href,
1400
+ timeoutMs
1401
+ });
1402
+ return cancelledOutcome();
1403
+ }
1404
+ return result;
1405
+ } catch (error) {
1406
+ if (signal.aborted) return cancelledOutcome();
1407
+ throw error;
1408
+ } finally {
1409
+ clearTimeout(timeout);
1410
+ stopWaiting();
1411
+ options.signal?.removeEventListener("abort", abortFromCaller);
1412
+ work.catch(() => {});
1413
+ }
1414
+ }
1415
+ async function lookupHops(initialUrl, options, openHop, signal) {
1416
+ let url = initialUrl;
1358
1417
  let redirected = 0;
1359
1418
  while (true) {
1419
+ if (signal.aborted) return {
1420
+ resource: null,
1421
+ result: "network_error",
1422
+ remoteHost: url.host
1423
+ };
1360
1424
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
1361
1425
  const remoteHost = url.host;
1362
- const session = await openSession(url, openHop, options.signal);
1426
+ const session = await openSession(url, openHop, signal);
1363
1427
  if (session == null) return {
1364
1428
  resource: null,
1365
1429
  result: "network_error",
@@ -1367,10 +1431,26 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1367
1431
  };
1368
1432
  let hop;
1369
1433
  try {
1370
- hop = await fetchHop(session, url, options);
1434
+ if (signal.aborted) return {
1435
+ resource: null,
1436
+ result: "network_error",
1437
+ remoteHost
1438
+ };
1439
+ hop = await fetchHopUntilAbort(session, url, options, signal);
1371
1440
  } finally {
1372
- await session.close();
1441
+ if (signal.aborted) session.close().catch((error) => {
1442
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
1443
+ url: url.href,
1444
+ error
1445
+ });
1446
+ });
1447
+ else await session.close();
1373
1448
  }
1449
+ if (signal.aborted) return {
1450
+ resource: null,
1451
+ result: "network_error",
1452
+ remoteHost
1453
+ };
1374
1454
  if ("outcome" in hop) return hop.outcome;
1375
1455
  redirected++;
1376
1456
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -1413,13 +1493,36 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1413
1493
  url = redirectedUrl;
1414
1494
  }
1415
1495
  }
1496
+ /** Lets the session close even when a custom fetch or body ignores abort. */
1497
+ async function fetchHopUntilAbort(session, url, options, signal) {
1498
+ const fetching = fetchHop(session, url, options, signal);
1499
+ let onAbort;
1500
+ const aborted = new Promise((resolve) => {
1501
+ const outcome = {
1502
+ resource: null,
1503
+ result: "network_error",
1504
+ remoteHost: url.host
1505
+ };
1506
+ if (signal.aborted) resolve({ outcome });
1507
+ else {
1508
+ onAbort = () => resolve({ outcome });
1509
+ signal.addEventListener("abort", onAbort, { once: true });
1510
+ }
1511
+ });
1512
+ try {
1513
+ return await Promise.race([fetching, aborted]);
1514
+ } finally {
1515
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
1516
+ fetching.catch(() => {});
1517
+ }
1518
+ }
1416
1519
  /**
1417
1520
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
1418
1521
  * or an aborted lookup yields `null` instead of an error.
1419
1522
  */
1420
1523
  async function openSession(url, openHop, signal) {
1421
1524
  try {
1422
- return await openHop(url.href);
1525
+ return await openHop(url.href, signal);
1423
1526
  } catch (e) {
1424
1527
  if (e instanceof UrlError) {
1425
1528
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -1443,7 +1546,7 @@ async function openSession(url, openHop, signal) {
1443
1546
  * Fetches a hop with the given session, and consumes the response body or
1444
1547
  * starts cancelling it before returning. The caller closes the session.
1445
1548
  */
1446
- async function fetchHop(session, url, options) {
1549
+ async function fetchHop(session, url, options, signal) {
1447
1550
  let response;
1448
1551
  try {
1449
1552
  response = await session.fetch(url, {
@@ -1452,7 +1555,7 @@ async function fetchHop(session, url, options) {
1452
1555
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
1453
1556
  },
1454
1557
  redirect: "manual",
1455
- signal: options.signal
1558
+ signal
1456
1559
  });
1457
1560
  } catch (error) {
1458
1561
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -1488,7 +1591,7 @@ async function fetchHop(session, url, options) {
1488
1591
  }
1489
1592
  try {
1490
1593
  return { outcome: {
1491
- resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
1594
+ resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)),
1492
1595
  result: "found",
1493
1596
  statusCode: response.status,
1494
1597
  remoteHost: url.host
@@ -2379,5 +2482,150 @@ test$1("lookupWebFinger() records network_error for rejected hop addresses", asy
2379
2482
  deepStrictEqual("http.response.status_code" in counter.attributes, false);
2380
2483
  }
2381
2484
  });
2485
+ test("lookupWebFinger() caller abort releases a stalled session open", async () => {
2486
+ const controller = new AbortController();
2487
+ let finishOpen;
2488
+ let closed = false;
2489
+ const opening = new Promise((resolve) => {
2490
+ finishOpen = resolve;
2491
+ });
2492
+ const lookup = lookupResourceWithDependencies("acct:alice@example.com", { signal: controller.signal }, { openHop: () => opening });
2493
+ controller.abort();
2494
+ deepStrictEqual(await settleWithin(lookup, 1e3), null);
2495
+ finishOpen({
2496
+ url: new URL("https://example.com"),
2497
+ fetch: () => {
2498
+ throw new Error("fetch after abort");
2499
+ },
2500
+ close: () => {
2501
+ closed = true;
2502
+ return Promise.resolve();
2503
+ }
2504
+ });
2505
+ await Promise.resolve();
2506
+ await Promise.resolve();
2507
+ ok(closed);
2508
+ });
2509
+ test("lookupWebFinger() deadline covers session opening", async () => {
2510
+ const [meterProvider, recorder] = createTestMeterProvider();
2511
+ deepStrictEqual(await settleWithin(lookupWebFingerWithDependencies("acct:alice@example.com", { meterProvider }, {
2512
+ timeoutMs: 20,
2513
+ openHop: () => new Promise(() => {})
2514
+ }), 1e3), null);
2515
+ const measurement = recorder.getMeasurement("webfinger.lookup");
2516
+ ok(measurement != null);
2517
+ deepStrictEqual(measurement.attributes["webfinger.lookup.result"], "network_error");
2518
+ deepStrictEqual(measurement.attributes["activitypub.remote.host"], "example.com");
2519
+ });
2520
+ test("lookupWebFinger() shares one deadline across redirects", async () => {
2521
+ const descriptor = {
2522
+ subject: "acct:alice@example.com",
2523
+ links: []
2524
+ };
2525
+ const pending = [];
2526
+ deepStrictEqual(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2527
+ timeoutMs: 100,
2528
+ openHop: (url) => Promise.resolve({
2529
+ url: new URL(url),
2530
+ fetch: () => {
2531
+ const response = new Promise((resolve) => {
2532
+ setTimeout(() => {
2533
+ resolve(url.includes("/final") ? new Response(JSON.stringify(descriptor)) : new Response(null, {
2534
+ status: 302,
2535
+ headers: { Location: "/final" }
2536
+ }));
2537
+ }, 60);
2538
+ });
2539
+ pending.push(response);
2540
+ return response;
2541
+ },
2542
+ close: () => Promise.resolve()
2543
+ })
2544
+ }), 1e3), null);
2545
+ await Promise.all(pending);
2546
+ });
2547
+ test("lookupWebFinger() caller signal cannot extend its deadline", async () => {
2548
+ const signal = AbortSignal.timeout(5e3);
2549
+ let reason;
2550
+ deepStrictEqual(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", { signal }, {
2551
+ timeoutMs: 50,
2552
+ openHop: (_url, effectiveSignal) => {
2553
+ effectiveSignal?.addEventListener("abort", () => {
2554
+ reason = effectiveSignal.reason;
2555
+ }, { once: true });
2556
+ return new Promise(() => {});
2557
+ }
2558
+ }), 1e3), null);
2559
+ ok(!signal.aborted);
2560
+ ok(reason instanceof DOMException);
2561
+ deepStrictEqual(reason.name, "TimeoutError");
2562
+ });
2563
+ test("lookupWebFinger() deadline covers response headers", async () => {
2564
+ let closed = false;
2565
+ let fetchSignal;
2566
+ let fetchAborted = false;
2567
+ deepStrictEqual(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2568
+ timeoutMs: 20,
2569
+ openHop: () => Promise.resolve({
2570
+ url: new URL("https://example.com"),
2571
+ fetch: (_input, init) => {
2572
+ fetchSignal = init?.signal;
2573
+ fetchSignal?.addEventListener("abort", () => {
2574
+ fetchAborted = true;
2575
+ }, { once: true });
2576
+ return new Promise(() => {});
2577
+ },
2578
+ close: () => {
2579
+ closed = true;
2580
+ return Promise.resolve();
2581
+ }
2582
+ })
2583
+ }), 1e3), null);
2584
+ ok(fetchSignal?.aborted);
2585
+ ok(fetchAborted);
2586
+ deepStrictEqual(fetchSignal.reason.name, "TimeoutError");
2587
+ await Promise.resolve();
2588
+ ok(closed);
2589
+ });
2590
+ test("lookupWebFinger() discards completed JSON when body stalls", async () => {
2591
+ const descriptor = {
2592
+ subject: "acct:alice@example.com",
2593
+ links: []
2594
+ };
2595
+ let cancelled;
2596
+ const cancellation = new Promise((resolve) => {
2597
+ cancelled = resolve;
2598
+ });
2599
+ deepStrictEqual(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2600
+ timeoutMs: 20,
2601
+ openHop: () => Promise.resolve({
2602
+ url: new URL("https://example.com"),
2603
+ fetch: () => Promise.resolve(new Response(new ReadableStream({
2604
+ start(controller) {
2605
+ controller.enqueue(new TextEncoder().encode(JSON.stringify(descriptor)));
2606
+ },
2607
+ cancel() {
2608
+ cancelled();
2609
+ }
2610
+ }))),
2611
+ close: async () => {}
2612
+ })
2613
+ }), 1e3), null);
2614
+ await settleWithin(cancellation, 1e3);
2615
+ });
2616
+ test("lookupWebFinger() accepts a response before its deadline", async () => {
2617
+ const descriptor = {
2618
+ subject: "acct:alice@example.com",
2619
+ links: []
2620
+ };
2621
+ deepStrictEqual(await lookupResourceWithDependencies("acct:alice@example.com", {}, {
2622
+ timeoutMs: 1e3,
2623
+ openHop: () => Promise.resolve({
2624
+ url: new URL("https://example.com"),
2625
+ fetch: () => Promise.resolve(new Response(JSON.stringify(descriptor))),
2626
+ close: async () => {}
2627
+ })
2628
+ }), descriptor);
2629
+ });
2382
2630
  //#endregion
2383
2631
  export {};
package/dist/mod.cjs CHANGED
@@ -5,7 +5,7 @@ let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  //#region deno.json
7
7
  var name = "@fedify/webfinger";
8
- var version = "2.4.6-dev.2837+bb303087";
8
+ var version = "2.4.6";
9
9
  //#endregion
10
10
  //#region src/body.ts
11
11
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -28,13 +28,18 @@ function validateBodySizeLimit(maxBytes) {
28
28
  * @param message The response or request to read.
29
29
  * @param maxBytes The maximum number of decoded bytes to read.
30
30
  * @param url The URL to include in errors and logs.
31
+ * @param signal The signal that cancels an in-progress body read.
31
32
  * @returns The decoded body text.
32
33
  * @throws {BodyTooLargeError} If the body exceeds the limit.
33
34
  * @internal
34
35
  */
35
- async function readBoundedText(message, maxBytes, url) {
36
+ async function readBoundedText(message, maxBytes, url, signal) {
36
37
  validateBodySizeLimit(maxBytes);
37
38
  const reader = message.body?.getReader();
39
+ const cancelOnAbort = () => {
40
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
41
+ };
42
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
38
43
  const tooLarge = () => {
39
44
  (0, _logtape_logtape.getLogger)([
40
45
  "fedify",
@@ -47,6 +52,7 @@ async function readBoundedText(message, maxBytes, url) {
47
52
  throw new BodyTooLargeError(url, maxBytes);
48
53
  };
49
54
  try {
55
+ signal?.throwIfAborted();
50
56
  const length = message.headers.get("Content-Length");
51
57
  const encoding = message.headers.get("Content-Encoding");
52
58
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -54,6 +60,7 @@ async function readBoundedText(message, maxBytes, url) {
54
60
  let size = 0;
55
61
  const textReader = new ReadableStream({ async pull(controller) {
56
62
  const { done, value } = await reader.read();
63
+ signal?.throwIfAborted();
57
64
  if (done) {
58
65
  controller.close();
59
66
  return;
@@ -66,9 +73,11 @@ async function readBoundedText(message, maxBytes, url) {
66
73
  const chunks = [];
67
74
  while (true) {
68
75
  const { done, value } = await textReader.read();
76
+ signal?.throwIfAborted();
69
77
  if (done) break;
70
78
  chunks.push(value);
71
79
  }
80
+ signal?.throwIfAborted();
72
81
  return chunks.join("");
73
82
  } finally {
74
83
  textReader.releaseLock();
@@ -77,6 +86,7 @@ async function readBoundedText(message, maxBytes, url) {
77
86
  if (reader != null) reader.cancel(error).catch(() => {});
78
87
  throw error;
79
88
  } finally {
89
+ signal?.removeEventListener("abort", cancelOnAbort);
80
90
  reader?.releaseLock();
81
91
  }
82
92
  }
@@ -88,6 +98,7 @@ const logger = (0, _logtape_logtape.getLogger)([
88
98
  "lookup"
89
99
  ]);
90
100
  const DEFAULT_MAX_REDIRECTION = 5;
101
+ const DEFAULT_TIMEOUT_MS = 1e4;
91
102
  /**
92
103
  * Looks up a WebFinger resource, opening a fetch session per hop. This is
93
104
  * the implementation of {@link lookupWebFinger}, which is not exported from
@@ -121,14 +132,67 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
121
132
  protocol = resource.protocol;
122
133
  server = resource.host;
123
134
  }
124
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
135
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
125
136
  url.searchParams.set("resource", resource.href);
126
- 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 }));
137
+ const controller = new AbortController();
138
+ const signal = controller.signal;
139
+ let timedOut = false;
140
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
141
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
142
+ const timeout = setTimeout(() => {
143
+ timedOut = true;
144
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
145
+ }, timeoutMs);
146
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
147
+ if (options.signal?.aborted) abortFromCaller();
148
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
149
+ let stopWaiting = () => {};
150
+ const cancelledOutcome = () => ({
151
+ resource: null,
152
+ result: "network_error",
153
+ remoteHost: url.host
154
+ });
155
+ const aborted = new Promise((resolve) => {
156
+ if (signal.aborted) resolve(cancelledOutcome());
157
+ else {
158
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
159
+ const onAbort = () => resolve(cancelledOutcome());
160
+ signal.addEventListener("abort", onAbort, { once: true });
161
+ }
162
+ });
163
+ const work = lookupHops(url, options, deps.openHop ?? ((hopUrl, hopSignal) => options.allowPrivateAddress === true ? (0, _fedify_vocab_runtime_internal.openDirectFetch)(hopUrl) : (0, _fedify_vocab_runtime_internal.openPublicFetch)(hopUrl, { signal: hopSignal })), signal);
164
+ try {
165
+ const result = await Promise.race([work, aborted]);
166
+ if (signal.aborted) {
167
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
168
+ url: url.href,
169
+ timeoutMs
170
+ });
171
+ return cancelledOutcome();
172
+ }
173
+ return result;
174
+ } catch (error) {
175
+ if (signal.aborted) return cancelledOutcome();
176
+ throw error;
177
+ } finally {
178
+ clearTimeout(timeout);
179
+ stopWaiting();
180
+ options.signal?.removeEventListener("abort", abortFromCaller);
181
+ work.catch(() => {});
182
+ }
183
+ }
184
+ async function lookupHops(initialUrl, options, openHop, signal) {
185
+ let url = initialUrl;
127
186
  let redirected = 0;
128
187
  while (true) {
188
+ if (signal.aborted) return {
189
+ resource: null,
190
+ result: "network_error",
191
+ remoteHost: url.host
192
+ };
129
193
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
130
194
  const remoteHost = url.host;
131
- const session = await openSession(url, openHop, options.signal);
195
+ const session = await openSession(url, openHop, signal);
132
196
  if (session == null) return {
133
197
  resource: null,
134
198
  result: "network_error",
@@ -136,10 +200,26 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
136
200
  };
137
201
  let hop;
138
202
  try {
139
- hop = await fetchHop(session, url, options);
203
+ if (signal.aborted) return {
204
+ resource: null,
205
+ result: "network_error",
206
+ remoteHost
207
+ };
208
+ hop = await fetchHopUntilAbort(session, url, options, signal);
140
209
  } finally {
141
- await session.close();
210
+ if (signal.aborted) session.close().catch((error) => {
211
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
212
+ url: url.href,
213
+ error
214
+ });
215
+ });
216
+ else await session.close();
142
217
  }
218
+ if (signal.aborted) return {
219
+ resource: null,
220
+ result: "network_error",
221
+ remoteHost
222
+ };
143
223
  if ("outcome" in hop) return hop.outcome;
144
224
  redirected++;
145
225
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -182,13 +262,36 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
182
262
  url = redirectedUrl;
183
263
  }
184
264
  }
265
+ /** Lets the session close even when a custom fetch or body ignores abort. */
266
+ async function fetchHopUntilAbort(session, url, options, signal) {
267
+ const fetching = fetchHop(session, url, options, signal);
268
+ let onAbort;
269
+ const aborted = new Promise((resolve) => {
270
+ const outcome = {
271
+ resource: null,
272
+ result: "network_error",
273
+ remoteHost: url.host
274
+ };
275
+ if (signal.aborted) resolve({ outcome });
276
+ else {
277
+ onAbort = () => resolve({ outcome });
278
+ signal.addEventListener("abort", onAbort, { once: true });
279
+ }
280
+ });
281
+ try {
282
+ return await Promise.race([fetching, aborted]);
283
+ } finally {
284
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
285
+ fetching.catch(() => {});
286
+ }
287
+ }
185
288
  /**
186
289
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
187
290
  * or an aborted lookup yields `null` instead of an error.
188
291
  */
189
292
  async function openSession(url, openHop, signal) {
190
293
  try {
191
- return await openHop(url.href);
294
+ return await openHop(url.href, signal);
192
295
  } catch (e) {
193
296
  if (e instanceof _fedify_vocab_runtime.UrlError) {
194
297
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -212,7 +315,7 @@ async function openSession(url, openHop, signal) {
212
315
  * Fetches a hop with the given session, and consumes the response body or
213
316
  * starts cancelling it before returning. The caller closes the session.
214
317
  */
215
- async function fetchHop(session, url, options) {
318
+ async function fetchHop(session, url, options, signal) {
216
319
  let response;
217
320
  try {
218
321
  response = await session.fetch(url, {
@@ -221,7 +324,7 @@ async function fetchHop(session, url, options) {
221
324
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
222
325
  },
223
326
  redirect: "manual",
224
- signal: options.signal
327
+ signal
225
328
  });
226
329
  } catch (error) {
227
330
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -257,7 +360,7 @@ async function fetchHop(session, url, options) {
257
360
  }
258
361
  try {
259
362
  return { outcome: {
260
- resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
363
+ resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)),
261
364
  result: "found",
262
365
  statusCode: response.status,
263
366
  remoteHost: url.host
package/dist/mod.d.cts CHANGED
@@ -72,7 +72,9 @@ interface LookupWebFingerDependencies {
72
72
  * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
73
73
  * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
74
74
  */
75
- readonly openHop?: (url: string) => Promise<PublicFetchSession>;
75
+ readonly openHop?: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>;
76
+ /** Overrides the lookup deadline for internal tests. */
77
+ readonly timeoutMs?: number;
76
78
  }
77
79
  //#endregion
78
80
  //#region src/lookup.d.ts
@@ -146,7 +148,8 @@ interface LookupWebFingerOptions {
146
148
  */
147
149
  meterProvider?: MeterProvider;
148
150
  /**
149
- * AbortSignal for cancelling the request.
151
+ * `AbortSignal` for cancelling the lookup sooner than its default 10-second
152
+ * deadline. A signal cannot extend that deadline.
150
153
  * @since 1.8.0
151
154
  */
152
155
  signal?: AbortSignal;
package/dist/mod.d.ts CHANGED
@@ -72,7 +72,9 @@ interface LookupWebFingerDependencies {
72
72
  * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
73
73
  * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
74
74
  */
75
- readonly openHop?: (url: string) => Promise<PublicFetchSession>;
75
+ readonly openHop?: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>;
76
+ /** Overrides the lookup deadline for internal tests. */
77
+ readonly timeoutMs?: number;
76
78
  }
77
79
  //#endregion
78
80
  //#region src/lookup.d.ts
@@ -146,7 +148,8 @@ interface LookupWebFingerOptions {
146
148
  */
147
149
  meterProvider?: MeterProvider;
148
150
  /**
149
- * AbortSignal for cancelling the request.
151
+ * `AbortSignal` for cancelling the lookup sooner than its default 10-second
152
+ * deadline. A signal cannot extend that deadline.
150
153
  * @since 1.8.0
151
154
  */
152
155
  signal?: AbortSignal;