@fedify/webfinger 2.3.16-dev.2845 → 2.3.16

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