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