@fedify/fedify 2.5.0-dev.2687 → 2.5.0-dev.2726

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 (244) hide show
  1. package/dist/federation/mod.cjs +1 -1
  2. package/dist/federation/mod.js +1 -1
  3. package/dist/{federation-pFFwPyoZ.cjs → federation-C0zalE9W.cjs} +8 -3
  4. package/dist/{http-T7h9GBAN.js → http-BC5Bd3-E.js} +1 -1
  5. package/dist/{http-CXX-QPzs.cjs → http-Dqzgc4Rj.cjs} +1 -1
  6. package/dist/{kv-cache-EFcb1kkU.js → kv-cache-CQ0u0Ry0.js} +1 -1
  7. package/dist/{kv-cache-C6XX_fwz.cjs → kv-cache-ihEHdx1v.cjs} +1 -1
  8. package/dist/{middleware-Bj91r7r2.js → middleware-Bgm3A90j.js} +8 -3
  9. package/dist/mod.cjs +4 -4
  10. package/dist/mod.js +4 -4
  11. package/dist/{portable-collection-Do5QA2oy.js → portable-collection-DZ_XqNUM.js} +1 -1
  12. package/dist/{portable-collection-BOl9oKrt.cjs → portable-collection-nvog8lS6.cjs} +1 -1
  13. package/dist/sig/mod.cjs +2 -2
  14. package/dist/sig/mod.js +2 -2
  15. package/dist/utils/mod.cjs +1 -1
  16. package/dist/utils/mod.js +1 -1
  17. package/package.json +22 -9
  18. package/skills/fedify/SKILL.md +35 -0
  19. package/dist/accept-CPVqki78.mjs +0 -145
  20. package/dist/activity-listener-CELFAodc.mjs +0 -44
  21. package/dist/assert-D1Eafmd_.mjs +0 -23
  22. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  23. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  24. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  25. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  26. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  27. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  28. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  29. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  30. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  31. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  32. package/dist/audience-CHQ-FlLD.mjs +0 -95
  33. package/dist/builder-D1FP_5nQ.mjs +0 -911
  34. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  35. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  36. package/dist/client-5SIFzW3q.mjs +0 -441
  37. package/dist/codec-C6rTrpIp.mjs +0 -147
  38. package/dist/collection-CnnP1UAv.mjs +0 -44
  39. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  40. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  41. package/dist/compat/public-audience.test.d.mts +0 -2
  42. package/dist/compat/public-audience.test.mjs +0 -187
  43. package/dist/compat/secured-document.test.d.mts +0 -2
  44. package/dist/compat/secured-document.test.mjs +0 -58
  45. package/dist/compat/transformers.test.d.mts +0 -2
  46. package/dist/compat/transformers.test.mjs +0 -62
  47. package/dist/compound-proof-DSHhnOEW.mjs +0 -1019
  48. package/dist/context-LgGFFSz7.mjs +0 -146
  49. package/dist/deno-C50ikGBU.mjs +0 -8
  50. package/dist/dist-_geWsuaI.mjs +0 -189
  51. package/dist/docloader-BY-SEID0.mjs +0 -136
  52. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  53. package/dist/exporter-DVG68ozH.mjs +0 -263
  54. package/dist/federation/audience.test.d.mts +0 -2
  55. package/dist/federation/audience.test.mjs +0 -130
  56. package/dist/federation/builder.test.d.mts +0 -2
  57. package/dist/federation/builder.test.mjs +0 -396
  58. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  59. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  60. package/dist/federation/collection.test.d.mts +0 -2
  61. package/dist/federation/collection.test.mjs +0 -21
  62. package/dist/federation/compound-fanout.test.d.mts +0 -2
  63. package/dist/federation/compound-fanout.test.mjs +0 -231
  64. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  65. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  66. package/dist/federation/handler.test.d.mts +0 -2
  67. package/dist/federation/handler.test.mjs +0 -5445
  68. package/dist/federation/hashlink-media.test.d.mts +0 -2
  69. package/dist/federation/hashlink-media.test.mjs +0 -422
  70. package/dist/federation/idempotency.test.d.mts +0 -2
  71. package/dist/federation/idempotency.test.mjs +0 -207
  72. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  73. package/dist/federation/inbox-actorless.test.mjs +0 -522
  74. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  75. package/dist/federation/inbox-authentication.test.mjs +0 -220
  76. package/dist/federation/inbox-report.test.d.mts +0 -2
  77. package/dist/federation/inbox-report.test.mjs +0 -719
  78. package/dist/federation/inbox-view.test.d.mts +0 -2
  79. package/dist/federation/inbox-view.test.mjs +0 -369
  80. package/dist/federation/inbox.test.d.mts +0 -2
  81. package/dist/federation/inbox.test.mjs +0 -139
  82. package/dist/federation/keycache.test.d.mts +0 -2
  83. package/dist/federation/keycache.test.mjs +0 -337
  84. package/dist/federation/kv.test.d.mts +0 -2
  85. package/dist/federation/kv.test.mjs +0 -88
  86. package/dist/federation/metrics.test.d.mts +0 -2
  87. package/dist/federation/metrics.test.mjs +0 -634
  88. package/dist/federation/middleware.test.d.mts +0 -2
  89. package/dist/federation/middleware.test.mjs +0 -9314
  90. package/dist/federation/mq.test.d.mts +0 -2
  91. package/dist/federation/mq.test.mjs +0 -591
  92. package/dist/federation/negotiation.test.d.mts +0 -2
  93. package/dist/federation/negotiation.test.mjs +0 -18
  94. package/dist/federation/outbound-body.test.d.mts +0 -2
  95. package/dist/federation/outbound-body.test.mjs +0 -149
  96. package/dist/federation/outbound-capture.test.d.mts +0 -2
  97. package/dist/federation/outbound-capture.test.mjs +0 -394
  98. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  99. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  100. package/dist/federation/outbound-document.test.d.mts +0 -2
  101. package/dist/federation/outbound-document.test.mjs +0 -171
  102. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  103. package/dist/federation/outbound-provenance.test.mjs +0 -543
  104. package/dist/federation/outbound-report.test.d.mts +0 -2
  105. package/dist/federation/outbound-report.test.mjs +0 -5475
  106. package/dist/federation/outbound-workers.test.d.mts +0 -2
  107. package/dist/federation/outbound-workers.test.mjs +0 -64
  108. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  109. package/dist/federation/outbound-workflow.test.mjs +0 -154
  110. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  111. package/dist/federation/outgoing-proof.test.mjs +0 -933
  112. package/dist/federation/portable-actor.test.d.mts +0 -2
  113. package/dist/federation/portable-actor.test.mjs +0 -496
  114. package/dist/federation/portable-chain.test.d.mts +0 -2
  115. package/dist/federation/portable-chain.test.mjs +0 -370
  116. package/dist/federation/portable-collection.test.d.mts +0 -2
  117. package/dist/federation/portable-collection.test.mjs +0 -832
  118. package/dist/federation/portable-delivery.test.d.mts +0 -2
  119. package/dist/federation/portable-delivery.test.mjs +0 -845
  120. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  121. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  122. package/dist/federation/portable-inbox.test.d.mts +0 -2
  123. package/dist/federation/portable-inbox.test.mjs +0 -1960
  124. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  125. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  126. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  127. package/dist/federation/portable-route-activity.test.mjs +0 -259
  128. package/dist/federation/portable.test.d.mts +0 -2
  129. package/dist/federation/portable.test.mjs +0 -1072
  130. package/dist/federation/retry.test.d.mts +0 -2
  131. package/dist/federation/retry.test.mjs +0 -42
  132. package/dist/federation/router.test.d.mts +0 -2
  133. package/dist/federation/router.test.mjs +0 -123
  134. package/dist/federation/send.test.d.mts +0 -2
  135. package/dist/federation/send.test.mjs +0 -1421
  136. package/dist/federation/tasks/codec.test.d.mts +0 -2
  137. package/dist/federation/tasks/codec.test.mjs +0 -302
  138. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  139. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  140. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  141. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  142. package/dist/federation/temporal.test.d.mts +0 -2
  143. package/dist/federation/temporal.test.mjs +0 -71
  144. package/dist/federation/webfinger.test.d.mts +0 -2
  145. package/dist/federation/webfinger.test.mjs +0 -944
  146. package/dist/http-BXbQQZDM.mjs +0 -1449
  147. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  148. package/dist/inbox-cS97XzOD.mjs +0 -399
  149. package/dist/inbox-view-D-d0Ar6o.mjs +0 -385
  150. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  151. package/dist/keycache-N2opu4-3.mjs +0 -221
  152. package/dist/keys-DIJNHW-Y.mjs +0 -120
  153. package/dist/kv-DBRWVx3Q.mjs +0 -104
  154. package/dist/kv-DCHkaJ9-.mjs +0 -92
  155. package/dist/kv-cache-fgbLHGVL.mjs +0 -121
  156. package/dist/ld-BpkhkDGj.mjs +0 -1752
  157. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  158. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  159. package/dist/metrics-Uqf8GomB.mjs +0 -818
  160. package/dist/middleware-DcXzz-YK.mjs +0 -9971
  161. package/dist/middleware-DgwZkvJR.mjs +0 -5
  162. package/dist/mq-eF96QxUT.mjs +0 -288
  163. package/dist/negotiation-BAKO9nih.mjs +0 -96
  164. package/dist/nodeinfo/client.test.d.mts +0 -2
  165. package/dist/nodeinfo/client.test.mjs +0 -1364
  166. package/dist/nodeinfo/handler.test.d.mts +0 -2
  167. package/dist/nodeinfo/handler.test.mjs +0 -94
  168. package/dist/nodeinfo/types.test.d.mts +0 -2
  169. package/dist/nodeinfo/types.test.mjs +0 -192
  170. package/dist/otel/exporter.test.d.mts +0 -2
  171. package/dist/otel/exporter.test.mjs +0 -887
  172. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  173. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  174. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  175. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  176. package/dist/owner-BVenIFg1.mjs +0 -267
  177. package/dist/portable-collection-DIk9gpjL.mjs +0 -418
  178. package/dist/portable-key-C7pVaHNR.mjs +0 -549
  179. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  180. package/dist/proof-BlfZ95--.mjs +0 -1420
  181. package/dist/public-audience--klBIOk1.mjs +0 -197
  182. package/dist/retry-zX5xw5e0.mjs +0 -34
  183. package/dist/router-u5O5KCQr.mjs +0 -156
  184. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  185. package/dist/send-DEGHPGFk.mjs +0 -710
  186. package/dist/sig/accept.test.d.mts +0 -2
  187. package/dist/sig/accept.test.mjs +0 -416
  188. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  189. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  190. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  191. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  192. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  193. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  194. package/dist/sig/compound-proof.test.d.mts +0 -2
  195. package/dist/sig/compound-proof.test.mjs +0 -411
  196. package/dist/sig/http.test.d.mts +0 -2
  197. package/dist/sig/http.test.mjs +0 -3328
  198. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  199. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  200. package/dist/sig/key.test.d.mts +0 -2
  201. package/dist/sig/key.test.mjs +0 -1250
  202. package/dist/sig/ld.test.d.mts +0 -2
  203. package/dist/sig/ld.test.mjs +0 -1044
  204. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  205. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  206. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  207. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  208. package/dist/sig/owner.test.d.mts +0 -2
  209. package/dist/sig/owner.test.mjs +0 -202
  210. package/dist/sig/portable-collection.test.d.mts +0 -2
  211. package/dist/sig/portable-collection.test.mjs +0 -697
  212. package/dist/sig/portable-interop.test.d.mts +0 -2
  213. package/dist/sig/portable-interop.test.mjs +0 -156
  214. package/dist/sig/portable-key-id.test.d.mts +0 -2
  215. package/dist/sig/portable-key-id.test.mjs +0 -67
  216. package/dist/sig/portable-key.test.d.mts +0 -2
  217. package/dist/sig/portable-key.test.mjs +0 -1438
  218. package/dist/sig/proof.test.d.mts +0 -2
  219. package/dist/sig/proof.test.mjs +0 -2638
  220. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  221. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  222. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  223. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  224. package/dist/sig/verification.test.d.mts +0 -2
  225. package/dist/sig/verification.test.mjs +0 -310
  226. package/dist/std__assert-DvMDRPes.mjs +0 -8
  227. package/dist/tasks-BCUmQbbz.mjs +0 -77
  228. package/dist/temporal-B4oQ8HpW.mjs +0 -95
  229. package/dist/testing/context.test.d.mts +0 -2
  230. package/dist/testing/context.test.mjs +0 -19
  231. package/dist/testing/kv.test.d.mts +0 -2
  232. package/dist/testing/kv.test.mjs +0 -101
  233. package/dist/testing/mod.d.mts +0 -6099
  234. package/dist/testing/mod.mjs +0 -9
  235. package/dist/testing-vrnD5Uaa.mjs +0 -8
  236. package/dist/types-DE_LV1JB.mjs +0 -46
  237. package/dist/utils/docloader.test.d.mts +0 -2
  238. package/dist/utils/docloader.test.mjs +0 -1076
  239. package/dist/utils/kv-cache.test.d.mts +0 -2
  240. package/dist/utils/kv-cache.test.mjs +0 -261
  241. package/dist/verification-C3954hQh.mjs +0 -5
  242. package/dist/verification-Dpfcw8ml.mjs +0 -105
  243. package/dist/vocab/cjs.test.d.mts +0 -2
  244. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,1960 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { t as esm_default } from "../esm-BHXXx4Wx.mjs";
