@fedify/webfinger 2.2.20 → 2.2.21

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.2.20";
7
+ var version = "2.2.21";
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
@@ -110,20 +121,72 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
110
121
  protocol = resource.protocol;
111
122
  server = resource.host;
112
123
  }
113
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
124
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
114
125
  url.searchParams.set("resource", resource.href);
115
- const openHop = deps.openHop ?? ((hopUrl) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: options.signal }));
126
+ const controller = new AbortController();
127
+ const signal = controller.signal;
128
+ let timedOut = false;
129
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
130
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
131
+ const timeout = setTimeout(() => {
132
+ timedOut = true;
133
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
134
+ }, timeoutMs);
135
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
136
+ if (options.signal?.aborted) abortFromCaller();
137
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
138
+ let stopWaiting = () => {};
139
+ const aborted = new Promise((resolve) => {
140
+ if (signal.aborted) resolve(null);
141
+ else {
142
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
143
+ const onAbort = () => resolve(null);
144
+ signal.addEventListener("abort", onAbort, { once: true });
145
+ }
146
+ });
147
+ const work = lookupHops(url, options, deps.openHop ?? ((hopUrl, hopSignal) => options.allowPrivateAddress === true ? openDirectFetch(hopUrl) : openPublicFetch(hopUrl, { signal: hopSignal })), signal);
148
+ try {
149
+ const result = await Promise.race([work, aborted]);
150
+ if (signal.aborted) {
151
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
152
+ url: url.href,
153
+ timeoutMs
154
+ });
155
+ return null;
156
+ }
157
+ return result;
158
+ } catch (error) {
159
+ if (signal.aborted) return null;
160
+ throw error;
161
+ } finally {
162
+ clearTimeout(timeout);
163
+ stopWaiting();
164
+ options.signal?.removeEventListener("abort", abortFromCaller);
165
+ work.catch(() => {});
166
+ }
167
+ }
168
+ async function lookupHops(initialUrl, options, openHop, signal) {
169
+ let url = initialUrl;
116
170
  let redirected = 0;
117
171
  while (true) {
172
+ if (signal.aborted) return null;
118
173
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
119
- const session = await openSession(url, openHop, options.signal);
174
+ const session = await openSession(url, openHop, signal);
120
175
  if (session == null) return null;
121
176
  let hop;
122
177
  try {
123
- hop = await fetchHop(session, url, options);
178
+ if (signal.aborted) return null;
179
+ hop = await fetchHopUntilAbort(session, url, options, signal);
124
180
  } finally {
125
- await session.close();
181
+ if (signal.aborted) session.close().catch((error) => {
182
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
183
+ url: url.href,
184
+ error
185
+ });
186
+ });
187
+ else await session.close();
126
188
  }
189
+ if (signal.aborted) return null;
127
190
  if ("result" in hop) return hop.result;
128
191
  redirected++;
129
192
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -142,13 +205,31 @@ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
142
205
  url = redirectedUrl;
143
206
  }
144
207
  }
208
+ /** Lets the session close even when a custom fetch or body ignores abort. */
209
+ async function fetchHopUntilAbort(session, url, options, signal) {
210
+ const fetching = fetchHop(session, url, options, signal);
211
+ let onAbort;
212
+ const aborted = new Promise((resolve) => {
213
+ if (signal.aborted) resolve({ result: null });
214
+ else {
215
+ onAbort = () => resolve({ result: null });
216
+ signal.addEventListener("abort", onAbort, { once: true });
217
+ }
218
+ });
219
+ try {
220
+ return await Promise.race([fetching, aborted]);
221
+ } finally {
222
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
223
+ fetching.catch(() => {});
224
+ }
225
+ }
145
226
  /**
146
227
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
147
228
  * or an aborted lookup yields `null` instead of an error.
148
229
  */
