forked from fedify-dev/fedify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebfinger.ts
More file actions
311 lines (293 loc) · 8.69 KB
/
Copy pathwebfinger.ts
File metadata and controls
311 lines (293 loc) · 8.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { type LanguageString, Link as LinkObject } from "@fedify/vocab";
import type { Link, ResourceDescriptor } from "@fedify/webfinger";
import { getLogger } from "@logtape/logtape";
import type { Span, Tracer } from "@opentelemetry/api";
import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
import { domainToASCII } from "node:url";
import type {
ActorAliasMapper,
ActorDispatcher,
ActorHandleMapper,
WebFingerLinksDispatcher,
} from "./callback.ts";
import type { RequestContext } from "./context.ts";
const logger = getLogger(["fedify", "webfinger", "server"]);
interface WebFingerSubjectAndAliasesOptions {
resourceUrl: URL;
actorUri: URL;
preferredUsername: string | LanguageString | null | undefined;
acctUsername: string | null;
host: string | undefined;
contextHost: string;
}
function getWebFingerSubjectAndAliases(
{
resourceUrl,
actorUri,
preferredUsername,
acctUsername,
host,
contextHost,
}: WebFingerSubjectAndAliasesOptions,
): Pick<ResourceDescriptor, "subject" | "aliases"> {
const aliases: string[] = [];
let subject = resourceUrl.href;
if (resourceUrl.protocol != "acct:" && preferredUsername != null) {
aliases.push(`acct:${preferredUsername}@${host ?? contextHost}`);
if (host != null && host !== contextHost) {
aliases.push(`acct:${preferredUsername}@${contextHost}`);
}
}
if (resourceUrl.href !== actorUri.href) {
aliases.push(actorUri.href);
}
if (
resourceUrl.protocol === "acct:" && host != null &&
host !== contextHost &&
!resourceUrl.href.endsWith(`@${host}`)
) {
subject = `acct:${preferredUsername ?? acctUsername}@${host}`;
aliases.push(resourceUrl.href);
if (
preferredUsername != null && preferredUsername !== "" &&
preferredUsername !== acctUsername
) {
aliases.push(`acct:${preferredUsername}@${contextHost}`);
}
}
return { subject, aliases };
}
/**
* Parameters for {@link handleWebFinger}.
*/
export interface WebFingerHandlerParameters<TContextData> {
/**
* The request context.
*/
context: RequestContext<TContextData>;
/**
* The canonical hostname of the server, if it's explicitly configured.
* @since 1.5.0
*/
host?: string;
/**
* The callback for dispatching the actor.
*/
actorDispatcher?: ActorDispatcher<TContextData>;
/**
* The callback for mapping a WebFinger username to the corresponding actor's
* internal identifier, or `null` if the username is not found.
* @since 0.15.0
*/
actorHandleMapper?: ActorHandleMapper<TContextData>;
/**
* The callback for mapping a WebFinger query to the corresponding actor's
* internal identifier or username, or `null` if the query is not found.
* @since 1.4.0
*/
actorAliasMapper?: ActorAliasMapper<TContextData>;
/**
* The callback for dispatching the Links of webFinger.
*/
webFingerLinksDispatcher?: WebFingerLinksDispatcher<TContextData>;
/**
* The function to call when the actor is not found.
*/
onNotFound(request: Request): Response | Promise<Response>;
/**
* The OpenTelemetry tracer.
* @since 1.3.0
*/
tracer?: Tracer;
/**
* The span for the request.
* @since 1.3.0
*/
span?: Span;
}
/**
* Handles a WebFinger request. You would not typically call this function
* directly, but instead use {@link Federation.fetch} method.
* @param request The WebFinger request to handle.
* @param parameters The parameters for handling the request.
* @returns The response to the request.
*/
export async function handleWebFinger<TContextData>(
request: Request,
options: WebFingerHandlerParameters<TContextData>,
): Promise<Response> {
if (options.tracer == null) {
return await handleWebFingerInternal(request, options);
}
return await options.tracer.startActiveSpan(
"webfinger.handle",
{ kind: SpanKind.SERVER },
async (span) => {
try {
const response = await handleWebFingerInternal(request, options);
span.setStatus({
code: response.ok ? SpanStatusCode.UNSET : SpanStatusCode.ERROR,
});
return response;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(error),
});
throw error;
} finally {
span.end();
}
},
);
}
async function handleWebFingerInternal<TContextData>(
request: Request,
{
context,
host,
actorDispatcher,
actorHandleMapper,
actorAliasMapper,
onNotFound,
span,
webFingerLinksDispatcher,
}: WebFingerHandlerParameters<TContextData>,
): Promise<Response> {
if (actorDispatcher == null) {
logger.error("Actor dispatcher is not set.");
return await onNotFound(request);
}
const resource = context.url.searchParams.get("resource");
if (resource == null) {
return new Response("Missing resource parameter.", { status: 400 });
}
span?.setAttribute("webfinger.resource", resource);
let resourceUrl: URL;
try {
resourceUrl = new URL(resource);
} catch (e) {
if (e instanceof TypeError) {
return new Response("Invalid resource URL.", { status: 400 });
}
throw e;
}
span?.setAttribute(
"webfinger.resource.scheme",
resourceUrl.protocol.replace(/:$/, ""),
);
async function mapUsernameToIdentifier(
username: string,
): Promise<string | null> {
if (actorHandleMapper == null) {
logger.error(
"No actor handle mapper is set; use the WebFinger username {username}" +
" as the actor's internal identifier.",
{ username },
);
return username;
}
const identifier = await actorHandleMapper(context, username);
if (identifier == null) {
logger.error("Actor {username} not found.", { username });
return null;
}
return identifier;
}
let identifier: string | null = null;
let acctUsername: string | null = null;
const uriParsed = context.parseUri(resourceUrl);
if (uriParsed?.type != "actor") {
const match = /^acct:([^@]+)@([^@]+)$/.exec(resource);
if (match == null) {
const result = await actorAliasMapper?.(context, resourceUrl);
if (result == null) return await onNotFound(request);
if ("identifier" in result) identifier = result.identifier;
else {
identifier = await mapUsernameToIdentifier(
result.username,
);
}
} else {
const portMatch = /:\d+$/.exec(match[2]);
const normalizedHost = portMatch == null
? domainToASCII(match[2].toLowerCase())
: domainToASCII(match[2].substring(0, portMatch.index).toLowerCase()) +
portMatch[0];
if (normalizedHost != context.url.host && normalizedHost != host) {
return await onNotFound(request);
} else {
acctUsername = match[1];
identifier = await mapUsernameToIdentifier(acctUsername);
resourceUrl = new URL(`acct:${acctUsername}@${normalizedHost}`);
}
}
} else {
identifier = uriParsed.identifier;
}
if (identifier == null) {
return await onNotFound(request);
}
const actor = await actorDispatcher(context, identifier);
if (actor == null) {
logger.error("Actor {identifier} not found.", { identifier });
return await onNotFound(request);
}
const actorUri = context.getActorUri(identifier);
const links: Link[] = [
{
rel: "self",
href: actorUri.href,
type: "application/activity+json",
},
];
for (const url of actor.urls) {
if (url instanceof LinkObject && url.href != null) {
links.push({
rel: url.rel ?? "http://webfinger.net/rel/profile-page",
href: url.href.href,
type: url.mediaType == null ? undefined : url.mediaType,
});
} else if (url instanceof URL) {
links.push({
rel: "http://webfinger.net/rel/profile-page",
href: url.href,
});
}
}
for await (const image of actor.getIcons()) {
if (image.url?.href == null) continue;
links.push({
rel: "http://webfinger.net/rel/avatar",
href: image.url.href.toString(),
...(image.mediaType != null && { type: image.mediaType }),
});
}
if (webFingerLinksDispatcher != null) {
const customLinks = await webFingerLinksDispatcher(context, resourceUrl);
if (customLinks != null) {
for (const link of customLinks) {
links.push(link);
}
}
}
const { subject, aliases } = getWebFingerSubjectAndAliases({
resourceUrl,
actorUri,
preferredUsername: actor.preferredUsername,
acctUsername,
host,
contextHost: context.url.host,
});
const jrd: ResourceDescriptor = {
subject,
aliases,
links,
};
return new Response(JSON.stringify(jrd), {
headers: {
"Content-Type": "application/jrd+json",
"Access-Control-Allow-Origin": "*",
},
});
}