@fedify/fedify 1.6.14 → 1.6.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.
Files changed (129) hide show
  1. package/dist/actor-C92GiVtr.js +146 -0
  2. package/dist/actor.js +34648 -5
  3. package/dist/{assert.js → assert-C-mZuSQl.js} +1 -1
  4. package/dist/{assert_instance_of.js → assert_instance_of-lS0Jr2iu.js} +1 -1
  5. package/dist/{assert_is_error.js → assert_is_error-CIYFACrT.js} +1 -1
  6. package/dist/{assert_not_equals.js → assert_not_equals-C1azCAB0.js} +1 -1
  7. package/dist/{assert_rejects.js → assert_rejects-Bkh5lA1a.js} +2 -2
  8. package/dist/{assert_throws.js → assert_throws-CmpfkWEM.js} +2 -2
  9. package/dist/authdocloader-D6yaLhIk.js +51 -0
  10. package/dist/authdocloader.js +2 -4
  11. package/dist/{builder.js → builder-BxA2MvN4.js} +5 -5
  12. package/dist/{client.js → client-CwG-8F8w.js} +2 -2
  13. package/dist/compat/transformers.test.js +30 -30
  14. package/dist/{context.js → context-p_zzA2HO.js} +4 -4
  15. package/dist/docloader-BHWMnBPo.js +4413 -0
  16. package/dist/docloader.js +61 -4
  17. package/dist/{esm.js → esm-BRXvTSrx.js} +1 -1
  18. package/dist/federation/builder.test.js +17 -17
  19. package/dist/federation/collection.test.js +8 -8
  20. package/dist/federation/handler.test.js +36 -36
  21. package/dist/federation/inbox.test.js +11 -11
  22. package/dist/federation/keycache.test.js +12 -12
  23. package/dist/federation/kv.test.js +8 -8
  24. package/dist/federation/middleware.test.js +39 -39
  25. package/dist/federation/mq.test.js +8 -8
  26. package/dist/federation/retry.test.js +5 -5
  27. package/dist/federation/router.test.js +9 -9
  28. package/dist/federation/send.test.js +23 -23
  29. package/dist/http-CDlvJGv-.js +780 -0
  30. package/dist/http.js +4 -5
  31. package/dist/{inbox.js → inbox-ABTFAUzE.js} +3 -3
  32. package/dist/key-B3u1GQO0.js +259 -0
  33. package/dist/key-CFRooZ-5.js +16 -0
  34. package/dist/key.js +1 -7
  35. package/dist/key2.js +2 -4
  36. package/dist/{keycache.js → keycache-cqA-vzFY.js} +1 -1
  37. package/dist/{keys.js → keys-Bf_ChvLf.js} +1 -1
  38. package/dist/{ld.js → ld-BqMJ-pvL.js} +4 -4
  39. package/dist/{lookup2.js → lookup-BjvH6B6r.js} +4 -4
  40. package/dist/lookup-DYr8tISP.js +129 -0
  41. package/dist/lookup.js +1 -3
  42. package/dist/middleware-BqxvDftt.js +32 -0
  43. package/dist/middleware-DrkMfeD5.js +2638 -0
  44. package/dist/middleware.js +1220 -362
  45. package/dist/middleware2.js +6 -21
  46. package/dist/nodeinfo/client.test.js +12 -12
  47. package/dist/nodeinfo/handler.test.js +34 -34
  48. package/dist/nodeinfo/semver.test.js +8 -8
  49. package/dist/nodeinfo/types.test.js +9 -9
  50. package/dist/{owner.js → owner-DmM37H3z.js} +3 -3
  51. package/dist/proof-DAyY3Emw.js +255 -0
  52. package/dist/proof.js +330 -8
  53. package/dist/runtime/authdocloader.test.js +20 -20
  54. package/dist/runtime/docloader.test.js +13 -13
  55. package/dist/runtime/key.test.js +15 -15
  56. package/dist/runtime/langstr.test.js +8 -8
  57. package/dist/runtime/multibase/multibase.test.js +8 -8
  58. package/dist/runtime/url.test.js +7 -7
  59. package/dist/{send.js → send-D8zkuKY4.js} +2 -2
  60. package/dist/sig/http.test.js +20 -20
  61. package/dist/sig/key.test.js +17 -17
  62. package/dist/sig/ld.test.js +18 -18
  63. package/dist/sig/owner.test.js +20 -20
  64. package/dist/sig/proof.test.js +19 -19
  65. package/dist/{std__assert.js → std__assert-BdP_WkD-.js} +1 -1
  66. package/dist/testing/docloader.test.js +8 -8
  67. package/dist/testing/mod.js +2 -2
  68. package/dist/{testing.js → testing-qaAD4B0t.js} +1 -1
  69. package/dist/types-CB_2uuCA.js +51 -0
  70. package/dist/types.js +397 -3
  71. package/dist/vocab/actor.test.js +16 -16
  72. package/dist/vocab/lookup.test.js +17 -17
  73. package/dist/vocab/type.test.js +9 -9
  74. package/dist/vocab/vocab.test.js +17 -17
  75. package/dist/vocab-Cj-MrEWI.js +34386 -0
  76. package/dist/vocab.js +133 -34351
  77. package/dist/webfinger/handler.test.js +34 -34
  78. package/dist/webfinger/lookup.test.js +11 -11
  79. package/dist/x/cfworkers.test.js +7 -7
  80. package/package.json +1 -1
  81. /package/dist/{assert_equals.js → assert_equals-Dy0MG_Zw.js} +0 -0
  82. /package/dist/{chunk.js → chunk-DvTpRkcT.js} +0 -0
  83. /package/dist/{collection.js → collection-XNLQhehO.js} +0 -0
  84. /package/dist/compat/{transformers.test.d.ts → transformers.test-DnJbd34u.d.ts} +0 -0
  85. /package/dist/{denokv.js → denokv-XeyH3cFs.js} +0 -0
  86. /package/dist/{docloader2.js → docloader-BDSHZfTJ.js} +0 -0
  87. /package/dist/federation/{builder.test.d.ts → builder.test-Bpt6NOZ6.d.ts} +0 -0
  88. /package/dist/federation/{collection.test.d.ts → collection.test-DKJ6JOZz.d.ts} +0 -0
  89. /package/dist/federation/{handler.test.d.ts → handler.test-BMT7uLC0.d.ts} +0 -0
  90. /package/dist/federation/{inbox.test.d.ts → inbox.test-Do6i02Qp.d.ts} +0 -0
  91. /package/dist/federation/{keycache.test.d.ts → keycache.test-BT83IPZY.d.ts} +0 -0
  92. /package/dist/federation/{kv.test.d.ts → kv.test-kFzzF2VN.d.ts} +0 -0
  93. /package/dist/federation/{middleware.test.d.ts → middleware.test-B1R4_e3-.d.ts} +0 -0
  94. /package/dist/federation/{mq.test.d.ts → mq.test-l79EQQOe.d.ts} +0 -0
  95. /package/dist/federation/{retry.test.d.ts → retry.test-BqS50VCX.d.ts} +0 -0
  96. /package/dist/federation/{router.test.d.ts → router.test-CYQl4po-.d.ts} +0 -0
  97. /package/dist/federation/{send.test.d.ts → send.test-COUnNUzv.d.ts} +0 -0
  98. /package/dist/{kv.js → kv-DosGYGwV.js} +0 -0
  99. /package/dist/{langstr.js → langstr-pFHBDU4y.js} +0 -0
  100. /package/dist/{multibase.js → multibase-DBcKTV2a.js} +0 -0
  101. /package/dist/nodeinfo/{client.test.d.ts → client.test-CZLe79hL.d.ts} +0 -0
  102. /package/dist/nodeinfo/{handler.test.d.ts → handler.test-B-EDZ_hK.d.ts} +0 -0
  103. /package/dist/nodeinfo/{semver.test.d.ts → semver.test-BEuuQSEM.d.ts} +0 -0
  104. /package/dist/nodeinfo/{types.test.d.ts → types.test-B5AT89WV.d.ts} +0 -0
  105. /package/dist/{retry.js → retry-BQet39_l.js} +0 -0
  106. /package/dist/{router.js → router-BuDkN4RQ.js} +0 -0
  107. /package/dist/runtime/{authdocloader.test.d.ts → authdocloader.test-hCRKzn9v.d.ts} +0 -0
  108. /package/dist/runtime/{docloader.test.d.ts → docloader.test-CVd7i_5h.d.ts} +0 -0
  109. /package/dist/runtime/{key.test.d.ts → key.test-DBsILYSD.d.ts} +0 -0
  110. /package/dist/runtime/{langstr.test.d.ts → langstr.test-CiKxuuRY.d.ts} +0 -0
  111. /package/dist/runtime/multibase/{multibase.test.d.ts → multibase.test-Brh6gPBP.d.ts} +0 -0
  112. /package/dist/runtime/{url.test.d.ts → url.test-DlRqkU2j.d.ts} +0 -0
  113. /package/dist/{semver.js → semver-D9d-VO-_.js} +0 -0
  114. /package/dist/sig/{http.test.d.ts → http.test-BpXNAWNI.d.ts} +0 -0
  115. /package/dist/sig/{key.test.d.ts → key.test-B2iLIugy.d.ts} +0 -0
  116. /package/dist/sig/{ld.test.d.ts → ld.test-D-cI70Gw.d.ts} +0 -0
  117. /package/dist/sig/{owner.test.d.ts → owner.test-B_YRjMPj.d.ts} +0 -0
  118. /package/dist/sig/{proof.test.d.ts → proof.test-BagEM_-4.d.ts} +0 -0
  119. /package/dist/testing/{docloader.test.d.ts → docloader.test-lrzf6sDZ.d.ts} +0 -0
  120. /package/dist/testing/{mod.d.ts → mod-3uM8ZvS7.d.ts} +0 -0
  121. /package/dist/{type.js → type-DFsmi-p1.js} +0 -0
  122. /package/dist/{url.js → url-BdNvnK9P.js} +0 -0
  123. /package/dist/vocab/{actor.test.d.ts → actor.test-ClC-iVWk.d.ts} +0 -0
  124. /package/dist/vocab/{lookup.test.d.ts → lookup.test-Cq1I-27w.d.ts} +0 -0
  125. /package/dist/vocab/{type.test.d.ts → type.test-bfFiYGcs.d.ts} +0 -0
  126. /package/dist/vocab/{vocab.test.d.ts → vocab.test-h-ZTisfu.d.ts} +0 -0
  127. /package/dist/webfinger/{handler.test.d.ts → handler.test-DiUeEDDD.d.ts} +0 -0
  128. /package/dist/webfinger/{lookup.test.d.ts → lookup.test-D9onm3U3.d.ts} +0 -0
  129. /package/dist/x/{cfworkers.test.d.ts → cfworkers.test-KXHlJ29z.d.ts} +0 -0
