@fedify/webfinger 2.5.0-dev.2664 → 2.5.0-dev.2710

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/src/lookup.ts DELETED
@@ -1,347 +0,0 @@
1
- import type { GetUserAgentOptions } from "@fedify/vocab-runtime";
2
- import {
3
- type Attributes,
4
- type Counter,
5
- type Histogram,
6
- type MeterProvider,
7
- SpanKind,
8
- SpanStatusCode,
9
- trace,
10
- type TracerProvider,
11
- } from "@opentelemetry/api";
12
- import metadata from "../deno.json" with { type: "json" };
13
- import type { ResourceDescriptor } from "./jrd.ts";
14
-
15
- import {
16
- type LookupWebFingerDependencies,
17
- lookupWebFingerInternal,
18
- } from "./lookup-impl.ts";
19
-
20
- /**
21
- * The terminal classification of an outgoing {@link lookupWebFinger} call,
22
- * recorded as the `webfinger.lookup.result` attribute on the
23
- * `webfinger.lookup` counter and `webfinger.lookup.duration` histogram.
24
- *
25
- * - `found`: the lookup returned a {@link ResourceDescriptor}.
26
- * - `not_found`: the remote responded with HTTP `404 Not Found` or
27
- * `410 Gone`. Recorded together with `http.response.status_code`.
28
- * - `invalid`: the remote responded with content Fedify could not parse
29
- * into a {@link ResourceDescriptor} (JSON parse failure or a body over
30
- * the size limit), the redirect chain exceeded `maxRedirection`, the
31
- * remote redirected to a different protocol, or the queried `acct:`
32
- * resource itself was malformed.
33
- * - `network_error`: no HTTP response was received (the URL was
34
- * rejected as a private address, `fetch()` threw, or an `AbortError`
35
- * cancelled the request).
36
- * - `error`: the remote responded with a non-2xx HTTP response that is
37
- * neither `404` nor `410`, or any other unexpected failure bubbled up
38
- * from the lookup.
39
- * @since 2.3.0
40
- */
41
- export type WebFingerLookupResult =
42
- | "found"
43
- | "not_found"
44
- | "invalid"
45
- | "network_error"
46
- | "error";
47
-
48
- interface WebFingerInstruments {
49
- lookup: Counter;
50
- lookupDuration: Histogram;
51
- }
52
-
53
- const WEBFINGER_HISTOGRAM_BUCKETS: ReadonlyArray<number> = [
54
- 5,
55
- 10,
56
- 25,
57
- 50,
58
- 75,
59
- 100,
60
- 250,
61
- 500,
62
- 750,
63
- 1000,
64
- 2500,
65
- 5000,
66
- 7500,
67
- 10000,
68
- ];
69
-
70
- const webFingerInstruments = new WeakMap<MeterProvider, WebFingerInstruments>();
71
-
72
- function getWebFingerInstruments(
73
- meterProvider: MeterProvider,
74
- ): WebFingerInstruments {
75
- let instruments = webFingerInstruments.get(meterProvider);
76
- if (instruments == null) {
77
- const meter = meterProvider.getMeter(metadata.name, metadata.version);
78
- instruments = {
79
- lookup: meter.createCounter("webfinger.lookup", {
80
- description: "Outgoing WebFinger lookup attempts.",
81
- unit: "{lookup}",
82
- }),
83
- lookupDuration: meter.createHistogram("webfinger.lookup.duration", {
84
- description: "Duration of outgoing WebFinger lookups.",
85
- unit: "ms",
86
- advice: { explicitBucketBoundaries: [...WEBFINGER_HISTOGRAM_BUCKETS] },
87
- }),
88
- };
89
- webFingerInstruments.set(meterProvider, instruments);
90
- }
91
- return instruments;
92
- }
93
-
94
- function getResourceScheme(resource: URL | string): string {
95
- if (typeof resource === "string") {
96
- const colon = resource.indexOf(":");
97
- return colon > 0 ? resource.substring(0, colon).toLowerCase() : "";
98
- }
99
- return resource.protocol.replace(/:$/, "").toLowerCase();
100
- }
101
-
102
- // The scheme attribute is recorded on the `webfinger.lookup` metric. Even
103
- // though most call sites pass scheme-controlled resources (Fedify code and
104
- // library users), `lookupObject()` accepts user-supplied identifiers that
105
- // flow into here, so the metric attribute is bucketed to the schemes
106
- // WebFinger / fediverse clients legitimately use (RFC 7565 +
107
- // ActivityPub). Anything else is bucketed as `other`, keeping metric
108
- // cardinality bounded even when a remote returns redirects whose target
109
- // scheme is unusual.
110
- const WEBFINGER_LOOKUP_SCHEME_WHITELIST: ReadonlySet<string> = new Set([
111
- "acct",
112
- "http",
113
- "https",
114
- "mailto",
115
- ]);
116
-
117
- function getMetricResourceScheme(scheme: string): string {
118
- return WEBFINGER_LOOKUP_SCHEME_WHITELIST.has(scheme) ? scheme : "other";
119
- }
120
-
121
- /**
122
- * The outcome of a {@link lookupWebFinger} call, returned in place of the
123
- * plain {@link ResourceDescriptor} when `options.withDiagnostics` is `true`.
124
- * @since 2.5.0
125
- */
126
- export interface WebFingerLookupOutcome {
127
- /**
128
- * The resource descriptor fetched from the remote WebFinger endpoint, or
129
- * `null` if the lookup did not succeed.
130
- */
131
- resource: ResourceDescriptor | null;
132
-
133
- /**
134
- * The terminal classification of the lookup. See
135
- * {@link WebFingerLookupResult} for what each value means.
136
- */
137
- result: WebFingerLookupResult;
138
-
139
- /**
140
- * The HTTP status code of the final response, if a response was received
141
- * from the remote server.
142
- */
143
- statusCode?: number;
144
-
145
- /**
146
- * The host of the final URL the lookup attempted to reach.
147
- */
148
- remoteHost?: string;
149
- }
150
-
151
- /**
152
- * Options for {@link lookupWebFinger}.
153
- * @since 1.3.0
154
- */
155
- export interface LookupWebFingerOptions {
156
- /**
157
- * The options for making `User-Agent` header.
158
- * If a string is given, it is used as the `User-Agent` header value.
159
- * If an object is given, it is passed to {@link getUserAgent} to generate
160
- * the `User-Agent` header value.
161
- */
162
- userAgent?: GetUserAgentOptions | string;
163
-
164
- /**
165
- * Whether to allow private IP addresses in the URL.
166
- *
167
- * Mostly useful for testing purposes. *Do not use this in production.*
168
- *
169
- * Turned off by default.
170
- * @since 1.4.0
171
- */
172
- allowPrivateAddress?: boolean;
173
-
174
- /**
175
- * The maximum number of redirections to follow.
176
- * @default `5`
177
- * @since 1.8.0
178
- */
179
- maxRedirection?: number;
180
-
181
- /**
182
- * The OpenTelemetry tracer provider. If omitted, the global tracer provider
183
- * is used.
184
- */
185
- tracerProvider?: TracerProvider;
186
-
187
- /**
188
- * The OpenTelemetry meter provider used to record the `webfinger.lookup`
189
- * counter and `webfinger.lookup.duration` histogram. If omitted, no
190
- * metric measurements are emitted (the helper is opt-in to avoid
191
- * touching the global meter provider for callers that do not use
192
- * OpenTelemetry).
193
- * @since 2.3.0
194
- */
195
- meterProvider?: MeterProvider;
196
-
197
- /**
198
- * AbortSignal for cancelling the request.
199
- * @since 1.8.0
200
- */
201
- signal?: AbortSignal;
202
- }
203
-
204
- /**
205
- * Looks up a WebFinger resource.
206
- * @param resource The resource URL to look up.
207
- * @param options Extra options for looking up the resource.
208
- * @returns The resource descriptor, or `null` if not found.
209
- * @since 0.2.0
210
- */
211
- export async function lookupWebFinger(
212
- resource: URL | string,
213
- options?: LookupWebFingerOptions & {
214
- /**
215
- * Whether to return a {@link WebFingerLookupOutcome} describing why
216
- * the lookup failed, instead of collapsing every failure into `null`.
217
- * Turned off by default.
218
- * @since 2.5.0
219
- */
220
- withDiagnostics?: false;
221
- },
222
- ): Promise<ResourceDescriptor | null>;
223
-
224
- /**
225
- * Looks up a WebFinger resource, returning diagnostics that explain why the
226
- * lookup failed instead of collapsing every failure into `null`.
227
- * @param resource The resource URL to look up.
228
- * @param options Extra options for looking up the resource. Must set
229
- * `withDiagnostics: true`.
230
- * @returns The outcome of the lookup.
231
- * @since 2.5.0
232
- */
233
- export async function lookupWebFinger(
234
- resource: URL | string,
235
- options: LookupWebFingerOptions & {
236
- /**
237
- * Returns a {@link WebFingerLookupOutcome} instead of a plain
238
- * {@link ResourceDescriptor}.
239
- * @since 2.5.0
240
- */
241
- withDiagnostics: true;
242
- },
243
- ): Promise<WebFingerLookupOutcome>;
244
-
245
- export async function lookupWebFinger(
246
- resource: URL | string,
247
- options: LookupWebFingerOptions & { withDiagnostics?: boolean } = {},
248
- ): Promise<ResourceDescriptor | null | WebFingerLookupOutcome> {
249
- return await lookupWebFingerWithDependencies(resource, options);
250
- }
251
-
252
- /**
253
- * The lookup implementation with injectable hop sessions for tests.
254
- * Not exported from the package entry point.
255
- * @internal
256
- */
257
- export function lookupWebFingerWithDependencies(
258
- resource: URL | string,
259
- options?: LookupWebFingerOptions & { withDiagnostics?: false },
260
- deps?: LookupWebFingerDependencies,
261
- ): Promise<ResourceDescriptor | null>;
262
- export function lookupWebFingerWithDependencies(
263
- resource: URL | string,
264
- options: LookupWebFingerOptions & { withDiagnostics: true },
265
- deps?: LookupWebFingerDependencies,
266
- ): Promise<WebFingerLookupOutcome>;
267
- export function lookupWebFingerWithDependencies(
268
- resource: URL | string,
269
- options: LookupWebFingerOptions & { withDiagnostics?: boolean },
270
- deps?: LookupWebFingerDependencies,
271
- ): Promise<ResourceDescriptor | null | WebFingerLookupOutcome>;
272
- export async function lookupWebFingerWithDependencies(
273
- resource: URL | string,
274
- options: LookupWebFingerOptions & { withDiagnostics?: boolean } = {},
275
- deps: LookupWebFingerDependencies = {},
276
- ): Promise<ResourceDescriptor | null | WebFingerLookupOutcome> {
277
- const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
278
- const tracer = tracerProvider.getTracer(
279
- metadata.name,
280
- metadata.version,
281
- );
282
- const scheme = getResourceScheme(resource);
283
- return await tracer.startActiveSpan(
284
- "webfinger.lookup",
285
- {
286
- kind: SpanKind.CLIENT,
287
- attributes: {
288
- "webfinger.resource": resource.toString(),
289
- "webfinger.resource.scheme": scheme,
290
- },
291
- },
292
- async (span) => {
293
- const meterProvider = options.meterProvider;
294
- const start = meterProvider == null ? 0 : performance.now();
295
- // Initialise the outcome with the `error` shape that the `finally`
296
- // block records when `lookupWebFingerInternal()` itself rejects;
297
- // the `try` body reassigns this to the actual outcome before any
298
- // other statement runs, so the `catch` does not need to reassign.
299
- let outcome: WebFingerLookupOutcome = {
300
- resource: null,
301
- result: "error",
302
- };
303
- try {
304
- outcome = await lookupWebFingerInternal(resource, options, deps);
305
- span.setStatus({
306
- code: outcome.resource === null
307
- ? SpanStatusCode.ERROR
308
- : SpanStatusCode.OK,
309
- });
310
- return options.withDiagnostics ? outcome : outcome.resource;
311
- } catch (error) {
312
- span.setStatus({
313
- code: SpanStatusCode.ERROR,
314
- message: String(error),
315
- });
316
- throw error;
317
- } finally {
318
- if (meterProvider != null) {
319
- const durationMs = Math.max(0, performance.now() - start);
320
- recordWebFingerLookup(meterProvider, durationMs, scheme, outcome);
321
- }
322
- span.end();
323
- }
324
- },
325
- );
326
- }
327
-
328
- function recordWebFingerLookup(
329
- meterProvider: MeterProvider,
330
- durationMs: number,
331
- scheme: string,
332
- outcome: WebFingerLookupOutcome,
333
- ): void {
334
- const attributes: Attributes = {
335
- "webfinger.lookup.result": outcome.result,
336
- "webfinger.resource.scheme": getMetricResourceScheme(scheme),
337
- };
338
- if (outcome.remoteHost != null) {
339
- attributes["activitypub.remote.host"] = outcome.remoteHost;
340
- }
341
- if (outcome.statusCode != null) {
342
- attributes["http.response.status_code"] = outcome.statusCode;
343
- }
344
- const instruments = getWebFingerInstruments(meterProvider);
345
- instruments.lookup.add(1, attributes);
346
- instruments.lookupDuration.record(durationMs, attributes);
347
- }
package/src/mod.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Exports WebFinger-related types and functions.
3
- *
4
- * @module
5
- */
6
- export * from "./jrd.ts";
7
- export * from "./lookup.ts";
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.node.json",
3
- "include": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
4
- "exclude": [
5
- "dist",
6
- "dist-tests",
7
- "node_modules"
8
- ]
9
- }
package/tsdown.config.ts DELETED
@@ -1,32 +0,0 @@
1
- import { glob } from "node:fs/promises";
2
- import { sep } from "node:path";
3
- import { defineConfig } from "tsdown";
4
-
5
- export default [
6
- defineConfig({
7
- entry: ["src/mod.ts"],
8
- dts: { compilerOptions: { isolatedDeclarations: true, declaration: true } },
9
- format: ["esm", "cjs"],
10
- platform: "node",
11
- outExtensions({ format }) {
12
- return {
13
- js: format === "cjs" ? ".cjs" : ".js",
14
- dts: format === "cjs" ? ".d.cts" : ".d.ts",
15
- };
16
- },
17
- deps: { neverBundle: [/^node:/] },
18
- }),
19
- defineConfig({
20
- entry: (await Array.fromAsync(glob(`src/**/*.test.ts`)))
21
- .map((f) => f.replace(sep, "/")),
22
- format: ["esm", "cjs"],
23
- platform: "node",
24
- outExtensions({ format }) {
25
- return {
26
- js: format === "cjs" ? ".cjs" : ".js",
27
- dts: format === "cjs" ? ".d.cts" : ".d.ts",
28
- };
29
- },
30
- deps: { neverBundle: [/^node:/, "@fedify/fixture"] },
31
- }),
32
- ];