@fedify/fedify 2.0.0-pr.412.1559 → 2.0.0-pr.412.1794

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 (204) hide show
  1. package/README.md +3 -0
  2. package/dist/{actor-Cc6B76eG.js → actor-BXHc5r-q.js} +1 -1
  3. package/dist/actor-Ba9Z1eNJ.cjs +42079 -0
  4. package/dist/{actor-C22bXuuC.d.ts → actor-DqFajh9s.d.ts} +2 -2
  5. package/dist/{actor-CTAuCsWy.js → actor-DzhunPC_.js} +7058 -2722
  6. package/dist/actor-f2NtjyCg.d.cts +128 -0
  7. package/dist/{assert_rejects-DiIiJbZn.js → assert_rejects-Ce45JcFg.js} +1 -1
  8. package/dist/{assert_is_error-BPGph1Jx.js → assert_throws-BNXdRGWP.js} +31 -1
  9. package/dist/{builder-BOEBObR8.js → builder-u7usRsT3.js} +13 -8
  10. package/dist/chunk-DqRYRqnO.cjs +34 -0
  11. package/dist/client-94iWEfQa.d.cts +222 -0
  12. package/dist/{client-DF8anIB5.d.ts → client-BsGzbnV-.d.ts} +3 -75
  13. package/dist/{client-De-z2UnN.js → client-pY7-3icS.js} +3 -22
  14. package/dist/compat/mod.cjs +10 -0
  15. package/dist/compat/mod.d.cts +12 -0
  16. package/dist/compat/mod.d.ts +11 -12
  17. package/dist/compat/mod.js +5 -5
  18. package/dist/compat/transformers.test.js +20 -20
  19. package/dist/compat-DmDDELst.cjs +4 -0
  20. package/dist/compat-nxUqe4Z-.js +4 -0
  21. package/dist/{context-9gCpIkiz.d.ts → context-DG0huGW-.d.ts} +184 -127
  22. package/dist/context-DJ8aSy2Q.d.cts +2312 -0
  23. package/dist/{authdocloader-CLgDGafZ.js → docloader-CrbAy9Oc.js} +17 -8
  24. package/dist/{esm-CHdxdkuH.js → esm-C-Qa1zEM.js} +11 -11
  25. package/dist/federation/builder.test.js +9 -12
  26. package/dist/federation/collection.test.js +7 -9
  27. package/dist/federation/handler.test.js +27 -148
  28. package/dist/federation/idempotency.test.js +201 -0
  29. package/dist/federation/inbox.test.js +4 -6
  30. package/dist/federation/keycache.test.js +3 -4
  31. package/dist/federation/kv.test.js +7 -8
  32. package/dist/federation/middleware.test.js +242 -64
  33. package/dist/federation/mod.cjs +27 -0
  34. package/dist/federation/mod.d.cts +12 -0
  35. package/dist/federation/mod.d.ts +12 -13
  36. package/dist/federation/mod.js +13 -15
  37. package/dist/federation/mq.test.js +8 -10
  38. package/dist/federation/negotiation.test.js +26 -0
  39. package/dist/federation/retry.test.js +4 -5
  40. package/dist/federation/router.test.js +6 -8
  41. package/dist/federation/send.test.js +13 -15
  42. package/dist/federation-CRpdnOMS.cjs +244 -0
  43. package/dist/{federation-CMX7WzeL.js → federation-jcR8-ZxP.js} +3 -3
  44. package/dist/fixtures/media.example.com/avatars/test-avatar.jpg.json +6 -0
  45. package/dist/{http-DqSNLFNY.d.ts → http-BbO0ejuk.d.ts} +2 -2
  46. package/dist/{http-l0TEupZK.js → http-CUVx-vzb.js} +260 -10
  47. package/dist/{http-CcdM1brU.js → http-D2kIm9la.js} +3 -3
  48. package/dist/http-Dofes42e.cjs +1106 -0
  49. package/dist/http-M8k5mKc0.d.cts +253 -0
  50. package/dist/{inbox-B6DZbGNf.js → inbox-HjG5peXY.js} +24 -7
  51. package/dist/{key-CzLv1phF.js → key-CxdLUFS6.js} +3 -2
  52. package/dist/{keycache-B8HdZJSt.js → keycache-bU7COwsh.js} +1 -1
  53. package/dist/{keys-zZwiKkfx.js → keys-DMHs8XNn.js} +2 -1
  54. package/dist/kv-Bxr0Q87_.d.cts +81 -0
  55. package/dist/kv-cache-CGXcDejL.js +122 -0
  56. package/dist/kv-cache-DN9pfMBe.js +94 -0
  57. package/dist/kv-cache-Dkvbn6rg.cjs +134 -0
  58. package/dist/{ld-CBcQdZ6N.js → ld-CIhvSCCr.js} +5 -4
  59. package/dist/lookup-CHkCVZTU.js +260 -0
  60. package/dist/lookup-CfFkONZD.cjs +272 -0
  61. package/dist/{type-SK-d7Tbw.js → lookup-DQRtjvb1.js} +7266 -7087
  62. package/dist/middleware-Bot7EEwV.js +26 -0
  63. package/dist/middleware-CFJgmUMW.cjs +15 -0
  64. package/dist/{middleware-BRgu1IH8.js → middleware-CJlj5Olw.js} +86 -181
  65. package/dist/middleware-CjHl2NHA.js +15 -0
  66. package/dist/middleware-D74TgW2E.cjs +4225 -0
  67. package/dist/{middleware-CxEkcFW0.js → middleware-DMk2Mdn9.js} +117 -127
  68. package/dist/mod-0noXw66R.d.cts +107 -0
  69. package/dist/mod-B-hUPT2N.d.cts +1 -0
  70. package/dist/{mod-Drmz72EK.d.ts → mod-B2iOw50L.d.ts} +3 -3
  71. package/dist/mod-B9M-8jm2.d.ts +109 -0
  72. package/dist/{mod-Cxt4Kpf6.d.ts → mod-BlVovdcy.d.ts} +20 -2
  73. package/dist/{mod-Bqxcp7eN.d.ts → mod-BoHnwOCs.d.ts} +2 -2
  74. package/dist/mod-BxRCHTz-.d.cts +307 -0
  75. package/dist/mod-C2tOeRkN.d.cts +1 -0
  76. package/dist/mod-C58MZ7Wx.d.cts +113 -0
  77. package/dist/mod-DJcZDvjA.d.cts +80 -0
  78. package/dist/mod-DgdBYYa0.d.cts +266 -0
  79. package/dist/{mod-DBzN0aCM.d.ts → mod-Ds0mpFZU.d.ts} +1 -1
  80. package/dist/mod.cjs +137 -0
  81. package/dist/mod.d.cts +16 -0
  82. package/dist/mod.d.ts +16 -17
  83. package/dist/mod.js +19 -21
  84. package/dist/mq-DcJPkXD5.d.cts +140 -0
  85. package/dist/negotiation-C4nFufNk.js +71 -0
  86. package/dist/nodeinfo/client.test.js +30 -111
  87. package/dist/nodeinfo/handler.test.js +25 -26
  88. package/dist/nodeinfo/mod.cjs +10 -0
  89. package/dist/nodeinfo/mod.d.cts +3 -0
  90. package/dist/nodeinfo/mod.d.ts +3 -5
  91. package/dist/nodeinfo/mod.js +6 -7
  92. package/dist/nodeinfo/types.test.js +8 -15
  93. package/dist/nodeinfo-BnthBobC.js +4 -0
  94. package/dist/nodeinfo-CdN0rEnZ.cjs +4 -0
  95. package/dist/owner-B4HbyP8s.d.cts +67 -0
  96. package/dist/{owner-VEIjmR8r.js → owner-Dvh7mBvr.js} +3 -2
  97. package/dist/{owner-CQPnQVtf.d.ts → owner-kQRGVXG1.d.ts} +3 -3
  98. package/dist/proof-D0uThUvD.cjs +674 -0
  99. package/dist/{proof-DoSQAGkE.js → proof-Dgy35fzc.js} +3 -3
  100. package/dist/{proof-tgUlT8hw.js → proof-fqzaMJ4g.js} +11 -10
  101. package/dist/{send-BzS7w-QF.js → send-Drp20VO9.js} +2 -2
  102. package/dist/sig/http.test.js +13 -14
  103. package/dist/sig/key.test.js +9 -11
  104. package/dist/sig/ld.test.js +8 -10
  105. package/dist/sig/mod.cjs +28 -0
  106. package/dist/sig/mod.d.cts +6 -0
  107. package/dist/sig/mod.d.ts +5 -7
  108. package/dist/sig/mod.js +8 -10
  109. package/dist/sig/owner.test.js +10 -12
  110. package/dist/sig/proof.test.js +13 -14
  111. package/dist/sig-C34-oHBl.js +4 -0
  112. package/dist/sig-YYj5tCnr.cjs +4 -0
  113. package/dist/testing/docloader.test.js +6 -8
  114. package/dist/testing/mod.d.ts +387 -224
  115. package/dist/testing/mod.js +2 -3
  116. package/dist/{testing-Z2omCvKy.js → testing-g4UC4liW.js} +1 -2
  117. package/dist/{transformers-Dna8Fg7k.js → transformers-BFT6d7J5.js} +3 -3
  118. package/dist/transformers-CoBS-oFG.cjs +116 -0
  119. package/dist/{types-DgPvoUWN.js → types-BtUjyi5y.js} +8 -169
  120. package/dist/{types-BIgY6c-l.js → types-C2XVl6gj.js} +1 -3
  121. package/dist/types-CWgzGaqk.cjs +315 -0
  122. package/dist/{runtime/authdocloader.test.js → utils/docloader.test.js} +14 -15
  123. package/dist/utils/kv-cache.test.js +209 -0
  124. package/dist/utils/mod.cjs +12 -0
  125. package/dist/utils/mod.d.cts +5 -0
  126. package/dist/utils/mod.d.ts +7 -0
  127. package/dist/utils/mod.js +11 -0
  128. package/dist/utils-D-Va7aXC.js +4 -0
  129. package/dist/utils-DyRU1gdZ.cjs +4 -0
  130. package/dist/vocab/actor.test.js +8 -10
  131. package/dist/vocab/lookup.test.js +257 -9
  132. package/dist/vocab/mod.cjs +86 -0
  133. package/dist/vocab/mod.d.cts +4 -0
  134. package/dist/vocab/mod.d.ts +3 -5
  135. package/dist/vocab/mod.js +6 -7
  136. package/dist/vocab/type.test.js +2 -3
  137. package/dist/vocab/vocab.test.js +438 -15
  138. package/dist/{vocab-SOE1ifCr.d.ts → vocab-BCWe1Ih5.d.ts} +292 -21
  139. package/dist/{vocab-CvD6Vbml.js → vocab-BnR3nIU9.js} +26 -17
  140. package/dist/vocab-CeDBzu-f.d.cts +14903 -0
  141. package/dist/{lookup-Bn_HEC_d.js → vocab-DFaWWYDn.cjs} +108 -139
  142. package/dist/webfinger/handler.test.js +24 -25
  143. package/dist/webfinger/lookup.test.js +7 -9
  144. package/dist/webfinger/mod.cjs +8 -0
  145. package/dist/webfinger/mod.d.cts +2 -0
  146. package/dist/webfinger/mod.d.ts +1 -3
  147. package/dist/webfinger/mod.js +5 -6
  148. package/dist/webfinger-C72Y8lrh.js +4 -0
  149. package/dist/webfinger-vAtLmxOF.cjs +4 -0
  150. package/dist/x/cfworkers.cjs +100 -0
  151. package/dist/x/cfworkers.d.cts +59 -0
  152. package/dist/x/cfworkers.d.ts +2 -2
  153. package/dist/x/cfworkers.js +3 -3
  154. package/dist/x/cfworkers.test.js +6 -8
  155. package/dist/x/hono.cjs +61 -0
  156. package/dist/x/hono.d.cts +53 -0
  157. package/dist/x/hono.d.ts +10 -11
  158. package/dist/x/hono.js +3 -3
  159. package/dist/x/sveltekit.cjs +69 -0
  160. package/dist/x/sveltekit.d.cts +45 -0
  161. package/dist/x/sveltekit.d.ts +10 -11
  162. package/dist/x/sveltekit.js +3 -3
  163. package/package.json +79 -23
  164. package/dist/assert_throws-BOO88avQ.js +0 -39
  165. package/dist/authdocloader-BFVqUbyo.js +0 -52
  166. package/dist/compat-Bb5myD13.js +0 -4
  167. package/dist/docloader-CxWcuWqQ.d.ts +0 -221
  168. package/dist/docloader-DEhniCVa.js +0 -4615
  169. package/dist/key-CUZQgVlf.js +0 -10
  170. package/dist/key-Deb0_wWL.js +0 -10
  171. package/dist/key-DxA6xRtZ.js +0 -260
  172. package/dist/lookup-dtdr2ftf.js +0 -131
  173. package/dist/middleware-BE_geSiJ.js +0 -17
  174. package/dist/middleware-BnU6hzVp.js +0 -26
  175. package/dist/mod-TFoH2Ql8.d.ts +0 -104
  176. package/dist/nodeinfo/semver.test.js +0 -143
  177. package/dist/nodeinfo-CyEbLjHs.js +0 -4
  178. package/dist/runtime/docloader.test.js +0 -522
  179. package/dist/runtime/key.test.js +0 -103
  180. package/dist/runtime/langstr.test.d.ts +0 -3
  181. package/dist/runtime/langstr.test.js +0 -39
  182. package/dist/runtime/mod.d.ts +0 -8
  183. package/dist/runtime/mod.js +0 -13
  184. package/dist/runtime/multibase/multibase.test.d.ts +0 -3
  185. package/dist/runtime/multibase/multibase.test.js +0 -358
  186. package/dist/runtime/url.test.d.ts +0 -3
  187. package/dist/runtime/url.test.js +0 -45
  188. package/dist/runtime-BSkOVUWM.js +0 -4
  189. package/dist/semver-dArNLkR9.js +0 -149
  190. package/dist/sig-BXJO--F9.js +0 -4
  191. package/dist/webfinger-C3GIyXIg.js +0 -4
  192. /package/dist/{assert_not_equals-f3m3epl3.js → assert_not_equals-C80BG-_5.js} +0 -0
  193. /package/dist/{collection-CSzG2j1P.js → collection-BzWsN9pB.js} +0 -0
  194. /package/dist/{denokv-Bv33Xxea.js → denokv-CCssOzMJ.js} +0 -0
  195. /package/dist/{nodeinfo/semver.test.d.ts → federation/idempotency.test.d.ts} +0 -0
  196. /package/dist/{runtime/authdocloader.test.d.ts → federation/negotiation.test.d.ts} +0 -0
  197. /package/dist/{kv-C7sopW2E.d.ts → kv-BKNZ-Tb-.d.ts} +0 -0
  198. /package/dist/{mod-1pDWKvUL.d.ts → mod-CVgZgliM.d.ts} +0 -0
  199. /package/dist/{mod-g0xFzAP9.d.ts → mod-xIj-IT58.d.ts} +0 -0
  200. /package/dist/{mq-CRGm1e_F.d.ts → mq-CUKlBw08.d.ts} +0 -0
  201. /package/dist/{retry-D4GJ670a.js → retry-CfF8Gn4d.js} +0 -0
  202. /package/dist/{std__assert-X-_kMxKM.js → std__assert-DWivtrGR.js} +0 -0
  203. /package/dist/{runtime → utils}/docloader.test.d.ts +0 -0
  204. /package/dist/{runtime/key.test.d.ts → utils/kv-cache.test.d.ts} +0 -0
