@dwk/webfinger 0.1.0-beta.0

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/log.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * `@dwk/webfinger` — structured observability event taxonomy.
3
+ *
4
+ * WebFinger is public discovery data, so the stakes are lower than an auth
5
+ * endpoint — but a server being scraped for `acct:` handles it does not control,
6
+ * or a misconfigured resource map that 404s every lookup, is exactly the kind of
7
+ * thing an operator wants a signal for. Logging and metrics are opt-in via an
8
+ * injected {@link Logger} and {@link Metrics} (see `@dwk/log`) and **share this
9
+ * one vocabulary**: the same dotted event name is passed to the logger and the
10
+ * metrics sink so a log line and its counter line up.
11
+ *
12
+ * Fields follow the redaction policy: a `resource` is reduced to its **host**
13
+ * (the domain of an `acct:`/`mailto:` handle or an `https:` URI) via the
14
+ * handler's `resourceHost` helper — the local part (the user identifier) is
15
+ * never logged, only the domain, a machine-readable `reason`, and the count of
16
+ * `rel` filters. See `spec/observability.md`.
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+ /** Stable event names emitted by `@dwk/webfinger`. */
21
+ export const WebfingerLogEvent = {
22
+ /**
23
+ * A `resource` was matched and a JRD returned. Fields: `resourceHost`
24
+ * (sanitized), `relCount` (number of `rel` filters applied).
25
+ */
26
+ Resolved: "webfinger.resolved",
27
+ /**
28
+ * A request was rejected before a JRD could be returned. Field: `reason`
29
+ * (`missing_resource`, `malformed_resource`, `not_found`, or
30
+ * `method_not_allowed`), plus `resourceHost` when a `resource` was supplied.
31
+ */
32
+ Rejected: "webfinger.rejected",
33
+ };
34
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,sDAAsD;AACtD,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B;;;OAGG;IACH,QAAQ,EAAE,oBAAoB;IAC9B;;;;OAIG;IACH,QAAQ,EAAE,oBAAoB;CACtB,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Resource-URI normalization for case-insensitive matching (RFC 7033 §4.1;
3
+ * RFC 3986 §3.1 and §6.2.2.1): a URI's **scheme** and **host** are
4
+ * case-insensitive, so a query for `acct:alice@EXAMPLE.COM` must match a
5
+ * configured `acct:alice@example.com`. The local part of an `acct:`/`mailto:`
6
+ * handle is the user identifier and stays **case-sensitive**.
7
+ *
8
+ * Normalization scopes the *lookup key* only: both the queried resource and the
9
+ * configured map keys are normalized before comparison (see `config.ts`). The
10
+ * echoed `subject` keeps the client's literal spelling — the package spec
11
+ * requires the subject to equal the queried resource URI, and fediverse software
12
+ * compares it case-insensitively.
13
+ */
14
+ /**
15
+ * Normalize a resource URI for comparison: lowercase the scheme and host,
16
+ * preserving the case of an `acct:`/`mailto:` local part. For `http(s)` URIs the
17
+ * WHATWG `URL` parser performs the scheme/host lowercasing (and its standard
18
+ * path normalization); a URI that does not parse is returned with only its
19
+ * scheme lowercased, and a string with no scheme is returned unchanged.
20
+ */
21
+ export declare function normalizeResource(resource: string): string;
22
+ /**
23
+ * Decide whether a queried `resource` is a syntactically well-formed URI
24
+ * (RFC 7033 §4.2): it MUST carry a scheme (RFC 3986 §3.1), and an `http(s)`
25
+ * resource MUST additionally parse as an absolute URL. A value with no scheme,
26
+ * an ill-formed scheme, or an unparseable `http(s)` authority is *malformed*,
27
+ * and the handler answers `400` (not `404`) before any lookup — §4.2 requires a
28
+ * "bad request" indication when `resource` is absent **or malformed**.
29
+ *
30
+ * Validation is deliberately minimal: a syntactically valid scheme is enough for
31
+ * non-`http(s)` URIs (`acct:`, `mailto:`, `urn:`), since the resolver — not this
32
+ * gate — owns whether such a resource is controlled.
33
+ */
34
+ export declare function isWellFormedResource(resource: string): boolean;
35
+ //# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAwB1D;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAgB9D"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Resource-URI normalization for case-insensitive matching (RFC 7033 §4.1;
3
+ * RFC 3986 §3.1 and §6.2.2.1): a URI's **scheme** and **host** are
4
+ * case-insensitive, so a query for `acct:alice@EXAMPLE.COM` must match a
5
+ * configured `acct:alice@example.com`. The local part of an `acct:`/`mailto:`
6
+ * handle is the user identifier and stays **case-sensitive**.
7
+ *
8
+ * Normalization scopes the *lookup key* only: both the queried resource and the
9
+ * configured map keys are normalized before comparison (see `config.ts`). The
10
+ * echoed `subject` keeps the client's literal spelling — the package spec
11
+ * requires the subject to equal the queried resource URI, and fediverse software
12
+ * compares it case-insensitively.
13
+ */
14
+ /**
15
+ * Normalize a resource URI for comparison: lowercase the scheme and host,
16
+ * preserving the case of an `acct:`/`mailto:` local part. For `http(s)` URIs the
17
+ * WHATWG `URL` parser performs the scheme/host lowercasing (and its standard
18
+ * path normalization); a URI that does not parse is returned with only its
19
+ * scheme lowercased, and a string with no scheme is returned unchanged.
20
+ */
21
+ export function normalizeResource(resource) {
22
+ const colon = resource.indexOf(":");
23
+ if (colon <= 0)
24
+ return resource;
25
+ const scheme = resource.slice(0, colon).toLowerCase();
26
+ const rest = resource.slice(colon + 1);
27
+ if (scheme === "acct" || scheme === "mailto") {
28
+ const at = rest.lastIndexOf("@");
29
+ if (at === -1)
30
+ return `${scheme}:${rest}`;
31
+ const local = rest.slice(0, at);
32
+ const host = rest.slice(at + 1).toLowerCase();
33
+ return `${scheme}:${local}@${host}`;
34
+ }
35
+ if (scheme === "http" || scheme === "https") {
36
+ try {
37
+ return new URL(resource).href;
38
+ }
39
+ catch {
40
+ return `${scheme}:${rest}`;
41
+ }
42
+ }
43
+ return `${scheme}:${rest}`;
44
+ }
45
+ /**
46
+ * A valid URI scheme per RFC 3986 §3.1: an ALPHA followed by any number of
47
+ * ALPHA / DIGIT / "+" / "-" / ".".
48
+ */
49
+ const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*$/i;
50
+ /**
51
+ * Decide whether a queried `resource` is a syntactically well-formed URI
52
+ * (RFC 7033 §4.2): it MUST carry a scheme (RFC 3986 §3.1), and an `http(s)`
53
+ * resource MUST additionally parse as an absolute URL. A value with no scheme,
54
+ * an ill-formed scheme, or an unparseable `http(s)` authority is *malformed*,
55
+ * and the handler answers `400` (not `404`) before any lookup — §4.2 requires a
56
+ * "bad request" indication when `resource` is absent **or malformed**.
57
+ *
58
+ * Validation is deliberately minimal: a syntactically valid scheme is enough for
59
+ * non-`http(s)` URIs (`acct:`, `mailto:`, `urn:`), since the resolver — not this
60
+ * gate — owns whether such a resource is controlled.
61
+ */
62
+ export function isWellFormedResource(resource) {
63
+ const colon = resource.indexOf(":");
64
+ if (colon <= 0)
65
+ return false;
66
+ const scheme = resource.slice(0, colon).toLowerCase();
67
+ if (!SCHEME_PATTERN.test(scheme))
68
+ return false;
69
+ if (scheme === "http" || scheme === "https") {
70
+ try {
71
+ new URL(resource);
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ }
77
+ return true;
78
+ }
79
+ //# sourceMappingURL=resource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.js","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,QAAgB;IAChD,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,QAAQ,CAAC;IAEhC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;IACtD,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;IAEvC,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC7C,MAAM,EAAE,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO,GAAG,MAAM,IAAI,IAAI,EAAE,CAAC;QAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAChC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9C,OAAO,GAAG,MAAM,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;IACtC,CAAC;IAED,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;QAC5C,IAAI,CAAC;YACH,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;QAChC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,GAAG,MAAM,IAAI,IAAI,EAAE,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,OAAO,GAAG,MAAM,IAAI,IAAI,EAAE,CAAC;AAC7B,CAAC;AAED;;;GAGG;AACH,MAAM,cAAc,GAAG,sBAAsB,CAAC;AAE9C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAgB;IACnD,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAE7B,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;IACtD,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IAE/C,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;QAC5C,IAAI,CAAC;YACH,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;QACpB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@dwk/webfinger",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "WebFinger (RFC 7033) account/resource discovery endpoint at /.well-known/webfinger.",
5
+ "keywords": [
6
+ "webfinger",
7
+ "rfc7033",
8
+ "well-known",
9
+ "discovery",
10
+ "cloudflare-workers"
11
+ ],
12
+ "type": "module",
13
+ "license": "ISC",
14
+ "author": "David W. Keith <me@dwk.io>",
15
+ "homepage": "https://github.com/davidwkeith/workers/tree/main/packages/webfinger#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/davidwkeith/workers.git",
19
+ "directory": "packages/webfinger"
20
+ },
21
+ "sideEffects": false,
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src",
33
+ "!src/**/*.test.ts"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "dependencies": {
39
+ "@dwk/log": "0.1.0-beta.0"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.build.json",
43
+ "typecheck": "tsc -p tsconfig.json",
44
+ "clean": "rm -rf dist"
45
+ }
46
+ }
package/src/config.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Configuration for {@link createWebfinger}: the set of resources this server
3
+ * controls (a static map, a resolver function, or both) plus the optional
4
+ * logging/metrics seams. Per the composition contract the package never reads
5
+ * the global environment — every resource mapping arrives here, so a handler can
6
+ * be instantiated multiple times and tested in isolation.
7
+ */
8
+
9
+ import { noopLogger, noopMetrics, type Logger, type Metrics } from "@dwk/log";
10
+
11
+ import type { ResourceRecord } from "./jrd";
12
+ import { normalizeResource } from "./resource";
13
+
14
+ /**
15
+ * A dynamic resolver from a queried `resource` URI to its {@link ResourceRecord},
16
+ * or `undefined` when this server does not control the resource (→ `404`). The
17
+ * `resource` is passed **normalized** (lowercased scheme/host per RFC 7033 §4.1),
18
+ * so a resolver can compare it directly without re-normalizing. The matched
19
+ * `rel` filters are passed through so a resolver backed by stored data (e.g. a
20
+ * profile document via `@dwk/rdf`) can avoid materialising links it is about to
21
+ * discard, but applying the filter is optional — the handler always re-applies
22
+ * {@link filterLinksByRel} to whatever is returned.
23
+ */
24
+ export type ResourceResolver = (
25
+ resource: string,
26
+ rels: readonly string[],
27
+ ) => ResourceRecord | undefined | Promise<ResourceRecord | undefined>;
28
+
29
+ /** Configuration passed to {@link createWebfinger}. */
30
+ export interface WebfingerConfig {
31
+ /**
32
+ * Static map of controlled `resource` URI → its descriptor. Keys are the
33
+ * exact `resource` values clients query (`acct:user@example.com`,
34
+ * `https://example.com/`, `mailto:user@example.com`). Consulted before
35
+ * {@link resolve}.
36
+ */
37
+ readonly resources?: Readonly<Record<string, ResourceRecord>>;
38
+ /**
39
+ * Dynamic fallback consulted when {@link resources} has no entry for the
40
+ * queried URI. At least one of {@link resources} or `resolve` MUST be
41
+ * supplied, or {@link createWebfinger} throws at construction time.
42
+ */
43
+ readonly resolve?: ResourceResolver;
44
+ /**
45
+ * Logger for discovery events; defaults to a no-op. Wire a real logger (see
46
+ * `@dwk/log`) to surface unknown-resource probes and method rejections instead
47
+ * of swallowing them.
48
+ */
49
+ readonly logger?: Logger;
50
+ /**
51
+ * Metrics sink for discovery counters; defaults to a no-op. Wire an adapter
52
+ * (e.g. `analyticsEngineMetrics` from `@dwk/log`) to chart the same events the
53
+ * logger names — "lookups/min", "404 rate", "rel-filtered lookups".
54
+ */
55
+ readonly metrics?: Metrics;
56
+ }
57
+
58
+ /** Configuration after defaults are filled and a unified resolver is built. */
59
+ export interface ResolvedConfig {
60
+ /** Look up a resource: static map first, then the dynamic resolver. */
61
+ readonly resolve: (
62
+ resource: string,
63
+ rels: readonly string[],
64
+ ) => Promise<ResourceRecord | undefined>;
65
+ readonly logger: Logger;
66
+ readonly metrics: Metrics;
67
+ }
68
+
69
+ /**
70
+ * Validate and normalise a {@link WebfingerConfig}. Fails loudly when neither a
71
+ * resource map nor a resolver is configured — a WebFinger endpoint that controls
72
+ * no resources is always a misconfiguration, not a silent "everything is a 404".
73
+ * Returns a single `resolve` that consults the static map first (an O(1) exact
74
+ * match) and then the dynamic resolver.
75
+ */
76
+ export function resolveConfig(config: WebfingerConfig): ResolvedConfig {
77
+ if (config.resources === undefined && config.resolve === undefined) {
78
+ throw new Error(
79
+ "@dwk/webfinger: configure `resources` and/or `resolve` — a WebFinger " +
80
+ "endpoint must control at least one resource source.",
81
+ );
82
+ }
83
+
84
+ // Key the static map by the normalized resource URI so matching is
85
+ // case-insensitive on scheme/host (RFC 7033 §4.1). When two configured keys
86
+ // normalize to the same value, the later entry wins.
87
+ const normalizedMap =
88
+ config.resources === undefined
89
+ ? undefined
90
+ : new Map(
91
+ Object.entries(config.resources).map(([key, record]) => [
92
+ normalizeResource(key),
93
+ record,
94
+ ]),
95
+ );
96
+ const dynamicResolve = config.resolve;
97
+
98
+ const resolve = async (
99
+ resource: string,
100
+ rels: readonly string[],
101
+ ): Promise<ResourceRecord | undefined> => {
102
+ const key = normalizeResource(resource);
103
+ if (normalizedMap !== undefined) {
104
+ const record = normalizedMap.get(key);
105
+ if (record !== undefined) {
106
+ return record;
107
+ }
108
+ }
109
+ if (dynamicResolve !== undefined) {
110
+ return await dynamicResolve(key, rels);
111
+ }
112
+ return undefined;
113
+ };
114
+
115
+ return {
116
+ resolve,
117
+ logger: config.logger ?? noopLogger,
118
+ metrics: config.metrics ?? noopMetrics,
119
+ };
120
+ }
package/src/handler.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The WebFinger fetch handler (RFC 7033): a stateless `GET` endpoint, mountable
3
+ * at `/.well-known/webfinger`, that dispatches on the `resource` query parameter,
4
+ * returns the matching JRD (`rel`-filtered), and otherwise distinguishes a
5
+ * missing or malformed parameter (`400`) from an uncontrolled resource (`404`).
6
+ * Discovery data is public, so every response carries permissive CORS (§10.2).
7
+ */
8
+
9
+ import { hostFromUrl, type LogFields } from "@dwk/log";
10
+
11
+ import {
12
+ resolveConfig,
13
+ type ResolvedConfig,
14
+ type WebfingerConfig,
15
+ } from "./config";
16
+ import { buildJrd } from "./jrd";
17
+ import { WebfingerLogEvent } from "./log";
18
+ import { isWellFormedResource } from "./resource";
19
+
20
+ /**
21
+ * Cloudflare bindings required by the WebFinger handler: **none**. The resource
22
+ * mapping is config-supplied (composition contract), so this fragment is empty
23
+ * and contributes nothing to the composed Worker's `Env`.
24
+ */
25
+ export type WebfingerEnv = Record<never, never>;
26
+
27
+ /** A `fetch`-compatible Worker handler. */
28
+ export type WebfingerHandler = (
29
+ request: Request,
30
+ env: WebfingerEnv,
31
+ ctx: ExecutionContext,
32
+ ) => Promise<Response>;
33
+
34
+ /** Media type for a JSON Resource Descriptor (RFC 7033 §10.2). */
35
+ const JRD_CONTENT_TYPE = "application/jrd+json; charset=utf-8";
36
+ const TEXT_CONTENT_TYPE = "text/plain; charset=utf-8";
37
+
38
+ /**
39
+ * WebFinger serves public discovery data to any origin, so every response —
40
+ * success or error — advertises permissive CORS per RFC 7033 §10.2.
41
+ */
42
+ const CORS_HEADERS: Readonly<Record<string, string>> = {
43
+ "access-control-allow-origin": "*",
44
+ };
45
+
46
+ /**
47
+ * Reduce a queried `resource` to its host for logging: the domain of an
48
+ * `acct:`/`mailto:` handle, or the host of an `https:`/`http:` URI. The local
49
+ * part (the user identifier) is deliberately dropped — only the domain is
50
+ * recorded (see `log.ts`).
51
+ */
52
+ function resourceHost(resource: string): string | undefined {
53
+ if (/^(acct|mailto):/i.test(resource)) {
54
+ const at = resource.lastIndexOf("@");
55
+ if (at !== -1) {
56
+ const host = resource.slice(at + 1).toLowerCase();
57
+ return host.length > 0 ? host : undefined;
58
+ }
59
+ return undefined;
60
+ }
61
+ return hostFromUrl(resource);
62
+ }
63
+
64
+ /**
65
+ * Emit a structured event on both the logger and the metrics seam, which share
66
+ * one event vocabulary (see `@dwk/log`): `warn` for rejections, `info` for a
67
+ * resolved lookup. Callers pass only sanitized hosts, reason codes, and counts.
68
+ */
69
+ function emit(
70
+ config: ResolvedConfig,
71
+ level: "info" | "warn",
72
+ event: string,
73
+ fields?: LogFields,
74
+ ): void {
75
+ config.logger[level](event, fields);
76
+ config.metrics.count(event, fields);
77
+ }
78
+
79
+ function jrdResponse(body: string, method: string): Response {
80
+ return new Response(method === "HEAD" ? null : body, {
81
+ status: 200,
82
+ headers: { "content-type": JRD_CONTENT_TYPE, ...CORS_HEADERS },
83
+ });
84
+ }
85
+
86
+ function errorResponse(
87
+ status: number,
88
+ message: string,
89
+ extraHeaders?: Readonly<Record<string, string>>,
90
+ ): Response {
91
+ return new Response(message, {
92
+ status,
93
+ headers: {
94
+ "content-type": TEXT_CONTENT_TYPE,
95
+ ...CORS_HEADERS,
96
+ ...extraHeaders,
97
+ },
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Build the WebFinger handler from configuration.
103
+ *
104
+ * The returned handler is mountable at `/.well-known/webfinger`. It accepts
105
+ * `GET` (and `HEAD`): a request with no `resource` parameter — or a malformed
106
+ * one (no scheme / unparseable URI, RFC 7033 §4.2) — gets `400`; a `resource`
107
+ * this server does not control gets `404`; a match gets `200` with an
108
+ * `application/jrd+json` body whose `subject` echoes the queried URI, filtered by
109
+ * any `rel` parameters. `OPTIONS` returns a CORS preflight; other methods get
110
+ * `405`. Fails loudly at construction if no resource source is configured.
111
+ */
112
+ export function createWebfinger(config: WebfingerConfig): WebfingerHandler {
113
+ const resolved = resolveConfig(config);
114
+
115
+ return async (request, _env, _ctx) => {
116
+ const method = request.method;
117
+
118
+ if (method === "OPTIONS") {
119
+ return new Response(null, {
120
+ status: 204,
121
+ headers: {
122
+ ...CORS_HEADERS,
123
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
124
+ "access-control-allow-headers": "*",
125
+ },
126
+ });
127
+ }
128
+
129
+ if (method !== "GET" && method !== "HEAD") {
130
+ emit(resolved, "warn", WebfingerLogEvent.Rejected, {
131
+ reason: "method_not_allowed",
132
+ });
133
+ return errorResponse(405, "method_not_allowed: use GET", {
134
+ allow: "GET, HEAD, OPTIONS",
135
+ });
136
+ }
137
+
138
+ const url = new URL(request.url);
139
+ const resource = url.searchParams.get("resource");
140
+
141
+ if (resource === null || resource.length === 0) {
142
+ emit(resolved, "warn", WebfingerLogEvent.Rejected, {
143
+ reason: "missing_resource",
144
+ });
145
+ return errorResponse(
146
+ 400,
147
+ "missing_resource: the `resource` query parameter is required",
148
+ );
149
+ }
150
+
151
+ if (!isWellFormedResource(resource)) {
152
+ emit(resolved, "warn", WebfingerLogEvent.Rejected, {
153
+ reason: "malformed_resource",
154
+ resourceHost: resourceHost(resource),
155
+ });
156
+ return errorResponse(
157
+ 400,
158
+ "malformed_resource: the `resource` query parameter is not a valid URI",
159
+ );
160
+ }
161
+
162
+ const rels = url.searchParams.getAll("rel").filter((rel) => rel.length > 0);
163
+
164
+ const record = await resolved.resolve(resource, rels);
165
+ if (record === undefined) {
166
+ emit(resolved, "warn", WebfingerLogEvent.Rejected, {
167
+ reason: "not_found",
168
+ resourceHost: resourceHost(resource),
169
+ });
170
+ return errorResponse(
171
+ 404,
172
+ "not_found: no descriptor for the requested resource",
173
+ );
174
+ }
175
+
176
+ const jrd = buildJrd(resource, record, rels);
177
+ emit(resolved, "info", WebfingerLogEvent.Resolved, {
178
+ resourceHost: resourceHost(resource),
179
+ relCount: rels.length,
180
+ });
181
+ return jrdResponse(JSON.stringify(jrd), method);
182
+ };
183
+ }
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `@dwk/webfinger` — WebFinger (RFC 7033) account/resource discovery endpoint.
3
+ *
4
+ * Endpoint package: exports a factory returning a `fetch`-compatible handler,
5
+ * mountable at `/.well-known/webfinger` so it composes with other `@dwk`
6
+ * packages in one Worker. It maps a queried `resource` URI (`acct:`, `mailto:`,
7
+ * `https:`) to a JSON Resource Descriptor (JRD) of links — avatar, profile page,
8
+ * OIDC issuer, the `self` ActivityPub actor — and is the foundational discovery
9
+ * step for federation.
10
+ *
11
+ * It exists because WebFinger is **borderline static**: a static host can emit a
12
+ * single JRD, but only request logic can dispatch on `resource` (404 for a URI
13
+ * this server does not control), echo the matched `subject`, and filter `links`
14
+ * by `rel`. The package is pure and stateless — the `resource → JRD` mapping is
15
+ * supplied by config (a static map and/or a resolver), never read from the
16
+ * global environment — so it ships no Durable Object and needs no bindings, and
17
+ * the discovery logic unit-tests under Node without a Workers runtime.
18
+ *
19
+ * @see spec/packages/webfinger.md
20
+ * @packageDocumentation
21
+ */
22
+
23
+ export { createWebfinger } from "./handler";
24
+ export type { WebfingerEnv, WebfingerHandler } from "./handler";
25
+
26
+ export {
27
+ resolveConfig,
28
+ type WebfingerConfig,
29
+ type ResourceResolver,
30
+ type ResolvedConfig,
31
+ } from "./config";
32
+
33
+ export {
34
+ filterLinksByRel,
35
+ buildJrd,
36
+ type Jrd,
37
+ type Link,
38
+ type ResourceRecord,
39
+ } from "./jrd";
40
+
41
+ export { normalizeResource, isWellFormedResource } from "./resource";
42
+
43
+ export { WebfingerLogEvent } from "./log";
44
+ export type { Logger, Metrics } from "@dwk/log";
package/src/jrd.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * JSON Resource Descriptor (JRD) data model and the pure `rel`-filtering rule
3
+ * from RFC 7033 §4.3. These types are plain data — no Workers runtime, no
4
+ * Cloudflare bindings — so the discovery logic unit-tests in isolation. The
5
+ * handler in `handler.ts` turns an HTTP request into a `resource` lookup and
6
+ * renders the resulting {@link Jrd} as `application/jrd+json`.
7
+ */
8
+
9
+ /**
10
+ * A single link relation in a JRD (RFC 7033 §4.4.4). `rel` is required; the
11
+ * remaining members are optional and emitted only when present. Either `href`
12
+ * (a concrete target) or `template` (a URI template) typically carries the
13
+ * link's value.
14
+ */
15
+ export interface Link {
16
+ /** The link relation type — a registered name or an absolute URI. */
17
+ readonly rel: string;
18
+ /** Media type of the target resource, when known. */
19
+ readonly type?: string;
20
+ /** The target URI. */
21
+ readonly href?: string;
22
+ /** Human-readable titles keyed by language tag (or `"und"`). */
23
+ readonly titles?: Readonly<Record<string, string>>;
24
+ /** Additional, scheme-defined properties; a `null` value means "absent". */
25
+ readonly properties?: Readonly<Record<string, string | null>>;
26
+ /** A URI template, used in place of `href` for parameterised links. */
27
+ readonly template?: string;
28
+ }
29
+
30
+ /**
31
+ * What the configured resource map (or {@link ResourceResolver}) yields for a
32
+ * controlled resource. `subject` is optional here: the handler defaults it to
33
+ * the queried `resource` URI (which is what Mastodon/fediverse clients require),
34
+ * so a record normally lists only its `aliases`, `properties`, and `links`.
35
+ */
36
+ export interface ResourceRecord {
37
+ /** Overrides the echoed subject; defaults to the queried `resource` URI. */
38
+ readonly subject?: string;
39
+ /** Other URIs that identify the same entity (RFC 7033 §4.4.2). */
40
+ readonly aliases?: readonly string[];
41
+ /** Subject-level properties; a `null` value means "absent". */
42
+ readonly properties?: Readonly<Record<string, string | null>>;
43
+ /** The link relations advertised for this resource. */
44
+ readonly links?: readonly Link[];
45
+ }
46
+
47
+ /**
48
+ * A fully-rendered JRD as serialised in a `200` response. `subject` and `links`
49
+ * are always present (`links` may be an empty array after `rel` filtering);
50
+ * `aliases` and `properties` appear only when the record supplied them.
51
+ */
52
+ export interface Jrd {
53
+ /** The subject URI — equals the queried `resource` unless the record overrode it. */
54
+ readonly subject: string;
55
+ /** Other URIs identifying the subject. */
56
+ readonly aliases?: readonly string[];
57
+ /** Subject-level properties. */
58
+ readonly properties?: Readonly<Record<string, string | null>>;
59
+ /** The (possibly `rel`-filtered) link set. */
60
+ readonly links: readonly Link[];
61
+ }
62
+
63
+ /**
64
+ * Apply the RFC 7033 §4.3 `rel` filter: with no `rel` parameters the full link
65
+ * set is returned; otherwise only links whose `rel` exactly matches one of the
66
+ * requested relations survive. `rel` filtering never touches `aliases` or
67
+ * subject `properties` — it scopes the `links` array only.
68
+ */
69
+ export function filterLinksByRel(
70
+ links: readonly Link[],
71
+ rels: readonly string[],
72
+ ): readonly Link[] {
73
+ if (rels.length === 0) return links;
74
+ return links.filter((link) => rels.includes(link.rel));
75
+ }
76
+
77
+ /**
78
+ * Render the final {@link Jrd} for a matched resource: echo the queried
79
+ * `resource` as the subject (unless the record overrides it), apply the `rel`
80
+ * filter to the links, and carry through `aliases`/`properties` only when the
81
+ * record actually supplied them (so the JSON stays minimal).
82
+ */
83
+ export function buildJrd(
84
+ resource: string,
85
+ record: ResourceRecord,
86
+ rels: readonly string[],
87
+ ): Jrd {
88
+ const jrd: {
89
+ subject: string;
90
+ aliases?: readonly string[];
91
+ properties?: Readonly<Record<string, string | null>>;
92
+ links: readonly Link[];
93
+ } = {
94
+ subject: record.subject ?? resource,
95
+ links: filterLinksByRel(record.links ?? [], rels),
96
+ };
97
+ if (record.aliases && record.aliases.length > 0) {
98
+ jrd.aliases = record.aliases;
99
+ }
100
+ if (record.properties && Object.keys(record.properties).length > 0) {
101
+ jrd.properties = record.properties;
102
+ }
103
+ return jrd;
104
+ }