@@ -0,0 +1,2638 @@
1
+
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+ import { URLPattern } from "urlpattern-polyfill";
4
+ globalThis.addEventListener = () => {};
5
+
6
+ import { d as version, i as getDocumentLoader, s as kvCache, u as name } from "./docloader-BHWMnBPo.js";
7
+ import { t as getNodeInfo } from "./client-CwG-8F8w.js";
8
+ import { n as RouterError } from "./router-BuDkN4RQ.js";
9
+ import { t as nodeInfoToJson } from "./types-CB_2uuCA.js";
10
+ import { _ as Object$1, b as OrderedCollectionPage, h as Multikey, m as Link, o as CryptographicKey, t as Activity, y as OrderedCollection } from "./vocab-Cj-MrEWI.js";
11
+ import { t as lookupWebFinger } from "./lookup-DYr8tISP.js";
12
+ import { t as getTypeId } from "./type-DFsmi-p1.js";
13
+ import { a as validateCryptoKey, i as importJwk, t as exportJwk } from "./key-B3u1GQO0.js";
14
+ import { l as verifyRequest } from "./http-CDlvJGv-.js";
15
+ import { t as getAuthenticatedDocumentLoader } from "./authdocloader-D6yaLhIk.js";
16
+ import { a as signJsonLd, i as hasSignature, o as verifyJsonLd, r as detachSignature } from "./ld-BqMJ-pvL.js";
17
+ import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-DmM37H3z.js";
18
+ import { n as signObject, r as verifyObject } from "./proof-DAyY3Emw.js";
19
+ import { n as traverseCollection, t as lookupObject } from "./lookup-BjvH6B6r.js";
20
+ import { n as routeActivity } from "./inbox-ABTFAUzE.js";
21
+ import { t as FederationBuilderImpl } from "./builder-BxA2MvN4.js";
22
+ import { t as buildCollectionSynchronizationHeader } from "./collection-XNLQhehO.js";
23
+ import { t as KvKeyCache } from "./keycache-cqA-vzFY.js";
24
+ import { t as createExponentialBackoffPolicy } from "./retry-BQet39_l.js";
25
+ import { n as sendActivity, t as extractInboxes } from "./send-D8zkuKY4.js";
26
+ import { getLogger, withContext } from "@logtape/logtape";
27
+ import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
28
+ import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
29
+ import { domainToASCII } from "node:url";
30
+
31
+ //#region compat/transformers.ts
32
+ const logger$1 = getLogger([
33
+ "fedify",
34
+ "compat",
35
+ "transformers"
36
+ ]);
37
+ /**
38
+ * An activity transformer that assigns a new random ID to an activity if it
39
+ * does not already have one. This is useful for ensuring that activities
40
+ * have an ID before they are sent to other servers.
41
+ *
42
+ * The generated ID is an origin URI with a fragment which contains an activity
43
+ * type name with a random UUID:
44
+ *
45
+ * ```
46
+ * https://example.com/#Follow/12345678-1234-5678-1234-567812345678
47
+ * ```
48
+ *
49
+ * @typeParam TContextData The type of the context data.
50
+ * @param activity The activity to assign an ID to.
51
+ * @param context The context of the activity.
52
+ * @return The activity with an ID assigned.
53
+ * @since 1.4.0
54
+ */
55
+ function autoIdAssigner(activity, context$1) {
56
+ if (activity.id != null) return activity;
57
+ const id = new URL(`/#${activity.constructor.name}/${crypto.randomUUID()}`, context$1.origin);
58
+ logger$1.warn("As the activity to send does not have an id, a new id {id} has been generated for it. However, it is recommended to explicitly set the id for the activity.", { id: id.href });
59
+ return activity.clone({ id });
60
+ }
61
+ /**
62
+ * An activity transformer that dehydrates the actor property of an activity
63
+ * so that it only contains the actor's URI. For example, suppose we have an
64
+ * activity like this:
65
+ *
66
+ * ```typescript
67
+ * import { Follow, Person } from "@fedify/fedify/vocab";
68
+ * const input = new Follow({
69
+ * id: new URL("http://example.com/activities/1"),
70
+ * actor: new Person({
71
+ * id: new URL("http://example.com/actors/1"),
72
+ * name: "Alice",
73
+ * preferredUsername: "alice",
74
+ * }),
75
+ * object: new Person({
76
+ * id: new URL("http://example.com/actors/2"),
77
+ * name: "Bob",
78
+ * preferredUsername: "bob",
79
+ * }),
80
+ * });
81
+ * ```
82
+ *
83
+ * The result of applying this transformer would be:
84
+ *
85
+ * ```typescript
86
+ * import { Follow, Person } from "@fedify/fedify/vocab";
87
+ * const output = new Follow({
88
+ * id: new URL("http://example.com/activities/1"),
89
+ * actor: new URL("http://example.com/actors/1"),
90
+ * object: new Person({
91
+ * id: new URL("http://example.com/actors/2"),
92
+ * name: "Bob",
93
+ * preferredUsername: "bob",
94
+ * }),
95
+ * });
96
+ * ```
97
+ *
98
+ * As some ActivityPub implementations like Threads fail to deal with inlined
99
+ * actor objects, this transformer can be used to work around this issue.
100
+ * @typeParam TContextData The type of the context data.
101
+ * @param activity The activity to dehydrate the actor property of.
102
+ * @param context The context of the activity.
103
+ * @returns The dehydrated activity.
104
+ * @since 1.4.0
105
+ */
106
+ function actorDehydrator(activity, _context) {
107
+ if (activity.actorIds.length < 1) return activity;
108
+ return activity.clone({ actors: activity.actorIds });
109
+ }
110
+ /**
111
+ * Gets the default activity transformers that are applied to all outgoing
112
+ * activities.
113
+ * @typeParam TContextData The type of the context data.
114
+ * @returns The default activity transformers.
115
+ * @since 1.4.0
116
+ */
117
+ function getDefaultActivityTransformers() {
118
+ return [autoIdAssigner, actorDehydrator];
119
+ }
120
+
121
+ //#endregion
122
+ //#region nodeinfo/handler.ts
123
+ /**
124
+ * Handles a NodeInfo request. You would not typically call this function
125
+ * directly, but instead use {@link Federation.handle} method.
126
+ * @param request The NodeInfo request to handle.
127
+ * @param parameters The parameters for handling the request.
128
+ * @returns The response to the request.
129
+ */
130
+ async function handleNodeInfo(_request, { context: context$1, nodeInfoDispatcher }) {
131
+ const promise = nodeInfoDispatcher(context$1);
132
+ const json = nodeInfoToJson(promise instanceof Promise ? await promise : promise);
133
+ return new Response(JSON.stringify(json), { headers: { "Content-Type": "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\"" } });
134
+ }
135
+ /**
136
+ * Handles a request to `/.well-known/nodeinfo`. You would not typically call
137
+ * this function directly, but instead use {@link Federation.handle} method.
138
+ * @param request The request to handle.
139
+ * @param context The request context.
140
+ * @returns The response to the request.
141
+ */
142
+ function handleNodeInfoJrd(_request, context$1) {
143
+ const links = [];
144
+ try {
145
+ links.push({
146
+ rel: "http://nodeinfo.diaspora.software/ns/schema/2.1",
147
+ href: context$1.getNodeInfoUri().href,
148
+ type: "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\""
149
+ });
150
+ } catch (e) {
151
+ if (!(e instanceof RouterError)) throw e;
152
+ }
153
+ const jrd = { links };
154
+ const response = new Response(JSON.stringify(jrd), { headers: { "Content-Type": "application/jrd+json" } });
155
+ return Promise.resolve(response);
156
+ }
157
+
158
+ //#endregion
159
+ //#region vocab/constants.ts
160
+ /**
161
+ * The special public collection for [public addressing]. *Do not mutate this
162
+ * object.*
163
+ *
164
+ * [public addressing]: https://www.w3.org/TR/activitypub/#public-addressing
165
+ *
166
+ * @since 0.7.0
167
+ */
168
+ const PUBLIC_COLLECTION = new URL("https://www.w3.org/ns/activitystreams#Public");
169
+
170
+ //#endregion
171
+ //#region webfinger/handler.ts
172
+ const logger = getLogger([
173
+ "fedify",
174
+ "webfinger",
175
+ "server"
176
+ ]);
177
+ /**
178
+ * Handles a WebFinger request. You would not typically call this function
179
+ * directly, but instead use {@link Federation.fetch} method.
180
+ * @param request The WebFinger request to handle.
181
+ * @param parameters The parameters for handling the request.
182
+ * @returns The response to the request.
183
+ */
184
+ async function handleWebFinger(request, options) {
185
+ if (options.tracer == null) return await handleWebFingerInternal(request, options);
186
+ return await options.tracer.startActiveSpan("webfinger.handle", { kind: SpanKind.SERVER }, async (span) => {
187
+ try {
188
+ const response = await handleWebFingerInternal(request, options);
189
+ span.setStatus({ code: response.ok ? SpanStatusCode.UNSET : SpanStatusCode.ERROR });
190
+ return response;
191
+ } catch (error) {
192
+ span.setStatus({
193
+ code: SpanStatusCode.ERROR,
194
+ message: String(error)
195
+ });
196
+ throw error;
197
+ } finally {
198
+ span.end();
199
+ }
200
+ });
201
+ }
202
+ async function handleWebFingerInternal(request, { context: context$1, host, actorDispatcher, actorHandleMapper, actorAliasMapper, onNotFound, span }) {
203
+ if (actorDispatcher == null) return await onNotFound(request);
204
+ const resource = context$1.url.searchParams.get("resource");
205
+ if (resource == null) return new Response("Missing resource parameter.", { status: 400 });
206
+ span?.setAttribute("webfinger.resource", resource);
207
+ let resourceUrl;
208
+ try {
209
+ resourceUrl = new URL(resource);
210
+ } catch (e) {
211
+ if (e instanceof TypeError) return new Response("Invalid resource URL.", { status: 400 });
212
+ throw e;
213
+ }
214
+ span?.setAttribute("webfinger.resource.scheme", resourceUrl.protocol.replace(/:$/, ""));
215
+ if (actorDispatcher == null) {
216
+ logger.error("Actor dispatcher is not set.");
217
+ return await onNotFound(request);
218
+ }
219
+ async function mapUsernameToIdentifier(username) {
220
+ if (actorHandleMapper == null) {
221
+ logger.error("No actor handle mapper is set; use the WebFinger username {username} as the actor's internal identifier.", { username });
222
+ return username;
223
+ }
224
+ const identifier$1 = await actorHandleMapper(context$1, username);
225
+ if (identifier$1 == null) {
226
+ logger.error("Actor {username} not found.", { username });
227
+ return null;
228
+ }
229
+ return identifier$1;
230
+ }
231
+ let identifier = null;
232
+ const uriParsed = context$1.parseUri(resourceUrl);
233
+ if (uriParsed?.type != "actor") {
234
+ const match = /^acct:([^@]+)@([^@]+)$/.exec(resource);
235
+ if (match == null) {
236
+ const result = await actorAliasMapper?.(context$1, resourceUrl);
237
+ if (result == null) return await onNotFound(request);
238
+ if ("identifier" in result) identifier = result.identifier;
239
+ else identifier = await mapUsernameToIdentifier(result.username);
240
+ } else {
241
+ const portMatch = /:\d+$/.exec(match[2]);
242
+ const normalizedHost = portMatch == null ? domainToASCII(match[2].toLowerCase()) : domainToASCII(match[2].substring(0, portMatch.index).toLowerCase()) + portMatch[0];
243
+ if (normalizedHost != context$1.url.host && normalizedHost != host) return await onNotFound(request);
244
+ else {
245
+ identifier = await mapUsernameToIdentifier(match[1]);
246
+ resourceUrl = new URL(`acct:${match[1]}@${normalizedHost}`);
247
+ }
248
+ }
249
+ } else identifier = uriParsed.identifier;
250
+ if (identifier == null) return await onNotFound(request);
251
+ const actor = await actorDispatcher(context$1, identifier);
252
+ if (actor == null) {
253
+ logger.error("Actor {identifier} not found.", { identifier });
254
+ return await onNotFound(request);
255
+ }
256
+ const links = [{
257
+ rel: "self",
258
+ href: context$1.getActorUri(identifier).href,
259
+ type: "application/activity+json"
260
+ }];
261
+ for (const url of actor.urls) if (url instanceof Link && url.href != null) links.push({
262
+ rel: url.rel ?? "http://webfinger.net/rel/profile-page",
263
+ href: url.href.href,
264
+ type: url.mediaType == null ? void 0 : url.mediaType
265
+ });
266
+ else if (url instanceof URL) links.push({
267
+ rel: "http://webfinger.net/rel/profile-page",
268
+ href: url.href
269
+ });
270
+ for await (const image of actor.getIcons()) {
271
+ if (image.url?.href == null) continue;
272
+ const link = {
273
+ rel: "http://webfinger.net/rel/avatar",
274
+ href: image.url.href.toString()
275
+ };
276
+ if (image.mediaType != null) link.type = image.mediaType;
277
+ links.push(link);
278
+ }
279
+ const aliases = [];
280
+ if (resourceUrl.protocol != "acct:" && actor.preferredUsername != null) {
281
+ aliases.push(`acct:${actor.preferredUsername}@${host ?? context$1.url.host}`);
282
+ if (host != null && host !== context$1.url.host) aliases.push(`acct:${actor.preferredUsername}@${context$1.url.host}`);
283
+ }
284
+ if (resourceUrl.href !== context$1.getActorUri(identifier).href) aliases.push(context$1.getActorUri(identifier).href);
285
+ if (resourceUrl.protocol === "acct:" && host != null && host !== context$1.url.host && !resourceUrl.href.endsWith(`@${host}`)) {
286
+ const username = resourceUrl.href.replace(/^acct:/, "").replace(/@.*$/, "");
287
+ aliases.push(`acct:${username}@${host}`);
288
+ }
289
+ const jrd = {
290
+ subject: resourceUrl.href,
291
+ aliases,
292
+ links
293
+ };
294
+ return new Response(JSON.stringify(jrd), { headers: {
295
+ "Content-Type": "application/jrd+json",
296
+ "Access-Control-Allow-Origin": "*"
297
+ } });
298
+ }
299
+
300
+ //#endregion
301
+ //#region federation/negotiation.ts
302
+ function compareSpecs(a, b) {
303
+ return b.q - a.q || (b.s ?? 0) - (a.s ?? 0) || (a.o ?? 0) - (b.o ?? 0) || a.i - b.i || 0;
304
+ }
305
+ function isQuality(spec) {
306
+ return spec.q > 0;
307
+ }
308
+ const simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
309
+ function splitKeyValuePair(str) {
310
+ const [key, value] = str.split("=");
311
+ return [key.toLowerCase(), value];
312
+ }
313
+ function parseMediaType(str, i) {
314
+ const match = simpleMediaTypeRegExp.exec(str);
315
+ if (!match) return;
316
+ const [, type, subtype, parameters] = match;
317
+ if (!type || !subtype) return;
318
+ const params = Object.create(null);
319
+ let q = 1;
320
+ if (parameters) {
321
+ const kvps = parameters.split(";").map((p) => p.trim()).map(splitKeyValuePair);
322
+ for (const [key, val] of kvps) {
323
+ const value = val && val[0] === `"` && val[val.length - 1] === `"` ? val.slice(1, val.length - 1) : val;
324
+ if (key === "q" && value) {
325
+ q = parseFloat(value);
326
+ break;
327
+ }
328
+ params[key] = value;
329
+ }
330
+ }
331
+ return {
332
+ type,
333
+ subtype,
334
+ params,
335
+ i,
336
+ o: void 0,
337
+ q,
338
+ s: void 0
339
+ };
340
+ }
341
+ function parseAccept(accept) {
342
+ const accepts = accept.split(",").map((p) => p.trim());
343
+ const mediaTypes = [];
344
+ for (const [index, accept$1] of accepts.entries()) {
345
+ const mediaType = parseMediaType(accept$1.trim(), index);
346
+ if (mediaType) mediaTypes.push(mediaType);
347
+ }
348
+ return mediaTypes;
349
+ }
350
+ function getFullType(spec) {
351
+ return `${spec.type}/${spec.subtype}`;
352
+ }
353
+ function preferredMediaTypes(accept) {
354
+ return parseAccept(accept === void 0 ? "*/*" : accept ?? "").filter(isQuality).sort(compareSpecs).map(getFullType);
355
+ }
356
+
357
+ //#endregion
358
+ //#region federation/handler.ts
359
+ function acceptsJsonLd(request) {
360
+ const accept = request.headers.get("Accept");
361
+ const types = accept ? preferredMediaTypes(accept) : ["*/*"];
362
+ if (types == null) return true;
363
+ if (types[0] === "text/html" || types[0] === "application/xhtml+xml") return false;
364
+ return types.includes("application/activity+json") || types.includes("application/ld+json") || types.includes("application/json");
365
+ }
366
+ async function handleActor(request, { identifier, context: context$1, actorDispatcher, authorizePredicate, onNotFound, onNotAcceptable, onUnauthorized }) {
367
+ const logger$2 = getLogger([
368
+ "fedify",
369
+ "federation",
370
+ "actor"
371
+ ]);
372
+ if (actorDispatcher == null) {
373
+ logger$2.debug("Actor dispatcher is not set.", { identifier });
374
+ return await onNotFound(request);
375
+ }
376
+ const actor = await actorDispatcher(context$1, identifier);
377
+ if (actor == null) {
378
+ logger$2.debug("Actor {identifier} not found.", { identifier });
379
+ return await onNotFound(request);
380
+ }
381
+ if (!acceptsJsonLd(request)) return await onNotAcceptable(request);
382
+ if (authorizePredicate != null) {
383
+ let key = await context$1.getSignedKey();
384
+ key = key?.clone({}, { $warning: {
385
+ category: [
386
+ "fedify",
387
+ "federation",
388
+ "actor"
389
+ ],
390
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
391
+ } }) ?? null;
392
+ let keyOwner = await context$1.getSignedKeyOwner();
393
+ keyOwner = keyOwner?.clone({}, { $warning: {
394
+ category: [
395
+ "fedify",
396
+ "federation",
397
+ "actor"
398
+ ],
399
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
400
+ } }) ?? null;
401
+ if (!await authorizePredicate(context$1, identifier, key, keyOwner)) return await onUnauthorized(request);
402
+ }
403
+ const jsonLd = await actor.toJsonLd(context$1);
404
+ return new Response(JSON.stringify(jsonLd), { headers: {
405
+ "Content-Type": "application/activity+json",
406
+ Vary: "Accept"
407
+ } });
408
+ }
409
+ async function handleObject(request, { values, context: context$1, objectDispatcher, authorizePredicate, onNotFound, onNotAcceptable, onUnauthorized }) {
410
+ if (objectDispatcher == null) return await onNotFound(request);
411
+ const object = await objectDispatcher(context$1, values);
412
+ if (object == null) return await onNotFound(request);
413
+ if (!acceptsJsonLd(request)) return await onNotAcceptable(request);
414
+ if (authorizePredicate != null) {
415
+ let key = await context$1.getSignedKey();
416
+ key = key?.clone({}, { $warning: {
417
+ category: [
418
+ "fedify",
419
+ "federation",
420
+ "object"
421
+ ],
422
+ message: "The third parameter of ObjectAuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
423
+ } }) ?? null;
424
+ let keyOwner = await context$1.getSignedKeyOwner();
425
+ keyOwner = keyOwner?.clone({}, { $warning: {
426
+ category: [
427
+ "fedify",
428
+ "federation",
429
+ "object"
430
+ ],
431
+ message: "The fourth parameter of ObjectAuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
432
+ } }) ?? null;
433
+ if (!await authorizePredicate(context$1, values, key, keyOwner)) return await onUnauthorized(request);
434
+ }
435
+ const jsonLd = await object.toJsonLd(context$1);
436
+ return new Response(JSON.stringify(jsonLd), { headers: {
437
+ "Content-Type": "application/activity+json",
438
+ Vary: "Accept"
439
+ } });
440
+ }
441
+ async function handleCollection(request, { name: name$1, identifier, uriGetter, filter, filterPredicate, context: context$1, collectionCallbacks, tracerProvider, onUnauthorized, onNotFound, onNotAcceptable }) {
442
+ const spanName = name$1.trim().replace(/\s+/g, "_");
443
+ tracerProvider = tracerProvider ?? trace.getTracerProvider();
444
+ const tracer = tracerProvider.getTracer(name, version);
445
+ const cursor = new URL(request.url).searchParams.get("cursor");
446
+ if (collectionCallbacks == null) return await onNotFound(request);
447
+ let collection;
448
+ const baseUri = uriGetter(identifier);
449
+ if (cursor == null) {
450
+ const firstCursor = await collectionCallbacks.firstCursor?.(context$1, identifier);
451
+ const totalItems = filter == null ? await collectionCallbacks.counter?.(context$1, identifier) : void 0;
452
+ if (firstCursor == null) {
453
+ const itemsOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection ${spanName}`, {
454
+ kind: SpanKind.SERVER,
455
+ attributes: {
456
+ "activitypub.collection.id": baseUri.href,
457
+ "activitypub.collection.type": OrderedCollection.typeId.href
458
+ }
459
+ }, async (span) => {
460
+ if (totalItems != null) span.setAttribute("activitypub.collection.total_items", Number(totalItems));
461
+ try {
462
+ const page = await collectionCallbacks.dispatcher(context$1, identifier, null, filter);
463
+ if (page == null) {
464
+ span.setStatus({ code: SpanStatusCode.ERROR });
465
+ return await onNotFound(request);
466
+ }
467
+ const { items } = page;
468
+ span.setAttribute("fedify.collection.items", items.length);
469
+ return items;
470
+ } catch (e) {
471
+ span.setStatus({
472
+ code: SpanStatusCode.ERROR,
473
+ message: String(e)
474
+ });
475
+ throw e;
476
+ } finally {
477
+ span.end();
478
+ }
479
+ });
480
+ if (itemsOrResponse instanceof Response) return itemsOrResponse;
481
+ collection = new OrderedCollection({
482
+ id: baseUri,
483
+ totalItems: totalItems == null ? null : Number(totalItems),
484
+ items: filterCollectionItems(itemsOrResponse, name$1, filterPredicate)
485
+ });
486
+ } else {
487
+ const lastCursor = await collectionCallbacks.lastCursor?.(context$1, identifier);
488
+ const first = new URL(context$1.url);
489
+ first.searchParams.set("cursor", firstCursor);
490
+ let last = null;
491
+ if (lastCursor != null) {
492
+ last = new URL(context$1.url);
493
+ last.searchParams.set("cursor", lastCursor);
494
+ }
495
+ collection = new OrderedCollection({
496
+ id: baseUri,
497
+ totalItems: totalItems == null ? null : Number(totalItems),
498
+ first,
499
+ last
500
+ });
501
+ }
502
+ } else {
503
+ const uri = new URL(baseUri);
504
+ uri.searchParams.set("cursor", cursor);
505
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$1}`, {
506
+ kind: SpanKind.SERVER,
507
+ attributes: {
508
+ "activitypub.collection.id": uri.href,
509
+ "activitypub.collection.type": OrderedCollectionPage.typeId.href,
510
+ "fedify.collection.cursor": cursor
511
+ }
512
+ }, async (span) => {
513
+ try {
514
+ const page = await collectionCallbacks.dispatcher(context$1, identifier, cursor, filter);
515
+ if (page == null) {
516
+ span.setStatus({ code: SpanStatusCode.ERROR });
517
+ return await onNotFound(request);
518
+ }
519
+ span.setAttribute("fedify.collection.items", page.items.length);
520
+ return page;
521
+ } catch (e) {
522
+ span.setStatus({
523
+ code: SpanStatusCode.ERROR,
524
+ message: String(e)
525
+ });
526
+ throw e;
527
+ } finally {
528
+ span.end();
529
+ }
530
+ });
531
+ if (pageOrResponse instanceof Response) return pageOrResponse;
532
+ const { items, prevCursor, nextCursor } = pageOrResponse;
533
+ let prev = null;
534
+ if (prevCursor != null) {
535
+ prev = new URL(context$1.url);
536
+ prev.searchParams.set("cursor", prevCursor);
537
+ }
538
+ let next = null;
539
+ if (nextCursor != null) {
540
+ next = new URL(context$1.url);
541
+ next.searchParams.set("cursor", nextCursor);
542
+ }
543
+ const partOf = new URL(context$1.url);
544
+ partOf.searchParams.delete("cursor");
545
+ collection = new OrderedCollectionPage({
546
+ id: uri,
547
+ prev,
548
+ next,
549
+ items: filterCollectionItems(items, name$1, filterPredicate),
550
+ partOf
551
+ });
552
+ }
553
+ if (!acceptsJsonLd(request)) return await onNotAcceptable(request);
554
+ if (collectionCallbacks.authorizePredicate != null) {
555
+ let key = await context$1.getSignedKey();
556
+ key = key?.clone({}, { $warning: {
557
+ category: [
558
+ "fedify",
559
+ "federation",
560
+ "collection"
561
+ ],
562
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
563
+ } }) ?? null;
564
+ let keyOwner = await context$1.getSignedKeyOwner();
565
+ keyOwner = keyOwner?.clone({}, { $warning: {
566
+ category: [
567
+ "fedify",
568
+ "federation",
569
+ "collection"
570
+ ],
571
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
572
+ } }) ?? null;
573
+ if (!await collectionCallbacks.authorizePredicate(context$1, identifier, key, keyOwner)) return await onUnauthorized(request);
574
+ }
575
+ const jsonLd = await collection.toJsonLd(context$1);
576
+ return new Response(JSON.stringify(jsonLd), { headers: {
577
+ "Content-Type": "application/activity+json",
578
+ Vary: "Accept"
579
+ } });
580
+ }
581
+ function filterCollectionItems(items, collectionName, filterPredicate) {
582
+ const result = [];
583
+ let logged = false;
584
+ for (const item of items) {
585
+ let mappedItem;
586
+ if (item instanceof Object$1 || item instanceof Link || item instanceof URL) mappedItem = item;
587
+ else if (item.id == null) continue;
588
+ else mappedItem = item.id;
589
+ if (filterPredicate != null && !filterPredicate(item)) {
590
+ if (!logged) {
591
+ getLogger([
592
+ "fedify",
593
+ "federation",
594
+ "collection"
595
+ ]).warn(`The ${collectionName} collection apparently does not implement filtering. This may result in a large response payload. Please consider implementing filtering for the collection. See also: https://fedify.dev/manual/collections#filtering-by-server`);
596
+ logged = true;
597
+ }
598
+ continue;
599
+ }
600
+ result.push(mappedItem);
601
+ }
602
+ return result;
603
+ }
604
+ async function handleInbox(request, options) {
605
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.inbox", {
606
+ kind: options.queue == null ? SpanKind.SERVER : SpanKind.PRODUCER,
607
+ attributes: { "activitypub.shared_inbox": options.recipient == null }
608
+ }, async (span) => {
609
+ if (options.recipient != null) span.setAttribute("fedify.inbox.recipient", options.recipient);
610
+ try {
611
+ return await handleInboxInternal(request, options, span);
612
+ } catch (e) {
613
+ span.setStatus({
614
+ code: SpanStatusCode.ERROR,
615
+ message: String(e)
616
+ });
617
+ throw e;
618
+ } finally {
619
+ span.end();
620
+ }
621
+ });
622
+ }
623
+ async function handleInboxInternal(request, { recipient, context: ctx, inboxContextFactory, kv, kvPrefixes, queue, actorDispatcher, inboxListeners, inboxErrorHandler, onNotFound, signatureTimeWindow, skipSignatureVerification, tracerProvider }, span) {
624
+ const logger$2 = getLogger([
625
+ "fedify",
626
+ "federation",
627
+ "inbox"
628
+ ]);
629
+ if (actorDispatcher == null) {
630
+ logger$2.error("Actor dispatcher is not set.", { recipient });
631
+ span.setStatus({
632
+ code: SpanStatusCode.ERROR,
633
+ message: "Actor dispatcher is not set."
634
+ });
635
+ return await onNotFound(request);
636
+ } else if (recipient != null) {
637
+ if (await actorDispatcher(ctx, recipient) == null) {
638
+ logger$2.error("Actor {recipient} not found.", { recipient });
639
+ span.setStatus({
640
+ code: SpanStatusCode.ERROR,
641
+ message: `Actor ${recipient} not found.`
642
+ });
643
+ return await onNotFound(request);
644
+ }
645
+ }
646
+ if (request.bodyUsed) {
647
+ logger$2.error("Request body has already been read.", { recipient });
648
+ span.setStatus({
649
+ code: SpanStatusCode.ERROR,
650
+ message: "Request body has already been read."
651
+ });
652
+ return new Response("Internal server error.", {
653
+ status: 500,
654
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
655
+ });
656
+ } else if (request.body?.locked) {
657
+ logger$2.error("Request body is locked.", { recipient });
658
+ span.setStatus({
659
+ code: SpanStatusCode.ERROR,
660
+ message: "Request body is locked."
661
+ });
662
+ return new Response("Internal server error.", {
663
+ status: 500,
664
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
665
+ });
666
+ }
667
+ let json;
668
+ try {
669
+ json = await request.clone().json();
670
+ } catch (error) {
671
+ logger$2.error("Failed to parse JSON:\n{error}", {
672
+ recipient,
673
+ error
674
+ });
675
+ try {
676
+ await inboxErrorHandler?.(ctx, error);
677
+ } catch (error$1) {
678
+ logger$2.error("An unexpected error occurred in inbox error handler:\n{error}", {
679
+ error: error$1,
680
+ activity: json,
681
+ recipient
682
+ });
683
+ }
684
+ span.setStatus({
685
+ code: SpanStatusCode.ERROR,
686
+ message: `Failed to parse JSON:\n${error}`
687
+ });
688
+ return new Response("Invalid JSON.", {
689
+ status: 400,
690
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
691
+ });
692
+ }
693
+ const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
694
+ let ldSigVerified;
695
+ try {
696
+ ldSigVerified = await verifyJsonLd(json, {
697
+ contextLoader: ctx.contextLoader,
698
+ documentLoader: ctx.documentLoader,
699
+ keyCache,
700
+ tracerProvider
701
+ });
702
+ } catch (error) {
703
+ if (error instanceof Error && error.name === "jsonld.SyntaxError") {
704
+ logger$2.error("Failed to parse JSON-LD:\n{error}", {
705
+ recipient,
706
+ error
707
+ });
708
+ return new Response("Invalid JSON-LD.", {
709
+ status: 400,
710
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
711
+ });
712
+ }
713
+ ldSigVerified = false;
714
+ }
715
+ const jsonWithoutSig = detachSignature(json);
716
+ let activity = null;
717
+ if (ldSigVerified) {
718
+ logger$2.debug("Linked Data Signatures are verified.", {
719
+ recipient,
720
+ json
721
+ });
722
+ activity = await Activity.fromJsonLd(jsonWithoutSig, ctx);
723
+ } else {
724
+ logger$2.debug("Linked Data Signatures are not verified.", {
725
+ recipient,
726
+ json
727
+ });
728
+ try {
729
+ activity = await verifyObject(Activity, jsonWithoutSig, {
730
+ contextLoader: ctx.contextLoader,
731
+ documentLoader: ctx.documentLoader,
732
+ keyCache,
733
+ tracerProvider
734
+ });
735
+ } catch (error) {
736
+ logger$2.error("Failed to parse activity:\n{error}", {
737
+ recipient,
738
+ activity: json,
739
+ error
740
+ });
741
+ try {
742
+ await inboxErrorHandler?.(ctx, error);
743
+ } catch (error$1) {
744
+ logger$2.error("An unexpected error occurred in inbox error handler:\n{error}", {
745
+ error: error$1,
746
+ activity: json,
747
+ recipient
748
+ });
749
+ }
750
+ span.setStatus({
751
+ code: SpanStatusCode.ERROR,
752
+ message: `Failed to parse activity:\n${error}`
753
+ });
754
+ return new Response("Invalid activity.", {
755
+ status: 400,
756
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
757
+ });
758
+ }
759
+ if (activity == null) logger$2.debug("Object Integrity Proofs are not verified.", {
760
+ recipient,
761
+ activity: json
762
+ });
763
+ else logger$2.debug("Object Integrity Proofs are verified.", {
764
+ recipient,
765
+ activity: json
766
+ });
767
+ }
768
+ let httpSigKey = null;
769
+ if (activity == null) {
770
+ if (!skipSignatureVerification) {
771
+ const key = await verifyRequest(request, {
772
+ contextLoader: ctx.contextLoader,
773
+ documentLoader: ctx.documentLoader,
774
+ timeWindow: signatureTimeWindow,
775
+ keyCache,
776
+ tracerProvider
777
+ });
778
+ if (key == null) {
779
+ logger$2.error("Failed to verify the request's HTTP Signatures.", { recipient });
780
+ span.setStatus({
781
+ code: SpanStatusCode.ERROR,
782
+ message: `Failed to verify the request's HTTP Signatures.`
783
+ });
784
+ return new Response("Failed to verify the request signature.", {
785
+ status: 401,
786
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
787
+ });
788
+ } else logger$2.debug("HTTP Signatures are verified.", { recipient });
789
+ httpSigKey = key;
790
+ }
791
+ activity = await Activity.fromJsonLd(jsonWithoutSig, ctx);
792
+ }
793
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
794
+ span.setAttribute("activitypub.activity.type", getTypeId(activity).href);
795
+ if (httpSigKey != null && !await doesActorOwnKey(activity, httpSigKey, ctx)) {
796
+ logger$2.error("The signer ({keyId}) and the actor ({actorId}) do not match.", {
797
+ activity: json,
798
+ recipient,
799
+ keyId: httpSigKey.id?.href,
800
+ actorId: activity.actorId?.href
801
+ });
802
+ span.setStatus({
803
+ code: SpanStatusCode.ERROR,
804
+ message: `The signer (${httpSigKey.id?.href}) and the actor (${activity.actorId?.href}) do not match.`
805
+ });
806
+ return new Response("The signer and the actor do not match.", {
807
+ status: 401,
808
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
809
+ });
810
+ }
811
+ const routeResult = await routeActivity({
812
+ context: ctx,
813
+ json,
814
+ activity,
815
+ recipient,
816
+ inboxListeners,
817
+ inboxContextFactory,
818
+ inboxErrorHandler,
819
+ kv,
820
+ kvPrefixes,
821
+ queue,
822
+ span,
823
+ tracerProvider
824
+ });
825
+ if (routeResult === "alreadyProcessed") return new Response(`Activity <${activity.id}> has already been processed.`, {
826
+ status: 202,
827
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
828
+ });
829
+ else if (routeResult === "missingActor") return new Response("Missing actor.", {
830
+ status: 400,
831
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
832
+ });
833
+ else if (routeResult === "enqueued") return new Response("Activity is enqueued.", {
834
+ status: 202,
835
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
836
+ });
837
+ else if (routeResult === "unsupportedActivity") return new Response("", {
838
+ status: 202,
839
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
840
+ });
841
+ else if (routeResult === "error") return new Response("Internal server error.", {
842
+ status: 500,
843
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
844
+ });
845
+ else return new Response("", {
846
+ status: 202,
847
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
848
+ });
849
+ }
850
+ /**
851
+ * Responds with the given object in JSON-LD format.
852
+ *
853
+ * @param object The object to respond with.
854
+ * @param options Options.
855
+ * @since 0.3.0
856
+ */
857
+ async function respondWithObject(object, options) {
858
+ const jsonLd = await object.toJsonLd(options);
859
+ return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
860
+ }
861
+ /**
862
+ * Responds with the given object in JSON-LD format if the request accepts
863
+ * JSON-LD.
864
+ *
865
+ * @param object The object to respond with.
866
+ * @param request The request to check for JSON-LD acceptability.
867
+ * @param options Options.
868
+ * @since 0.3.0
869
+ */
870
+ async function respondWithObjectIfAcceptable(object, request, options) {
871
+ if (!acceptsJsonLd(request)) return null;
872
+ const response = await respondWithObject(object, options);
873
+ response.headers.set("Vary", "Accept");
874
+ return response;
875
+ }
876
+
877
+ //#endregion
878
+ //#region federation/middleware.ts
879
+ /**
880
+ * Create a new {@link Federation} instance.
881
+ * @param parameters Parameters for initializing the instance.
882
+ * @returns A new {@link Federation} instance.
883
+ * @since 0.10.0
884
+ */
885
+ function createFederation(options) {
886
+ return new FederationImpl(options);
887
+ }
888
+ var FederationImpl = class extends FederationBuilderImpl {
889
+ kv;
890
+ kvPrefixes;
891
+ inboxQueue;
892
+ outboxQueue;
893
+ fanoutQueue;
894
+ inboxQueueStarted;
895
+ outboxQueueStarted;
896
+ fanoutQueueStarted;
897
+ manuallyStartQueue;
898
+ origin;
899
+ documentLoaderFactory;
900
+ contextLoaderFactory;
901
+ authenticatedDocumentLoaderFactory;
902
+ allowPrivateAddress;
903
+ userAgent;
904
+ onOutboxError;
905
+ signatureTimeWindow;
906
+ skipSignatureVerification;
907
+ outboxRetryPolicy;
908
+ inboxRetryPolicy;
909
+ activityTransformers;
910
+ tracerProvider;
911
+ constructor(options) {
912
+ super();
913
+ const logger$2 = getLogger(["fedify", "federation"]);
914
+ this.kv = options.kv;
915
+ this.kvPrefixes = {
916
+ activityIdempotence: ["_fedify", "activityIdempotence"],
917
+ remoteDocument: ["_fedify", "remoteDocument"],
918
+ publicKey: ["_fedify", "publicKey"],
919
+ httpMessageSignaturesSpec: ["_fedify", "httpMessageSignaturesSpec"],
920
+ ...options.kvPrefixes ?? {}
921
+ };
922
+ if (options.queue == null) {
923
+ this.inboxQueue = void 0;
924
+ this.outboxQueue = void 0;
925
+ this.fanoutQueue = void 0;
926
+ } else if ("enqueue" in options.queue && "listen" in options.queue) {
927
+ this.inboxQueue = options.queue;
928
+ this.outboxQueue = options.queue;
929
+ this.fanoutQueue = options.queue;
930
+ } else {
931
+ this.inboxQueue = options.queue.inbox;
932
+ this.outboxQueue = options.queue.outbox;
933
+ this.fanoutQueue = options.queue.fanout;
934
+ }
935
+ this.inboxQueueStarted = false;
936
+ this.outboxQueueStarted = false;
937
+ this.fanoutQueueStarted = false;
938
+ this.manuallyStartQueue = options.manuallyStartQueue ?? false;
939
+ if (options.origin != null) if (typeof options.origin === "string") {
940
+ if (!URL.canParse(options.origin) || !options.origin.match(/^https?:\/\//)) throw new TypeError(`Invalid origin: ${JSON.stringify(options.origin)}`);
941
+ const origin = new URL(options.origin);
942
+ if (!origin.pathname.match(/^\/*$/) || origin.search !== "" || origin.hash !== "") throw new TypeError(`Invalid origin: ${JSON.stringify(options.origin)}`);
943
+ this.origin = {
944
+ handleHost: origin.host,
945
+ webOrigin: origin.origin
946
+ };
947
+ } else {
948
+ const { handleHost, webOrigin } = options.origin;
949
+ if (!URL.canParse(`https://${handleHost}/`) || handleHost.includes("/")) throw new TypeError(`Invalid origin.handleHost: ${JSON.stringify(handleHost)}`);
950
+ if (!URL.canParse(webOrigin) || !webOrigin.match(/^https?:\/\//)) throw new TypeError(`Invalid origin.webOrigin: ${JSON.stringify(webOrigin)}`);
951
+ const webOriginUrl = new URL(webOrigin);
952
+ if (!webOriginUrl.pathname.match(/^\/*$/) || webOriginUrl.search !== "" || webOriginUrl.hash !== "") throw new TypeError(`Invalid origin.webOrigin: ${JSON.stringify(webOrigin)}`);
953
+ this.origin = {
954
+ handleHost: new URL(`https://${handleHost}/`).host,
955
+ webOrigin: webOriginUrl.origin
956
+ };
957
+ }
958
+ this.router.trailingSlashInsensitive = options.trailingSlashInsensitive ?? false;
959
+ this._initializeRouter();
960
+ if (options.allowPrivateAddress || options.userAgent != null) {
961
+ if (options.documentLoader != null) throw new TypeError("Cannot set documentLoader with allowPrivateAddress or userAgent options.");
962
+ else if (options.contextLoader != null) throw new TypeError("Cannot set contextLoader with allowPrivateAddress or userAgent options.");
963
+ else if (options.authenticatedDocumentLoaderFactory != null) throw new TypeError("Cannot set authenticatedDocumentLoaderFactory with allowPrivateAddress or userAgent options.");
964
+ }
965
+ const { allowPrivateAddress, userAgent } = options;
966
+ this.allowPrivateAddress = allowPrivateAddress ?? false;
967
+ if (options.documentLoader != null) {
968
+ if (options.documentLoaderFactory != null) throw new TypeError("Cannot set both documentLoader and documentLoaderFactory options at a time; use documentLoaderFactory only.");
969
+ this.documentLoaderFactory = () => options.documentLoader;
970
+ logger$2.warn("The documentLoader option is deprecated; use documentLoaderFactory option instead.");
971
+ } else this.documentLoaderFactory = options.documentLoaderFactory ?? ((opts) => {
972
+ return kvCache({
973
+ loader: getDocumentLoader({
974
+ allowPrivateAddress: opts?.allowPrivateAddress ?? allowPrivateAddress,
975
+ userAgent: opts?.userAgent ?? userAgent
976
+ }),
977
+ kv: options.kv,
978
+ prefix: this.kvPrefixes.remoteDocument
979
+ });
980
+ });
981
+ if (options.contextLoader != null) {
982
+ if (options.contextLoaderFactory != null) throw new TypeError("Cannot set both contextLoader and contextLoaderFactory options at a time; use contextLoaderFactory only.");
983
+ this.contextLoaderFactory = () => options.contextLoader;
984
+ logger$2.warn("The contextLoader option is deprecated; use contextLoaderFactory option instead.");
985
+ } else this.contextLoaderFactory = options.contextLoaderFactory ?? this.documentLoaderFactory;
986
+ this.authenticatedDocumentLoaderFactory = options.authenticatedDocumentLoaderFactory ?? ((identity) => getAuthenticatedDocumentLoader(identity, {
987
+ allowPrivateAddress,
988
+ userAgent,
989
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec),
990
+ tracerProvider: this.tracerProvider
991
+ }));
992
+ this.userAgent = userAgent;
993
+ this.onOutboxError = options.onOutboxError;
994
+ this.signatureTimeWindow = options.signatureTimeWindow ?? { hours: 1 };
995
+ this.skipSignatureVerification = options.skipSignatureVerification ?? false;
996
+ this.outboxRetryPolicy = options.outboxRetryPolicy ?? createExponentialBackoffPolicy();
997
+ this.inboxRetryPolicy = options.inboxRetryPolicy ?? createExponentialBackoffPolicy();
998
+ this.activityTransformers = options.activityTransformers ?? getDefaultActivityTransformers();
999
+ this.tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
1000
+ }
1001
+ _initializeRouter() {
1002
+ this.router.add("/.well-known/webfinger", "webfinger");
1003
+ this.router.add("/.well-known/nodeinfo", "nodeInfoJrd");
1004
+ }
1005
+ _getTracer() {
1006
+ return this.tracerProvider.getTracer(name, version);
1007
+ }
1008
+ async _startQueueInternal(ctxData, signal, queue) {
1009
+ if (this.inboxQueue == null && this.outboxQueue == null) return;
1010
+ const logger$2 = getLogger([
1011
+ "fedify",
1012
+ "federation",
1013
+ "queue"
1014
+ ]);
1015
+ const promises = [];
1016
+ if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
1017
+ logger$2.debug("Starting an inbox task worker.");
1018
+ this.inboxQueueStarted = true;
1019
+ promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
1020
+ }
1021
+ if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
1022
+ logger$2.debug("Starting an outbox task worker.");
1023
+ this.outboxQueueStarted = true;
1024
+ promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
1025
+ }
1026
+ if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
1027
+ logger$2.debug("Starting a fanout task worker.");
1028
+ this.fanoutQueueStarted = true;
1029
+ promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
1030
+ }
1031
+ await Promise.all(promises);
1032
+ }
1033
+ processQueuedTask(contextData, message) {
1034
+ const tracer = this._getTracer();
1035
+ const extractedContext = propagation.extract(context.active(), message.traceContext);
1036
+ return withContext({ messageId: message.id }, async () => {
1037
+ if (message.type === "fanout") await tracer.startActiveSpan("activitypub.fanout", {
1038
+ kind: SpanKind.CONSUMER,
1039
+ attributes: { "activitypub.activity.type": message.activityType }
1040
+ }, extractedContext, async (span) => {
1041
+ if (message.activityId != null) span.setAttribute("activitypub.activity.id", message.activityId);
1042
+ try {
1043
+ await this.#listenFanoutMessage(contextData, message);
1044
+ } catch (e) {
1045
+ span.setStatus({
1046
+ code: SpanStatusCode.ERROR,
1047
+ message: String(e)
1048
+ });
1049
+ throw e;
1050
+ } finally {
1051
+ span.end();
1052
+ }
1053
+ });
1054
+ else if (message.type === "outbox") await tracer.startActiveSpan("activitypub.outbox", {
1055
+ kind: SpanKind.CONSUMER,
1056
+ attributes: {
1057
+ "activitypub.activity.type": message.activityType,
1058
+ "activitypub.activity.retries": message.attempt
1059
+ }
1060
+ }, extractedContext, async (span) => {
1061
+ if (message.activityId != null) span.setAttribute("activitypub.activity.id", message.activityId);
1062
+ try {
1063
+ await this.#listenOutboxMessage(contextData, message, span);
1064
+ } catch (e) {
1065
+ span.setStatus({
1066
+ code: SpanStatusCode.ERROR,
1067
+ message: String(e)
1068
+ });
1069
+ throw e;
1070
+ } finally {
1071
+ span.end();
1072
+ }
1073
+ });
1074
+ else if (message.type === "inbox") await tracer.startActiveSpan("activitypub.inbox", {
1075
+ kind: SpanKind.CONSUMER,
1076
+ attributes: { "activitypub.shared_inbox": message.identifier == null }
1077
+ }, extractedContext, async (span) => {
1078
+ try {
1079
+ await this.#listenInboxMessage(contextData, message, span);
1080
+ } catch (e) {
1081
+ span.setStatus({
1082
+ code: SpanStatusCode.ERROR,
1083
+ message: String(e)
1084
+ });
1085
+ throw e;
1086
+ } finally {
1087
+ span.end();
1088
+ }
1089
+ });
1090
+ });
1091
+ }
1092
+ async #listenFanoutMessage(data, message) {
1093
+ getLogger([
1094
+ "fedify",
1095
+ "federation",
1096
+ "fanout"
1097
+ ]).debug("Fanning out activity {activityId} to {inboxes} inbox(es)...", {
1098
+ activityId: message.activityId,
1099
+ inboxes: globalThis.Object.keys(message.inboxes).length
1100
+ });
1101
+ const keys = await Promise.all(message.keys.map(async ({ keyId, privateKey }) => ({
1102
+ keyId: new URL(keyId),
1103
+ privateKey: await importJwk(privateKey, "private")
1104
+ })));
1105
+ const activity = await Activity.fromJsonLd(message.activity, {
1106
+ contextLoader: this.contextLoaderFactory({
1107
+ allowPrivateAddress: this.allowPrivateAddress,
1108
+ userAgent: this.userAgent
1109
+ }),
1110
+ documentLoader: this.documentLoaderFactory({
1111
+ allowPrivateAddress: this.allowPrivateAddress,
1112
+ userAgent: this.userAgent
1113
+ }),
1114
+ tracerProvider: this.tracerProvider
1115
+ });
1116
+ const context$1 = this.#createContext(new URL(message.baseUrl), data, { documentLoader: this.documentLoaderFactory({
1117
+ allowPrivateAddress: this.allowPrivateAddress,
1118
+ userAgent: this.userAgent
1119
+ }) });
1120
+ await this.sendActivity(keys, message.inboxes, activity, {
1121
+ collectionSync: message.collectionSync,
1122
+ context: context$1
1123
+ });
1124
+ }
1125
+ async #listenOutboxMessage(_, message, span) {
1126
+ const logger$2 = getLogger([
1127
+ "fedify",
1128
+ "federation",
1129
+ "outbox"
1130
+ ]);
1131
+ const logData = {
1132
+ keyIds: message.keys.map((pair) => pair.keyId),
1133
+ inbox: message.inbox,
1134
+ activity: message.activity,
1135
+ activityId: message.activityId,
1136
+ attempt: message.attempt,
1137
+ headers: message.headers
1138
+ };
1139
+ const keys = [];
1140
+ let rsaKeyPair = null;
1141
+ for (const { keyId, privateKey } of message.keys) {
1142
+ const pair = {
1143
+ keyId: new URL(keyId),
1144
+ privateKey: await importJwk(privateKey, "private")
1145
+ };
1146
+ if (rsaKeyPair == null && pair.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") rsaKeyPair = pair;
1147
+ keys.push(pair);
1148
+ }
1149
+ try {
1150
+ await sendActivity({
1151
+ keys,
1152
+ activity: message.activity,
1153
+ activityId: message.activityId,
1154
+ activityType: message.activityType,
1155
+ inbox: new URL(message.inbox),
1156
+ sharedInbox: message.sharedInbox,
1157
+ headers: new Headers(message.headers),
1158
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec),
1159
+ tracerProvider: this.tracerProvider
1160
+ });
1161
+ } catch (error) {
1162
+ span.setStatus({
1163
+ code: SpanStatusCode.ERROR,
1164
+ message: String(error)
1165
+ });
1166
+ const loaderOptions = this.#getLoaderOptions(message.baseUrl);
1167
+ const activity = await Activity.fromJsonLd(message.activity, {
1168
+ contextLoader: this.contextLoaderFactory(loaderOptions),
1169
+ documentLoader: rsaKeyPair == null ? this.documentLoaderFactory(loaderOptions) : this.authenticatedDocumentLoaderFactory(rsaKeyPair, loaderOptions),
1170
+ tracerProvider: this.tracerProvider
1171
+ });
1172
+ try {
1173
+ this.onOutboxError?.(error, activity);
1174
+ } catch (error$1) {
1175
+ logger$2.error("An unexpected error occurred in onError handler:\n{error}", {
1176
+ ...logData,
1177
+ error: error$1
1178
+ });
1179
+ }
1180
+ const delay = this.outboxRetryPolicy({
1181
+ elapsedTime: Temporal.Instant.from(message.started).until(Temporal.Now.instant()),
1182
+ attempts: message.attempt
1183
+ });
1184
+ if (delay != null) {
1185
+ logger$2.error("Failed to send activity {activityId} to {inbox} (attempt #{attempt}); retry...:\n{error}", {
1186
+ ...logData,
1187
+ error
1188
+ });
1189
+ await this.outboxQueue?.enqueue({
1190
+ ...message,
1191
+ attempt: message.attempt + 1
1192
+ }, { delay: Temporal.Duration.compare(delay, { seconds: 0 }) < 0 ? Temporal.Duration.from({ seconds: 0 }) : delay });
1193
+ } else logger$2.error("Failed to send activity {activityId} to {inbox} after {attempt} attempts; giving up:\n{error}", {
1194
+ ...logData,
1195
+ error
1196
+ });
1197
+ return;
1198
+ }
1199
+ logger$2.info("Successfully sent activity {activityId} to {inbox}.", { ...logData });
1200
+ }
1201
+ async #listenInboxMessage(ctxData, message, span) {
1202
+ const logger$2 = getLogger([
1203
+ "fedify",
1204
+ "federation",
1205
+ "inbox"
1206
+ ]);
1207
+ const baseUrl = new URL(message.baseUrl);
1208
+ let context$1 = this.#createContext(baseUrl, ctxData);
1209
+ if (message.identifier != null) context$1 = this.#createContext(baseUrl, ctxData, { documentLoader: await context$1.getDocumentLoader({ identifier: message.identifier }) });
1210
+ else if (this.sharedInboxKeyDispatcher != null) {
1211
+ const identity = await this.sharedInboxKeyDispatcher(context$1);
1212
+ if (identity != null) context$1 = this.#createContext(baseUrl, ctxData, { documentLoader: "identifier" in identity || "username" in identity || "handle" in identity ? await context$1.getDocumentLoader(identity) : context$1.getDocumentLoader(identity) });
1213
+ }
1214
+ const activity = await Activity.fromJsonLd(message.activity, context$1);
1215
+ span.setAttribute("activitypub.activity.type", getTypeId(activity).href);
1216
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
1217
+ const cacheKey = activity.id == null ? null : [
1218
+ ...this.kvPrefixes.activityIdempotence,
1219
+ context$1.origin,
1220
+ activity.id.href
1221
+ ];
1222
+ if (cacheKey != null) {
1223
+ if (await this.kv.get(cacheKey) === true) {
1224
+ logger$2.debug("Activity {activityId} has already been processed.", {
1225
+ activityId: activity.id?.href,
1226
+ activity: message.activity,
1227
+ recipient: message.identifier
1228
+ });
1229
+ return;
1230
+ }
1231
+ }
1232
+ await this._getTracer().startActiveSpan("activitypub.dispatch_inbox_listener", { kind: SpanKind.INTERNAL }, async (span$1) => {
1233
+ const dispatched = this.inboxListeners?.dispatchWithClass(activity);
1234
+ if (dispatched == null) {
1235
+ logger$2.error("Unsupported activity type:\n{activity}", {
1236
+ activityId: activity.id?.href,
1237
+ activity: message.activity,
1238
+ recipient: message.identifier,
1239
+ trial: message.attempt
1240
+ });
1241
+ span$1.setStatus({
1242
+ code: SpanStatusCode.ERROR,
1243
+ message: `Unsupported activity type: ${getTypeId(activity).href}`
1244
+ });
1245
+ span$1.end();
1246
+ return;
1247
+ }
1248
+ const { class: cls, listener } = dispatched;
1249
+ span$1.updateName(`activitypub.dispatch_inbox_listener ${cls.name}`);
1250
+ try {
1251
+ await listener(context$1.toInboxContext(message.identifier, message.activity, activity.id?.href, getTypeId(activity).href), activity);
1252
+ } catch (error) {
1253
+ try {
1254
+ await this.inboxErrorHandler?.(context$1, error);
1255
+ } catch (error$1) {
1256
+ logger$2.error("An unexpected error occurred in inbox error handler:\n{error}", {
1257
+ error: error$1,
1258
+ trial: message.attempt,
1259
+ activityId: activity.id?.href,
1260
+ activity: message.activity,
1261
+ recipient: message.identifier
1262
+ });
1263
+ }
1264
+ const delay = this.inboxRetryPolicy({
1265
+ elapsedTime: Temporal.Instant.from(message.started).until(Temporal.Now.instant()),
1266
+ attempts: message.attempt
1267
+ });
1268
+ if (delay != null) {
1269
+ logger$2.error("Failed to process the incoming activity {activityId} (attempt #{attempt}); retry...:\n{error}", {
1270
+ error,
1271
+ attempt: message.attempt,
1272
+ activityId: activity.id?.href,
1273
+ activity: message.activity,
1274
+ recipient: message.identifier
1275
+ });
1276
+ await this.inboxQueue?.enqueue({
1277
+ ...message,
1278
+ attempt: message.attempt + 1
1279
+ }, { delay: Temporal.Duration.compare(delay, { seconds: 0 }) < 0 ? Temporal.Duration.from({ seconds: 0 }) : delay });
1280
+ } else logger$2.error("Failed to process the incoming activity {activityId} after {trial} attempts; giving up:\n{error}", {
1281
+ error,
1282
+ activityId: activity.id?.href,
1283
+ activity: message.activity,
1284
+ recipient: message.identifier
1285
+ });
1286
+ span$1.setStatus({
1287
+ code: SpanStatusCode.ERROR,
1288
+ message: String(error)
1289
+ });
1290
+ span$1.end();
1291
+ return;
1292
+ }
1293
+ if (cacheKey != null) await this.kv.set(cacheKey, true, { ttl: Temporal.Duration.from({ days: 1 }) });
1294
+ logger$2.info("Activity {activityId} has been processed.", {
1295
+ activityId: activity.id?.href,
1296
+ activity: message.activity,
1297
+ recipient: message.identifier
1298
+ });
1299
+ span$1.end();
1300
+ });
1301
+ }
1302
+ startQueue(contextData, options = {}) {
1303
+ return this._startQueueInternal(contextData, options.signal, options.queue);
1304
+ }
1305
+ createContext(urlOrRequest, contextData) {
1306
+ return urlOrRequest instanceof Request ? this.#createContext(urlOrRequest, contextData) : this.#createContext(urlOrRequest, contextData);
1307
+ }
1308
+ #createContext(urlOrRequest, contextData, opts = {}) {
1309
+ const request = urlOrRequest instanceof Request ? urlOrRequest : null;
1310
+ const url = urlOrRequest instanceof URL ? new URL(urlOrRequest) : new URL(urlOrRequest.url);
1311
+ if (request == null) {
1312
+ url.pathname = "/";
1313
+ url.hash = "";
1314
+ url.search = "";
1315
+ }
1316
+ const loaderOptions = this.#getLoaderOptions(url.origin);
1317
+ const ctxOptions = {
1318
+ url,
1319
+ federation: this,
1320
+ data: contextData,
1321
+ documentLoader: opts.documentLoader ?? this.documentLoaderFactory(loaderOptions),
1322
+ contextLoader: this.contextLoaderFactory(loaderOptions)
1323
+ };
1324
+ if (request == null) return new ContextImpl(ctxOptions);
1325
+ return new RequestContextImpl({
1326
+ ...ctxOptions,
1327
+ request,
1328
+ invokedFromActorDispatcher: opts.invokedFromActorDispatcher,
1329
+ invokedFromObjectDispatcher: opts.invokedFromObjectDispatcher
1330
+ });
1331
+ }
1332
+ #getLoaderOptions(origin) {
1333
+ origin = typeof origin === "string" ? new URL(origin).origin : origin.origin;
1334
+ return {
1335
+ allowPrivateAddress: this.allowPrivateAddress,
1336
+ userAgent: typeof this.userAgent === "string" ? this.userAgent : {
1337
+ url: origin,
1338
+ ...this.userAgent
1339
+ }
1340
+ };
1341
+ }
1342
+ async sendActivity(keys, inboxes, activity, options) {
1343
+ const logger$2 = getLogger([
1344
+ "fedify",
1345
+ "federation",
1346
+ "outbox"
1347
+ ]);
1348
+ const { immediate, collectionSync, context: ctx } = options;
1349
+ if (activity.id == null) throw new TypeError("The activity to send must have an id.");
1350
+ if (activity.actorId == null) throw new TypeError("The activity to send must have at least one actor property.");
1351
+ else if (keys.length < 1) throw new TypeError("The keys must not be empty.");
1352
+ const contextLoader = this.contextLoaderFactory(this.#getLoaderOptions(ctx.origin));
1353
+ const activityId = activity.id.href;
1354
+ let proofCreated = false;
1355
+ let rsaKey = null;
1356
+ for (const { keyId, privateKey } of keys) {
1357
+ validateCryptoKey(privateKey, "private");
1358
+ if (rsaKey == null && privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
1359
+ rsaKey = {
1360
+ keyId,
1361
+ privateKey
1362
+ };
1363
+ continue;
1364
+ }
1365
+ if (privateKey.algorithm.name === "Ed25519") {
1366
+ activity = await signObject(activity, privateKey, keyId, {
1367
+ contextLoader,
1368
+ tracerProvider: this.tracerProvider
1369
+ });
1370
+ proofCreated = true;
1371
+ }
1372
+ }
1373
+ let jsonLd = await activity.toJsonLd({
1374
+ format: "compact",
1375
+ contextLoader
1376
+ });
1377
+ if (rsaKey == null) logger$2.warn("No supported key found to create a Linked Data signature for the activity {activityId}. The activity will be sent without a Linked Data signature. In order to create a Linked Data signature, at least one RSASSA-PKCS1-v1_5 key must be provided.", {
1378
+ activityId,
1379
+ keys: keys.map((pair) => ({
1380
+ keyId: pair.keyId.href,
1381
+ privateKey: pair.privateKey
1382
+ }))
1383
+ });
1384
+ else jsonLd = await signJsonLd(jsonLd, rsaKey.privateKey, rsaKey.keyId, {
1385
+ contextLoader,
1386
+ tracerProvider: this.tracerProvider
1387
+ });
1388
+ if (!proofCreated) logger$2.warn("No supported key found to create a proof for the activity {activityId}. The activity will be sent without a proof. In order to create a proof, at least one Ed25519 key must be provided.", {
1389
+ activityId,
1390
+ keys: keys.map((pair) => ({
1391
+ keyId: pair.keyId.href,
1392
+ privateKey: pair.privateKey
1393
+ }))
1394
+ });
1395
+ if (immediate || this.outboxQueue == null) {
1396
+ if (immediate) logger$2.debug("Sending activity immediately without queue since immediate option is set.", {
1397
+ activityId: activity.id.href,
1398
+ activity: jsonLd
1399
+ });
1400
+ else logger$2.debug("Sending activity immediately without queue since queue is not set.", {
1401
+ activityId: activity.id.href,
1402
+ activity: jsonLd
1403
+ });
1404
+ const promises = [];
1405
+ for (const inbox in inboxes) promises.push(sendActivity({
1406
+ keys,
1407
+ activity: jsonLd,
1408
+ activityId: activity.id?.href,
1409
+ activityType: getTypeId(activity).href,
1410
+ inbox: new URL(inbox),
1411
+ sharedInbox: inboxes[inbox].sharedInbox,
1412
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
1413
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec),
1414
+ tracerProvider: this.tracerProvider
1415
+ }));
1416
+ await Promise.all(promises);
1417
+ return;
1418
+ }
1419
+ logger$2.debug("Enqueuing activity {activityId} to send later.", {
1420
+ activityId: activity.id.href,
1421
+ activity: jsonLd
1422
+ });
1423
+ const keyJwkPairs = [];
1424
+ for (const { keyId, privateKey } of keys) {
1425
+ const privateKeyJwk = await exportJwk(privateKey);
1426
+ keyJwkPairs.push({
1427
+ keyId: keyId.href,
1428
+ privateKey: privateKeyJwk
1429
+ });
1430
+ }
1431
+ if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
1432
+ const carrier = {};
1433
+ propagation.inject(context.active(), carrier);
1434
+ const messages = [];
1435
+ for (const inbox in inboxes) {
1436
+ const message = {
1437
+ type: "outbox",
1438
+ id: crypto.randomUUID(),
1439
+ baseUrl: ctx.origin,
1440
+ keys: keyJwkPairs,
1441
+ activity: jsonLd,
1442
+ activityId: activity.id?.href,
1443
+ activityType: getTypeId(activity).href,
1444
+ inbox,
1445
+ sharedInbox: inboxes[inbox].sharedInbox,
1446
+ started: (/* @__PURE__ */ new Date()).toISOString(),
1447
+ attempt: 0,
1448
+ headers: collectionSync == null ? {} : { "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) },
1449
+ traceContext: carrier
1450
+ };
1451
+ messages.push(message);
1452
+ }
1453
+ const { outboxQueue } = this;
1454
+ if (outboxQueue.enqueueMany == null) {
1455
+ const promises = messages.map((m) => outboxQueue.enqueue(m));
1456
+ const errors = (await Promise.allSettled(promises)).filter((r) => r.status === "rejected").map((r) => r.reason);
1457
+ if (errors.length > 0) {
1458
+ logger$2.error("Failed to enqueue activity {activityId} to send later: {errors}", {
1459
+ activityId: activity.id.href,
1460
+ errors
1461
+ });
1462
+ if (errors.length > 1) throw new AggregateError(errors, `Failed to enqueue activity ${activityId} to send later.`);
1463
+ throw errors[0];
1464
+ }
1465
+ } else try {
1466
+ await outboxQueue.enqueueMany(messages);
1467
+ } catch (error) {
1468
+ logger$2.error("Failed to enqueue activity {activityId} to send later: {error}", {
1469
+ activityId: activity.id.href,
1470
+ error
1471
+ });
1472
+ throw error;
1473
+ }
1474
+ }
1475
+ fetch(request, options) {
1476
+ return withContext({ requestId: getRequestId(request) }, async () => {
1477
+ const tracer = this._getTracer();
1478
+ return await tracer.startActiveSpan(request.method, {
1479
+ kind: SpanKind.SERVER,
1480
+ attributes: {
1481
+ [ATTR_HTTP_REQUEST_METHOD]: request.method,
1482
+ [ATTR_URL_FULL]: request.url
1483
+ }
1484
+ }, async (span) => {
1485
+ const logger$2 = getLogger([
1486
+ "fedify",
1487
+ "federation",
1488
+ "http"
1489
+ ]);
1490
+ if (span.isRecording()) for (const [k, v] of request.headers) span.setAttribute(ATTR_HTTP_REQUEST_HEADER(k), [v]);
1491
+ let response;
1492
+ try {
1493
+ response = await this.#fetch(request, {
1494
+ ...options,
1495
+ span,
1496
+ tracer
1497
+ });
1498
+ } catch (error) {
1499
+ span.setStatus({
1500
+ code: SpanStatusCode.ERROR,
1501
+ message: `${error}`
1502
+ });
1503
+ span.end();
1504
+ logger$2.error("An error occurred while serving request {method} {url}: {error}", {
1505
+ method: request.method,
1506
+ url: request.url,
1507
+ error
1508
+ });
1509
+ throw error;
1510
+ }
1511
+ if (span.isRecording()) {
1512
+ span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
1513
+ for (const [k, v] of response.headers) span.setAttribute(ATTR_HTTP_RESPONSE_HEADER(k), [v]);
1514
+ span.setStatus({
1515
+ code: response.status >= 500 ? SpanStatusCode.ERROR : SpanStatusCode.UNSET,
1516
+ message: response.statusText
1517
+ });
1518
+ }
1519
+ span.end();
1520
+ const url = new URL(request.url);
1521
+ const logTpl = "{method} {path}: {status}";
1522
+ const values = {
1523
+ method: request.method,
1524
+ path: `${url.pathname}${url.search}`,
1525
+ url: request.url,
1526
+ status: response.status
1527
+ };
1528
+ if (response.status >= 500) logger$2.error(logTpl, values);
1529
+ else if (response.status >= 400) logger$2.warn(logTpl, values);
1530
+ else logger$2.info(logTpl, values);
1531
+ return response;
1532
+ });
1533
+ });
1534
+ }
1535
+ async #fetch(request, { onNotFound, onNotAcceptable, onUnauthorized, contextData, span, tracer }) {
1536
+ onNotFound ??= notFound;
1537
+ onNotAcceptable ??= notAcceptable;
1538
+ onUnauthorized ??= unauthorized;
1539
+ const url = new URL(request.url);
1540
+ const route = this.router.route(url.pathname);
1541
+ if (route == null) return await onNotFound(request);
1542
+ span.updateName(`${request.method} ${route.template}`);
1543
+ let context$1 = this.#createContext(request, contextData);
1544
+ const routeName = route.name.replace(/:.*$/, "");
1545
+ switch (routeName) {
1546
+ case "webfinger": return await handleWebFinger(request, {
1547
+ context: context$1,
1548
+ host: this.origin?.handleHost,
1549
+ actorDispatcher: this.actorCallbacks?.dispatcher,
1550
+ actorHandleMapper: this.actorCallbacks?.handleMapper,
1551
+ actorAliasMapper: this.actorCallbacks?.aliasMapper,
1552
+ onNotFound,
1553
+ tracer
1554
+ });
1555
+ case "nodeInfoJrd": return await handleNodeInfoJrd(request, context$1);
1556
+ case "nodeInfo": return await handleNodeInfo(request, {
1557
+ context: context$1,
1558
+ nodeInfoDispatcher: this.nodeInfoDispatcher
1559
+ });
1560
+ case "actor":
1561
+ context$1 = this.#createContext(request, contextData, { invokedFromActorDispatcher: { identifier: route.values.identifier ?? route.values.handle } });
1562
+ return await handleActor(request, {
1563
+ identifier: route.values.identifier ?? route.values.handle,
1564
+ context: context$1,
1565
+ actorDispatcher: this.actorCallbacks?.dispatcher,
1566
+ authorizePredicate: this.actorCallbacks?.authorizePredicate,
1567
+ onUnauthorized,
1568
+ onNotFound,
1569
+ onNotAcceptable
1570
+ });
1571
+ case "object": {
1572
+ const typeId = route.name.replace(/^object:/, "");
1573
+ const callbacks = this.objectCallbacks[typeId];
1574
+ const cls = this.objectTypeIds[typeId];
1575
+ context$1 = this.#createContext(request, contextData, { invokedFromObjectDispatcher: {
1576
+ cls,
1577
+ values: route.values
1578
+ } });
1579
+ return await handleObject(request, {
1580
+ values: route.values,
1581
+ context: context$1,
1582
+ objectDispatcher: callbacks?.dispatcher,
1583
+ authorizePredicate: callbacks?.authorizePredicate,
1584
+ onUnauthorized,
1585
+ onNotFound,
1586
+ onNotAcceptable
1587
+ });
1588
+ }
1589
+ case "outbox": return await handleCollection(request, {
1590
+ name: "outbox",
1591
+ identifier: route.values.identifier ?? route.values.handle,
1592
+ uriGetter: context$1.getOutboxUri.bind(context$1),
1593
+ context: context$1,
1594
+ collectionCallbacks: this.outboxCallbacks,
1595
+ tracerProvider: this.tracerProvider,
1596
+ onUnauthorized,
1597
+ onNotFound,
1598
+ onNotAcceptable
1599
+ });
1600
+ case "inbox":
1601
+ if (request.method !== "POST") return await handleCollection(request, {
1602
+ name: "inbox",
1603
+ identifier: route.values.identifier ?? route.values.handle,
1604
+ uriGetter: context$1.getInboxUri.bind(context$1),
1605
+ context: context$1,
1606
+ collectionCallbacks: this.inboxCallbacks,
1607
+ tracerProvider: this.tracerProvider,
1608
+ onUnauthorized,
1609
+ onNotFound,
1610
+ onNotAcceptable
1611
+ });
1612
+ context$1 = this.#createContext(request, contextData, { documentLoader: await context$1.getDocumentLoader({ identifier: route.values.identifier ?? route.values.handle }) });
1613
+ case "sharedInbox":
1614
+ if (routeName !== "inbox" && this.sharedInboxKeyDispatcher != null) {
1615
+ const identity = await this.sharedInboxKeyDispatcher(context$1);
1616
+ if (identity != null) context$1 = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity || "handle" in identity ? await context$1.getDocumentLoader(identity) : context$1.getDocumentLoader(identity) });
1617
+ }
1618
+ if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
1619
+ return await handleInbox(request, {
1620
+ recipient: route.values.identifier ?? route.values.handle ?? null,
1621
+ context: context$1,
1622
+ inboxContextFactory: context$1.toInboxContext.bind(context$1),
1623
+ kv: this.kv,
1624
+ kvPrefixes: this.kvPrefixes,
1625
+ queue: this.inboxQueue,
1626
+ actorDispatcher: this.actorCallbacks?.dispatcher,
1627
+ inboxListeners: this.inboxListeners,
1628
+ inboxErrorHandler: this.inboxErrorHandler,
1629
+ onNotFound,
1630
+ signatureTimeWindow: this.signatureTimeWindow,
1631
+ skipSignatureVerification: this.skipSignatureVerification,
1632
+ tracerProvider: this.tracerProvider
1633
+ });
1634
+ case "following": return await handleCollection(request, {
1635
+ name: "following",
1636
+ identifier: route.values.identifier ?? route.values.handle,
1637
+ uriGetter: context$1.getFollowingUri.bind(context$1),
1638
+ context: context$1,
1639
+ collectionCallbacks: this.followingCallbacks,
1640
+ tracerProvider: this.tracerProvider,
1641
+ onUnauthorized,
1642
+ onNotFound,
1643
+ onNotAcceptable
1644
+ });
1645
+ case "followers": {
1646
+ let baseUrl = url.searchParams.get("base-url");
1647
+ if (baseUrl != null) try {
1648
+ baseUrl = `${new URL(baseUrl).origin}/`;
1649
+ } catch {
1650
+ baseUrl = null;
1651
+ }
1652
+ return await handleCollection(request, {
1653
+ name: "followers",
1654
+ identifier: route.values.identifier ?? route.values.handle,
1655
+ uriGetter: baseUrl == null ? context$1.getFollowersUri.bind(context$1) : (identifier) => {
1656
+ const uri = context$1.getFollowersUri(identifier);
1657
+ uri.searchParams.set("base-url", baseUrl);
1658
+ return uri;
1659
+ },
1660
+ context: context$1,
1661
+ filter: baseUrl != null ? new URL(baseUrl) : void 0,
1662
+ filterPredicate: baseUrl != null ? ((i) => (i instanceof URL ? i.href : i.id?.href ?? "").startsWith(baseUrl)) : void 0,
1663
+ collectionCallbacks: this.followersCallbacks,
1664
+ tracerProvider: this.tracerProvider,
1665
+ onUnauthorized,
1666
+ onNotFound,
1667
+ onNotAcceptable
1668
+ });
1669
+ }
1670
+ case "liked": return await handleCollection(request, {
1671
+ name: "liked",
1672
+ identifier: route.values.identifier ?? route.values.handle,
1673
+ uriGetter: context$1.getLikedUri.bind(context$1),
1674
+ context: context$1,
1675
+ collectionCallbacks: this.likedCallbacks,
1676
+ tracerProvider: this.tracerProvider,
1677
+ onUnauthorized,
1678
+ onNotFound,
1679
+ onNotAcceptable
1680
+ });
1681
+ case "featured": return await handleCollection(request, {
1682
+ name: "featured",
1683
+ identifier: route.values.identifier ?? route.values.handle,
1684
+ uriGetter: context$1.getFeaturedUri.bind(context$1),
1685
+ context: context$1,
1686
+ collectionCallbacks: this.featuredCallbacks,
1687
+ tracerProvider: this.tracerProvider,
1688
+ onUnauthorized,
1689
+ onNotFound,
1690
+ onNotAcceptable
1691
+ });
1692
+ case "featuredTags": return await handleCollection(request, {
1693
+ name: "featured tags",
1694
+ identifier: route.values.identifier ?? route.values.handle,
1695
+ uriGetter: context$1.getFeaturedTagsUri.bind(context$1),
1696
+ context: context$1,
1697
+ collectionCallbacks: this.featuredTagsCallbacks,
1698
+ tracerProvider: this.tracerProvider,
1699
+ onUnauthorized,
1700
+ onNotFound,
1701
+ onNotAcceptable
1702
+ });
1703
+ default: {
1704
+ const response = onNotFound(request);
1705
+ return response instanceof Promise ? await response : response;
1706
+ }
1707
+ }
1708
+ }
1709
+ };
1710
+ const FANOUT_THRESHOLD = 5;
1711
+ var ContextImpl = class ContextImpl {
1712
+ url;
1713
+ federation;
1714
+ data;
1715
+ documentLoader;
1716
+ contextLoader;
1717
+ invokedFromActorKeyPairsDispatcher;
1718
+ constructor({ url, federation, data, documentLoader, contextLoader, invokedFromActorKeyPairsDispatcher }) {
1719
+ this.url = url;
1720
+ this.federation = federation;
1721
+ this.data = data;
1722
+ this.documentLoader = documentLoader;
1723
+ this.contextLoader = contextLoader;
1724
+ this.invokedFromActorKeyPairsDispatcher = invokedFromActorKeyPairsDispatcher;
1725
+ }
1726
+ clone(data) {
1727
+ return new ContextImpl({
1728
+ url: this.url,
1729
+ federation: this.federation,
1730
+ data,
1731
+ documentLoader: this.documentLoader,
1732
+ contextLoader: this.contextLoader,
1733
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
1734
+ });
1735
+ }
1736
+ toInboxContext(recipient, activity, activityId, activityType) {
1737
+ return new InboxContextImpl(recipient, activity, activityId, activityType, {
1738
+ url: this.url,
1739
+ federation: this.federation,
1740
+ data: this.data,
1741
+ documentLoader: this.documentLoader,
1742
+ contextLoader: this.contextLoader,
1743
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
1744
+ });
1745
+ }
1746
+ get hostname() {
1747
+ return this.url.hostname;
1748
+ }
1749
+ get host() {
1750
+ return this.url.host;
1751
+ }
1752
+ get origin() {
1753
+ return this.url.origin;
1754
+ }
1755
+ get canonicalOrigin() {
1756
+ return this.federation.origin?.webOrigin ?? this.origin;
1757
+ }
1758
+ get tracerProvider() {
1759
+ return this.federation.tracerProvider;
1760
+ }
1761
+ getNodeInfoUri() {
1762
+ const path = this.federation.router.build("nodeInfo", {});
1763
+ if (path == null) throw new RouterError("No NodeInfo dispatcher registered.");
1764
+ return new URL(path, this.canonicalOrigin);
1765
+ }
1766
+ getActorUri(identifier) {
1767
+ const path = this.federation.router.build("actor", {
1768
+ identifier,
1769
+ handle: identifier
1770
+ });
1771
+ if (path == null) throw new RouterError("No actor dispatcher registered.");
1772
+ return new URL(path, this.canonicalOrigin);
1773
+ }
1774
+ getObjectUri(cls, values) {
1775
+ const callbacks = this.federation.objectCallbacks[cls.typeId.href];
1776
+ if (callbacks == null) throw new RouterError("No object dispatcher registered.");
1777
+ for (const param of callbacks.parameters) if (!(param in values)) throw new TypeError(`Missing parameter: ${param}`);
1778
+ const path = this.federation.router.build(`object:${cls.typeId.href}`, values);
1779
+ if (path == null) throw new RouterError("No object dispatcher registered.");
1780
+ return new URL(path, this.canonicalOrigin);
1781
+ }
1782
+ getOutboxUri(identifier) {
1783
+ const path = this.federation.router.build("outbox", {
1784
+ identifier,
1785
+ handle: identifier
1786
+ });
1787
+ if (path == null) throw new RouterError("No outbox dispatcher registered.");
1788
+ return new URL(path, this.canonicalOrigin);
1789
+ }
1790
+ getInboxUri(identifier) {
1791
+ if (identifier == null) {
1792
+ const path$1 = this.federation.router.build("sharedInbox", {});
1793
+ if (path$1 == null) throw new RouterError("No shared inbox path registered.");
1794
+ return new URL(path$1, this.canonicalOrigin);
1795
+ }
1796
+ const path = this.federation.router.build("inbox", {
1797
+ identifier,
1798
+ handle: identifier
1799
+ });
1800
+ if (path == null) throw new RouterError("No inbox path registered.");
1801
+ return new URL(path, this.canonicalOrigin);
1802
+ }
1803
+ getFollowingUri(identifier) {
1804
+ const path = this.federation.router.build("following", {
1805
+ identifier,
1806
+ handle: identifier
1807
+ });
1808
+ if (path == null) throw new RouterError("No following collection path registered.");
1809
+ return new URL(path, this.canonicalOrigin);
1810
+ }
1811
+ getFollowersUri(identifier) {
1812
+ const path = this.federation.router.build("followers", {
1813
+ identifier,
1814
+ handle: identifier
1815
+ });
1816
+ if (path == null) throw new RouterError("No followers collection path registered.");
1817
+ return new URL(path, this.canonicalOrigin);
1818
+ }
1819
+ getLikedUri(identifier) {
1820
+ const path = this.federation.router.build("liked", {
1821
+ identifier,
1822
+ handle: identifier
1823
+ });
1824
+ if (path == null) throw new RouterError("No liked collection path registered.");
1825
+ return new URL(path, this.canonicalOrigin);
1826
+ }
1827
+ getFeaturedUri(identifier) {
1828
+ const path = this.federation.router.build("featured", {
1829
+ identifier,
1830
+ handle: identifier
1831
+ });
1832
+ if (path == null) throw new RouterError("No featured collection path registered.");
1833
+ return new URL(path, this.canonicalOrigin);
1834
+ }
1835
+ getFeaturedTagsUri(identifier) {
1836
+ const path = this.federation.router.build("featuredTags", {
1837
+ identifier,
1838
+ handle: identifier
1839
+ });
1840
+ if (path == null) throw new RouterError("No featured tags collection path registered.");
1841
+ return new URL(path, this.canonicalOrigin);
1842
+ }
1843
+ parseUri(uri) {
1844
+ if (uri == null) return null;
1845
+ if (uri.origin !== this.origin && uri.origin !== this.canonicalOrigin) return null;
1846
+ const route = this.federation.router.route(uri.pathname);
1847
+ const logger$2 = getLogger(["fedify", "federation"]);
1848
+ if (route == null) return null;
1849
+ else if (route.name === "sharedInbox") return {
1850
+ type: "inbox",
1851
+ identifier: void 0,
1852
+ get handle() {
1853
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1854
+ }
1855
+ };
1856
+ const identifier = "identifier" in route.values ? route.values.identifier : route.values.handle;
1857
+ if (route.name === "actor") return {
1858
+ type: "actor",
1859
+ identifier,
1860
+ get handle() {
1861
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1862
+ return identifier;
1863
+ }
1864
+ };
1865
+ else if (route.name.startsWith("object:")) {
1866
+ const typeId = route.name.replace(/^object:/, "");
1867
+ return {
1868
+ type: "object",
1869
+ class: this.federation.objectTypeIds[typeId],
1870
+ typeId: new URL(typeId),
1871
+ values: route.values
1872
+ };
1873
+ } else if (route.name === "inbox") return {
1874
+ type: "inbox",
1875
+ identifier,
1876
+ get handle() {
1877
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1878
+ return identifier;
1879
+ }
1880
+ };
1881
+ else if (route.name === "outbox") return {
1882
+ type: "outbox",
1883
+ identifier,
1884
+ get handle() {
1885
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1886
+ return identifier;
1887
+ }
1888
+ };
1889
+ else if (route.name === "following") return {
1890
+ type: "following",
1891
+ identifier,
1892
+ get handle() {
1893
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1894
+ return identifier;
1895
+ }
1896
+ };
1897
+ else if (route.name === "followers") return {
1898
+ type: "followers",
1899
+ identifier,
1900
+ get handle() {
1901
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1902
+ return identifier;
1903
+ }
1904
+ };
1905
+ else if (route.name === "liked") return {
1906
+ type: "liked",
1907
+ identifier,
1908
+ get handle() {
1909
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1910
+ return identifier;
1911
+ }
1912
+ };
1913
+ else if (route.name === "featured") return {
1914
+ type: "featured",
1915
+ identifier,
1916
+ get handle() {
1917
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1918
+ return identifier;
1919
+ }
1920
+ };
1921
+ else if (route.name === "featuredTags") return {
1922
+ type: "featuredTags",
1923
+ identifier,
1924
+ get handle() {
1925
+ logger$2.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
1926
+ return identifier;
1927
+ }
1928
+ };
1929
+ return null;
1930
+ }
1931
+ async getActorKeyPairs(identifier) {
1932
+ const logger$2 = getLogger([
1933
+ "fedify",
1934
+ "federation",
1935
+ "actor"
1936
+ ]);
1937
+ if (this.invokedFromActorKeyPairsDispatcher != null) logger$2.warn("Context.getActorKeyPairs({getActorKeyPairsIdentifier}) method is invoked from the actor key pairs dispatcher ({actorKeyPairsDispatcherIdentifier}); this may cause an infinite loop.", {
1938
+ getActorKeyPairsIdentifier: identifier,
1939
+ actorKeyPairsDispatcherIdentifier: this.invokedFromActorKeyPairsDispatcher.identifier
1940
+ });
1941
+ let keyPairs;
1942
+ try {
1943
+ keyPairs = await this.getKeyPairsFromIdentifier(identifier);
1944
+ } catch (_) {
1945
+ logger$2.warn("No actor key pairs dispatcher registered.");
1946
+ return [];
1947
+ }
1948
+ const owner = this.getActorUri(identifier);
1949
+ const result = [];
1950
+ for (const keyPair of keyPairs) {
1951
+ const newPair = {
1952
+ ...keyPair,
1953
+ cryptographicKey: new CryptographicKey({
1954
+ id: keyPair.keyId,
1955
+ owner,
1956
+ publicKey: keyPair.publicKey
1957
+ }),
1958
+ multikey: new Multikey({
1959
+ id: keyPair.keyId,
1960
+ controller: owner,
1961
+ publicKey: keyPair.publicKey
1962
+ })
1963
+ };
1964
+ result.push(newPair);
1965
+ }
1966
+ return result;
1967
+ }
1968
+ async getKeyPairsFromIdentifier(identifier) {
1969
+ const logger$2 = getLogger([
1970
+ "fedify",
1971
+ "federation",
1972
+ "actor"
1973
+ ]);
1974
+ if (this.federation.actorCallbacks?.keyPairsDispatcher == null) throw new Error("No actor key pairs dispatcher registered.");
1975
+ const path = this.federation.router.build("actor", {
1976
+ identifier,
1977
+ handle: identifier
1978
+ });
1979
+ if (path == null) {
1980
+ logger$2.warn("No actor dispatcher registered.");
1981
+ return [];
1982
+ }
1983
+ const actorUri = new URL(path, this.canonicalOrigin);
1984
+ const keyPairs = await this.federation.actorCallbacks?.keyPairsDispatcher(new ContextImpl({
1985
+ ...this,
1986
+ invokedFromActorKeyPairsDispatcher: { identifier }
1987
+ }), identifier);
1988
+ if (keyPairs.length < 1) logger$2.warn("No key pairs found for actor {identifier}.", { identifier });
1989
+ let i = 0;
1990
+ const result = [];
1991
+ for (const keyPair of keyPairs) {
1992
+ result.push({
1993
+ ...keyPair,
1994
+ keyId: new URL(i == 0 ? `#main-key` : `#key-${i + 1}`, actorUri)
1995
+ });
1996
+ i++;
1997
+ }
1998
+ return result;
1999
+ }
2000
+ async getRsaKeyPairFromIdentifier(identifier) {
2001
+ const keyPairs = await this.getKeyPairsFromIdentifier(identifier);
2002
+ for (const keyPair of keyPairs) {
2003
+ const { privateKey } = keyPair;
2004
+ if (privateKey.algorithm.name === "RSASSA-PKCS1-v1_5" && privateKey.algorithm.hash.name === "SHA-256") return keyPair;
2005
+ }
2006
+ getLogger([
2007
+ "fedify",
2008
+ "federation",
2009
+ "actor"
2010
+ ]).warn("No RSA-PKCS#1-v1.5 SHA-256 key found for actor {identifier}.", { identifier });
2011
+ return null;
2012
+ }
2013
+ getDocumentLoader(identity) {
2014
+ if ("identifier" in identity || "username" in identity || "handle" in identity) {
2015
+ let identifierPromise;
2016
+ if ("username" in identity || "handle" in identity) {
2017
+ let username;
2018
+ if ("username" in identity) username = identity.username;
2019
+ else {
2020
+ username = identity.handle;
2021
+ getLogger([
2022
+ "fedify",
2023
+ "runtime",
2024
+ "docloader"
2025
+ ]).warn("The \"handle\" property is deprecated; use \"identifier\" or \"username\" instead.", { identity });
2026
+ }
2027
+ const mapper = this.federation.actorCallbacks?.handleMapper;
2028
+ if (mapper == null) identifierPromise = Promise.resolve(username);
2029
+ else {
2030
+ const identifier = mapper(this, username);
2031
+ identifierPromise = identifier instanceof Promise ? identifier : Promise.resolve(identifier);
2032
+ }
2033
+ } else identifierPromise = Promise.resolve(identity.identifier);
2034
+ return identifierPromise.then((identifier) => {
2035
+ if (identifier == null) return this.documentLoader;
2036
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
2037
+ });
2038
+ }
2039
+ return this.federation.authenticatedDocumentLoaderFactory(identity);
2040
+ }
2041
+ lookupObject(identifier, options = {}) {
2042
+ return lookupObject(identifier, {
2043
+ ...options,
2044
+ documentLoader: options.documentLoader ?? this.documentLoader,
2045
+ contextLoader: options.contextLoader ?? this.contextLoader,
2046
+ userAgent: options.userAgent ?? this.federation.userAgent,
2047
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
2048
+ allowPrivateAddress: this.federation.allowPrivateAddress
2049
+ });
2050
+ }
2051
+ traverseCollection(collection, options = {}) {
2052
+ return traverseCollection(collection, {
2053
+ ...options,
2054
+ documentLoader: options.documentLoader ?? this.documentLoader,
2055
+ contextLoader: options.contextLoader ?? this.contextLoader
2056
+ });
2057
+ }
2058
+ lookupNodeInfo(url, options = {}) {
2059
+ return options.parse === "none" ? getNodeInfo(url, {
2060
+ parse: "none",
2061
+ direct: options.direct,
2062
+ userAgent: options?.userAgent ?? this.federation.userAgent
2063
+ }) : getNodeInfo(url, {
2064
+ parse: options.parse,
2065
+ direct: options.direct,
2066
+ userAgent: options?.userAgent ?? this.federation.userAgent
2067
+ });
2068
+ }
2069
+ lookupWebFinger(resource, options = {}) {
2070
+ return lookupWebFinger(resource, {
2071
+ ...options,
2072
+ userAgent: options.userAgent ?? this.federation.userAgent,
2073
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
2074
+ allowPrivateAddress: this.federation.allowPrivateAddress
2075
+ });
2076
+ }
2077
+ sendActivity(sender, recipients, activity, options = {}) {
2078
+ return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
2079
+ kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
2080
+ attributes: {
2081
+ "activitypub.activity.type": getTypeId(activity).href,
2082
+ "activitypub.activity.to": activity.toIds.map((to) => to.href),
2083
+ "activitypub.activity.cc": activity.toIds.map((cc) => cc.href),
2084
+ "activitypub.activity.bto": activity.btoIds.map((bto) => bto.href),
2085
+ "activitypub.activity.bcc": activity.toIds.map((bcc) => bcc.href)
2086
+ }
2087
+ }, async (span) => {
2088
+ try {
2089
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
2090
+ await this.sendActivityInternal(sender, recipients, activity, options, span);
2091
+ } catch (e) {
2092
+ span.setStatus({
2093
+ code: SpanStatusCode.ERROR,
2094
+ message: String(e)
2095
+ });
2096
+ throw e;
2097
+ } finally {
2098
+ span.end();
2099
+ }
2100
+ });
2101
+ }
2102
+ async sendActivityInternal(sender, recipients, activity, options, span) {
2103
+ const logger$2 = getLogger([
2104
+ "fedify",
2105
+ "federation",
2106
+ "outbox"
2107
+ ]);
2108
+ let keys;
2109
+ let identifier = null;
2110
+ if ("identifier" in sender || "username" in sender || "handle" in sender) {
2111
+ if ("identifier" in sender) identifier = sender.identifier;
2112
+ else {
2113
+ let username;
2114
+ if ("username" in sender) username = sender.username;
2115
+ else {
2116
+ username = sender.handle;
2117
+ logger$2.warn("The \"handle\" property for the sender parameter is deprecated; use \"identifier\" or \"username\" instead.", { sender });
2118
+ }
2119
+ if (this.federation.actorCallbacks?.handleMapper == null) identifier = username;
2120
+ else {
2121
+ const mapped = await this.federation.actorCallbacks.handleMapper(this, username);
2122
+ if (mapped == null) throw new Error(`No actor found for the given username ${JSON.stringify(username)}.`);
2123
+ identifier = mapped;
2124
+ }
2125
+ }
2126
+ span.setAttribute("fedify.actor.identifier", identifier);
2127
+ keys = await this.getKeyPairsFromIdentifier(identifier);
2128
+ if (keys.length < 1) throw new Error(`No key pair found for actor ${JSON.stringify(identifier)}.`);
2129
+ } else if (Array.isArray(sender)) {
2130
+ if (sender.length < 1) throw new Error("The sender's key pairs are empty.");
2131
+ keys = sender;
2132
+ } else keys = [sender];
2133
+ if (keys.length < 1) throw new TypeError("The sender's keys must not be empty.");
2134
+ for (const { privateKey } of keys) validateCryptoKey(privateKey, "private");
2135
+ const opts = { context: this };
2136
+ let expandedRecipients;
2137
+ if (Array.isArray(recipients)) expandedRecipients = recipients;
2138
+ else if (recipients === "followers") {
2139
+ if (identifier == null) throw new Error("If recipients is \"followers\", sender must be an actor identifier or username.");
2140
+ expandedRecipients = [];
2141
+ for await (const recipient of this.getFollowers(identifier)) expandedRecipients.push(recipient);
2142
+ if (options.syncCollection) {
2143
+ const collectionId = this.federation.router.build("followers", {
2144
+ identifier,
2145
+ handle: identifier
2146
+ });
2147
+ opts.collectionSync = collectionId == null ? void 0 : new URL(collectionId, this.canonicalOrigin).href;
2148
+ }
2149
+ } else expandedRecipients = [recipients];
2150
+ span.setAttribute("activitypub.inboxes", expandedRecipients.length);
2151
+ for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
2152
+ span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
2153
+ if (activity.actorId == null) {
2154
+ logger$2.error("Activity {activityId} to send does not have an actor.", {
2155
+ activity,
2156
+ activityId: activity?.id?.href
2157
+ });
2158
+ throw new TypeError("The activity to send must have at least one actor property.");
2159
+ }
2160
+ const inboxes = extractInboxes({
2161
+ recipients: expandedRecipients,
2162
+ preferSharedInbox: options.preferSharedInbox,
2163
+ excludeBaseUris: options.excludeBaseUris
2164
+ });
2165
+ logger$2.debug("Sending activity {activityId} to inboxes:\n{inboxes}", {
2166
+ inboxes: globalThis.Object.keys(inboxes),
2167
+ activityId: activity.id?.href,
2168
+ activity
2169
+ });
2170
+ if (this.federation.fanoutQueue == null || options.immediate || options.fanout === "skip" || (options.fanout ?? "auto") === "auto" && globalThis.Object.keys(inboxes).length < FANOUT_THRESHOLD) {
2171
+ await this.federation.sendActivity(keys, inboxes, activity, opts);
2172
+ return;
2173
+ }
2174
+ const keyJwkPairs = await Promise.all(keys.map(async ({ keyId, privateKey }) => ({
2175
+ keyId: keyId.href,
2176
+ privateKey: await exportJwk(privateKey)
2177
+ })));
2178
+ const carrier = {};
2179
+ propagation.inject(context.active(), carrier);
2180
+ const message = {
2181
+ type: "fanout",
2182
+ id: crypto.randomUUID(),
2183
+ baseUrl: this.origin,
2184
+ keys: keyJwkPairs,
2185
+ inboxes: globalThis.Object.fromEntries(globalThis.Object.entries(inboxes).map(([k, { actorIds, sharedInbox }]) => [k, {
2186
+ actorIds: [...actorIds],
2187
+ sharedInbox
2188
+ }])),
2189
+ activity: await activity.toJsonLd({
2190
+ format: "compact",
2191
+ contextLoader: this.contextLoader
2192
+ }),
2193
+ activityId: activity.id?.href,
2194
+ activityType: getTypeId(activity).href,
2195
+ collectionSync: opts.collectionSync,
2196
+ traceContext: carrier
2197
+ };
2198
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
2199
+ this.federation.fanoutQueue.enqueue(message);
2200
+ }
2201
+ async *getFollowers(identifier) {
2202
+ if (this.federation.followersCallbacks == null) throw new Error("No followers collection dispatcher registered.");
2203
+ const result = await this.federation.followersCallbacks.dispatcher(this, identifier, null);
2204
+ if (result != null) {
2205
+ for (const recipient of result.items) yield recipient;
2206
+ return;
2207
+ }
2208
+ if (this.federation.followersCallbacks.firstCursor == null) throw new Error("No first cursor dispatcher registered for followers collection.");
2209
+ let cursor = await this.federation.followersCallbacks.firstCursor(this, identifier);
2210
+ if (cursor != null) getLogger([
2211
+ "fedify",
2212
+ "federation",
2213
+ "outbox"
2214
+ ]).warn("Since the followers collection dispatcher returned null for no cursor (i.e., one-shot dispatcher), the pagination is used to fetch \"followers\". However, it is recommended to implement the one-shot dispatcher for better performance.", { identifier });
2215
+ while (cursor != null) {
2216
+ const result$1 = await this.federation.followersCallbacks.dispatcher(this, identifier, cursor);
2217
+ if (result$1 == null) break;
2218
+ for (const recipient of result$1.items) yield recipient;
2219
+ cursor = result$1.nextCursor ?? null;
2220
+ }
2221
+ }
2222
+ routeActivity(recipient, activity, options = {}) {
2223
+ return (this.tracerProvider ?? this.tracerProvider).getTracer(name, version).startActiveSpan("activitypub.inbox", {
2224
+ kind: this.federation.inboxQueue == null || options.immediate ? SpanKind.INTERNAL : SpanKind.PRODUCER,
2225
+ attributes: { "activitypub.activity.type": getTypeId(activity).href }
2226
+ }, async (span) => {
2227
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
2228
+ if (activity.toIds.length > 0) span.setAttribute("activitypub.activity.to", activity.toIds.map((to) => to.href));
2229
+ if (activity.ccIds.length > 0) span.setAttribute("activitypub.activity.cc", activity.ccIds.map((cc) => cc.href));
2230
+ if (activity.btoIds.length > 0) span.setAttribute("activitypub.activity.bto", activity.btoIds.map((bto) => bto.href));
2231
+ if (activity.bccIds.length > 0) span.setAttribute("activitypub.activity.bcc", activity.bccIds.map((bcc) => bcc.href));
2232
+ try {
2233
+ const ok = await this.routeActivityInternal(recipient, activity, options, span);
2234
+ if (ok) {
2235
+ span.setAttribute("activitypub.shared_inbox", recipient == null);
2236
+ if (recipient != null) span.setAttribute("fedify.inbox.recipient", recipient);
2237
+ } else span.setStatus({ code: SpanStatusCode.ERROR });
2238
+ return ok;
2239
+ } catch (e) {
2240
+ span.setStatus({
2241
+ code: SpanStatusCode.ERROR,
2242
+ message: String(e)
2243
+ });
2244
+ throw e;
2245
+ } finally {
2246
+ span.end();
2247
+ }
2248
+ });
2249
+ }
2250
+ async routeActivityInternal(recipient, activity, options = {}, span) {
2251
+ const logger$2 = getLogger([
2252
+ "fedify",
2253
+ "federation",
2254
+ "inbox"
2255
+ ]);
2256
+ const contextLoader = options.contextLoader ?? this.contextLoader;
2257
+ const json = await activity.toJsonLd({ contextLoader });
2258
+ const keyCache = new KvKeyCache(this.federation.kv, this.federation.kvPrefixes.publicKey, this);
2259
+ if (await verifyObject(Activity, json, {
2260
+ contextLoader,
2261
+ documentLoader: options.documentLoader ?? this.documentLoader,
2262
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
2263
+ keyCache
2264
+ }) == null) {
2265
+ logger$2.debug("Object Integrity Proofs are not verified.", {
2266
+ recipient,
2267
+ activity: json
2268
+ });
2269
+ if (activity.id == null) {
2270
+ logger$2.debug("Activity is missing an ID; unable to fetch.", {
2271
+ recipient,
2272
+ activity: json
2273
+ });
2274
+ return false;
2275
+ }
2276
+ const fetched = await this.lookupObject(activity.id, options);
2277
+ if (fetched == null) {
2278
+ logger$2.debug("Failed to fetch the remote activity object {activityId}.", {
2279
+ recipient,
2280
+ activity: json,
2281
+ activityId: activity.id.href
2282
+ });
2283
+ return false;
2284
+ } else if (!(fetched instanceof Activity)) {
2285
+ logger$2.debug("Fetched object is not an Activity.", {
2286
+ recipient,
2287
+ activity: await fetched.toJsonLd({ contextLoader })
2288
+ });
2289
+ return false;
2290
+ } else if (fetched.id?.href !== activity.id.href) {
2291
+ logger$2.debug("Fetched activity object has a different ID; failed to verify.", {
2292
+ recipient,
2293
+ activity: await fetched.toJsonLd({ contextLoader })
2294
+ });
2295
+ return false;
2296
+ } else if (fetched.actorIds.length < 1) {
2297
+ logger$2.debug("Fetched activity object is missing an actor; unable to verify.", {
2298
+ recipient,
2299
+ activity: await fetched.toJsonLd({ contextLoader })
2300
+ });
2301
+ return false;
2302
+ }
2303
+ const activityId = fetched.id;
2304
+ if (!fetched.actorIds.every((actor) => actor.origin === activityId.origin)) {
2305
+ logger$2.debug("Fetched activity object has actors from different origins; unable to verify.", {
2306
+ recipient,
2307
+ activity: await fetched.toJsonLd({ contextLoader })
2308
+ });
2309
+ return false;
2310
+ }
2311
+ logger$2.debug("Successfully fetched the remote activity object {activityId}; ignore the original activity and use the fetched one, which is trustworthy.");
2312
+ activity = fetched;
2313
+ } else logger$2.debug("Object Integrity Proofs are verified.", {
2314
+ recipient,
2315
+ activity: json
2316
+ });
2317
+ const routeResult = await routeActivity({
2318
+ context: this,
2319
+ json,
2320
+ activity,
2321
+ recipient,
2322
+ inboxListeners: this.federation.inboxListeners,
2323
+ inboxContextFactory: this.toInboxContext.bind(this),
2324
+ inboxErrorHandler: this.federation.inboxErrorHandler,
2325
+ kv: this.federation.kv,
2326
+ kvPrefixes: this.federation.kvPrefixes,
2327
+ queue: this.federation.inboxQueue,
2328
+ span,
2329
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
2330
+ });
2331
+ return routeResult === "alreadyProcessed" || routeResult === "enqueued" || routeResult === "unsupportedActivity" || routeResult === "success";
2332
+ }
2333
+ };
2334
+ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
2335
+ #invokedFromActorDispatcher;
2336
+ #invokedFromObjectDispatcher;
2337
+ request;
2338
+ url;
2339
+ constructor(options) {
2340
+ super(options);
2341
+ this.#invokedFromActorDispatcher = options.invokedFromActorDispatcher;
2342
+ this.#invokedFromObjectDispatcher = options.invokedFromObjectDispatcher;
2343
+ this.request = options.request;
2344
+ this.url = options.url;
2345
+ }
2346
+ clone(data) {
2347
+ return new RequestContextImpl({
2348
+ url: this.url,
2349
+ federation: this.federation,
2350
+ data,
2351
+ documentLoader: this.documentLoader,
2352
+ contextLoader: this.contextLoader,
2353
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher,
2354
+ invokedFromActorDispatcher: this.#invokedFromActorDispatcher,
2355
+ invokedFromObjectDispatcher: this.#invokedFromObjectDispatcher,
2356
+ request: this.request
2357
+ });
2358
+ }
2359
+ async getActor(identifier) {
2360
+ if (this.federation.actorCallbacks == null || this.federation.actorCallbacks.dispatcher == null) throw new Error("No actor dispatcher registered.");
2361
+ if (this.#invokedFromActorDispatcher != null) getLogger([
2362
+ "fedify",
2363
+ "federation",
2364
+ "actor"
2365
+ ]).warn("RequestContext.getActor({getActorIdentifier}) is invoked from the actor dispatcher ({actorDispatcherIdentifier}); this may cause an infinite loop.", {
2366
+ getActorIdentifier: identifier,
2367
+ actorDispatcherIdentifier: this.#invokedFromActorDispatcher.identifier
2368
+ });
2369
+ return await this.federation.actorCallbacks.dispatcher(new RequestContextImpl({
2370
+ ...this,
2371
+ invokedFromActorDispatcher: { identifier }
2372
+ }), identifier);
2373
+ }
2374
+ async getObject(cls, values) {
2375
+ const callbacks = this.federation.objectCallbacks[cls.typeId.href];
2376
+ if (callbacks == null) throw new Error("No object dispatcher registered.");
2377
+ for (const param of callbacks.parameters) if (!(param in values)) throw new TypeError(`Missing parameter: ${param}`);
2378
+ if (this.#invokedFromObjectDispatcher != null) getLogger(["fedify", "federation"]).warn("RequestContext.getObject({getObjectClass}, {getObjectValues}) is invoked from the object dispatcher ({actorDispatcherClass}, {actorDispatcherValues}); this may cause an infinite loop.", {
2379
+ getObjectClass: cls.name,
2380
+ getObjectValues: values,
2381
+ actorDispatcherClass: this.#invokedFromObjectDispatcher.cls.name,
2382
+ actorDispatcherValues: this.#invokedFromObjectDispatcher.values
2383
+ });
2384
+ return await callbacks.dispatcher(new RequestContextImpl({
2385
+ ...this,
2386
+ invokedFromObjectDispatcher: {
2387
+ cls,
2388
+ values
2389
+ }
2390
+ }), values);
2391
+ }
2392
+ #signedKey = void 0;
2393
+ async getSignedKey(options = {}) {
2394
+ if (this.#signedKey != null) return this.#signedKey;
2395
+ return this.#signedKey = await verifyRequest(this.request, {
2396
+ ...this,
2397
+ contextLoader: options.contextLoader ?? this.contextLoader,
2398
+ documentLoader: options.documentLoader ?? this.documentLoader,
2399
+ timeWindow: this.federation.signatureTimeWindow,
2400
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
2401
+ });
2402
+ }
2403
+ #signedKeyOwner = void 0;
2404
+ async getSignedKeyOwner(options = {}) {
2405
+ if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
2406
+ const key = await this.getSignedKey(options);
2407
+ if (key == null) return this.#signedKeyOwner = null;
2408
+ return this.#signedKeyOwner = await getKeyOwner(key, {
2409
+ contextLoader: options.contextLoader ?? this.contextLoader,
2410
+ documentLoader: options.documentLoader ?? this.documentLoader,
2411
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
2412
+ });
2413
+ }
2414
+ };
2415
+ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
2416
+ recipient;
2417
+ activity;
2418
+ activityId;
2419
+ activityType;
2420
+ constructor(recipient, activity, activityId, activityType, options) {
2421
+ super(options);
2422
+ this.recipient = recipient;
2423
+ this.activity = activity;
2424
+ this.activityId = activityId;
2425
+ this.activityType = activityType;
2426
+ }
2427
+ clone(data) {
2428
+ return new InboxContextImpl(this.recipient, this.activity, this.activityId, this.activityType, {
2429
+ url: this.url,
2430
+ federation: this.federation,
2431
+ data,
2432
+ documentLoader: this.documentLoader,
2433
+ contextLoader: this.contextLoader,
2434
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
2435
+ });
2436
+ }
2437
+ forwardActivity(forwarder, recipients, options) {
2438
+ return this.tracerProvider.getTracer(name, version).startActiveSpan("activitypub.outbox", {
2439
+ kind: this.federation.outboxQueue == null || options?.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
2440
+ attributes: { "activitypub.activity.type": this.activityType }
2441
+ }, async (span) => {
2442
+ try {
2443
+ if (this.activityId != null) span.setAttribute("activitypub.activity.id", this.activityId);
2444
+ await this.forwardActivityInternal(forwarder, recipients, options);
2445
+ } catch (e) {
2446
+ span.setStatus({
2447
+ code: SpanStatusCode.ERROR,
2448
+ message: String(e)
2449
+ });
2450
+ throw e;
2451
+ } finally {
2452
+ span.end();
2453
+ }
2454
+ });
2455
+ }
2456
+ async forwardActivityInternal(forwarder, recipients, options) {
2457
+ const logger$2 = getLogger([
2458
+ "fedify",
2459
+ "federation",
2460
+ "inbox"
2461
+ ]);
2462
+ let keys;
2463
+ let identifier = null;
2464
+ if ("identifier" in forwarder || "username" in forwarder || "handle" in forwarder) {
2465
+ if ("identifier" in forwarder) identifier = forwarder.identifier;
2466
+ else {
2467
+ let username;
2468
+ if ("username" in forwarder) username = forwarder.username;
2469
+ else {
2470
+ username = forwarder.handle;
2471
+ logger$2.warn("The \"handle\" property for the forwarder parameter is deprecated; use \"identifier\" or \"username\" instead.", { forwarder });
2472
+ }
2473
+ if (this.federation.actorCallbacks?.handleMapper == null) identifier = username;
2474
+ else {
2475
+ const mapped = await this.federation.actorCallbacks.handleMapper(this, username);
2476
+ if (mapped == null) throw new Error(`No actor found for the given username ${JSON.stringify(username)}.`);
2477
+ identifier = mapped;
2478
+ }
2479
+ }
2480
+ keys = await this.getKeyPairsFromIdentifier(identifier);
2481
+ if (keys.length < 1) throw new Error(`No key pair found for actor ${JSON.stringify(identifier)}.`);
2482
+ } else if (Array.isArray(forwarder)) {
2483
+ if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
2484
+ keys = forwarder;
2485
+ } else keys = [forwarder];
2486
+ if (!hasSignature(this.activity)) {
2487
+ let hasProof;
2488
+ try {
2489
+ hasProof = await (await Activity.fromJsonLd(this.activity, this)).getProof() != null;
2490
+ } catch {
2491
+ hasProof = false;
2492
+ }
2493
+ if (!hasProof) {
2494
+ if (options?.skipIfUnsigned) return;
2495
+ logger$2.warn("The received activity {activityId} is not signed; even if it is forwarded to other servers as is, it may not be accepted by them due to the lack of a signature/proof.");
2496
+ }
2497
+ }
2498
+ if (recipients === "followers") {
2499
+ if (identifier == null) throw new Error("If recipients is \"followers\", forwarder must be an actor identifier or username.");
2500
+ const followers = [];
2501
+ for await (const recipient of this.getFollowers(identifier)) followers.push(recipient);
2502
+ recipients = followers;
2503
+ }
2504
+ const inboxes = extractInboxes({
2505
+ recipients: Array.isArray(recipients) ? recipients : [recipients],
2506
+ preferSharedInbox: options?.preferSharedInbox,
2507
+ excludeBaseUris: options?.excludeBaseUris
2508
+ });
2509
+ logger$2.debug("Forwarding activity {activityId} to inboxes:\n{inboxes}", {
2510
+ inboxes: globalThis.Object.keys(inboxes),
2511
+ activityId: this.activityId,
2512
+ activity: this.activity
2513
+ });
2514
+ if (options?.immediate || this.federation.outboxQueue == null) {
2515
+ if (options?.immediate) logger$2.debug("Forwarding activity immediately without queue since immediate option is set.");
2516
+ else logger$2.debug("Forwarding activity immediately without queue since queue is not set.");
2517
+ const promises = [];
2518
+ for (const inbox in inboxes) promises.push(sendActivity({
2519
+ keys,
2520
+ activity: this.activity,
2521
+ activityId: this.activityId,
2522
+ activityType: this.activityType,
2523
+ inbox: new URL(inbox),
2524
+ sharedInbox: inboxes[inbox].sharedInbox,
2525
+ tracerProvider: this.tracerProvider,
2526
+ specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec)
2527
+ }));
2528
+ await Promise.all(promises);
2529
+ return;
2530
+ }
2531
+ logger$2.debug("Enqueuing activity {activityId} to forward later.", {
2532
+ activityId: this.activityId,
2533
+ activity: this.activity
2534
+ });
2535
+ const keyJwkPairs = [];
2536
+ for (const { keyId, privateKey } of keys) {
2537
+ const privateKeyJwk = await exportJwk(privateKey);
2538
+ keyJwkPairs.push({
2539
+ keyId: keyId.href,
2540
+ privateKey: privateKeyJwk
2541
+ });
2542
+ }
2543
+ const carrier = {};
2544
+ propagation.inject(context.active(), carrier);
2545
+ const messages = [];
2546
+ for (const inbox in inboxes) {
2547
+ const message = {
2548
+ type: "outbox",
2549
+ id: crypto.randomUUID(),
2550
+ baseUrl: this.origin,
2551
+ keys: keyJwkPairs,
2552
+ activity: this.activity,
2553
+ activityId: this.activityId,
2554
+ activityType: this.activityType,
2555
+ inbox,
2556
+ sharedInbox: inboxes[inbox].sharedInbox,
2557
+ started: (/* @__PURE__ */ new Date()).toISOString(),
2558
+ attempt: 0,
2559
+ headers: {},
2560
+ traceContext: carrier
2561
+ };
2562
+ messages.push(message);
2563
+ }
2564
+ const { outboxQueue } = this.federation;
2565
+ if (outboxQueue.enqueueMany == null) {
2566
+ const promises = messages.map((m) => outboxQueue.enqueue(m));
2567
+ const errors = (await Promise.allSettled(promises)).filter((r) => r.status === "rejected").map((r) => r.reason);
2568
+ if (errors.length > 0) {
2569
+ logger$2.error("Failed to enqueue activity {activityId} to forward later:\n{errors}", {
2570
+ activityId: this.activityId,
2571
+ errors
2572
+ });
2573
+ if (errors.length > 1) throw new AggregateError(errors, `Failed to enqueue activity ${this.activityId} to forward later.`);
2574
+ throw errors[0];
2575
+ }
2576
+ } else try {
2577
+ await outboxQueue.enqueueMany(messages);
2578
+ } catch (error) {
2579
+ logger$2.error("Failed to enqueue activity {activityId} to forward later:\n{error}", {
2580
+ activityId: this.activityId,
2581
+ error
2582
+ });
2583
+ throw error;
2584
+ }
2585
+ }
2586
+ };
2587
+ var KvSpecDeterminer = class {
2588
+ kv;
2589
+ prefix;
2590
+ defaultSpec;
2591
+ constructor(kv, prefix, defaultSpec = "rfc9421") {
2592
+ this.kv = kv;
2593
+ this.prefix = prefix;
2594
+ this.defaultSpec = defaultSpec;
2595
+ }
2596
+ async determineSpec(origin) {
2597
+ return await this.kv.get([...this.prefix, origin]) ?? this.defaultSpec;
2598
+ }
2599
+ async rememberSpec(origin, spec) {
2600
+ await this.kv.set([...this.prefix, origin], spec);
2601
+ }
2602
+ };
2603
+ function notFound(_request) {
2604
+ return new Response("Not Found", { status: 404 });
2605
+ }
2606
+ function notAcceptable(_request) {
2607
+ return new Response("Not Acceptable", {
2608
+ status: 406,
2609
+ headers: { Vary: "Accept, Signature" }
2610
+ });
2611
+ }
2612
+ function unauthorized(_request) {
2613
+ return new Response("Unauthorized", {
2614
+ status: 401,
2615
+ headers: { Vary: "Accept, Signature" }
2616
+ });
2617
+ }
2618
+ /**
2619
+ * Generates or extracts a unique identifier for a request.
2620
+ *
2621
+ * This function first attempts to extract an existing request ID from standard
2622
+ * tracing headers. If none exists, it generates a new one. The ID format is:
2623
+ *
2624
+ * - If from headers, uses the existing ID.
2625
+ * - If generated, uses format `req_` followed by a base36 timestamp and
2626
+ * 6 random chars.
2627
+ *
2628
+ * @param request The incoming HTTP request.
2629
+ * @returns A string identifier unique to this request.
2630
+ */
2631
+ function getRequestId(request) {
2632
+ const traceId = request.headers.get("X-Request-Id") || request.headers.get("X-Correlation-Id") || request.headers.get("Traceparent")?.split("-")[1];
2633
+ if (traceId != null) return traceId;
2634
+ return `req_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
2635
+ }
2636
+
2637
+ //#endregion
2638
+ export { autoIdAssigner as _, createFederation as a, handleCollection as c, respondWithObject as d, respondWithObjectIfAcceptable as f, actorDehydrator as g, handleNodeInfoJrd as h, KvSpecDeterminer as i, handleInbox as l, handleNodeInfo as m, FederationImpl as n, acceptsJsonLd as o, handleWebFinger as p, InboxContextImpl as r, handleActor as s, ContextImpl as t, handleObject as u };