@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.
@@ -0,0 +1,343 @@
1
+ import { getUserAgent, UrlError } from "@fedify/vocab-runtime";
2
+ import {
3
+ openDirectFetch,
4
+ openPublicFetch,
5
+ type PublicFetchSession,
6
+ } from "@fedify/vocab-runtime/internal";
7
+ import { getLogger } from "@logtape/logtape";
8
+ import { BodyTooLargeError, MAX_BODY_SIZE, readBoundedText } from "./body.ts";
9
+ import type { ResourceDescriptor } from "./jrd.ts";
10
+ import type { LookupWebFingerOptions } from "./lookup.ts";
11
+
12
+ const logger = getLogger(["fedify", "webfinger", "lookup"]);
13
+
14
+ const DEFAULT_MAX_REDIRECTION = 5;
15
+ const DEFAULT_TIMEOUT_MS = 10_000;
16
+
17
+ /**
18
+ * The dependencies of {@link lookupWebFingerInternal}.
19
+ * @internal
20
+ */
21
+ export interface LookupWebFingerDependencies {
22
+ /**
23
+ * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
24
+ * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
25
+ */
26
+ readonly openHop?: (
27
+ url: string,
28
+ signal?: AbortSignal,
29
+ ) => Promise<PublicFetchSession>;
30
+ /** Overrides the lookup deadline for internal tests. */
31
+ readonly timeoutMs?: number;
32
+ }
33
+
34
+ /**
35
+ * The outcome of a single hop: either a redirect to follow, or the final
36
+ * result of the lookup.
37
+ */
38
+ type HopResult =
39
+ | { readonly redirect: string }
40
+ | { readonly result: ResourceDescriptor | null };
41
+
42
+ /**
43
+ * Looks up a WebFinger resource, opening a fetch session per hop. This is
44
+ * the implementation of {@link lookupWebFinger}, which is not exported from
45
+ * the package entry point.
46
+ * @param resource The resource URL to look up.
47
+ * @param options Extra options for looking up the resource.
48
+ * @param deps The dependencies.
49
+ * @returns The resource descriptor, or `null` if not found.
50
+ * @internal
51
+ */
52
+ export async function lookupWebFingerInternal(
53
+ resource: URL | string,
54
+ options: LookupWebFingerOptions = {},
55
+ deps: LookupWebFingerDependencies = {},
56
+ ): Promise<ResourceDescriptor | null> {
57
+ if (typeof resource === "string") resource = new URL(resource);
58
+ let protocol = "https:";
59
+ let server: string;
60
+ if (resource.protocol === "acct:") {
61
+ const atPos = resource.pathname.lastIndexOf("@");
62
+ if (atPos < 0) return null;
63
+ server = resource.pathname.substring(atPos + 1);
64
+ if (server === "") return null;
65
+ } else {
66
+ protocol = resource.protocol;
67
+ server = resource.host;
68
+ }
69
+ const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
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
+ });
103
+ const openHop = deps.openHop ??
104
+ ((hopUrl: string, hopSignal?: AbortSignal) =>
105
+ options.allowPrivateAddress === true
106
+ ? openDirectFetch(hopUrl)
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;
144
+ let redirected = 0;
145
+ while (true) {
146
+ if (signal.aborted) return null;
147
+ logger.debug(
148
+ "Fetching WebFinger resource descriptor from {url}...",
149
+ { url: url.href },
150
+ );
151
+ const session = await openSession(url, openHop, signal);
152
+ if (session == null) return null;
153
+ let hop: HopResult;
154
+ try {
155
+ if (signal.aborted) return null;
156
+ hop = await fetchHopUntilAbort(session, url, options, signal);
157
+ } finally {
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();
166
+ }
167
+ if (signal.aborted) return null;
168
+ if ("result" in hop) return hop.result;
169
+ redirected++;
170
+ const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
171
+ if (redirected >= maxRedirection) {
172
+ logger.error(
173
+ "Too many redirections ({redirections}) while fetching WebFinger " +
174
+ "resource descriptor.",
175
+ { redirections: redirected },
176
+ );
177
+ return null;
178
+ }
179
+ // The request URL is the base, since a pinned response's url can be an
180
+ // IP address URL:
181
+ const redirectedUrl = new URL(hop.redirect, url);
182
+ if (redirectedUrl.protocol !== url.protocol) {
183
+ logger.error(
184
+ "Redirected to a different protocol ({protocol} to " +
185
+ "{redirectedProtocol}) while fetching WebFinger resource " +
186
+ "descriptor.",
187
+ {
188
+ protocol: url.protocol,
189
+ redirectedProtocol: redirectedUrl.protocol,
190
+ },
191
+ );
192
+ return null;
193
+ }
194
+ url = redirectedUrl;
195
+ }
196
+ }
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
+
222
+ /**
223
+ * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
224
+ * or an aborted lookup yields `null` instead of an error.
225
+ */
226
+ async function openSession(
227
+ url: URL,
228
+ openHop: (url: string, signal?: AbortSignal) => Promise<PublicFetchSession>,
229
+ signal: AbortSignal | undefined,
230
+ ): Promise<PublicFetchSession | null> {
231
+ try {
232
+ return await openHop(url.href, signal);
233
+ } catch (e) {
234
+ if (e instanceof UrlError) {
235
+ if (e.reason === "dns") {
236
+ logger.debug("DNS lookup failed for {url}", {
237
+ url: url.href,
238
+ error: e,
239
+ });
240
+ } else {
241
+ logger.error(
242
+ "Invalid URL for WebFinger resource descriptor: {error}",
243
+ { error: e },
244
+ );
245
+ }
246
+ // TODO: When merging forward into 2.3-maintenance and later, where
247
+ // this returns { resource: null, result: "network_error", remoteHost }
248
+ // instead of null, keep that return value for both reasons.
249
+ return null;
250
+ }
251
+ if (signal?.aborted) {
252
+ logger.debug(
253
+ "Failed to fetch WebFinger resource descriptor: {error}",
254
+ { url: url.href, error: e },
255
+ );
256
+ return null;
257
+ }
258
+ throw e;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Fetches a hop with the given session, and consumes the response body or
264
+ * starts cancelling it before returning. The caller closes the session.
265
+ */
266
+ async function fetchHop(
267
+ session: PublicFetchSession,
268
+ url: URL,
269
+ options: LookupWebFingerOptions,
270
+ signal: AbortSignal,
271
+ ): Promise<HopResult> {
272
+ let response: Response;
273
+ try {
274
+ response = await session.fetch(url, {
275
+ headers: {
276
+ Accept: "application/jrd+json",
277
+ "User-Agent": typeof options.userAgent === "string"
278
+ ? options.userAgent
279
+ : getUserAgent(options.userAgent),
280
+ },
281
+ redirect: "manual",
282
+ signal,
283
+ });
284
+ } catch (error) {
285
+ logger.debug(
286
+ "Failed to fetch WebFinger resource descriptor: {error}",
287
+ { url: url.href, error },
288
+ );
289
+ return { result: null };
290
+ }
291
+ if (
292
+ response.status >= 300 && response.status < 400 &&
293
+ response.headers.has("Location")
294
+ ) {
295
+ cancelBody(response, url);
296
+ return { redirect: response.headers.get("Location")! };
297
+ }
298
+ if (!response.ok) {
299
+ logger.debug(
300
+ "Failed to fetch WebFinger resource descriptor: {status} {statusText}.",
301
+ {
302
+ url: url.href,
303
+ status: response.status,
304
+ statusText: response.statusText,
305
+ },
306
+ );
307
+ cancelBody(response, url);
308
+ return { result: null };
309
+ }
310
+ try {
311
+ return {
312
+ result: JSON.parse(
313
+ await readBoundedText(response, MAX_BODY_SIZE, url, signal),
314
+ ) as ResourceDescriptor,
315
+ };
316
+ } catch (e) {
317
+ if (e instanceof BodyTooLargeError) return { result: null };
318
+ if (e instanceof SyntaxError) {
319
+ logger.debug(
320
+ "Failed to parse WebFinger resource descriptor as JSON: {error}",
321
+ { error: e },
322
+ );
323
+ return { result: null };
324
+ }
325
+ throw e;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Starts cancelling a response body that is not read, without waiting for it
331
+ * to settle. The cancellation of a branch of a tee (e.g., a body cloned by
332
+ * a fetch mock) settles only after the other branch is cancelled too, per
333
+ * the Streams standard, so awaiting it could block forever. A failure is
334
+ * only logged.
335
+ */
336
+ function cancelBody(response: Response, url: URL): void {
337
+ response.body?.cancel().catch((error) => {
338
+ logger.debug(
339
+ "Failed to cancel the response body from {url}: {error}",
340
+ { url: url.href, error },
341
+ );
342
+ });
343
+ }