@fedify/webfinger 2.0.36-dev.2779 → 2.0.36-dev.2842

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.0.36-dev.2779+68f8f486",
3
+ "version": "2.0.36-dev.2842+d35af543",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": "./src/mod.ts"
@@ -1229,7 +1229,7 @@ var esm_default = new class FetchMock {
1229
1229
  //#endregion
1230
1230
  //#region deno.json
1231
1231
  var name = "@fedify/webfinger";
1232
- var version = "2.0.36-dev.2779+68f8f486";
1232
+ var version = "2.0.36-dev.2842+d35af543";
1233
1233
  //#endregion
1234
1234
  //#region src/body.ts
1235
1235
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -1252,13 +1252,18 @@ function validateBodySizeLimit(maxBytes) {
1252
1252
  * @param message The response or request to read.
1253
1253
  * @param maxBytes The maximum number of decoded bytes to read.
1254
1254
  * @param url The URL to include in errors and logs.
1255
+ * @param signal The signal that cancels an in-progress body read.
1255
1256
  * @returns The decoded body text.
1256
1257
  * @throws {BodyTooLargeError} If the body exceeds the limit.
1257
1258
  * @internal
1258
1259
  */
1259
- async function readBoundedText(message, maxBytes, url) {
1260
+ async function readBoundedText(message, maxBytes, url, signal) {
1260
1261
  validateBodySizeLimit(maxBytes);
1261
1262
  const reader = message.body?.getReader();
1263
+ const cancelOnAbort = () => {
1264
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
1265
+ };
1266
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
1262
1267
  const tooLarge = () => {
1263
1268
  (0, _logtape_logtape.getLogger)([
1264
1269
  "fedify",
@@ -1271,6 +1276,7 @@ async function readBoundedText(message, maxBytes, url) {
1271
1276
  throw new BodyTooLargeError(url, maxBytes);
1272
1277
  };
1273
1278
  try {
1279
+ signal?.throwIfAborted();
1274
1280
  const length = message.headers.get("Content-Length");
1275
1281
  const encoding = message.headers.get("Content-Encoding");
1276
1282
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -1278,6 +1284,7 @@ async function readBoundedText(message, maxBytes, url) {
1278
1284
  let size = 0;
1279
1285
  const textReader = new ReadableStream({ async pull(controller) {
1280
1286
  const { done, value } = await reader.read();
1287
+ signal?.throwIfAborted();
1281
1288
  if (done) {
1282
1289
  controller.close();
1283
1290
  return;
@@ -1290,9 +1297,11 @@ async function readBoundedText(message, maxBytes, url) {
1290
1297
  const chunks = [];
1291
1298
  while (true) {
1292
1299
  const { done, value } = await textReader.read();
1300
+ signal?.throwIfAborted();
1293
1301
  if (done) break;
1294
1302
  chunks.push(value);
1295
1303
  }
1304
+ signal?.throwIfAborted();
1296
1305
  return chunks.join("");
1297
1306
  } finally {
1298
1307
  textReader.releaseLock();
@@ -1301,6 +1310,7 @@ async function readBoundedText(message, maxBytes, url) {
1301
1310
  if (reader != null) reader.cancel(error).catch(() => {});
1302
1311
  throw error;
1303
1312
  } finally {
1313
+ signal?.removeEventListener("abort", cancelOnAbort);
1304
1314
  reader?.releaseLock();
1305
1315
  }
1306
1316
  }
@@ -1312,6 +1322,7 @@ const logger = (0, _logtape_logtape.getLogger)([
1312
1322
  "lookup"
1313
1323
  ]);
1314
1324
  const DEFAULT_MAX_REDIRECTION = 5;
1325
+ const DEFAULT_TIMEOUT_MS = 1e4;
1315
1326
  /**
1316
1327
  * Looks up a WebFinger resource, opening a fetch session per hop. This is
1317
1328
  * the implementation of {@link lookupWebFinger}, which is not exported from
@@ -1335,20 +1346,72 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1335
1346
  protocol = resource.protocol;
1336
1347
  server = resource.host;
1337
1348
  }
1338
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1349
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
1339
1350
  url.searchParams.set("resource", resource.href);
1340
- 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 }));
1351
+ const controller = new AbortController();
1352
+ const signal = controller.signal;
1353
+ let timedOut = false;
1354
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1355
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
1356
+ const timeout = setTimeout(() => {
1357
+ timedOut = true;
1358
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
1359
+ }, timeoutMs);
1360
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
1361
+ if (options.signal?.aborted) abortFromCaller();
1362
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
1363
+ let stopWaiting = () => {};
1364
+ const aborted = new Promise((resolve) => {
1365
+ if (signal.aborted) resolve(null);
1366
+ else {
1367
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
1368
+ const onAbort = () => resolve(null);
1369
+ signal.addEventListener("abort", onAbort, { once: true });
1370
+ }
1371
+ });
1372
+ 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);
1373
+ try {
1374
+ const result = await Promise.race([work, aborted]);
1375
+ if (signal.aborted) {
1376
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
1377
+ url: url.href,
1378
+ timeoutMs
1379
+ });
1380
+ return null;
1381
+ }
1382
+ return result;
1383
+ } catch (error) {
1384
+ if (signal.aborted) return null;
1385
+ throw error;
1386
+ } finally {
1387
+ clearTimeout(timeout);
1388
+ stopWaiting();
1389
+ options.signal?.removeEventListener("abort", abortFromCaller);
1390
+ work.catch(() => {});
1391
+ }
1392
+ }
1393
+ async function lookupHops(initialUrl, options, openHop, signal) {
1394
+ let url = initialUrl;
1341
1395
  let redirected = 0;
1342
1396
  while (true) {
1397
+ if (signal.aborted) return null;
1343
1398
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
1344
- const session = await openSession(url, openHop, options.signal);
1399
+ const session = await openSession(url, openHop, signal);
1345
1400
  if (session == null) return null;
1346
1401
  let hop;
1347
1402
  try {
1348
- hop = await fetchHop(session, url, options);
1403
+ if (signal.aborted) return null;
1404
+ hop = await fetchHopUntilAbort(session, url, options, signal);
1349
1405
  } finally {
1350
- await session.close();
1406
+ if (signal.aborted) session.close().catch((error) => {
1407
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
1408
+ url: url.href,
1409
+ error
1410
+ });
1411
+ });
1412
+ else await session.close();
1351
1413
  }
1414
+ if (signal.aborted) return null;
1352
1415
  if ("result" in hop) return hop.result;
1353
1416
  redirected++;
1354
1417
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -1367,13 +1430,31 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
1367
1430
  url = redirectedUrl;
1368
1431
  }
1369
1432
  }
1433
+ /** Lets the session close even when a custom fetch or body ignores abort. */
1434
+ async function fetchHopUntilAbort(session, url, options, signal) {
1435
+ const fetching = fetchHop(session, url, options, signal);
1436
+ let onAbort;
1437
+ const aborted = new Promise((resolve) => {
1438
+ if (signal.aborted) resolve({ result: null });
1439
+ else {
1440
+ onAbort = () => resolve({ result: null });
1441
+ signal.addEventListener("abort", onAbort, { once: true });
1442
+ }
1443
+ });
1444
+ try {
1445
+ return await Promise.race([fetching, aborted]);
1446
+ } finally {
1447
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
1448
+ fetching.catch(() => {});
1449
+ }
1450
+ }
1370
1451
  /**
1371
1452
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
1372
1453
  * or an aborted lookup yields `null` instead of an error.
1373
1454
  */
1374
1455
  async function openSession(url, openHop, signal) {
1375
1456
  try {
1376
- return await openHop(url.href);
1457
+ return await openHop(url.href, signal);
1377
1458
  } catch (e) {
1378
1459
  if (e instanceof _fedify_vocab_runtime.UrlError) {
1379
1460
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -1397,7 +1478,7 @@ async function openSession(url, openHop, signal) {
1397
1478
  * Fetches a hop with the given session, and consumes the response body or
1398
1479
  * starts cancelling it before returning. The caller closes the session.
1399
1480
  */
1400
- async function fetchHop(session, url, options) {
1481
+ async function fetchHop(session, url, options, signal) {
1401
1482
  let response;
1402
1483
  try {
1403
1484
  response = await session.fetch(url, {
@@ -1406,7 +1487,7 @@ async function fetchHop(session, url, options) {
1406
1487
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
1407
1488
  },
1408
1489
  redirect: "manual",
1409
- signal: options.signal
1490
+ signal
1410
1491
  });
1411
1492
  } catch (error) {
1412
1493
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -1429,7 +1510,7 @@ async function fetchHop(session, url, options) {
1429
1510
  return { result: null };
1430
1511
  }
1431
1512
  try {
1432
- return { result: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)) };
1513
+ return { result: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)) };
1433
1514
  } catch (e) {
1434
1515
  if (e instanceof BodyTooLargeError) return { result: null };
1435
1516
  if (e instanceof SyntaxError) {
@@ -1981,4 +2062,144 @@ function neverCancellableResponse(init) {
1981
2062
  esm_default.hardReset();
1982
2063
  }
1983
2064
  });
2065
+ (0, _fedify_fixture.test)("lookupWebFinger() caller abort releases a stalled session open", async () => {
2066
+ const controller = new AbortController();
2067
+ let finishOpen;
2068
+ let closed = false;
2069
+ const opening = new Promise((resolve) => {
2070
+ finishOpen = resolve;
2071
+ });
2072
+ const lookup = lookupWebFingerInternal("acct:alice@example.com", { signal: controller.signal }, { openHop: () => opening });
2073
+ controller.abort();
2074
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookup, 1e3), null);
2075
+ finishOpen({
2076
+ url: new URL("https://example.com"),
2077
+ fetch: () => {
2078
+ throw new Error("fetch after abort");
2079
+ },
2080
+ close: () => {
2081
+ closed = true;
2082
+ return Promise.resolve();
2083
+ }
2084
+ });
2085
+ await Promise.resolve();
2086
+ await Promise.resolve();
2087
+ (0, node_assert_strict.ok)(closed);
2088
+ });
2089
+ (0, _fedify_fixture.test)("lookupWebFinger() deadline covers session opening", async () => {
2090
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerInternal("acct:alice@example.com", {}, {
2091
+ timeoutMs: 20,
2092
+ openHop: () => new Promise(() => {})
2093
+ }), 1e3), null);
2094
+ });
2095
+ (0, _fedify_fixture.test)("lookupWebFinger() shares one deadline across redirects", async () => {
2096
+ const descriptor = {
2097
+ subject: "acct:alice@example.com",
2098
+ links: []
2099
+ };
2100
+ const pending = [];
2101
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerInternal("acct:alice@example.com", {}, {
2102
+ timeoutMs: 100,
2103
+ openHop: (url) => Promise.resolve({
2104
+ url: new URL(url),
2105
+ fetch: () => {
2106
+ const response = new Promise((resolve) => {
2107
+ setTimeout(() => {
2108
+ resolve(url.includes("/final") ? new Response(JSON.stringify(descriptor)) : new Response(null, {
2109
+ status: 302,
2110
+ headers: { Location: "/final" }
2111
+ }));
2112
+ }, 60);
2113
+ });
2114
+ pending.push(response);
2115
+ return response;
2116
+ },
2117
+ close: () => Promise.resolve()
2118
+ })
2119
+ }), 1e3), null);
2120
+ await Promise.all(pending);
2121
+ });
2122
+ (0, _fedify_fixture.test)("lookupWebFinger() caller signal cannot extend its deadline", async () => {
2123
+ const signal = AbortSignal.timeout(5e3);
2124
+ let reason;
2125
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerInternal("acct:alice@example.com", { signal }, {
2126
+ timeoutMs: 50,
2127
+ openHop: (_url, effectiveSignal) => {
2128
+ effectiveSignal?.addEventListener("abort", () => {
2129
+ reason = effectiveSignal.reason;
2130
+ }, { once: true });
2131
+ return new Promise(() => {});
2132
+ }
2133
+ }), 1e3), null);
2134
+ (0, node_assert_strict.ok)(!signal.aborted);
2135
+ (0, node_assert_strict.ok)(reason instanceof DOMException);
2136
+ (0, node_assert_strict.deepStrictEqual)(reason.name, "TimeoutError");
2137
+ });
2138
+ (0, _fedify_fixture.test)("lookupWebFinger() deadline covers response headers", async () => {
2139
+ let closed = false;
2140
+ let fetchSignal;
2141
+ let fetchAborted = false;
2142
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerInternal("acct:alice@example.com", {}, {
2143
+ timeoutMs: 20,
2144
+ openHop: () => Promise.resolve({
2145
+ url: new URL("https://example.com"),
2146
+ fetch: (_input, init) => {
2147
+ fetchSignal = init?.signal;
2148
+ fetchSignal?.addEventListener("abort", () => {
2149
+ fetchAborted = true;
2150
+ }, { once: true });
2151
+ return new Promise(() => {});
2152
+ },
2153
+ close: () => {
2154
+ closed = true;
2155
+ return Promise.resolve();
2156
+ }
2157
+ })
2158
+ }), 1e3), null);
2159
+ (0, node_assert_strict.ok)(fetchSignal?.aborted);
2160
+ (0, node_assert_strict.ok)(fetchAborted);
2161
+ (0, node_assert_strict.deepStrictEqual)(fetchSignal.reason.name, "TimeoutError");
2162
+ await Promise.resolve();
2163
+ (0, node_assert_strict.ok)(closed);
2164
+ });
2165
+ (0, _fedify_fixture.test)("lookupWebFinger() discards completed JSON when body stalls", async () => {
2166
+ const descriptor = {
2167
+ subject: "acct:alice@example.com",
2168
+ links: []
2169
+ };
2170
+ let cancelled;
2171
+ const cancellation = new Promise((resolve) => {
2172
+ cancelled = resolve;
2173
+ });
2174
+ (0, node_assert_strict.deepStrictEqual)(await settleWithin(lookupWebFingerInternal("acct:alice@example.com", {}, {
2175
+ timeoutMs: 20,
2176
+ openHop: () => Promise.resolve({
2177
+ url: new URL("https://example.com"),
2178
+ fetch: () => Promise.resolve(new Response(new ReadableStream({
2179
+ start(controller) {
2180
+ controller.enqueue(new TextEncoder().encode(JSON.stringify(descriptor)));
2181
+ },
2182
+ cancel() {
2183
+ cancelled();
2184
+ }
2185
+ }))),
2186
+ close: async () => {}
2187
+ })
2188
+ }), 1e3), null);
2189
+ await settleWithin(cancellation, 1e3);
2190
+ });
2191
+ (0, _fedify_fixture.test)("lookupWebFinger() accepts a response before its deadline", async () => {
2192
+ const descriptor = {
2193
+ subject: "acct:alice@example.com",
2194
+ links: []
2195
+ };
2196
+ (0, node_assert_strict.deepStrictEqual)(await lookupWebFingerInternal("acct:alice@example.com", {}, {
2197
+ timeoutMs: 1e3,
2198
+ openHop: () => Promise.resolve({
2199
+ url: new URL("https://example.com"),
2200
+ fetch: () => Promise.resolve(new Response(JSON.stringify(descriptor))),
2201
+ close: async () => {}
2202
+ })
2203
+ }), descriptor);
2204
+ });
1984
2205
  //#endregion