@@ -0,0 +1,4225 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+ const { URLPattern } = require("urlpattern-polyfill");
4
+
5
+ const require_chunk = require('./chunk-DqRYRqnO.cjs');
6
+ const require_transformers = require('./transformers-CoBS-oFG.cjs');
7
+ const require_lookup = require('./lookup-CfFkONZD.cjs');
8
+ const require_actor = require('./actor-Ba9Z1eNJ.cjs');
9
+ const require_http = require('./http-Dofes42e.cjs');
10
+ const require_proof = require('./proof-D0uThUvD.cjs');
11
+ const require_types = require('./types-CWgzGaqk.cjs');
12
+ const require_kv_cache = require('./kv-cache-Dkvbn6rg.cjs');
13
+ const require_vocab = require('./vocab-DFaWWYDn.cjs');
14
+ const __logtape_logtape = require_chunk.__toESM(require("@logtape/logtape"));
15
+ const __opentelemetry_api = require_chunk.__toESM(require("@opentelemetry/api"));
16
+ const __fedify_vocab_runtime = require_chunk.__toESM(require("@fedify/vocab-runtime"));
17
+ const es_toolkit = require_chunk.__toESM(require("es-toolkit"));
18
+ const uri_template_router = require_chunk.__toESM(require("uri-template-router"));
19
+ const url_template = require_chunk.__toESM(require("url-template"));
20
+ const byte_encodings_hex = require_chunk.__toESM(require("byte-encodings/hex"));
21
+ const __opentelemetry_semantic_conventions = require_chunk.__toESM(require("@opentelemetry/semantic-conventions"));
22
+ const node_url = require_chunk.__toESM(require("node:url"));
23
+
24
+ //#region src/federation/inbox.ts
25
+ var InboxListenerSet = class InboxListenerSet {
26
+ #listeners;
27
+ constructor() {
28
+ this.#listeners = /* @__PURE__ */ new Map();
29
+ }
30
+ clone() {
31
+ const clone = new InboxListenerSet();
32
+ clone.#listeners = new Map(this.#listeners);
33
+ return clone;
34
+ }
35
+ add(type, listener) {
36
+ if (this.#listeners.has(type)) throw new TypeError("Listener already set for this type.");
37
+ this.#listeners.set(type, listener);
38
+ }
39
+ dispatchWithClass(activity) {
40
+ let cls = activity.constructor;
41
+ const inboxListeners = this.#listeners;
42
+ if (inboxListeners == null) return null;
43
+ while (true) {
44
+ if (inboxListeners.has(cls)) break;
45
+ if (cls === require_actor.Activity) return null;
46
+ cls = globalThis.Object.getPrototypeOf(cls);
47
+ }
48
+ const listener = inboxListeners.get(cls);
49
+ return {
50
+ class: cls,
51
+ listener
52
+ };
53
+ }
54
+ dispatch(activity) {
55
+ return this.dispatchWithClass(activity)?.listener ?? null;
56
+ }
57
+ };
58
+ async function routeActivity({ context: ctx, json, activity, recipient, inboxListeners, inboxContextFactory, inboxErrorHandler, kv, kvPrefixes, queue, span, tracerProvider, idempotencyStrategy }) {
59
+ const logger$1 = (0, __logtape_logtape.getLogger)([
60
+ "fedify",
61
+ "federation",
62
+ "inbox"
63
+ ]);
64
+ let cacheKey = null;
65
+ if (activity.id != null) {
66
+ const inboxContext = inboxContextFactory(recipient, json, activity.id?.href, require_actor.getTypeId(activity).href);
67
+ const strategy = idempotencyStrategy ?? "per-inbox";
68
+ let keyString;
69
+ if (typeof strategy === "function") {
70
+ const result = await strategy(inboxContext, activity);
71
+ keyString = result;
72
+ } else switch (strategy) {
73
+ case "global":
74
+ keyString = activity.id.href;
75
+ break;
76
+ case "per-origin":
77
+ keyString = `${ctx.origin}\n${activity.id.href}`;
78
+ break;
79
+ case "per-inbox":
80
+ keyString = `${ctx.origin}\n${activity.id.href}\n${recipient == null ? "sharedInbox" : `inbox\n${recipient}`}`;
81
+ break;
82
+ default: keyString = `${ctx.origin}\n${activity.id.href}`;
83
+ }
84
+ if (keyString != null) cacheKey = [...kvPrefixes.activityIdempotence, keyString];
85
+ }
86
+ if (cacheKey != null) {
87
+ const cached = await kv.get(cacheKey);
88
+ if (cached === true) {
89
+ logger$1.debug("Activity {activityId} has already been processed.", {
90
+ activityId: activity.id?.href,
91
+ activity: json,
92
+ recipient
93
+ });
94
+ span.setStatus({
95
+ code: __opentelemetry_api.SpanStatusCode.UNSET,
96
+ message: `Activity ${activity.id?.href} has already been processed.`
97
+ });
98
+ return "alreadyProcessed";
99
+ }
100
+ }
101
+ if (activity.actorId == null) {
102
+ logger$1.error("Missing actor.", { activity: json });
103
+ span.setStatus({
104
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
105
+ message: "Missing actor."
106
+ });
107
+ return "missingActor";
108
+ }
109
+ span.setAttribute("activitypub.actor.id", activity.actorId.href);
110
+ if (queue != null) {
111
+ const carrier = {};
112
+ __opentelemetry_api.propagation.inject(__opentelemetry_api.context.active(), carrier);
113
+ try {
114
+ await queue.enqueue({
115
+ type: "inbox",
116
+ id: crypto.randomUUID(),
117
+ baseUrl: ctx.origin,
118
+ activity: json,
119
+ identifier: recipient,
120
+ attempt: 0,
121
+ started: (/* @__PURE__ */ new Date()).toISOString(),
122
+ traceContext: carrier
123
+ });
124
+ } catch (error) {
125
+ logger$1.error("Failed to enqueue the incoming activity {activityId}:\n{error}", {
126
+ error,
127
+ activityId: activity.id?.href,
128
+ activity: json,
129
+ recipient
130
+ });
131
+ span.setStatus({
132
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
133
+ message: `Failed to enqueue the incoming activity ${activity.id?.href}.`
134
+ });
135
+ throw error;
136
+ }
137
+ logger$1.info("Activity {activityId} is enqueued.", {
138
+ activityId: activity.id?.href,
139
+ activity: json,
140
+ recipient
141
+ });
142
+ return "enqueued";
143
+ }
144
+ tracerProvider = tracerProvider ?? __opentelemetry_api.trace.getTracerProvider();
145
+ const tracer = tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
146
+ return await tracer.startActiveSpan("activitypub.dispatch_inbox_listener", { kind: __opentelemetry_api.SpanKind.INTERNAL }, async (span$1) => {
147
+ const dispatched = inboxListeners?.dispatchWithClass(activity);
148
+ if (dispatched == null) {
149
+ logger$1.error("Unsupported activity type:\n{activity}", {
150
+ activity: json,
151
+ recipient
152
+ });
153
+ span$1.setStatus({
154
+ code: __opentelemetry_api.SpanStatusCode.UNSET,
155
+ message: `Unsupported activity type: ${require_actor.getTypeId(activity).href}`
156
+ });
157
+ span$1.end();
158
+ return "unsupportedActivity";
159
+ }
160
+ const { class: cls, listener } = dispatched;
161
+ span$1.updateName(`activitypub.dispatch_inbox_listener ${cls.name}`);
162
+ try {
163
+ await listener(inboxContextFactory(recipient, json, activity?.id?.href, require_actor.getTypeId(activity).href), activity);
164
+ } catch (error) {
165
+ try {
166
+ await inboxErrorHandler?.(ctx, error);
167
+ } catch (error$1) {
168
+ logger$1.error("An unexpected error occurred in inbox error handler:\n{error}", {
169
+ error: error$1,
170
+ activityId: activity.id?.href,
171
+ activity: json,
172
+ recipient
173
+ });
174
+ }
175
+ logger$1.error("Failed to process the incoming activity {activityId}:\n{error}", {
176
+ error,
177
+ activityId: activity.id?.href,
178
+ activity: json,
179
+ recipient
180
+ });
181
+ span$1.setStatus({
182
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
183
+ message: String(error)
184
+ });
185
+ span$1.end();
186
+ return "error";
187
+ }
188
+ if (cacheKey != null) await kv.set(cacheKey, true, { ttl: Temporal.Duration.from({ days: 1 }) });
189
+ logger$1.info("Activity {activityId} has been processed.", {
190
+ activityId: activity.id?.href,
191
+ activity: json,
192
+ recipient
193
+ });
194
+ span$1.end();
195
+ return "success";
196
+ });
197
+ }
198
+
199
+ //#endregion
200
+ //#region src/federation/router.ts
201
+ function cloneInnerRouter(router) {
202
+ const clone = new uri_template_router.Router();
203
+ clone.nid = router.nid;
204
+ clone.fsm = (0, es_toolkit.cloneDeep)(router.fsm);
205
+ clone.routeSet = new Set(router.routeSet);
206
+ clone.templateRouteMap = new Map(router.templateRouteMap);
207
+ clone.valueRouteMap = new Map(router.valueRouteMap);
208
+ clone.hierarchy = (0, es_toolkit.cloneDeep)(router.hierarchy);
209
+ return clone;
210
+ }
211
+ /**
212
+ * URL router and constructor based on URI Template
213
+ * ([RFC 6570](https://tools.ietf.org/html/rfc6570)).
214
+ */
215
+ var Router = class Router {
216
+ #router;
217
+ #templates;
218
+ #templateStrings;
219
+ /**
220
+ * Whether to ignore trailing slashes when matching paths.
221
+ * @since 1.6.0
222
+ */
223
+ trailingSlashInsensitive;
224
+ /**
225
+ * Create a new {@link Router}.
226
+ * @param options Options for the router.
227
+ */
228
+ constructor(options = {}) {
229
+ this.#router = new uri_template_router.Router();
230
+ this.#templates = {};
231
+ this.#templateStrings = {};
232
+ this.trailingSlashInsensitive = options.trailingSlashInsensitive ?? false;
233
+ }
234
+ clone() {
235
+ const clone = new Router({ trailingSlashInsensitive: this.trailingSlashInsensitive });
236
+ clone.#router = cloneInnerRouter(this.#router);
237
+ clone.#templates = { ...this.#templates };
238
+ clone.#templateStrings = { ...this.#templateStrings };
239
+ return clone;
240
+ }
241
+ /**
242
+ * Checks if a path name exists in the router.
243
+ * @param name The name of the path.
244
+ * @returns `true` if the path name exists, otherwise `false`.
245
+ */
246
+ has(name) {
247
+ return name in this.#templates;
248
+ }
249
+ /**
250
+ * Adds a new path rule to the router.
251
+ * @param template The path pattern.
252
+ * @param name The name of the path.
253
+ * @returns The names of the variables in the path pattern.
254
+ */
255
+ add(template, name) {
256
+ if (!template.startsWith("/")) throw new RouterError("Path must start with a slash.");
257
+ const rule = this.#router.addTemplate(template, {}, name);
258
+ this.#templates[name] = (0, url_template.parseTemplate)(template);
259
+ this.#templateStrings[name] = template;
260
+ return new Set(rule.variables.map((v) => v.varname));
261
+ }
262
+ /**
263
+ * Resolves a path name and values from a URL, if any match.
264
+ * @param url The URL to resolve.
265
+ * @returns The name of the path and its values, if any match. Otherwise,
266
+ * `null`.
267
+ */
268
+ route(url) {
269
+ let match = this.#router.resolveURI(url);
270
+ if (match == null) {
271
+ if (!this.trailingSlashInsensitive) return null;
272
+ url = url.endsWith("/") ? url.replace(/\/+$/, "") : `${url}/`;
273
+ match = this.#router.resolveURI(url);
274
+ if (match == null) return null;
275
+ }
276
+ return {
277
+ name: match.matchValue,
278
+ template: this.#templateStrings[match.matchValue],
279
+ values: match.params
280
+ };
281
+ }
282
+ /**
283
+ * Constructs a URL/path from a path name and values.
284
+ * @param name The name of the path.
285
+ * @param values The values to expand the path with.
286
+ * @returns The URL/path, if the name exists. Otherwise, `null`.
287
+ */
288
+ build(name, values) {
289
+ if (name in this.#templates) return this.#templates[name].expand(values);
290
+ return null;
291
+ }
292
+ };
293
+ /**
294
+ * An error thrown by the {@link Router}.
295
+ */
296
+ var RouterError = class extends Error {
297
+ /**
298
+ * Create a new {@link RouterError}.
299
+ * @param message The error message.
300
+ */
301
+ constructor(message) {
302
+ super(message);
303
+ this.name = "RouterError";
304
+ }
305
+ };
306
+
307
+ //#endregion
308
+ //#region src/federation/builder.ts
309
+ var FederationBuilderImpl = class {
310
+ router;
311
+ actorCallbacks;
312
+ nodeInfoDispatcher;
313
+ webFingerLinksDispatcher;
314
+ objectCallbacks;
315
+ objectTypeIds;
316
+ inboxPath;
317
+ inboxCallbacks;
318
+ outboxCallbacks;
319
+ followingCallbacks;
320
+ followersCallbacks;
321
+ likedCallbacks;
322
+ featuredCallbacks;
323
+ featuredTagsCallbacks;
324
+ inboxListeners;
325
+ inboxErrorHandler;
326
+ sharedInboxKeyDispatcher;
327
+ idempotencyStrategy;
328
+ collectionTypeIds;
329
+ collectionCallbacks;
330
+ /**
331
+ * Symbol registry for unique identification of unnamed symbols.
332
+ */
333
+ #symbolRegistry = /* @__PURE__ */ new Map();
334
+ constructor() {
335
+ this.router = new Router();
336
+ this.objectCallbacks = {};
337
+ this.objectTypeIds = {};
338
+ this.collectionCallbacks = {};
339
+ this.collectionTypeIds = {};
340
+ }
341
+ async build(options) {
342
+ const { FederationImpl: FederationImpl$1 } = await Promise.resolve().then(() => require("./middleware-CFJgmUMW.cjs"));
343
+ const f = new FederationImpl$1(options);
344
+ const trailingSlashInsensitiveValue = f.router.trailingSlashInsensitive;
345
+ f.router = this.router.clone();
346
+ f.router.trailingSlashInsensitive = trailingSlashInsensitiveValue;
347
+ f._initializeRouter();
348
+ f.actorCallbacks = this.actorCallbacks == null ? void 0 : { ...this.actorCallbacks };
349
+ f.nodeInfoDispatcher = this.nodeInfoDispatcher;
350
+ f.webFingerLinksDispatcher = this.webFingerLinksDispatcher;
351
+ f.objectCallbacks = { ...this.objectCallbacks };
352
+ f.objectTypeIds = { ...this.objectTypeIds };
353
+ f.inboxPath = this.inboxPath;
354
+ f.inboxCallbacks = this.inboxCallbacks == null ? void 0 : { ...this.inboxCallbacks };
355
+ f.outboxCallbacks = this.outboxCallbacks == null ? void 0 : { ...this.outboxCallbacks };
356
+ f.followingCallbacks = this.followingCallbacks == null ? void 0 : { ...this.followingCallbacks };
357
+ f.followersCallbacks = this.followersCallbacks == null ? void 0 : { ...this.followersCallbacks };
358
+ f.likedCallbacks = this.likedCallbacks == null ? void 0 : { ...this.likedCallbacks };
359
+ f.featuredCallbacks = this.featuredCallbacks == null ? void 0 : { ...this.featuredCallbacks };
360
+ f.featuredTagsCallbacks = this.featuredTagsCallbacks == null ? void 0 : { ...this.featuredTagsCallbacks };
361
+ f.inboxListeners = this.inboxListeners?.clone();
362
+ f.inboxErrorHandler = this.inboxErrorHandler;
363
+ f.sharedInboxKeyDispatcher = this.sharedInboxKeyDispatcher;
364
+ f.idempotencyStrategy = this.idempotencyStrategy;
365
+ return f;
366
+ }
367
+ _getTracer() {
368
+ return __opentelemetry_api.trace.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
369
+ }
370
+ setActorDispatcher(path, dispatcher) {
371
+ if (this.router.has("actor")) throw new RouterError("Actor dispatcher already set.");
372
+ const variables = this.router.add(path, "actor");
373
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for actor dispatcher must have one variable: {identifier}");
374
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
375
+ "fedify",
376
+ "federation",
377
+ "actor"
378
+ ]).warn("The {{handle}} variable in the actor dispatcher path is deprecated. Use {{identifier}} instead.");
379
+ const callbacks = { dispatcher: async (context$2, identifier) => {
380
+ const actor = await this._getTracer().startActiveSpan("activitypub.dispatch_actor", {
381
+ kind: __opentelemetry_api.SpanKind.SERVER,
382
+ attributes: { "fedify.actor.identifier": identifier }
383
+ }, async (span) => {
384
+ try {
385
+ const actor$1 = await dispatcher(context$2, identifier);
386
+ span.setAttribute("activitypub.actor.id", (actor$1?.id ?? context$2.getActorUri(identifier)).href);
387
+ if (actor$1 == null) span.setStatus({ code: __opentelemetry_api.SpanStatusCode.ERROR });
388
+ else span.setAttribute("activitypub.actor.type", require_actor.getTypeId(actor$1).href);
389
+ return actor$1;
390
+ } catch (error) {
391
+ span.setStatus({
392
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
393
+ message: String(error)
394
+ });
395
+ throw error;
396
+ } finally {
397
+ span.end();
398
+ }
399
+ });
400
+ if (actor == null) return null;
401
+ const logger$1 = (0, __logtape_logtape.getLogger)([
402
+ "fedify",
403
+ "federation",
404
+ "actor"
405
+ ]);
406
+ if (actor.id == null) logger$1.warn("Actor dispatcher returned an actor without an id property. Set the property with Context.getActorUri(identifier).");
407
+ else if (actor.id.href != context$2.getActorUri(identifier).href) logger$1.warn("Actor dispatcher returned an actor with an id property that does not match the actor URI. Set the property with Context.getActorUri(identifier).");
408
+ if (this.followingCallbacks != null && this.followingCallbacks.dispatcher != null) {
409
+ if (actor.followingId == null) logger$1.warn("You configured a following collection dispatcher, but the actor does not have a following property. Set the property with Context.getFollowingUri(identifier).");
410
+ else if (actor.followingId.href != context$2.getFollowingUri(identifier).href) logger$1.warn("You configured a following collection dispatcher, but the actor's following property does not match the following collection URI. Set the property with Context.getFollowingUri(identifier).");
411
+ }
412
+ if (this.followersCallbacks != null && this.followersCallbacks.dispatcher != null) {
413
+ if (actor.followersId == null) logger$1.warn("You configured a followers collection dispatcher, but the actor does not have a followers property. Set the property with Context.getFollowersUri(identifier).");
414
+ else if (actor.followersId.href != context$2.getFollowersUri(identifier).href) logger$1.warn("You configured a followers collection dispatcher, but the actor's followers property does not match the followers collection URI. Set the property with Context.getFollowersUri(identifier).");
415
+ }
416
+ if (this.outboxCallbacks != null && this.outboxCallbacks.dispatcher != null) {
417
+ if (actor?.outboxId == null) logger$1.warn("You configured an outbox collection dispatcher, but the actor does not have an outbox property. Set the property with Context.getOutboxUri(identifier).");
418
+ else if (actor.outboxId.href != context$2.getOutboxUri(identifier).href) logger$1.warn("You configured an outbox collection dispatcher, but the actor's outbox property does not match the outbox collection URI. Set the property with Context.getOutboxUri(identifier).");
419
+ }
420
+ if (this.likedCallbacks != null && this.likedCallbacks.dispatcher != null) {
421
+ if (actor?.likedId == null) logger$1.warn("You configured a liked collection dispatcher, but the actor does not have a liked property. Set the property with Context.getLikedUri(identifier).");
422
+ else if (actor.likedId.href != context$2.getLikedUri(identifier).href) logger$1.warn("You configured a liked collection dispatcher, but the actor's liked property does not match the liked collection URI. Set the property with Context.getLikedUri(identifier).");
423
+ }
424
+ if (this.featuredCallbacks != null && this.featuredCallbacks.dispatcher != null) {
425
+ if (actor?.featuredId == null) logger$1.warn("You configured a featured collection dispatcher, but the actor does not have a featured property. Set the property with Context.getFeaturedUri(identifier).");
426
+ else if (actor.featuredId.href != context$2.getFeaturedUri(identifier).href) logger$1.warn("You configured a featured collection dispatcher, but the actor's featured property does not match the featured collection URI. Set the property with Context.getFeaturedUri(identifier).");
427
+ }
428
+ if (this.featuredTagsCallbacks != null && this.featuredTagsCallbacks.dispatcher != null) {
429
+ if (actor?.featuredTagsId == null) logger$1.warn("You configured a featured tags collection dispatcher, but the actor does not have a featuredTags property. Set the property with Context.getFeaturedTagsUri(identifier).");
430
+ else if (actor.featuredTagsId.href != context$2.getFeaturedTagsUri(identifier).href) logger$1.warn("You configured a featured tags collection dispatcher, but the actor's featuredTags property does not match the featured tags collection URI. Set the property with Context.getFeaturedTagsUri(identifier).");
431
+ }
432
+ if (this.router.has("inbox")) {
433
+ if (actor.inboxId == null) logger$1.warn("You configured inbox listeners, but the actor does not have an inbox property. Set the property with Context.getInboxUri(identifier).");
434
+ else if (actor.inboxId.href != context$2.getInboxUri(identifier).href) logger$1.warn("You configured inbox listeners, but the actor's inbox property does not match the inbox URI. Set the property with Context.getInboxUri(identifier).");
435
+ if (actor.endpoints == null || actor.endpoints.sharedInbox == null) logger$1.warn("You configured inbox listeners, but the actor does not have a endpoints.sharedInbox property. Set the property with Context.getInboxUri().");
436
+ else if (actor.endpoints.sharedInbox.href != context$2.getInboxUri().href) logger$1.warn("You configured inbox listeners, but the actor's endpoints.sharedInbox property does not match the shared inbox URI. Set the property with Context.getInboxUri().");
437
+ }
438
+ if (callbacks.keyPairsDispatcher != null) {
439
+ if (actor.publicKeyId == null) logger$1.warn("You configured a key pairs dispatcher, but the actor does not have a publicKey property. Set the property with Context.getActorKeyPairs(identifier).");
440
+ if (actor.assertionMethodId == null) logger$1.warn("You configured a key pairs dispatcher, but the actor does not have an assertionMethod property. Set the property with Context.getActorKeyPairs(identifier).");
441
+ }
442
+ return actor;
443
+ } };
444
+ this.actorCallbacks = callbacks;
445
+ const setters = {
446
+ setKeyPairsDispatcher: (dispatcher$1) => {
447
+ callbacks.keyPairsDispatcher = (ctx, identifier) => this._getTracer().startActiveSpan("activitypub.dispatch_actor_key_pairs", {
448
+ kind: __opentelemetry_api.SpanKind.SERVER,
449
+ attributes: {
450
+ "activitypub.actor.id": ctx.getActorUri(identifier).href,
451
+ "fedify.actor.identifier": identifier
452
+ }
453
+ }, async (span) => {
454
+ try {
455
+ return await dispatcher$1(ctx, identifier);
456
+ } catch (e) {
457
+ span.setStatus({
458
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
459
+ message: String(e)
460
+ });
461
+ throw e;
462
+ } finally {
463
+ span.end();
464
+ }
465
+ });
466
+ return setters;
467
+ },
468
+ mapHandle(mapper) {
469
+ callbacks.handleMapper = mapper;
470
+ return setters;
471
+ },
472
+ mapAlias(mapper) {
473
+ callbacks.aliasMapper = mapper;
474
+ return setters;
475
+ },
476
+ authorize(predicate) {
477
+ callbacks.authorizePredicate = predicate;
478
+ return setters;
479
+ }
480
+ };
481
+ return setters;
482
+ }
483
+ setNodeInfoDispatcher(path, dispatcher) {
484
+ if (this.router.has("nodeInfo")) throw new RouterError("NodeInfo dispatcher already set.");
485
+ const variables = this.router.add(path, "nodeInfo");
486
+ if (variables.size !== 0) throw new RouterError("Path for NodeInfo dispatcher must have no variables.");
487
+ this.nodeInfoDispatcher = dispatcher;
488
+ }
489
+ setWebFingerLinksDispatcher(dispatcher) {
490
+ this.webFingerLinksDispatcher = dispatcher;
491
+ }
492
+ setObjectDispatcher(cls, path, dispatcher) {
493
+ const routeName = `object:${cls.typeId.href}`;
494
+ if (this.router.has(routeName)) throw new RouterError(`Object dispatcher for ${cls.name} already set.`);
495
+ const variables = this.router.add(path, routeName);
496
+ if (variables.size < 1) throw new RouterError("Path for object dispatcher must have at least one variable.");
497
+ const callbacks = {
498
+ dispatcher: (ctx, values) => {
499
+ const tracer = this._getTracer();
500
+ return tracer.startActiveSpan("activitypub.dispatch_object", {
501
+ kind: __opentelemetry_api.SpanKind.SERVER,
502
+ attributes: {
503
+ "fedify.object.type": cls.typeId.href,
504
+ ...globalThis.Object.fromEntries(globalThis.Object.entries(values).map(([k, v]) => [`fedify.object.values.${k}`, v]))
505
+ }
506
+ }, async (span) => {
507
+ try {
508
+ const object = await dispatcher(ctx, values);
509
+ span.setAttribute("activitypub.object.id", (object?.id ?? ctx.getObjectUri(cls, values)).href);
510
+ if (object == null) span.setStatus({ code: __opentelemetry_api.SpanStatusCode.ERROR });
511
+ else span.setAttribute("activitypub.object.type", require_actor.getTypeId(object).href);
512
+ return object;
513
+ } catch (e) {
514
+ span.setStatus({
515
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
516
+ message: String(e)
517
+ });
518
+ throw e;
519
+ } finally {
520
+ span.end();
521
+ }
522
+ });
523
+ },
524
+ parameters: variables
525
+ };
526
+ this.objectCallbacks[cls.typeId.href] = callbacks;
527
+ this.objectTypeIds[cls.typeId.href] = cls;
528
+ const setters = { authorize(predicate) {
529
+ callbacks.authorizePredicate = predicate;
530
+ return setters;
531
+ } };
532
+ return setters;
533
+ }
534
+ setInboxDispatcher(path, dispatcher) {
535
+ if (this.inboxCallbacks != null) throw new RouterError("Inbox dispatcher already set.");
536
+ if (this.router.has("inbox")) {
537
+ if (this.inboxPath !== path) throw new RouterError("Inbox dispatcher path must match inbox listener path.");
538
+ } else {
539
+ const variables = this.router.add(path, "inbox");
540
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for inbox dispatcher must have one variable: {identifier}");
541
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
542
+ "fedify",
543
+ "federation",
544
+ "inbox"
545
+ ]).warn("The {{handle}} variable in the inbox dispatcher path is deprecated. Use {{identifier}} instead.");
546
+ this.inboxPath = path;
547
+ }
548
+ const callbacks = { dispatcher };
549
+ this.inboxCallbacks = callbacks;
550
+ const setters = {
551
+ setCounter(counter) {
552
+ callbacks.counter = counter;
553
+ return setters;
554
+ },
555
+ setFirstCursor(cursor) {
556
+ callbacks.firstCursor = cursor;
557
+ return setters;
558
+ },
559
+ setLastCursor(cursor) {
560
+ callbacks.lastCursor = cursor;
561
+ return setters;
562
+ },
563
+ authorize(predicate) {
564
+ callbacks.authorizePredicate = predicate;
565
+ return setters;
566
+ }
567
+ };
568
+ return setters;
569
+ }
570
+ setOutboxDispatcher(path, dispatcher) {
571
+ if (this.router.has("outbox")) throw new RouterError("Outbox dispatcher already set.");
572
+ const variables = this.router.add(path, "outbox");
573
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for outbox dispatcher must have one variable: {identifier}");
574
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
575
+ "fedify",
576
+ "federation",
577
+ "outbox"
578
+ ]).warn("The {{handle}} variable in the outbox dispatcher path is deprecated. Use {{identifier}} instead.");
579
+ const callbacks = { dispatcher };
580
+ this.outboxCallbacks = callbacks;
581
+ const setters = {
582
+ setCounter(counter) {
583
+ callbacks.counter = counter;
584
+ return setters;
585
+ },
586
+ setFirstCursor(cursor) {
587
+ callbacks.firstCursor = cursor;
588
+ return setters;
589
+ },
590
+ setLastCursor(cursor) {
591
+ callbacks.lastCursor = cursor;
592
+ return setters;
593
+ },
594
+ authorize(predicate) {
595
+ callbacks.authorizePredicate = predicate;
596
+ return setters;
597
+ }
598
+ };
599
+ return setters;
600
+ }
601
+ setFollowingDispatcher(path, dispatcher) {
602
+ if (this.router.has("following")) throw new RouterError("Following collection dispatcher already set.");
603
+ const variables = this.router.add(path, "following");
604
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for following collection dispatcher must have one variable: {identifier}");
605
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
606
+ "fedify",
607
+ "federation",
608
+ "collection"
609
+ ]).warn("The {{handle}} variable in the following collection dispatcher path is deprecated. Use {{identifier}} instead.");
610
+ const callbacks = { dispatcher };
611
+ this.followingCallbacks = callbacks;
612
+ const setters = {
613
+ setCounter(counter) {
614
+ callbacks.counter = counter;
615
+ return setters;
616
+ },
617
+ setFirstCursor(cursor) {
618
+ callbacks.firstCursor = cursor;
619
+ return setters;
620
+ },
621
+ setLastCursor(cursor) {
622
+ callbacks.lastCursor = cursor;
623
+ return setters;
624
+ },
625
+ authorize(predicate) {
626
+ callbacks.authorizePredicate = predicate;
627
+ return setters;
628
+ }
629
+ };
630
+ return setters;
631
+ }
632
+ setFollowersDispatcher(path, dispatcher) {
633
+ if (this.router.has("followers")) throw new RouterError("Followers collection dispatcher already set.");
634
+ const variables = this.router.add(path, "followers");
635
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for followers collection dispatcher must have one variable: {identifier}");
636
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
637
+ "fedify",
638
+ "federation",
639
+ "collection"
640
+ ]).warn("The {{handle}} variable in the followers collection dispatcher path is deprecated. Use {{identifier}} instead.");
641
+ const callbacks = { dispatcher };
642
+ this.followersCallbacks = callbacks;
643
+ const setters = {
644
+ setCounter(counter) {
645
+ callbacks.counter = counter;
646
+ return setters;
647
+ },
648
+ setFirstCursor(cursor) {
649
+ callbacks.firstCursor = cursor;
650
+ return setters;
651
+ },
652
+ setLastCursor(cursor) {
653
+ callbacks.lastCursor = cursor;
654
+ return setters;
655
+ },
656
+ authorize(predicate) {
657
+ callbacks.authorizePredicate = predicate;
658
+ return setters;
659
+ }
660
+ };
661
+ return setters;
662
+ }
663
+ setLikedDispatcher(path, dispatcher) {
664
+ if (this.router.has("liked")) throw new RouterError("Liked collection dispatcher already set.");
665
+ const variables = this.router.add(path, "liked");
666
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for liked collection dispatcher must have one variable: {identifier}");
667
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
668
+ "fedify",
669
+ "federation",
670
+ "collection"
671
+ ]).warn("The {{handle}} variable in the liked collection dispatcher path is deprecated. Use {{identifier}} instead.");
672
+ const callbacks = { dispatcher };
673
+ this.likedCallbacks = callbacks;
674
+ const setters = {
675
+ setCounter(counter) {
676
+ callbacks.counter = counter;
677
+ return setters;
678
+ },
679
+ setFirstCursor(cursor) {
680
+ callbacks.firstCursor = cursor;
681
+ return setters;
682
+ },
683
+ setLastCursor(cursor) {
684
+ callbacks.lastCursor = cursor;
685
+ return setters;
686
+ },
687
+ authorize(predicate) {
688
+ callbacks.authorizePredicate = predicate;
689
+ return setters;
690
+ }
691
+ };
692
+ return setters;
693
+ }
694
+ setFeaturedDispatcher(path, dispatcher) {
695
+ if (this.router.has("featured")) throw new RouterError("Featured collection dispatcher already set.");
696
+ const variables = this.router.add(path, "featured");
697
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for featured collection dispatcher must have one variable: {identifier}");
698
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
699
+ "fedify",
700
+ "federation",
701
+ "collection"
702
+ ]).warn("The {{handle}} variable in the featured collection dispatcher path is deprecated. Use {{identifier}} instead.");
703
+ const callbacks = { dispatcher };
704
+ this.featuredCallbacks = callbacks;
705
+ const setters = {
706
+ setCounter(counter) {
707
+ callbacks.counter = counter;
708
+ return setters;
709
+ },
710
+ setFirstCursor(cursor) {
711
+ callbacks.firstCursor = cursor;
712
+ return setters;
713
+ },
714
+ setLastCursor(cursor) {
715
+ callbacks.lastCursor = cursor;
716
+ return setters;
717
+ },
718
+ authorize(predicate) {
719
+ callbacks.authorizePredicate = predicate;
720
+ return setters;
721
+ }
722
+ };
723
+ return setters;
724
+ }
725
+ setFeaturedTagsDispatcher(path, dispatcher) {
726
+ if (this.router.has("featuredTags")) throw new RouterError("Featured tags collection dispatcher already set.");
727
+ const variables = this.router.add(path, "featuredTags");
728
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for featured tags collection dispatcher must have one variable: {identifier}");
729
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
730
+ "fedify",
731
+ "federation",
732
+ "collection"
733
+ ]).warn("The {{handle}} variable in the featured tags collection dispatcher path is deprecated. Use {{identifier}} instead.");
734
+ const callbacks = { dispatcher };
735
+ this.featuredTagsCallbacks = callbacks;
736
+ const setters = {
737
+ setCounter(counter) {
738
+ callbacks.counter = counter;
739
+ return setters;
740
+ },
741
+ setFirstCursor(cursor) {
742
+ callbacks.firstCursor = cursor;
743
+ return setters;
744
+ },
745
+ setLastCursor(cursor) {
746
+ callbacks.lastCursor = cursor;
747
+ return setters;
748
+ },
749
+ authorize(predicate) {
750
+ callbacks.authorizePredicate = predicate;
751
+ return setters;
752
+ }
753
+ };
754
+ return setters;
755
+ }
756
+ setInboxListeners(inboxPath, sharedInboxPath) {
757
+ if (this.inboxListeners != null) throw new RouterError("Inbox listeners already set.");
758
+ if (this.router.has("inbox")) {
759
+ if (this.inboxPath !== inboxPath) throw new RouterError("Inbox listener path must match inbox dispatcher path.");
760
+ } else {
761
+ const variables = this.router.add(inboxPath, "inbox");
762
+ if (variables.size !== 1 || !(variables.has("identifier") || variables.has("handle"))) throw new RouterError("Path for inbox must have one variable: {identifier}");
763
+ this.inboxPath = inboxPath;
764
+ if (variables.has("handle")) (0, __logtape_logtape.getLogger)([
765
+ "fedify",
766
+ "federation",
767
+ "inbox"
768
+ ]).warn("The {{handle}} variable in the inbox path is deprecated. Use {{identifier}} instead.");
769
+ }
770
+ if (sharedInboxPath != null) {
771
+ const siVars = this.router.add(sharedInboxPath, "sharedInbox");
772
+ if (siVars.size !== 0) throw new RouterError("Path for shared inbox must have no variables.");
773
+ }
774
+ const listeners = this.inboxListeners = new InboxListenerSet();
775
+ const setters = {
776
+ on(type, listener) {
777
+ listeners.add(type, listener);
778
+ return setters;
779
+ },
780
+ onError: (handler) => {
781
+ this.inboxErrorHandler = handler;
782
+ return setters;
783
+ },
784
+ setSharedKeyDispatcher: (dispatcher) => {
785
+ this.sharedInboxKeyDispatcher = dispatcher;
786
+ return setters;
787
+ },
788
+ withIdempotency: (strategy) => {
789
+ this.idempotencyStrategy = strategy;
790
+ return setters;
791
+ }
792
+ };
793
+ return setters;
794
+ }
795
+ setCollectionDispatcher(name, itemType, path, dispatcher) {
796
+ return this.#setCustomCollectionDispatcher(name, "collection", itemType, path, dispatcher);
797
+ }
798
+ setOrderedCollectionDispatcher(name, itemType, path, dispatcher) {
799
+ return this.#setCustomCollectionDispatcher(name, "orderedCollection", itemType, path, dispatcher);
800
+ }
801
+ #setCustomCollectionDispatcher(name, collectionType, itemType, path, dispatcher) {
802
+ const strName = String(name);
803
+ const routeName = `${collectionType}:${this.#uniqueCollectionId(name)}`;
804
+ if (this.router.has(routeName)) throw new RouterError(`Collection dispatcher for ${strName} already set.`);
805
+ if (this.collectionCallbacks[name] != null) throw new RouterError(`Collection dispatcher for ${strName} already set.`);
806
+ const variables = this.router.add(path, routeName);
807
+ if (variables.size < 1) throw new RouterError("Path for collection dispatcher must have at least one variable.");
808
+ const callbacks = { dispatcher };
809
+ this.collectionCallbacks[name] = callbacks;
810
+ this.collectionTypeIds[name] = itemType;
811
+ const setters = {
812
+ setCounter(counter) {
813
+ callbacks.counter = counter;
814
+ return setters;
815
+ },
816
+ setFirstCursor(cursor) {
817
+ callbacks.firstCursor = cursor;
818
+ return setters;
819
+ },
820
+ setLastCursor(cursor) {
821
+ callbacks.lastCursor = cursor;
822
+ return setters;
823
+ },
824
+ authorize(predicate) {
825
+ callbacks.authorizePredicate = predicate;
826
+ return setters;
827
+ }
828
+ };
829
+ return setters;
830
+ }
831
+ /**
832
+ * Get the URL path for a custom collection.
833
+ * If the collection is not registered, returns null.
834
+ * @template TParam The parameter names of the requested URL.
835
+ * @param {string | symbol} name The name of the custom collection.
836
+ * @param {TParam} values The values to fill in the URL parameters.
837
+ * @returns {string | null} The URL path for the custom collection, or null if not registered.
838
+ */
839
+ getCollectionPath(name, values) {
840
+ if (!(name in this.collectionCallbacks)) return null;
841
+ const routeName = this.#uniqueCollectionId(name);
842
+ const path = this.router.build(`collection:${routeName}`, values) ?? this.router.build(`orderedCollection:${routeName}`, values);
843
+ return path;
844
+ }
845
+ /**
846
+ * Converts a name (string or symbol) to a unique string identifier.
847
+ * For symbols, generates and caches a UUID if not already present.
848
+ * For strings, returns the string as-is.
849
+ * @param name The name to convert to a unique identifier
850
+ * @returns A unique string identifier
851
+ */
852
+ #uniqueCollectionId(name) {
853
+ if (typeof name === "string") return name;
854
+ if (!this.#symbolRegistry.has(name)) this.#symbolRegistry.set(name, crypto.randomUUID());
855
+ return this.#symbolRegistry.get(name);
856
+ }
857
+ };
858
+ /**
859
+ * Creates a new {@link FederationBuilder} instance.
860
+ * @returns A new {@link FederationBuilder} instance.
861
+ * @since 1.6.0
862
+ */
863
+ function createFederationBuilder() {
864
+ return new FederationBuilderImpl();
865
+ }
866
+
867
+ //#endregion
868
+ //#region src/federation/collection.ts
869
+ /**
870
+ * Calculates the [partial follower collection digest][1].
871
+ *
872
+ * [1]: https://w3id.org/fep/8fcf#partial-follower-collection-digest
873
+ * @param uris The URIs to calculate the digest. Duplicate URIs are ignored.
874
+ * @returns The digest.
875
+ */
876
+ async function digest(uris) {
877
+ const processed = /* @__PURE__ */ new Set();
878
+ const encoder = new TextEncoder();
879
+ const result = new Uint8Array(32);
880
+ for (const uri of uris) {
881
+ const u = uri instanceof URL ? uri.href : uri;
882
+ if (processed.has(u)) continue;
883
+ processed.add(u);
884
+ const encoded = encoder.encode(u);
885
+ const digest$1 = new Uint8Array(await crypto.subtle.digest("SHA-256", encoded));
886
+ for (let i = 0; i < 32; i++) result[i] ^= digest$1[i];
887
+ }
888
+ return result;
889
+ }
890
+ /**
891
+ * Builds [`Collection-Synchronization`][1] header content.
892
+ *
893
+ * [1]: https://w3id.org/fep/8fcf#the-collection-synchronization-http-header
894
+ *
895
+ * @param collectionId The sender's followers collection URI.
896
+ * @param actorIds The actor URIs to digest.
897
+ * @returns The header content.
898
+ */
899
+ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
900
+ const [anyActorId] = actorIds;
901
+ const baseUrl = new URL(anyActorId);
902
+ const url = new URL(collectionId);
903
+ url.searchParams.set("base-url", `${baseUrl.origin}/`);
904
+ const hash = (0, byte_encodings_hex.encodeHex)(await digest(actorIds));
905
+ return `collectionId="${collectionId}", url="${url}", digest="${hash}"`;
906
+ }
907
+
908
+ //#endregion
909
+ //#region src/federation/keycache.ts
910
+ var KvKeyCache = class {
911
+ kv;
912
+ prefix;
913
+ options;
914
+ nullKeys;
915
+ constructor(kv, prefix, options = {}) {
916
+ this.kv = kv;
917
+ this.prefix = prefix;
918
+ this.nullKeys = /* @__PURE__ */ new Set();
919
+ this.options = options;
920
+ }
921
+ async get(keyId) {
922
+ if (this.nullKeys.has(keyId.href)) return null;
923
+ const serialized = await this.kv.get([...this.prefix, keyId.href]);
924
+ if (serialized == null) return void 0;
925
+ try {
926
+ return await require_actor.CryptographicKey.fromJsonLd(serialized, this.options);
927
+ } catch {
928
+ try {
929
+ return await require_actor.Multikey.fromJsonLd(serialized, this.options);
930
+ } catch {
931
+ await this.kv.delete([...this.prefix, keyId.href]);
932
+ return void 0;
933
+ }
934
+ }
935
+ }
936
+ async set(keyId, key) {
937
+ if (key == null) {
938
+ this.nullKeys.add(keyId.href);
939
+ await this.kv.delete([...this.prefix, keyId.href]);
940
+ return;
941
+ }
942
+ this.nullKeys.delete(keyId.href);
943
+ const serialized = await key.toJsonLd(this.options);
944
+ await this.kv.set([...this.prefix, keyId.href], serialized);
945
+ }
946
+ };
947
+
948
+ //#endregion
949
+ //#region src/federation/negotiation.ts
950
+ function compareSpecs(a, b) {
951
+ return b.q - a.q || (b.s ?? 0) - (a.s ?? 0) || (a.o ?? 0) - (b.o ?? 0) || a.i - b.i || 0;
952
+ }
953
+ function isQuality(spec) {
954
+ return spec.q > 0;
955
+ }
956
+ const simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
957
+ function splitKeyValuePair(str) {
958
+ const [key, value] = str.split("=");
959
+ return [key.toLowerCase(), value];
960
+ }
961
+ function parseMediaType(str, i) {
962
+ const match = simpleMediaTypeRegExp.exec(str);
963
+ if (!match) return;
964
+ const [, type, subtype, parameters] = match;
965
+ if (!type || !subtype) return;
966
+ const params = Object.create(null);
967
+ let q = 1;
968
+ if (parameters) {
969
+ const kvps = parameters.split(";").map((p) => p.trim()).map(splitKeyValuePair);
970
+ for (const [key, val] of kvps) {
971
+ const value = val && val[0] === `"` && val[val.length - 1] === `"` ? val.slice(1, val.length - 1) : val;
972
+ if (key === "q" && value) {
973
+ q = parseFloat(value);
974
+ break;
975
+ }
976
+ params[key] = value;
977
+ }
978
+ }
979
+ return {
980
+ type,
981
+ subtype,
982
+ params,
983
+ i,
984
+ o: void 0,
985
+ q,
986
+ s: void 0
987
+ };
988
+ }
989
+ function parseAccept(accept) {
990
+ const accepts = accept.split(",").map((p) => p.trim());
991
+ const mediaTypes = [];
992
+ for (const [index, accept$1] of accepts.entries()) {
993
+ const mediaType = parseMediaType(accept$1.trim(), index);
994
+ if (mediaType) mediaTypes.push(mediaType);
995
+ }
996
+ return mediaTypes;
997
+ }
998
+ function getFullType(spec) {
999
+ return `${spec.type}/${spec.subtype}`;
1000
+ }
1001
+ function preferredMediaTypes(accept) {
1002
+ const accepts = parseAccept(accept === void 0 ? "*/*" : accept ?? "");
1003
+ return accepts.filter(isQuality).sort(compareSpecs).map(getFullType);
1004
+ }
1005
+ function acceptsJsonLd(request) {
1006
+ const accept = request.headers.get("Accept");
1007
+ const types = accept ? preferredMediaTypes(accept) : ["*/*"];
1008
+ if (types == null) return true;
1009
+ if (types[0] === "text/html" || types[0] === "application/xhtml+xml") return false;
1010
+ return types.includes("application/activity+json") || types.includes("application/ld+json") || types.includes("application/json");
1011
+ }
1012
+
1013
+ //#endregion
1014
+ //#region src/federation/handler.ts
1015
+ /**
1016
+ * Handles an actor request.
1017
+ * @template TContextData The context data to pass to the context.
1018
+ * @param request The HTTP request.
1019
+ * @param parameters The parameters for handling the actor.
1020
+ * @returns A promise that resolves to an HTTP response.
1021
+ */
1022
+ async function handleActor(request, { identifier, context: context$2, actorDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
1023
+ const logger$1 = (0, __logtape_logtape.getLogger)([
1024
+ "fedify",
1025
+ "federation",
1026
+ "actor"
1027
+ ]);
1028
+ if (actorDispatcher == null) {
1029
+ logger$1.debug("Actor dispatcher is not set.", { identifier });
1030
+ return await onNotFound(request);
1031
+ }
1032
+ const actor = await actorDispatcher(context$2, identifier);
1033
+ if (actor == null) {
1034
+ logger$1.debug("Actor {identifier} not found.", { identifier });
1035
+ return await onNotFound(request);
1036
+ }
1037
+ if (authorizePredicate != null) {
1038
+ let key = await context$2.getSignedKey();
1039
+ key = key?.clone({}, { $warning: {
1040
+ category: [
1041
+ "fedify",
1042
+ "federation",
1043
+ "actor"
1044
+ ],
1045
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
1046
+ } }) ?? null;
1047
+ let keyOwner = await context$2.getSignedKeyOwner();
1048
+ keyOwner = keyOwner?.clone({}, { $warning: {
1049
+ category: [
1050
+ "fedify",
1051
+ "federation",
1052
+ "actor"
1053
+ ],
1054
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
1055
+ } }) ?? null;
1056
+ if (!await authorizePredicate(context$2, identifier, key, keyOwner)) return await onUnauthorized(request);
1057
+ }
1058
+ const jsonLd = await actor.toJsonLd(context$2);
1059
+ return new Response(JSON.stringify(jsonLd), { headers: {
1060
+ "Content-Type": "application/activity+json",
1061
+ Vary: "Accept"
1062
+ } });
1063
+ }
1064
+ /**
1065
+ * Handles an object request.
1066
+ * @template TContextData The context data to pass to the context.
1067
+ * @param request The HTTP request.
1068
+ * @param parameters The parameters for handling the object.
1069
+ * @returns A promise that resolves to an HTTP response.
1070
+ */
1071
+ async function handleObject(request, { values, context: context$2, objectDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
1072
+ if (objectDispatcher == null) return await onNotFound(request);
1073
+ const object = await objectDispatcher(context$2, values);
1074
+ if (object == null) return await onNotFound(request);
1075
+ if (authorizePredicate != null) {
1076
+ let key = await context$2.getSignedKey();
1077
+ key = key?.clone({}, { $warning: {
1078
+ category: [
1079
+ "fedify",
1080
+ "federation",
1081
+ "object"
1082
+ ],
1083
+ message: "The third parameter of ObjectAuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
1084
+ } }) ?? null;
1085
+ let keyOwner = await context$2.getSignedKeyOwner();
1086
+ keyOwner = keyOwner?.clone({}, { $warning: {
1087
+ category: [
1088
+ "fedify",
1089
+ "federation",
1090
+ "object"
1091
+ ],
1092
+ message: "The fourth parameter of ObjectAuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
1093
+ } }) ?? null;
1094
+ if (!await authorizePredicate(context$2, values, key, keyOwner)) return await onUnauthorized(request);
1095
+ }
1096
+ const jsonLd = await object.toJsonLd(context$2);
1097
+ return new Response(JSON.stringify(jsonLd), { headers: {
1098
+ "Content-Type": "application/activity+json",
1099
+ Vary: "Accept"
1100
+ } });
1101
+ }
1102
+ /**
1103
+ * Handles a collection request.
1104
+ * @template TItem The type of items in the collection.
1105
+ * @template TContext The type of the context, extending {@link RequestContext}.
1106
+ * @template TContextData The context data to pass to the `TContext`.
1107
+ * @template TFilter The type of the filter.
1108
+ * @param request The HTTP request.
1109
+ * @param parameters The parameters for handling the collection.
1110
+ * @returns A promise that resolves to an HTTP response.
1111
+ */
1112
+ async function handleCollection(request, { name, identifier, uriGetter, filter, filterPredicate, context: context$2, collectionCallbacks, tracerProvider, onUnauthorized, onNotFound }) {
1113
+ const spanName = name.trim().replace(/\s+/g, "_");
1114
+ tracerProvider = tracerProvider ?? __opentelemetry_api.trace.getTracerProvider();
1115
+ const tracer = tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
1116
+ const url = new URL(request.url);
1117
+ const cursor = url.searchParams.get("cursor");
1118
+ if (collectionCallbacks == null) return await onNotFound(request);
1119
+ let collection;
1120
+ const baseUri = uriGetter(identifier);
1121
+ if (cursor == null) {
1122
+ const firstCursor = await collectionCallbacks.firstCursor?.(context$2, identifier);
1123
+ const totalItems = filter == null ? await collectionCallbacks.counter?.(context$2, identifier) : void 0;
1124
+ if (firstCursor == null) {
1125
+ const itemsOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection ${spanName}`, {
1126
+ kind: __opentelemetry_api.SpanKind.SERVER,
1127
+ attributes: {
1128
+ "activitypub.collection.id": baseUri.href,
1129
+ "activitypub.collection.type": require_actor.OrderedCollection.typeId.href
1130
+ }
1131
+ }, async (span) => {
1132
+ if (totalItems != null) span.setAttribute("activitypub.collection.total_items", Number(totalItems));
1133
+ try {
1134
+ const page = await collectionCallbacks.dispatcher(context$2, identifier, null, filter);
1135
+ if (page == null) {
1136
+ span.setStatus({ code: __opentelemetry_api.SpanStatusCode.ERROR });
1137
+ return await onNotFound(request);
1138
+ }
1139
+ const { items } = page;
1140
+ span.setAttribute("fedify.collection.items", items.length);
1141
+ return items;
1142
+ } catch (e) {
1143
+ span.setStatus({
1144
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1145
+ message: String(e)
1146
+ });
1147
+ throw e;
1148
+ } finally {
1149
+ span.end();
1150
+ }
1151
+ });
1152
+ if (itemsOrResponse instanceof Response) return itemsOrResponse;
1153
+ collection = new require_actor.OrderedCollection({
1154
+ id: baseUri,
1155
+ totalItems: totalItems == null ? null : Number(totalItems),
1156
+ items: filterCollectionItems(itemsOrResponse, name, filterPredicate)
1157
+ });
1158
+ } else {
1159
+ const lastCursor = await collectionCallbacks.lastCursor?.(context$2, identifier);
1160
+ const first = new URL(context$2.url);
1161
+ first.searchParams.set("cursor", firstCursor);
1162
+ let last = null;
1163
+ if (lastCursor != null) {
1164
+ last = new URL(context$2.url);
1165
+ last.searchParams.set("cursor", lastCursor);
1166
+ }
1167
+ collection = new require_actor.OrderedCollection({
1168
+ id: baseUri,
1169
+ totalItems: totalItems == null ? null : Number(totalItems),
1170
+ first,
1171
+ last
1172
+ });
1173
+ }
1174
+ } else {
1175
+ const uri = new URL(baseUri);
1176
+ uri.searchParams.set("cursor", cursor);
1177
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name}`, {
1178
+ kind: __opentelemetry_api.SpanKind.SERVER,
1179
+ attributes: {
1180
+ "activitypub.collection.id": uri.href,
1181
+ "activitypub.collection.type": require_actor.OrderedCollectionPage.typeId.href,
1182
+ "fedify.collection.cursor": cursor
1183
+ }
1184
+ }, async (span) => {
1185
+ try {
1186
+ const page = await collectionCallbacks.dispatcher(context$2, identifier, cursor, filter);
1187
+ if (page == null) {
1188
+ span.setStatus({ code: __opentelemetry_api.SpanStatusCode.ERROR });
1189
+ return await onNotFound(request);
1190
+ }
1191
+ span.setAttribute("fedify.collection.items", page.items.length);
1192
+ return page;
1193
+ } catch (e) {
1194
+ span.setStatus({
1195
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1196
+ message: String(e)
1197
+ });
1198
+ throw e;
1199
+ } finally {
1200
+ span.end();
1201
+ }
1202
+ });
1203
+ if (pageOrResponse instanceof Response) return pageOrResponse;
1204
+ const { items, prevCursor, nextCursor } = pageOrResponse;
1205
+ let prev = null;
1206
+ if (prevCursor != null) {
1207
+ prev = new URL(context$2.url);
1208
+ prev.searchParams.set("cursor", prevCursor);
1209
+ }
1210
+ let next = null;
1211
+ if (nextCursor != null) {
1212
+ next = new URL(context$2.url);
1213
+ next.searchParams.set("cursor", nextCursor);
1214
+ }
1215
+ const partOf = new URL(context$2.url);
1216
+ partOf.searchParams.delete("cursor");
1217
+ collection = new require_actor.OrderedCollectionPage({
1218
+ id: uri,
1219
+ prev,
1220
+ next,
1221
+ items: filterCollectionItems(items, name, filterPredicate),
1222
+ partOf
1223
+ });
1224
+ }
1225
+ if (collectionCallbacks.authorizePredicate != null) {
1226
+ let key = await context$2.getSignedKey();
1227
+ key = key?.clone({}, { $warning: {
1228
+ category: [
1229
+ "fedify",
1230
+ "federation",
1231
+ "collection"
1232
+ ],
1233
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
1234
+ } }) ?? null;
1235
+ let keyOwner = await context$2.getSignedKeyOwner();
1236
+ keyOwner = keyOwner?.clone({}, { $warning: {
1237
+ category: [
1238
+ "fedify",
1239
+ "federation",
1240
+ "collection"
1241
+ ],
1242
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
1243
+ } }) ?? null;
1244
+ if (!await collectionCallbacks.authorizePredicate(context$2, identifier, key, keyOwner)) return await onUnauthorized(request);
1245
+ }
1246
+ const jsonLd = await collection.toJsonLd(context$2);
1247
+ return new Response(JSON.stringify(jsonLd), { headers: {
1248
+ "Content-Type": "application/activity+json",
1249
+ Vary: "Accept"
1250
+ } });
1251
+ }
1252
+ /**
1253
+ * Filters collection items based on the provided predicate.
1254
+ * @template TItem The type of items to filter.
1255
+ * @param items The items to filter.
1256
+ * @param collectionName The name of the collection for logging purposes.
1257
+ * @param filterPredicate Optional predicate function to filter items.
1258
+ * @returns The filtered items as Objects, Links, or URLs.
1259
+ */
1260
+ function filterCollectionItems(items, collectionName, filterPredicate) {
1261
+ const result = [];
1262
+ let logged = false;
1263
+ for (const item of items) {
1264
+ let mappedItem;
1265
+ if (item instanceof require_actor.Object || item instanceof require_actor.Link || item instanceof URL) mappedItem = item;
1266
+ else if (item.id == null) continue;
1267
+ else mappedItem = item.id;
1268
+ if (filterPredicate != null && !filterPredicate(item)) {
1269
+ if (!logged) {
1270
+ (0, __logtape_logtape.getLogger)([
1271
+ "fedify",
1272
+ "federation",
1273
+ "collection"
1274
+ ]).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`);
1275
+ logged = true;
1276
+ }
1277
+ continue;
1278
+ }
1279
+ result.push(mappedItem);
1280
+ }
1281
+ return result;
1282
+ }
1283
+ /**
1284
+ * Handles an inbox request for ActivityPub activities.
1285
+ * @template TContextData The context data to pass to the context.
1286
+ * @param request The HTTP request.
1287
+ * @param options The parameters for handling the inbox.
1288
+ * @returns A promise that resolves to an HTTP response.
1289
+ */
1290
+ async function handleInbox(request, options) {
1291
+ const tracerProvider = options.tracerProvider ?? __opentelemetry_api.trace.getTracerProvider();
1292
+ const tracer = tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
1293
+ return await tracer.startActiveSpan("activitypub.inbox", {
1294
+ kind: options.queue == null ? __opentelemetry_api.SpanKind.SERVER : __opentelemetry_api.SpanKind.PRODUCER,
1295
+ attributes: { "activitypub.shared_inbox": options.recipient == null }
1296
+ }, async (span) => {
1297
+ if (options.recipient != null) span.setAttribute("fedify.inbox.recipient", options.recipient);
1298
+ try {
1299
+ return await handleInboxInternal(request, options, span);
1300
+ } catch (e) {
1301
+ span.setStatus({
1302
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1303
+ message: String(e)
1304
+ });
1305
+ throw e;
1306
+ } finally {
1307
+ span.end();
1308
+ }
1309
+ });
1310
+ }
1311
+ /**
1312
+ * Internal function for handling inbox requests with detailed processing.
1313
+ * @template TContextData The context data to pass to the context.
1314
+ * @param request The HTTP request.
1315
+ * @param options The parameters for handling the inbox.
1316
+ * @param span The OpenTelemetry span for tracing.
1317
+ * @returns A promise that resolves to an HTTP response.
1318
+ */
1319
+ async function handleInboxInternal(request, parameters, span) {
1320
+ const { recipient, context: ctx, inboxContextFactory, kv, kvPrefixes, queue, actorDispatcher, inboxListeners, inboxErrorHandler, onNotFound, signatureTimeWindow, skipSignatureVerification, tracerProvider } = parameters;
1321
+ const logger$1 = (0, __logtape_logtape.getLogger)([
1322
+ "fedify",
1323
+ "federation",
1324
+ "inbox"
1325
+ ]);
1326
+ if (actorDispatcher == null) {
1327
+ logger$1.error("Actor dispatcher is not set.", { recipient });
1328
+ span.setStatus({
1329
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1330
+ message: "Actor dispatcher is not set."
1331
+ });
1332
+ return await onNotFound(request);
1333
+ } else if (recipient != null) {
1334
+ const actor = await actorDispatcher(ctx, recipient);
1335
+ if (actor == null) {
1336
+ logger$1.error("Actor {recipient} not found.", { recipient });
1337
+ span.setStatus({
1338
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1339
+ message: `Actor ${recipient} not found.`
1340
+ });
1341
+ return await onNotFound(request);
1342
+ }
1343
+ }
1344
+ if (request.bodyUsed) {
1345
+ logger$1.error("Request body has already been read.", { recipient });
1346
+ span.setStatus({
1347
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1348
+ message: "Request body has already been read."
1349
+ });
1350
+ return new Response("Internal server error.", {
1351
+ status: 500,
1352
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1353
+ });
1354
+ } else if (request.body?.locked) {
1355
+ logger$1.error("Request body is locked.", { recipient });
1356
+ span.setStatus({
1357
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1358
+ message: "Request body is locked."
1359
+ });
1360
+ return new Response("Internal server error.", {
1361
+ status: 500,
1362
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1363
+ });
1364
+ }
1365
+ let json;
1366
+ try {
1367
+ json = await request.clone().json();
1368
+ } catch (error) {
1369
+ logger$1.error("Failed to parse JSON:\n{error}", {
1370
+ recipient,
1371
+ error
1372
+ });
1373
+ try {
1374
+ await inboxErrorHandler?.(ctx, error);
1375
+ } catch (error$1) {
1376
+ logger$1.error("An unexpected error occurred in inbox error handler:\n{error}", {
1377
+ error: error$1,
1378
+ activity: json,
1379
+ recipient
1380
+ });
1381
+ }
1382
+ span.setStatus({
1383
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1384
+ message: `Failed to parse JSON:\n${error}`
1385
+ });
1386
+ return new Response("Invalid JSON.", {
1387
+ status: 400,
1388
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1389
+ });
1390
+ }
1391
+ const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1392
+ let ldSigVerified;
1393
+ try {
1394
+ ldSigVerified = await require_proof.verifyJsonLd(json, {
1395
+ contextLoader: ctx.contextLoader,
1396
+ documentLoader: ctx.documentLoader,
1397
+ keyCache,
1398
+ tracerProvider
1399
+ });
1400
+ } catch (error) {
1401
+ if (error instanceof Error && error.name === "jsonld.SyntaxError") {
1402
+ logger$1.error("Failed to parse JSON-LD:\n{error}", {
1403
+ recipient,
1404
+ error
1405
+ });
1406
+ return new Response("Invalid JSON-LD.", {
1407
+ status: 400,
1408
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1409
+ });
1410
+ }
1411
+ ldSigVerified = false;
1412
+ }
1413
+ const jsonWithoutSig = require_proof.detachSignature(json);
1414
+ let activity = null;
1415
+ if (ldSigVerified) {
1416
+ logger$1.debug("Linked Data Signatures are verified.", {
1417
+ recipient,
1418
+ json
1419
+ });
1420
+ activity = await require_actor.Activity.fromJsonLd(jsonWithoutSig, ctx);
1421
+ } else {
1422
+ logger$1.debug("Linked Data Signatures are not verified.", {
1423
+ recipient,
1424
+ json
1425
+ });
1426
+ try {
1427
+ activity = await require_proof.verifyObject(require_actor.Activity, jsonWithoutSig, {
1428
+ contextLoader: ctx.contextLoader,
1429
+ documentLoader: ctx.documentLoader,
1430
+ keyCache,
1431
+ tracerProvider
1432
+ });
1433
+ } catch (error) {
1434
+ logger$1.error("Failed to parse activity:\n{error}", {
1435
+ recipient,
1436
+ activity: json,
1437
+ error
1438
+ });
1439
+ try {
1440
+ await inboxErrorHandler?.(ctx, error);
1441
+ } catch (error$1) {
1442
+ logger$1.error("An unexpected error occurred in inbox error handler:\n{error}", {
1443
+ error: error$1,
1444
+ activity: json,
1445
+ recipient
1446
+ });
1447
+ }
1448
+ span.setStatus({
1449
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1450
+ message: `Failed to parse activity:\n${error}`
1451
+ });
1452
+ return new Response("Invalid activity.", {
1453
+ status: 400,
1454
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1455
+ });
1456
+ }
1457
+ if (activity == null) logger$1.debug("Object Integrity Proofs are not verified.", {
1458
+ recipient,
1459
+ activity: json
1460
+ });
1461
+ else logger$1.debug("Object Integrity Proofs are verified.", {
1462
+ recipient,
1463
+ activity: json
1464
+ });
1465
+ }
1466
+ let httpSigKey = null;
1467
+ if (activity == null) {
1468
+ if (!skipSignatureVerification) {
1469
+ const key = await require_http.verifyRequest(request, {
1470
+ contextLoader: ctx.contextLoader,
1471
+ documentLoader: ctx.documentLoader,
1472
+ timeWindow: signatureTimeWindow,
1473
+ keyCache,
1474
+ tracerProvider
1475
+ });
1476
+ if (key == null) {
1477
+ logger$1.error("Failed to verify the request's HTTP Signatures.", { recipient });
1478
+ span.setStatus({
1479
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1480
+ message: `Failed to verify the request's HTTP Signatures.`
1481
+ });
1482
+ const response = new Response("Failed to verify the request signature.", {
1483
+ status: 401,
1484
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1485
+ });
1486
+ return response;
1487
+ } else logger$1.debug("HTTP Signatures are verified.", { recipient });
1488
+ httpSigKey = key;
1489
+ }
1490
+ activity = await require_actor.Activity.fromJsonLd(jsonWithoutSig, ctx);
1491
+ }
1492
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
1493
+ span.setAttribute("activitypub.activity.type", require_actor.getTypeId(activity).href);
1494
+ if (httpSigKey != null && !await require_proof.doesActorOwnKey(activity, httpSigKey, ctx)) {
1495
+ logger$1.error("The signer ({keyId}) and the actor ({actorId}) do not match.", {
1496
+ activity: json,
1497
+ recipient,
1498
+ keyId: httpSigKey.id?.href,
1499
+ actorId: activity.actorId?.href
1500
+ });
1501
+ span.setStatus({
1502
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1503
+ message: `The signer (${httpSigKey.id?.href}) and the actor (${activity.actorId?.href}) do not match.`
1504
+ });
1505
+ return new Response("The signer and the actor do not match.", {
1506
+ status: 401,
1507
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1508
+ });
1509
+ }
1510
+ const routeResult = await routeActivity({
1511
+ context: ctx,
1512
+ json,
1513
+ activity,
1514
+ recipient,
1515
+ inboxListeners,
1516
+ inboxContextFactory,
1517
+ inboxErrorHandler,
1518
+ kv,
1519
+ kvPrefixes,
1520
+ queue,
1521
+ span,
1522
+ tracerProvider,
1523
+ idempotencyStrategy: parameters.idempotencyStrategy
1524
+ });
1525
+ if (routeResult === "alreadyProcessed") return new Response(`Activity <${activity.id}> has already been processed.`, {
1526
+ status: 202,
1527
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1528
+ });
1529
+ else if (routeResult === "missingActor") return new Response("Missing actor.", {
1530
+ status: 400,
1531
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1532
+ });
1533
+ else if (routeResult === "enqueued") return new Response("Activity is enqueued.", {
1534
+ status: 202,
1535
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1536
+ });
1537
+ else if (routeResult === "unsupportedActivity") return new Response("", {
1538
+ status: 202,
1539
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1540
+ });
1541
+ else if (routeResult === "error") return new Response("Internal server error.", {
1542
+ status: 500,
1543
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1544
+ });
1545
+ else return new Response("", {
1546
+ status: 202,
1547
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1548
+ });
1549
+ }
1550
+ /**
1551
+ * Handles a custom collection request.
1552
+ * @template TItem The type of items in the collection.
1553
+ * @template TParam The parameter names of the requested URL.
1554
+ * @template TContext The type of the context, extending {@link RequestContext}.
1555
+ * @template TContextData The context data to pass to the `TContext`.
1556
+ * @param request The HTTP request.
1557
+ * @param handleParams Parameters for handling the collection.
1558
+ * @returns A promise that resolves to an HTTP response.
1559
+ * @since 1.8.0
1560
+ */
1561
+ const handleCustomCollection = exceptWrapper(_handleCustomCollection);
1562
+ async function _handleCustomCollection(request, { name, values, context: context$2, tracerProvider, collectionCallbacks: callbacks, filterPredicate }) {
1563
+ verifyDefined(callbacks);
1564
+ await authIfNeeded(context$2, values, callbacks);
1565
+ const cursor = new URL(request.url).searchParams.get("cursor");
1566
+ return await new CustomCollectionHandler(name, values, context$2, callbacks, tracerProvider, require_actor.Collection, require_actor.CollectionPage, filterPredicate).fetchCollection(cursor).toJsonLd().then(respondAsActivity);
1567
+ }
1568
+ /**
1569
+ * Handles an ordered collection request.
1570
+ * @template TItem The type of items in the collection.
1571
+ * @template TParam The parameter names of the requested URL.
1572
+ * @template TContext The type of the context, extending {@link RequestContext}.
1573
+ * @template TContextData The context data to pass to the `TContext`.
1574
+ * @param request The HTTP request.
1575
+ * @param handleParams Parameters for handling the collection.
1576
+ * @returns A promise that resolves to an HTTP response.
1577
+ * @since 1.8.0
1578
+ */
1579
+ const handleOrderedCollection = exceptWrapper(_handleOrderedCollection);
1580
+ async function _handleOrderedCollection(request, { name, values, context: context$2, tracerProvider, collectionCallbacks: callbacks, filterPredicate }) {
1581
+ verifyDefined(callbacks);
1582
+ await authIfNeeded(context$2, values, callbacks);
1583
+ const cursor = new URL(request.url).searchParams.get("cursor");
1584
+ return await new CustomCollectionHandler(name, values, context$2, callbacks, tracerProvider, require_actor.OrderedCollection, require_actor.OrderedCollectionPage, filterPredicate).fetchCollection(cursor).toJsonLd().then(respondAsActivity);
1585
+ }
1586
+ /**
1587
+ * Handling custom collections with support for pagination and filtering.
1588
+ * The main flow is on `getCollection`, `dispatch`.
1589
+ *
1590
+ * @template TItem The type of items in the collection.
1591
+ * @template TParam The parameter names of the requested URL.
1592
+ * @template TContext The type of the context. {@link Context} or {@link RequestContext}.
1593
+ * @template TContextData The context data to pass to the `TContext`.
1594
+ * @template TCollection The type of the collection, extending {@link Collection}.
1595
+ * @template TCollectionPage The type of the collection page, extending {@link CollectionPage}.
1596
+ * @since 1.8.0
1597
+ */
1598
+ var CustomCollectionHandler = class {
1599
+ /**
1600
+ * The tracer for telemetry.
1601
+ * @type {Tracer}
1602
+ */
1603
+ #tracer;
1604
+ /**
1605
+ * The ID of the collection.
1606
+ * @type {URL}
1607
+ */
1608
+ #id;
1609
+ /**
1610
+ * Store total count of items in the collection.
1611
+ * Use `this.totalItems` to access the total items count.
1612
+ * It is a promise because it may require an asynchronous operation to count items.
1613
+ * @type {Promise<number | null> | undefined}
1614
+ */
1615
+ #totalItems = void 0;
1616
+ /**
1617
+ * The first cursor for pagination.
1618
+ * It is a promise because it may require an asynchronous operation to get the first cursor.
1619
+ * @type {Promise<string | null> | undefined}
1620
+ */
1621
+ #dispatcher;
1622
+ #collection = null;
1623
+ /**
1624
+ * Creates a new CustomCollection instance.
1625
+ * @param name The name of the collection.
1626
+ * @param values The parameter values for the collection.
1627
+ * @param context The request context.
1628
+ * @param callbacks The collection callbacks.
1629
+ * @param tracerProvider The tracer provider for telemetry.
1630
+ * @param Collection The Collection constructor.
1631
+ * @param CollectionPage The CollectionPage constructor.
1632
+ * @param filterPredicate Optional filter predicate for items.
1633
+ */
1634
+ constructor(name, values, context$2, callbacks, tracerProvider = __opentelemetry_api.trace.getTracerProvider(), Collection$1, CollectionPage$1, filterPredicate) {
1635
+ this.name = name;
1636
+ this.values = values;
1637
+ this.context = context$2;
1638
+ this.callbacks = callbacks;
1639
+ this.tracerProvider = tracerProvider;
1640
+ this.Collection = Collection$1;
1641
+ this.CollectionPage = CollectionPage$1;
1642
+ this.filterPredicate = filterPredicate;
1643
+ this.name = this.name.trim().replace(/\s+/g, "_");
1644
+ this.#tracer = this.tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
1645
+ this.#id = new URL(this.context.url);
1646
+ this.#dispatcher = callbacks.dispatcher.bind(callbacks);
1647
+ }
1648
+ /**
1649
+ * Converts the collection to JSON-LD format.
1650
+ * @returns A promise that resolves to the JSON-LD representation.
1651
+ */
1652
+ async toJsonLd() {
1653
+ return (await this.collection).toJsonLd(this.context);
1654
+ }
1655
+ /**
1656
+ * Fetches the collection with optional cursor for pagination.
1657
+ * This method is defined for method chaining and to show processing flow properly.
1658
+ * So it is no problem to call `toJsonLd` directly on the instance.
1659
+ * @param cursor The cursor for pagination, or null for the first page.
1660
+ * @returns The CustomCollection instance for method chaining.
1661
+ */
1662
+ fetchCollection(cursor = null) {
1663
+ this.#collection = this.getCollection(cursor);
1664
+ return this;
1665
+ }
1666
+ /**
1667
+ * Gets the collection or collection page based on the cursor.
1668
+ * @param {string | null} cursor The cursor for pagination, or null for the main collection.
1669
+ * @returns {Promise<TCollection | TCollectionPage>} A promise that resolves to a Collection or CollectionPage.
1670
+ */
1671
+ async getCollection(cursor = null) {
1672
+ if (cursor !== null) {
1673
+ const props$1 = await this.getPageProps(cursor);
1674
+ return new this.CollectionPage(props$1);
1675
+ }
1676
+ const firstCursor = await this.firstCursor;
1677
+ const props = typeof firstCursor === "string" ? await this.getProps(firstCursor) : await this.getPropsWithoutCursor();
1678
+ return new this.Collection(props);
1679
+ }
1680
+ /**
1681
+ * Gets the properties for a collection page.
1682
+ * Returns the page properties including items, previous and next cursors.
1683
+ * @param {string} cursor The cursor for the page.
1684
+ * @returns A promise that resolves to the page properties.
1685
+ */
1686
+ async getPageProps(cursor) {
1687
+ const id = this.#id;
1688
+ const pages = await this.getPages({ cursor });
1689
+ const { prevCursor, nextCursor } = pages;
1690
+ const partOf = new URL(id);
1691
+ partOf.searchParams.delete("cursor");
1692
+ return {
1693
+ id,
1694
+ partOf,
1695
+ items: this.filterItems(pages.items),
1696
+ prev: this.appendToUrl(prevCursor),
1697
+ next: this.appendToUrl(nextCursor)
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Gets the properties for a collection with cursors.
1702
+ * Returns the first cursor and last cursor as URL, along with total items count.
1703
+ * @param {string} firstCursor The first cursor for pagination.
1704
+ * @returns A promise that resolves to the collection properties.
1705
+ */
1706
+ async getProps(firstCursor) {
1707
+ const lastCursor = await this.callbacks.lastCursor?.(this.context, this.values);
1708
+ return {
1709
+ id: this.#id,
1710
+ first: this.appendToUrl(firstCursor),
1711
+ last: this.appendToUrl(lastCursor),
1712
+ totalItems: await this.totalItems
1713
+ };
1714
+ }
1715
+ /**
1716
+ * Gets the properties for a collection of all items and the count.
1717
+ * @returns A promise that resolves to the collection properties.
1718
+ */
1719
+ async getPropsWithoutCursor() {
1720
+ const totalItems = await this.totalItems;
1721
+ const pages = await this.getPages({ totalItems });
1722
+ return {
1723
+ id: this.#id,
1724
+ totalItems,
1725
+ items: this.filterItems(pages.items)
1726
+ };
1727
+ }
1728
+ /**
1729
+ * Gets a page of items from the collection.
1730
+ * Wraps the dispatcher in a span for telemetry.
1731
+ * @param options Options for getting the page, including cursor and total items.
1732
+ * @returns A promise that resolves to the page items.
1733
+ */
1734
+ async getPages({ cursor = null, totalItems = null }) {
1735
+ return await this.#tracer.startActiveSpan(`${this.ATTRS.DISPATCH_COLLECTION} ${this.name}`, this.spanOptions(__opentelemetry_api.SpanKind.SERVER, cursor), this.spanPages({
1736
+ cursor,
1737
+ totalItems
1738
+ }));
1739
+ }
1740
+ /**
1741
+ * Creates span options for telemetry.
1742
+ * @param {SpanKind} kind The span kind.
1743
+ * @param {string | null} cursor The optional cursor value.
1744
+ * @returns {SpanOptions}The span options.
1745
+ */
1746
+ spanOptions = (kind, cursor) => ({
1747
+ kind,
1748
+ attributes: {
1749
+ [this.ATTRS.ID]: this.#id.href,
1750
+ [this.ATTRS.TYPE]: this.Collection.typeId.href,
1751
+ ...cursor ? { [this.ATTRS.CURSOR]: cursor } : {}
1752
+ }
1753
+ });
1754
+ /**
1755
+ * Creates a function to wrap the dispatcher so tracing can be applied.
1756
+ * @param params Parameters including cursor and total items.
1757
+ * @returns A function that handles the span operation.
1758
+ */
1759
+ spanPages = ({ totalItems = null, cursor = null }) => async (span) => {
1760
+ try {
1761
+ if (totalItems !== null) span.setAttribute(this.ATTRS.TOTAL_ITEMS, totalItems);
1762
+ const page = await this.dispatch(cursor);
1763
+ span.setAttribute(this.ATTRS.ITEMS, page.items.length);
1764
+ return page;
1765
+ } catch (e) {
1766
+ const message = e instanceof Error ? e.message : String(e);
1767
+ span.setStatus({
1768
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
1769
+ message
1770
+ });
1771
+ throw e;
1772
+ } finally {
1773
+ span.end();
1774
+ }
1775
+ };
1776
+ /**
1777
+ * Dispatches the collection request to get items.
1778
+ * @param cursor The cursor for pagination, or null for the first page.
1779
+ * @returns A promise that resolves to the page items.
1780
+ */
1781
+ async dispatch(cursor = null) {
1782
+ return await this.#dispatcher(this.context, this.values, cursor) ?? new ItemsNotFoundError().throw();
1783
+ }
1784
+ /**
1785
+ * Filters the items in the collection.
1786
+ * @param items The items to filter.
1787
+ * @returns The filtered items.
1788
+ */
1789
+ filterItems(items) {
1790
+ return filterCollectionItems(items, this.name, this.filterPredicate);
1791
+ }
1792
+ /**
1793
+ * Appends a cursor to the URL if it exists.
1794
+ * @param cursor The cursor to append, or null/undefined.
1795
+ * @returns The URL with cursor appended, or null if cursor is null/undefined.
1796
+ */
1797
+ appendToUrl(cursor) {
1798
+ return appendCursorIfExists(this.context.url, cursor);
1799
+ }
1800
+ /**
1801
+ * Gets the stored collection or collection page.
1802
+ * @returns A promise that resolves to the collection or collection page.
1803
+ */
1804
+ get collection() {
1805
+ if (this.#collection === null) this.#collection = this.getCollection();
1806
+ return this.#collection;
1807
+ }
1808
+ /**
1809
+ * Gets the total number of items in the collection.
1810
+ * @returns A promise that resolves to the total items count,
1811
+ * or null if not available.
1812
+ */
1813
+ get totalItems() {
1814
+ if (this.#totalItems === void 0) this.totalItems = this.callbacks.counter?.(this.context, this.values);
1815
+ return this.#totalItems;
1816
+ }
1817
+ /**
1818
+ * Sets the total number of items in the collection.
1819
+ * @param value The total items count or a promise that resolves to it.
1820
+ */
1821
+ set totalItems(value) {
1822
+ const toNumber = (value$1) => value$1 == null ? null : Number(value$1);
1823
+ this.#totalItems = value instanceof Promise ? value.then(toNumber) : Promise.resolve(toNumber(value));
1824
+ }
1825
+ /**
1826
+ * Gets the first cursor for pagination.
1827
+ * @returns A promise that resolves to the first cursor,
1828
+ * or null if not available.
1829
+ */
1830
+ get firstCursor() {
1831
+ const cursor = this.callbacks.firstCursor?.(this.context, this.values);
1832
+ return Promise.resolve(cursor ?? null);
1833
+ }
1834
+ /**
1835
+ * Attribute constants for telemetry spans.
1836
+ */
1837
+ ATTRS = {
1838
+ DISPATCH_COLLECTION: "activitypub.dispatch_collection",
1839
+ CURSOR: "fedify.collection.cursor",
1840
+ ID: "activitypub.collection.id",
1841
+ ITEMS: "fedify.collection.items",
1842
+ TOTAL_ITEMS: "activitypub.collection.total_items",
1843
+ TYPE: "activitypub.collection.type"
1844
+ };
1845
+ };
1846
+ /**
1847
+ * A wrapper function that catches specific errors and handles them appropriately.
1848
+ * @template TParams The type of parameters that extend ErrorHandlers.
1849
+ * @param handler The handler function to wrap.
1850
+ * @returns A wrapped handler function that catches and handles specific errors.
1851
+ * @since 1.8.0
1852
+ */
1853
+ function exceptWrapper(handler) {
1854
+ return async (request, handlerParams) => {
1855
+ try {
1856
+ return await handler(request, handlerParams);
1857
+ } catch (error) {
1858
+ const { onNotFound, onUnauthorized } = handlerParams;
1859
+ switch (error?.constructor) {
1860
+ case ItemsNotFoundError: return await onNotFound(request);
1861
+ case UnauthorizedError: return await onUnauthorized(request);
1862
+ default: throw error;
1863
+ }
1864
+ }
1865
+ };
1866
+ }
1867
+ /**
1868
+ * Verifies that a value is defined (not undefined).
1869
+ * @template T The type of the value, excluding undefined.
1870
+ * @param callbacks The value to verify.
1871
+ * @throws {ItemsNotFoundError} If the value is undefined.
1872
+ * @since 1.8.0
1873
+ */
1874
+ const verifyDefined = (callbacks) => {
1875
+ if (callbacks === void 0) throw new ItemsNotFoundError();
1876
+ };
1877
+ /**
1878
+ * Performs authorization if needed based on the authorization predicate.
1879
+ * @template TContextData The context data type.
1880
+ * @param {RequestContext<TContextData>} context The request context.
1881
+ * @param {Record<string, string>} values The parameter values.
1882
+ * @param options Options containing the authorization predicate.
1883
+ * @throws {UnauthorizedError} If authorization fails.
1884
+ * @since 1.8.0
1885
+ */
1886
+ const authIfNeeded = async (context$2, values, { authorizePredicate: authorize = void 0 }) => {
1887
+ if (authorize === void 0) return;
1888
+ const key = (await context$2.getSignedKey())?.clone({}, warning.key) ?? null;
1889
+ const keyOwner = (await context$2.getSignedKeyOwner())?.clone({}, warning.keyOwner) ?? null;
1890
+ if (!await authorize(context$2, values, key, keyOwner)) throw new UnauthorizedError();
1891
+ };
1892
+ /** Warning messages for `authIfNeeded`. */
1893
+ const warning = {
1894
+ key: { $warning: {
1895
+ category: [
1896
+ "fedify",
1897
+ "federation",
1898
+ "collection"
1899
+ ],
1900
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
1901
+ } },
1902
+ keyOwner: { $warning: {
1903
+ category: [
1904
+ "fedify",
1905
+ "federation",
1906
+ "collection"
1907
+ ],
1908
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
1909
+ } }
1910
+ };
1911
+ /**
1912
+ * Appends a cursor parameter to a URL if the cursor exists.
1913
+ * @template Cursor The type of the cursor (string, null, or undefined).
1914
+ * @param {URL} url The base URL to append the cursor to.
1915
+ * @param {string | null | undefined} cursor The cursor value to append.
1916
+ * @returns The URL with cursor appended if cursor is a string, null otherwise.
1917
+ * @since 1.8.0
1918
+ */
1919
+ const appendCursorIfExists = (url, cursor) => {
1920
+ if (cursor === null || cursor === void 0) return null;
1921
+ const copied = new URL(url);
1922
+ copied.searchParams.set("cursor", cursor);
1923
+ return copied;
1924
+ };
1925
+ /**
1926
+ * Creates an HTTP response for ActivityPub data.
1927
+ * @param {unknown} data The data to serialize as JSON-LD.
1928
+ * @returns {Response} An HTTP response with the data as ActivityPub JSON.
1929
+ * @since 1.8.0
1930
+ */
1931
+ const respondAsActivity = (data) => new Response(JSON.stringify(data), { headers: {
1932
+ "Content-Type": "application/activity+json",
1933
+ Vary: "Accept"
1934
+ } });
1935
+ /**
1936
+ * Base class for handler errors.
1937
+ * @since 1.8.0
1938
+ */
1939
+ var HandlerError = class extends Error {
1940
+ constructor(message) {
1941
+ super(message);
1942
+ }
1943
+ /**
1944
+ * Throws this error.
1945
+ * @returns Never returns, always throws.
1946
+ */
1947
+ throw() {
1948
+ throw this;
1949
+ }
1950
+ };
1951
+ /**
1952
+ * Error thrown when items are not found in a collection.
1953
+ * @since 1.8.0
1954
+ */
1955
+ var ItemsNotFoundError = class extends HandlerError {
1956
+ constructor() {
1957
+ super("Items not found in the collection.");
1958
+ }
1959
+ };
1960
+ /**
1961
+ * Error thrown when access to a collection is unauthorized.
1962
+ * @since 1.8.0
1963
+ */
1964
+ var UnauthorizedError = class extends HandlerError {
1965
+ constructor() {
1966
+ super("Unauthorized access to the collection.");
1967
+ }
1968
+ };
1969
+ /**
1970
+ * Responds with the given object in JSON-LD format.
1971
+ *
1972
+ * @param object The object to respond with.
1973
+ * @param options Options.
1974
+ * @since 0.3.0
1975
+ */
1976
+ async function respondWithObject(object, options) {
1977
+ const jsonLd = await object.toJsonLd(options);
1978
+ return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
1979
+ }
1980
+ /**
1981
+ * Responds with the given object in JSON-LD format if the request accepts
1982
+ * JSON-LD.
1983
+ *
1984
+ * @param object The object to respond with.
1985
+ * @param request The request to check for JSON-LD acceptability.
1986
+ * @param options Options.
1987
+ * @since 0.3.0
1988
+ */
1989
+ async function respondWithObjectIfAcceptable(object, request, options) {
1990
+ if (!acceptsJsonLd(request)) return null;
1991
+ const response = await respondWithObject(object, options);
1992
+ response.headers.set("Vary", "Accept");
1993
+ return response;
1994
+ }
1995
+
1996
+ //#endregion
1997
+ //#region src/nodeinfo/handler.ts
1998
+ /**
1999
+ * Handles a NodeInfo request. You would not typically call this function
2000
+ * directly, but instead use {@link Federation.handle} method.
2001
+ * @param request The NodeInfo request to handle.
2002
+ * @param parameters The parameters for handling the request.
2003
+ * @returns The response to the request.
2004
+ */
2005
+ async function handleNodeInfo(_request, { context: context$2, nodeInfoDispatcher }) {
2006
+ const promise = nodeInfoDispatcher(context$2);
2007
+ const nodeInfo = promise instanceof Promise ? await promise : promise;
2008
+ const json = require_types.nodeInfoToJson(nodeInfo);
2009
+ return new Response(JSON.stringify(json), { headers: { "Content-Type": "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\"" } });
2010
+ }
2011
+ /**
2012
+ * Handles a request to `/.well-known/nodeinfo`. You would not typically call
2013
+ * this function directly, but instead use {@link Federation.handle} method.
2014
+ * @param request The request to handle.
2015
+ * @param context The request context.
2016
+ * @returns The response to the request.
2017
+ */
2018
+ function handleNodeInfoJrd(_request, context$2) {
2019
+ const links = [];
2020
+ try {
2021
+ links.push({
2022
+ rel: "http://nodeinfo.diaspora.software/ns/schema/2.1",
2023
+ href: context$2.getNodeInfoUri().href,
2024
+ type: "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\""
2025
+ });
2026
+ } catch (e) {
2027
+ if (!(e instanceof RouterError)) throw e;
2028
+ }
2029
+ const jrd = { links };
2030
+ const response = new Response(JSON.stringify(jrd), { headers: { "Content-Type": "application/jrd+json" } });
2031
+ return Promise.resolve(response);
2032
+ }
2033
+
2034
+ //#endregion
2035
+ //#region src/webfinger/handler.ts
2036
+ const logger = (0, __logtape_logtape.getLogger)([
2037
+ "fedify",
2038
+ "webfinger",
2039
+ "server"
2040
+ ]);
2041
+ /**
2042
+ * Handles a WebFinger request. You would not typically call this function
2043
+ * directly, but instead use {@link Federation.fetch} method.
2044
+ * @param request The WebFinger request to handle.
2045
+ * @param parameters The parameters for handling the request.
2046
+ * @returns The response to the request.
2047
+ */
2048
+ async function handleWebFinger(request, options) {
2049
+ if (options.tracer == null) return await handleWebFingerInternal(request, options);
2050
+ return await options.tracer.startActiveSpan("webfinger.handle", { kind: __opentelemetry_api.SpanKind.SERVER }, async (span) => {
2051
+ try {
2052
+ const response = await handleWebFingerInternal(request, options);
2053
+ span.setStatus({ code: response.ok ? __opentelemetry_api.SpanStatusCode.UNSET : __opentelemetry_api.SpanStatusCode.ERROR });
2054
+ return response;
2055
+ } catch (error) {
2056
+ span.setStatus({
2057
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2058
+ message: String(error)
2059
+ });
2060
+ throw error;
2061
+ } finally {
2062
+ span.end();
2063
+ }
2064
+ });
2065
+ }
2066
+ async function handleWebFingerInternal(request, { context: context$2, host, actorDispatcher, actorHandleMapper, actorAliasMapper, onNotFound, span, webFingerLinksDispatcher }) {
2067
+ if (actorDispatcher == null) {
2068
+ logger.error("Actor dispatcher is not set.");
2069
+ return await onNotFound(request);
2070
+ }
2071
+ const resource = context$2.url.searchParams.get("resource");
2072
+ if (resource == null) return new Response("Missing resource parameter.", { status: 400 });
2073
+ span?.setAttribute("webfinger.resource", resource);
2074
+ let resourceUrl;
2075
+ try {
2076
+ resourceUrl = new URL(resource);
2077
+ } catch (e) {
2078
+ if (e instanceof TypeError) return new Response("Invalid resource URL.", { status: 400 });
2079
+ throw e;
2080
+ }
2081
+ span?.setAttribute("webfinger.resource.scheme", resourceUrl.protocol.replace(/:$/, ""));
2082
+ async function mapUsernameToIdentifier(username) {
2083
+ if (actorHandleMapper == null) {
2084
+ logger.error("No actor handle mapper is set; use the WebFinger username {username} as the actor's internal identifier.", { username });
2085
+ return username;
2086
+ }
2087
+ const identifier$1 = await actorHandleMapper(context$2, username);
2088
+ if (identifier$1 == null) {
2089
+ logger.error("Actor {username} not found.", { username });
2090
+ return null;
2091
+ }
2092
+ return identifier$1;
2093
+ }
2094
+ let identifier = null;
2095
+ const uriParsed = context$2.parseUri(resourceUrl);
2096
+ if (uriParsed?.type != "actor") {
2097
+ const match = /^acct:([^@]+)@([^@]+)$/.exec(resource);
2098
+ if (match == null) {
2099
+ const result = await actorAliasMapper?.(context$2, resourceUrl);
2100
+ if (result == null) return await onNotFound(request);
2101
+ if ("identifier" in result) identifier = result.identifier;
2102
+ else identifier = await mapUsernameToIdentifier(result.username);
2103
+ } else {
2104
+ const portMatch = /:\d+$/.exec(match[2]);
2105
+ const normalizedHost = portMatch == null ? (0, node_url.domainToASCII)(match[2].toLowerCase()) : (0, node_url.domainToASCII)(match[2].substring(0, portMatch.index).toLowerCase()) + portMatch[0];
2106
+ if (normalizedHost != context$2.url.host && normalizedHost != host) return await onNotFound(request);
2107
+ else {
2108
+ identifier = await mapUsernameToIdentifier(match[1]);
2109
+ resourceUrl = new URL(`acct:${match[1]}@${normalizedHost}`);
2110
+ }
2111
+ }
2112
+ } else identifier = uriParsed.identifier;
2113
+ if (identifier == null) return await onNotFound(request);
2114
+ const actor = await actorDispatcher(context$2, identifier);
2115
+ if (actor == null) {
2116
+ logger.error("Actor {identifier} not found.", { identifier });
2117
+ return await onNotFound(request);
2118
+ }
2119
+ const links = [{
2120
+ rel: "self",
2121
+ href: context$2.getActorUri(identifier).href,
2122
+ type: "application/activity+json"
2123
+ }];
2124
+ for (const url of actor.urls) if (url instanceof require_actor.Link && url.href != null) links.push({
2125
+ rel: url.rel ?? "http://webfinger.net/rel/profile-page",
2126
+ href: url.href.href,
2127
+ type: url.mediaType == null ? void 0 : url.mediaType
2128
+ });
2129
+ else if (url instanceof URL) links.push({
2130
+ rel: "http://webfinger.net/rel/profile-page",
2131
+ href: url.href
2132
+ });
2133
+ for await (const image of actor.getIcons()) {
2134
+ if (image.url?.href == null) continue;
2135
+ const link = {
2136
+ rel: "http://webfinger.net/rel/avatar",
2137
+ href: image.url.href.toString()
2138
+ };
2139
+ if (image.mediaType != null) link.type = image.mediaType;
2140
+ links.push(link);
2141
+ }
2142
+ if (webFingerLinksDispatcher != null) {
2143
+ const customLinks = await webFingerLinksDispatcher(context$2, resourceUrl);
2144
+ if (customLinks != null) for (const link of customLinks) links.push(link);
2145
+ }
2146
+ const aliases = [];
2147
+ if (resourceUrl.protocol != "acct:" && actor.preferredUsername != null) {
2148
+ aliases.push(`acct:${actor.preferredUsername}@${host ?? context$2.url.host}`);
2149
+ if (host != null && host !== context$2.url.host) aliases.push(`acct:${actor.preferredUsername}@${context$2.url.host}`);
2150
+ }
2151
+ if (resourceUrl.href !== context$2.getActorUri(identifier).href) aliases.push(context$2.getActorUri(identifier).href);
2152
+ if (resourceUrl.protocol === "acct:" && host != null && host !== context$2.url.host && !resourceUrl.href.endsWith(`@${host}`)) {
2153
+ const username = resourceUrl.href.replace(/^acct:/, "").replace(/@.*$/, "");
2154
+ aliases.push(`acct:${username}@${host}`);
2155
+ }
2156
+ const jrd = {
2157
+ subject: resourceUrl.href,
2158
+ aliases,
2159
+ links
2160
+ };
2161
+ return new Response(JSON.stringify(jrd), { headers: {
2162
+ "Content-Type": "application/jrd+json",
2163
+ "Access-Control-Allow-Origin": "*"
2164
+ } });
2165
+ }
2166
+
2167
+ //#endregion
2168
+ //#region src/federation/retry.ts
2169
+ /**
2170
+ * Creates an exponential backoff retry policy. The delay between retries
2171
+ * starts at the `initialDelay` and is multiplied by the `factor` for each
2172
+ * subsequent retry, up to the `maxDelay`. The policy will give up after
2173
+ * `maxAttempts` attempts. The actual delay is randomized to avoid
2174
+ * synchronization (jitter).
2175
+ * @param options The options for the policy.
2176
+ * @returns The retry policy.
2177
+ * @since 0.12.0
2178
+ */
2179
+ function createExponentialBackoffPolicy(options = {}) {
2180
+ const initialDelay = Temporal.Duration.from(options.initialDelay ?? { seconds: 1 });
2181
+ const maxDelay = Temporal.Duration.from(options.maxDelay ?? { hours: 12 });
2182
+ const maxAttempts = options.maxAttempts ?? 10;
2183
+ const factor = options.factor ?? 2;
2184
+ const jitter = options.jitter ?? true;
2185
+ return ({ attempts }) => {
2186
+ if (attempts >= maxAttempts) return null;
2187
+ let milliseconds = initialDelay.total("millisecond");
2188
+ milliseconds *= factor ** attempts;
2189
+ if (jitter) {
2190
+ milliseconds *= 1 + Math.random();
2191
+ milliseconds = Math.round(milliseconds);
2192
+ }
2193
+ const delay = Temporal.Duration.from({ milliseconds });
2194
+ return Temporal.Duration.compare(delay, maxDelay) > 0 ? maxDelay : delay;
2195
+ };
2196
+ }
2197
+
2198
+ //#endregion
2199
+ //#region src/federation/send.ts
2200
+ /**
2201
+ * Extracts the inbox URLs from recipients.
2202
+ * @param parameters The parameters to extract the inboxes.
2203
+ * See also {@link ExtractInboxesParameters}.
2204
+ * @returns The inboxes as a map of inbox URL to actor URIs.
2205
+ */
2206
+ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2207
+ const inboxes = {};
2208
+ for (const recipient of recipients) {
2209
+ let inbox;
2210
+ let sharedInbox = false;
2211
+ if (preferSharedInbox && recipient.endpoints?.sharedInbox != null) {
2212
+ inbox = recipient.endpoints.sharedInbox;
2213
+ sharedInbox = true;
2214
+ } else inbox = recipient.inboxId;
2215
+ if (inbox != null && recipient.id != null) {
2216
+ if (excludeBaseUris != null && excludeBaseUris.some((u) => u.origin === inbox?.origin)) continue;
2217
+ inboxes[inbox.href] ??= {
2218
+ actorIds: /* @__PURE__ */ new Set(),
2219
+ sharedInbox
2220
+ };
2221
+ inboxes[inbox.href].actorIds.add(recipient.id.href);
2222
+ }
2223
+ }
2224
+ return inboxes;
2225
+ }
2226
+ /**
2227
+ * Sends an {@link Activity} to an inbox.
2228
+ *
2229
+ * @param parameters The parameters for sending the activity.
2230
+ * See also {@link SendActivityParameters}.
2231
+ * @throws {Error} If the activity fails to send.
2232
+ */
2233
+ function sendActivity(options) {
2234
+ const tracerProvider = options.tracerProvider ?? __opentelemetry_api.trace.getTracerProvider();
2235
+ const tracer = tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
2236
+ return tracer.startActiveSpan("activitypub.send_activity", {
2237
+ kind: __opentelemetry_api.SpanKind.CLIENT,
2238
+ attributes: { "activitypub.shared_inbox": options.sharedInbox ?? false }
2239
+ }, async (span) => {
2240
+ if (options.activityId != null) span.setAttribute("activitypub.activity.id", options.activityId);
2241
+ if (options.activityType != null) span.setAttribute("activitypub.activity.type", options.activityType);
2242
+ try {
2243
+ await sendActivityInternal({
2244
+ ...options,
2245
+ tracerProvider
2246
+ });
2247
+ } catch (e) {
2248
+ span.setStatus({
2249
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2250
+ message: String(e)
2251
+ });
2252
+ throw e;
2253
+ } finally {
2254
+ span.end();
2255
+ }
2256
+ });
2257
+ }
2258
+ async function sendActivityInternal({ activity, activityId, keys, inbox, headers, specDeterminer, tracerProvider }) {
2259
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2260
+ "fedify",
2261
+ "federation",
2262
+ "outbox"
2263
+ ]);
2264
+ headers = new Headers(headers);
2265
+ headers.set("Content-Type", "application/activity+json");
2266
+ const request = new Request(inbox, {
2267
+ method: "POST",
2268
+ headers,
2269
+ body: JSON.stringify(activity)
2270
+ });
2271
+ let rsaKey = null;
2272
+ for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
2273
+ rsaKey = key;
2274
+ break;
2275
+ }
2276
+ if (rsaKey == null) logger$1.warn("No supported key found to sign the request to {inbox}. The request will be sent without a signature. In order to sign the request, at least one RSASSA-PKCS1-v1_5 key must be provided.", {
2277
+ inbox: inbox.href,
2278
+ keys: keys.map((pair) => ({
2279
+ keyId: pair.keyId.href,
2280
+ privateKey: pair.privateKey
2281
+ }))
2282
+ });
2283
+ let response;
2284
+ try {
2285
+ response = rsaKey == null ? await fetch(request) : await require_http.doubleKnock(request, rsaKey, {
2286
+ tracerProvider,
2287
+ specDeterminer
2288
+ });
2289
+ } catch (error) {
2290
+ logger$1.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2291
+ activityId,
2292
+ inbox: inbox.href,
2293
+ error
2294
+ });
2295
+ throw error;
2296
+ }
2297
+ if (!response.ok) {
2298
+ let error;
2299
+ try {
2300
+ error = await response.text();
2301
+ } catch (_) {
2302
+ error = "";
2303
+ }
2304
+ logger$1.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
2305
+ activityId,
2306
+ inbox: inbox.href,
2307
+ status: response.status,
2308
+ statusText: response.statusText,
2309
+ error
2310
+ });
2311
+ throw new Error(`Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`);
2312
+ }
2313
+ }
2314
+
2315
+ //#endregion
2316
+ //#region src/federation/middleware.ts
2317
+ /**
2318
+ * Create a new {@link Federation} instance.
2319
+ * @param parameters Parameters for initializing the instance.
2320
+ * @returns A new {@link Federation} instance.
2321
+ * @since 0.10.0
2322
+ */
2323
+ function createFederation(options) {
2324
+ return new FederationImpl(options);
2325
+ }
2326
+ var FederationImpl = class extends FederationBuilderImpl {
2327
+ kv;
2328
+ kvPrefixes;
2329
+ inboxQueue;
2330
+ outboxQueue;
2331
+ fanoutQueue;
2332
+ inboxQueueStarted;
2333
+ outboxQueueStarted;
2334
+ fanoutQueueStarted;
2335
+ manuallyStartQueue;
2336
+ origin;
2337
+ documentLoaderFactory;
2338
+ contextLoaderFactory;
2339
+ authenticatedDocumentLoaderFactory;
2340
+ allowPrivateAddress;
2341
+ userAgent;
2342
+ onOutboxError;
2343
+ signatureTimeWindow;
2344
+ skipSignatureVerification;
2345
+ outboxRetryPolicy;
2346
+ inboxRetryPolicy;
2347
+ activityTransformers;
2348
+ tracerProvider;
2349
+ firstKnock;
2350
+ constructor(options) {
2351
+ super();
2352
+ this.kv = options.kv;
2353
+ this.kvPrefixes = {
2354
+ activityIdempotence: ["_fedify", "activityIdempotence"],
2355
+ remoteDocument: ["_fedify", "remoteDocument"],
2356
+ publicKey: ["_fedify", "publicKey"],
2357
+ httpMessageSignaturesSpec: ["_fedify", "httpMessageSignaturesSpec"],
2358
+ ...options.kvPrefixes ?? {}
2359
+ };
2360
+ if (options.queue == null) {
2361
+ this.inboxQueue = void 0;
2362
+ this.outboxQueue = void 0;
2363
+ this.fanoutQueue = void 0;
2364
+ } else if ("enqueue" in options.queue && "listen" in options.queue) {
2365
+ this.inboxQueue = options.queue;
2366
+ this.outboxQueue = options.queue;
2367
+ this.fanoutQueue = options.queue;
2368
+ } else {
2369
+ this.inboxQueue = options.queue.inbox;
2370
+ this.outboxQueue = options.queue.outbox;
2371
+ this.fanoutQueue = options.queue.fanout;
2372
+ }
2373
+ this.inboxQueueStarted = false;
2374
+ this.outboxQueueStarted = false;
2375
+ this.fanoutQueueStarted = false;
2376
+ this.manuallyStartQueue = options.manuallyStartQueue ?? false;
2377
+ if (options.origin != null) if (typeof options.origin === "string") {
2378
+ if (!URL.canParse(options.origin) || !options.origin.match(/^https?:\/\//)) throw new TypeError(`Invalid origin: ${JSON.stringify(options.origin)}`);
2379
+ const origin = new URL(options.origin);
2380
+ if (!origin.pathname.match(/^\/*$/) || origin.search !== "" || origin.hash !== "") throw new TypeError(`Invalid origin: ${JSON.stringify(options.origin)}`);
2381
+ this.origin = {
2382
+ handleHost: origin.host,
2383
+ webOrigin: origin.origin
2384
+ };
2385
+ } else {
2386
+ const { handleHost, webOrigin } = options.origin;
2387
+ if (!URL.canParse(`https://${handleHost}/`) || handleHost.includes("/")) throw new TypeError(`Invalid origin.handleHost: ${JSON.stringify(handleHost)}`);
2388
+ if (!URL.canParse(webOrigin) || !webOrigin.match(/^https?:\/\//)) throw new TypeError(`Invalid origin.webOrigin: ${JSON.stringify(webOrigin)}`);
2389
+ const webOriginUrl = new URL(webOrigin);
2390
+ if (!webOriginUrl.pathname.match(/^\/*$/) || webOriginUrl.search !== "" || webOriginUrl.hash !== "") throw new TypeError(`Invalid origin.webOrigin: ${JSON.stringify(webOrigin)}`);
2391
+ this.origin = {
2392
+ handleHost: new URL(`https://${handleHost}/`).host,
2393
+ webOrigin: webOriginUrl.origin
2394
+ };
2395
+ }
2396
+ this.router.trailingSlashInsensitive = options.trailingSlashInsensitive ?? false;
2397
+ this._initializeRouter();
2398
+ if (options.allowPrivateAddress || options.userAgent != null) {
2399
+ if (options.documentLoaderFactory != null) throw new TypeError("Cannot set documentLoaderFactory with allowPrivateAddress or userAgent options.");
2400
+ if (options.contextLoaderFactory != null) throw new TypeError("Cannot set contextLoaderFactory with allowPrivateAddress or userAgent options.");
2401
+ if (options.authenticatedDocumentLoaderFactory != null) throw new TypeError("Cannot set authenticatedDocumentLoaderFactory with allowPrivateAddress or userAgent options.");
2402
+ }
2403
+ const { allowPrivateAddress, userAgent } = options;
2404
+ this.allowPrivateAddress = allowPrivateAddress ?? false;
2405
+ this.documentLoaderFactory = options.documentLoaderFactory ?? ((opts) => {
2406
+ return require_kv_cache.kvCache({
2407
+ loader: (0, __fedify_vocab_runtime.getDocumentLoader)({
2408
+ allowPrivateAddress: opts?.allowPrivateAddress ?? allowPrivateAddress,
2409
+ userAgent: opts?.userAgent ?? userAgent
2410
+ }),
2411
+ kv: options.kv,
2412
+ prefix: this.kvPrefixes.remoteDocument
2413
+ });
2414
+ });
2415
+ this.contextLoaderFactory = options.contextLoaderFactory ?? this.documentLoaderFactory;
2416
+ this.authenticatedDocumentLoaderFactory = options.authenticatedDocumentLoaderFactory ?? ((identity) => require_kv_cache.getAuthenticatedDocumentLoader(identity, {
2417
+ allowPrivateAddress,
2418
+ userAgent,
2419
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, options.firstKnock),
2420
+ tracerProvider: this.tracerProvider
2421
+ }));
2422
+ this.userAgent = userAgent;
2423
+ this.onOutboxError = options.onOutboxError;
2424
+ this.signatureTimeWindow = options.signatureTimeWindow ?? { hours: 1 };
2425
+ this.skipSignatureVerification = options.skipSignatureVerification ?? false;
2426
+ this.outboxRetryPolicy = options.outboxRetryPolicy ?? createExponentialBackoffPolicy();
2427
+ this.inboxRetryPolicy = options.inboxRetryPolicy ?? createExponentialBackoffPolicy();
2428
+ this.activityTransformers = options.activityTransformers ?? require_transformers.getDefaultActivityTransformers();
2429
+ this.tracerProvider = options.tracerProvider ?? __opentelemetry_api.trace.getTracerProvider();
2430
+ this.firstKnock = options.firstKnock;
2431
+ }
2432
+ _initializeRouter() {
2433
+ this.router.add("/.well-known/webfinger", "webfinger");
2434
+ this.router.add("/.well-known/nodeinfo", "nodeInfoJrd");
2435
+ }
2436
+ _getTracer() {
2437
+ return this.tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
2438
+ }
2439
+ async _startQueueInternal(ctxData, signal, queue) {
2440
+ if (this.inboxQueue == null && this.outboxQueue == null) return;
2441
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2442
+ "fedify",
2443
+ "federation",
2444
+ "queue"
2445
+ ]);
2446
+ const promises = [];
2447
+ if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
2448
+ logger$1.debug("Starting an inbox task worker.");
2449
+ this.inboxQueueStarted = true;
2450
+ promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2451
+ }
2452
+ if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
2453
+ logger$1.debug("Starting an outbox task worker.");
2454
+ this.outboxQueueStarted = true;
2455
+ promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2456
+ }
2457
+ if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
2458
+ logger$1.debug("Starting a fanout task worker.");
2459
+ this.fanoutQueueStarted = true;
2460
+ promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2461
+ }
2462
+ await Promise.all(promises);
2463
+ }
2464
+ processQueuedTask(contextData, message) {
2465
+ const tracer = this._getTracer();
2466
+ const extractedContext = __opentelemetry_api.propagation.extract(__opentelemetry_api.context.active(), message.traceContext);
2467
+ return (0, __logtape_logtape.withContext)({ messageId: message.id }, async () => {
2468
+ if (message.type === "fanout") await tracer.startActiveSpan("activitypub.fanout", {
2469
+ kind: __opentelemetry_api.SpanKind.CONSUMER,
2470
+ attributes: { "activitypub.activity.type": message.activityType }
2471
+ }, extractedContext, async (span) => {
2472
+ if (message.activityId != null) span.setAttribute("activitypub.activity.id", message.activityId);
2473
+ try {
2474
+ await this.#listenFanoutMessage(contextData, message);
2475
+ } catch (e) {
2476
+ span.setStatus({
2477
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2478
+ message: String(e)
2479
+ });
2480
+ throw e;
2481
+ } finally {
2482
+ span.end();
2483
+ }
2484
+ });
2485
+ else if (message.type === "outbox") await tracer.startActiveSpan("activitypub.outbox", {
2486
+ kind: __opentelemetry_api.SpanKind.CONSUMER,
2487
+ attributes: {
2488
+ "activitypub.activity.type": message.activityType,
2489
+ "activitypub.activity.retries": message.attempt
2490
+ }
2491
+ }, extractedContext, async (span) => {
2492
+ if (message.activityId != null) span.setAttribute("activitypub.activity.id", message.activityId);
2493
+ try {
2494
+ await this.#listenOutboxMessage(contextData, message, span);
2495
+ } catch (e) {
2496
+ span.setStatus({
2497
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2498
+ message: String(e)
2499
+ });
2500
+ throw e;
2501
+ } finally {
2502
+ span.end();
2503
+ }
2504
+ });
2505
+ else if (message.type === "inbox") await tracer.startActiveSpan("activitypub.inbox", {
2506
+ kind: __opentelemetry_api.SpanKind.CONSUMER,
2507
+ attributes: { "activitypub.shared_inbox": message.identifier == null }
2508
+ }, extractedContext, async (span) => {
2509
+ try {
2510
+ await this.#listenInboxMessage(contextData, message, span);
2511
+ } catch (e) {
2512
+ span.setStatus({
2513
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2514
+ message: String(e)
2515
+ });
2516
+ throw e;
2517
+ } finally {
2518
+ span.end();
2519
+ }
2520
+ });
2521
+ });
2522
+ }
2523
+ async #listenFanoutMessage(data, message) {
2524
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2525
+ "fedify",
2526
+ "federation",
2527
+ "fanout"
2528
+ ]);
2529
+ logger$1.debug("Fanning out activity {activityId} to {inboxes} inbox(es)...", {
2530
+ activityId: message.activityId,
2531
+ inboxes: globalThis.Object.keys(message.inboxes).length
2532
+ });
2533
+ const keys = await Promise.all(message.keys.map(async ({ keyId, privateKey }) => ({
2534
+ keyId: new URL(keyId),
2535
+ privateKey: await require_http.importJwk(privateKey, "private")
2536
+ })));
2537
+ const activity = await require_actor.Activity.fromJsonLd(message.activity, {
2538
+ contextLoader: this.contextLoaderFactory({
2539
+ allowPrivateAddress: this.allowPrivateAddress,
2540
+ userAgent: this.userAgent
2541
+ }),
2542
+ documentLoader: this.documentLoaderFactory({
2543
+ allowPrivateAddress: this.allowPrivateAddress,
2544
+ userAgent: this.userAgent
2545
+ }),
2546
+ tracerProvider: this.tracerProvider
2547
+ });
2548
+ const context$2 = this.#createContext(new URL(message.baseUrl), data, { documentLoader: this.documentLoaderFactory({
2549
+ allowPrivateAddress: this.allowPrivateAddress,
2550
+ userAgent: this.userAgent
2551
+ }) });
2552
+ await this.sendActivity(keys, message.inboxes, activity, {
2553
+ collectionSync: message.collectionSync,
2554
+ context: context$2
2555
+ });
2556
+ }
2557
+ async #listenOutboxMessage(_, message, span) {
2558
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2559
+ "fedify",
2560
+ "federation",
2561
+ "outbox"
2562
+ ]);
2563
+ const logData = {
2564
+ keyIds: message.keys.map((pair) => pair.keyId),
2565
+ inbox: message.inbox,
2566
+ activity: message.activity,
2567
+ activityId: message.activityId,
2568
+ attempt: message.attempt,
2569
+ headers: message.headers
2570
+ };
2571
+ const keys = [];
2572
+ let rsaKeyPair = null;
2573
+ for (const { keyId, privateKey } of message.keys) {
2574
+ const pair = {
2575
+ keyId: new URL(keyId),
2576
+ privateKey: await require_http.importJwk(privateKey, "private")
2577
+ };
2578
+ if (rsaKeyPair == null && pair.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") rsaKeyPair = pair;
2579
+ keys.push(pair);
2580
+ }
2581
+ try {
2582
+ await sendActivity({
2583
+ keys,
2584
+ activity: message.activity,
2585
+ activityId: message.activityId,
2586
+ activityType: message.activityType,
2587
+ inbox: new URL(message.inbox),
2588
+ sharedInbox: message.sharedInbox,
2589
+ headers: new Headers(message.headers),
2590
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
2591
+ tracerProvider: this.tracerProvider
2592
+ });
2593
+ } catch (error) {
2594
+ span.setStatus({
2595
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2596
+ message: String(error)
2597
+ });
2598
+ const loaderOptions = this.#getLoaderOptions(message.baseUrl);
2599
+ const activity = await require_actor.Activity.fromJsonLd(message.activity, {
2600
+ contextLoader: this.contextLoaderFactory(loaderOptions),
2601
+ documentLoader: rsaKeyPair == null ? this.documentLoaderFactory(loaderOptions) : this.authenticatedDocumentLoaderFactory(rsaKeyPair, loaderOptions),
2602
+ tracerProvider: this.tracerProvider
2603
+ });
2604
+ try {
2605
+ this.onOutboxError?.(error, activity);
2606
+ } catch (error$1) {
2607
+ logger$1.error("An unexpected error occurred in onError handler:\n{error}", {
2608
+ ...logData,
2609
+ error: error$1
2610
+ });
2611
+ }
2612
+ if (this.outboxQueue?.nativeRetrial) {
2613
+ logger$1.error("Failed to send activity {activityId} to {inbox}; backend will handle retry:\n{error}", {
2614
+ ...logData,
2615
+ error
2616
+ });
2617
+ throw error;
2618
+ }
2619
+ const delay = this.outboxRetryPolicy({
2620
+ elapsedTime: Temporal.Instant.from(message.started).until(Temporal.Now.instant()),
2621
+ attempts: message.attempt
2622
+ });
2623
+ if (delay != null) {
2624
+ logger$1.error("Failed to send activity {activityId} to {inbox} (attempt #{attempt}); retry...:\n{error}", {
2625
+ ...logData,
2626
+ error
2627
+ });
2628
+ await this.outboxQueue?.enqueue({
2629
+ ...message,
2630
+ attempt: message.attempt + 1
2631
+ }, { delay: Temporal.Duration.compare(delay, { seconds: 0 }) < 0 ? Temporal.Duration.from({ seconds: 0 }) : delay });
2632
+ } else logger$1.error("Failed to send activity {activityId} to {inbox} after {attempt} attempts; giving up:\n{error}", {
2633
+ ...logData,
2634
+ error
2635
+ });
2636
+ return;
2637
+ }
2638
+ logger$1.info("Successfully sent activity {activityId} to {inbox}.", { ...logData });
2639
+ }
2640
+ async #listenInboxMessage(ctxData, message, span) {
2641
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2642
+ "fedify",
2643
+ "federation",
2644
+ "inbox"
2645
+ ]);
2646
+ const baseUrl = new URL(message.baseUrl);
2647
+ let context$2 = this.#createContext(baseUrl, ctxData);
2648
+ if (message.identifier != null) context$2 = this.#createContext(baseUrl, ctxData, { documentLoader: await context$2.getDocumentLoader({ identifier: message.identifier }) });
2649
+ else if (this.sharedInboxKeyDispatcher != null) {
2650
+ const identity = await this.sharedInboxKeyDispatcher(context$2);
2651
+ if (identity != null) context$2 = this.#createContext(baseUrl, ctxData, { documentLoader: "identifier" in identity || "username" in identity || "handle" in identity ? await context$2.getDocumentLoader(identity) : context$2.getDocumentLoader(identity) });
2652
+ }
2653
+ const activity = await require_actor.Activity.fromJsonLd(message.activity, context$2);
2654
+ span.setAttribute("activitypub.activity.type", require_actor.getTypeId(activity).href);
2655
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
2656
+ const cacheKey = activity.id == null ? null : [
2657
+ ...this.kvPrefixes.activityIdempotence,
2658
+ context$2.origin,
2659
+ activity.id.href
2660
+ ];
2661
+ if (cacheKey != null) {
2662
+ const cached = await this.kv.get(cacheKey);
2663
+ if (cached === true) {
2664
+ logger$1.debug("Activity {activityId} has already been processed.", {
2665
+ activityId: activity.id?.href,
2666
+ activity: message.activity,
2667
+ recipient: message.identifier
2668
+ });
2669
+ return;
2670
+ }
2671
+ }
2672
+ await this._getTracer().startActiveSpan("activitypub.dispatch_inbox_listener", { kind: __opentelemetry_api.SpanKind.INTERNAL }, async (span$1) => {
2673
+ const dispatched = this.inboxListeners?.dispatchWithClass(activity);
2674
+ if (dispatched == null) {
2675
+ logger$1.error("Unsupported activity type:\n{activity}", {
2676
+ activityId: activity.id?.href,
2677
+ activity: message.activity,
2678
+ recipient: message.identifier,
2679
+ trial: message.attempt
2680
+ });
2681
+ span$1.setStatus({
2682
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2683
+ message: `Unsupported activity type: ${require_actor.getTypeId(activity).href}`
2684
+ });
2685
+ span$1.end();
2686
+ return;
2687
+ }
2688
+ const { class: cls, listener } = dispatched;
2689
+ span$1.updateName(`activitypub.dispatch_inbox_listener ${cls.name}`);
2690
+ try {
2691
+ await listener(context$2.toInboxContext(message.identifier, message.activity, activity.id?.href, require_actor.getTypeId(activity).href), activity);
2692
+ } catch (error) {
2693
+ try {
2694
+ await this.inboxErrorHandler?.(context$2, error);
2695
+ } catch (error$1) {
2696
+ logger$1.error("An unexpected error occurred in inbox error handler:\n{error}", {
2697
+ error: error$1,
2698
+ trial: message.attempt,
2699
+ activityId: activity.id?.href,
2700
+ activity: message.activity,
2701
+ recipient: message.identifier
2702
+ });
2703
+ }
2704
+ if (this.inboxQueue?.nativeRetrial) {
2705
+ logger$1.error("Failed to process the incoming activity {activityId}; backend will handle retry:\n{error}", {
2706
+ error,
2707
+ activityId: activity.id?.href,
2708
+ activity: message.activity,
2709
+ recipient: message.identifier
2710
+ });
2711
+ span$1.setStatus({
2712
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2713
+ message: String(error)
2714
+ });
2715
+ span$1.end();
2716
+ throw error;
2717
+ }
2718
+ const delay = this.inboxRetryPolicy({
2719
+ elapsedTime: Temporal.Instant.from(message.started).until(Temporal.Now.instant()),
2720
+ attempts: message.attempt
2721
+ });
2722
+ if (delay != null) {
2723
+ logger$1.error("Failed to process the incoming activity {activityId} (attempt #{attempt}); retry...:\n{error}", {
2724
+ error,
2725
+ attempt: message.attempt,
2726
+ activityId: activity.id?.href,
2727
+ activity: message.activity,
2728
+ recipient: message.identifier
2729
+ });
2730
+ await this.inboxQueue?.enqueue({
2731
+ ...message,
2732
+ attempt: message.attempt + 1
2733
+ }, { delay: Temporal.Duration.compare(delay, { seconds: 0 }) < 0 ? Temporal.Duration.from({ seconds: 0 }) : delay });
2734
+ } else logger$1.error("Failed to process the incoming activity {activityId} after {trial} attempts; giving up:\n{error}", {
2735
+ error,
2736
+ activityId: activity.id?.href,
2737
+ activity: message.activity,
2738
+ recipient: message.identifier
2739
+ });
2740
+ span$1.setStatus({
2741
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2742
+ message: String(error)
2743
+ });
2744
+ span$1.end();
2745
+ return;
2746
+ }
2747
+ if (cacheKey != null) await this.kv.set(cacheKey, true, { ttl: Temporal.Duration.from({ days: 1 }) });
2748
+ logger$1.info("Activity {activityId} has been processed.", {
2749
+ activityId: activity.id?.href,
2750
+ activity: message.activity,
2751
+ recipient: message.identifier
2752
+ });
2753
+ span$1.end();
2754
+ });
2755
+ }
2756
+ startQueue(contextData, options = {}) {
2757
+ return this._startQueueInternal(contextData, options.signal, options.queue);
2758
+ }
2759
+ createContext(urlOrRequest, contextData) {
2760
+ return urlOrRequest instanceof Request ? this.#createContext(urlOrRequest, contextData) : this.#createContext(urlOrRequest, contextData);
2761
+ }
2762
+ #createContext(urlOrRequest, contextData, opts = {}) {
2763
+ const request = urlOrRequest instanceof Request ? urlOrRequest : null;
2764
+ const url = urlOrRequest instanceof URL ? new URL(urlOrRequest) : new URL(urlOrRequest.url);
2765
+ if (request == null) {
2766
+ url.pathname = "/";
2767
+ url.hash = "";
2768
+ url.search = "";
2769
+ }
2770
+ const loaderOptions = this.#getLoaderOptions(url.origin);
2771
+ const ctxOptions = {
2772
+ url,
2773
+ federation: this,
2774
+ data: contextData,
2775
+ documentLoader: opts.documentLoader ?? this.documentLoaderFactory(loaderOptions),
2776
+ contextLoader: this.contextLoaderFactory(loaderOptions)
2777
+ };
2778
+ if (request == null) return new ContextImpl(ctxOptions);
2779
+ return new RequestContextImpl({
2780
+ ...ctxOptions,
2781
+ request,
2782
+ invokedFromActorDispatcher: opts.invokedFromActorDispatcher,
2783
+ invokedFromObjectDispatcher: opts.invokedFromObjectDispatcher
2784
+ });
2785
+ }
2786
+ #getLoaderOptions(origin) {
2787
+ origin = typeof origin === "string" ? new URL(origin).origin : origin.origin;
2788
+ return {
2789
+ allowPrivateAddress: this.allowPrivateAddress,
2790
+ userAgent: typeof this.userAgent === "string" ? this.userAgent : {
2791
+ url: origin,
2792
+ ...this.userAgent
2793
+ }
2794
+ };
2795
+ }
2796
+ async sendActivity(keys, inboxes, activity, options) {
2797
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2798
+ "fedify",
2799
+ "federation",
2800
+ "outbox"
2801
+ ]);
2802
+ const { immediate, collectionSync, context: ctx } = options;
2803
+ if (activity.id == null) throw new TypeError("The activity to send must have an id.");
2804
+ if (activity.actorId == null) throw new TypeError("The activity to send must have at least one actor property.");
2805
+ else if (keys.length < 1) throw new TypeError("The keys must not be empty.");
2806
+ const contextLoader = this.contextLoaderFactory(this.#getLoaderOptions(ctx.origin));
2807
+ const activityId = activity.id.href;
2808
+ let proofCreated = false;
2809
+ let rsaKey = null;
2810
+ for (const { keyId, privateKey } of keys) {
2811
+ require_http.validateCryptoKey(privateKey, "private");
2812
+ if (rsaKey == null && privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
2813
+ rsaKey = {
2814
+ keyId,
2815
+ privateKey
2816
+ };
2817
+ continue;
2818
+ }
2819
+ if (privateKey.algorithm.name === "Ed25519") {
2820
+ activity = await require_proof.signObject(activity, privateKey, keyId, {
2821
+ contextLoader,
2822
+ tracerProvider: this.tracerProvider
2823
+ });
2824
+ proofCreated = true;
2825
+ }
2826
+ }
2827
+ let jsonLd = await activity.toJsonLd({
2828
+ format: "compact",
2829
+ contextLoader
2830
+ });
2831
+ if (rsaKey == null) logger$1.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.", {
2832
+ activityId,
2833
+ keys: keys.map((pair) => ({
2834
+ keyId: pair.keyId.href,
2835
+ privateKey: pair.privateKey
2836
+ }))
2837
+ });
2838
+ else jsonLd = await require_proof.signJsonLd(jsonLd, rsaKey.privateKey, rsaKey.keyId, {
2839
+ contextLoader,
2840
+ tracerProvider: this.tracerProvider
2841
+ });
2842
+ if (!proofCreated) logger$1.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.", {
2843
+ activityId,
2844
+ keys: keys.map((pair) => ({
2845
+ keyId: pair.keyId.href,
2846
+ privateKey: pair.privateKey
2847
+ }))
2848
+ });
2849
+ if (immediate || this.outboxQueue == null) {
2850
+ if (immediate) logger$1.debug("Sending activity immediately without queue since immediate option is set.", {
2851
+ activityId: activity.id.href,
2852
+ activity: jsonLd
2853
+ });
2854
+ else logger$1.debug("Sending activity immediately without queue since queue is not set.", {
2855
+ activityId: activity.id.href,
2856
+ activity: jsonLd
2857
+ });
2858
+ const promises = [];
2859
+ for (const inbox in inboxes) promises.push(sendActivity({
2860
+ keys,
2861
+ activity: jsonLd,
2862
+ activityId: activity.id?.href,
2863
+ activityType: require_actor.getTypeId(activity).href,
2864
+ inbox: new URL(inbox),
2865
+ sharedInbox: inboxes[inbox].sharedInbox,
2866
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
2867
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
2868
+ tracerProvider: this.tracerProvider
2869
+ }));
2870
+ await Promise.all(promises);
2871
+ return;
2872
+ }
2873
+ logger$1.debug("Enqueuing activity {activityId} to send later.", {
2874
+ activityId: activity.id.href,
2875
+ activity: jsonLd
2876
+ });
2877
+ const keyJwkPairs = [];
2878
+ for (const { keyId, privateKey } of keys) {
2879
+ const privateKeyJwk = await require_http.exportJwk(privateKey);
2880
+ keyJwkPairs.push({
2881
+ keyId: keyId.href,
2882
+ privateKey: privateKeyJwk
2883
+ });
2884
+ }
2885
+ if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
2886
+ const carrier = {};
2887
+ __opentelemetry_api.propagation.inject(__opentelemetry_api.context.active(), carrier);
2888
+ const messages = [];
2889
+ for (const inbox in inboxes) {
2890
+ const message = {
2891
+ type: "outbox",
2892
+ id: crypto.randomUUID(),
2893
+ baseUrl: ctx.origin,
2894
+ keys: keyJwkPairs,
2895
+ activity: jsonLd,
2896
+ activityId: activity.id?.href,
2897
+ activityType: require_actor.getTypeId(activity).href,
2898
+ inbox,
2899
+ sharedInbox: inboxes[inbox].sharedInbox,
2900
+ started: (/* @__PURE__ */ new Date()).toISOString(),
2901
+ attempt: 0,
2902
+ headers: collectionSync == null ? {} : { "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) },
2903
+ traceContext: carrier
2904
+ };
2905
+ messages.push(message);
2906
+ }
2907
+ const { outboxQueue } = this;
2908
+ if (outboxQueue.enqueueMany == null) {
2909
+ const promises = messages.map((m) => outboxQueue.enqueue(m));
2910
+ const results = await Promise.allSettled(promises);
2911
+ const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
2912
+ if (errors.length > 0) {
2913
+ logger$1.error("Failed to enqueue activity {activityId} to send later: {errors}", {
2914
+ activityId: activity.id.href,
2915
+ errors
2916
+ });
2917
+ if (errors.length > 1) throw new AggregateError(errors, `Failed to enqueue activity ${activityId} to send later.`);
2918
+ throw errors[0];
2919
+ }
2920
+ } else try {
2921
+ await outboxQueue.enqueueMany(messages);
2922
+ } catch (error) {
2923
+ logger$1.error("Failed to enqueue activity {activityId} to send later: {error}", {
2924
+ activityId: activity.id.href,
2925
+ error
2926
+ });
2927
+ throw error;
2928
+ }
2929
+ }
2930
+ fetch(request, options) {
2931
+ const requestId = getRequestId(request);
2932
+ return (0, __logtape_logtape.withContext)({ requestId }, async () => {
2933
+ const tracer = this._getTracer();
2934
+ return await tracer.startActiveSpan(request.method, {
2935
+ kind: __opentelemetry_api.SpanKind.SERVER,
2936
+ attributes: {
2937
+ [__opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: request.method,
2938
+ [__opentelemetry_semantic_conventions.ATTR_URL_FULL]: request.url
2939
+ }
2940
+ }, async (span) => {
2941
+ const logger$1 = (0, __logtape_logtape.getLogger)([
2942
+ "fedify",
2943
+ "federation",
2944
+ "http"
2945
+ ]);
2946
+ if (span.isRecording()) for (const [k, v] of request.headers) span.setAttribute((0, __opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_HEADER)(k), [v]);
2947
+ let response;
2948
+ try {
2949
+ response = await this.#fetch(request, {
2950
+ ...options,
2951
+ span,
2952
+ tracer
2953
+ });
2954
+ if (acceptsJsonLd(request)) response.headers.set("Vary", "Accept");
2955
+ } catch (error) {
2956
+ span.setStatus({
2957
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
2958
+ message: `${error}`
2959
+ });
2960
+ span.end();
2961
+ logger$1.error("An error occurred while serving request {method} {url}: {error}", {
2962
+ method: request.method,
2963
+ url: request.url,
2964
+ error
2965
+ });
2966
+ throw error;
2967
+ }
2968
+ if (span.isRecording()) {
2969
+ span.setAttribute(__opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
2970
+ for (const [k, v] of response.headers) span.setAttribute((0, __opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_HEADER)(k), [v]);
2971
+ span.setStatus({
2972
+ code: response.status >= 500 ? __opentelemetry_api.SpanStatusCode.ERROR : __opentelemetry_api.SpanStatusCode.UNSET,
2973
+ message: response.statusText
2974
+ });
2975
+ }
2976
+ span.end();
2977
+ const url = new URL(request.url);
2978
+ const logTpl = "{method} {path}: {status}";
2979
+ const values = {
2980
+ method: request.method,
2981
+ path: `${url.pathname}${url.search}`,
2982
+ url: request.url,
2983
+ status: response.status
2984
+ };
2985
+ if (response.status >= 500) logger$1.error(logTpl, values);
2986
+ else if (response.status >= 400) logger$1.warn(logTpl, values);
2987
+ else logger$1.info(logTpl, values);
2988
+ return response;
2989
+ });
2990
+ });
2991
+ }
2992
+ async #fetch(request, { onNotFound, onNotAcceptable, onUnauthorized, contextData, span, tracer }) {
2993
+ onNotFound ??= notFound;
2994
+ onNotAcceptable ??= notAcceptable;
2995
+ onUnauthorized ??= unauthorized;
2996
+ const url = new URL(request.url);
2997
+ const route = this.router.route(url.pathname);
2998
+ if (route == null) return await onNotFound(request);
2999
+ span.updateName(`${request.method} ${route.template}`);
3000
+ let context$2 = this.#createContext(request, contextData);
3001
+ const routeName = route.name.replace(/:.*$/, "");
3002
+ switch (routeName) {
3003
+ case "webfinger": return await handleWebFinger(request, {
3004
+ context: context$2,
3005
+ host: this.origin?.handleHost,
3006
+ actorDispatcher: this.actorCallbacks?.dispatcher,
3007
+ actorHandleMapper: this.actorCallbacks?.handleMapper,
3008
+ actorAliasMapper: this.actorCallbacks?.aliasMapper,
3009
+ webFingerLinksDispatcher: this.webFingerLinksDispatcher,
3010
+ onNotFound,
3011
+ tracer
3012
+ });
3013
+ case "nodeInfoJrd": return await handleNodeInfoJrd(request, context$2);
3014
+ case "nodeInfo": return await handleNodeInfo(request, {
3015
+ context: context$2,
3016
+ nodeInfoDispatcher: this.nodeInfoDispatcher
3017
+ });
3018
+ }
3019
+ if (request.method !== "POST" && !acceptsJsonLd(request)) return await onNotAcceptable(request);
3020
+ switch (routeName) {
3021
+ case "actor":
3022
+ context$2 = this.#createContext(request, contextData, { invokedFromActorDispatcher: { identifier: route.values.identifier ?? route.values.handle } });
3023
+ return await handleActor(request, {
3024
+ identifier: route.values.identifier ?? route.values.handle,
3025
+ context: context$2,
3026
+ actorDispatcher: this.actorCallbacks?.dispatcher,
3027
+ authorizePredicate: this.actorCallbacks?.authorizePredicate,
3028
+ onUnauthorized,
3029
+ onNotFound
3030
+ });
3031
+ case "object": {
3032
+ const typeId = route.name.replace(/^object:/, "");
3033
+ const callbacks = this.objectCallbacks[typeId];
3034
+ const cls = this.objectTypeIds[typeId];
3035
+ context$2 = this.#createContext(request, contextData, { invokedFromObjectDispatcher: {
3036
+ cls,
3037
+ values: route.values
3038
+ } });
3039
+ return await handleObject(request, {
3040
+ values: route.values,
3041
+ context: context$2,
3042
+ objectDispatcher: callbacks?.dispatcher,
3043
+ authorizePredicate: callbacks?.authorizePredicate,
3044
+ onUnauthorized,
3045
+ onNotFound
3046
+ });
3047
+ }
3048
+ case "outbox": return await handleCollection(request, {
3049
+ name: "outbox",
3050
+ identifier: route.values.identifier ?? route.values.handle,
3051
+ uriGetter: context$2.getOutboxUri.bind(context$2),
3052
+ context: context$2,
3053
+ collectionCallbacks: this.outboxCallbacks,
3054
+ tracerProvider: this.tracerProvider,
3055
+ onUnauthorized,
3056
+ onNotFound
3057
+ });
3058
+ case "inbox":
3059
+ if (request.method !== "POST") return await handleCollection(request, {
3060
+ name: "inbox",
3061
+ identifier: route.values.identifier ?? route.values.handle,
3062
+ uriGetter: context$2.getInboxUri.bind(context$2),
3063
+ context: context$2,
3064
+ collectionCallbacks: this.inboxCallbacks,
3065
+ tracerProvider: this.tracerProvider,
3066
+ onUnauthorized,
3067
+ onNotFound
3068
+ });
3069
+ context$2 = this.#createContext(request, contextData, { documentLoader: await context$2.getDocumentLoader({ identifier: route.values.identifier ?? route.values.handle }) });
3070
+ case "sharedInbox":
3071
+ if (routeName !== "inbox" && this.sharedInboxKeyDispatcher != null) {
3072
+ const identity = await this.sharedInboxKeyDispatcher(context$2);
3073
+ if (identity != null) context$2 = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity || "handle" in identity ? await context$2.getDocumentLoader(identity) : context$2.getDocumentLoader(identity) });
3074
+ }
3075
+ if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
3076
+ return await handleInbox(request, {
3077
+ recipient: route.values.identifier ?? route.values.handle ?? null,
3078
+ context: context$2,
3079
+ inboxContextFactory: context$2.toInboxContext.bind(context$2),
3080
+ kv: this.kv,
3081
+ kvPrefixes: this.kvPrefixes,
3082
+ queue: this.inboxQueue,
3083
+ actorDispatcher: this.actorCallbacks?.dispatcher,
3084
+ inboxListeners: this.inboxListeners,
3085
+ inboxErrorHandler: this.inboxErrorHandler,
3086
+ onNotFound,
3087
+ signatureTimeWindow: this.signatureTimeWindow,
3088
+ skipSignatureVerification: this.skipSignatureVerification,
3089
+ tracerProvider: this.tracerProvider,
3090
+ idempotencyStrategy: this.idempotencyStrategy
3091
+ });
3092
+ case "following": return await handleCollection(request, {
3093
+ name: "following",
3094
+ identifier: route.values.identifier ?? route.values.handle,
3095
+ uriGetter: context$2.getFollowingUri.bind(context$2),
3096
+ context: context$2,
3097
+ collectionCallbacks: this.followingCallbacks,
3098
+ tracerProvider: this.tracerProvider,
3099
+ onUnauthorized,
3100
+ onNotFound
3101
+ });
3102
+ case "followers": {
3103
+ let baseUrl = url.searchParams.get("base-url");
3104
+ if (baseUrl != null) try {
3105
+ baseUrl = `${new URL(baseUrl).origin}/`;
3106
+ } catch {
3107
+ baseUrl = null;
3108
+ }
3109
+ return await handleCollection(request, {
3110
+ name: "followers",
3111
+ identifier: route.values.identifier ?? route.values.handle,
3112
+ uriGetter: baseUrl == null ? context$2.getFollowersUri.bind(context$2) : (identifier) => {
3113
+ const uri = context$2.getFollowersUri(identifier);
3114
+ uri.searchParams.set("base-url", baseUrl);
3115
+ return uri;
3116
+ },
3117
+ context: context$2,
3118
+ filter: baseUrl != null ? new URL(baseUrl) : void 0,
3119
+ filterPredicate: baseUrl != null ? (i) => (i instanceof URL ? i.href : i.id?.href ?? "").startsWith(baseUrl) : void 0,
3120
+ collectionCallbacks: this.followersCallbacks,
3121
+ tracerProvider: this.tracerProvider,
3122
+ onUnauthorized,
3123
+ onNotFound
3124
+ });
3125
+ }
3126
+ case "liked": return await handleCollection(request, {
3127
+ name: "liked",
3128
+ identifier: route.values.identifier ?? route.values.handle,
3129
+ uriGetter: context$2.getLikedUri.bind(context$2),
3130
+ context: context$2,
3131
+ collectionCallbacks: this.likedCallbacks,
3132
+ tracerProvider: this.tracerProvider,
3133
+ onUnauthorized,
3134
+ onNotFound
3135
+ });
3136
+ case "featured": return await handleCollection(request, {
3137
+ name: "featured",
3138
+ identifier: route.values.identifier ?? route.values.handle,
3139
+ uriGetter: context$2.getFeaturedUri.bind(context$2),
3140
+ context: context$2,
3141
+ collectionCallbacks: this.featuredCallbacks,
3142
+ tracerProvider: this.tracerProvider,
3143
+ onUnauthorized,
3144
+ onNotFound
3145
+ });
3146
+ case "featuredTags": return await handleCollection(request, {
3147
+ name: "featured tags",
3148
+ identifier: route.values.identifier ?? route.values.handle,
3149
+ uriGetter: context$2.getFeaturedTagsUri.bind(context$2),
3150
+ context: context$2,
3151
+ collectionCallbacks: this.featuredTagsCallbacks,
3152
+ tracerProvider: this.tracerProvider,
3153
+ onUnauthorized,
3154
+ onNotFound
3155
+ });
3156
+ case "collection": {
3157
+ const name = route.name.replace(/^collection:/, "");
3158
+ const callbacks = this.collectionCallbacks[name];
3159
+ return await handleCustomCollection(request, {
3160
+ name,
3161
+ context: context$2,
3162
+ values: route.values,
3163
+ collectionCallbacks: callbacks,
3164
+ tracerProvider: this.tracerProvider,
3165
+ onUnauthorized,
3166
+ onNotFound
3167
+ });
3168
+ }
3169
+ case "orderedCollection": {
3170
+ const name = route.name.replace(/^orderedCollection:/, "");
3171
+ const callbacks = this.collectionCallbacks[name];
3172
+ return await handleOrderedCollection(request, {
3173
+ name,
3174
+ context: context$2,
3175
+ values: route.values,
3176
+ collectionCallbacks: callbacks,
3177
+ tracerProvider: this.tracerProvider,
3178
+ onUnauthorized,
3179
+ onNotFound
3180
+ });
3181
+ }
3182
+ default: {
3183
+ const response = onNotFound(request);
3184
+ return response instanceof Promise ? await response : response;
3185
+ }
3186
+ }
3187
+ }
3188
+ };
3189
+ const FANOUT_THRESHOLD = 5;
3190
+ var ContextImpl = class ContextImpl {
3191
+ url;
3192
+ federation;
3193
+ data;
3194
+ documentLoader;
3195
+ contextLoader;
3196
+ invokedFromActorKeyPairsDispatcher;
3197
+ constructor({ url, federation, data, documentLoader, contextLoader, invokedFromActorKeyPairsDispatcher }) {
3198
+ this.url = url;
3199
+ this.federation = federation;
3200
+ this.data = data;
3201
+ this.documentLoader = documentLoader;
3202
+ this.contextLoader = contextLoader;
3203
+ this.invokedFromActorKeyPairsDispatcher = invokedFromActorKeyPairsDispatcher;
3204
+ }
3205
+ clone(data) {
3206
+ return new ContextImpl({
3207
+ url: this.url,
3208
+ federation: this.federation,
3209
+ data,
3210
+ documentLoader: this.documentLoader,
3211
+ contextLoader: this.contextLoader,
3212
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
3213
+ });
3214
+ }
3215
+ toInboxContext(recipient, activity, activityId, activityType) {
3216
+ return new InboxContextImpl(recipient, activity, activityId, activityType, {
3217
+ url: this.url,
3218
+ federation: this.federation,
3219
+ data: this.data,
3220
+ documentLoader: this.documentLoader,
3221
+ contextLoader: this.contextLoader,
3222
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
3223
+ });
3224
+ }
3225
+ get hostname() {
3226
+ return this.url.hostname;
3227
+ }
3228
+ get host() {
3229
+ return this.url.host;
3230
+ }
3231
+ get origin() {
3232
+ return this.url.origin;
3233
+ }
3234
+ get canonicalOrigin() {
3235
+ return this.federation.origin?.webOrigin ?? this.origin;
3236
+ }
3237
+ get tracerProvider() {
3238
+ return this.federation.tracerProvider;
3239
+ }
3240
+ getNodeInfoUri() {
3241
+ const path = this.federation.router.build("nodeInfo", {});
3242
+ if (path == null) throw new RouterError("No NodeInfo dispatcher registered.");
3243
+ return new URL(path, this.canonicalOrigin);
3244
+ }
3245
+ getActorUri(identifier) {
3246
+ const path = this.federation.router.build("actor", {
3247
+ identifier,
3248
+ handle: identifier
3249
+ });
3250
+ if (path == null) throw new RouterError("No actor dispatcher registered.");
3251
+ return new URL(path, this.canonicalOrigin);
3252
+ }
3253
+ getObjectUri(cls, values) {
3254
+ const callbacks = this.federation.objectCallbacks[cls.typeId.href];
3255
+ if (callbacks == null) throw new RouterError("No object dispatcher registered.");
3256
+ for (const param of callbacks.parameters) if (!(param in values)) throw new TypeError(`Missing parameter: ${param}`);
3257
+ const path = this.federation.router.build(`object:${cls.typeId.href}`, values);
3258
+ if (path == null) throw new RouterError("No object dispatcher registered.");
3259
+ return new URL(path, this.canonicalOrigin);
3260
+ }
3261
+ getOutboxUri(identifier) {
3262
+ const path = this.federation.router.build("outbox", {
3263
+ identifier,
3264
+ handle: identifier
3265
+ });
3266
+ if (path == null) throw new RouterError("No outbox dispatcher registered.");
3267
+ return new URL(path, this.canonicalOrigin);
3268
+ }
3269
+ getInboxUri(identifier) {
3270
+ if (identifier == null) {
3271
+ const path$1 = this.federation.router.build("sharedInbox", {});
3272
+ if (path$1 == null) throw new RouterError("No shared inbox path registered.");
3273
+ return new URL(path$1, this.canonicalOrigin);
3274
+ }
3275
+ const path = this.federation.router.build("inbox", {
3276
+ identifier,
3277
+ handle: identifier
3278
+ });
3279
+ if (path == null) throw new RouterError("No inbox path registered.");
3280
+ return new URL(path, this.canonicalOrigin);
3281
+ }
3282
+ getFollowingUri(identifier) {
3283
+ const path = this.federation.router.build("following", {
3284
+ identifier,
3285
+ handle: identifier
3286
+ });
3287
+ if (path == null) throw new RouterError("No following collection path registered.");
3288
+ return new URL(path, this.canonicalOrigin);
3289
+ }
3290
+ getFollowersUri(identifier) {
3291
+ const path = this.federation.router.build("followers", {
3292
+ identifier,
3293
+ handle: identifier
3294
+ });
3295
+ if (path == null) throw new RouterError("No followers collection path registered.");
3296
+ return new URL(path, this.canonicalOrigin);
3297
+ }
3298
+ getLikedUri(identifier) {
3299
+ const path = this.federation.router.build("liked", {
3300
+ identifier,
3301
+ handle: identifier
3302
+ });
3303
+ if (path == null) throw new RouterError("No liked collection path registered.");
3304
+ return new URL(path, this.canonicalOrigin);
3305
+ }
3306
+ getFeaturedUri(identifier) {
3307
+ const path = this.federation.router.build("featured", {
3308
+ identifier,
3309
+ handle: identifier
3310
+ });
3311
+ if (path == null) throw new RouterError("No featured collection path registered.");
3312
+ return new URL(path, this.canonicalOrigin);
3313
+ }
3314
+ getFeaturedTagsUri(identifier) {
3315
+ const path = this.federation.router.build("featuredTags", {
3316
+ identifier,
3317
+ handle: identifier
3318
+ });
3319
+ if (path == null) throw new RouterError("No featured tags collection path registered.");
3320
+ return new URL(path, this.canonicalOrigin);
3321
+ }
3322
+ getCollectionUri(name, values) {
3323
+ const path = this.federation.getCollectionPath(name, values);
3324
+ if (path === null) throw new RouterError(`No collection dispatcher registered for "${String(name)}".`);
3325
+ return new URL(path, this.canonicalOrigin);
3326
+ }
3327
+ parseUri(uri) {
3328
+ if (uri == null) return null;
3329
+ if (uri.origin !== this.origin && uri.origin !== this.canonicalOrigin) return null;
3330
+ const route = this.federation.router.route(uri.pathname);
3331
+ const logger$1 = (0, __logtape_logtape.getLogger)(["fedify", "federation"]);
3332
+ if (route == null) return null;
3333
+ else if (route.name === "sharedInbox") return {
3334
+ type: "inbox",
3335
+ identifier: void 0,
3336
+ get handle() {
3337
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3338
+ return void 0;
3339
+ }
3340
+ };
3341
+ const identifier = "identifier" in route.values ? route.values.identifier : route.values.handle;
3342
+ if (route.name === "actor") return {
3343
+ type: "actor",
3344
+ identifier,
3345
+ get handle() {
3346
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3347
+ return identifier;
3348
+ }
3349
+ };
3350
+ else if (route.name.startsWith("object:")) {
3351
+ const typeId = route.name.replace(/^object:/, "");
3352
+ return {
3353
+ type: "object",
3354
+ class: this.federation.objectTypeIds[typeId],
3355
+ typeId: new URL(typeId),
3356
+ values: route.values
3357
+ };
3358
+ } else if (route.name === "inbox") return {
3359
+ type: "inbox",
3360
+ identifier,
3361
+ get handle() {
3362
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3363
+ return identifier;
3364
+ }
3365
+ };
3366
+ else if (route.name === "outbox") return {
3367
+ type: "outbox",
3368
+ identifier,
3369
+ get handle() {
3370
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3371
+ return identifier;
3372
+ }
3373
+ };
3374
+ else if (route.name === "following") return {
3375
+ type: "following",
3376
+ identifier,
3377
+ get handle() {
3378
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3379
+ return identifier;
3380
+ }
3381
+ };
3382
+ else if (route.name === "followers") return {
3383
+ type: "followers",
3384
+ identifier,
3385
+ get handle() {
3386
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3387
+ return identifier;
3388
+ }
3389
+ };
3390
+ else if (route.name === "liked") return {
3391
+ type: "liked",
3392
+ identifier,
3393
+ get handle() {
3394
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3395
+ return identifier;
3396
+ }
3397
+ };
3398
+ else if (route.name === "featured") return {
3399
+ type: "featured",
3400
+ identifier,
3401
+ get handle() {
3402
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3403
+ return identifier;
3404
+ }
3405
+ };
3406
+ else if (route.name === "featuredTags") return {
3407
+ type: "featuredTags",
3408
+ identifier,
3409
+ get handle() {
3410
+ logger$1.warn("The ParseUriResult.handle property is deprecated; use ParseUriResult.identifier instead.");
3411
+ return identifier;
3412
+ }
3413
+ };
3414
+ const collectionTypes = ["collection", "orderedCollection"];
3415
+ const collectionRegex = /* @__PURE__ */ new RegExp(`^(${collectionTypes.join("|")}):(.*)$`);
3416
+ const match = route.name.match(collectionRegex);
3417
+ if (match !== null) {
3418
+ const [, type, name] = match;
3419
+ const cls = this.federation.collectionTypeIds[name];
3420
+ return {
3421
+ type,
3422
+ name,
3423
+ class: cls,
3424
+ typeId: cls.typeId,
3425
+ values: route.values
3426
+ };
3427
+ }
3428
+ return null;
3429
+ }
3430
+ async getActorKeyPairs(identifier) {
3431
+ const logger$1 = (0, __logtape_logtape.getLogger)([
3432
+ "fedify",
3433
+ "federation",
3434
+ "actor"
3435
+ ]);
3436
+ if (this.invokedFromActorKeyPairsDispatcher != null) logger$1.warn("Context.getActorKeyPairs({getActorKeyPairsIdentifier}) method is invoked from the actor key pairs dispatcher ({actorKeyPairsDispatcherIdentifier}); this may cause an infinite loop.", {
3437
+ getActorKeyPairsIdentifier: identifier,
3438
+ actorKeyPairsDispatcherIdentifier: this.invokedFromActorKeyPairsDispatcher.identifier
3439
+ });
3440
+ let keyPairs;
3441
+ try {
3442
+ keyPairs = await this.getKeyPairsFromIdentifier(identifier);
3443
+ } catch (_) {
3444
+ logger$1.warn("No actor key pairs dispatcher registered.");
3445
+ return [];
3446
+ }
3447
+ const owner = this.getActorUri(identifier);
3448
+ const result = [];
3449
+ for (const keyPair of keyPairs) {
3450
+ const newPair = {
3451
+ ...keyPair,
3452
+ cryptographicKey: new require_actor.CryptographicKey({
3453
+ id: keyPair.keyId,
3454
+ owner,
3455
+ publicKey: keyPair.publicKey
3456
+ }),
3457
+ multikey: new require_actor.Multikey({
3458
+ id: keyPair.keyId,
3459
+ controller: owner,
3460
+ publicKey: keyPair.publicKey
3461
+ })
3462
+ };
3463
+ result.push(newPair);
3464
+ }
3465
+ return result;
3466
+ }
3467
+ async getKeyPairsFromIdentifier(identifier) {
3468
+ const logger$1 = (0, __logtape_logtape.getLogger)([
3469
+ "fedify",
3470
+ "federation",
3471
+ "actor"
3472
+ ]);
3473
+ if (this.federation.actorCallbacks?.keyPairsDispatcher == null) throw new Error("No actor key pairs dispatcher registered.");
3474
+ let actorUri;
3475
+ try {
3476
+ actorUri = this.getActorUri(identifier);
3477
+ } catch (error) {
3478
+ if (error instanceof RouterError) {
3479
+ logger$1.warn(error.message);
3480
+ return [];
3481
+ }
3482
+ throw error;
3483
+ }
3484
+ const keyPairs = await this.federation.actorCallbacks?.keyPairsDispatcher(new ContextImpl({
3485
+ ...this,
3486
+ invokedFromActorKeyPairsDispatcher: { identifier }
3487
+ }), identifier);
3488
+ if (keyPairs.length < 1) logger$1.warn("No key pairs found for actor {identifier}.", { identifier });
3489
+ let i = 0;
3490
+ const result = [];
3491
+ for (const keyPair of keyPairs) {
3492
+ result.push({
3493
+ ...keyPair,
3494
+ keyId: new URL(i == 0 ? `#main-key` : `#key-${i + 1}`, actorUri)
3495
+ });
3496
+ i++;
3497
+ }
3498
+ return result;
3499
+ }
3500
+ async getRsaKeyPairFromIdentifier(identifier) {
3501
+ const keyPairs = await this.getKeyPairsFromIdentifier(identifier);
3502
+ for (const keyPair of keyPairs) {
3503
+ const { privateKey } = keyPair;
3504
+ if (privateKey.algorithm.name === "RSASSA-PKCS1-v1_5" && privateKey.algorithm.hash.name === "SHA-256") return keyPair;
3505
+ }
3506
+ (0, __logtape_logtape.getLogger)([
3507
+ "fedify",
3508
+ "federation",
3509
+ "actor"
3510
+ ]).warn("No RSA-PKCS#1-v1.5 SHA-256 key found for actor {identifier}.", { identifier });
3511
+ return null;
3512
+ }
3513
+ getDocumentLoader(identity) {
3514
+ if ("identifier" in identity || "username" in identity || "handle" in identity) {
3515
+ let identifierPromise;
3516
+ if ("username" in identity || "handle" in identity) {
3517
+ let username;
3518
+ if ("username" in identity) username = identity.username;
3519
+ else {
3520
+ username = identity.handle;
3521
+ (0, __logtape_logtape.getLogger)([
3522
+ "fedify",
3523
+ "runtime",
3524
+ "docloader"
3525
+ ]).warn("The \"handle\" property is deprecated; use \"identifier\" or \"username\" instead.", { identity });
3526
+ }
3527
+ const mapper = this.federation.actorCallbacks?.handleMapper;
3528
+ if (mapper == null) identifierPromise = Promise.resolve(username);
3529
+ else {
3530
+ const identifier = mapper(this, username);
3531
+ identifierPromise = identifier instanceof Promise ? identifier : Promise.resolve(identifier);
3532
+ }
3533
+ } else identifierPromise = Promise.resolve(identity.identifier);
3534
+ return identifierPromise.then((identifier) => {
3535
+ if (identifier == null) return this.documentLoader;
3536
+ const keyPair = this.getRsaKeyPairFromIdentifier(identifier);
3537
+ return keyPair.then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
3538
+ });
3539
+ }
3540
+ return this.federation.authenticatedDocumentLoaderFactory(identity);
3541
+ }
3542
+ lookupObject(identifier, options = {}) {
3543
+ return require_vocab.lookupObject(identifier, {
3544
+ ...options,
3545
+ documentLoader: options.documentLoader ?? this.documentLoader,
3546
+ contextLoader: options.contextLoader ?? this.contextLoader,
3547
+ userAgent: options.userAgent ?? this.federation.userAgent,
3548
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
3549
+ allowPrivateAddress: this.federation.allowPrivateAddress
3550
+ });
3551
+ }
3552
+ traverseCollection(collection, options = {}) {
3553
+ return require_vocab.traverseCollection(collection, {
3554
+ ...options,
3555
+ documentLoader: options.documentLoader ?? this.documentLoader,
3556
+ contextLoader: options.contextLoader ?? this.contextLoader
3557
+ });
3558
+ }
3559
+ lookupNodeInfo(url, options = {}) {
3560
+ return options.parse === "none" ? require_types.getNodeInfo(url, {
3561
+ parse: "none",
3562
+ direct: options.direct,
3563
+ userAgent: options?.userAgent ?? this.federation.userAgent
3564
+ }) : require_types.getNodeInfo(url, {
3565
+ parse: options.parse,
3566
+ direct: options.direct,
3567
+ userAgent: options?.userAgent ?? this.federation.userAgent
3568
+ });
3569
+ }
3570
+ lookupWebFinger(resource, options = {}) {
3571
+ return require_lookup.lookupWebFinger(resource, {
3572
+ ...options,
3573
+ userAgent: options.userAgent ?? this.federation.userAgent,
3574
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
3575
+ allowPrivateAddress: this.federation.allowPrivateAddress
3576
+ });
3577
+ }
3578
+ sendActivity(sender, recipients, activity, options = {}) {
3579
+ const tracer = this.tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
3580
+ return tracer.startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
3581
+ kind: this.federation.outboxQueue == null || options.immediate ? __opentelemetry_api.SpanKind.CLIENT : __opentelemetry_api.SpanKind.PRODUCER,
3582
+ attributes: {
3583
+ "activitypub.activity.type": require_actor.getTypeId(activity).href,
3584
+ "activitypub.activity.to": activity.toIds.map((to) => to.href),
3585
+ "activitypub.activity.cc": activity.toIds.map((cc) => cc.href),
3586
+ "activitypub.activity.bto": activity.btoIds.map((bto) => bto.href),
3587
+ "activitypub.activity.bcc": activity.toIds.map((bcc) => bcc.href)
3588
+ }
3589
+ }, async (span) => {
3590
+ try {
3591
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
3592
+ await this.sendActivityInternal(sender, recipients, activity, options, span);
3593
+ } catch (e) {
3594
+ span.setStatus({
3595
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
3596
+ message: String(e)
3597
+ });
3598
+ throw e;
3599
+ } finally {
3600
+ span.end();
3601
+ }
3602
+ });
3603
+ }
3604
+ async sendActivityInternal(sender, recipients, activity, options, span) {
3605
+ const logger$1 = (0, __logtape_logtape.getLogger)([
3606
+ "fedify",
3607
+ "federation",
3608
+ "outbox"
3609
+ ]);
3610
+ let keys;
3611
+ let identifier = null;
3612
+ if ("identifier" in sender || "username" in sender || "handle" in sender) {
3613
+ if ("identifier" in sender) identifier = sender.identifier;
3614
+ else {
3615
+ let username;
3616
+ if ("username" in sender) username = sender.username;
3617
+ else {
3618
+ username = sender.handle;
3619
+ logger$1.warn("The \"handle\" property for the sender parameter is deprecated; use \"identifier\" or \"username\" instead.", { sender });
3620
+ }
3621
+ if (this.federation.actorCallbacks?.handleMapper == null) identifier = username;
3622
+ else {
3623
+ const mapped = await this.federation.actorCallbacks.handleMapper(this, username);
3624
+ if (mapped == null) throw new Error(`No actor found for the given username ${JSON.stringify(username)}.`);
3625
+ identifier = mapped;
3626
+ }
3627
+ }
3628
+ span.setAttribute("fedify.actor.identifier", identifier);
3629
+ keys = await this.getKeyPairsFromIdentifier(identifier);
3630
+ if (keys.length < 1) throw new Error(`No key pair found for actor ${JSON.stringify(identifier)}.`);
3631
+ } else if (Array.isArray(sender)) {
3632
+ if (sender.length < 1) throw new Error("The sender's key pairs are empty.");
3633
+ keys = sender;
3634
+ } else keys = [sender];
3635
+ if (keys.length < 1) throw new TypeError("The sender's keys must not be empty.");
3636
+ for (const { privateKey } of keys) require_http.validateCryptoKey(privateKey, "private");
3637
+ const opts = { context: this };
3638
+ let expandedRecipients;
3639
+ if (Array.isArray(recipients)) expandedRecipients = recipients;
3640
+ else if (recipients === "followers") {
3641
+ if (identifier == null) throw new Error("If recipients is \"followers\", sender must be an actor identifier or username.");
3642
+ expandedRecipients = [];
3643
+ for await (const recipient of this.getFollowers(identifier)) expandedRecipients.push(recipient);
3644
+ if (options.syncCollection) try {
3645
+ opts.collectionSync = this.getFollowersUri(identifier).href;
3646
+ } catch (error) {
3647
+ if (error instanceof RouterError) opts.collectionSync = void 0;
3648
+ else throw error;
3649
+ }
3650
+ } else expandedRecipients = [recipients];
3651
+ span.setAttribute("activitypub.inboxes", expandedRecipients.length);
3652
+ for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
3653
+ span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
3654
+ if (activity.actorId == null) {
3655
+ logger$1.error("Activity {activityId} to send does not have an actor.", {
3656
+ activity,
3657
+ activityId: activity?.id?.href
3658
+ });
3659
+ throw new TypeError("The activity to send must have at least one actor property.");
3660
+ }
3661
+ const inboxes = extractInboxes({
3662
+ recipients: expandedRecipients,
3663
+ preferSharedInbox: options.preferSharedInbox,
3664
+ excludeBaseUris: options.excludeBaseUris
3665
+ });
3666
+ logger$1.debug("Sending activity {activityId} to inboxes:\n{inboxes}", {
3667
+ inboxes: globalThis.Object.keys(inboxes),
3668
+ activityId: activity.id?.href,
3669
+ activity
3670
+ });
3671
+ if (this.federation.fanoutQueue == null || options.immediate || options.fanout === "skip" || (options.fanout ?? "auto") === "auto" && globalThis.Object.keys(inboxes).length < FANOUT_THRESHOLD) {
3672
+ await this.federation.sendActivity(keys, inboxes, activity, opts);
3673
+ return;
3674
+ }
3675
+ const keyJwkPairs = await Promise.all(keys.map(async ({ keyId, privateKey }) => ({
3676
+ keyId: keyId.href,
3677
+ privateKey: await require_http.exportJwk(privateKey)
3678
+ })));
3679
+ const carrier = {};
3680
+ __opentelemetry_api.propagation.inject(__opentelemetry_api.context.active(), carrier);
3681
+ const message = {
3682
+ type: "fanout",
3683
+ id: crypto.randomUUID(),
3684
+ baseUrl: this.origin,
3685
+ keys: keyJwkPairs,
3686
+ inboxes: globalThis.Object.fromEntries(globalThis.Object.entries(inboxes).map(([k, { actorIds, sharedInbox }]) => [k, {
3687
+ actorIds: [...actorIds],
3688
+ sharedInbox
3689
+ }])),
3690
+ activity: await activity.toJsonLd({
3691
+ format: "compact",
3692
+ contextLoader: this.contextLoader
3693
+ }),
3694
+ activityId: activity.id?.href,
3695
+ activityType: require_actor.getTypeId(activity).href,
3696
+ collectionSync: opts.collectionSync,
3697
+ traceContext: carrier
3698
+ };
3699
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
3700
+ this.federation.fanoutQueue.enqueue(message);
3701
+ }
3702
+ async *getFollowers(identifier) {
3703
+ if (this.federation.followersCallbacks == null) throw new Error("No followers collection dispatcher registered.");
3704
+ const result = await this.federation.followersCallbacks.dispatcher(this, identifier, null);
3705
+ if (result != null) {
3706
+ for (const recipient of result.items) yield recipient;
3707
+ return;
3708
+ }
3709
+ if (this.federation.followersCallbacks.firstCursor == null) throw new Error("No first cursor dispatcher registered for followers collection.");
3710
+ let cursor = await this.federation.followersCallbacks.firstCursor(this, identifier);
3711
+ if (cursor != null) (0, __logtape_logtape.getLogger)([
3712
+ "fedify",
3713
+ "federation",
3714
+ "outbox"
3715
+ ]).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 });
3716
+ while (cursor != null) {
3717
+ const result$1 = await this.federation.followersCallbacks.dispatcher(this, identifier, cursor);
3718
+ if (result$1 == null) break;
3719
+ for (const recipient of result$1.items) yield recipient;
3720
+ cursor = result$1.nextCursor ?? null;
3721
+ }
3722
+ }
3723
+ routeActivity(recipient, activity, options = {}) {
3724
+ const tracerProvider = this.tracerProvider ?? this.tracerProvider;
3725
+ const tracer = tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
3726
+ return tracer.startActiveSpan("activitypub.inbox", {
3727
+ kind: this.federation.inboxQueue == null || options.immediate ? __opentelemetry_api.SpanKind.INTERNAL : __opentelemetry_api.SpanKind.PRODUCER,
3728
+ attributes: { "activitypub.activity.type": require_actor.getTypeId(activity).href }
3729
+ }, async (span) => {
3730
+ if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
3731
+ if (activity.toIds.length > 0) span.setAttribute("activitypub.activity.to", activity.toIds.map((to) => to.href));
3732
+ if (activity.ccIds.length > 0) span.setAttribute("activitypub.activity.cc", activity.ccIds.map((cc) => cc.href));
3733
+ if (activity.btoIds.length > 0) span.setAttribute("activitypub.activity.bto", activity.btoIds.map((bto) => bto.href));
3734
+ if (activity.bccIds.length > 0) span.setAttribute("activitypub.activity.bcc", activity.bccIds.map((bcc) => bcc.href));
3735
+ try {
3736
+ const ok = await this.routeActivityInternal(recipient, activity, options, span);
3737
+ if (ok) {
3738
+ span.setAttribute("activitypub.shared_inbox", recipient == null);
3739
+ if (recipient != null) span.setAttribute("fedify.inbox.recipient", recipient);
3740
+ } else span.setStatus({ code: __opentelemetry_api.SpanStatusCode.ERROR });
3741
+ return ok;
3742
+ } catch (e) {
3743
+ span.setStatus({
3744
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
3745
+ message: String(e)
3746
+ });
3747
+ throw e;
3748
+ } finally {
3749
+ span.end();
3750
+ }
3751
+ });
3752
+ }
3753
+ async routeActivityInternal(recipient, activity, options = {}, span) {
3754
+ const logger$1 = (0, __logtape_logtape.getLogger)([
3755
+ "fedify",
3756
+ "federation",
3757
+ "inbox"
3758
+ ]);
3759
+ const contextLoader = options.contextLoader ?? this.contextLoader;
3760
+ const json = await activity.toJsonLd({ contextLoader });
3761
+ const keyCache = new KvKeyCache(this.federation.kv, this.federation.kvPrefixes.publicKey, this);
3762
+ const verified = await require_proof.verifyObject(require_actor.Activity, json, {
3763
+ contextLoader,
3764
+ documentLoader: options.documentLoader ?? this.documentLoader,
3765
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
3766
+ keyCache
3767
+ });
3768
+ if (verified == null) {
3769
+ logger$1.debug("Object Integrity Proofs are not verified.", {
3770
+ recipient,
3771
+ activity: json
3772
+ });
3773
+ if (activity.id == null) {
3774
+ logger$1.debug("Activity is missing an ID; unable to fetch.", {
3775
+ recipient,
3776
+ activity: json
3777
+ });
3778
+ return false;
3779
+ }
3780
+ const fetched = await this.lookupObject(activity.id, options);
3781
+ if (fetched == null) {
3782
+ logger$1.debug("Failed to fetch the remote activity object {activityId}.", {
3783
+ recipient,
3784
+ activity: json,
3785
+ activityId: activity.id.href
3786
+ });
3787
+ return false;
3788
+ } else if (!(fetched instanceof require_actor.Activity)) {
3789
+ logger$1.debug("Fetched object is not an Activity.", {
3790
+ recipient,
3791
+ activity: await fetched.toJsonLd({ contextLoader })
3792
+ });
3793
+ return false;
3794
+ } else if (fetched.id?.href !== activity.id.href) {
3795
+ logger$1.debug("Fetched activity object has a different ID; failed to verify.", {
3796
+ recipient,
3797
+ activity: await fetched.toJsonLd({ contextLoader })
3798
+ });
3799
+ return false;
3800
+ } else if (fetched.actorIds.length < 1) {
3801
+ logger$1.debug("Fetched activity object is missing an actor; unable to verify.", {
3802
+ recipient,
3803
+ activity: await fetched.toJsonLd({ contextLoader })
3804
+ });
3805
+ return false;
3806
+ }
3807
+ const activityId = fetched.id;
3808
+ if (!fetched.actorIds.every((actor) => actor.origin === activityId.origin)) {
3809
+ logger$1.debug("Fetched activity object has actors from different origins; unable to verify.", {
3810
+ recipient,
3811
+ activity: await fetched.toJsonLd({ contextLoader })
3812
+ });
3813
+ return false;
3814
+ }
3815
+ logger$1.debug("Successfully fetched the remote activity object {activityId}; ignore the original activity and use the fetched one, which is trustworthy.");
3816
+ activity = fetched;
3817
+ } else logger$1.debug("Object Integrity Proofs are verified.", {
3818
+ recipient,
3819
+ activity: json
3820
+ });
3821
+ const routeResult = await routeActivity({
3822
+ context: this,
3823
+ json,
3824
+ activity,
3825
+ recipient,
3826
+ inboxListeners: this.federation.inboxListeners,
3827
+ inboxContextFactory: this.toInboxContext.bind(this),
3828
+ inboxErrorHandler: this.federation.inboxErrorHandler,
3829
+ kv: this.federation.kv,
3830
+ kvPrefixes: this.federation.kvPrefixes,
3831
+ queue: this.federation.inboxQueue,
3832
+ span,
3833
+ tracerProvider: options.tracerProvider ?? this.tracerProvider,
3834
+ idempotencyStrategy: this.federation.idempotencyStrategy
3835
+ });
3836
+ return routeResult === "alreadyProcessed" || routeResult === "enqueued" || routeResult === "unsupportedActivity" || routeResult === "success";
3837
+ }
3838
+ };
3839
+ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
3840
+ #invokedFromActorDispatcher;
3841
+ #invokedFromObjectDispatcher;
3842
+ request;
3843
+ url = void 0;
3844
+ constructor(options) {
3845
+ super(options);
3846
+ this.#invokedFromActorDispatcher = options.invokedFromActorDispatcher;
3847
+ this.#invokedFromObjectDispatcher = options.invokedFromObjectDispatcher;
3848
+ this.request = options.request;
3849
+ this.url = options.url;
3850
+ }
3851
+ clone(data) {
3852
+ return new RequestContextImpl({
3853
+ url: this.url,
3854
+ federation: this.federation,
3855
+ data,
3856
+ documentLoader: this.documentLoader,
3857
+ contextLoader: this.contextLoader,
3858
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher,
3859
+ invokedFromActorDispatcher: this.#invokedFromActorDispatcher,
3860
+ invokedFromObjectDispatcher: this.#invokedFromObjectDispatcher,
3861
+ request: this.request
3862
+ });
3863
+ }
3864
+ async getActor(identifier) {
3865
+ if (this.federation.actorCallbacks == null || this.federation.actorCallbacks.dispatcher == null) throw new Error("No actor dispatcher registered.");
3866
+ if (this.#invokedFromActorDispatcher != null) (0, __logtape_logtape.getLogger)([
3867
+ "fedify",
3868
+ "federation",
3869
+ "actor"
3870
+ ]).warn("RequestContext.getActor({getActorIdentifier}) is invoked from the actor dispatcher ({actorDispatcherIdentifier}); this may cause an infinite loop.", {
3871
+ getActorIdentifier: identifier,
3872
+ actorDispatcherIdentifier: this.#invokedFromActorDispatcher.identifier
3873
+ });
3874
+ return await this.federation.actorCallbacks.dispatcher(new RequestContextImpl({
3875
+ ...this,
3876
+ invokedFromActorDispatcher: { identifier }
3877
+ }), identifier);
3878
+ }
3879
+ async getObject(cls, values) {
3880
+ const callbacks = this.federation.objectCallbacks[cls.typeId.href];
3881
+ if (callbacks == null) throw new Error("No object dispatcher registered.");
3882
+ for (const param of callbacks.parameters) if (!(param in values)) throw new TypeError(`Missing parameter: ${param}`);
3883
+ if (this.#invokedFromObjectDispatcher != null) (0, __logtape_logtape.getLogger)(["fedify", "federation"]).warn("RequestContext.getObject({getObjectClass}, {getObjectValues}) is invoked from the object dispatcher ({actorDispatcherClass}, {actorDispatcherValues}); this may cause an infinite loop.", {
3884
+ getObjectClass: cls.name,
3885
+ getObjectValues: values,
3886
+ actorDispatcherClass: this.#invokedFromObjectDispatcher.cls.name,
3887
+ actorDispatcherValues: this.#invokedFromObjectDispatcher.values
3888
+ });
3889
+ return await callbacks.dispatcher(new RequestContextImpl({
3890
+ ...this,
3891
+ invokedFromObjectDispatcher: {
3892
+ cls,
3893
+ values
3894
+ }
3895
+ }), values);
3896
+ }
3897
+ #signedKey = void 0;
3898
+ async getSignedKey(options = {}) {
3899
+ if (this.#signedKey != null) return this.#signedKey;
3900
+ return this.#signedKey = await require_http.verifyRequest(this.request, {
3901
+ ...this,
3902
+ contextLoader: options.contextLoader ?? this.contextLoader,
3903
+ documentLoader: options.documentLoader ?? this.documentLoader,
3904
+ timeWindow: this.federation.signatureTimeWindow,
3905
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
3906
+ });
3907
+ }
3908
+ #signedKeyOwner = void 0;
3909
+ async getSignedKeyOwner(options = {}) {
3910
+ if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
3911
+ const key = await this.getSignedKey(options);
3912
+ if (key == null) return this.#signedKeyOwner = null;
3913
+ return this.#signedKeyOwner = await require_proof.getKeyOwner(key, {
3914
+ contextLoader: options.contextLoader ?? this.contextLoader,
3915
+ documentLoader: options.documentLoader ?? this.documentLoader,
3916
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
3917
+ });
3918
+ }
3919
+ };
3920
+ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
3921
+ recipient;
3922
+ activity;
3923
+ activityId;
3924
+ activityType;
3925
+ constructor(recipient, activity, activityId, activityType, options) {
3926
+ super(options);
3927
+ this.recipient = recipient;
3928
+ this.activity = activity;
3929
+ this.activityId = activityId;
3930
+ this.activityType = activityType;
3931
+ }
3932
+ clone(data) {
3933
+ return new InboxContextImpl(this.recipient, this.activity, this.activityId, this.activityType, {
3934
+ url: this.url,
3935
+ federation: this.federation,
3936
+ data,
3937
+ documentLoader: this.documentLoader,
3938
+ contextLoader: this.contextLoader,
3939
+ invokedFromActorKeyPairsDispatcher: this.invokedFromActorKeyPairsDispatcher
3940
+ });
3941
+ }
3942
+ forwardActivity(forwarder, recipients, options) {
3943
+ const tracer = this.tracerProvider.getTracer(require_lookup.deno_default.name, require_lookup.deno_default.version);
3944
+ return tracer.startActiveSpan("activitypub.outbox", {
3945
+ kind: this.federation.outboxQueue == null || options?.immediate ? __opentelemetry_api.SpanKind.CLIENT : __opentelemetry_api.SpanKind.PRODUCER,
3946
+ attributes: { "activitypub.activity.type": this.activityType }
3947
+ }, async (span) => {
3948
+ try {
3949
+ if (this.activityId != null) span.setAttribute("activitypub.activity.id", this.activityId);
3950
+ await this.forwardActivityInternal(forwarder, recipients, options);
3951
+ } catch (e) {
3952
+ span.setStatus({
3953
+ code: __opentelemetry_api.SpanStatusCode.ERROR,
3954
+ message: String(e)
3955
+ });
3956
+ throw e;
3957
+ } finally {
3958
+ span.end();
3959
+ }
3960
+ });
3961
+ }
3962
+ async forwardActivityInternal(forwarder, recipients, options) {
3963
+ const logger$1 = (0, __logtape_logtape.getLogger)([
3964
+ "fedify",
3965
+ "federation",
3966
+ "inbox"
3967
+ ]);
3968
+ let keys;
3969
+ let identifier = null;
3970
+ if ("identifier" in forwarder || "username" in forwarder || "handle" in forwarder) {
3971
+ if ("identifier" in forwarder) identifier = forwarder.identifier;
3972
+ else {
3973
+ let username;
3974
+ if ("username" in forwarder) username = forwarder.username;
3975
+ else {
3976
+ username = forwarder.handle;
3977
+ logger$1.warn("The \"handle\" property for the forwarder parameter is deprecated; use \"identifier\" or \"username\" instead.", { forwarder });
3978
+ }
3979
+ if (this.federation.actorCallbacks?.handleMapper == null) identifier = username;
3980
+ else {
3981
+ const mapped = await this.federation.actorCallbacks.handleMapper(this, username);
3982
+ if (mapped == null) throw new Error(`No actor found for the given username ${JSON.stringify(username)}.`);
3983
+ identifier = mapped;
3984
+ }
3985
+ }
3986
+ keys = await this.getKeyPairsFromIdentifier(identifier);
3987
+ if (keys.length < 1) throw new Error(`No key pair found for actor ${JSON.stringify(identifier)}.`);
3988
+ } else if (Array.isArray(forwarder)) {
3989
+ if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
3990
+ keys = forwarder;
3991
+ } else keys = [forwarder];
3992
+ if (!require_proof.hasSignature(this.activity)) {
3993
+ let hasProof;
3994
+ try {
3995
+ const activity = await require_actor.Activity.fromJsonLd(this.activity, this);
3996
+ hasProof = await activity.getProof() != null;
3997
+ } catch {
3998
+ hasProof = false;
3999
+ }
4000
+ if (!hasProof) {
4001
+ if (options?.skipIfUnsigned) return;
4002
+ logger$1.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.");
4003
+ }
4004
+ }
4005
+ if (recipients === "followers") {
4006
+ if (identifier == null) throw new Error("If recipients is \"followers\", forwarder must be an actor identifier or username.");
4007
+ const followers = [];
4008
+ for await (const recipient of this.getFollowers(identifier)) followers.push(recipient);
4009
+ recipients = followers;
4010
+ }
4011
+ const inboxes = extractInboxes({
4012
+ recipients: Array.isArray(recipients) ? recipients : [recipients],
4013
+ preferSharedInbox: options?.preferSharedInbox,
4014
+ excludeBaseUris: options?.excludeBaseUris
4015
+ });
4016
+ logger$1.debug("Forwarding activity {activityId} to inboxes:\n{inboxes}", {
4017
+ inboxes: globalThis.Object.keys(inboxes),
4018
+ activityId: this.activityId,
4019
+ activity: this.activity
4020
+ });
4021
+ if (options?.immediate || this.federation.outboxQueue == null) {
4022
+ if (options?.immediate) logger$1.debug("Forwarding activity immediately without queue since immediate option is set.");
4023
+ else logger$1.debug("Forwarding activity immediately without queue since queue is not set.");
4024
+ const promises = [];
4025
+ for (const inbox in inboxes) promises.push(sendActivity({
4026
+ keys,
4027
+ activity: this.activity,
4028
+ activityId: this.activityId,
4029
+ activityType: this.activityType,
4030
+ inbox: new URL(inbox),
4031
+ sharedInbox: inboxes[inbox].sharedInbox,
4032
+ tracerProvider: this.tracerProvider,
4033
+ specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
4034
+ }));
4035
+ await Promise.all(promises);
4036
+ return;
4037
+ }
4038
+ logger$1.debug("Enqueuing activity {activityId} to forward later.", {
4039
+ activityId: this.activityId,
4040
+ activity: this.activity
4041
+ });
4042
+ const keyJwkPairs = [];
4043
+ for (const { keyId, privateKey } of keys) {
4044
+ const privateKeyJwk = await require_http.exportJwk(privateKey);
4045
+ keyJwkPairs.push({
4046
+ keyId: keyId.href,
4047
+ privateKey: privateKeyJwk
4048
+ });
4049
+ }
4050
+ const carrier = {};
4051
+ __opentelemetry_api.propagation.inject(__opentelemetry_api.context.active(), carrier);
4052
+ const messages = [];
4053
+ for (const inbox in inboxes) {
4054
+ const message = {
4055
+ type: "outbox",
4056
+ id: crypto.randomUUID(),
4057
+ baseUrl: this.origin,
4058
+ keys: keyJwkPairs,
4059
+ activity: this.activity,
4060
+ activityId: this.activityId,
4061
+ activityType: this.activityType,
4062
+ inbox,
4063
+ sharedInbox: inboxes[inbox].sharedInbox,
4064
+ started: (/* @__PURE__ */ new Date()).toISOString(),
4065
+ attempt: 0,
4066
+ headers: {},
4067
+ traceContext: carrier
4068
+ };
4069
+ messages.push(message);
4070
+ }
4071
+ const { outboxQueue } = this.federation;
4072
+ if (outboxQueue.enqueueMany == null) {
4073
+ const promises = messages.map((m) => outboxQueue.enqueue(m));
4074
+ const results = await Promise.allSettled(promises);
4075
+ const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
4076
+ if (errors.length > 0) {
4077
+ logger$1.error("Failed to enqueue activity {activityId} to forward later:\n{errors}", {
4078
+ activityId: this.activityId,
4079
+ errors
4080
+ });
4081
+ if (errors.length > 1) throw new AggregateError(errors, `Failed to enqueue activity ${this.activityId} to forward later.`);
4082
+ throw errors[0];
4083
+ }
4084
+ } else try {
4085
+ await outboxQueue.enqueueMany(messages);
4086
+ } catch (error) {
4087
+ logger$1.error("Failed to enqueue activity {activityId} to forward later:\n{error}", {
4088
+ activityId: this.activityId,
4089
+ error
4090
+ });
4091
+ throw error;
4092
+ }
4093
+ }
4094
+ };
4095
+ var KvSpecDeterminer = class {
4096
+ kv;
4097
+ prefix;
4098
+ defaultSpec;
4099
+ constructor(kv, prefix, defaultSpec = "rfc9421") {
4100
+ this.kv = kv;
4101
+ this.prefix = prefix;
4102
+ this.defaultSpec = defaultSpec;
4103
+ }
4104
+ async determineSpec(origin) {
4105
+ return await this.kv.get([...this.prefix, origin]) ?? this.defaultSpec;
4106
+ }
4107
+ async rememberSpec(origin, spec) {
4108
+ await this.kv.set([...this.prefix, origin], spec);
4109
+ }
4110
+ };
4111
+ function notFound(_request) {
4112
+ return new Response("Not Found", { status: 404 });
4113
+ }
4114
+ function notAcceptable(_request) {
4115
+ return new Response("Not Acceptable", {
4116
+ status: 406,
4117
+ headers: { Vary: "Accept, Signature" }
4118
+ });
4119
+ }
4120
+ function unauthorized(_request) {
4121
+ return new Response("Unauthorized", {
4122
+ status: 401,
4123
+ headers: { Vary: "Accept, Signature" }
4124
+ });
4125
+ }
4126
+ /**
4127
+ * Generates or extracts a unique identifier for a request.
4128
+ *
4129
+ * This function first attempts to extract an existing request ID from standard
4130
+ * tracing headers. If none exists, it generates a new one. The ID format is:
4131
+ *
4132
+ * - If from headers, uses the existing ID.
4133
+ * - If generated, uses format `req_` followed by a base36 timestamp and
4134
+ * 6 random chars.
4135
+ *
4136
+ * @param request The incoming HTTP request.
4137
+ * @returns A string identifier unique to this request.
4138
+ */
4139
+ function getRequestId(request) {
4140
+ const traceId = request.headers.get("X-Request-Id") || request.headers.get("X-Correlation-Id") || request.headers.get("Traceparent")?.split("-")[1];
4141
+ if (traceId != null) return traceId;
4142
+ const timestamp = Date.now().toString(36);
4143
+ const random = Math.random().toString(36).slice(2, 8);
4144
+ return `req_${timestamp}${random}`;
4145
+ }
4146
+
4147
+ //#endregion
4148
+ Object.defineProperty(exports, 'ContextImpl', {
4149
+ enumerable: true,
4150
+ get: function () {
4151
+ return ContextImpl;
4152
+ }
4153
+ });
4154
+ Object.defineProperty(exports, 'FederationImpl', {
4155
+ enumerable: true,
4156
+ get: function () {
4157
+ return FederationImpl;
4158
+ }
4159
+ });
4160
+ Object.defineProperty(exports, 'InboxContextImpl', {
4161
+ enumerable: true,
4162
+ get: function () {
4163
+ return InboxContextImpl;
4164
+ }
4165
+ });
4166
+ Object.defineProperty(exports, 'KvSpecDeterminer', {
4167
+ enumerable: true,
4168
+ get: function () {
4169
+ return KvSpecDeterminer;
4170
+ }
4171
+ });
4172
+ Object.defineProperty(exports, 'Router', {
4173
+ enumerable: true,
4174
+ get: function () {
4175
+ return Router;
4176
+ }
4177
+ });
4178
+ Object.defineProperty(exports, 'RouterError', {
4179
+ enumerable: true,
4180
+ get: function () {
4181
+ return RouterError;
4182
+ }
4183
+ });
4184
+ Object.defineProperty(exports, 'buildCollectionSynchronizationHeader', {
4185
+ enumerable: true,
4186
+ get: function () {
4187
+ return buildCollectionSynchronizationHeader;
4188
+ }
4189
+ });
4190
+ Object.defineProperty(exports, 'createExponentialBackoffPolicy', {
4191
+ enumerable: true,
4192
+ get: function () {
4193
+ return createExponentialBackoffPolicy;
4194
+ }
4195
+ });
4196
+ Object.defineProperty(exports, 'createFederation', {
4197
+ enumerable: true,
4198
+ get: function () {
4199
+ return createFederation;
4200
+ }
4201
+ });
4202
+ Object.defineProperty(exports, 'createFederationBuilder', {
4203
+ enumerable: true,
4204
+ get: function () {
4205
+ return createFederationBuilder;
4206
+ }
4207
+ });
4208
+ Object.defineProperty(exports, 'digest', {
4209
+ enumerable: true,
4210
+ get: function () {
4211
+ return digest;
4212
+ }
4213
+ });
4214
+ Object.defineProperty(exports, 'respondWithObject', {
4215
+ enumerable: true,
4216
+ get: function () {
4217
+ return respondWithObject;
4218
+ }
4219
+ });
4220
+ Object.defineProperty(exports, 'respondWithObjectIfAcceptable', {
4221
+ enumerable: true,
4222
+ get: function () {
4223
+ return respondWithObjectIfAcceptable;
4224
+ }
4225
+ });