@fedify/webfinger 2.4.6-dev.2628 → 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.
package/README.md CHANGED
@@ -96,11 +96,14 @@ const result = await lookupWebFinger("acct:alice@example.com", {
96
96
  // Maximum redirects to follow (default: 5)
97
97
  maxRedirection: 3,
98
98
 
99
- // AbortSignal for cancellation
99
+ // Cancel sooner than the default 10-second lookup deadline
100
100
  signal: AbortSignal.timeout(5000),
101
101
  });
102
102
  ~~~~
103
103
 
104
+ Each lookup has a 10-second deadline across DNS resolution, redirects, and
105
+ response reading. A supplied signal can end it sooner but cannot extend it.
106
+
104
107
 
105
108
  API
106
109
  ---
package/deno.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/webfinger",
3
- "version": "2.4.6-dev.2628+2a78382f",
3
+ "version": "2.4.6",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": "./src/mod.ts"
@@ -1237,7 +1237,7 @@ var esm_default = new class FetchMock {
1237
1237
  //#endregion
1238
1238
  //#region deno.json
1239
1239
  var name = "@fedify/webfinger";
1240
- var version = "2.4.6-dev.2628+2a78382f";
1240
+ var version = "2.4.6";
1241
1241
  //#endregion
1242
1242
  //#region src/body.ts
1243
1243
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -1260,13 +1260,18 @@ function validateBodySizeLimit(maxBytes) {
1260
1260
  * @param message The response or request to read.
1261
1261
  * @param maxBytes The maximum number of decoded bytes to read.
1262
1262
  * @param url The URL to include in errors and logs.
1263
+ * @param signal The signal that cancels an in-progress body read.
1263
1264
  * @returns The decoded body text.
1264
1265
  * @throws {BodyTooLargeError} If the body exceeds the limit.
1265
1266
  * @internal
1266
1267
  */
1267
- async function readBoundedText(message, maxBytes, url) {
1268
+ async function readBoundedText(message, maxBytes, url, signal) {
1268
1269
  validateBodySizeLimit(maxBytes);
1269
1270
  const reader = message.body?.getReader();
1271
+ const cancelOnAbort = () => {
1272
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
1273
+ };
1274
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
1270
1275
  const tooLarge = () => {
1271
1276
  (0, _logtape_logtape.getLogger)([
1272
1277
  "fedify",
@@ -1279,6 +1284,7 @@ async function readBoundedText(message, maxBytes, url) {
1279
1284
  throw new BodyTooLargeError(url, maxBytes);
1280
1285
  };
1281
1286
  try {
1287
+ signal?.throwIfAborted();
1282
1288
  const length = message.headers.get("Content-Length");
1283
1289
  const encoding = message.headers.get("Content-Encoding");
1284
1290
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -1286,6 +1292,7 @@ async function readBoundedText(message, maxBytes, url) {
1286
1292
  let size = 0;
1287
1293
  const textReader = new ReadableStream({ async pull(controller) {
1288
1294
  const { done, value } = await reader.read();
1295
+ signal?.throwIfAborted();
1289
1296
  if (done) {
1290
1297
  controller.close();
1291
1298
  return;
@@ -1298,9 +1305,11 @@ async function readBoundedText(message, maxBytes, url) {
1298
1305
  const chunks = [];
1299
1306
  while (true) {
1300
1307
  const { done, value } = await textReader.read();
1308
+ signal?.throwIfAborted();
1301
1309
  if (done) break;
1302
1310
  chunks.push(value);
1303
1311
  }
1312
+ signal?.throwIfAborted();
1304
1313
  return chunks.join("");
1305
1314
  } finally {
1306
1315
  textReader.releaseLock();
@@ -1309,6 +1318,7 @@ async function readBoundedText(message, maxBytes, url) {
1309
1318
  if (reader != null) reader.cancel(error).catch(() => {});
1310
1319
  throw error;
1311
1320
  } finally {
1321
+ signal?.removeEventListener("abort", cancelOnAbort);
1312
1322
  reader?.releaseLock();
1313
1323
  }
1314
1324
  }
@@ -1320,6 +1330,7 @@ const logger = (0, _logtape_logtape.getLogger)([
1320
1330
  "lookup"
1321
1331
  ]);
1322
1332
  const DEFAULT_MAX_REDIRECTION = 5;
1333
+ const DEFAULT_TIMEOUT_MS = 1e4;
1323
1334
  /**
1324
1335
  * Looks up a WebFinger resource, opening a fetch session per hop. This is
1325
1336
  * the implementation of {@link lookupWebFinger}, which is not exported from
@@ -1353,14 +1364,67 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1353
1364
  protocol = resource.protocol;
1354
1365
  server = resource.host;
1355
1366
  }
1356
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1367
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1357
1368
  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 }));
1369
+ const controller = new AbortController();
1370
+ const signal = controller.signal;
1371
+ let timedOut = false;
1372
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1373
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
1374
+ const timeout = setTimeout(() => {
1375
+ timedOut = true;
1376
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
1377
+ }, timeoutMs);
1378
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
1379
+ if (options.signal?.aborted) abortFromCaller();
1380
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
1381
+ let stopWaiting = () => {};
1382
+ const cancelledOutcome = () => ({
1383
+ resource: null,
1384
+ result: "network_error",
1385
+ remoteHost: url.host
1386
+ });
1387
+ const aborted = new Promise((resolve) => {
1388
+ if (signal.aborted) resolve(cancelledOutcome());
1389
+ else {
1390
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
1391
+ const onAbort = () => resolve(cancelledOutcome());
1392
+ signal.addEventListener("abort", onAbort, { once: true });
1393
+ }
1394
+ });
1395
+ 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);
1396
+ try {
1397
+ const result = await Promise.race([work, aborted]);
1398
+ if (signal.aborted) {
1399
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
1400
+ url: url.href,
1401
+ timeoutMs
1402
+ });
1403
+ return cancelledOutcome();
1404
+ }
1405
+ return result;
1406
+ } catch (error) {
1407
+ if (signal.aborted) return cancelledOutcome();
1408
+ throw error;
1409
+ } finally {
1410
+ clearTimeout(timeout);
1411
+ stopWaiting();
1412
+ options.signal?.removeEventListener("abort", abortFromCaller);
1413
+ work.catch(() => {});
1414
+ }
1415
+ }
1416
+ async function lookupHops(initialUrl, options, openHop, signal) {
1417
+ let url = initialUrl;
1359
1418
  let redirected = 0;
1360
1419
  while (true) {
1420
+ if (signal.aborted) return {
1421
+ resource: null,
1422
+ result: "network_error",
1423
+ remoteHost: url.host
1424
+ };
1361
1425
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
1362
1426
  const remoteHost = url.host;
1363
- const session = await openSession(url, openHop, options.signal);
1427
+ const session = await openSession(url, openHop, signal);
1364
1428
  if (session == null) return {
1365
1429
  resource: null,
1366
1430
  result: "network_error",
@@ -1368,10 +1432,26 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1368
1432
  };
1369
1433
  let hop;
1370
1434
  try {
1371
- hop = await fetchHop(session, url, options);
1435
+ if (signal.aborted) return {
1436
+ resource: null,
1437
+ result: "network_error",
1438
+ remoteHost
1439
+ };
1440
+ hop = await fetchHopUntilAbort(session, url, options, signal);
1372
1441
  } finally {
1373
- await session.close();
1442
+ if (signal.aborted) session.close().catch((error) => {
1443
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
1444
+ url: url.href,
1445
+ error
1446
+ });
1447
+ });
1448
+ else await session.close();
1374
1449
  }
1450
+ if (signal.aborted) return {
1451
+ resource: null,
1452
+ result: "network_error",
1453
+ remoteHost
1454
+ };
1375
1455
  if ("outcome" in hop) return hop.outcome;
1376
1456
  redirected++;
1377
1457
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -1414,13 +1494,36 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1414
1494
  url = redirectedUrl;
1415
1495
  }
1416
1496
  }
1497
+ /** Lets the session close even when a custom fetch or body ignores abort. */
1498
+ async function fetchHopUntilAbort(session, url, options, signal) {
1499
+ const fetching = fetchHop(session, url, options, signal);
1500
+ let onAbort;
1501
+ const aborted = new Promise((resolve) => {
1502
+ const outcome = {
1503
+ resource: null,
1504
+ result: "network_error",
1505
+ remoteHost: url.host
1506
+ };
1507
+ if (signal.aborted) resolve({ outcome });
1508
+ else {
1509
+ onAbort = () => resolve({ outcome });
1510
+ signal.addEventListener("abort", onAbort, { once: true });
1511
+ }
1512
+ });
1513
+ try {
1514
+ return await Promise.race([fetching, aborted]);
1515
+ } finally {
1516
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
1517
+ fetching.catch(() => {});
1518
+ }
1519
+ }
1417
1520
  /**
1418
1521
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
1419
1522
  * or an aborted lookup yields `null` instead of an error.
1420
1523
  */
1421
1524
  async function openSession(url, openHop, signal) {
1422
1525
  try {
1423
- return await openHop(url.href);
1526
+ return await openHop(url.href, signal);
1424
1527
  } catch (e) {
1425
1528
  if (e instanceof _fedify_vocab_runtime.UrlError) {
1426
1529
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -1444,7 +1547,7 @@ async function openSession(url, openHop, signal) {
1444
1547
  * Fetches a hop with the given session, and consumes the response body or
1445
1548
  * starts cancelling it before returning. The caller closes the session.
1446
1549
  */
1447
- async function fetchHop(session, url, options) {
1550
+ async function fetchHop(session, url, options, signal) {
1448
1551
  let response;
1449
1552
  try {
1450
1553
  response = await session.fetch(url, {
@@ -1453,7 +1556,7 @@ async function fetchHop(session, url, options) {
1453
1556
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
1454
1557
  },
1455
1558
  redirect: "manual",
1456
- signal: options.signal
1559
+ signal
1457
1560
  });
1458
1561
  } catch (error) {
1459
1562
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -1489,7 +1592,7 @@ async function fetchHop(session, url, options) {
1489
1592
  }
1490
1593
  try {
1491
1594
  return { outcome: {
1492
- resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
1595
+ resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)),
1493
1596
  result: "found",
1494
1597
  statusCode: response.status,
1495
1598
  remoteHost: url.host
@@ -2380,4 +2483,149 @@ function neverCancellableResponse(init) {
2380
2483
  (0, node_assert_strict.deepStrictEqual)("http.response.status_code" in counter.attributes, false);
2381
2484
  }
2382
2485
  });
2486
+ (0, _fedify_fixture.test)("lookupWebFinger() caller abort releases a stalled session open", async () => {
2487
+ const controller = new AbortController();
2488
+ let finishOpen;
2489
+ let closed = false;
2490
+ const opening = new Promise((resolve) => {
2491
+ finishOpen = resolve;
2492
+ });
2493
+ const lookup = lookupResourceWithDependencies("acct:alice@example.com", { signal: controller.signal }, { openHop: () => opening });
2494
+ controller.abort();
2495
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookup, 1e3), null);
2496
+ finishOpen({
2497
+ url: new URL("https://example.com"),
2498
+ fetch: () => {
2499
+ throw new Error("fetch after abort");
2500
+ },
2501
+ close: () => {
2502
+ closed = true;
2503
+ return Promise.resolve();
2504
+ }
2505
+ });
2506
+ await Promise.resolve();
2507
+ await Promise.resolve();
2508
+ (0, node_assert_strict.ok)(closed);
2509
+ });
2510
+ (0, _fedify_fixture.test)("lookupWebFinger() deadline covers session opening", async () => {
2511
+ const [meterProvider, recorder] = (0, _fedify_fixture.createTestMeterProvider)();
2512
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerWithDependencies("acct:alice@example.com", { meterProvider }, {
2513
+ timeoutMs: 20,
2514
+ openHop: () => new Promise(() => {})
2515
+ }), 1e3), null);
2516
+ const measurement = recorder.getMeasurement("webfinger.lookup");
2517
+ (0, node_assert_strict.ok)(measurement != null);
2518
+ (0, node_assert_strict.deepStrictEqual)(measurement.attributes["webfinger.lookup.result"], "network_error");
2519
+ (0, node_assert_strict.deepStrictEqual)(measurement.attributes["activitypub.remote.host"], "example.com");
2520
+ });
2521
+ (0, _fedify_fixture.test)("lookupWebFinger() shares one deadline across redirects", async () => {
2522
+ const descriptor = {
2523
+ subject: "acct:alice@example.com",
2524
+ links: []
2525
+ };
2526
+ const pending = [];
2527
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2528
+ timeoutMs: 100,
2529
+ openHop: (url) => Promise.resolve({
2530
+ url: new URL(url),
2531
+ fetch: () => {
2532
+ const response = new Promise((resolve) => {
2533
+ setTimeout(() => {
2534
+ resolve(url.includes("/final") ? new Response(JSON.stringify(descriptor)) : new Response(null, {
2535
+ status: 302,
2536
+ headers: { Location: "/final" }
2537
+ }));
2538
+ }, 60);
2539
+ });
2540
+ pending.push(response);
2541
+ return response;
2542
+ },
2543
+ close: () => Promise.resolve()
2544
+ })
2545
+ }), 1e3), null);
2546
+ await Promise.all(pending);
2547
+ });
2548
+ (0, _fedify_fixture.test)("lookupWebFinger() caller signal cannot extend its deadline", async () => {
2549
+ const signal = AbortSignal.timeout(5e3);
2550
+ let reason;
2551
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", { signal }, {
2552
+ timeoutMs: 50,
2553
+ openHop: (_url, effectiveSignal) => {
2554
+ effectiveSignal?.addEventListener("abort", () => {
2555
+ reason = effectiveSignal.reason;
2556
+ }, { once: true });
2557
+ return new Promise(() => {});
2558
+ }
2559
+ }), 1e3), null);
2560
+ (0, node_assert_strict.ok)(!signal.aborted);
2561
+ (0, node_assert_strict.ok)(reason instanceof DOMException);
2562
+ (0, node_assert_strict.deepStrictEqual)(reason.name, "TimeoutError");
2563
+ });
2564
+ (0, _fedify_fixture.test)("lookupWebFinger() deadline covers response headers", async () => {
2565
+ let closed = false;
2566
+ let fetchSignal;
2567
+ let fetchAborted = false;
2568
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2569
+ timeoutMs: 20,
2570
+ openHop: () => Promise.resolve({
2571
+ url: new URL("https://example.com"),
2572
+ fetch: (_input, init) => {
2573
+ fetchSignal = init?.signal;
2574
+ fetchSignal?.addEventListener("abort", () => {
2575
+ fetchAborted = true;
2576
+ }, { once: true });
2577
+ return new Promise(() => {});
2578
+ },
2579
+ close: () => {
2580
+ closed = true;
2581
+ return Promise.resolve();
2582
+ }
2583
+ })
2584
+ }), 1e3), null);
2585
+ (0, node_assert_strict.ok)(fetchSignal?.aborted);
2586
+ (0, node_assert_strict.ok)(fetchAborted);
2587
+ (0, node_assert_strict.deepStrictEqual)(fetchSignal.reason.name, "TimeoutError");
2588
+ await Promise.resolve();
2589
+ (0, node_assert_strict.ok)(closed);
2590
+ });
2591
+ (0, _fedify_fixture.test)("lookupWebFinger() discards completed JSON when body stalls", async () => {
2592
+ const descriptor = {
2593
+ subject: "acct:alice@example.com",
2594
+ links: []
2595
+ };
2596
+ let cancelled;
2597
+ const cancellation = new Promise((resolve) => {
2598
+ cancelled = resolve;
2599
+ });
2600
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupResourceWithDependencies("acct:alice@example.com", {}, {
2601
+ timeoutMs: 20,
2602
+ openHop: () => Promise.resolve({
2603
+ url: new URL("https://example.com"),
2604
+ fetch: () => Promise.resolve(new Response(new ReadableStream({
2605
+ start(controller) {
2606
+ controller.enqueue(new TextEncoder().encode(JSON.stringify(descriptor)));
2607
+ },
2608
+ cancel() {
2609
+ cancelled();
2610
+ }
2611
+ }))),
2612
+ close: async () => {}
2613
+ })
2614
+ }), 1e3), null);
2615
+ await settleWithin(cancellation, 1e3);
2616
+ });
2617
+ (0, _fedify_fixture.test)("lookupWebFinger() accepts a response before its deadline", async () => {
2618
+ const descriptor = {
2619
+ subject: "acct:alice@example.com",
2620
+ links: []
2621
+ };
2622
+ (0, node_assert_strict.deepStrictEqual)(await lookupResourceWithDependencies("acct:alice@example.com", {}, {
2623
+ timeoutMs: 1e3,
2624
+ openHop: () => Promise.resolve({
2625
+ url: new URL("https://example.com"),
2626
+ fetch: () => Promise.resolve(new Response(JSON.stringify(descriptor))),
2627
+ close: async () => {}
2628
+ })
2629
+ }), descriptor);
2630
+ });
2383
2631
  //#endregion