@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/dist/mod.js CHANGED
@@ -4,7 +4,7 @@ import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  //#region deno.json
6
6
  var name = "@fedify/webfinger";
7
- var version = "2.3.16-dev.2845+6e764b6f";
7
+ var version = "2.3.16";
8
8
  //#endregion
9
9
  //#region src/body.ts
10
10
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -27,13 +27,18 @@ function validateBodySizeLimit(maxBytes) {
27
27
  * @param message The response or request to read.
28
28
  * @param maxBytes The maximum number of decoded bytes to read.
29
29
  * @param url The URL to include in errors and logs.
30
+ * @param signal The signal that cancels an in-progress body read.
30
31
  * @returns The decoded body text.
31
32
  * @throws {BodyTooLargeError} If the body exceeds the limit.
32
33
  * @internal
33
34
  */
34
- async function readBoundedText(message, maxBytes, url) {
35
+ async function readBoundedText(message, maxBytes, url, signal) {
35
36
  validateBodySizeLimit(maxBytes);
36
37
  const reader = message.body?.getReader();
38
+ const cancelOnAbort = () => {
39
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
40
+ };
41
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
37
42
  const tooLarge = () => {
38
43
  getLogger([
39
44
  "fedify",
@@ -46,6 +51,7 @@ async function readBoundedText(message, maxBytes, url) {
46
51
  throw new BodyTooLargeError(url, maxBytes);
47
52
  };
48
53
  try {
54
+ signal?.throwIfAborted();
49
55
  const length = message.headers.get("Content-Length");
50
56
  const encoding = message.headers.get("Content-Encoding");
51
57
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -53,6 +59,7 @@ async function readBoundedText(message, maxBytes, url) {
53
59
  let size = 0;
54
60
  const textReader = new ReadableStream({ async pull(controller) {
55
61
  const { done, value } = await reader.read();
62
+ signal?.throwIfAborted();
56
63
  if (done) {
57
64
  controller.close();
58
65
  return;
@@ -65,9 +72,11 @@ async function readBoundedText(message, maxBytes, url) {
65
72
  const chunks = [];
66
73
  while (true) {
67
74
  const { done, value } = await textReader.read();
75
+ signal?.throwIfAborted();
68
76
  if (done) break;
69
77
  chunks.push(value);
70
78
  }
79
+ signal?.throwIfAborted();
71
80
  return chunks.join("");
72
81
  } finally {
73
82
  textReader.releaseLock();
@@ -76,6 +85,7 @@ async function readBoundedText(message, maxBytes, url) {
76
85
  if (reader != null) reader.cancel(error).catch(() => {});
77
86
  throw error;
78
87
  } finally {
88
+ signal?.removeEventListener("abort", cancelOnAbort);
79
89
  reader?.releaseLock();
80
90
  }
81
91
  }
@@ -87,6 +97,7 @@ const logger = getLogger([
87
97
  "lookup"
88
98
  ]);
89
99
  const DEFAULT_MAX_REDIRECTION = 5;
100
+ const DEFAULT_TIMEOUT_MS = 1e4;
90
101
  /**
91
102
  * Looks up a WebFinger resource, opening a fetch session per hop. This is
92
103
  * the implementation of {@link lookupWebFinger}, which is not exported from
@@ -120,14 +131,67 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
120
131
  protocol = resource.protocol;
121
132
  server = resource.host;
122
133
  }
123
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
134
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
124
135
  url.searchParams.set("resource", resource.href);
125
- const openHop = deps.openHop ?? ((hopUrl) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: options.signal }));
136
+ const controller = new AbortController();
137
+ const signal = controller.signal;
138
+ let timedOut = false;
139
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
140
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
141
+ const timeout = setTimeout(() => {
142
+ timedOut = true;
143
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
144
+ }, timeoutMs);
145
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
146
+ if (options.signal?.aborted) abortFromCaller();
147
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
148
+ let stopWaiting = () => {};
149
+ const cancelledOutcome = () => ({
150
+ resource: null,
151
+ result: "network_error",
152
+ remoteHost: url.host
153
+ });
154
+ const aborted = new Promise((resolve) => {
155
+ if (signal.aborted) resolve(cancelledOutcome());
156
+ else {
157
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
158
+ const onAbort = () => resolve(cancelledOutcome());
159
+ signal.addEventListener("abort", onAbort, { once: true });
160
+ }
161
+ });
162
+ const work = lookupHops(url, options, deps.openHop ?? ((hopUrl, hopSignal) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: hopSignal })), signal);
163
+ try {
164
+ const result = await Promise.race([work, aborted]);
165
+ if (signal.aborted) {
166
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
167
+ url: url.href,
168
+ timeoutMs
169
+ });
170
+ return cancelledOutcome();
171
+ }
172
+ return result;
173
+ } catch (error) {
174
+ if (signal.aborted) return cancelledOutcome();
175
+ throw error;
176
+ } finally {
177
+ clearTimeout(timeout);
178
+ stopWaiting();
179
+ options.signal?.removeEventListener("abort", abortFromCaller);
180
+ work.catch(() => {});
181
+ }
182
+ }
183
+ async function lookupHops(initialUrl, options, openHop, signal) {
184
+ let url = initialUrl;
126
185
  let redirected = 0;
127
186
  while (true) {
187
+ if (signal.aborted) return {
188
+ resource: null,
189
+ result: "network_error",
190
+ remoteHost: url.host
191
+ };
128
192
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
129
193
  const remoteHost = url.host;
130
- const session = await openSession(url, openHop, options.signal);
194
+ const session = await openSession(url, openHop, signal);
131
195
  if (session == null) return {
132
196
  resource: null,
133
197
  result: "network_error",
@@ -135,10 +199,26 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
135
199
  };
136
200
  let hop;
137
201
  try {
138
- hop = await fetchHop(session, url, options);
202
+ if (signal.aborted) return {
203
+ resource: null,
204
+ result: "network_error",
205
+ remoteHost
206
+ };
207
+ hop = await fetchHopUntilAbort(session, url, options, signal);
139
208
  } finally {
140
- await session.close();
209
+ if (signal.aborted) session.close().catch((error) => {
210
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
211
+ url: url.href,
212
+ error
213
+ });
214
+ });
215
+ else await session.close();
141
216
  }
217
+ if (signal.aborted) return {
218
+ resource: null,
219
+ result: "network_error",
220
+ remoteHost
221
+ };
142
222
  if ("outcome" in hop) return hop.outcome;
143
223
  redirected++;
144
224
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -181,13 +261,36 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
181
261
  url = redirectedUrl;
182
262
  }
183
263
  }
264
+ /** Lets the session close even when a custom fetch or body ignores abort. */
265
+ async function fetchHopUntilAbort(session, url, options, signal) {
266
+ const fetching = fetchHop(session, url, options, signal);
267
+ let onAbort;
268
+ const aborted = new Promise((resolve) => {
269
+ const outcome = {
270
+ resource: null,
271
+ result: "network_error",
272
+ remoteHost: url.host
273
+ };
274
+ if (signal.aborted) resolve({ outcome });
275
+ else {
276
+ onAbort = () => resolve({ outcome });
277
+ signal.addEventListener("abort", onAbort, { once: true });
278
+ }
279
+ });
280
+ try {
281
+ return await Promise.race([fetching, aborted]);
282
+ } finally {
283
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
284
+ fetching.catch(() => {});
285
+ }
286
+ }
184
287
  /**
185
288
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
186
289
  * or an aborted lookup yields `null` instead of an error.
187
290
  */
188
291
  async function openSession(url, openHop, signal) {
189
292
  try {
190
- return await openHop(url.href);
293
+ return await openHop(url.href, signal);
191
294
  } catch (e) {
192
295
  if (e instanceof UrlError) {
193
296
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -211,7 +314,7 @@ async function openSession(url, openHop, signal) {
211
314
  * Fetches a hop with the given session, and consumes the response body or
212
315
  * starts cancelling it before returning. The caller closes the session.
213
316
  */
214
- async function fetchHop(session, url, options) {
317
+ async function fetchHop(session, url, options, signal) {
215
318
  let response;
216
319
  try {
217
320
  response = await session.fetch(url, {
@@ -220,7 +323,7 @@ async function fetchHop(session, url, options) {
220
323
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
221
324
  },
222
325
  redirect: "manual",
223
- signal: options.signal
326
+ signal
224
327
  });
225
328
  } catch (error) {
226
329
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -256,7 +359,7 @@ async function fetchHop(session, url, options) {
256
359
  }
257
360
  try {
258
361
  return { outcome: {
259
- resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
362
+ resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)),
260
363
  result: "found",
261
364
  statusCode: response.status,
262
365
  remoteHost: url.host
package/package.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
  "homepage": "https://fedify.dev/",
5
5
  "repository": {
6
6
  "type": "git",
@@ -60,7 +60,7 @@
60
60
  "@logtape/logtape": "^2.2.0",
61
61
  "@opentelemetry/api": "~1.9.1",
62
62
  "es-toolkit": "1.46.1",
63
- "@fedify/vocab-runtime": "2.3.16-dev.2845+6e764b6f"
63
+ "@fedify/vocab-runtime": "2.3.16"
64
64
  },
65
65
  "scripts": {
66
66
  "build:self": "tsdown",
package/src/body.ts CHANGED
@@ -31,6 +31,7 @@ function validateBodySizeLimit(maxBytes: number): void {
31
31
  * @param message The response or request to read.
32
32
  * @param maxBytes The maximum number of decoded bytes to read.
33
33
  * @param url The URL to include in errors and logs.
34
+ * @param signal The signal that cancels an in-progress body read.
34
35
  * @returns The decoded body text.
35
36
  * @throws {BodyTooLargeError} If the body exceeds the limit.
36
37
  * @internal
@@ -39,9 +40,14 @@ export async function readBoundedText(
39
40
  message: Pick<Request, "body" | "headers">,
40
41
  maxBytes: number,
41
42
  url: string | URL,
43
+ signal?: AbortSignal,
42
44
  ): Promise<string> {
43
45
  validateBodySizeLimit(maxBytes);
44
46
  const reader = message.body?.getReader();
47
+ const cancelOnAbort = () => {
48
+ if (reader != null) void reader.cancel(signal?.reason).catch(() => {});
49
+ };
50
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
45
51
  const tooLarge = (): never => {
46
52
  getLogger(["fedify", "runtime", "body"]).warn(
47
53
  "Body from {url} exceeds the limit of {maxBytes} bytes.",
@@ -50,6 +56,7 @@ export async function readBoundedText(
50
56
  throw new BodyTooLargeError(url, maxBytes);
51
57
  };
52
58
  try {
59
+ signal?.throwIfAborted();
53
60
  // Content-Length describes the encoded body when compression is used.
54
61
  // Only use it as an early rejection for an unencoded body.
55
62
  const length = message.headers.get("Content-Length");
@@ -63,6 +70,7 @@ export async function readBoundedText(
63
70
  const bounded = new ReadableStream<BufferSource>({
64
71
  async pull(controller) {
65
72
  const { done, value } = await reader.read();
73
+ signal?.throwIfAborted();
66
74
  if (done) {
67
75
  controller.close();
68
76
  return;
@@ -77,9 +85,11 @@ export async function readBoundedText(
77
85
  const chunks: string[] = [];
78
86
  while (true) {
79
87
  const { done, value } = await textReader.read();
88
+ signal?.throwIfAborted();
80
89
  if (done) break;
81
90
  chunks.push(value);
82
91
  }
92
+ signal?.throwIfAborted();
83
93
  return chunks.join("");
84
94
  } finally {
85
95
  textReader.releaseLock();
@@ -90,6 +100,7 @@ export async function readBoundedText(
90
100
  if (reader != null) void reader.cancel(error).catch(() => {});
91
101
  throw error;
92
102
  } finally {
103
+ signal?.removeEventListener("abort", cancelOnAbort);
93
104
  reader?.releaseLock();
94
105
  }
95
106
  }
@@ -15,6 +15,7 @@ import type {
15
15
  const logger = getLogger(["fedify", "webfinger", "lookup"]);
16
16
 
17
17
  const DEFAULT_MAX_REDIRECTION = 5;
18
+ const DEFAULT_TIMEOUT_MS = 10_000;
18
19
 
19
20
  /**
20
21
  * The dependencies of {@link lookupWebFingerInternal}.
@@ -25,7 +26,12 @@ export interface LookupWebFingerDependencies {
25
26
  * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
26
27
  * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
27
28
  */
28
- readonly openHop?: (url: string) => Promise<PublicFetchSession>;
29
+ readonly openHop?: (
30
+ url: string,
31
+ signal?: AbortSignal,
32
+ ) => Promise<PublicFetchSession>;
33
+ /** Overrides the lookup deadline for internal tests. */
34
+ readonly timeoutMs?: number;
29
35
  }
30
36
 
31
37
  /**
@@ -87,29 +93,118 @@ export async function lookupWebFingerInternal(
87
93
  protocol = resource.protocol;
88
94
  server = resource.host;
89
95
  }
90
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
96
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
91
97
  url.searchParams.set("resource", resource.href);
98
+ const controller = new AbortController();
99
+ const signal = controller.signal;
100
+ let timedOut = false;
101
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
102
+ if (
103
+ !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 ||
104
+ timeoutMs > 2_147_483_647
105
+ ) {
106
+ throw new RangeError(
107
+ "The WebFinger timeout must be a positive integer of at most 2147483647 ms.",
108
+ );
109
+ }
110
+ const timeout = setTimeout(() => {
111
+ timedOut = true;
112
+ controller.abort(
113
+ new DOMException("WebFinger lookup timed out", "TimeoutError"),
114
+ );
115
+ }, timeoutMs);
116
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
117
+ if (options.signal?.aborted) abortFromCaller();
118
+ else {options.signal?.addEventListener("abort", abortFromCaller, {
119
+ once: true,
120
+ });}
121
+ let stopWaiting: () => void = () => {};
122
+ const cancelledOutcome = (): WebFingerLookupOutcome => ({
123
+ resource: null,
124
+ result: "network_error",
125
+ remoteHost: url.host,
126
+ });
127
+ const aborted = new Promise<WebFingerLookupOutcome>((resolve) => {
128
+ if (signal.aborted) resolve(cancelledOutcome());
129
+ else {
130
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
131
+ const onAbort = () => resolve(cancelledOutcome());
132
+ signal.addEventListener("abort", onAbort, { once: true });
133
+ }
134
+ });
92
135
  const openHop = deps.openHop ??
93
- ((hopUrl: string) =>
136
+ ((hopUrl: string, hopSignal?: AbortSignal) =>
94
137
  options.allowPrivateAddress === true
95
138
  ? openDirectFetch(hopUrl)
96
- : openPublicFetch(hopUrl, { signal: options.signal }));
139
+ : openPublicFetch(hopUrl, { signal: hopSignal }));
140
+ const work = lookupHops(url, options, openHop, signal);
141
+ try {
142
+ const result = await Promise.race([work, aborted]);
143
+ if (signal.aborted) {
144
+ if (timedOut) {
145
+ logger.warn(
146
+ "WebFinger lookup timed out for {url} after {timeoutMs} ms.",
147
+ {
148
+ url: url.href,
149
+ timeoutMs,
150
+ },
151
+ );
152
+ }
153
+ return cancelledOutcome();
154
+ }
155
+ return result;
156
+ } catch (error) {
157
+ if (signal.aborted) return cancelledOutcome();
158
+ throw error;
159
+ } finally {
160
+ clearTimeout(timeout);
161
+ stopWaiting();
162
+ options.signal?.removeEventListener("abort", abortFromCaller);
163
+ // A DNS resolver or a custom stream may ignore cancellation. Observe
164
+ // the abandoned work so its eventual rejection is never unhandled.
165
+ void work.catch(() => {});
166
+ }
167
+ }
168
+
169
+ async function lookupHops(
170
+ initialUrl: URL,
171
+ options: LookupWebFingerOptions,
172
+ openHop: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>,
173
+ signal: AbortSignal,
174
+ ): Promise<WebFingerLookupOutcome> {
175
+ let url = initialUrl;
97
176
  let redirected = 0;
98
177
  while (true) {
178
+ if (signal.aborted) {
179
+ return { resource: null, result: "network_error", remoteHost: url.host };
180
+ }
99
181
  logger.debug(
100
182
  "Fetching WebFinger resource descriptor from {url}...",
101
183
  { url: url.href },
102
184
  );
103
185
  const remoteHost = url.host;
104
- const session = await openSession(url, openHop, options.signal);
186
+ const session = await openSession(url, openHop, signal);
105
187
  if (session == null) {
106
188
  return { resource: null, result: "network_error", remoteHost };
107
189
  }
108
190
  let hop: HopResult;
109
191
  try {
110
- hop = await fetchHop(session, url, options);
192
+ if (signal.aborted) {
193
+ return { resource: null, result: "network_error", remoteHost };
194
+ }
195
+ hop = await fetchHopUntilAbort(session, url, options, signal);
111
196
  } finally {
112
- await session.close();
197
+ if (signal.aborted) {
198
+ void session.close().catch((error) => {
199
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
200
+ url: url.href,
201
+ error,
202
+ });
203
+ });
204
+ } else await session.close();
205
+ }
206
+ if (signal.aborted) {
207
+ return { resource: null, result: "network_error", remoteHost };
113
208
  }
114
209
  if ("outcome" in hop) return hop.outcome;
115
210
  redirected++;
@@ -165,17 +260,46 @@ export async function lookupWebFingerInternal(
165
260
  }
166
261
  }
167
262
 
263
+ /** Lets the session close even when a custom fetch or body ignores abort. */
264
+ async function fetchHopUntilAbort(
265
+ session: PublicFetchSession,
266
+ url: URL,
267
+ options: LookupWebFingerOptions,
268
+ signal: AbortSignal,
269
+ ): Promise<HopResult> {
270
+ const fetching = fetchHop(session, url, options, signal);
271
+ let onAbort: (() => void) | undefined;
272
+ const aborted = new Promise<HopResult>((resolve) => {
273
+ const outcome: WebFingerLookupOutcome = {
274
+ resource: null,
275
+ result: "network_error",
276
+ remoteHost: url.host,
277
+ };
278
+ if (signal.aborted) resolve({ outcome });
279
+ else {
280
+ onAbort = () => resolve({ outcome });
281
+ signal.addEventListener("abort", onAbort, { once: true });
282
+ }
283
+ });
284
+ try {
285
+ return await Promise.race([fetching, aborted]);
286
+ } finally {
287
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
288
+ void fetching.catch(() => {});
289
+ }
290
+ }
291
+
168
292
  /**
169
293
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
170
294
  * or an aborted lookup yields `null` instead of an error.
171
295
  */
172
296
  async function openSession(
173
297
  url: URL,
174
- openHop: (url: string) => Promise<PublicFetchSession>,
298
+ openHop: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>,
175
299
  signal: AbortSignal | undefined,
176
300
  ): Promise<PublicFetchSession | null> {
177
301
  try {
178
- return await openHop(url.href);
302
+ return await openHop(url.href, signal);
179
303
  } catch (e) {
180
304
  if (e instanceof UrlError) {
181
305
  if (e.reason === "dns") {
@@ -210,6 +334,7 @@ async function fetchHop(
210
334
  session: PublicFetchSession,
211
335
  url: URL,
212
336
  options: LookupWebFingerOptions,
337
+ signal: AbortSignal,
213
338
  ): Promise<HopResult> {
214
339
  let response: Response;
215
340
  try {
@@ -221,7 +346,7 @@ async function fetchHop(
221
346
  : getUserAgent(options.userAgent),
222
347
  },
223
348
  redirect: "manual",
224
- signal: options.signal,
349
+ signal,
225
350
  });
226
351
  } catch (error) {
227
352
  logger.debug(
@@ -271,7 +396,7 @@ async function fetchHop(
271
396
  return {
272
397
  outcome: {
273
398
  resource: JSON.parse(
274
- await readBoundedText(response, MAX_BODY_SIZE, url),
399
+ await readBoundedText(response, MAX_BODY_SIZE, url, signal),
275
400
  ) as ResourceDescriptor,
276
401
  result: "found",
277
402
  statusCode: response.status,