@fedify/webfinger 2.3.15-dev.2482 → 2.3.15

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.3.15-dev.2482+41d364a2";
8
+ var version = "2.3.15";
8
9
  //#endregion
9
10
  //#region src/body.ts
10
11
  /** Decoded JSON body limit: 16 MiB. @internal */
@@ -80,13 +81,223 @@ async function readBoundedText(message, maxBytes, url) {
80
81
  }
81
82
  }
82
83
  //#endregion
83
- //#region src/lookup.ts
84
+ //#region src/lookup-impl.ts
84
85
  const logger = (0, _logtape_logtape.getLogger)([
85
86
  "fedify",
86
87
  "webfinger",
87
88
  "lookup"
88
89
  ]);
89
90
  const DEFAULT_MAX_REDIRECTION = 5;
91
+ /**
92
+ * Looks up a WebFinger resource, opening a fetch session per hop. This is
93
+ * the implementation of {@link lookupWebFinger}, which is not exported from
94
+ * the package entry point.
95
+ * @param resource The resource URL to look up.
96
+ * @param options Extra options for looking up the resource.
97
+ * @param deps The dependencies.
98
+ * @returns The resource descriptor and terminal lookup classification.
99
+ * @internal
100
+ */
101
+ async function lookupWebFingerInternal(resource, options = {}, deps = {}) {
102
+ if (typeof resource === "string") resource = new URL(resource);
103
+ let protocol = "https:";
104
+ let server;
105
+ if (resource.protocol === "acct:" || resource.protocol === "mailto:") {
106
+ const atPos = resource.pathname.lastIndexOf("@");
107
+ if (atPos < 0) return {
108
+ resource: null,
109
+ result: "invalid"
110
+ };
111
+ server = resource.pathname.substring(atPos + 1);
112
+ if (server === "" || /[/?#]/.test(server)) return {
113
+ resource: null,
114
+ result: "invalid"
115
+ };
116
+ if (resource.protocol === "acct:" && (resource.search !== "" || resource.hash !== "")) return {
117
+ resource: null,
118
+ result: "invalid"
119
+ };
120
+ } else {
121
+ protocol = resource.protocol;
122
+ server = resource.host;
123
+ }
124
+ let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
125
+ url.searchParams.set("resource", resource.href);
126
+ const openHop = deps.openHop ?? ((hopUrl) => options.allowPrivateAddress === true ? (0, _fedify_vocab_runtime_internal.openDirectFetch)(hopUrl) : (0, _fedify_vocab_runtime_internal.openPublicFetch)(hopUrl, { signal: options.signal }));
127
+ let redirected = 0;
128
+ while (true) {
129
+ logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
130
+ const remoteHost = url.host;
131
+ const session = await openSession(url, openHop, options.signal);
132
+ if (session == null) return {
133
+ resource: null,
134
+ result: "network_error",
135
+ remoteHost
136
+ };
137
+ let hop;
138
+ try {
139
+ hop = await fetchHop(session, url, options);
140
+ } finally {
141
+ await session.close();
142
+ }
143
+ if ("outcome" in hop) return hop.outcome;
144
+ redirected++;
145
+ const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
146
+ if (redirected > maxRedirection) {
147
+ logger.error("Too many redirections ({redirections}) while fetching WebFinger resource descriptor.", { redirections: redirected });
148
+ return {
149
+ resource: null,
150
+ result: "invalid",
151
+ statusCode: hop.statusCode,
152
+ remoteHost
153
+ };
154
+ }
155
+ let redirectedUrl;
156
+ try {
157
+ redirectedUrl = new URL(hop.redirect, url);
158
+ } catch (error) {
159
+ logger.error("Invalid Location header while following WebFinger redirect: {error}", {
160
+ url: url.href,
161
+ error
162
+ });
163
+ return {
164
+ resource: null,
165
+ result: "invalid",
166
+ statusCode: hop.statusCode,
167
+ remoteHost
168
+ };
169
+ }
170
+ if (redirectedUrl.protocol !== url.protocol) {
171
+ logger.error("Redirected to a different protocol ({protocol} to {redirectedProtocol}) while fetching WebFinger resource descriptor.", {
172
+ protocol: url.protocol,
173
+ redirectedProtocol: redirectedUrl.protocol
174
+ });
175
+ return {
176
+ resource: null,
177
+ result: "invalid",
178
+ statusCode: hop.statusCode,
179
+ remoteHost
180
+ };
181
+ }
182
+ url = redirectedUrl;
183
+ }
184
+ }
185
+ /**
186
+ * Opens a fetch session for a hop. A disallowed URL, a failed DNS lookup,
187
+ * or an aborted lookup yields `null` instead of an error.
188
+ */
189
+ async function openSession(url, openHop, signal) {
190
+ try {
191
+ return await openHop(url.href);
192
+ } catch (e) {
193
+ if (e instanceof _fedify_vocab_runtime.UrlError) {
194
+ if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
195
+ url: url.href,
196
+ error: e
197
+ });
198
+ else logger.error("Invalid URL for WebFinger resource descriptor: {error}", { error: e });
199
+ return null;
200
+ }
201
+ if (signal?.aborted) {
202
+ logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
203
+ url: url.href,
204
+ error: e
205
+ });
206
+ return null;
207
+ }
208
+ throw e;
209
+ }
210
+ }
211
+ /**
212
+ * Fetches a hop with the given session, and consumes the response body or
213
+ * starts cancelling it before returning. The caller closes the session.
214
+ */
215
+ async function fetchHop(session, url, options) {
216
+ let response;
217
+ try {
218
+ response = await session.fetch(url, {
219
+ headers: {
220
+ Accept: "application/jrd+json",
221
+ "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
222
+ },
223
+ redirect: "manual",
224
+ signal: options.signal
225
+ });
226
+ } catch (error) {
227
+ logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
228
+ url: url.href,
229
+ error
230
+ });
231
+ return { outcome: {
232
+ resource: null,
233
+ result: "network_error",
234
+ remoteHost: url.host
235
+ } };
236
+ }
237
+ if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
238
+ cancelBody(response, url);
239
+ return {
240
+ redirect: response.headers.get("Location"),
241
+ statusCode: response.status
242
+ };
243
+ }
244
+ if (!response.ok) {
245
+ logger.debug("Failed to fetch WebFinger resource descriptor: {status} {statusText}.", {
246
+ url: url.href,
247
+ status: response.status,
248
+ statusText: response.statusText
249
+ });
250
+ cancelBody(response, url);
251
+ return { outcome: {
252
+ resource: null,
253
+ result: response.status === 404 || response.status === 410 ? "not_found" : "error",
254
+ statusCode: response.status,
255
+ remoteHost: url.host
256
+ } };
257
+ }
258
+ try {
259
+ return { outcome: {
260
+ resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
261
+ result: "found",
262
+ statusCode: response.status,
263
+ remoteHost: url.host
264
+ } };
265
+ } catch (e) {
266
+ if (e instanceof BodyTooLargeError) return { outcome: {
267
+ resource: null,
268
+ result: "invalid",
269
+ statusCode: response.status,
270
+ remoteHost: url.host
271
+ } };
272
+ if (e instanceof SyntaxError) {
273
+ logger.debug("Failed to parse WebFinger resource descriptor as JSON: {error}", { error: e });
274
+ return { outcome: {
275
+ resource: null,
276
+ result: "invalid",
277
+ statusCode: response.status,
278
+ remoteHost: url.host
279
+ } };
280
+ }
281
+ throw e;
282
+ }
283
+ }
284
+ /**
285
+ * Starts cancelling a response body that is not read, without waiting for it
286
+ * to settle. The cancellation of a branch of a tee (e.g., a body cloned by
287
+ * a fetch mock) settles only after the other branch is cancelled too, per
288
+ * the Streams standard, so awaiting it could block forever. A failure is
289
+ * only logged.
290
+ */
291
+ function cancelBody(response, url) {
292
+ response.body?.cancel().catch((error) => {
293
+ logger.debug("Failed to cancel the response body from {url}: {error}", {
294
+ url: url.href,
295
+ error
296
+ });
297
+ });
298
+ }
299
+ //#endregion
300
+ //#region src/lookup.ts
90
301
  const WEBFINGER_HISTOGRAM_BUCKETS = [
91
302
  5,
92
303
  10,
@@ -147,6 +358,14 @@ function getMetricResourceScheme(scheme) {
147
358
  * @since 0.2.0
148
359
  */
149
360
  async function lookupWebFinger(resource, options = {}) {
361
+ return await lookupWebFingerWithDependencies(resource, options);
362
+ }
363
+ /**
364
+ * The lookup implementation with injectable hop sessions for tests.
365
+ * Not exported from the package entry point.
366
+ * @internal
367
+ */
368
+ async function lookupWebFingerWithDependencies(resource, options = {}, deps = {}) {
150
369
  const tracer = (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version);
151
370
  const scheme = getResourceScheme(resource);
152
371
  return await tracer.startActiveSpan("webfinger.lookup", {
@@ -163,7 +382,7 @@ async function lookupWebFinger(resource, options = {}) {
163
382
  result: "error"
164
383
  };
165
384
  try {
166
- outcome = await lookupWebFingerInternal(resource, options);
385
+ outcome = await lookupWebFingerInternal(resource, options, deps);
167
386
  span.setStatus({ code: outcome.resource === null ? _opentelemetry_api.SpanStatusCode.ERROR : _opentelemetry_api.SpanStatusCode.OK });
168
387
  return outcome.resource;
169
388
  } catch (error) {
@@ -189,154 +408,6 @@ function recordWebFingerLookup(meterProvider, durationMs, scheme, outcome) {
189
408
  instruments.lookup.add(1, attributes);
190
409
  instruments.lookupDuration.record(durationMs, attributes);
191
410
  }
192
- async function lookupWebFingerInternal(resource, options = {}) {
193
- if (typeof resource === "string") resource = new URL(resource);
194
- let protocol = "https:";
195
- let server;
196
- if (resource.protocol === "acct:" || resource.protocol === "mailto:") {
197
- const atPos = resource.pathname.lastIndexOf("@");
198
- if (atPos < 0) return {
199
- resource: null,
200
- result: "invalid"
201
- };
202
- server = resource.pathname.substring(atPos + 1);
203
- if (server === "" || /[/?#]/.test(server)) return {
204
- resource: null,
205
- result: "invalid"
206
- };
207
- if (resource.protocol === "acct:" && (resource.search !== "" || resource.hash !== "")) return {
208
- resource: null,
209
- result: "invalid"
210
- };
211
- } else {
212
- protocol = resource.protocol;
213
- server = resource.host;
214
- }
215
- let url = new URL(`${protocol}//${server}/.well-known/webfinger`);
216
- url.searchParams.set("resource", resource.href);
217
- let redirected = 0;
218
- while (true) {
219
- const remoteHost = url.host;
220
- logger.debug("Fetching WebFinger resource descriptor from {url}...", { url: url.href });
221
- let response;
222
- if (options.allowPrivateAddress !== true) try {
223
- await (0, _fedify_vocab_runtime.validatePublicUrl)(url.href);
224
- } catch (e) {
225
- if (e instanceof _fedify_vocab_runtime.UrlError) {
226
- if (e.reason === "dns") logger.debug("DNS lookup failed for {url}", {
227
- url: url.href,
228
- error: e
229
- });
230
- else logger.error("Invalid URL for WebFinger resource descriptor: {error}", { error: e });
231
- return {
232
- resource: null,
233
- result: "network_error",
234
- remoteHost
235
- };
236
- }
237
- throw e;
238
- }
239
- try {
240
- response = await fetch(url, {
241
- headers: {
242
- Accept: "application/jrd+json",
243
- "User-Agent": typeof options.userAgent === "string" ? options.userAgent : (0, _fedify_vocab_runtime.getUserAgent)(options.userAgent)
244
- },
245
- redirect: "manual",
246
- signal: options.signal
247
- });
248
- } catch (error) {
249
- logger.debug("Failed to fetch WebFinger resource descriptor: {error}", {
250
- url: url.href,
251
- error
252
- });
253
- return {
254
- resource: null,
255
- result: "network_error",
256
- remoteHost
257
- };
258
- }
259
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
260
- redirected++;
261
- const maxRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
262
- if (redirected > maxRedirection) {
263
- logger.error("Too many redirections ({redirections}) while fetching WebFinger resource descriptor.", { redirections: redirected });
264
- return {
265
- resource: null,
266
- result: "invalid",
267
- statusCode: response.status,
268
- remoteHost
269
- };
270
- }
271
- let redirectedUrl;
272
- try {
273
- redirectedUrl = new URL(response.headers.get("Location"), response.url == null || response.url === "" ? url : response.url);
274
- } catch (e) {
275
- logger.error("Invalid Location header while following WebFinger redirect: {error}", {
276
- url: url.href,
277
- error: e
278
- });
279
- return {
280
- resource: null,
281
- result: "invalid",
282
- statusCode: response.status,
283
- remoteHost
284
- };
285
- }
286
- if (redirectedUrl.protocol !== url.protocol) {
287
- logger.error("Redirected to a different protocol ({protocol} to {redirectedProtocol}) while fetching WebFinger resource descriptor.", {
288
- protocol: url.protocol,
289
- redirectedProtocol: redirectedUrl.protocol
290
- });
291
- return {
292
- resource: null,
293
- result: "invalid",
294
- statusCode: response.status,
295
- remoteHost
296
- };
297
- }
298
- url = redirectedUrl;
299
- continue;
300
- }
301
- if (!response.ok) {
302
- logger.debug("Failed to fetch WebFinger resource descriptor: {status} {statusText}.", {
303
- url: url.href,
304
- status: response.status,
305
- statusText: response.statusText
306
- });
307
- return {
308
- resource: null,
309
- result: response.status === 404 || response.status === 410 ? "not_found" : "error",
310
- statusCode: response.status,
311
- remoteHost
312
- };
313
- }
314
- try {
315
- return {
316
- resource: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, url)),
317
- result: "found",
318
- statusCode: response.status,
319
- remoteHost
320
- };
321
- } catch (e) {
322
- if (e instanceof BodyTooLargeError) return {
323
- resource: null,
324
- result: "invalid",
325
- statusCode: response.status,
326
- remoteHost
327
- };
328
- if (e instanceof SyntaxError) {
329
- logger.debug("Failed to parse WebFinger resource descriptor as JSON: {error}", { error: e });
330
- return {
331
- resource: null,
332
- result: "invalid",
333
- statusCode: response.status,
334
- remoteHost
335
- };
336
- }
337
- throw e;
338
- }
339
- }
340
- }
341
411
  //#endregion
342
412
  exports.lookupWebFinger = lookupWebFinger;
413
+ exports.lookupWebFingerWithDependencies = lookupWebFingerWithDependencies;
package/dist/mod.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { GetUserAgentOptions } from "@fedify/vocab-runtime";
2
2
  import { MeterProvider, TracerProvider } from "@opentelemetry/api";
3
+ import { PublicFetchSession } from "@fedify/vocab-runtime/internal";
3
4
 
4
5
  //#region src/jrd.d.ts
5
6
  /**
@@ -61,6 +62,19 @@ interface Link {
61
62
  readonly template?: string;
62
63
  }
63
64
  //#endregion
65
+ //#region src/lookup-impl.d.ts
66
+ /**
67
+ * The dependencies of {@link lookupWebFingerInternal}.
68
+ * @internal
69
+ */
70
+ interface LookupWebFingerDependencies {
71
+ /**
72
+ * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
73
+ * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
74
+ */
75
+ readonly openHop?: (url: string) => Promise<PublicFetchSession>;
76
+ }
77
+ //#endregion
64
78
  //#region src/lookup.d.ts
65
79
  /**
66
80
  * The terminal classification of an outgoing {@link lookupWebFinger} call,
@@ -84,6 +98,12 @@ interface Link {
84
98
  * @since 2.3.0
85
99
  */
86
100
  type WebFingerLookupResult = "found" | "not_found" | "invalid" | "network_error" | "error";
101
+ interface WebFingerLookupOutcome {
102
+ resource: ResourceDescriptor | null;
103
+ result: WebFingerLookupResult;
104
+ statusCode?: number;
105
+ remoteHost?: string;
106
+ }
87
107
  /**
88
108
  * Options for {@link lookupWebFinger}.
89
109
  * @since 1.3.0
@@ -139,5 +159,11 @@ interface LookupWebFingerOptions {
139
159
  * @since 0.2.0
140
160
  */
141
161
  declare function lookupWebFinger(resource: URL | string, options?: LookupWebFingerOptions): Promise<ResourceDescriptor | null>;
162
+ /**
163
+ * The lookup implementation with injectable hop sessions for tests.
164
+ * Not exported from the package entry point.
165
+ * @internal
166
+ */
167
+ declare function lookupWebFingerWithDependencies(resource: URL | string, options?: LookupWebFingerOptions, deps?: LookupWebFingerDependencies): Promise<ResourceDescriptor | null>;
142
168
  //#endregion
143
- export { Link, LookupWebFingerOptions, ResourceDescriptor, WebFingerLookupResult, lookupWebFinger };
169
+ export { Link, LookupWebFingerOptions, ResourceDescriptor, WebFingerLookupOutcome, WebFingerLookupResult, lookupWebFinger, lookupWebFingerWithDependencies };
package/dist/mod.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { GetUserAgentOptions } from "@fedify/vocab-runtime";
2
1
  import { MeterProvider, TracerProvider } from "@opentelemetry/api";
2
+ import { GetUserAgentOptions } from "@fedify/vocab-runtime";
3
+ import { PublicFetchSession } from "@fedify/vocab-runtime/internal";
3
4
 
4
5
  //#region src/jrd.d.ts
5
6
  /**
@@ -61,6 +62,19 @@ interface Link {
61
62
  readonly template?: string;
62
63
  }
63
64
  //#endregion
65
+ //#region src/lookup-impl.d.ts
66
+ /**
67
+ * The dependencies of {@link lookupWebFingerInternal}.
68
+ * @internal
69
+ */
70
+ interface LookupWebFingerDependencies {
71
+ /**
72
+ * Opens a fetch session for a single hop. Defaults to `openDirectFetch()`
73
+ * if `allowPrivateAddress` is turned on, or `openPublicFetch()` otherwise.
74
+ */
75
+ readonly openHop?: (url: string) => Promise<PublicFetchSession>;
76
+ }
77
+ //#endregion
64
78
  //#region src/lookup.d.ts
65
79
  /**
66
80
  * The terminal classification of an outgoing {@link lookupWebFinger} call,
@@ -84,6 +98,12 @@ interface Link {
84
98
  * @since 2.3.0
85
99
  */
86
100
  type WebFingerLookupResult = "found" | "not_found" | "invalid" | "network_error" | "error";
101
+ interface WebFingerLookupOutcome {
102
+ resource: ResourceDescriptor | null;
103
+ result: WebFingerLookupResult;
104
+ statusCode?: number;
105
+ remoteHost?: string;
106
+ }
87
107
  /**
88
108
  * Options for {@link lookupWebFinger}.
89
109
  * @since 1.3.0
@@ -139,5 +159,11 @@ interface LookupWebFingerOptions {
139
159
  * @since 0.2.0
140
160
  */
141
161
  declare function lookupWebFinger(resource: URL | string, options?: LookupWebFingerOptions): Promise<ResourceDescriptor | null>;
162
+ /**
163
+ * The lookup implementation with injectable hop sessions for tests.
164
+ * Not exported from the package entry point.
165
+ * @internal
166
+ */
167
+ declare function lookupWebFingerWithDependencies(resource: URL | string, options?: LookupWebFingerOptions, deps?: LookupWebFingerDependencies): Promise<ResourceDescriptor | null>;
142
168
  //#endregion
143
- export { Link, LookupWebFingerOptions, ResourceDescriptor, WebFingerLookupResult, lookupWebFinger };
169
+ export { Link, LookupWebFingerOptions, ResourceDescriptor, WebFingerLookupOutcome, WebFingerLookupResult, lookupWebFinger, lookupWebFingerWithDependencies };