@fedify/webfinger 2.0.36-dev.2828 → 2.0.36-dev.2843
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 +4 -1
- package/deno.json +1 -1
- package/dist/lookup.test.cjs +232 -11
- package/dist/lookup.test.js +232 -11
- package/dist/mod.cjs +92 -11
- package/dist/mod.d.cts +2 -1
- package/dist/mod.d.ts +2 -1
- package/dist/mod.js +92 -11
- package/package.json +2 -2
- package/src/body.ts +11 -0
- package/src/lookup-impl.ts +120 -11
- package/src/lookup.test.ts +175 -0
- package/src/lookup.ts +2 -1
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.0.36-dev.
|
|
7
|
+
var version = "2.0.36-dev.2843+780589e4";
|
|
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
|
-
|
|
124
|
+
const url = new URL(`${protocol}//${server}/.well-known/webfinger`);
|
|
114
125
|
url.searchParams.set("resource", resource.href);
|
|
115
|
-
const
|
|
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,
|
|
174
|
+
const session = await openSession(url, openHop, signal);
|
|
120
175
|
if (session == null) return null;
|
|
121
176
|
let hop;
|
|
122
177
|
try {
|
|
123
|
-
|
|
178
|
+
if (signal.aborted) return null;
|
|
179
|
+
hop = await fetchHopUntilAbort(session, url, options, signal);
|
|
124
180
|
} finally {
|
|
125
|
-
|
|
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
|
|
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.0.36-dev.
|
|
3
|
+
"version": "2.0.36-dev.2843+780589e4",
|
|
4
4
|
"homepage": "https://fedify.dev/",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"@logtape/logtape": "^2.0.0",
|
|
61
61
|
"@opentelemetry/api": "~1.9.0",
|
|
62
62
|
"es-toolkit": "1.43.0",
|
|
63
|
-
"@fedify/vocab-runtime": "2.0.36-dev.
|
|
63
|
+
"@fedify/vocab-runtime": "2.0.36-dev.2843+780589e4"
|
|
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
|
}
|
package/src/lookup-impl.ts
CHANGED
|
@@ -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?: (
|
|
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
|
-
|
|
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:
|
|
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,
|
|
151
|
+
const session = await openSession(url, openHop, signal);
|
|
77
152
|
if (session == null) return null;
|
|
78
153
|
let hop: HopResult;
|
|
79
154
|
try {
|
|
80
|
-
|
|
155
|
+
if (signal.aborted) return null;
|
|
156
|
+
hop = await fetchHopUntilAbort(session, url, options, signal);
|
|
81
157
|
} finally {
|
|
82
|
-
|
|
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
|
|
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) {
|
package/src/lookup.test.ts
CHANGED
|
@@ -862,3 +862,178 @@ test("lookupWebFinger() does not wait for cancelling response bodies", async (t)
|
|
|
862
862
|
fetchMock.hardReset();
|
|
863
863
|
}
|
|
864
864
|
});
|
|
865
|
+
|
|
866
|
+
test("lookupWebFinger() caller abort releases a stalled session open", async () => {
|
|
867
|
+
const controller = new AbortController();
|
|
868
|
+
let finishOpen!: (session: PublicFetchSession) => void;
|
|
869
|
+
let closed = false;
|
|
870
|
+
const opening = new Promise<PublicFetchSession>((resolve) => {
|
|
871
|
+
finishOpen = resolve;
|
|
872
|
+
});
|
|
873
|
+
const lookup = lookupWebFingerInternal("acct:alice@example.com", {
|
|
874
|
+
signal: controller.signal,
|
|
875
|
+
}, { openHop: () => opening });
|
|
876
|
+
controller.abort();
|
|
877
|
+
deepStrictEqual(await settleWithin(lookup, 1000), null);
|
|
878
|
+
finishOpen({
|
|
879
|
+
url: new URL("https://example.com"),
|
|
880
|
+
fetch: () => {
|
|
881
|
+
throw new Error("fetch after abort");
|
|
882
|
+
},
|
|
883
|
+
close: () => {
|
|
884
|
+
closed = true;
|
|
885
|
+
return Promise.resolve();
|
|
886
|
+
},
|
|
887
|
+
});
|
|
888
|
+
await Promise.resolve();
|
|
889
|
+
await Promise.resolve();
|
|
890
|
+
ok(closed);
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
test("lookupWebFinger() deadline covers session opening", async () => {
|
|
894
|
+
const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
|
|
895
|
+
timeoutMs: 20,
|
|
896
|
+
openHop: () => new Promise(() => {}),
|
|
897
|
+
});
|
|
898
|
+
deepStrictEqual(await settleWithin(result, 1000), null);
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
test("lookupWebFinger() shares one deadline across redirects", async () => {
|
|
902
|
+
const descriptor: ResourceDescriptor = {
|
|
903
|
+
subject: "acct:alice@example.com",
|
|
904
|
+
links: [],
|
|
905
|
+
};
|
|
906
|
+
const pending: Promise<Response>[] = [];
|
|
907
|
+
const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
|
|
908
|
+
timeoutMs: 100,
|
|
909
|
+
openHop: (url) =>
|
|
910
|
+
Promise.resolve({
|
|
911
|
+
url: new URL(url),
|
|
912
|
+
fetch: () => {
|
|
913
|
+
const response = new Promise<Response>((resolve) => {
|
|
914
|
+
setTimeout(() => {
|
|
915
|
+
resolve(
|
|
916
|
+
url.includes("/final")
|
|
917
|
+
? new Response(JSON.stringify(descriptor))
|
|
918
|
+
: new Response(null, {
|
|
919
|
+
status: 302,
|
|
920
|
+
headers: { Location: "/final" },
|
|
921
|
+
}),
|
|
922
|
+
);
|
|
923
|
+
}, 60);
|
|
924
|
+
});
|
|
925
|
+
pending.push(response);
|
|
926
|
+
return response;
|
|
927
|
+
},
|
|
928
|
+
close: () => Promise.resolve(),
|
|
929
|
+
}),
|
|
930
|
+
});
|
|
931
|
+
deepStrictEqual(await settleWithin(result, 1000), null);
|
|
932
|
+
await Promise.all(pending);
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
test("lookupWebFinger() caller signal cannot extend its deadline", async () => {
|
|
936
|
+
const signal = AbortSignal.timeout(5000);
|
|
937
|
+
let reason: unknown;
|
|
938
|
+
const result = lookupWebFingerInternal("acct:alice@example.com", {
|
|
939
|
+
signal,
|
|
940
|
+
}, {
|
|
941
|
+
timeoutMs: 50,
|
|
942
|
+
openHop: (_url, effectiveSignal) => {
|
|
943
|
+
effectiveSignal?.addEventListener("abort", () => {
|
|
944
|
+
reason = effectiveSignal.reason;
|
|
945
|
+
}, { once: true });
|
|
946
|
+
return new Promise(() => {});
|
|
947
|
+
},
|
|
948
|
+
});
|
|
949
|
+
deepStrictEqual(await settleWithin(result, 1000), null);
|
|
950
|
+
ok(!signal.aborted);
|
|
951
|
+
ok(reason instanceof DOMException);
|
|
952
|
+
deepStrictEqual(reason.name, "TimeoutError");
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
test("lookupWebFinger() deadline covers response headers", async () => {
|
|
956
|
+
let closed = false;
|
|
957
|
+
let fetchSignal: AbortSignal | null | undefined;
|
|
958
|
+
let fetchAborted = false;
|
|
959
|
+
const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
|
|
960
|
+
timeoutMs: 20,
|
|
961
|
+
openHop: () =>
|
|
962
|
+
Promise.resolve({
|
|
963
|
+
url: new URL("https://example.com"),
|
|
964
|
+
fetch: (_input, init) => {
|
|
965
|
+
fetchSignal = init?.signal;
|
|
966
|
+
fetchSignal?.addEventListener("abort", () => {
|
|
967
|
+
fetchAborted = true;
|
|
968
|
+
}, { once: true });
|
|
969
|
+
return new Promise(() => {});
|
|
970
|
+
},
|
|
971
|
+
close: () => {
|
|
972
|
+
closed = true;
|
|
973
|
+
return Promise.resolve();
|
|
974
|
+
},
|
|
975
|
+
}),
|
|
976
|
+
});
|
|
977
|
+
deepStrictEqual(await settleWithin(result, 1000), null);
|
|
978
|
+
ok(fetchSignal?.aborted);
|
|
979
|
+
ok(fetchAborted);
|
|
980
|
+
deepStrictEqual(fetchSignal.reason.name, "TimeoutError");
|
|
981
|
+
await Promise.resolve();
|
|
982
|
+
ok(closed);
|
|
983
|
+
});
|
|
984
|
+
|
|
985
|
+
test("lookupWebFinger() discards completed JSON when body stalls", async () => {
|
|
986
|
+
const descriptor: ResourceDescriptor = {
|
|
987
|
+
subject: "acct:alice@example.com",
|
|
988
|
+
links: [],
|
|
989
|
+
};
|
|
990
|
+
let cancelled!: () => void;
|
|
991
|
+
const cancellation = new Promise<void>((resolve) => {
|
|
992
|
+
cancelled = resolve;
|
|
993
|
+
});
|
|
994
|
+
const result = lookupWebFingerInternal("acct:alice@example.com", {}, {
|
|
995
|
+
timeoutMs: 20,
|
|
996
|
+
openHop: () =>
|
|
997
|
+
Promise.resolve({
|
|
998
|
+
url: new URL("https://example.com"),
|
|
999
|
+
fetch: () =>
|
|
1000
|
+
Promise.resolve(
|
|
1001
|
+
new Response(
|
|
1002
|
+
new ReadableStream<Uint8Array>({
|
|
1003
|
+
start(controller) {
|
|
1004
|
+
controller.enqueue(
|
|
1005
|
+
new TextEncoder().encode(JSON.stringify(descriptor)),
|
|
1006
|
+
);
|
|
1007
|
+
},
|
|
1008
|
+
cancel() {
|
|
1009
|
+
cancelled();
|
|
1010
|
+
},
|
|
1011
|
+
}),
|
|
1012
|
+
),
|
|
1013
|
+
),
|
|
1014
|
+
close: async () => {},
|
|
1015
|
+
}),
|
|
1016
|
+
});
|
|
1017
|
+
deepStrictEqual(await settleWithin(result, 1000), null);
|
|
1018
|
+
await settleWithin(cancellation, 1000);
|
|
1019
|
+
});
|
|
1020
|
+
|
|
1021
|
+
test("lookupWebFinger() accepts a response before its deadline", async () => {
|
|
1022
|
+
const descriptor: ResourceDescriptor = {
|
|
1023
|
+
subject: "acct:alice@example.com",
|
|
1024
|
+
links: [],
|
|
1025
|
+
};
|
|
1026
|
+
deepStrictEqual(
|
|
1027
|
+
await lookupWebFingerInternal("acct:alice@example.com", {}, {
|
|
1028
|
+
timeoutMs: 1000,
|
|
1029
|
+
openHop: () =>
|
|
1030
|
+
Promise.resolve({
|
|
1031
|
+
url: new URL("https://example.com"),
|
|
1032
|
+
fetch: () =>
|
|
1033
|
+
Promise.resolve(new Response(JSON.stringify(descriptor))),
|
|
1034
|
+
close: async () => {},
|
|
1035
|
+
}),
|
|
1036
|
+
}),
|
|
1037
|
+
descriptor,
|
|
1038
|
+
);
|
|
1039
|
+
});
|
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
|
|
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;
|