@fedify/webfinger 2.1.30 → 2.1.32

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.cjs CHANGED
@@ -1,10 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _opentelemetry_api = require("@opentelemetry/api");
2
3
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
4
+ let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
3
5
  let _logtape_logtape = require("@logtape/logtape");
4
- let _opentelemetry_api = require("@opentelemetry/api");
5
6
  //#region deno.json
6
7
  var name = "@fedify/webfinger";
7
- var version = "2.1.30";
8
+ var version = "2.1.32";
8
9
  //#endregion
9
10
  //#region src/body.ts
10
11
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -27,13 +28,18 @@ function validateBodySizeLimit(maxBytes) {
27
28
  * @param message The response or request to read.
28
29
  * @param maxBytes The maximum number of decoded bytes to read.
29
30
  * @param url The URL to include in errors and logs.
31
+ * @param signal The signal that cancels an in-progress body read.
30
32
  * @returns The decoded body text.
31
33
  * @throws {BodyTooLargeError} If the body exceeds the limit.
32
34
  * @internal
33
35
  */
34
- async function readBoundedText(message, maxBytes, url) {
36
+ async function readBoundedText(message, maxBytes, url, signal) {
35
37
  validateBodySizeLimit(maxBytes);
36
38
  const reader = message.body?.getReader();
39
+ const cancelOnAbort = () => {
40
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
41
+ };
42
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
37
43
  const tooLarge = () => {
38
44
  (0, _logtape_logtape.getLogger)([
39
45
  "fedify",
@@ -46,6 +52,7 @@ async function readBoundedText(message, maxBytes, url) {
46
52
  throw new BodyTooLargeError(url, maxBytes);
47
53
  };
48
54
  try {
55
+ signal?.throwIfAborted();
49
56
  const length = message.headers.get("Content-Length");
50
57
  const encoding = message.headers.get("Content-Encoding");
51
58
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -53,6 +60,7 @@ async function readBoundedText(message, maxBytes, url) {
53
60
  let size = 0;
54
61
  const textReader = new ReadableStream({ async pull(controller) {
55
62
  const { done, value } = await reader.read();
63
+ signal?.throwIfAborted();
56
64
  if (done) {
57
65
  controller.close();
58
66
  return;
@@ -65,9 +73,11 @@ async function readBoundedText(message, maxBytes, url) {
65
73
  const chunks = [];
66
74
  while (true) {
67
75
  const { done, value } = await textReader.read();
76
+ signal?.throwIfAborted();
68
77
  if (done) break;
69
78
  chunks.push(value);
70
79
  }
80
+ signal?.throwIfAborted();
71
81
  return chunks.join("");
72
82
  } finally {
73
83
  textReader.releaseLock();
@@ -76,48 +86,30 @@ async function readBoundedText(message, maxBytes, url) {
76
86
  if (reader != null) reader.cancel(error).catch(() => {});
77
87
  throw error;
78
88
  } finally {
89
+ signal?.removeEventListener("abort", cancelOnAbort);
79
90
  reader?.releaseLock();
80
91
  }
81
92
  }
82
93
  //#endregion
83
- //#region src/lookup.ts
94
+ //#region src/lookup-impl.ts
84
95
  const logger = (0, _logtape_logtape.getLogger)([
85
96
  "fedify",
86
97
  "webfinger",
87
98
  "lookup"
88
99
  ]);
89
100
  const DEFAULT_MAX_REDIRECTION = 5;
101
+ const DEFAULT_TIMEOUT_MS = 1e4;
90
102
  /**
91
- * Looks up a WebFinger resource.
103
+ * Looks up a WebFinger resource, opening a fetch session per hop. This is
104
+ * the implementation of {@link lookupWebFinger}, which is not exported from
105
+ * the package entry point.
92
106
  * @param resource The resource URL to look up.
93
107
  * @param options Extra options for looking up the resource.
108
+ * @param deps The dependencies.
94
109
  * @returns The resource descriptor, or `null` if not found.
95
- * @since 0.2.0
110
+ * @internal
96
111
  */
97
- async function lookupWebFinger(resource, options = {}) {
98
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("webfinger.lookup", {
99
- kind: _opentelemetry_api.SpanKind.CLIENT,
100
- attributes: {
101
- "webfinger.resource": resource.toString(),
102
- "webfinger.resource.scheme": typeof resource === "string" ? resource.replace(/:.*$/, "") : resource.protocol.replace(/:$/, "")
103
- }
104
- }, async (span) => {
105
- try {
106
- const result = await lookupWebFingerInternal(resource, options);
107
- span.setStatus({ code: result === null ? _opentelemetry_api.SpanStatusCode.ERROR : _opentelemetry_api.SpanStatusCode.OK });
108
- return result;
109
- } catch (error) {
110
- span.setStatus({
111
- code: _opentelemetry_api.SpanStatusCode.ERROR,
112
- message: String(error)
113
- });
114
- throw error;
115
- } finally {
116
- span.end();
117
- }
118
- });
119
- }
120
- async function lookupWebFingerInternal(resource, options = {}) {
112
+ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
121
113
  if (typeof resource === "string") resource = new URL(resource);
122
114
  let protocol = "https:";
123
115
  let server;
@@ -130,78 +122,226 @@ async function lookupWebFingerInternal(resource, options = {}) {
130
122
  protocol = resource.protocol;
131
123
  server = resource.host;
132
124
  }
133
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
125
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
134
126
  url.searchParams.set("resource", resource.href);
127
+ const controller = new AbortController();
128
+ const signal = controller.signal;
129
+ let timedOut = false;
130
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
131
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new RangeError("The WebFinger timeout must be a positive integer of at most 2147483647 ms.");
132
+ const timeout = setTimeout(() => {
133
+ timedOut = true;
134
+ controller.abort(new DOMException("WebFinger lookup timed out", "TimeoutError"));
135
+ }, timeoutMs);
136
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
137
+ if (options.signal?.aborted) abortFromCaller();
138
+ else options.signal?.addEventListener("abort", abortFromCaller, { once: true });
139
+ let stopWaiting = () => {};
140
+ const aborted = new Promise((resolve) => {
141
+ if (signal.aborted) resolve(null);
142
+ else {
143
+ stopWaiting = () => signal.removeEventListener("abort", onAbort);
144
+ const onAbort = () => resolve(null);
145
+ signal.addEventListener("abort", onAbort, { once: true });
146
+ }
147
+ });
148
+ 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);
149
+ try {
150
+ const result = await Promise.race([work, aborted]);
151
+ if (signal.aborted) {
152
+ if (timedOut) logger.warn("WebFinger lookup timed out for {url} after {timeoutMs} ms.", {
153
+ url: url.href,
154
+ timeoutMs
155
+ });
156
+ return null;
157
+ }
158
+ return result;
159
+ } catch (error) {
160
+ if (signal.aborted) return null;
161
+ throw error;
162
+ } finally {
163
+ clearTimeout(timeout);
164
+ stopWaiting();
165
+ options.signal?.removeEventListener("abort", abortFromCaller);
166
+ work.catch(() => {});
167
+ }
168
+ }
169
+ async function lookupHops(initialUrl, options, openHop, signal) {
170
+ let url = initialUrl;
135
171
  let redirected = 0;
136
172
  while (true) {
173
+ if (signal.aborted) return null;
137
174
  logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
138
- let response;
139
- if (options.allowPrivateAddress !== true) try {
140
- await (0, _fedify_vocab_runtime.validatePublicUrl)(url.href);
141
- } catch (e) {
142
- if (e instanceof _fedify_vocab_runtime.UrlError) {
143
- if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
175
+ const session = await openSession(url, openHop, signal);
176
+ if (session == null) return null;
177
+ let hop;
178
+ try {
179
+ if (signal.aborted) return null;
180
+ hop = await fetchHopUntilAbort(session, url, options, signal);
181
+ } finally {
182
+ if (signal.aborted) session.close().catch((error) => {
183
+ logger.debug("Failed to close WebFinger session for {url}: {error}", {
144
184
  url: url.href,
145
- error: e
185
+ error
146
186
  });
147
- else logger.error("Invalid URL for WebFinger resource descriptor: {error}", { error: e });
148
- return null;
149
- }
150
- throw e;
187
+ });
188
+ else await session.close();
151
189
  }
152
- try {
153
- response = await fetch(url, {
154
- headers: {
155
- Accept: "application/jrd+json",
156
- "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
157
- },
158
- redirect: "manual",
159
- signal: options.signal
190
+ if (signal.aborted) return null;
191
+ if ("result" in hop) return hop.result;
192
+ redirected++;
193
+ const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
194
+ if (redirected >= maxRedirection) {
195
+ logger.error("Too many redirections ({redirections}) while fetching WebFinger resource descriptor.", { redirections: redirected });
196
+ return null;
197
+ }
198
+ const redirectedUrl = new URL(hop.redirect, url);
199
+ if (redirectedUrl.protocol !== url.protocol) {
200
+ logger.error("Redirected to a different protocol ({protocol} to {redirectedProtocol}) while fetching WebFinger resource descriptor.", {
201
+ protocol: url.protocol,
202
+ redirectedProtocol: redirectedUrl.protocol
160
203
  });
161
- } catch (error) {
162
- logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
204
+ return null;
205
+ }
206
+ url = redirectedUrl;
207
+ }
208
+ }
209
+ /** Lets the session close even when a custom fetch or body ignores abort. */
210
+ async function fetchHopUntilAbort(session, url, options, signal) {
211
+ const fetching = fetchHop(session, url, options, signal);
212
+ let onAbort;
213
+ const aborted = new Promise((resolve) => {
214
+ if (signal.aborted) resolve({ result: null });
215
+ else {
216
+ onAbort = () => resolve({ result: null });
217
+ signal.addEventListener("abort", onAbort, { once: true });
218
+ }
219
+ });
220
+ try {
221
+ return await Promise.race([fetching, aborted]);
222
+ } finally {
223
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
224
+ fetching.catch(() => {});
225
+ }
226
+ }
227
+ /**
228
+ * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
229
+ * or an aborted lookup yields `null` instead of an error.
230
+ */
231
+ async function openSession(url, openHop, signal) {
232
+ try {
233
+ return await openHop(url.href, signal);
234
+ } catch (e) {
235
+ if (e instanceof _fedify_vocab_runtime.UrlError) {
236
+ if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
163
237
  url: url.href,
164
- error
238
+ error: e
165
239
  });
240
+ else logger.error("Invalid URL for WebFinger resource descriptor: {error}", { error: e });
166
241
  return null;
167
242
  }
168
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
169
- redirected++;
170
- const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
171
- if (redirected >= maxRedirection) {
172
- logger.error("Too many redirections ({redirections}) while fetching WebFinger resource descriptor.", { redirections: redirected });
173
- return null;
174
- }
175
- const redirectedUrl = new URL(response.headers.get("Location"), response.url == null || response.url === "" ? url : response.url);
176
- if (redirectedUrl.protocol !== url.protocol) {
177
- logger.error("Redirected to a different protocol ({protocol} to {redirectedProtocol}) while fetching WebFinger resource descriptor.", {
178
- protocol: url.protocol,
179
- redirectedProtocol: redirectedUrl.protocol
180
- });
181
- return null;
182
- }
183
- url = redirectedUrl;
184
- continue;
185
- }
186
- if (!response.ok) {
187
- logger.debug("Failed to fetch WebFinger resource descriptor: {status} {statusText}.", {
243
+ if (signal?.aborted) {
244
+ logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
188
245
  url: url.href,
189
- status: response.status,
190
- statusText: response.statusText
246
+ error: e
191
247
  });
192
248
  return null;
193
249
  }
194
- try {
195
- return JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url));
196
- } catch (e) {
197
- if (e instanceof BodyTooLargeError) return null;
198
- if (e instanceof SyntaxError) {
199
- logger.debug("Failed to parse WebFinger resource descriptor as JSON: {error}", { error: e });
200
- return null;
201
- }
202
- throw e;
250
+ throw e;
251
+ }
252
+ }
253
+ /**
254
+ * Fetches a hop with the given session, and consumes the response body or
255
+ * starts cancelling it before returning. The caller closes the session.
256
+ */
257
+ async function fetchHop(session, url, options, signal) {
258
+ let response;
259
+ try {
260
+ response = await session.fetch(url, {
261
+ headers: {
262
+ Accept: "application/jrd+json",
263
+ "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
264
+ },
265
+ redirect: "manual",
266
+ signal
267
+ });
268
+ } catch (error) {
269
+ logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
270
+ url: url.href,
271
+ error
272
+ });
273
+ return { result: null };
274
+ }
275
+ if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
276
+ cancelBody(response, url);
277
+ return { redirect: response.headers.get("Location") };
278
+ }
279
+ if (!response.ok) {
280
+ logger.debug("Failed to fetch WebFinger resource descriptor: {status} {statusText}.", {
281
+ url: url.href,
282
+ status: response.status,
283
+ statusText: response.statusText
284
+ });
285
+ cancelBody(response, url);
286
+ return { result: null };
287
+ }
288
+ try {
289
+ return { result: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url, signal)) };
290
+ } catch (e) {
291
+ if (e instanceof BodyTooLargeError) return { result: null };
292
+ if (e instanceof SyntaxError) {
293
+ logger.debug("Failed to parse WebFinger resource descriptor as JSON: {error}", { error: e });
294
+ return { result: null };
203
295
  }
296
+ throw e;
204
297
  }
205
298
  }
299
+ /**
300
+ * Starts cancelling a response body that is not read, without waiting for it
301
+ * to settle. The cancellation of a branch of a tee (e.g., a body cloned by
302
+ * a fetch mock) settles only after the other branch is cancelled too, per
303
+ * the Streams standard, so awaiting it could block forever. A failure is
304
+ * only logged.
305
+ */
306
+ function cancelBody(response, url) {
307
+ response.body?.cancel().catch((error) => {
308
+ logger.debug("Failed to cancel the response body from {url}: {error}", {
309
+ url: url.href,
310
+ error
311
+ });
312
+ });
313
+ }
314
+ //#endregion
315
+ //#region src/lookup.ts
316
+ /**
317
+ * Looks up a WebFinger resource.
318
+ * @param resource The resource URL to look up.
319
+ * @param options Extra options for looking up the resource.
320
+ * @returns The resource descriptor, or `null` if not found.
321
+ * @since 0.2.0
322
+ */
323
+ async function lookupWebFinger(resource, options = {}) {
324
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("webfinger.lookup", {
325
+ kind: _opentelemetry_api.SpanKind.CLIENT,
326
+ attributes: {
327
+ "webfinger.resource": resource.toString(),
328
+ "webfinger.resource.scheme": typeof resource === "string" ? resource.replace(/:.*$/, "") : resource.protocol.replace(/:$/, "")
329
+ }
330
+ }, async (span) => {
331
+ try {
332
+ const result = await lookupWebFingerInternal(resource, options);
333
+ span.setStatus({ code: result === null ? _opentelemetry_api.SpanStatusCode.ERROR : _opentelemetry_api.SpanStatusCode.OK });
334
+ return result;
335
+ } catch (error) {
336
+ span.setStatus({
337
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
338
+ message: String(error)
339
+ });
340
+ throw error;
341
+ } finally {
342
+ span.end();
343
+ }
344
+ });
345
+ }
206
346
  //#endregion
207
347
  exports.lookupWebFinger = lookupWebFinger;
package/dist/mod.d.cts CHANGED
@@ -95,7 +95,8 @@ interface LookupWebFingerOptions {
95
95
  */
96
96
  tracerProvider?: TracerProvider;
97
97
  /**
98
- * AbortSignal for cancelling the request.
98
+ * `AbortSignal` for cancelling the lookup sooner than its default 10-second
99
+ * deadline. A signal cannot extend that deadline.
99
100
  * @since 1.8.0
100
101
  */
101
102
  signal?: AbortSignal;
package/dist/mod.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { GetUserAgentOptions } from "@fedify/vocab-runtime";
2
1
  import { TracerProvider } from "@opentelemetry/api";
2
+ import { GetUserAgentOptions } from "@fedify/vocab-runtime";
3
3
 
4
4
  //#region src/jrd.d.ts
5
5
  /**
@@ -95,7 +95,8 @@ interface LookupWebFingerOptions {
95
95
  */
96
96
  tracerProvider?: TracerProvider;
97
97
  /**
98
- * AbortSignal for cancelling the request.
98
+ * `AbortSignal` for cancelling the lookup sooner than its default 10-second
99
+ * deadline. A signal cannot extend that deadline.
99
100
  * @since 1.8.0
100
101
  */
101
102
  signal?: AbortSignal;