5
- import { t as MemoryKvStore } from "../kv-DCHkaJ9-.mjs";
6
- import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
7
- import { t as assertFalse } from "../assert_false-CPdRnc3E.mjs";
8
- import { t as assertThrows } from "../assert_throws-BYITOvPO.mjs";
9
- import "../std__assert-DvMDRPes.mjs";
10
- import { t as assertStrictEquals } from "../assert_strict_equals-CYvBmkpC.mjs";
11
- import { t as assert } from "../assert-D1Eafmd_.mjs";
12
- import { m as signJsonLd } from "../ld-BpkhkDGj.mjs";
13
- import { s as signObject } from "../proof-BlfZ95--.mjs";
14
- import { m as verifyRequestDetailed, u as signRequest } from "../http-BXbQQZDM.mjs";
15
- import { a as rsaPrivateKey3, c as rsaPublicKey3, i as rsaPrivateKey2, n as ed25519PrivateKey, r as ed25519PublicKey, s as rsaPublicKey2 } from "../keys-DIJNHW-Y.mjs";
16
- import { M as observeOutboundBroadcast, _ as coversDelivery, o as createFederation, v as forwardPortableInboxActivity, y as resolvePortableInboxForwardingOptions } from "../middleware-DcXzz-YK.mjs";
17
- import { Create, CryptographicKey, Follow, Note, Person, Tombstone } from "@fedify/vocab";
18
- import { exportDidKey, formatIri, parseIri } from "@fedify/vocab-runtime";
19
- import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
20
- import { encodeBase64 } from "byte-encodings/base64";
21
- //#region src/federation/portable-inbox.test.ts
22
- const did = await exportDidKey(ed25519PublicKey.publicKey);
23
- const keyId = new URL(`${did}#${did.substring(8)}`);
24
- const otherKeyPair = await crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"]);
25
- const otherDid = await exportDidKey(otherKeyPair.publicKey);
26
- const LOCAL = "https://example.com";
27
- const GATEWAY2 = "https://example.org";
28
- const GATEWAY3 = "https://example.net";
29
- function inboxUrl(authority = did, path = "/users/alice/inbox", origin = LOCAL) {
30
- return `${origin}/.well-known/apgateway/${authority}${path}`;
31
- }
32
- function post(url, body, headers = {}) {
33
- return new Request(url, {
34
- method: "POST",
35
- headers: {
36
- "Content-Type": "application/activity+json",
37
- ...headers
38
- },
39
- body: JSON.stringify(body)
40
- });
41
- }
42
- var RecordingQueue = class {
43
- messages = [];
44
- failFor;
45
- enqueue(message) {
46
- if (this.failFor != null && message.type === "outbox" && message.inbox.startsWith(this.failFor)) return Promise.reject(/* @__PURE__ */ new Error("Enqueue failed."));
47
- this.messages.push(message);
48
- return Promise.resolve();
49
- }
50
- listen() {
51
- return Promise.resolve();
52
- }
53
- get outbox() {
54
- return this.messages.filter((m) => m.type === "outbox");
55
- }
56
- };
57
- function setup({ gateways = [
58
- LOCAL,
59
- GATEWAY2,
60
- GATEWAY3
61
- ], kv = new MemoryKvStore(), queue, options = {}, actor, listenerError = false, keyPairs = true, aliceKeyPairs = [], mapPortableActorId, onSharedInboxKey } = {}) {
62
- const federation = createFederation({
63
- kv,
64
- ...options.allowPrivateAddress ? {} : {
65
- documentLoaderFactory: () => mockDocumentLoader,
66
- contextLoaderFactory: () => mockDocumentLoader
67
- },
68
- manuallyStartQueue: true,
69
- ...queue == null ? {} : { queue: { outbox: queue } },
70
- ...options
71
- });
72
- const received = [];
73
- const actorCallbacks = federation.setActorDispatcher("/users/{identifier}", actor ?? ((ctx, identifier) => {
74
- if (identifier === "ordinary") return new Person({
75
- id: ctx.getActorUri(identifier),
76
- inbox: ctx.getInboxUri(identifier)
77
- });
78
- if (identifier !== "alice") return null;
79
- return new Person({
80
- id: parseIri(`ap+ef61://${did}/users/alice`),
81
- inbox: ctx.getPortableInboxUri(identifier, did),
82
- gateways: gateways.map((g) => new URL(g))
83
- });
84
- }));
85
- if (keyPairs) actorCallbacks.setKeyPairsDispatcher((_ctx, identifier) => identifier === "ordinary" ? [{
86
- privateKey: rsaPrivateKey2,
87
- publicKey: rsaPublicKey2.publicKey
88
- }] : identifier === "alice" ? aliceKeyPairs : []);
89
- if (mapPortableActorId != null) actorCallbacks.mapPortableActorId((_ctx, identifier) => mapPortableActorId(identifier));
90
- const reports = [];
91
- const inboxListeners = federation.setInboxListeners("/users/{identifier}/inbox", "/inbox").onRequestFinished((_ctx, report) => {
92
- reports.push(report);
93
- });
94
- if (onSharedInboxKey != null) inboxListeners.setSharedKeyDispatcher(() => {
95
- onSharedInboxKey();
96
- return null;
97
- });
98
- inboxListeners.on(Follow, (ctx, activity) => {
99
- received.push({
100
- activity,
101
- recipient: ctx.recipient
102
- });
103
- if (listenerError) throw new Error("Listener failed.");
104
- }).on(Create, (ctx, activity) => {
105
- received.push({
106
- activity,
107
- recipient: ctx.recipient
108
- });
109
- });
110
- return {
111
- federation,
112
- received,
113
- kv,
114
- queue,
115
- reports
116
- };
117
- }
118
- let activityCounter = 0;
119
- async function signedFollow(authority = did, privateKey = ed25519PrivateKey, signingKeyId = keyId) {
120
- return await (await signObject(new Follow({
121
- id: parseIri(`ap+ef61://${authority}/follows/${++activityCounter}`),
122
- actor: parseIri(`ap+ef61://${authority}/users/bob`),
123
- object: parseIri(`ap+ef61://${did}/users/alice`)
124
- }), privateKey, signingKeyId, { contextLoader: mockDocumentLoader })).toJsonLd({ contextLoader: mockDocumentLoader });
125
- }
126
- test("Federation.fetch() delivers to portable inboxes", async (t) => {
127
- const queue = new RecordingQueue();
128
- const { federation, received } = setup({ queue });
129
- const json = await signedFollow();
130
- await t.step("routes to the existing inbox listeners", async () => {
131
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
132
- assertEquals(received.length, 1);
133
- assertEquals(received[0].recipient, "alice");
134
- assert(received[0].activity instanceof Follow);
135
- });
136
- await t.step("forwards the activity to the other gateways", () => {
137
- assertEquals(queue.outbox.map((m) => m.inbox).sort(), [inboxUrl(did, "/users/alice/inbox", GATEWAY3), inboxUrl(did, "/users/alice/inbox", GATEWAY2)]);
138
- for (const message of queue.outbox) {
139
- assertEquals(message.keys, []);
140
- assertEquals(message.activity, json);
141
- assertFalse(message.sharedInbox);
142
- }
143
- });
144
- await t.step("neither forwards nor dispatches duplicates", async () => {
145
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
146
- assertEquals(received.length, 1);
147
- assertEquals(queue.outbox.length, 2);
148
- });
149
- await t.step("accepts ap: and percent-encoded DIDs", async () => {
150
- assertEquals((await federation.fetch(post(inboxUrl(did.replaceAll(":", "%3A")), await signedFollow()), { contextData: void 0 })).status, 202);
151
- assertEquals(received.length, 2);
152
- });
153
- });
154
- test("Federation.fetch() delivers to portable inboxes without key pairs", async () => {
155
- const queue = new RecordingQueue();
156
- const { federation, received } = setup({
157
- queue,
158
- keyPairs: false
159
- });
160
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
161
- assertEquals(received.length, 1);
162
- assertEquals(queue.outbox.length, 2);
163
- });
164
- test("Federation.fetch() refuses portable inbox deliveries it does not accept", async (t) => {
165
- const { federation, received } = setup({ gateways: [GATEWAY2] });
166
- const json = await signedFollow();
167
- await t.step("this server is not a gateway of the actor", async () => {
168
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 404);
169
- });
170
- const accepting = setup();
171
- const cases = [
172
- ["unknown actor", inboxUrl(did, "/users/unknown/inbox")],
173
- ["non-portable actor", inboxUrl(did, "/users/ordinary/inbox")],
174
- ["DID mismatch", inboxUrl(otherDid)],
175
- ["shared inbox", inboxUrl(did, "/inbox")],
176
- ["actor path", inboxUrl(did, "/users/alice")],
177
- ["unregistered path", inboxUrl(did, "/unknown/alice/inbox")]
178
- ];
179
- for (const [name, url] of cases) await t.step(name, async () => {
180
- assertEquals((await accepting.federation.fetch(post(url, json), { contextData: void 0 })).status, 404);
181
- });
182
- await t.step("inbox mismatch", async () => {
183
- const { federation } = setup({ actor: () => new Person({
184
- id: parseIri(`ap+ef61://${did}/users/alice`),
185
- inbox: parseIri(`ap+ef61://${did}/users/alice/other-inbox`),
186
- gateways: [new URL(LOCAL)]
187
- }) });
188
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 404);
189
- });
190
- await t.step("tombstone", async () => {
191
- const { federation } = setup({ actor: () => new Tombstone({ id: parseIri(`ap+ef61://${did}/users/alice`) }) });
192
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 404);
193
- });
194
- await t.step("malformed DID", async () => {
195
- assertEquals((await accepting.federation.fetch(post(`${LOCAL}/.well-known/apgateway/did:key:/users/alice/inbox`, json), { contextData: void 0 })).status, 400);
196
- });
197
- await t.step("listeners are not called", () => {
198
- assertEquals(received.length, 0);
199
- assertEquals(accepting.received.length, 0);
200
- });
201
- });
202
- test("onRequestFinished retains crypto success when a portable activity's DID mismatches", async () => {
203
- const { federation, reports, received } = setup();
204
- const signingKeyId = new URL(`${otherDid}#${otherDid.substring(8)}`);
205
- const activity = await signObject(new Follow({
206
- id: parseIri(`ap+ef61://${did}/follows/mismatched-report`),
207
- actor: parseIri(`ap+ef61://${otherDid}/users/bob`),
208
- object: parseIri(`ap+ef61://${did}/users/alice`)
209
- }), otherKeyPair.privateKey, signingKeyId, { contextLoader: mockDocumentLoader });
210
- assertEquals((await federation.fetch(post(inboxUrl(), await activity.toJsonLd({ contextLoader: mockDocumentLoader })), { contextData: void 0 })).status, 401);
211
- assertEquals(received.length, 0);
212
- assertEquals(reports.length, 1);
213
- const report = reports[0];
214
- assert(report.authentication.status === "rejected");
215
- assert(report.authentication.reason.type === "proofPolicy");
216
- assertEquals(report.authentication.reason.policy, "portableActivity");
217
- assertEquals(report.authentication.reason.detail?.type, "verificationMethodMismatch");
218
- assert(report.attempts.some((attempt) => attempt.mechanism === "objectIntegrity" && attempt.checks.some((check) => check.status === "verified")));
219
- assert(report.attempts.some((attempt) => attempt.status === "rejected" && attempt.reason.type === "proofPolicy" && attempt.reason.reason.type === "verificationMethodMismatch"));
220
- assertEquals(report.outcome, {
221
- type: "response",
222
- status: 401,
223
- disposition: "rejected",
224
- reason: "authentication"
225
- });
226
- });
227
- test("Federation.fetch() applies the proof policy to portable inbox deliveries", async (t) => {
228
- const queue = new RecordingQueue();
229
- const { federation, received } = setup({ queue });
230
- await t.step("unsigned portable activity", async () => {
231
- const json = await new Follow({
232
- id: parseIri(`ap+ef61://${did}/follows/unsigned`),
233
- actor: parseIri(`ap+ef61://${did}/users/bob`),
234
- object: parseIri(`ap+ef61://${did}/users/alice`)
235
- }).toJsonLd({ contextLoader: mockDocumentLoader });
236
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 401);
237
- });
238
- await t.step("proof made by another DID", async () => {
239
- const json = await signedFollow(did, otherKeyPair.privateKey, new URL(`${otherDid}#${otherDid.substring(8)}`));
240
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 401);
241
- });
242
- await t.step("unsigned portable object in a signed activity", async () => {
243
- const json = await (await signObject(new Create({
244
- id: parseIri(`ap+ef61://${did}/creates/1`),
245
- actor: parseIri(`ap+ef61://${did}/users/bob`),
246
- object: new Note({
247
- id: parseIri(`ap+ef61://${did}/notes/1`),
248
- content: "Hello"
249
- })
250
- }), ed25519PrivateKey, keyId, { contextLoader: mockDocumentLoader })).toJsonLd({ contextLoader: mockDocumentLoader });
251
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 401);
252
- });
253
- await t.step("nothing is dispatched or forwarded", () => {
254
- assertEquals(received.length, 0);
255
- assertEquals(queue.outbox.length, 0);
256
- });
257
- });
258
- test("Federation.fetch() does not forward activities authenticated only by HTTP Signatures", async () => {
259
- const queue = new RecordingQueue();
260
- const { federation, received } = setup({ queue });
261
- const activity = {
262
- "@context": "https://www.w3.org/ns/activitystreams",
263
- id: "https://example.com/follows/http",
264
- type: "Follow",
265
- actor: "https://example.com/person2",
266
- object: formatIri(parseIri(`ap+ef61://${did}/users/alice`))
267
- };
268
- const request = await signRequest(post(inboxUrl(), activity), rsaPrivateKey3, new URL("https://example.com/person2#key3"));
269
- assertEquals((await federation.fetch(request, { contextData: void 0 })).status, 202);
270
- assertEquals(received.length, 1);
271
- assertEquals(queue.outbox.length, 0);
272
- });
273
- test("Federation.fetch() forwards activities authenticated by Linked Data Signatures", async () => {
274
- const queue = new RecordingQueue();
275
- const { federation, received } = setup({ queue });
276
- const activity = await signJsonLd({
277
- "@context": "https://www.w3.org/ns/activitystreams",
278
- id: "https://example.com/follows/lds",
279
- type: "Follow",
280
- actor: "https://example.com/person2",
281
- object: formatIri(parseIri(`ap+ef61://${did}/users/alice`))
282
- }, rsaPrivateKey3, rsaPublicKey3.id, { contextLoader: mockDocumentLoader });
283
- assertEquals((await federation.fetch(post(inboxUrl(), activity), { contextData: void 0 })).status, 202);
284
- assertEquals(received.length, 1);
285
- assertEquals(queue.outbox.length, 2);
286
- for (const message of queue.outbox) assertEquals(message.activity, activity);
287
- });
288
- test("Federation.fetch() does not forward portable inbox deliveries without verification", async () => {
289
- const queue = new RecordingQueue();
290
- const { federation, received } = setup({
291
- queue,
292
- options: { skipSignatureVerification: true }
293
- });
294
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
295
- assertEquals(received.length, 1);
296
- assertEquals(queue.outbox.length, 0);
297
- });
298
- test("Federation.fetch() does not forward portable inbox deliveries whose listener failed", async () => {
299
- const queue = new RecordingQueue();
300
- const { federation } = setup({
301
- queue,
302
- listenerError: true
303
- });
304
- const json = await signedFollow();
305
- let response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
306
- assertEquals(response.status, 500);
307
- assertEquals(queue.outbox.length, 0);
308
- response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
309
- assertEquals(response.status, 500);
310
- assertEquals(queue.outbox.length, 0);
311
- });
312
- test("Federation.fetch() forwards each portable inbox delivery at most once", async (t) => {
313
- await t.step("concurrent deliveries", async () => {
314
- const queue = new RecordingQueue();
315
- const { federation } = setup({ queue });
316
- const json = await signedFollow();
317
- const responses = await Promise.all([
318
- federation.fetch(post(inboxUrl(), json), { contextData: void 0 }),
319
- federation.fetch(post(inboxUrl(), json), { contextData: void 0 }),
320
- federation.fetch(post(inboxUrl(), json), { contextData: void 0 })
321
- ]);
322
- for (const response of responses) assertEquals(response.status, 202);
323
- assertEquals(queue.outbox.map((m) => m.inbox).sort(), [inboxUrl(did, "/users/alice/inbox", GATEWAY3), inboxUrl(did, "/users/alice/inbox", GATEWAY2)]);
324
- });
325
- await t.step("failed hand-offs are not retried", async () => {
326
- const queue = new RecordingQueue();
327
- queue.failFor = GATEWAY2;
328
- const { federation, received } = setup({ queue });
329
- const json = await signedFollow();
330
- let response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
331
- assertEquals(response.status, 202);
332
- assertEquals(queue.outbox.map((m) => m.inbox), [inboxUrl(did, "/users/alice/inbox", GATEWAY3)]);
333
- queue.failFor = void 0;
334
- response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
335
- assertEquals(response.status, 202);
336
- assertEquals(queue.outbox.length, 1);
337
- assertEquals(received.length, 1);
338
- });
339
- await t.step("a delivery forwarded back is not forwarded again", async () => {
340
- const queue = new RecordingQueue();
341
- const local = setup({
342
- queue,
343
- kv: new MemoryKvStore()
344
- });
345
- const json = await signedFollow();
346
- await local.federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
347
- assertEquals(queue.outbox.length, 2);
348
- assertEquals((await local.federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
349
- assertEquals(queue.outbox.length, 2);
350
- assertEquals(local.received.length, 1);
351
- });
352
- await t.step("without KvStore.cas()", async () => {
353
- const queue = new RecordingQueue();
354
- const memory = new MemoryKvStore();
355
- const { federation, received } = setup({
356
- queue,
357
- kv: {
358
- get: (key) => memory.get(key),
359
- set: (key, value, options) => memory.set(key, value, options),
360
- delete: (key) => memory.delete(key),
361
- list: (prefix) => memory.list(prefix)
362
- }
363
- });
364
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
365
- assertEquals(received.length, 1);
366
- assertEquals(queue.outbox.length, 0);
367
- });
368
- await t.step("configured origin", async () => {
369
- const queue = new RecordingQueue();
370
- const { federation } = setup({
371
- queue,
372
- gateways: [
373
- GATEWAY2,
374
- LOCAL,
375
- GATEWAY3
376
- ],
377
- options: { origin: GATEWAY2 }
378
- });
379
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
380
- assertEquals(queue.outbox.map((m) => m.inbox), [inboxUrl(did, "/users/alice/inbox", GATEWAY3)]);
381
- });
382
- await t.step("gateway cap", async () => {
383
- const queue = new RecordingQueue();
384
- const gateways = [LOCAL];
385
- for (let i = 0; i < 15; i++) gateways.push(`https://gw${i}.example.net`);
386
- const { federation } = setup({
387
- queue,
388
- gateways
389
- });
390
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
391
- assertEquals(queue.outbox.length, 10);
392
- });
393
- });
394
- test("FederationOptions.portableInboxForwarding", async (t) => {
395
- await t.step("maxTargets", async () => {
396
- const queue = new RecordingQueue();
397
- const { federation } = setup({
398
- queue,
399
- options: { portableInboxForwarding: { maxTargets: 1 } }
400
- });
401
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
402
- assertEquals(queue.outbox.map((m) => m.inbox), [inboxUrl(did, "/users/alice/inbox", GATEWAY2)]);
403
- });
404
- await t.step("maxTargets: 0 turns off forwarding", async () => {
405
- const queue = new RecordingQueue();
406
- const { federation, received } = setup({
407
- queue,
408
- options: { portableInboxForwarding: { maxTargets: 0 } }
409
- });
410
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
411
- assertEquals(received.length, 1);
412
- assertEquals(queue.outbox.length, 0);
413
- });
414
- await t.step("ttl", async () => {
415
- const queue = new RecordingQueue();
416
- const memory = new MemoryKvStore();
417
- const claimTtls = [];
418
- const { federation } = setup({
419
- queue,
420
- kv: {
421
- get: (key) => memory.get(key),
422
- set: (key, value, options) => memory.set(key, value, options),
423
- delete: (key) => memory.delete(key),
424
- list: (prefix) => memory.list(prefix),
425
- cas: (key, expected, value, options) => {
426
- if (key[1] === "portableInboxForwarding") claimTtls.push(options?.ttl);
427
- return memory.cas(key, expected, value, options);
428
- }
429
- },
430
- options: { portableInboxForwarding: { ttl: Temporal.Duration.from({ days: 7 }) } }
431
- });
432
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
433
- assertEquals(queue.outbox.length, 2);
434
- assertEquals(claimTtls.map((ttl) => ttl?.total("day")), [7, 7]);
435
- });
436
- await t.step("longest deadline", () => {
437
- assertEquals(resolvePortableInboxForwardingOptions({ deadline: { milliseconds: 2 ** 31 - 1 } }).deadline.total("millisecond"), 2 ** 31 - 1);
438
- });
439
- await t.step("defaults", () => {
440
- const resolved = resolvePortableInboxForwardingOptions();
441
- assertEquals(resolved.maxTargets, 10);
442
- assertEquals(resolved.ttl.total("day"), 30);
443
- assertEquals(resolved.deadline.total("second"), 10);
444
- });
445
- await t.step("invalid values", () => {
446
- for (const portableInboxForwarding of [
447
- { maxTargets: -1 },
448
- { maxTargets: 1.5 },
449
- { maxTargets: NaN },
450
- { ttl: { seconds: 0 } },
451
- { ttl: { weeks: 1 } },
452
- { ttl: { months: 1 } },
453
- { deadline: { seconds: -1 } },
454
- { deadline: { years: 1 } },
455
- { deadline: { milliseconds: 2 ** 31 } }
456
- ]) assertThrows(() => setup({ options: { portableInboxForwarding } }), RangeError);
457
- });
458
- });
459
- test("Federation.fetch() forwards portable inbox deliveries immediately without a queue", async () => {
460
- esm_default.spyGlobal();
461
- const requests = [];
462
- esm_default.post(`begin:${GATEWAY2}/`, async (callLog) => {
463
- const request = callLog.request;
464
- requests.push({
465
- url: request.url,
466
- headers: new Headers(request.headers),
467
- body: await request.json()
468
- });
469
- return new Response(null, { status: 202 });
470
- });
471
- esm_default.post(`begin:${GATEWAY3}/`, () => {
472
- throw new TypeError("Connection refused.");
473
- });
474
- try {
475
- const { federation, received } = setup({ options: { allowPrivateAddress: true } });
476
- const json = await signedFollow();
477
- let response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
478
- assertEquals(response.status, 202);
479
- assertEquals(received.length, 1);
480
- assertEquals(requests.length, 1);
481
- assertEquals(requests[0].url, inboxUrl(did, "/users/alice/inbox", GATEWAY2));
482
- assertFalse(requests[0].headers.has("Signature"));
483
- assertFalse(requests[0].headers.has("Signature-Input"));
484
- assertEquals(requests[0].body, json);
485
- response = await federation.fetch(post(inboxUrl(), json), { contextData: void 0 });
486
- assertEquals(response.status, 202);
487
- assertEquals(requests.length, 1);
488
- assertEquals(esm_default.callHistory.calls(`begin:${GATEWAY3}/`).length, 1);
489
- } finally {
490
- esm_default.hardReset();
491
- }
492
- });
493
- test("Federation.fetch() forwards portable inbox deliveries when it enqueues them", async () => {
494
- const queue = new RecordingQueue();
495
- const inboxQueue = new RecordingQueue();
496
- let sharedInboxKeyCalls = 0;
497
- const { federation, received } = setup({
498
- queue,
499
- keyPairs: false,
500
- onSharedInboxKey: () => sharedInboxKeyCalls++,
501
- options: { queue: {
502
- inbox: inboxQueue,
503
- outbox: queue
504
- } }
505
- });
506
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
507
- assertEquals(received.length, 0);
508
- assertEquals(inboxQueue.messages.length, 1);
509
- assertEquals(inboxQueue.messages[0].type, "inbox");
510
- assertEquals(queue.outbox.length, 2);
511
- await federation.processQueuedTask(void 0, inboxQueue.messages[0]);
512
- assertEquals(received.length, 1);
513
- assertEquals(received[0].recipient, "alice");
514
- assertEquals(sharedInboxKeyCalls, 0);
515
- });
516
- test("forwardPortableInboxActivity() does not wait for slow gateways", async () => {
517
- esm_default.spyGlobal();
518
- let release = () => {};
519
- const pending = new Promise((resolve) => release = resolve);
520
- esm_default.post(`begin:${GATEWAY2}/`, async () => {
521
- await pending;
522
- throw new TypeError("Connection reset.");
523
- });
524
- try {
525
- const kv = new MemoryKvStore();
526
- const activityId = parseIri(`ap+ef61://${did}/follows/slow`);
527
- const parameters = {
528
- recipient: {
529
- actorId: parseIri(`ap+ef61://${did}/users/alice`),
530
- inboxId: parseIri(`ap+ef61://${did}/users/alice/inbox`),
531
- canonicalInboxId: `ap://${did}/users/alice/inbox`,
532
- gateways: [new URL(LOCAL), new URL(GATEWAY2)]
533
- },
534
- activity: { id: formatIri(activityId) },
535
- activityId,
536
- activityType: "https://www.w3.org/ns/activitystreams#Follow",
537
- excludedOrigins: [LOCAL],
538
- baseUrl: LOCAL,
539
- kv,
540
- kvPrefix: ["_fedify", "portableInboxForwarding"],
541
- options: resolvePortableInboxForwardingOptions({ deadline: { milliseconds: 10 } }),
542
- allowPrivateAddress: true
543
- };
544
- const started = performance.now();
545
- const forwarded = await forwardPortableInboxActivity(parameters);
546
- assert(performance.now() - started < 5e3);
547
- assertEquals(forwarded.map((u) => u.href), [inboxUrl(did, "/users/alice/inbox", GATEWAY2)]);
548
- release();
549
- await new Promise((resolve) => setTimeout(resolve, 10));
550
- assertEquals(await forwardPortableInboxActivity(parameters), []);
551
- assertEquals(esm_default.callHistory.calls().length, 1);
552
- } finally {
553
- esm_default.hardReset();
554
- }
555
- });
556
- function compatibleAlice(path = "/users/alice", { authority = did, origin = LOCAL, gateways = [
557
- LOCAL,
558
- GATEWAY2,
559
- GATEWAY3
560
- ] } = {}) {
561
- return {
562
- id: new URL(`${origin}/.well-known/apgateway/${authority}${path}`),
563
- inbox: new URL(inboxUrl(authority, `${path}/inbox`, origin)),
564
- gateways: gateways.map((g) => new URL(g))
565
- };
566
- }
567
- test("Federation.fetch() delivers to portable inboxes of compatible-ID actors", async (t) => {
568
- const apAlice = parseIri(`ap+ef61://${did}/users/alice`);
569
- const apInbox = parseIri(`ap+ef61://${did}/users/alice/inbox`);
570
- const cases = [
571
- [
572
- "compatible actor and inbox",
573
- compatibleAlice(),
574
- ""
575
- ],
576
- [
577
- "on another gateway",
578
- compatibleAlice(void 0, { origin: GATEWAY2 }),
579
- ""
580
- ],
581
- [
582
- "compatible actor and ap: inbox",
583
- {
584
- ...compatibleAlice(),
585
- inbox: apInbox
586
- },
587
- ""
588
- ],
589
- [
590
- "ap: actor and compatible inbox",
591
- {
592
- ...compatibleAlice(),
593
- id: apAlice
594
- },
595
- ""
596
- ],
597
- [
598
- "compatible inbox with a query",
599
- {
600
- ...compatibleAlice(),
601
- inbox: new URL(inboxUrl() + "?page=1")
602
- },
603
- "?page=1"
604
- ]
605
- ];
606
- for (const [name, alice, query] of cases) await t.step(name, async () => {
607
- const queue = new RecordingQueue();
608
- const { federation, received } = setup({
609
- queue,
610
- actor: (_ctx, identifier) => identifier === "alice" ? new Person(alice) : null
611
- });
612
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
613
- assertEquals(received.length, 1);
614
- assertEquals(received[0].recipient, "alice");
615
- assertEquals(queue.outbox.map((m) => m.inbox).sort(), [inboxUrl(did, "/users/alice/inbox", GATEWAY3) + query, inboxUrl(did, "/users/alice/inbox", GATEWAY2) + query]);
616
- });
617
- const json = await signedFollow();
618
- const rejections = [
619
- ["DID mismatch", new Person(compatibleAlice(void 0, { authority: otherDid }))],
620
- ["inbox mismatch", new Person({
621
- ...compatibleAlice(),
622
- inbox: new URL(inboxUrl(did, "/users/alice/other-inbox"))
623
- })],
624
- ["this server is not a gateway of the actor", new Person(compatibleAlice(void 0, { gateways: [GATEWAY2] }))],
625
- ["malformed actor ID", new Person({
626
- ...compatibleAlice(),
627
- id: new URL(compatibleAlice().id.href + "?@gateway=https%3A%2F%2Fexample.com")
628
- })],
629
- ["malformed inbox ID", new Person({
630
- ...compatibleAlice(),
631
- inbox: new URL(inboxUrl() + "?@gateway=https%3A%2F%2Fexample.com")
632
- })]
633
- ];
634
- for (const [name, actor] of rejections) await t.step(name, async () => {
635
- const { federation, received } = setup({ actor: (_ctx, identifier) => identifier === "alice" ? actor : null });
636
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 404);
637
- assertEquals(received.length, 0);
638
- });
639
- });
640
- test("forwardPortableInboxActivity() deduplicates compatible activity IDs", async () => {
641
- const kv = new MemoryKvStore();
642
- const queue = new RecordingQueue();
643
- const forward = (activityId) => forwardPortableInboxActivity({
644
- recipient: {
645
- actorId: compatibleAlice().id,
646
- inboxId: parseIri(`ap+ef61://${did}/users/alice/inbox`),
647
- canonicalInboxId: `ap+ef61://${did}/users/alice/inbox`,
648
- gateways: [new URL(LOCAL), new URL(GATEWAY2)]
649
- },
650
- activity: { id: activityId.href },
651
- activityId,
652
- activityType: "https://www.w3.org/ns/activitystreams#Follow",
653
- excludedOrigins: [LOCAL],
654
- baseUrl: LOCAL,
655
- kv,
656
- kvPrefix: ["_fedify", "portableInboxForwarding"],
657
- outboxQueue: queue
658
- });
659
- const path = `${did}/follows/compatible`;
660
- assertEquals((await forward(new URL(`${LOCAL}/.well-known/apgateway/${path}`))).length, 1);
661
- for (const id of [
662
- new URL(`${GATEWAY2}/.well-known/apgateway/${path}`),
663
- new URL(`${LOCAL}/.well-known/apgateway/${path}?x=1`),
664
- parseIri(`ap://${path}`)
665
- ]) assertEquals(await forward(id), [], id.href);
666
- assertEquals(queue.outbox.length, 1);
667
- });
668
- const aliceId = parseIri(`ap+ef61://${did}/users/alice`);
669
- const rsaGatewayKeyPair = await crypto.subtle.generateKey({
670
- name: "RSASSA-PKCS1-v1_5",
671
- modulusLength: 2048,
672
- publicExponent: new Uint8Array([
673
- 1,
674
- 0,
675
- 1
676
- ]),
677
- hash: "SHA-256"
678
- }, true, ["sign", "verify"]);
679
- function compatibleAliceId(origin = LOCAL) {
680
- return `${origin}/.well-known/apgateway/${did}/users/alice`;
681
- }
682
- function mapAlice(identifier) {
683
- return identifier === "alice" ? aliceId : null;
684
- }
685
- function signatureKeyId(headers) {
686
- return headers.get("Signature-Input")?.match(/keyid="([^"]+)"/)?.[1] ?? headers.get("Signature")?.match(/keyId="([^"]+)"/)?.[1];
687
- }
688
- /**
689
- * Makes a document loader that serves Alice's actor document as the gateway
690
- * at {@link LOCAL} does: signed by her DID, and embedding the gateway keys in
691
- * its `assertionMethod`.
692
- */
693
- async function createGatewayLoader(keyPairs, origin = LOCAL) {
694
- const { federation } = setup({
695
- aliceKeyPairs: keyPairs,
696
- mapPortableActorId: mapAlice
697
- });
698
- const keys = await federation.createContext(new URL(origin)).getActorKeyPairs("alice");
699
- const document = await (await signObject(new Person({
700
- id: aliceId,
701
- inbox: parseIri(`${aliceId.href}/inbox`),
702
- gateways: [
703
- new URL(LOCAL),
704
- new URL(GATEWAY2),
705
- new URL(GATEWAY3)
706
- ],
707
- assertionMethods: keys.map((k) => k.multikey)
708
- }), ed25519PrivateKey, keyId, { contextLoader: mockDocumentLoader })).toJsonLd({ contextLoader: mockDocumentLoader });
709
- return (url) => {
710
- if (url.replace(/#.*$/, "") !== compatibleAliceId(origin)) return mockDocumentLoader(url);
711
- return Promise.resolve({
712
- contextUrl: null,
713
- documentUrl: url,
714
- document: structuredClone(document)
715
- });
716
- };
717
- }
718
- function toRequest({ url, headers, body }) {
719
- return new Request(url, {
720
- method: "POST",
721
- headers,
722
- body
723
- });
724
- }
725
- async function assertSignedBy(request, expectedKeyId, documentLoader) {
726
- assertEquals(signatureKeyId(request.headers), expectedKeyId);
727
- const result = await verifyRequestDetailed(toRequest(request), {
728
- documentLoader,
729
- contextLoader: mockDocumentLoader
730
- });
731
- assert(result.verified, JSON.stringify(result));
732
- assertEquals(result.key.id?.href, expectedKeyId);
733
- }
734
- /** Records the requests made to the gateways other than {@link LOCAL}. */
735
- function captureGatewayRequests(respond = () => new Response(null, { status: 202 })) {
736
- const requests = [];
737
- esm_default.spyGlobal();
738
- for (const gateway of [GATEWAY2, GATEWAY3]) esm_default.post(`begin:${gateway}/`, async (callLog) => {
739
- const request = callLog.request;
740
- const captured = {
741
- url: request.url,
742
- headers: new Headers(request.headers),
743
- body: await request.text()
744
- };
745
- requests.push(captured);
746
- return respond(captured);
747
- });
748
- return requests;
749
- }
750
- test("Federation.fetch() signs forwarded portable inbox deliveries with gateway keys", async (t) => {
751
- const keyOrders = [[
752
- "RSA key first",
753
- [rsaGatewayKeyPair, otherKeyPair],
754
- "#main-key"
755
- ], [
756
- "Ed25519 key first",
757
- [otherKeyPair, rsaGatewayKeyPair],
758
- "#key-2"
759
- ]];
760
- for (const [name, aliceKeyPairs, fragment] of keyOrders) await t.step(name, async () => {
761
- const requests = captureGatewayRequests();
762
- try {
763
- const kv = new MemoryKvStore();
764
- const { federation, received } = setup({
765
- kv,
766
- aliceKeyPairs,
767
- mapPortableActorId: mapAlice,
768
- options: { allowPrivateAddress: true }
769
- });
770
- const json = await signedFollow();
771
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
772
- assertEquals(received.length, 1);
773
- assertEquals(requests.map((r) => r.url).sort(), [inboxUrl(did, "/users/alice/inbox", GATEWAY3), inboxUrl(did, "/users/alice/inbox", GATEWAY2)]);
774
- const loader = await createGatewayLoader(aliceKeyPairs);
775
- for (const request of requests) {
776
- await assertSignedBy(request, compatibleAliceId() + fragment, loader);
777
- assertEquals(JSON.parse(request.body), json);
778
- }
779
- assertEquals(await kv.get([
780
- "_fedify",
781
- "httpMessageSignaturesSpec",
782
- GATEWAY2
783
- ]), "rfc9421");
784
- } finally {
785
- esm_default.hardReset();
786
- }
787
- });
788
- });
789
- test("Federation.fetch() signs queued forwarded portable inbox deliveries with gateway keys", async () => {
790
- const queue = new RecordingQueue();
791
- const aliceKeyPairs = [otherKeyPair, rsaGatewayKeyPair];
792
- const { federation } = setup({
793
- queue,
794
- aliceKeyPairs,
795
- mapPortableActorId: mapAlice,
796
- options: { allowPrivateAddress: true }
797
- });
798
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
799
- assertEquals(queue.outbox.length, 2);
800
- const expectedKeyId = `${compatibleAliceId()}#key-2`;
801
- for (const message of queue.outbox) {
802
- assertEquals(message.keys.map((k) => k.keyId), [expectedKeyId]);
803
- assertEquals(message.keys[0].privateKey.kty, "RSA");
804
- }
805
- const requests = captureGatewayRequests();
806
- try {
807
- for (const message of queue.outbox) await federation.processQueuedTask(void 0, message);
808
- } finally {
809
- esm_default.hardReset();
810
- }
811
- assertEquals(requests.length, 2);
812
- const loader = await createGatewayLoader(aliceKeyPairs);
813
- for (const request of requests) await assertSignedBy(request, expectedKeyId, loader);
814
- });
815
- test("Federation.fetch() forwards portable inbox deliveries unsigned without gateway keys", async (t) => {
816
- const otherActorId = parseIri(`ap+ef61://${otherDid}/users/alice`);
817
- const cases = [
818
- ["without a mapper", { aliceKeyPairs: [rsaGatewayKeyPair] }],
819
- ["the mapper returns null", {
820
- aliceKeyPairs: [rsaGatewayKeyPair],
821
- mapPortableActorId: () => null
822
- }],
823
- ["the mapper returns another actor", {
824
- aliceKeyPairs: [rsaGatewayKeyPair],
825
- mapPortableActorId: () => otherActorId
826
- }],
827
- ["the mapper returns another actor of the same DID", {
828
- aliceKeyPairs: [rsaGatewayKeyPair],
829
- mapPortableActorId: () => parseIri(`ap+ef61://${did}/users/bob`)
830
- }],
831
- ["without a key pairs dispatcher", {
832
- keyPairs: false,
833
- mapPortableActorId: mapAlice
834
- }],
835
- ["without key pairs", { mapPortableActorId: mapAlice }],
836
- ["without an RSA key", {
837
- aliceKeyPairs: [otherKeyPair],
838
- mapPortableActorId: mapAlice
839
- }]
840
- ];
841
- for (const [name, options] of cases) await t.step(name, async () => {
842
- const queue = new RecordingQueue();
843
- const { federation, received } = setup({
844
- ...options,
845
- queue
846
- });
847
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
848
- assertEquals(received.length, 1);
849
- assertEquals(queue.outbox.length, 2);
850
- for (const message of queue.outbox) assertEquals(message.keys, []);
851
- });
852
- });
853
- test("Federation.fetch() signs forwarded portable inbox deliveries if the mapper returns an equivalent ID", async (t) => {
854
- const ids = [
855
- ["ap: URI", parseIri(`ap://${did}/users/alice`)],
856
- ["percent-encoded DID", parseIri(`ap+ef61://${did.replaceAll(":", "%3A")}/users/alice`)],
857
- ["compatible identifier", new URL(compatibleAliceId(GATEWAY2))]
858
- ];
859
- for (const [name, id] of ids) await t.step(name, async () => {
860
- const queue = new RecordingQueue();
861
- const { federation } = setup({
862
- queue,
863
- aliceKeyPairs: [rsaGatewayKeyPair],
864
- mapPortableActorId: (identifier) => identifier === "alice" ? id : null
865
- });
866
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
867
- assertEquals(queue.outbox.length, 2);
868
- for (const message of queue.outbox) assertEquals(message.keys.map((k) => k.keyId), [`${compatibleAliceId()}#main-key`]);
869
- });
870
- });
871
- test("Federation.fetch() signs forwarded portable inbox deliveries with the gateway keys of the canonical origin", async () => {
872
- const queue = new RecordingQueue();
873
- const { federation } = setup({
874
- queue,
875
- gateways: [
876
- GATEWAY2,
877
- LOCAL,
878
- GATEWAY3
879
- ],
880
- aliceKeyPairs: [rsaGatewayKeyPair],
881
- mapPortableActorId: mapAlice,
882
- options: { origin: GATEWAY2 }
883
- });
884
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
885
- assertEquals(queue.outbox.length, 1);
886
- assertEquals(queue.outbox[0].keys.map((k) => k.keyId), [`${compatibleAliceId(GATEWAY2)}#main-key`]);
887
- });
888
- test("Federation.fetch() double-knocks forwarded portable inbox deliveries", async (t) => {
889
- await t.step("firstKnock", async () => {
890
- const requests = captureGatewayRequests();
891
- try {
892
- const { federation } = setup({
893
- aliceKeyPairs: [rsaGatewayKeyPair],
894
- mapPortableActorId: mapAlice,
895
- options: {
896
- allowPrivateAddress: true,
897
- firstKnock: "draft-cavage-http-signatures-12"
898
- }
899
- });
900
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
901
- assertEquals(requests.length, 2);
902
- for (const request of requests) {
903
- assert(request.headers.has("Signature"));
904
- assertFalse(request.headers.has("Signature-Input"));
905
- }
906
- } finally {
907
- esm_default.hardReset();
908
- }
909
- });
910
- await t.step("falls back to the other spec", async () => {
911
- const requests = captureGatewayRequests((request) => new Response(null, { status: request.headers.has("Signature-Input") ? 401 : 202 }));
912
- try {
913
- const kv = new MemoryKvStore();
914
- const { federation } = setup({
915
- kv,
916
- aliceKeyPairs: [rsaGatewayKeyPair],
917
- mapPortableActorId: mapAlice,
918
- options: { allowPrivateAddress: true }
919
- });
920
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
921
- assertEquals(requests.length, 4);
922
- const loader = await createGatewayLoader([rsaGatewayKeyPair]);
923
- for (const request of requests) {
924
- if (request.headers.has("Signature-Input")) continue;
925
- await assertSignedBy(request, `${compatibleAliceId()}#main-key`, loader);
926
- }
927
- assertEquals(await kv.get([
928
- "_fedify",
929
- "httpMessageSignaturesSpec",
930
- GATEWAY2
931
- ]), "draft-cavage-http-signatures-12");
932
- } finally {
933
- esm_default.hardReset();
934
- }
935
- });
936
- });
937
- test("A Fedify gateway accepts signed forwarded portable inbox deliveries", async () => {
938
- const requests = captureGatewayRequests();
939
- let forwarded;
940
- try {
941
- const { federation } = setup({
942
- aliceKeyPairs: [rsaGatewayKeyPair],
943
- mapPortableActorId: mapAlice,
944
- options: { allowPrivateAddress: true }
945
- });
946
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
947
- forwarded = requests.find((r) => r.url.startsWith(`${GATEWAY2}/`));
948
- } finally {
949
- esm_default.hardReset();
950
- }
951
- await assertSignedBy(forwarded, `${compatibleAliceId()}#main-key`, await createGatewayLoader([rsaGatewayKeyPair]));
952
- const queue = new RecordingQueue();
953
- const loader = await createGatewayLoader([rsaGatewayKeyPair]);
954
- const { federation, received } = setup({
955
- queue,
956
- options: {
957
- origin: GATEWAY2,
958
- documentLoaderFactory: () => loader
959
- }
960
- });
961
- assertEquals((await federation.fetch(toRequest(forwarded), { contextData: void 0 })).status, 202);
962
- assertEquals(received.length, 1);
963
- assertEquals(received[0].recipient, "alice");
964
- assertEquals(queue.outbox.map((m) => m.inbox), [inboxUrl(did, "/users/alice/inbox", GATEWAY3)]);
965
- });
966
- /** Records the URLs that a document loader is asked for. */
967
- function recordLoader(loader) {
968
- const urls = [];
969
- return {
970
- urls,
971
- loader: (url, options) => {
972
- urls.push(url);
973
- return loader(url, options);
974
- }
975
- };
976
- }
977
- const gateway2KeyId = new URL(`${compatibleAliceId(GATEWAY2)}#main-key`);
978
- /** Signs a delivery to Alice's inbox on {@link LOCAL}. */
979
- async function signDelivery(body, { keyId = gateway2KeyId, privateKey = rsaGatewayKeyPair.privateKey, spec = "draft-cavage-http-signatures-12", components, label, headers } = {}) {
980
- const signed = await signRequest(post(inboxUrl(), body, headers), privateKey, keyId, {
981
- spec,
982
- ...components == null ? {} : { body: null },
983
- rfc9421: {
984
- label,
985
- components: components?.map((value) => ({
986
- value,
987
- params: {}
988
- }))
989
- }
990
- });
991
- return new Request(signed.url, {
992
- method: "POST",
993
- headers: signed.headers,
994
- body: JSON.stringify(body)
995
- });
996
- }
997
- async function deliverToGateway(request, { loader, kv, maxTargets, maxHttpSignatures }) {
998
- const queue = new RecordingQueue();
999
- const { federation, received, kv: store } = setup({
1000
- queue,
1001
- kv,
1002
- options: {
1003
- documentLoaderFactory: () => loader,
1004
- maxHttpSignatures,
1005
- ...maxTargets == null ? {} : { portableInboxForwarding: { maxTargets } }
1006
- }
1007
- });
1008
- const response = await federation.fetch(request, { contextData: void 0 });
1009
- assert(received.length <= 1);
1010
- return {
1011
- response,
1012
- queue,
1013
- kv: store
1014
- };
1015
- }
1016
- function forwardedGateways(queue) {
1017
- return queue.outbox.map((m) => new URL(m.inbox).origin).sort();
1018
- }
1019
- test("Federation.fetch() does not forward portable inbox deliveries back to the gateway that forwarded them", async (t) => {
1020
- const gatewayLoader = await createGatewayLoader([rsaGatewayKeyPair], GATEWAY2);
1021
- for (const spec of ["draft-cavage-http-signatures-12", "rfc9421"]) await t.step(spec, async () => {
1022
- const { loader, urls } = recordLoader(gatewayLoader);
1023
- const json = await signedFollow();
1024
- const { response, queue, kv } = await deliverToGateway(await signDelivery(json, { spec }), { loader });
1025
- assertEquals(response.status, 202);
1026
- assertEquals(forwardedGateways(queue), [GATEWAY3]);
1027
- assertEquals(urls.filter((u) => u.startsWith(GATEWAY2)), [gateway2KeyId.href]);
1028
- const { queue: queue2 } = await deliverToGateway(post(inboxUrl(), json), {
1029
- loader,
1030
- kv
1031
- });
1032
- assertEquals(queue2.outbox, []);
1033
- });
1034
- await t.step("identified before the targets are capped", async () => {
1035
- const { queue } = await deliverToGateway(await signDelivery(await signedFollow()), {
1036
- loader: gatewayLoader,
1037
- maxTargets: 1
1038
- });
1039
- assertEquals(forwardedGateways(queue), [GATEWAY3]);
1040
- });
1041
- await t.step("with an unrelated signature first", async () => {
1042
- const { loader, urls } = recordLoader(gatewayLoader);
1043
- const json = await signedFollow();
1044
- const unrelated = await signDelivery(json, {
1045
- spec: "rfc9421",
1046
- keyId: new URL("https://unrelated.example/key"),
1047
- privateKey: rsaPrivateKey3,
1048
- label: "sig1"
1049
- });
1050
- const gateway = await signDelivery(json, {
1051
- spec: "rfc9421",
1052
- label: "sig2"
1053
- });
1054
- const headers = new Headers(gateway.headers);
1055
- for (const name of ["Signature-Input", "Signature"]) headers.set(name, `${unrelated.headers.get(name)}, ${gateway.headers.get(name)}`);
1056
- const { queue } = await deliverToGateway(new Request(gateway.url, {
1057
- method: "POST",
1058
- headers,
1059
- body: JSON.stringify(json)
1060
- }), { loader });
1061
- assertEquals(forwardedGateways(queue), [GATEWAY3]);
1062
- assertFalse(urls.some((u) => u.startsWith("https://unrelated.example/")));
1063
- });
1064
- await t.step("with the gateway's signature beyond maxHttpSignatures", async () => {
1065
- const json = await signedFollow();
1066
- const unrelated = await signDelivery(json, {
1067
- spec: "rfc9421",
1068
- keyId: new URL("https://unrelated.example/key"),
1069
- privateKey: rsaPrivateKey3,
1070
- label: "sig1"
1071
- });
1072
- const gateway = await signDelivery(json, {
1073
- spec: "rfc9421",
1074
- label: "sig2"
1075
- });
1076
- const headers = new Headers(gateway.headers);
1077
- for (const name of ["Signature-Input", "Signature"]) headers.set(name, `${unrelated.headers.get(name)}, ${gateway.headers.get(name)}`);
1078
- const request = () => new Request(gateway.url, {
1079
- method: "POST",
1080
- headers,
1081
- body: JSON.stringify(json)
1082
- });
1083
- for (const [maxHttpSignatures, expected] of [[2, [GATEWAY3]], [1, [GATEWAY2, GATEWAY3]]]) {
1084
- const { loader, urls } = recordLoader(gatewayLoader);
1085
- const { queue } = await deliverToGateway(request(), {
1086
- loader,
1087
- maxHttpSignatures
1088
- });
1089
- assertEquals(forwardedGateways(queue), [...expected].sort());
1090
- assertEquals(urls.some((u) => u.startsWith(GATEWAY2)), maxHttpSignatures > 1);
1091
- }
1092
- });
1093
- await t.step("activity authenticated by a Linked Data Signature", async () => {
1094
- const { queue } = await deliverToGateway(await signDelivery(await signJsonLd({
1095
- "@context": "https://www.w3.org/ns/activitystreams",
1096
- id: `https://example.com/follows/lds-${++activityCounter}`,
1097
- type: "Follow",
1098
- actor: "https://example.com/person2",
1099
- object: formatIri(aliceId)
1100
- }, rsaPrivateKey3, rsaPublicKey3.id, { contextLoader: mockDocumentLoader })), { loader: gatewayLoader });
1101
- assertEquals(forwardedGateways(queue), [GATEWAY3]);
1102
- });
1103
- });
1104
- test("Federation.fetch() forwards portable inbox deliveries whose sending gateway is not identified", async (t) => {
1105
- const gatewayLoader = await createGatewayLoader([rsaGatewayKeyPair], GATEWAY2);
1106
- const bobKeyId = new URL(`${GATEWAY2}/.well-known/apgateway/${did}/users/bob#main-key`);
1107
- const compatibleId = new URL(compatibleAliceId(GATEWAY2));
1108
- const unsignedActor = await new Person({
1109
- id: compatibleId,
1110
- inbox: new URL(`${compatibleId.href}/inbox`),
1111
- publicKey: rsaPublicKey2.clone({
1112
- id: gateway2KeyId,
1113
- owner: compatibleId
1114
- })
1115
- }).toJsonLd({ contextLoader: mockDocumentLoader });
1116
- const unsignedLoader = (url) => {
1117
- if (url.replace(/#.*$/, "") !== compatibleId.href) return mockDocumentLoader(url);
1118
- return Promise.resolve({
1119
- contextUrl: null,
1120
- documentUrl: url,
1121
- document: structuredClone(unsignedActor)
1122
- });
1123
- };
1124
- const json = await signedFollow();
1125
- const contentDigest = `sha-256=:${encodeBase64(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(json))))}:`;
1126
- const cases = [
1127
- {
1128
- name: "unsigned",
1129
- unsigned: true,
1130
- fetches: false
1131
- },
1132
- {
1133
- name: "invalid signature",
1134
- sign: { privateKey: rsaPrivateKey2 },
1135
- fetches: true
1136
- },
1137
- {
1138
- name: "unknown key",
1139
- loader: mockDocumentLoader,
1140
- fetches: true
1141
- },
1142
- {
1143
- name: "gateway not in gateways",
1144
- sign: { keyId: new URL(`https://unlisted.example/.well-known/apgateway/${did}/users/alice#main-key`) },
1145
- fetches: false
1146
- },
1147
- {
1148
- name: "key of another actor",
1149
- sign: { keyId: bobKeyId },
1150
- fetches: false
1151
- },
1152
- {
1153
- name: "key at an ap: key ID",
1154
- sign: { keyId: parseIri(`ap+ef61://${did}/users/alice?@gateway=${encodeURIComponent(GATEWAY2)}#main-key`) },
1155
- fetches: false
1156
- },
1157
- {
1158
- name: "content-digest not covered",
1159
- sign: {
1160
- spec: "rfc9421",
1161
- components: ["@method", "@target-uri"]
1162
- },
1163
- fetches: false
1164
- },
1165
- {
1166
- name: "target URI not covered",
1167
- sign: {
1168
- spec: "rfc9421",
1169
- components: [
1170
- "@method",
1171
- "@authority",
1172
- "@path",
1173
- "content-digest"
1174
- ],
1175
- headers: { "Content-Digest": contentDigest }
1176
- },
1177
- fetches: false
1178
- },
1179
- {
1180
- name: "non-canonical spelling of content-digest",
1181
- sign: {
1182
- spec: "rfc9421",
1183
- components: [
1184
- "@method",
1185
- "@target-uri",
1186
- "Content-Digest"
1187
- ],
1188
- headers: { "Content-Digest": "sha-256=:AAAA:" }
1189
- },
1190
- fetches: false
1191
- },
1192
- {
1193
- name: "key not vouched for by the DID",
1194
- sign: { privateKey: rsaPrivateKey2 },
1195
- loader: unsignedLoader,
1196
- fetches: true
1197
- }
1198
- ];
1199
- for (const { name, sign, unsigned, loader, fetches } of cases) await t.step(name, async () => {
1200
- const recorded = recordLoader(loader ?? gatewayLoader);
1201
- const { response, queue } = await deliverToGateway(unsigned ? post(inboxUrl(), json) : await signDelivery(json, sign), { loader: recorded.loader });
1202
- assertEquals(response.status, 202);
1203
- assertEquals(forwardedGateways(queue), [GATEWAY3, GATEWAY2].sort());
1204
- assertEquals(recorded.urls.some((u) => u.includes("/.well-known/apgateway/")), fetches);
1205
- });
1206
- await t.step("already forwarded to the gateway", async () => {
1207
- const recorded = recordLoader(gatewayLoader);
1208
- const kv = new MemoryKvStore();
1209
- const json = await signedFollow();
1210
- const { queue } = await deliverToGateway(post(inboxUrl(), json), {
1211
- loader: recorded.loader,
1212
- kv
1213
- });
1214
- assertEquals(forwardedGateways(queue), [GATEWAY3, GATEWAY2].sort());
1215
- const { queue: queue2 } = await deliverToGateway(await signDelivery(json), {
1216
- loader: recorded.loader,
1217
- kv
1218
- });
1219
- assertEquals(queue2.outbox, []);
1220
- assertEquals(recorded.urls.filter((u) => u.startsWith(GATEWAY2)), []);
1221
- });
1222
- });
1223
- function forwardingParameters(overrides = {}) {
1224
- const activityId = parseIri(`ap+ef61://${did}/follows/${++activityCounter}`);
1225
- return {
1226
- recipient: {
1227
- actorId: aliceId,
1228
- inboxId: parseIri(`ap+ef61://${did}/users/alice/inbox`),
1229
- canonicalInboxId: `ap://${did}/users/alice/inbox`,
1230
- gateways: [new URL(LOCAL), new URL(GATEWAY2)]
1231
- },
1232
- activity: { id: formatIri(activityId) },
1233
- activityId,
1234
- activityType: "https://www.w3.org/ns/activitystreams#Follow",
1235
- excludedOrigins: [LOCAL],
1236
- baseUrl: LOCAL,
1237
- kv: new MemoryKvStore(),
1238
- kvPrefix: ["_fedify", "portableInboxForwarding"],
1239
- allowPrivateAddress: true,
1240
- ...overrides
1241
- };
1242
- }
1243
- const gatewayKey = {
1244
- keyId: new URL(`${compatibleAliceId()}#main-key`),
1245
- privateKey: rsaGatewayKeyPair.privateKey
1246
- };
1247
- test("forwardPortableInboxActivity() gets keys only when it forwards", async () => {
1248
- let calls = 0;
1249
- const parameters = forwardingParameters({
1250
- outboxQueue: new RecordingQueue(),
1251
- getKeys: () => {
1252
- calls++;
1253
- return Promise.resolve([gatewayKey]);
1254
- }
1255
- });
1256
- assertEquals((await forwardPortableInboxActivity(parameters)).length, 1);
1257
- assertEquals(calls, 1);
1258
- assertEquals(await forwardPortableInboxActivity(parameters), []);
1259
- assertEquals(calls, 1);
1260
- });
1261
- test("forwardPortableInboxActivity() forwards unsigned if it cannot get keys", async (t) => {
1262
- const nonExtractable = await crypto.subtle.generateKey({
1263
- name: "RSASSA-PKCS1-v1_5",
1264
- modulusLength: 2048,
1265
- publicExponent: new Uint8Array([
1266
- 1,
1267
- 0,
1268
- 1
1269
- ]),
1270
- hash: "SHA-256"
1271
- }, false, ["sign", "verify"]);
1272
- const getKeysCases = [["getKeys() rejects", () => Promise.reject(/* @__PURE__ */ new Error("Unavailable."))], ["the key is not extractable", () => Promise.resolve([{
1273
- keyId: gatewayKey.keyId,
1274
- privateKey: nonExtractable.privateKey
1275
- }])]];
1276
- for (const [name, getKeys] of getKeysCases) {
1277
- await t.step(`${name} (queued)`, async () => {
1278
- const queue = new RecordingQueue();
1279
- assertEquals((await forwardPortableInboxActivity(forwardingParameters({
1280
- outboxQueue: queue,
1281
- getKeys
1282
- }))).length, 1);
1283
- assertEquals(queue.outbox.length, 1);
1284
- assertEquals(queue.outbox[0].keys, []);
1285
- });
1286
- await t.step(`${name} (immediate)`, async () => {
1287
- const requests = captureGatewayRequests();
1288
- try {
1289
- assertEquals((await forwardPortableInboxActivity(forwardingParameters({ getKeys }))).length, 1);
1290
- } finally {
1291
- esm_default.hardReset();
1292
- }
1293
- assertEquals(requests.length, 1);
1294
- assertEquals(signatureKeyId(requests[0].headers), void 0);
1295
- });
1296
- }
1297
- });
1298
- test("forwardPortableInboxActivity() does not wait for slow keys", async () => {
1299
- let release = () => {};
1300
- const pending = new Promise((resolve) => release = resolve);
1301
- const requests = captureGatewayRequests();
1302
- try {
1303
- const started = performance.now();
1304
- const forwarded = await forwardPortableInboxActivity(forwardingParameters({
1305
- options: resolvePortableInboxForwardingOptions({ deadline: { milliseconds: 10 } }),
1306
- getKeys: async () => {
1307
- await pending;
1308
- throw new Error("Unavailable.");
1309
- }
1310
- }));
1311
- assert(performance.now() - started < 5e3);
1312
- assertEquals(forwarded.length, 1);
1313
- assertEquals(requests.length, 0);
1314
- release();
1315
- for (let i = 0; i < 100 && requests.length < 1; i++) await new Promise((resolve) => setTimeout(resolve, 10));
1316
- assertEquals(requests.length, 1);
1317
- assertEquals(signatureKeyId(requests[0].headers), void 0);
1318
- } finally {
1319
- esm_default.hardReset();
1320
- }
1321
- });
1322
- function gatewaySignature(keyId, verify) {
1323
- return {
1324
- keyId,
1325
- coversDelivery: true,
1326
- verify
1327
- };
1328
- }
1329
- function gatewayKeyOf(keyId, owner = aliceId) {
1330
- return new CryptographicKey({
1331
- id: keyId,
1332
- owner,
1333
- publicKey: rsaGatewayKeyPair.publicKey
1334
- });
1335
- }
1336
- test("forwardPortableInboxActivity() skips the gateway that forwarded the activity", async (t) => {
1337
- const recipient = {
1338
- actorId: parseIri(`ap://${did}/users/alice`),
1339
- inboxId: parseIri(`ap+ef61://${did}/users/alice/inbox`),
1340
- canonicalInboxId: `ap://${did}/users/alice/inbox`,
1341
- gateways: [
1342
- new URL(LOCAL),
1343
- new URL(GATEWAY3),
1344
- new URL(GATEWAY2)
1345
- ]
1346
- };
1347
- const owners = [["identified", aliceId], ["identified by a key of a compatible identifier", new URL(compatibleAliceId())]];
1348
- for (const [name, owner] of owners) await t.step(name, async () => {
1349
- const queue = new RecordingQueue();
1350
- assertEquals((await forwardPortableInboxActivity(forwardingParameters({
1351
- recipient,
1352
- outboxQueue: queue,
1353
- signatures: [gatewaySignature(gateway2KeyId, () => Promise.resolve(gatewayKeyOf(gateway2KeyId, owner)))]
1354
- }))).map((u) => u.origin), [GATEWAY3]);
1355
- });
1356
- const notIdentified = [
1357
- ["verify() rejects", [gatewaySignature(gateway2KeyId, () => Promise.reject(/* @__PURE__ */ new Error("Failed.")))]],
1358
- ["verify() throws", [gatewaySignature(gateway2KeyId, () => {
1359
- throw new Error("Failed.");
1360
- })]],
1361
- ["not verified", [gatewaySignature(gateway2KeyId, () => Promise.resolve(null))]],
1362
- ["the key is not owned by a portable actor", [gatewaySignature(gateway2KeyId, () => Promise.resolve(gatewayKeyOf(gateway2KeyId, new URL(`${GATEWAY2}/users/alice`))))]],
1363
- ["the key is owned by another actor", [gatewaySignature(gateway2KeyId, () => Promise.resolve(gatewayKeyOf(gateway2KeyId, parseIri(`ap://${did}/users/bob`))))]],
1364
- ["another key is verified", [gatewaySignature(gateway2KeyId, () => Promise.resolve(gatewayKeyOf(new URL(`${compatibleAliceId(GATEWAY3)}#main-key`))))]],
1365
- ["the signature does not cover the delivery", [{
1366
- ...gatewaySignature(gateway2KeyId, () => Promise.resolve(gatewayKeyOf(gateway2KeyId))),
1367
- coversDelivery: false
1368
- }]]
1369
- ];
1370
- for (const [name, signatures] of notIdentified) await t.step(name, async () => {
1371
- const queue = new RecordingQueue();
1372
- assertEquals((await forwardPortableInboxActivity(forwardingParameters({
1373
- recipient,
1374
- outboxQueue: queue,
1375
- signatures
1376
- }))).map((u) => u.origin), [GATEWAY3, GATEWAY2]);
1377
- });
1378
- await t.step("verified only if it may save a request", async (t) => {
1379
- const cases = [
1380
- ["forwarding is turned off", { options: resolvePortableInboxForwardingOptions({ maxTargets: 0 }) }],
1381
- ["no compare-and-swap", { kv: {
1382
- ...new MemoryKvStore(),
1383
- cas: void 0
1384
- } }],
1385
- ["this server", { excludedOrigins: [LOCAL, GATEWAY2] }]
1386
- ];
1387
- for (const [name, overrides] of cases) await t.step(name, async () => {
1388
- let calls = 0;
1389
- await forwardPortableInboxActivity(forwardingParameters({
1390
- recipient,
1391
- outboxQueue: new RecordingQueue(),
1392
- signatures: [gatewaySignature(gateway2KeyId, () => {
1393
- calls++;
1394
- return Promise.resolve(gatewayKeyOf(gateway2KeyId));
1395
- })],
1396
- ...overrides
1397
- }));
1398
- assertEquals(calls, 0);
1399
- });
1400
- });
1401
- await t.step("verification does not finish in time", async () => {
1402
- let release = () => {};
1403
- const pending = new Promise((resolve) => release = resolve);
1404
- const kv = new MemoryKvStore();
1405
- const parameters = forwardingParameters({
1406
- recipient,
1407
- kv,
1408
- outboxQueue: new RecordingQueue(),
1409
- options: resolvePortableInboxForwardingOptions({
1410
- maxTargets: 1,
1411
- deadline: { milliseconds: 10 }
1412
- }),
1413
- signatures: [gatewaySignature(gateway2KeyId, () => pending)]
1414
- });
1415
- const started = performance.now();
1416
- const forwarded = await forwardPortableInboxActivity(parameters);
1417
- assert(performance.now() - started < 5e3);
1418
- assertEquals(forwarded.map((u) => u.origin), [GATEWAY3]);
1419
- release(gatewayKeyOf(gateway2KeyId));
1420
- await new Promise((resolve) => setTimeout(resolve, 20));
1421
- const claimed = [];
1422
- for await (const { key } of kv.list(parameters.kvPrefix)) claimed.push(String(key.at(-1)));
1423
- assertEquals(claimed, [GATEWAY3]);
1424
- });
1425
- });
1426
- test("coversDelivery()", () => {
1427
- const signature = (label, ...names) => ({
1428
- keyId: gateway2KeyId,
1429
- label,
1430
- components: names.map((value) => ({
1431
- value,
1432
- params: {}
1433
- }))
1434
- });
1435
- assert(coversDelivery(signature("sig1", "@method", "@target-uri", "@authority", "content-digest")));
1436
- assert(coversDelivery(signature(null, "(request-target)", "host", "date", "digest")));
1437
- assertFalse(coversDelivery(signature("sig1", "@method", "@target-uri")));
1438
- assertFalse(coversDelivery(signature("sig1", "@method", "@target-uri", "Content-Digest")));
1439
- assertFalse(coversDelivery(signature("sig1", "@method", "@authority", "@path", "content-digest")));
1440
- assertFalse(coversDelivery(signature(null, "(request-target)", "digest")));
1441
- assertFalse(coversDelivery({
1442
- keyId: gateway2KeyId,
1443
- label: "sig1",
1444
- components: [
1445
- {
1446
- value: "@method",
1447
- params: {}
1448
- },
1449
- {
1450
- value: "@target-uri",
1451
- params: {}
1452
- },
1453
- {
1454
- value: "content-digest",
1455
- params: { req: true }
1456
- }
1457
- ]
1458
- }));
1459
- });
1460
- test("Context.getPortableInboxUri()", async (t) => {
1461
- const { federation } = setup();
1462
- await t.step("Context", () => {
1463
- const ctx = federation.createContext(new URL(LOCAL), void 0);
1464
- const uri = ctx.getPortableInboxUri("alice", did);
1465
- assertEquals(uri.protocol, "ap+ef61:");
1466
- assertEquals(formatIri(uri), `ap+ef61://${did}/users/alice/inbox`);
1467
- assertThrows(() => ctx.getPortableInboxUri("alice", "not-a-did"), TypeError);
1468
- });
1469
- await t.step("RequestContext without portable request", () => {
1470
- const ctx = federation.createContext(new Request(LOCAL), void 0);
1471
- assertThrows(() => ctx.getPortableInboxUri("alice"), TypeError);
1472
- assertEquals(formatIri(ctx.getPortableInboxUri("alice", did)), `ap+ef61://${did}/users/alice/inbox`);
1473
- });
1474
- });
1475
- test("Federation.fetch() serves and delivers to one portable actor dispatcher", async () => {
1476
- const { federation, received } = setup({ actor: async (ctx, identifier) => {
1477
- if (identifier !== "alice") return null;
1478
- if (ctx.portableRequest != null && ctx.portableRequest.authority !== did) return null;
1479
- return await signObject(new Person({
1480
- id: ctx.getPortableActorUri(identifier, did),
1481
- inbox: ctx.getPortableInboxUri(identifier, did),
1482
- gateways: [new URL(LOCAL)]
1483
- }), ed25519PrivateKey, keyId, { contextLoader: mockDocumentLoader });
1484
- } });
1485
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
1486
- assertEquals(received.length, 1);
1487
- assertEquals(received[0].recipient, "alice");
1488
- const get = (authority) => federation.fetch(new Request(inboxUrl(authority, "/users/alice"), { headers: { Accept: "application/activity+json" } }), { contextData: void 0 });
1489
- const actor = await get(did);
1490
- assertEquals(actor.status, 200);
1491
- const json = await actor.json();
1492
- assertEquals(json.id, `ap+ef61://${did}/users/alice`);
1493
- assertEquals(json.inbox, `ap+ef61://${did}/users/alice/inbox`);
1494
- assertEquals((await get(otherDid)).status, 404);
1495
- });
1496
- test("Federation.fetch() keeps ordinary inbox deliveries unchanged", async () => {
1497
- const queue = new RecordingQueue();
1498
- const { federation, received } = setup({ queue });
1499
- assertEquals((await federation.fetch(post(`${LOCAL}/users/alice/inbox`, await signedFollow()), { contextData: void 0 })).status, 202);
1500
- assertEquals(received.length, 1);
1501
- assertEquals(queue.outbox.length, 0);
1502
- });
1503
- test("onRequestFinished covers portable ingress and recipient lookup failures", async () => {
1504
- const { federation, reports } = setup({ options: { portableInboxForwarding: { maxTargets: 0 } } });
1505
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
1506
- assertEquals(reports.length, 1);
1507
- assertEquals(reports[0].inbox, {
1508
- kind: "portable",
1509
- recipient: "alice"
1510
- });
1511
- assertEquals(reports[0].authentication.status, "verified");
1512
- assert(reports[0].attempts.some((attempt) => attempt.subject.pointer === "" && attempt.status === "verified"));
1513
- const absent = setup({ actor: () => null });
1514
- assertEquals((await absent.federation.fetch(post(inboxUrl(), {}), { contextData: void 0 })).status, 404);
1515
- assertEquals(absent.reports[0].payload, { status: "unavailable" });
1516
- assertEquals(absent.reports[0].authentication, { status: "notDetermined" });
1517
- const failure = /* @__PURE__ */ new Error("recipient lookup failed");
1518
- const broken = setup({ actor: () => {
1519
- throw failure;
1520
- } });
1521
- let thrown;
1522
- try {
1523
- await broken.federation.fetch(post(inboxUrl(), {}), { contextData: void 0 });
1524
- } catch (error) {
1525
- thrown = error;
1526
- }
1527
- assertEquals(thrown, failure);
1528
- assertEquals(broken.reports.length, 1);
1529
- assertEquals(broken.reports[0].outcome, {
1530
- type: "exception",
1531
- stage: "prepare",
1532
- error: failure
1533
- });
1534
- });
1535
- function replicationResult(events) {
1536
- assertEquals(events.map((event) => event.stage), ["started", "preparation-finished"]);
1537
- assertEquals(events.map((event) => event.operation), ["portable-replication", "portable-replication"]);
1538
- assertEquals(events[0].broadcastId, events[1].broadcastId);
1539
- const event = events[1];
1540
- assert(event.stage === "preparation-finished");
1541
- return event.result;
1542
- }
1543
- test("portable replication observers distinguish disabled, unavailable, and unclaimed work", async (t) => {
1544
- for (const scenario of [
1545
- "disabled",
1546
- "unavailable",
1547
- "no-targets"
1548
- ]) await t.step(scenario, async () => {
1549
- const memory = new MemoryKvStore();
1550
- const kv = scenario === "unavailable" ? {
1551
- get: (key) => memory.get(key),
1552
- set: (key, value, options) => memory.set(key, value, options),
1553
- delete: (key) => memory.delete(key),
1554
- list: (prefix) => memory.list(prefix)
1555
- } : memory;
1556
- const queue = new RecordingQueue();
1557
- const { federation } = setup({
1558
- kv,
1559
- queue,
1560
- keyPairs: false,
1561
- gateways: scenario === "no-targets" ? [LOCAL] : [LOCAL, GATEWAY2],
1562
- options: { portableInboxForwarding: { maxTargets: scenario === "disabled" ? 0 : 10 } }
1563
- });
1564
- const events = [];
1565
- const deliveries = [];
1566
- const contexts = [];
1567
- federation.setOutboundObservers({
1568
- onDelivery(_ctx, event) {
1569
- deliveries.push(event);
1570
- },
1571
- onBroadcast(ctx, event) {
1572
- contexts.push(ctx);
1573
- events.push(event);
1574
- }
1575
- });
1576
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
1577
- assertEquals(replicationResult(events), {
1578
- type: "skipped",
1579
- reason: scenario === "disabled" ? "forwarding-disabled" : scenario === "unavailable" ? "forwarding-unavailable" : "no-forwarding-targets"
1580
- });
1581
- assertEquals(events[0].activity, {});
1582
- assertEquals(events[1].activity.type, Follow.typeId.href);
1583
- assert(events[1].activity.id?.startsWith("ap+ef61://"));
1584
- assert(Object.isFrozen(events[1].activity));
1585
- assertStrictEquals(contexts[0], contexts[1]);
1586
- assertEquals(deliveries, []);
1587
- assertEquals(queue.outbox.length, 0);
1588
- });
1589
- });
1590
- test("portable replication observers preserve lazy enqueue, unsigned fallback, and failed claims", async (t) => {
1591
- await t.step("readiness precedes acceptance without delaying earlier handoffs", async () => {
1592
- const queue = new RecordingQueue();
1593
- let accept;
1594
- const acceptance = new Promise((resolve) => {
1595
- accept = resolve;
1596
- });
1597
- queue.enqueue = (message) => {
1598
- queue.messages.push(message);
1599
- return queue.messages.length === 1 ? acceptance.then(() => {
1600
- throw new Error("acceptance unknown");
1601
- }) : Promise.resolve();
1602
- };
1603
- const { federation, reports } = setup({
1604
- queue,
1605
- keyPairs: false
1606
- });
1607
- const events = [];
1608
- const deliveries = [];
1609
- let ready;
1610
- const prepared = new Promise((resolve) => {
1611
- ready = resolve;
1612
- });
1613
- let release;
1614
- const observerGate = new Promise((resolve) => {
1615
- release = resolve;
1616
- });
1617
- federation.setOutboundObservers({
1618
- onDelivery(_ctx, event) {
1619
- deliveries.push(event);
1620
- },
1621
- async onBroadcast(_ctx, event) {
1622
- events.push(event);
1623
- if (event.stage === "preparation-finished") {
1624
- ready();
1625
- await observerGate;
1626
- }
1627
- throw new Error("recorder failed");
1628
- }
1629
- });
1630
- const json = await signedFollow();
1631
- let settled = false;
1632
- const pending = federation.fetch(post(inboxUrl(), json), { contextData: void 0 }).finally(() => {
1633
- settled = true;
1634
- });
1635
- await prepared;
1636
- assertEquals(queue.outbox.length, 1);
1637
- assertFalse(settled);
1638
- assertEquals(replicationResult(events), {
1639
- type: "prepared",
1640
- preparedFor: "delivery",
1641
- destinationCount: 2
1642
- });
1643
- accept();
1644
- release();
1645
- assertEquals((await pending).status, 202);
1646
- assertEquals(queue.outbox.length, 2);
1647
- for (const message of queue.outbox) {
1648
- assertEquals(message.activity, json);
1649
- assertEquals(message.keys, []);
1650
- assertFalse("broadcastId" in message);
1651
- const plan = deliveries.find((event) => event.stage === "planned" && event.destinationInbox === message.inbox);
1652
- assert(plan);
1653
- assertEquals(message.outbound, {
1654
- broadcast: plan.broadcast,
1655
- deliveryId: plan.deliveryId,
1656
- destinationInbox: plan.destinationInbox,
1657
- portableInbox: plan.portableInbox
1658
- });
1659
- assertEquals(JSON.parse(JSON.stringify(message.outbound)), message.outbound);
1660
- assertEquals(structuredClone(message.outbound), message.outbound);
1661
- }
1662
- assertEquals(deliveries.filter((event) => event.stage === "planned").length, 2);
1663
- const handoffs = deliveries.filter((event) => event.stage === "handoff");
1664
- assertEquals(handoffs.length, 2);
1665
- assertEquals(handoffs.filter((event) => event.stage === "handoff" && event.result.type === "enqueued").length, 1);
1666
- assertEquals(handoffs.filter((event) => event.stage === "handoff" && event.result.type === "enqueue-failed" && event.result.acceptance === "unknown").length, 1);
1667
- for (const event of deliveries) {
1668
- assertEquals(event.portableInbox, `ap+ef61://${did}/users/alice/inbox`);
1669
- if (event.stage === "planned") assertEquals(event.mode, "portable-replication");
1670
- }
1671
- assertEquals(events.length, 2);
1672
- const source = events[0].provenance.inboxRequest;
1673
- assert(source);
1674
- assertEquals(source.inboxRequestId, reports[0].inboxRequestId);
1675
- assertEquals(source.requestId, reports[0].requestId);
1676
- assertEquals(source.context.origin, LOCAL);
1677
- for (const message of queue.outbox) assertEquals(message.provenance?.inboxRequest, source);
1678
- for (const event of [...events, ...deliveries]) assertEquals(event.provenance.inboxRequest, source);
1679
- federation.setOutboundObservers({
1680
- onDelivery(_ctx, event) {
1681
- deliveries.push(event);
1682
- },
1683
- onBroadcast(_ctx, event) {
1684
- events.push(event);
1685
- }
1686
- });
1687
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
1688
- assertEquals(replicationResult(events.slice(2)), {
1689
- type: "skipped",
1690
- reason: "no-forwarding-targets"
1691
- });
1692
- assert(events[0].broadcastId !== events[2].broadcastId);
1693
- assertEquals(queue.outbox.length, 2);
1694
- });
1695
- await t.step("partial claim failure is incomplete planning and preserves ingress acceptance", async () => {
1696
- const memory = new MemoryKvStore();
1697
- const cas = memory.cas.bind(memory);
1698
- const failure = { failed: "second claim" };
1699
- let claims = 0;
1700
- memory.cas = (...args) => {
1701
- if (args[0][1] === "portableInboxForwarding" && ++claims === 2) return Promise.reject(failure);
1702
- return cas(...args);
1703
- };
1704
- const queue = new RecordingQueue();
1705
- const { federation } = setup({
1706
- kv: memory,
1707
- queue,
1708
- keyPairs: false
1709
- });
1710
- const events = [];
1711
- const deliveries = [];
1712
- federation.setOutboundObservers({
1713
- onDelivery(_ctx, event) {
1714
- deliveries.push(event);
1715
- },
1716
- onBroadcast(_ctx, event) {
1717
- events.push(event);
1718
- }
1719
- });
1720
- assertEquals((await federation.fetch(post(inboxUrl(), await signedFollow()), { contextData: void 0 })).status, 202);
1721
- assertEquals(replicationResult(events), {
1722
- type: "failed",
1723
- failure: {
1724
- kind: "local",
1725
- phase: "destination-planning",
1726
- error: failure
1727
- },
1728
- planning: "incomplete",
1729
- plannedDestinationCount: 1
1730
- });
1731
- assertEquals(deliveries.map((event) => event.stage), ["planned"]);
1732
- assertEquals(queue.outbox.length, 0);
1733
- });
1734
- await t.step("a handled key failure prepares unsigned queue messages", async () => {
1735
- const queue = new RecordingQueue();
1736
- const parameters = forwardingParameters({
1737
- outboxQueue: queue,
1738
- getKeys: () => Promise.reject(/* @__PURE__ */ new Error("no keys"))
1739
- });
1740
- const ctx = createFederation({ kv: parameters.kv }).createContext(new URL(LOCAL));
1741
- const events = [];
1742
- const deliveries = [];
1743
- await observeOutboundBroadcast(ctx, {
1744
- onDelivery(_ctx, event) {
1745
- deliveries.push(event);
1746
- },
1747
- onBroadcast: (_ctx, event) => {
1748
- events.push(event);
1749
- }
1750
- }, (observation) => forwardPortableInboxActivity(parameters, observation), "portable-replication");
1751
- assertEquals(replicationResult(events), {
1752
- type: "prepared",
1753
- preparedFor: "delivery",
1754
- destinationCount: 1
1755
- });
1756
- assertEquals(deliveries.map((event) => event.stage), ["planned", "handoff"]);
1757
- const accepted = deliveries[1];
1758
- assert(accepted.stage === "handoff" && accepted.result.type === "enqueued");
1759
- assertEquals(queue.outbox[0].keys, []);
1760
- assertStrictEquals(queue.outbox[0].activity, parameters.activity);
1761
- });
1762
- });
1763
- test("portable replication attempts settle independently after the forwarding deadline", async () => {
1764
- const [tracerProvider, exporter] = createTestTracerProvider();
1765
- let release;
1766
- const gate = new Promise((resolve) => {
1767
- release = resolve;
1768
- });
1769
- let fetched;
1770
- const fetching = new Promise((resolve) => {
1771
- fetched = resolve;
1772
- });
1773
- let failed;
1774
- const failureReported = new Promise((resolve) => {
1775
- failed = resolve;
1776
- });
1777
- let succeeded;
1778
- const successReported = new Promise((resolve) => {
1779
- succeeded = resolve;
1780
- });
1781
- let ended;
1782
- const concreteSendsEnded = new Promise((resolve) => {
1783
- ended = resolve;
1784
- });
1785
- const exportSpans = exporter.export.bind(exporter);
1786
- exporter.export = (spans, callback) => {
1787
- exportSpans(spans, callback);
1788
- if (exporter.getSpans("activitypub.send_activity").length === 2) ended();
1789
- };
1790
- const attempts = [];
1791
- const submitted = [];
1792
- esm_default.spyGlobal().post(`begin:${GATEWAY2}/`, (call) => {
1793
- submitted.push(JSON.parse(String(call.options.body)));
1794
- return 503;
1795
- }).post(`begin:${GATEWAY3}/`, async (call) => {
1796
- submitted.push(JSON.parse(String(call.options.body)));
1797
- fetched();
1798
- await gate;
1799
- return 202;
1800
- });
1801
- try {
1802
- const { federation, reports } = setup({
1803
- keyPairs: false,
1804
- options: {
1805
- allowPrivateAddress: true,
1806
- tracerProvider,
1807
- portableInboxForwarding: { deadline: { milliseconds: 0 } }
1808
- }
1809
- });
1810
- let replacements = 0;
1811
- federation.setOutboundObservers({
1812
- senderPayload: true,
1813
- onAttempt(_ctx, report) {
1814
- attempts.push(report);
1815
- if (report.outcome.type === "failed") failed();
1816
- else succeeded();
1817
- throw new Error("replication observer failure must be isolated");
1818
- }
1819
- });
1820
- const json = await signedFollow();
1821
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
1822
- await Promise.all([fetching, failureReported]);
1823
- assertEquals(attempts.length, 1);
1824
- assertEquals(attempts[0].outcome.type, "failed");
1825
- assert(attempts[0].outcome.response.type === "final");
1826
- assertEquals(attempts[0].outcome.response.metadata.status, 503);
1827
- assertEquals(attempts[0].httpExchangeCount, 1);
1828
- federation.setOutboundObservers({ onAttempt() {
1829
- replacements++;
1830
- } });
1831
- release();
1832
- await Promise.all([successReported, concreteSendsEnded]);
1833
- assertEquals(attempts.length, 2);
1834
- assertEquals(attempts[1].outcome.type, "succeeded");
1835
- assert(attempts[1].outcome.response.type === "final");
1836
- assertEquals(attempts[1].outcome.response.metadata.status, 202);
1837
- assertEquals(attempts[1].httpExchangeCount, 1);
1838
- assertEquals(replacements, 0);
1839
- assert(attempts[0].attemptId !== attempts[1].attemptId);
1840
- assert(attempts[0].deliveryId !== attempts[1].deliveryId);
1841
- assertEquals(attempts[0].broadcast, attempts[1].broadcast);
1842
- for (const report of attempts) {
1843
- assertEquals(report.senderPayload.stage, "sender-payload");
1844
- if (report.senderPayload.type === "unavailable") assertEquals(report.senderPayload.reason, "privacy-filter-unavailable");
1845
- else {
1846
- assertEquals(report.senderPayload.representation, "privacy-projection");
1847
- assert(Object.isFrozen(report.senderPayload.value));
1848
- }
1849
- assertEquals(report.destinationInbox, report.inboxUrl);
1850
- assertEquals(report.portableInbox, `ap+ef61://${did}/users/alice/inbox`);
1851
- assertEquals(report.provenance.inboxRequest?.inboxRequestId, reports[0].inboxRequestId);
1852
- assert(report.provenance.inboxRequest);
1853
- const span = exporter.spans.find((span) => span.spanContext().spanId === report.trace?.spanId);
1854
- assert(span);
1855
- assertEquals(span.name, "activitypub.send_activity");
1856
- }
1857
- assertEquals(submitted, [json, json]);
1858
- assertEquals((await federation.fetch(post(inboxUrl(), json), { contextData: void 0 })).status, 202);
1859
- assertEquals(submitted.length, 2);
1860
- assertEquals(replacements, 0);
1861
- } finally {
1862
- release();
1863
- esm_default.hardReset();
1864
- await tracerProvider.shutdown();
1865
- }
1866
- });
1867
- test("portable replication observers retain preparation after the forwarding deadline", async (t) => {
1868
- for (const failed of [false, true]) await t.step(failed ? "late preparation failure" : "late unsigned readiness", async () => {
1869
- let release;
1870
- const keyGate = new Promise((resolve) => {
1871
- release = resolve;
1872
- });
1873
- const [tracerProvider, exporter] = createTestTracerProvider();
1874
- let ended;
1875
- const concreteSendEnded = new Promise((resolve) => {
1876
- ended = resolve;
1877
- });
1878
- const exportSpans = exporter.export.bind(exporter);
1879
- exporter.export = (spans, callback) => {
1880
- exportSpans(spans, callback);
1881
- if (spans.some((span) => span.name === "activitypub.send_activity")) ended();
1882
- };
1883
- const failure = { failed: "late local preparation" };
1884
- const parameters = forwardingParameters({
1885
- tracerProvider,
1886
- options: resolvePortableInboxForwardingOptions({ deadline: { milliseconds: 0 } }),
1887
- getKeys: async () => {
1888
- await keyGate;
1889
- if (failed) Object.defineProperty(parameters.activityId, "href", { get() {
1890
- throw failure;
1891
- } });
1892
- return [];
1893
- }
1894
- });
1895
- const ctx = createFederation({ kv: parameters.kv }).createContext(new URL(LOCAL));
1896
- const events = [];
1897
- const deliveries = [];
1898
- let finished;
1899
- const preparation = new Promise((resolve) => {
1900
- finished = resolve;
1901
- });
1902
- let fetched;
1903
- const fetching = new Promise((resolve) => {
1904
- fetched = resolve;
1905
- });
1906
- esm_default.spyGlobal().post(`begin:${GATEWAY2}/`, () => {
1907
- fetched();
1908
- return new Response(null, { status: 503 });
1909
- });
1910
- try {
1911
- assertEquals((await observeOutboundBroadcast(ctx, {
1912
- onDelivery(_ctx, event) {
1913
- deliveries.push(event);
1914
- },
1915
- onBroadcast: (_ctx, event) => {
1916
- events.push(event);
1917
- if (event.stage === "preparation-finished") finished();
1918
- }
1919
- }, (observation) => forwardPortableInboxActivity(parameters, observation), "portable-replication")).length, 1);
1920
- assertEquals(events.map((event) => event.stage), ["started"]);
1921
- release();
1922
- await preparation;
1923
- assertEquals(deliveries.map((event) => event.stage), ["planned", failed ? "preparation-failed" : "handoff"]);
1924
- assertEquals(deliveries[0].deliveryId, deliveries[1].deliveryId);
1925
- if (failed) {
1926
- const failedDelivery = deliveries[1];
1927
- assert(failedDelivery.stage === "preparation-failed");
1928
- assertStrictEquals(failedDelivery.failure.error, failure);
1929
- assertEquals(replicationResult(events), {
1930
- type: "failed",
1931
- failure: {
1932
- kind: "local",
1933
- phase: "request-preparation",
1934
- error: failure
1935
- },
1936
- planning: "complete",
1937
- plannedDestinationCount: 1
1938
- });
1939
- assertEquals(esm_default.callHistory.calls().length, 0);
1940
- } else {
1941
- assertEquals(replicationResult(events), {
1942
- type: "prepared",
1943
- preparedFor: "delivery",
1944
- destinationCount: 1
1945
- });
1946
- await fetching;
1947
- await concreteSendEnded;
1948
- await new Promise((resolve) => setTimeout(resolve, 0));
1949
- assertEquals(events.length, 2);
1950
- assertEquals(await forwardPortableInboxActivity(parameters), []);
1951
- }
1952
- } finally {
1953
- release();
1954
- esm_default.hardReset();
1955
- await tracerProvider.shutdown();
1956
- }
1957
- });
1958
- });
1959
- //#endregion
1960
- export {};