149
230
  async function openSession(url, openHop, signal) {
150
231
  try {
151
- return await openHop(url.href);
232
+ return await openHop(url.href, signal);
152
233
  } catch (e) {
153
234
  if (e instanceof UrlError) {
154
235
  if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
@@ -172,7 +253,7 @@ async function openSession(url, openHop, signal) {
172
253
  * Fetches a hop with the given session, and consumes the response body or
173
254
  * starts cancelling it before returning. The caller closes the session.
174
255
  */
175
- async function fetchHop(session, url, options) {
256
+ async function fetchHop(session, url, options, signal) {
176
257
  let response;
177
258
  try {
178
259
  response = await session.fetch(url, {
@@ -181,7 +262,7 @@ async function fetchHop(session, url, options) {
181
262
  "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
182
263
  },
183
264
  redirect: "manual",
184
- signal: options.signal
265
+ signal
185
266
  });
186
267
  } catch (error) {
187
268
  logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
@@ -204,7 +285,7 @@ async function fetchHop(session, url, options) {
204
285
  return { result: null };
205
286
  }
206
287
  try {
207
- return { result: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)) };
288
+ return { result: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)) };
208
289
  } catch (e) {
209
290
  if (e instanceof BodyTooLargeError) return { result: null };
210
291
  if (e instanceof SyntaxError) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/webfinger",
3
- "version": "2.2.20",
3
+ "version": "2.2.21",
4
4
  "homepage": "https://fedify.dev/",
5
5
  "repository": {
6
6
  "type": "git",
@@ -60,7 +60,7 @@
60
60
  "@logtape/logtape": "^2.0.5",
61
61
  "@opentelemetry/api": "~1.9.0",
62
62
  "es-toolkit": "1.43.0",
63
- "@fedify/vocab-runtime": "2.2.20"
63
+ "@fedify/vocab-runtime": "2.2.21"
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
  }
@@ -12,6 +12,7 @@ import type { LookupWebFingerOptions } from "./lookup.ts";
12
12
  const logger = getLogger(["fedify", "webfinger", "lookup"]);
13
13
 
14
14
  const DEFAULT_MAX_REDIRECTION = 5;
15
+ const DEFAULT_TIMEOUT_MS = 10_000;
15
16
 
16
17
  /**
17
18
  * The dependencies of {@link lookupWebFingerInternal}.
@@ -22,7 +23,12 @@ export interface LookupWebFingerDependencies {
22
23
  * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
23
24
  * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
24
25
  */
25
- readonly openHop?: (url: string) => Promise<PublicFetchSession>;
26
+ readonly openHop?: (
27
+ url: string,
28
+ signal?: AbortSignal,
29
+ ) => Promise<PublicFetchSession>;
30
+ /** Overrides the lookup deadline for internal tests. */
31
+ readonly timeoutMs?: number;
26
32
  }
27
33
 
28
34
  /**
@@ -60,27 +66,105 @@ export async function lookupWebFingerInternal(
60
66
  protocol = resource.protocol;
61
67
  server = resource.host;
62
68
  }
63
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
69
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
64
70
  url.searchParams.set("resource", resource.href);
71
+ const controller = new AbortController();
72
+ const signal = controller.signal;
73
+ let timedOut = false;
74
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
75
+ if (
76
+ !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 ||
77
+ timeoutMs > 2_147_483_647
78
+ ) {
79
+ throw new RangeError(
80
+ "The WebFinger timeout must be a positive integer of at most 2147483647 ms.",
81
+ );
82
+ }
83
+ const timeout = setTimeout(() => {
84
+ timedOut = true;
85
+ controller.abort(
86
+ new DOMException("WebFinger lookup timed out", "TimeoutError"),
87
+ );
88
+ }, timeoutMs);
89
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
90
+ if (options.signal?.aborted) abortFromCaller();
91
+ else {options.signal?.addEventListener("abort", abortFromCaller, {
92
+ once: true,
93
+ });}
94
+ let stopWaiting: () => void = () => {};
95
+ const aborted = new Promise<null>((resolve) => {
96
+ if (signal.aborted) resolve(null);
97
+ else {
98
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
99
+ const onAbort = () => resolve(null);
100
+ signal.addEventListener("abort", onAbort, { once: true });
101
+ }
102
+ });
65
103
  const openHop = deps.openHop ??
66
- ((hopUrl: string) =>
104
+ ((hopUrl: string, hopSignal?: AbortSignal) =>
67
105
  options.allowPrivateAddress === true
68
106
  ? openDirectFetch(hopUrl)
69
- : openPublicFetch(hopUrl, { signal: options.signal }));
107
+ : openPublicFetch(hopUrl, { signal: hopSignal }));
108
+ const work = lookupHops(url, options, openHop, signal);
109
+ try {
110
+ const result = await Promise.race([work, aborted]);
111
+ if (signal.aborted) {
112
+ if (timedOut) {
113
+ logger.warn(
114
+ "WebFinger lookup timed out for {url} after {timeoutMs} ms.",
115
+ {
116
+ url: url.href,
117
+ timeoutMs,
118
+ },
119
+ );
120
+ }
121
+ return null;
122
+ }
123
+ return result;
124
+ } catch (error) {
125
+ if (signal.aborted) return null;
126
+ throw error;
127
+ } finally {
128
+ clearTimeout(timeout);
129
+ stopWaiting();
130
+ options.signal?.removeEventListener("abort", abortFromCaller);
131
+ // A DNS resolver or a custom stream may ignore cancellation. Observe
132
+ // the abandoned work so its eventual rejection is never unhandled.
133
+ void work.catch(() => {});
134
+ }
135
+ }
136
+
137
+ async function lookupHops(
138
+ initialUrl: URL,
139
+ options: LookupWebFingerOptions,
140
+ openHop: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>,
141
+ signal: AbortSignal,
142
+ ): Promise<ResourceDescriptor | null> {
143
+ let url = initialUrl;
70
144
  let redirected = 0;
71
145
  while (true) {
146
+ if (signal.aborted) return null;
72
147
  logger.debug(
73
148
  "Fetching WebFinger resource descriptor from {url}...",
74
149
  { url: url.href },
75
150
  );
76
- const session = await openSession(url, openHop, options.signal);
151
+ const session = await openSession(url, openHop, signal);
77
152
  if (session == null) return null;
78
153
  let hop: HopResult;
79
154
  try {
80
- hop = await fetchHop(session, url, options);
155
+ if (signal.aborted) return null;
156
+ hop = await fetchHopUntilAbort(session, url, options, signal);
81
157
  } finally {
82
- await session.close();
158
+ if (signal.aborted) {
159
+ void session.close().catch((error) => {
160
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
161
+ url: url.href,
162
+ error,
163
+ });
164
+ });
165
+ } else await session.close();
83
166
  }
167
+ if (signal.aborted) return null;
84
168
  if ("result" in hop) return hop.result;
85
169
  redirected++;
86
170
  const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
@@ -111,17 +195,41 @@ export async function lookupWebFingerInternal(
111
195
  }
112
196
  }
113
197
 
198
+ /** Lets the session close even when a custom fetch or body ignores abort. */
199
+ async function fetchHopUntilAbort(
200
+ session: PublicFetchSession,
201
+ url: URL,
202
+ options: LookupWebFingerOptions,
203
+ signal: AbortSignal,
204
+ ): Promise<HopResult> {
205
+ const fetching = fetchHop(session, url, options, signal);
206
+ let onAbort: (() => void) | undefined;
207
+ const aborted = new Promise<HopResult>((resolve) => {
208
+ if (signal.aborted) resolve({ result: null });
209
+ else {
210
+ onAbort = () => resolve({ result: null });
211
+ signal.addEventListener("abort", onAbort, { once: true });
212
+ }
213
+ });
214
+ try {
215
+ return await Promise.race([fetching, aborted]);
216
+ } finally {
217
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
218
+ void fetching.catch(() => {});
219
+ }
220
+ }
221
+
114
222
  /**
115
223
  * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
116
224
  * or an aborted lookup yields `null` instead of an error.
117
225
  */
118
226
  async function openSession(
119
227
  url: URL,
120
- openHop: (url: string) => Promise<PublicFetchSession>,
228
+ openHop: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>,
121
229
  signal: AbortSignal | undefined,
122
230
  ): Promise<PublicFetchSession | null> {
123
231
  try {
124
- return await openHop(url.href);
232
+ return await openHop(url.href, signal);
125
233
  } catch (e) {
126
234
  if (e instanceof UrlError) {
127
235
  if (e.reason === "dns") {
@@ -159,6 +267,7 @@ async function fetchHop(
159
267
  session: PublicFetchSession,
160
268
  url: URL,
161
269
  options: LookupWebFingerOptions,
270
+ signal: AbortSignal,
162
271
  ): Promise<HopResult> {
163
272
  let response: Response;
164
273
  try {
@@ -170,7 +279,7 @@ async function fetchHop(
170
279
  : getUserAgent(options.userAgent),
171
280
  },
172
281
  redirect: "manual",
173
- signal: options.signal,
282
+ signal,
174
283
  });
175
284
  } catch (error) {
176
285
  logger.debug(
@@ -201,7 +310,7 @@ async function fetchHop(
201
310
  try {
202
311
  return {
203
312
  result: JSON.parse(
204
- await readBoundedText(response, MAX_BODY_SIZE, url),
313
+ await readBoundedText(response, MAX_BODY_SIZE, url, signal),
205
314
  ) as ResourceDescriptor,
206
315
  };
207
316
  } catch (e) {
@@ -865,3 +865,178 @@ test("lookupWebFinger() does not wait for cancelling response bodies", async (t)
865
865
  fetchMock.hardReset();
866
866
  }
867
867
  });
868
+
869
+ test("lookupWebFinger() caller abort releases a stalled session open", async () => {
870
+ const controller = new AbortController();
871
+ let finishOpen!: (session: PublicFetchSession) => void;
872
+ let closed = false;
873
+ const opening = new Promise<PublicFetchSession>((resolve) => {
874
+ finishOpen = resolve;
875
+ });
876
+ const lookup = lookupWebFingerInternal("acct:alice@example.com", {
877
+ signal: controller.signal,
878
+ }, { openHop: () => opening });
879
+ controller.abort();
880
+ deepStrictEqual(await settleWithin(lookup, 1000), null);
881
+ finishOpen({
882
+ url: new URL("https://example.com"),
883
+ fetch: () => {
884
+ throw new Error("fetch after abort");
885
+ },
886
+ close: () => {
887
+ closed = true;
888
+ return Promise.resolve();
889
+ },
890
+ });
891
+ await Promise.resolve();
892
+ await Promise.resolve();
893
+ ok(closed);
894
+ });
895
+
896
+ test("lookupWebFinger() deadline covers session opening", async () => {
897
+ const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
898
+ timeoutMs: 20,
899
+ openHop: () => new Promise(() => {}),
900
+ });
901
+ deepStrictEqual(await settleWithin(result, 1000), null);
902
+ });
903
+
904
+ test("lookupWebFinger() shares one deadline across redirects", async () => {
905
+ const descriptor: ResourceDescriptor = {
906
+ subject: "acct:alice@example.com",
907
+ links: [],
908
+ };
909
+ const pending: Promise<Response>[] = [];
910
+ const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
911
+ timeoutMs: 100,
912
+ openHop: (url) =>
913
+ Promise.resolve({
914
+ url: new URL(url),
915
+ fetch: () => {
916
+ const response = new Promise<Response>((resolve) => {
917
+ setTimeout(() => {
918
+ resolve(
919
+ url.includes("/final")
920
+ ? new Response(JSON.stringify(descriptor))
921
+ : new Response(null, {
922
+ status: 302,
923
+ headers: { Location: "/final" },
924
+ }),
925
+ );
926
+ }, 60);
927
+ });
928
+ pending.push(response);
929
+ return response;
930
+ },
931
+ close: () => Promise.resolve(),
932
+ }),
933
+ });
934
+ deepStrictEqual(await settleWithin(result, 1000), null);
935
+ await Promise.all(pending);
936
+ });
937
+
938
+ test("lookupWebFinger() caller signal cannot extend its deadline", async () => {
939
+ const signal = AbortSignal.timeout(5000);
940
+ let reason: unknown;
941
+ const result = lookupWebFingerInternal("acct:alice@example.com", {
942
+ signal,
943
+ }, {
944
+ timeoutMs: 50,
945
+ openHop: (_url, effectiveSignal) => {
946
+ effectiveSignal?.addEventListener("abort", () => {
947
+ reason = effectiveSignal.reason;
948
+ }, { once: true });
949
+ return new Promise(() => {});
950
+ },
951
+ });
952
+ deepStrictEqual(await settleWithin(result, 1000), null);
953
+ ok(!signal.aborted);
954
+ ok(reason instanceof DOMException);
955
+ deepStrictEqual(reason.name, "TimeoutError");
956
+ });
957
+
958
+ test("lookupWebFinger() deadline covers response headers", async () => {
959
+ let closed = false;
960
+ let fetchSignal: AbortSignal | null | undefined;
961
+ let fetchAborted = false;
962
+ const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
963
+ timeoutMs: 20,
964
+ openHop: () =>
965
+ Promise.resolve({
966
+ url: new URL("https://example.com"),
967
+ fetch: (_input, init) => {
968
+ fetchSignal = init?.signal;
969
+ fetchSignal?.addEventListener("abort", () => {
970
+ fetchAborted = true;
971
+ }, { once: true });
972
+ return new Promise(() => {});
973
+ },
974
+ close: () => {
975
+ closed = true;
976
+ return Promise.resolve();
977
+ },
978
+ }),
979
+ });
980
+ deepStrictEqual(await settleWithin(result, 1000), null);
981
+ ok(fetchSignal?.aborted);
982
+ ok(fetchAborted);
983
+ deepStrictEqual(fetchSignal.reason.name, "TimeoutError");
984
+ await Promise.resolve();
985
+ ok(closed);
986
+ });
987
+
988
+ test("lookupWebFinger() discards completed JSON when body stalls", async () => {
989
+ const descriptor: ResourceDescriptor = {
990
+ subject: "acct:alice@example.com",
991
+ links: [],
992
+ };
993
+ let cancelled!: () => void;
994
+ const cancellation = new Promise<void>((resolve) => {
995
+ cancelled = resolve;
996
+ });
997
+ const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
998
+ timeoutMs: 20,
999
+ openHop: () =>
1000
+ Promise.resolve({
1001
+ url: new URL("https://example.com"),
1002
+ fetch: () =>
1003
+ Promise.resolve(
1004
+ new Response(
1005
+ new ReadableStream<Uint8Array>({
1006
+ start(controller) {
1007
+ controller.enqueue(
1008
+ new TextEncoder().encode(JSON.stringify(descriptor)),
1009
+ );
1010
+ },
1011
+ cancel() {
1012
+ cancelled();
1013
+ },
1014
+ }),
1015
+ ),
1016
+ ),
1017
+ close: async () => {},
1018
+ }),
1019
+ });
1020
+ deepStrictEqual(await settleWithin(result, 1000), null);
1021
+ await settleWithin(cancellation, 1000);
1022
+ });
1023
+
1024
+ test("lookupWebFinger() accepts a response before its deadline", async () => {
1025
+ const descriptor: ResourceDescriptor = {
1026
+ subject: "acct:alice@example.com",
1027
+ links: [],
1028
+ };
1029
+ deepStrictEqual(
1030
+ await lookupWebFingerInternal("acct:alice@example.com", {}, {
1031
+ timeoutMs: 1000,
1032
+ openHop: () =>
1033
+ Promise.resolve({
1034
+ url: new URL("https://example.com"),
1035
+ fetch: () =>
1036
+ Promise.resolve(new Response(JSON.stringify(descriptor))),
1037
+ close: async () => {},
1038
+ }),
1039
+ }),
1040
+ descriptor,
1041
+ );
1042
+ });
package/src/lookup.ts CHANGED
@@ -46,7 +46,8 @@ export interface LookupWebFingerOptions {
46
46
  tracerProvider?: TracerProvider;
47
47
 
48
48
  /**
49
- * AbortSignal for cancelling the request.
49
+ * `AbortSignal` for cancelling the lookup sooner than its default 10-second
50
+ * deadline. A signal cannot extend that deadline.
50
51
  * @since 1.8.0
51
52
  */
52
53
  signal?: AbortSignal;