@fedify/fedify 2.2.19 → 2.2.21

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 (109) hide show
  1. package/dist/attachment-arrays-CalAATqD.mjs +16 -0
  2. package/dist/{builder-UmydCxtK.mjs → builder-4ImvtjG4.mjs} +3 -3
  3. package/dist/callback-0KrwzutD.d.mts +2607 -0
  4. package/dist/{client-CSddvgWN.d.ts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CAM_bQXx.d.cts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-9F_u23dc.mjs → client-XYMC0Mmk.mjs} +189 -65
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +255 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  12. package/dist/compat/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-tJbL_Hkw.d.cts → context-CjWuov0g.d.cts} +57 -14
  15. package/dist/{context-OkwEpc3-.d.ts → context-DZqI2LJD.d.ts} +57 -14
  16. package/dist/{deno-CD-8UlUi.mjs → deno-AWk3S2Ug.mjs} +1 -1
  17. package/dist/docloader-Bogpjg4d.mjs +125 -0
  18. package/dist/federation/attachment-responses.test.d.mts +2 -0
  19. package/dist/federation/attachment-responses.test.mjs +182 -0
  20. package/dist/federation/builder.test.mjs +1 -1
  21. package/dist/federation/collection.test.mjs +1 -1
  22. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  23. package/dist/federation/delivery-attachments.test.mjs +288 -0
  24. package/dist/federation/handler.test.mjs +208 -16
  25. package/dist/federation/idempotency.test.mjs +2 -2
  26. package/dist/federation/inbox.test.mjs +2 -2
  27. package/dist/federation/middleware.test.mjs +1567 -30
  28. package/dist/federation/mod.cjs +1 -1
  29. package/dist/federation/mod.d.cts +2 -2
  30. package/dist/federation/mod.d.ts +2 -2
  31. package/dist/federation/mod.js +1 -1
  32. package/dist/federation/negotiation.test.mjs +1 -1
  33. package/dist/federation/retry.test.mjs +1 -1
  34. package/dist/federation/send.test.mjs +723 -68
  35. package/dist/federation/temporal.test.mjs +25 -1
  36. package/dist/federation/webfinger.test.mjs +1 -1
  37. package/dist/{http-BBBUbwKh.mjs → http-B3wCvgu8.mjs} +199 -99
  38. package/dist/{http-DrUG4fPS.cjs → http-BNaPJVnF.cjs} +178 -107
  39. package/dist/{http-DJK2udgX.js → http-BpdLaGy8.js} +177 -106
  40. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  41. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  42. package/dist/{inbox-Dca_0fwc.mjs → inbox-DLy6WBXU.mjs} +1 -1
  43. package/dist/{key-DolXUaLH.mjs → key-Bhc8cQC7.mjs} +3 -2
  44. package/dist/{kv-cache-Bk3V1Tiu.cjs → kv-cache-Bj3CY9Jo.cjs} +59 -17
  45. package/dist/{kv-cache-DDm80t1K.js → kv-cache-CvjLUQTf.js} +60 -18
  46. package/dist/{ld-rTdIfZ63.mjs → ld-DTeykI0e.mjs} +153 -21
  47. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  48. package/dist/{middleware-BWOwEGpy.cjs → middleware-BSQP4d9p.cjs} +642 -149
  49. package/dist/{middleware-B4-Rzdi3.cjs → middleware-CWOzxb3o.cjs} +1 -1
  50. package/dist/{middleware-DYK_res8.mjs → middleware-DkMsC5mQ.mjs} +1 -1
  51. package/dist/{middleware-BimXKBcP.js → middleware-Dx1iwFk8.js} +641 -149
  52. package/dist/{middleware-CpXoRHs3.mjs → middleware-dlGvSrXl.mjs} +452 -122
  53. package/dist/{mod-D2JyWtW3.d.cts → mod-BmxqcEnU.d.ts} +30 -13
  54. package/dist/{mod-a6kmB8xD.d.cts → mod-DWEx2D4q.d.cts} +1 -1
  55. package/dist/{mod-DQGjRJUG.d.ts → mod-DnPmz3-S.d.ts} +1 -1
  56. package/dist/{mod-ej_rLx8h.d.ts → mod-INjDw-m0.d.cts} +30 -13
  57. package/dist/{mod-B6LmugJ4.d.ts → mod-REfljt0T.d.ts} +4 -10
  58. package/dist/{mod-V2vDnYNu.d.cts → mod-UvIGUHqW.d.cts} +4 -10
  59. package/dist/mod.cjs +5 -5
  60. package/dist/mod.d.cts +8 -8
  61. package/dist/mod.d.ts +8 -8
  62. package/dist/mod.js +5 -5
  63. package/dist/nodeinfo/client.test.mjs +764 -18
  64. package/dist/nodeinfo/handler.test.mjs +1 -1
  65. package/dist/nodeinfo/mod.cjs +1 -1
  66. package/dist/nodeinfo/mod.d.cts +1 -1
  67. package/dist/nodeinfo/mod.d.ts +1 -1
  68. package/dist/nodeinfo/mod.js +1 -1
  69. package/dist/nodeinfo/types.test.mjs +1 -1
  70. package/dist/otel/exporter.test.mjs +292 -30
  71. package/dist/otel/mod.cjs +36 -30
  72. package/dist/otel/mod.d.cts +13 -0
  73. package/dist/otel/mod.d.ts +13 -0
  74. package/dist/otel/mod.js +36 -30
  75. package/dist/{outgoing-jsonld-amccRMrV.mjs → outgoing-jsonld-DHf_DYXp.mjs} +38 -8
  76. package/dist/{owner-CVfzyM5V.mjs → owner-BsA7qMHB.mjs} +2 -2
  77. package/dist/{proof-gOGM-sJS.mjs → proof-C63Hqt9N.mjs} +40 -15
  78. package/dist/{proof-DhaTTn-P.cjs → proof-Dbz6ApNP.cjs} +1190 -1007
  79. package/dist/{proof-CaQ4KG6y.js → proof-QV_o5ZqS.js} +1174 -1003
  80. package/dist/send-CAdpwbFX.mjs +416 -0
  81. package/dist/sig/http.test.mjs +528 -2
  82. package/dist/sig/key-types.test.d.mts +218 -0
  83. package/dist/sig/key-types.test.mjs +8 -0
  84. package/dist/sig/key.test.mjs +2 -2
  85. package/dist/sig/ld.test.mjs +573 -8
  86. package/dist/sig/mod.cjs +2 -2
  87. package/dist/sig/mod.d.cts +3 -3
  88. package/dist/sig/mod.d.ts +3 -3
  89. package/dist/sig/mod.js +2 -2
  90. package/dist/sig/owner.test.mjs +1 -1
  91. package/dist/sig/proof.test.mjs +96 -4
  92. package/dist/{temporal-CA4Y9hBJ.mjs → temporal-B3JGkVgk.mjs} +3 -5
  93. package/dist/testing/mod.d.mts +1 -2396
  94. package/dist/{types-DRPjmHVV.cjs → types-BWx7zw3Y.cjs} +187 -63
  95. package/dist/{types-miAYfiGO.js → types-Dx_w2JSM.js} +188 -64
  96. package/dist/utils/docloader.test.mjs +318 -34
  97. package/dist/utils/mod.cjs +1 -1
  98. package/dist/utils/mod.d.cts +1 -1
  99. package/dist/utils/mod.d.ts +1 -1
  100. package/dist/utils/mod.js +1 -1
  101. package/package.json +6 -6
  102. package/dist/docloader-D1ghurDJ.mjs +0 -83
  103. package/dist/send-D35Va72B.mjs +0 -260
  104. /package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-tztVvlNb.mjs} +0 -0
  105. /package/dist/{collection-D-HqUuA2.mjs → collection-CA3V5zyK.mjs} +0 -0
  106. /package/dist/{negotiation-SQvQgUqe.mjs → negotiation-VnHNB0Q5.mjs} +0 -0
  107. /package/dist/{public-audience-DpJqzPuh.mjs → public-audience-4g3_Ze4y.mjs} +0 -0
  108. /package/dist/{retry-v_sGLH1d.mjs → retry-CXg_MBI-.mjs} +0 -0
  109. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -10,21 +10,23 @@ import { n as assertInstanceOf, t as assert } from "../assert-BhQd8QHP.mjs";
10
10
  import { t as assertNotEquals } from "../assert_not_equals-BkxW5QJI.mjs";
11
11
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
12
12
  import { t as assertStrictEquals } from "../assert_strict_equals-Dmjbg-bA.mjs";
13
- import { l as verifyRequest, s as signRequest } from "../http-BBBUbwKh.mjs";
13
+ import { c as signRequest, u as verifyRequest } from "../http-B3wCvgu8.mjs";
14
14
  import { a as rsaPrivateKey3, c as rsaPublicKey3, i as rsaPrivateKey2, n as ed25519PrivateKey, r as ed25519PublicKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-BAK-tUlf.mjs";
15
- import { t as getAuthenticatedDocumentLoader } from "../docloader-D1ghurDJ.mjs";
15
+ import { n as getAuthenticatedDocumentLoader } from "../docloader-Bogpjg4d.mjs";
16
16
  import { t as MemoryKvStore } from "../kv-mI4Ix2EU.mjs";
17
- import { a as compactJsonLd, h as verifyJsonLd, p as signJsonLd, s as detachSignature } from "../ld-rTdIfZ63.mjs";
18
- import { t as doesActorOwnKey } from "../owner-CVfzyM5V.mjs";
19
- import { i as verifyObject, r as signObject } from "../proof-gOGM-sJS.mjs";
20
- import { i as KvSpecDeterminer, n as FederationImpl, o as createFederation, r as InboxContextImpl, t as ContextImpl } from "../middleware-CpXoRHs3.mjs";
17
+ import { _ as verifyJsonLd, a as compactJsonLd, c as detachSignature, h as signJsonLd, i as attachSignature } from "../ld-DTeykI0e.mjs";
18
+ import { t as ldSignatureWithoutCreated } from "../ld-signature-Dgz_b89j.mjs";
19
+ import { t as doesActorOwnKey } from "../owner-BsA7qMHB.mjs";
20
+ import { i as verifyObject, r as signObject } from "../proof-C63Hqt9N.mjs";
21
+ import { i as KvSpecDeterminer, n as FederationImpl, o as createFederation, r as InboxContextImpl, t as ContextImpl } from "../middleware-dlGvSrXl.mjs";
22
+ import { t as SendActivityError } from "../send-CAdpwbFX.mjs";
21
23
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
22
24
  import * as vocab from "@fedify/vocab";
23
25
  import { Create, Offer, Person, getTypeId, lookupObject } from "@fedify/vocab";
24
26
  import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
25
27
  import { configure, reset } from "@logtape/logtape";
26
- import dns from "node:dns/promises";
27
28
  import serialize from "json-canon";
29
+ import dns from "node:dns/promises";
28
30
  //#region ../fixture/src/fixtures/example.com/create.json
29
31
  var id$2 = "https://example.com/create";
30
32
  var create_default = {
@@ -89,7 +91,7 @@ var person2_default = {
89
91
  };
90
92
  //#endregion
91
93
  //#region src/federation/middleware.test.ts
92
- const documentLoader = getDocumentLoader();
94
+ const documentLoader = getDocumentLoader({ allowPrivateAddress: true });
93
95
  let logtapeLock = Promise.resolve();
94
96
  async function withLogtapeLock(fn) {
95
97
  const run = logtapeLock.then(fn, fn);
@@ -203,6 +205,104 @@ test("createFederation()", async (t) => {
203
205
  }), TypeError);
204
206
  });
205
207
  });
208
+ test("FederationImpl.startQueue()", async (t) => {
209
+ function createCountingQueue() {
210
+ const messages = [];
211
+ let listenCount = 0;
212
+ return {
213
+ messages,
214
+ get listenCount() {
215
+ return listenCount;
216
+ },
217
+ enqueue(message) {
218
+ messages.push(message);
219
+ return Promise.resolve();
220
+ },
221
+ listen() {
222
+ listenCount++;
223
+ return Promise.resolve();
224
+ }
225
+ };
226
+ }
227
+ await t.step("starts a fanout-only queue with an explicit selector", async () => {
228
+ const queue = createCountingQueue();
229
+ const federation = new FederationImpl({
230
+ kv: new MemoryKvStore(),
231
+ queue: { fanout: queue },
232
+ manuallyStartQueue: true
233
+ });
234
+ await federation.startQueue(void 0, { queue: "fanout" });
235
+ assertEquals(queue.listenCount, 1);
236
+ await federation.startQueue(void 0, { queue: "fanout" });
237
+ assertEquals(queue.listenCount, 1);
238
+ });
239
+ await t.step("starts a fanout-only queue without a selector", async () => {
240
+ const queue = createCountingQueue();
241
+ await new FederationImpl({
242
+ kv: new MemoryKvStore(),
243
+ queue: { fanout: queue },
244
+ manuallyStartQueue: true
245
+ }).startQueue(void 0);
246
+ assertEquals(queue.listenCount, 1);
247
+ });
248
+ await t.step("starts a fanout-only queue after a fanout enqueue", async () => {
249
+ const queue = createCountingQueue();
250
+ const ctx = new ContextImpl({
251
+ data: void 0,
252
+ federation: new FederationImpl({
253
+ kv: new MemoryKvStore(),
254
+ contextLoaderFactory: () => mockDocumentLoader,
255
+ queue: { fanout: queue }
256
+ }),
257
+ url: new URL("https://example.com/"),
258
+ documentLoader: mockDocumentLoader,
259
+ contextLoader: mockDocumentLoader
260
+ });
261
+ const activity = new vocab.Create({
262
+ id: new URL("https://example.com/activity/1"),
263
+ actor: new URL("https://example.com/person")
264
+ });
265
+ await ctx.sendActivity([{
266
+ privateKey: rsaPrivateKey2,
267
+ keyId: rsaPublicKey2.id
268
+ }], {
269
+ id: new URL("https://example.com/recipient"),
270
+ inboxId: new URL("https://example.com/inbox")
271
+ }, activity, { fanout: "force" });
272
+ assertEquals(queue.listenCount, 1);
273
+ assertEquals(queue.messages.length, 1);
274
+ assertEquals(queue.messages[0].type, "fanout");
275
+ });
276
+ await t.step("does not start a fanout-only queue automatically when manually started", async () => {
277
+ const queue = createCountingQueue();
278
+ const ctx = new ContextImpl({
279
+ data: void 0,
280
+ federation: new FederationImpl({
281
+ kv: new MemoryKvStore(),
282
+ contextLoaderFactory: () => mockDocumentLoader,
283
+ queue: { fanout: queue },
284
+ manuallyStartQueue: true
285
+ }),
286
+ url: new URL("https://example.com/"),
287
+ documentLoader: mockDocumentLoader,
288
+ contextLoader: mockDocumentLoader
289
+ });
290
+ const activity = new vocab.Create({
291
+ id: new URL("https://example.com/activity/1"),
292
+ actor: new URL("https://example.com/person")
293
+ });
294
+ await ctx.sendActivity([{
295
+ privateKey: rsaPrivateKey2,
296
+ keyId: rsaPublicKey2.id
297
+ }], {
298
+ id: new URL("https://example.com/recipient"),
299
+ inboxId: new URL("https://example.com/inbox")
300
+ }, activity, { fanout: "force" });
301
+ assertEquals(queue.listenCount, 0);
302
+ assertEquals(queue.messages.length, 1);
303
+ assertEquals(queue.messages[0].type, "fanout");
304
+ });
305
+ });
206
306
  test({
207
307
  name: "Federation.createContext()",
208
308
  permissions: {
@@ -225,7 +325,8 @@ test({
225
325
  const federation = createFederation({
226
326
  kv,
227
327
  documentLoaderFactory: () => rejectingLoader,
228
- contextLoaderFactory: () => mockDocumentLoader
328
+ contextLoaderFactory: () => mockDocumentLoader,
329
+ authenticatedDocumentLoaderFactory: (identity) => getAuthenticatedDocumentLoader(identity, { allowPrivateAddress: true })
229
330
  });
230
331
  let ctx = federation.createContext(new URL("https://example.com:1234/"), 123);
231
332
  assertEquals(ctx.data, 123);
@@ -330,7 +431,7 @@ test({
330
431
  documentUrl: "https://example.com/auth-check",
331
432
  document: true
332
433
  });
333
- assertEquals(await ctx.lookupObject("https://example.com/object"), null);
434
+ assertEquals(await withDnsLookup(() => Promise.reject(/* @__PURE__ */ new Error("Resolver unavailable")), () => ctx.lookupObject("https://example.com/object")), null);
334
435
  await assertRejects(() => ctx.sendActivity({ identifier: "handle" }, [], new vocab.Create({})), TypeError, "The activity to send must have at least one actor property.");
335
436
  await ctx.sendActivity({ identifier: "handle" }, [], new vocab.Create({ actor: new URL("https://example.com/users/handle") }));
336
437
  esm_default.get("https://example.com/object", () => new Response(JSON.stringify({
@@ -579,7 +680,7 @@ test({
579
680
  assertStrictEquals(clone.contextLoader, ctx.contextLoader);
580
681
  assertStrictEquals(clone.federation, ctx.federation);
581
682
  });
582
- esm_default.get("https://example.com/.well-known/nodeinfo", (cl) => {
683
+ esm_default.get("path:/.well-known/nodeinfo", (cl) => {
583
684
  const headers = cl.options.headers ?? {};
584
685
  assertEquals(new Headers(headers).get("User-Agent"), "CustomUserAgent/1.2.3");
585
686
  return new Response(JSON.stringify({ links: [{
@@ -587,7 +688,7 @@ test({
587
688
  href: "https://example.com/nodeinfo/2.1"
588
689
  }] }));
589
690
  });
590
- esm_default.get("https://example.com/nodeinfo/2.1", (cl) => {
691
+ esm_default.get("path:/nodeinfo/2.1", (cl) => {
591
692
  const headers = cl.options.headers ?? {};
592
693
  assertEquals(new Headers(headers).get("User-Agent"), "CustomUserAgent/1.2.3");
593
694
  return new Response(JSON.stringify({
@@ -608,7 +709,11 @@ test({
608
709
  kv,
609
710
  userAgent: "CustomUserAgent/1.2.3"
610
711
  }).createContext(new URL("https://example.com/"), 123);
611
- assertEquals(await ctx.lookupNodeInfo("https://example.com/"), {
712
+ const lookupExample = () => Promise.resolve([{
713
+ address: "93.184.215.14",
714
+ family: 4
715
+ }]);
716
+ assertEquals(await withDnsLookup(lookupExample, () => ctx.lookupNodeInfo("https://example.com/")), {
612
717
  software: {
613
718
  name: "foo",
614
719
  version: "1.2.3"
@@ -620,7 +725,7 @@ test({
620
725
  localComments: 456
621
726
  }
622
727
  });
623
- assertEquals(await ctx.lookupNodeInfo("https://example.com/", { parse: "none" }), {
728
+ assertEquals(await withDnsLookup(lookupExample, () => ctx.lookupNodeInfo("https://example.com/", { parse: "none" })), {
624
729
  software: {
625
730
  name: "foo",
626
731
  version: "1.2.3"
@@ -632,6 +737,22 @@ test({
632
737
  localComments: 456
633
738
  }
634
739
  });
740
+ await assertRejects(() => ctx.lookupNodeInfo("https://example.com/", { timeout: 0 }), RangeError);
741
+ const caller = new AbortController();
742
+ caller.abort();
743
+ assertEquals(await ctx.lookupNodeInfo("https://example.com/", {
744
+ signal: caller.signal,
745
+ timeout: null
746
+ }), void 0);
747
+ assertEquals(await ctx.lookupNodeInfo("https://example.com/", {
748
+ parse: "none",
749
+ signal: caller.signal,
750
+ timeout: null
751
+ }), void 0);
752
+ await assertRejects(() => ctx.lookupNodeInfo("https://example.com/", {
753
+ parse: "none",
754
+ timeout: 0
755
+ }), RangeError);
635
756
  });
636
757
  await t.step("RequestContext", async () => {
637
758
  const federation = createFederation({
@@ -739,6 +860,343 @@ test({
739
860
  esm_default.hardReset();
740
861
  }
741
862
  });
863
+ test("RequestContext signature checks", async (t) => {
864
+ const [tracerProvider, exporter] = createTestTracerProvider();
865
+ const keyId = rsaPublicKey3.id.href;
866
+ const ownerId = rsaPublicKey3.ownerId.href;
867
+ const request = await signRequest(new Request("https://example.com/"), rsaPrivateKey3, rsaPublicKey3.id);
868
+ function setup(options = {}) {
869
+ const loads = {
870
+ key: 0,
871
+ owner: 0
872
+ };
873
+ const loader = async (url, loaderOptions) => {
874
+ if (url === keyId) loads.key++;
875
+ else if (url === ownerId) loads.owner++;
876
+ await options.gate;
877
+ return await (options.load ?? mockDocumentLoader)(url, loaderOptions);
878
+ };
879
+ const federation = createFederation({
880
+ kv: new MemoryKvStore(),
881
+ documentLoaderFactory: () => loader,
882
+ contextLoaderFactory: () => mockDocumentLoader,
883
+ tracerProvider: options.tracerProvider ?? tracerProvider
884
+ });
885
+ return {
886
+ ctx: federation.createContext(options.request ?? new Request(request), void 0),
887
+ loads,
888
+ loader,
889
+ federation
890
+ };
891
+ }
892
+ try {
893
+ for (const mode of [
894
+ "keys",
895
+ "owners",
896
+ "warm owners",
897
+ "mixed"
898
+ ]) await t.step(`coalesces ${mode}`, async () => {
899
+ exporter.clear();
900
+ let release;
901
+ const { ctx, loads, loader } = setup({ gate: new Promise((resolve) => release = resolve) });
902
+ if (mode === "warm owners") {
903
+ release();
904
+ assert(await ctx.getSignedKey());
905
+ }
906
+ const results = Promise.all(Array.from({ length: 8 }, (_, i) => {
907
+ const options = i % 2 === 0 ? {} : {
908
+ documentLoader: loader,
909
+ contextLoader: ctx.contextLoader,
910
+ tracerProvider
911
+ };
912
+ return mode === "keys" || mode === "mixed" && i % 2 === 0 ? ctx.getSignedKey(options) : ctx.getSignedKeyOwner(options);
913
+ }));
914
+ release();
915
+ for (const result of await results) assert(result != null);
916
+ assertEquals(loads, {
917
+ key: 1,
918
+ owner: mode === "keys" ? 0 : 1
919
+ });
920
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
921
+ assert(await ctx.getSignedKey());
922
+ if (mode !== "keys") assert(await ctx.getSignedKeyOwner());
923
+ assertEquals(loads, {
924
+ key: 1,
925
+ owner: mode === "keys" ? 0 : 1
926
+ });
927
+ });
928
+ await t.step("memoizes null keys", async () => {
929
+ exporter.clear();
930
+ const { ctx, loads } = setup({ load: () => Promise.reject(/* @__PURE__ */ new Error("unavailable")) });
931
+ for (let i = 0; i < 3; i++) {
932
+ assertEquals(await ctx.getSignedKey(), null);
933
+ assertEquals(await ctx.getSignedKeyOwner(), null);
934
+ }
935
+ assertEquals(loads, {
936
+ key: 1,
937
+ owner: 0
938
+ });
939
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
940
+ assert(await ctx.getSignedKey({ documentLoader: mockDocumentLoader }));
941
+ assert(await ctx.getSignedKeyOwner({ documentLoader: mockDocumentLoader }));
942
+ });
943
+ await t.step("coalesces key-owner FetchError results", async () => {
944
+ const { ctx, loads } = setup({ load: async (url, options) => {
945
+ if (url === ownerId) throw new FetchError(new URL(url), "HTTP 401: Unauthorized");
946
+ return await mockDocumentLoader(url, options);
947
+ } });
948
+ assert(await ctx.getSignedKey());
949
+ assertEquals(await Promise.all(Array.from({ length: 8 }, () => ctx.getSignedKeyOwner())), Array(8).fill(null));
950
+ assertEquals(await ctx.getSignedKeyOwner(), null);
951
+ assertEquals(loads, {
952
+ key: 1,
953
+ owner: 1
954
+ });
955
+ assert(await ctx.getSignedKeyOwner({ documentLoader: mockDocumentLoader }));
956
+ });
957
+ await t.step("memoizes unsigned requests", async () => {
958
+ exporter.clear();
959
+ const { ctx, loads } = setup({ request: new Request("https://example.com/") });
960
+ for (let i = 0; i < 3; i++) {
961
+ assertEquals(await ctx.getSignedKey(), null);
962
+ assertEquals(await ctx.getSignedKeyOwner(), null);
963
+ }
964
+ assertEquals(loads, {
965
+ key: 0,
966
+ owner: 0
967
+ });
968
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
969
+ });
970
+ await t.step("memoizes null owners without trusting a key's owner claim", async () => {
971
+ const { ctx, loads } = setup({ load: async (url, options) => url === ownerId ? {
972
+ documentUrl: url,
973
+ contextUrl: null,
974
+ document: {
975
+ ...person2_default,
976
+ publicKey: []
977
+ }
978
+ } : await mockDocumentLoader(url, options) });
979
+ assert(await ctx.getSignedKey());
980
+ assertEquals(await Promise.all(Array.from({ length: 8 }, () => ctx.getSignedKeyOwner())), Array(8).fill(null));
981
+ for (let i = 0; i < 3; i++) assertEquals(await ctx.getSignedKeyOwner(), null);
982
+ assertEquals(loads, {
983
+ key: 1,
984
+ owner: 1
985
+ });
986
+ assert(await ctx.getSignedKeyOwner({ documentLoader: mockDocumentLoader }));
987
+ assert(await ctx.getSignedKeyOwner());
988
+ });
989
+ await t.step("isolates concurrent document loaders before success", async () => {
990
+ const { ctx, loads } = setup();
991
+ let otherLoads = 0;
992
+ const otherLoader = async (url, options) => {
993
+ otherLoads++;
994
+ if (url === ownerId) return {
995
+ documentUrl: url,
996
+ contextUrl: null,
997
+ document: {
998
+ ...person2_default,
999
+ name: "Other view"
1000
+ }
1001
+ };
1002
+ return await mockDocumentLoader(url, options);
1003
+ };
1004
+ const [first, second] = await Promise.all([ctx.getSignedKeyOwner(), ctx.getSignedKeyOwner({ documentLoader: otherLoader })]);
1005
+ assertEquals(first?.name, "Jane Doe");
1006
+ assertEquals(second?.name, "Other view");
1007
+ const cached = await ctx.getSignedKeyOwner();
1008
+ assert(cached === first || cached === second);
1009
+ assertStrictEquals(await ctx.getSignedKeyOwner({ documentLoader: otherLoader }), cached);
1010
+ assertEquals(loads, {
1011
+ key: 1,
1012
+ owner: 1
1013
+ });
1014
+ assertEquals(otherLoads, 2);
1015
+ });
1016
+ await t.step("preserves in-flight null while another loader succeeds", async () => {
1017
+ exporter.clear();
1018
+ let release;
1019
+ const gate = new Promise((resolve) => release = resolve);
1020
+ const { ctx, loads } = setup({ load: async () => {
1021
+ await gate;
1022
+ throw new TypeError("fetch failed");
1023
+ } });
1024
+ const failed = Promise.all([ctx.getSignedKey(), ctx.getSignedKeyOwner()]);
1025
+ const owner = await ctx.getSignedKeyOwner({ documentLoader: mockDocumentLoader });
1026
+ assert(owner);
1027
+ release();
1028
+ assertEquals(await failed, [null, null]);
1029
+ assertStrictEquals(await ctx.getSignedKeyOwner(), owner);
1030
+ assert(await ctx.getSignedKey());
1031
+ assertEquals(loads, {
1032
+ key: 1,
1033
+ owner: 0
1034
+ });
1035
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 2);
1036
+ });
1037
+ await t.step("isolates context loaders", async () => {
1038
+ exporter.clear();
1039
+ const { ctx, loads } = setup();
1040
+ const otherContextLoader = (url, options) => mockDocumentLoader(url, options);
1041
+ await Promise.all([ctx.getSignedKeyOwner(), ctx.getSignedKeyOwner({ contextLoader: otherContextLoader })]);
1042
+ assertEquals(loads, {
1043
+ key: 2,
1044
+ owner: 2
1045
+ });
1046
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 2);
1047
+ });
1048
+ await t.step("shares work across tracer providers", async () => {
1049
+ exporter.clear();
1050
+ const [otherProvider, otherExporter] = createTestTracerProvider();
1051
+ try {
1052
+ const { ctx, loads } = setup();
1053
+ await Promise.all([
1054
+ ctx.getSignedKeyOwner(),
1055
+ ctx.getSignedKeyOwner({ tracerProvider: otherProvider }),
1056
+ ctx.getSignedKey(),
1057
+ ctx.getSignedKey({ tracerProvider: otherProvider })
1058
+ ]);
1059
+ assert(await ctx.getSignedKeyOwner({ tracerProvider: otherProvider }));
1060
+ assertEquals(loads, {
1061
+ key: 1,
1062
+ owner: 1
1063
+ });
1064
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
1065
+ assertEquals(otherExporter.getSpans("http_signatures.verify").length, 0);
1066
+ } finally {
1067
+ await otherProvider.shutdown();
1068
+ }
1069
+ });
1070
+ await t.step("reuses success with a fresh authorization loader", async () => {
1071
+ exporter.clear();
1072
+ const { ctx, loads } = setup();
1073
+ let freshLoads = 0;
1074
+ const freshLoader = (url, options) => {
1075
+ freshLoads++;
1076
+ return mockDocumentLoader(url, options);
1077
+ };
1078
+ const key = await ctx.getSignedKey({ documentLoader: freshLoader });
1079
+ assert(key);
1080
+ assertStrictEquals(await ctx.getSignedKey(), key);
1081
+ const owner = await ctx.getSignedKeyOwner();
1082
+ assert(owner);
1083
+ assertStrictEquals(await ctx.getSignedKeyOwner({ documentLoader: freshLoader }), owner);
1084
+ assertEquals(loads, {
1085
+ key: 0,
1086
+ owner: 1
1087
+ });
1088
+ assertEquals(freshLoads, 1);
1089
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
1090
+ });
1091
+ await t.step("retains a transient owner lookup failure as null", async () => {
1092
+ let fail = true;
1093
+ const { ctx, loads } = setup({ load: async (url, options) => {
1094
+ if (url === ownerId && fail) throw new TypeError("fetch failed");
1095
+ return await mockDocumentLoader(url, options);
1096
+ } });
1097
+ assert(await ctx.getSignedKey());
1098
+ assertEquals(await ctx.getSignedKeyOwner(), null);
1099
+ fail = false;
1100
+ assertEquals(await ctx.getSignedKeyOwner(), null);
1101
+ assertEquals(loads, {
1102
+ key: 1,
1103
+ owner: 1
1104
+ });
1105
+ assert(await ctx.getSignedKeyOwner({ documentLoader: mockDocumentLoader }));
1106
+ });
1107
+ await t.step("rechecks an owner after another loader verifies the key", async () => {
1108
+ let fail = true;
1109
+ const { ctx, loads } = setup({ load: async (url, options) => {
1110
+ if (url === keyId && fail) throw new TypeError("fetch failed");
1111
+ return await mockDocumentLoader(url, options);
1112
+ } });
1113
+ assertEquals(await ctx.getSignedKeyOwner(), null);
1114
+ fail = false;
1115
+ assertEquals(await ctx.getSignedKeyOwner(), null);
1116
+ assertEquals(loads, {
1117
+ key: 1,
1118
+ owner: 0
1119
+ });
1120
+ assert(await ctx.getSignedKey({ documentLoader: mockDocumentLoader }));
1121
+ assertEquals((await ctx.getSignedKeyOwner())?.id?.href, ownerId);
1122
+ assertEquals(loads, {
1123
+ key: 1,
1124
+ owner: 1
1125
+ });
1126
+ });
1127
+ await t.step("retries unexpected key rejections from a rejection handler", async () => {
1128
+ exporter.clear();
1129
+ const failure = /* @__PURE__ */ new Error("transient context loader failure");
1130
+ let rejectContext = true;
1131
+ const contextLoader = async (url, options) => {
1132
+ if (rejectContext) throw failure;
1133
+ return await mockDocumentLoader(url, options);
1134
+ };
1135
+ const { ctx, loads } = setup();
1136
+ const options = { contextLoader };
1137
+ const failedKeys = Promise.allSettled([
1138
+ ctx.getSignedKey(options),
1139
+ ctx.getSignedKeyOwner(options),
1140
+ ctx.getSignedKey(options)
1141
+ ]);
1142
+ const recovery = ctx.getSignedKey(options).catch(() => {
1143
+ rejectContext = false;
1144
+ return ctx.getSignedKey(options);
1145
+ });
1146
+ for (const result of await failedKeys) assertEquals(result.status, "rejected");
1147
+ assert(await recovery);
1148
+ assertEquals(loads, {
1149
+ key: 2,
1150
+ owner: 0
1151
+ });
1152
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 2);
1153
+ });
1154
+ await t.step("retries owner rejections while retaining the verified key", async () => {
1155
+ exporter.clear();
1156
+ let rejectContext = false;
1157
+ const contextLoader = async (url, options) => {
1158
+ if (rejectContext) throw new Error("transient owner context failure");
1159
+ return await mockDocumentLoader(url, options);
1160
+ };
1161
+ const { ctx, loads } = setup();
1162
+ const options = { contextLoader };
1163
+ assert(await ctx.getSignedKey(options));
1164
+ assertEquals(loads, {
1165
+ key: 1,
1166
+ owner: 0
1167
+ });
1168
+ rejectContext = true;
1169
+ const failures = await Promise.allSettled([ctx.getSignedKeyOwner(options), ctx.getSignedKeyOwner(options)]);
1170
+ for (const result of failures) assertEquals(result.status, "rejected");
1171
+ assertEquals(loads, {
1172
+ key: 1,
1173
+ owner: 1
1174
+ });
1175
+ rejectContext = false;
1176
+ assert(await ctx.getSignedKeyOwner(options));
1177
+ assertEquals(loads, {
1178
+ key: 1,
1179
+ owner: 2
1180
+ });
1181
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 1);
1182
+ });
1183
+ await t.step("keeps clones and separate requests independent", async () => {
1184
+ exporter.clear();
1185
+ const { ctx, loads, federation } = setup();
1186
+ assert(await ctx.getSignedKeyOwner());
1187
+ const clone = ctx.clone(void 0);
1188
+ const separate = federation.createContext(new Request(request), void 0);
1189
+ await Promise.all([clone.getSignedKeyOwner(), separate.getSignedKeyOwner()]);
1190
+ assertEquals(loads, {
1191
+ key: 3,
1192
+ owner: 3
1193
+ });
1194
+ assertEquals(exporter.getSpans("http_signatures.verify").length, 3);
1195
+ });
1196
+ } finally {
1197
+ await tracerProvider.shutdown();
1198
+ }
1199
+ });
742
1200
  test("Federation.fetch() [rfc9421] multiple POST signatures", async (t) => {
743
1201
  for (const validSecond of [true, false]) await t.step(validSecond ? "valid second signature" : "both signatures invalid", async () => {
744
1202
  const inbox = [];
@@ -782,7 +1240,7 @@ test("Federation.fetch()", async (t) => {
782
1240
  kv,
783
1241
  documentLoaderFactory: () => mockDocumentLoader,
784
1242
  authenticatedDocumentLoaderFactory(identity) {
785
- const docLoader = getAuthenticatedDocumentLoader(identity);
1243
+ const docLoader = getAuthenticatedDocumentLoader(identity, { allowPrivateAddress: true });
786
1244
  return (url) => {
787
1245
  if (new URL(url).host === "example.com") return docLoader(url);
788
1246
  return mockDocumentLoader(url);
@@ -988,7 +1446,7 @@ test("Federation.setInboxListeners()", async (t) => {
988
1446
  kv,
989
1447
  documentLoaderFactory: () => mockDocumentLoader,
990
1448
  authenticatedDocumentLoaderFactory(identity) {
991
- const docLoader = getAuthenticatedDocumentLoader(identity);
1449
+ const docLoader = getAuthenticatedDocumentLoader(identity, { allowPrivateAddress: true });
992
1450
  return (url) => {
993
1451
  const urlObj = new URL(url);
994
1452
  authenticatedRequests.push([url, identity.keyId.href]);
@@ -1311,7 +1769,7 @@ test("Federation.setInboxListeners()", async (t) => {
1311
1769
  kv,
1312
1770
  documentLoaderFactory: () => mockDocumentLoader,
1313
1771
  authenticatedDocumentLoaderFactory(identity) {
1314
- const docLoader = getAuthenticatedDocumentLoader(identity);
1772
+ const docLoader = getAuthenticatedDocumentLoader(identity, { allowPrivateAddress: true });
1315
1773
  return (url) => {
1316
1774
  if (new URL(url).host === "example.com") return docLoader(url);
1317
1775
  return mockDocumentLoader(url);
@@ -1524,10 +1982,11 @@ test("Federation.setOutboxListeners()", async (t) => {
1524
1982
  sinks: ["buffer"]
1525
1983
  }]
1526
1984
  });
1527
- const federation = createFederation({
1985
+ const federation = new FederationImpl({
1528
1986
  kv,
1529
1987
  documentLoaderFactory: () => mockDocumentLoader
1530
1988
  });
1989
+ federation.allowPrivateAddress = true;
1531
1990
  federation.setActorDispatcher("/users/{identifier}", (_ctx, identifier) => identifier === "john" ? new vocab.Person({}) : null).setKeyPairsDispatcher(() => [{
1532
1991
  privateKey: rsaPrivateKey2,
1533
1992
  publicKey: rsaPublicKey2.publicKey
@@ -1630,10 +2089,11 @@ test("Federation.setOutboxListeners()", async (t) => {
1630
2089
  sinks: ["buffer"]
1631
2090
  }]
1632
2091
  });
1633
- const federation = createFederation({
2092
+ const federation = new FederationImpl({
1634
2093
  kv,
1635
2094
  documentLoaderFactory: () => mockDocumentLoader
1636
2095
  });
2096
+ federation.allowPrivateAddress = true;
1637
2097
  federation.setActorDispatcher("/{identifier}", (_ctx, identifier) => identifier === "person2" ? new vocab.Person({}) : null).setKeyPairsDispatcher(() => [{
1638
2098
  privateKey: rsaPrivateKey2,
1639
2099
  publicKey: rsaPublicKey2.publicKey
@@ -1858,7 +2318,7 @@ test("FederationImpl.sendActivity()", async (t) => {
1858
2318
  });
1859
2319
  const federation = new FederationImpl({
1860
2320
  kv: new MemoryKvStore(),
1861
- contextLoaderFactory: () => mockDocumentLoader
2321
+ allowPrivateAddress: true
1862
2322
  });
1863
2323
  const context = federation.createContext(new URL("https://example.com/"));
1864
2324
  await t.step("success", async () => {
@@ -1994,6 +2454,356 @@ test("FederationImpl.sendActivity()", async (t) => {
1994
2454
  });
1995
2455
  esm_default.hardReset();
1996
2456
  });
2457
+ const QUEUE_STARTUP_WARNING = "Failed to start queue workers automatically: {error}";
2458
+ /**
2459
+ * Captures unhandled promise rejections for the duration of a test step.
2460
+ *
2461
+ * Deno dispatches `unhandledrejection` on `globalThis`, while Node.js and Bun
2462
+ * dispatch `unhandledRejection` on `process`. Bun's test runner currently
2463
+ * fires neither, so there the native runner's own unhandled-rejection failure
2464
+ * remains the signal; the assertion is harmless otherwise.
2465
+ */
2466
+ function captureUnhandledRejections() {
2467
+ const reasons = [];
2468
+ const isDeno = "Deno" in globalThis;
2469
+ const onRejectionEvent = (event) => {
2470
+ event.preventDefault();
2471
+ reasons.push(event.reason);
2472
+ };
2473
+ const onProcessRejection = (reason) => {
2474
+ reasons.push(reason);
2475
+ };
2476
+ const globalTarget = globalThis;
2477
+ const proc = globalThis.process;
2478
+ if (isDeno) globalTarget.addEventListener?.("unhandledrejection", onRejectionEvent);
2479
+ else proc?.on?.("unhandledRejection", onProcessRejection);
2480
+ async function settle() {
2481
+ await new Promise((resolve) => setTimeout(resolve, 0));
2482
+ await new Promise((resolve) => setTimeout(resolve, 0));
2483
+ }
2484
+ return {
2485
+ reasons,
2486
+ settle,
2487
+ stop() {
2488
+ if (isDeno) globalTarget.removeEventListener?.("unhandledrejection", onRejectionEvent);
2489
+ else proc?.off?.("unhandledRejection", onProcessRejection);
2490
+ }
2491
+ };
2492
+ }
2493
+ async function configureQueueStartupWarningCapture(records) {
2494
+ await configure({
2495
+ sinks: { buffer(record) {
2496
+ records.push(record);
2497
+ } },
2498
+ loggers: [{
2499
+ category: "fedify",
2500
+ sinks: ["buffer"],
2501
+ lowestLevel: "warning"
2502
+ }, {
2503
+ category: ["logtape", "meta"],
2504
+ sinks: []
2505
+ }],
2506
+ reset: true
2507
+ });
2508
+ }
2509
+ function queueStartupWarnings(records, error) {
2510
+ return records.filter((record) => record.level === "warning" && record.category.length === 3 && record.category[0] === "fedify" && record.category[1] === "federation" && record.category[2] === "queue" && record.rawMessage === QUEUE_STARTUP_WARNING && record.properties.error === error);
2511
+ }
2512
+ test("Federation.fetch() reports automatic queue startup failures", async (t) => {
2513
+ const listenError = /* @__PURE__ */ new TypeError("simulated listen() failure");
2514
+ const queue = {
2515
+ enqueue() {
2516
+ return Promise.resolve();
2517
+ },
2518
+ listen() {
2519
+ throw listenError;
2520
+ }
2521
+ };
2522
+ const capture = captureUnhandledRejections();
2523
+ const records = [];
2524
+ await configureQueueStartupWarningCapture(records);
2525
+ try {
2526
+ const federation = createFederation({
2527
+ kv: new MemoryKvStore(),
2528
+ queue,
2529
+ skipSignatureVerification: true,
2530
+ documentLoaderFactory: () => mockDocumentLoader,
2531
+ contextLoaderFactory: () => mockDocumentLoader
2532
+ });
2533
+ federation.setActorDispatcher("/actors/{identifier}", () => new Person({ id: new URL("https://example.com/actor") }));
2534
+ federation.setInboxListeners("/actors/{identifier}/inbox", "/inbox").on(Create, () => {});
2535
+ const post = (id) => federation.fetch(new Request("https://example.com/inbox", {
2536
+ method: "POST",
2537
+ headers: { "Content-Type": "application/activity+json" },
2538
+ body: JSON.stringify({
2539
+ "@context": "https://www.w3.org/ns/activitystreams",
2540
+ id,
2541
+ type: "Create",
2542
+ actor: "https://example.com/actor"
2543
+ })
2544
+ }), { contextData: void 0 });
2545
+ await t.step("synchronous failure", async () => {
2546
+ assertEquals((await post("https://example.com/activities/queued-1")).status, 202);
2547
+ await capture.settle();
2548
+ assertEquals(queueStartupWarnings(records, listenError).length, 1);
2549
+ assertEquals(capture.reasons, []);
2550
+ assertEquals((await post("https://example.com/activities/queued-2")).status, 202);
2551
+ await capture.settle();
2552
+ assertEquals(queueStartupWarnings(records, listenError).length, 1, "the warning must be logged only once per federation instance");
2553
+ assertEquals(capture.reasons, []);
2554
+ });
2555
+ await t.step("asynchronous failure", async () => {
2556
+ const asyncError = /* @__PURE__ */ new TypeError("simulated async listen() failure");
2557
+ let rejectListen;
2558
+ const asyncFederation = createFederation({
2559
+ kv: new MemoryKvStore(),
2560
+ queue: {
2561
+ enqueue() {
2562
+ return Promise.resolve();
2563
+ },
2564
+ listen() {
2565
+ return new Promise((_resolve, reject) => {
2566
+ rejectListen = reject;
2567
+ });
2568
+ }
2569
+ },
2570
+ skipSignatureVerification: true,
2571
+ documentLoaderFactory: () => mockDocumentLoader,
2572
+ contextLoaderFactory: () => mockDocumentLoader
2573
+ });
2574
+ asyncFederation.setActorDispatcher("/actors/{identifier}", () => new Person({ id: new URL("https://example.com/actor") }));
2575
+ asyncFederation.setInboxListeners("/actors/{identifier}/inbox", "/inbox").on(Create, () => {});
2576
+ assertEquals((await asyncFederation.fetch(new Request("https://example.com/inbox", {
2577
+ method: "POST",
2578
+ headers: { "Content-Type": "application/activity+json" },
2579
+ body: JSON.stringify({
2580
+ "@context": "https://www.w3.org/ns/activitystreams",
2581
+ id: "https://example.com/activities/queued-async",
2582
+ type: "Create",
2583
+ actor: "https://example.com/actor"
2584
+ })
2585
+ }), { contextData: void 0 })).status, 202);
2586
+ await capture.settle();
2587
+ assertEquals(queueStartupWarnings(records, asyncError).length, 0);
2588
+ assert(rejectListen != null);
2589
+ rejectListen(asyncError);
2590
+ await capture.settle();
2591
+ assertEquals(queueStartupWarnings(records, asyncError).length, 1, "a listener that rejects after startup must still be reported");
2592
+ assertEquals(capture.reasons, []);
2593
+ });
2594
+ } finally {
2595
+ await capture.settle();
2596
+ capture.stop();
2597
+ await reset();
2598
+ }
2599
+ });
2600
+ test("Federation.startQueue() rejects when a queue cannot listen", async () => {
2601
+ const listenError = /* @__PURE__ */ new TypeError("simulated listen() failure");
2602
+ const federation = createFederation({
2603
+ kv: new MemoryKvStore(),
2604
+ queue: {
2605
+ enqueue() {
2606
+ return Promise.resolve();
2607
+ },
2608
+ listen() {
2609
+ throw listenError;
2610
+ }
2611
+ },
2612
+ manuallyStartQueue: true
2613
+ });
2614
+ assertStrictEquals(await assertRejects(() => federation.startQueue(void 0)), listenError);
2615
+ });
2616
+ test("Federation.startQueue() keeps other queue workers running", async () => {
2617
+ const outboxError = /* @__PURE__ */ new TypeError("simulated outbox listen() failure");
2618
+ const lateInboxError = /* @__PURE__ */ new TypeError("simulated late inbox failure");
2619
+ let rejectInbox;
2620
+ let fanoutStarted = false;
2621
+ const inbox = {
2622
+ enqueue() {
2623
+ return Promise.resolve();
2624
+ },
2625
+ listen() {
2626
+ return new Promise((_resolve, reject) => {
2627
+ rejectInbox = reject;
2628
+ });
2629
+ }
2630
+ };
2631
+ const outbox = {
2632
+ enqueue() {
2633
+ return Promise.resolve();
2634
+ },
2635
+ listen() {
2636
+ throw outboxError;
2637
+ }
2638
+ };
2639
+ const fanout = {
2640
+ enqueue() {
2641
+ return Promise.resolve();
2642
+ },
2643
+ listen() {
2644
+ fanoutStarted = true;
2645
+ return new Promise(() => {});
2646
+ }
2647
+ };
2648
+ const capture = captureUnhandledRejections();
2649
+ try {
2650
+ const federation = createFederation({
2651
+ kv: new MemoryKvStore(),
2652
+ queue: {
2653
+ inbox,
2654
+ outbox,
2655
+ fanout
2656
+ },
2657
+ manuallyStartQueue: true
2658
+ });
2659
+ assertStrictEquals(await assertRejects(() => federation.startQueue(void 0)), outboxError);
2660
+ assert(fanoutStarted, "a synchronous throw from one queue must not prevent later queues from starting");
2661
+ assert(rejectInbox != null);
2662
+ rejectInbox(lateInboxError);
2663
+ await capture.settle();
2664
+ assertEquals(capture.reasons, [], "an earlier listener rejection must remain handled after startup fails");
2665
+ } finally {
2666
+ await capture.settle();
2667
+ capture.stop();
2668
+ }
2669
+ });
2670
+ test("ContextImpl.sendActivity() reports automatic queue startup failures", async (t) => {
2671
+ const sender = [{
2672
+ privateKey: ed25519PrivateKey,
2673
+ keyId: ed25519Multikey.id
2674
+ }];
2675
+ const recipient = {
2676
+ id: new URL("https://example.com/recipient"),
2677
+ inboxId: new URL("https://example.com/inbox")
2678
+ };
2679
+ const createActivity = () => new Create({
2680
+ id: new URL("https://example.com/activities/queue-startup-send"),
2681
+ actor: new URL("https://example.com/actor")
2682
+ });
2683
+ await t.step("outbox", async () => {
2684
+ const listenError = /* @__PURE__ */ new TypeError("simulated outbox listen() failure");
2685
+ const messages = [];
2686
+ const queue = {
2687
+ enqueue(message) {
2688
+ messages.push(message);
2689
+ return Promise.resolve();
2690
+ },
2691
+ listen() {
2692
+ throw listenError;
2693
+ }
2694
+ };
2695
+ const capture = captureUnhandledRejections();
2696
+ const records = [];
2697
+ await configureQueueStartupWarningCapture(records);
2698
+ try {
2699
+ await new ContextImpl({
2700
+ data: void 0,
2701
+ federation: new FederationImpl({
2702
+ kv: new MemoryKvStore(),
2703
+ queue: { outbox: queue },
2704
+ documentLoaderFactory: () => mockDocumentLoader,
2705
+ contextLoaderFactory: () => mockDocumentLoader
2706
+ }),
2707
+ url: new URL("https://example.com/"),
2708
+ documentLoader: mockDocumentLoader,
2709
+ contextLoader: mockDocumentLoader
2710
+ }).sendActivity(sender, recipient, createActivity());
2711
+ assertEquals(messages.map((message) => message.type), ["outbox"]);
2712
+ await capture.settle();
2713
+ assertEquals(queueStartupWarnings(records, listenError).length, 1);
2714
+ assertEquals(capture.reasons, []);
2715
+ } finally {
2716
+ await capture.settle();
2717
+ capture.stop();
2718
+ await reset();
2719
+ }
2720
+ });
2721
+ await t.step("fanout", async () => {
2722
+ const listenError = /* @__PURE__ */ new TypeError("simulated fanout listen() failure");
2723
+ const messages = [];
2724
+ const outbox = {
2725
+ enqueue() {
2726
+ return Promise.resolve();
2727
+ },
2728
+ listen() {
2729
+ return Promise.resolve();
2730
+ }
2731
+ };
2732
+ const fanout = {
2733
+ enqueue(message) {
2734
+ messages.push(message);
2735
+ return Promise.resolve();
2736
+ },
2737
+ listen() {
2738
+ throw listenError;
2739
+ }
2740
+ };
2741
+ const capture = captureUnhandledRejections();
2742
+ const records = [];
2743
+ await configureQueueStartupWarningCapture(records);
2744
+ try {
2745
+ await new ContextImpl({
2746
+ data: void 0,
2747
+ federation: new FederationImpl({
2748
+ kv: new MemoryKvStore(),
2749
+ queue: {
2750
+ outbox,
2751
+ fanout
2752
+ },
2753
+ documentLoaderFactory: () => mockDocumentLoader,
2754
+ contextLoaderFactory: () => mockDocumentLoader
2755
+ }),
2756
+ url: new URL("https://example.com/"),
2757
+ documentLoader: mockDocumentLoader,
2758
+ contextLoader: mockDocumentLoader
2759
+ }).sendActivity(sender, recipient, createActivity(), { fanout: "force" });
2760
+ assertEquals(messages.map((message) => message.type), ["fanout"]);
2761
+ await capture.settle();
2762
+ assertEquals(queueStartupWarnings(records, listenError).length, 1);
2763
+ assertEquals(capture.reasons, []);
2764
+ } finally {
2765
+ await capture.settle();
2766
+ capture.stop();
2767
+ await reset();
2768
+ }
2769
+ });
2770
+ });
2771
+ test("queued Linked Data signatures without created use normalization contexts", async (t) => {
2772
+ for (const legacy of [false, true]) await t.step(legacy ? "legacy compacted payload" : "verified normalized cache", async () => {
2773
+ const normalized = await compactJsonLd(ldSignatureWithoutCreated, mockDocumentLoader);
2774
+ const raw = legacy ? normalized : structuredClone(ldSignatureWithoutCreated);
2775
+ const federation = new FederationImpl({
2776
+ kv: new MemoryKvStore(),
2777
+ contextLoaderFactory: () => async (url) => {
2778
+ if (url === "https://www.w3.org/ns/activitystreams" || url === "https://w3id.org/identity/v1") return await mockDocumentLoader(url);
2779
+ throw new Error(`Unexpected context: ${url}`);
2780
+ }
2781
+ });
2782
+ let deliveries = 0;
2783
+ let receivedRaw;
2784
+ federation.setInboxListeners("/users/{identifier}/inbox", "/inbox").on(Create, (ctx, activity) => {
2785
+ deliveries++;
2786
+ receivedRaw = ctx.activity;
2787
+ assertEquals(activity.id?.href, ldSignatureWithoutCreated.id);
2788
+ });
2789
+ await federation.processQueuedTask(void 0, {
2790
+ type: "inbox",
2791
+ id: crypto.randomUUID(),
2792
+ baseUrl: "https://example.com",
2793
+ activity: raw,
2794
+ ...legacy ? {} : {
2795
+ normalizedActivity: normalized,
2796
+ ldSignatureVerified: true
2797
+ },
2798
+ started: (/* @__PURE__ */ new Date()).toISOString(),
2799
+ attempt: 0,
2800
+ identifier: null,
2801
+ traceContext: {}
2802
+ });
2803
+ assertEquals(deliveries, 1);
2804
+ assertEquals(receivedRaw, raw);
2805
+ });
2806
+ });
1997
2807
  test("FederationImpl.processQueuedTask()", async (t) => {
1998
2808
  await t.step("with MessageQueue having nativeRetrial", async () => {
1999
2809
  const kv = new MemoryKvStore();
@@ -3900,7 +4710,7 @@ test("ContextImpl.sendActivity()", async (t) => {
3900
4710
  const kv = new MemoryKvStore();
3901
4711
  const federation = new FederationImpl({
3902
4712
  kv,
3903
- contextLoaderFactory: () => mockDocumentLoader
4713
+ allowPrivateAddress: true
3904
4714
  });
3905
4715
  federation.setActorDispatcher("/{identifier}", async (ctx, identifier) => {
3906
4716
  if (identifier !== "1") return null;
@@ -4023,11 +4833,13 @@ test("ContextImpl.sendActivity()", async (t) => {
4023
4833
  });
4024
4834
  await t.step("records recipient span attributes correctly", async () => {
4025
4835
  const [tracerProvider, exporter] = createTestTracerProvider();
4026
- const ctx = new FederationImpl({
4836
+ const federation3 = new FederationImpl({
4027
4837
  kv,
4028
4838
  contextLoaderFactory: () => mockDocumentLoader,
4029
4839
  tracerProvider
4030
- }).createContext(new URL("https://example.com/"), void 0);
4840
+ });
4841
+ federation3.allowPrivateAddress = true;
4842
+ const ctx = federation3.createContext(new URL("https://example.com/"), void 0);
4031
4843
  const activity = new vocab.Create({
4032
4844
  id: new URL("https://example.com/activity/telemetry"),
4033
4845
  actor: new URL("https://example.com/person"),
@@ -4061,19 +4873,23 @@ test("ContextImpl.sendActivity()", async (t) => {
4061
4873
  };
4062
4874
  const federation2 = new FederationImpl({
4063
4875
  kv,
4064
- contextLoaderFactory: () => mockDocumentLoader,
4876
+ allowPrivateAddress: true,
4065
4877
  queue
4066
4878
  });
4067
4879
  federation2.setActorDispatcher("/{identifier}", async (ctx, identifier) => {
4068
- if (identifier !== "john") return null;
4880
+ if (identifier !== "john" && identifier !== "rsa-only") return null;
4069
4881
  const keys = await ctx.getActorKeyPairs(identifier);
4070
4882
  return new vocab.Person({
4071
4883
  id: ctx.getActorUri(identifier),
4072
- preferredUsername: "john",
4884
+ preferredUsername: identifier,
4073
4885
  publicKey: keys[0].cryptographicKey,
4074
4886
  assertionMethods: keys.map((k) => k.multikey)
4075
4887
  });
4076
4888
  }).setKeyPairsDispatcher((_ctx, identifier) => {
4889
+ if (identifier === "rsa-only") return [{
4890
+ privateKey: rsaPrivateKey2,
4891
+ publicKey: rsaPublicKey2.publicKey
4892
+ }];
4077
4893
  if (identifier !== "john") return [];
4078
4894
  return [{
4079
4895
  privateKey: rsaPrivateKey2,
@@ -4122,6 +4938,375 @@ test("ContextImpl.sendActivity()", async (t) => {
4122
4938
  proofCount++;
4123
4939
  }
4124
4940
  assertEquals(proofCount, 1);
4941
+ const oldContext = [
4942
+ "https://w3id.org/identity/v1",
4943
+ "https://www.w3.org/ns/activitystreams",
4944
+ "https://w3id.org/security/data-integrity/v1"
4945
+ ];
4946
+ const oldJson = await (await signObject(new vocab.Create({
4947
+ id: new URL("https://example.com/activity/1"),
4948
+ actor: new URL("https://example.com/john")
4949
+ }), ed25519PrivateKey, ed25519Multikey.id, {
4950
+ contextLoader: documentLoader,
4951
+ context: oldContext
4952
+ })).toJsonLd({
4953
+ format: "compact",
4954
+ contextLoader: documentLoader,
4955
+ context: oldContext
4956
+ });
4957
+ queue.clear();
4958
+ await federation2.processQueuedTask(void 0, {
4959
+ ...fanoutMsg,
4960
+ id: crypto.randomUUID(),
4961
+ activity: oldJson
4962
+ });
4963
+ const replayed = queue.messages.at(-1);
4964
+ assert(replayed != null && replayed.type === "outbox");
4965
+ assertEquals(detachSignature(replayed.activity), oldJson);
4966
+ const proofless = { ...oldJson };
4967
+ delete proofless.proof;
4968
+ queue.clear();
4969
+ await federation2.processQueuedTask(void 0, {
4970
+ ...fanoutMsg,
4971
+ id: crypto.randomUUID(),
4972
+ activity: proofless
4973
+ });
4974
+ const signedReplay = queue.messages.at(-1);
4975
+ assert(signedReplay != null && signedReplay.type === "outbox");
4976
+ assert(typeof signedReplay.activity === "object" && signedReplay.activity != null && "proof" in signedReplay.activity);
4977
+ const edKey = (await ctx2.getActorKeyPairs("john")).find((key) => key.privateKey.algorithm.name === "Ed25519");
4978
+ assert(edKey != null && edKey.multikey.id != null);
4979
+ const restoredJson = await (await signObject(new vocab.Create({
4980
+ id: new URL("https://example.com/activity/old"),
4981
+ actor: ctx2.getActorUri("john")
4982
+ }), edKey.privateKey, edKey.multikey.id, {
4983
+ contextLoader: documentLoader,
4984
+ context: oldContext
4985
+ })).toJsonLd({
4986
+ format: "compact",
4987
+ contextLoader: documentLoader,
4988
+ context: oldContext
4989
+ });
4990
+ const restored = await vocab.Create.fromJsonLd(restoredJson, {
4991
+ contextLoader: documentLoader,
4992
+ documentLoader
4993
+ });
4994
+ queue.clear();
4995
+ await ctx2.sendActivity([{
4996
+ privateKey: rsaPrivateKey2,
4997
+ keyId: rsaPublicKey2.id
4998
+ }], {
4999
+ id: new URL("https://example.com/recipient"),
5000
+ inboxId: new URL("https://example.com/inbox")
5001
+ }, restored);
5002
+ const resent = queue.messages.at(-1);
5003
+ assert(resent != null && resent.type === "outbox");
5004
+ assertEquals(detachSignature(resent.activity), restoredJson);
5005
+ queue.clear();
5006
+ await ctx2.sendActivity([{
5007
+ privateKey: rsaPrivateKey2,
5008
+ keyId: rsaPublicKey2.id
5009
+ }], {
5010
+ id: new URL("https://example.com/recipient"),
5011
+ inboxId: new URL("https://example.com/inbox")
5012
+ }, restored, { fanout: "force" });
5013
+ const queuedFanout = queue.messages.at(-1);
5014
+ assert(queuedFanout != null && queuedFanout.type === "fanout");
5015
+ assertEquals(queuedFanout.activity, restoredJson);
5016
+ const restoredWithSignature = await vocab.Create.fromJsonLd(attachSignature(restoredJson, {
5017
+ "@context": "https://w3id.org/identity/v1",
5018
+ type: "RsaSignature2017",
5019
+ creator: "https://example.com/person2#key4",
5020
+ created: "2026-01-01T00:00:00Z",
5021
+ signatureValue: "abc"
5022
+ }), {
5023
+ contextLoader: documentLoader,
5024
+ documentLoader
5025
+ });
5026
+ queue.clear();
5027
+ await ctx2.sendActivity([{
5028
+ privateKey: rsaPrivateKey2,
5029
+ keyId: rsaPublicKey2.id
5030
+ }], {
5031
+ id: new URL("https://example.com/recipient"),
5032
+ inboxId: new URL("https://example.com/inbox")
5033
+ }, restoredWithSignature);
5034
+ const resigned = queue.messages.at(-1);
5035
+ assert(resigned != null && resigned.type === "outbox");
5036
+ assertEquals(detachSignature(resigned.activity), restoredJson);
5037
+ const rsaOnlyJson = await (await signObject(new vocab.Create({
5038
+ id: new URL("https://example.com/activity/rsa-only"),
5039
+ actor: new URL("https://example.com/rsa-only")
5040
+ }), ed25519PrivateKey, ed25519Multikey.id, {
5041
+ contextLoader: documentLoader,
5042
+ context: oldContext
5043
+ })).toJsonLd({
5044
+ format: "compact",
5045
+ contextLoader: documentLoader,
5046
+ context: oldContext
5047
+ });
5048
+ const rsaOnlyRestored = await vocab.Create.fromJsonLd(rsaOnlyJson, {
5049
+ contextLoader: documentLoader,
5050
+ documentLoader
5051
+ });
5052
+ queue.clear();
5053
+ await ctx2.sendActivity({ identifier: "rsa-only" }, {
5054
+ id: new URL("https://example.com/recipient"),
5055
+ inboxId: new URL("https://example.com/inbox")
5056
+ }, rsaOnlyRestored, { fanout: "force" });
5057
+ const rsaOnlyMessage = queue.messages.at(-1);
5058
+ assert(rsaOnlyMessage != null && rsaOnlyMessage.type === "fanout");
5059
+ assertEquals(rsaOnlyMessage.activity, rsaOnlyJson);
5060
+ queue.clear();
5061
+ await ctx2.sendActivity({ username: "john" }, {
5062
+ id: new URL("https://example.com/recipient"),
5063
+ inboxId: new URL("https://example.com/inbox")
5064
+ }, restored, { fanout: "force" });
5065
+ const namedFanout = queue.messages.at(-1);
5066
+ assert(namedFanout != null && namedFanout.type === "fanout");
5067
+ const namedJson = detachSignature(namedFanout.activity);
5068
+ assertEquals((Array.isArray(namedJson.proof) ? namedJson.proof : [namedJson.proof]).length, 1);
5069
+ assert(namedJson["@context"].includes("https://w3id.org/security/v1"));
5070
+ const noIdJson = await (await signObject(new vocab.Create({ actor: ctx2.getActorUri("john") }), edKey.privateKey, edKey.multikey.id, {
5071
+ contextLoader: documentLoader,
5072
+ context: oldContext
5073
+ })).toJsonLd({
5074
+ format: "compact",
5075
+ contextLoader: documentLoader,
5076
+ context: oldContext
5077
+ });
5078
+ const noIdRestored = await vocab.Create.fromJsonLd(noIdJson, {
5079
+ contextLoader: documentLoader,
5080
+ documentLoader
5081
+ });
5082
+ queue.clear();
5083
+ await ctx2.sendActivity([{
5084
+ privateKey: rsaPrivateKey2,
5085
+ keyId: rsaPublicKey2.id
5086
+ }], {
5087
+ id: new URL("https://example.com/recipient"),
5088
+ inboxId: new URL("https://example.com/inbox")
5089
+ }, noIdRestored);
5090
+ const noIdQueued = queue.messages.at(-1);
5091
+ assert(noIdQueued != null && noIdQueued.type === "outbox");
5092
+ assert(typeof detachSignature(noIdQueued.activity).id === "string");
5093
+ const currentJson = await (await signObject(new vocab.Create({
5094
+ id: new URL("https://example.com/activity/current"),
5095
+ actor: ctx2.getActorUri("john")
5096
+ }), edKey.privateKey, edKey.multikey.id, { contextLoader: documentLoader })).toJsonLd({
5097
+ format: "compact",
5098
+ contextLoader: documentLoader
5099
+ });
5100
+ const currentRestored = await vocab.Create.fromJsonLd(currentJson, {
5101
+ contextLoader: documentLoader,
5102
+ documentLoader
5103
+ });
5104
+ queue.clear();
5105
+ await ctx2.sendActivity({ username: "john" }, {
5106
+ id: new URL("https://example.com/recipient"),
5107
+ inboxId: new URL("https://example.com/inbox")
5108
+ }, currentRestored, { fanout: "force" });
5109
+ const currentFanout = queue.messages.at(-1);
5110
+ assert(currentFanout != null && currentFanout.type === "fanout");
5111
+ const currentQueued = detachSignature(currentFanout.activity);
5112
+ assertEquals((Array.isArray(currentQueued.proof) ? currentQueued.proof : [currentQueued.proof]).length, 2);
5113
+ });
5114
+ queue.clear();
5115
+ await t.step("activity transformers preserve proofs", async () => {
5116
+ const originalProof = new vocab.DataIntegrityProof({
5117
+ cryptosuite: "eddsa-jcs-2022",
5118
+ verificationMethod: new URL("https://example.com/rsa-only#multikey-2"),
5119
+ proofPurpose: "assertionMethod",
5120
+ proofValue: new Uint8Array([
5121
+ 1,
5122
+ 2,
5123
+ 3,
5124
+ 4
5125
+ ]),
5126
+ created: Temporal.Instant.from("2026-01-01T00:00:00Z")
5127
+ });
5128
+ const addedProof = new vocab.DataIntegrityProof({
5129
+ cryptosuite: "eddsa-jcs-2022",
5130
+ verificationMethod: new URL("https://example.com/rsa-only#multikey-2"),
5131
+ proofPurpose: "assertionMethod",
5132
+ proofValue: new Uint8Array([
5133
+ 5,
5134
+ 6,
5135
+ 7,
5136
+ 8
5137
+ ]),
5138
+ created: Temporal.Instant.from("2026-01-02T00:00:00Z")
5139
+ });
5140
+ const replacementProof = new vocab.DataIntegrityProof({
5141
+ cryptosuite: "eddsa-jcs-2022",
5142
+ verificationMethod: new URL("https://example.com/rsa-only#multikey-2"),
5143
+ proofPurpose: "assertionMethod",
5144
+ proofValue: new Uint8Array([
5145
+ 9,
5146
+ 10,
5147
+ 11,
5148
+ 12
5149
+ ]),
5150
+ created: Temporal.Instant.from("2026-01-03T00:00:00Z")
5151
+ });
5152
+ const restoredProof = new vocab.DataIntegrityProof({
5153
+ cryptosuite: "eddsa-jcs-2022",
5154
+ verificationMethod: new URL("https://example.com/rsa-only#multikey-2"),
5155
+ proofPurpose: "assertionMethod",
5156
+ proofValue: new Uint8Array([
5157
+ 13,
5158
+ 14,
5159
+ 15,
5160
+ 16
5161
+ ]),
5162
+ created: Temporal.Instant.from("2026-01-04T00:00:00Z")
5163
+ });
5164
+ const restoredProofHolder = {};
5165
+ const federation3 = new FederationImpl({
5166
+ kv,
5167
+ allowPrivateAddress: true,
5168
+ queue,
5169
+ activityTransformers: [(activity) => {
5170
+ if (activity.id?.href === "https://example.com/activity/transformed-proof") return activity.clone({ proofs: [originalProof, addedProof] });
5171
+ if (activity.id?.href === "https://example.com/activity/replaced-proof") return new vocab.Create({
5172
+ id: activity.id,
5173
+ actor: new URL("https://example.com/rsa-only"),
5174
+ object: new URL("https://example.com/note/replaced"),
5175
+ proofs: [replacementProof]
5176
+ });
5177
+ if (activity.id?.href === "https://example.com/activity/restored-proof") return activity.clone({ proofs: [restoredProofHolder.old, restoredProof] });
5178
+ return activity;
5179
+ }]
5180
+ });
5181
+ federation3.setActorDispatcher("/{identifier}", async (ctx, identifier) => {
5182
+ if (identifier !== "rsa-only") return null;
5183
+ const keys = await ctx.getActorKeyPairs(identifier);
5184
+ return new vocab.Person({
5185
+ id: ctx.getActorUri(identifier),
5186
+ preferredUsername: identifier,
5187
+ publicKey: keys[0].cryptographicKey,
5188
+ assertionMethods: keys.map((k) => k.multikey)
5189
+ });
5190
+ }).setKeyPairsDispatcher((_ctx, identifier) => identifier === "rsa-only" ? [{
5191
+ privateKey: rsaPrivateKey2,
5192
+ publicKey: rsaPublicKey2.publicKey
5193
+ }] : []);
5194
+ const ctx3 = new ContextImpl({
5195
+ data: void 0,
5196
+ federation: federation3,
5197
+ url: new URL("https://example.com/"),
5198
+ documentLoader,
5199
+ contextLoader: documentLoader
5200
+ });
5201
+ const activity = new vocab.Create({
5202
+ id: new URL("https://example.com/activity/transformed-proof"),
5203
+ actor: ctx3.getActorUri("rsa-only"),
5204
+ proofs: [originalProof]
5205
+ });
5206
+ await ctx3.sendActivity({ identifier: "rsa-only" }, {
5207
+ id: new URL("https://example.com/recipient"),
5208
+ inboxId: new URL("https://example.com/inbox")
5209
+ }, activity, { fanout: "force" });
5210
+ const fanout = queue.messages.at(-1);
5211
+ assert(fanout != null && fanout.type === "fanout");
5212
+ const fanoutJson = detachSignature(fanout.activity);
5213
+ assertEquals((Array.isArray(fanoutJson.proof) ? fanoutJson.proof : [fanoutJson.proof]).length, 2);
5214
+ const replacedActivity = new vocab.Create({
5215
+ id: new URL("https://example.com/activity/replaced-proof"),
5216
+ actor: ctx3.getActorUri("rsa-only"),
5217
+ proofs: [originalProof]
5218
+ });
5219
+ queue.clear();
5220
+ await ctx3.sendActivity({ identifier: "rsa-only" }, {
5221
+ id: new URL("https://example.com/recipient"),
5222
+ inboxId: new URL("https://example.com/inbox")
5223
+ }, replacedActivity, { fanout: "force" });
5224
+ const replacedFanout = queue.messages.at(-1);
5225
+ assert(replacedFanout != null && replacedFanout.type === "fanout");
5226
+ const replacedJson = detachSignature(replacedFanout.activity);
5227
+ assertEquals(replacedJson.object, "https://example.com/note/replaced");
5228
+ const replacedProofs = Array.isArray(replacedJson.proof) ? replacedJson.proof : [replacedJson.proof];
5229
+ assertEquals(replacedProofs.length, 1);
5230
+ const [keptProof] = replacedProofs;
5231
+ assertEquals(keptProof.created, "2026-01-03T00:00:00Z");
5232
+ const oldContext = [
5233
+ "https://w3id.org/identity/v1",
5234
+ "https://www.w3.org/ns/activitystreams",
5235
+ "https://w3id.org/security/data-integrity/v1"
5236
+ ];
5237
+ const restoredJson = await (await signObject(new vocab.Create({
5238
+ id: new URL("https://example.com/activity/restored-proof"),
5239
+ actor: ctx3.getActorUri("rsa-only")
5240
+ }), ed25519PrivateKey, ed25519Multikey.id, {
5241
+ contextLoader: documentLoader,
5242
+ context: oldContext
5243
+ })).toJsonLd({
5244
+ format: "compact",
5245
+ contextLoader: documentLoader,
5246
+ context: oldContext
5247
+ });
5248
+ const restored = await vocab.Create.fromJsonLd(restoredJson, {
5249
+ contextLoader: documentLoader,
5250
+ documentLoader
5251
+ });
5252
+ for await (const proof of restored.getProofs({ contextLoader: documentLoader })) {
5253
+ restoredProofHolder.old = proof;
5254
+ break;
5255
+ }
5256
+ queue.clear();
5257
+ await ctx3.sendActivity({ identifier: "rsa-only" }, {
5258
+ id: new URL("https://example.com/recipient"),
5259
+ inboxId: new URL("https://example.com/inbox")
5260
+ }, restored, { fanout: "force" });
5261
+ const restoredFanout = queue.messages.at(-1);
5262
+ assert(restoredFanout != null && restoredFanout.type === "fanout");
5263
+ const restoredFanoutJson = detachSignature(restoredFanout.activity);
5264
+ const restoredProofs = Array.isArray(restoredFanoutJson.proof) ? restoredFanoutJson.proof : [restoredFanoutJson.proof];
5265
+ assertEquals(restoredProofs.length, 1);
5266
+ const [transformedProof] = restoredProofs;
5267
+ assertEquals(transformedProof.created, "2026-01-04T00:00:00Z");
5268
+ assert(Array.isArray(restoredFanoutJson["@context"]) && restoredFanoutJson["@context"].includes("https://w3id.org/security/v1"));
5269
+ const staleTimestampJson = await (await signObject(new vocab.Create({
5270
+ id: new URL("https://example.com/activity/stale-timestamp"),
5271
+ actor: ctx3.getActorUri("rsa-only")
5272
+ }), ed25519PrivateKey, ed25519Multikey.id, {
5273
+ contextLoader: documentLoader,
5274
+ context: oldContext
5275
+ })).toJsonLd({
5276
+ format: "compact",
5277
+ contextLoader: documentLoader,
5278
+ context: oldContext
5279
+ });
5280
+ const staleTimestampProof = Array.isArray(staleTimestampJson.proof) ? staleTimestampJson.proof[0] : staleTimestampJson.proof;
5281
+ staleTimestampProof.created = "2026-01-01T00:00:00+00:00";
5282
+ const staleTimestamp = await vocab.Create.fromJsonLd(staleTimestampJson, {
5283
+ contextLoader: documentLoader,
5284
+ documentLoader
5285
+ });
5286
+ queue.clear();
5287
+ await ctx3.sendActivity({ identifier: "rsa-only" }, {
5288
+ id: new URL("https://example.com/recipient"),
5289
+ inboxId: new URL("https://example.com/inbox")
5290
+ }, staleTimestamp, { fanout: "force" });
5291
+ const staleTimestampFanout = queue.messages.at(-1);
5292
+ assert(staleTimestampFanout != null && staleTimestampFanout.type === "fanout");
5293
+ assertEquals(detachSignature(staleTimestampFanout.activity), staleTimestampJson);
5294
+ const proofless = new vocab.Create({
5295
+ id: new URL("https://example.com/activity/proofless"),
5296
+ actor: ctx3.getActorUri("rsa-only")
5297
+ });
5298
+ let unformattedSerializations = 0;
5299
+ const originalToJsonLd = proofless.toJsonLd.bind(proofless);
5300
+ Object.defineProperty(proofless, "toJsonLd", { value: async (options) => {
5301
+ if (options?.format == null) unformattedSerializations++;
5302
+ return await originalToJsonLd(options);
5303
+ } });
5304
+ queue.clear();
5305
+ await ctx3.sendActivity({ identifier: "rsa-only" }, {
5306
+ id: new URL("https://example.com/recipient"),
5307
+ inboxId: new URL("https://example.com/inbox")
5308
+ }, proofless, { fanout: "skip" });
5309
+ assertEquals(unformattedSerializations, 0);
4125
5310
  });
4126
5311
  queue.clear();
4127
5312
  await t.step("fanout: \"force\" preserves pre-signed proof normalization", async () => {
@@ -4232,7 +5417,7 @@ test("ContextImpl.sendActivity()", async (t) => {
4232
5417
  const asyncEnqueued = [];
4233
5418
  const fed = new FederationImpl({
4234
5419
  kv,
4235
- contextLoaderFactory: () => mockDocumentLoader,
5420
+ allowPrivateAddress: true,
4236
5421
  queue: {
4237
5422
  enqueue(message) {
4238
5423
  return new Promise((resolve) => {
@@ -4399,10 +5584,10 @@ test({
4399
5584
  const signedInvite = await signObject(new vocab.Invite({ actor: new URL("https://example.com/person2") }), ed25519PrivateKey, ed25519Multikey.id);
4400
5585
  assert(await ctx.routeActivity("id", signedInvite));
4401
5586
  assertEquals(activities, [[null, signedOffer], ["id", signedInvite]]);
4402
- assertFalse(await ctx.routeActivity(null, new vocab.Create({
5587
+ assertFalse(await withDnsLookup(() => Promise.reject(/* @__PURE__ */ new Error("Resolver unavailable")), () => ctx.routeActivity(null, new vocab.Create({
4403
5588
  id: new URL("https://example.com/not-found"),
4404
5589
  actor: new URL("https://example.com/person")
4405
- })));
5590
+ }))));
4406
5591
  assertEquals(activities, [[null, signedOffer], ["id", signedInvite]]);
4407
5592
  assertFalse(await ctx.routeActivity(null, new vocab.Create({
4408
5593
  id: new URL("https://example.com/person"),
@@ -4761,7 +5946,7 @@ test("InboxContextImpl.forwardActivity()", async (t) => {
4761
5946
  const kv = new MemoryKvStore();
4762
5947
  const federation = new FederationImpl({
4763
5948
  kv,
4764
- contextLoaderFactory: () => mockDocumentLoader
5949
+ allowPrivateAddress: true
4765
5950
  });
4766
5951
  await t.step("skip", async () => {
4767
5952
  await new InboxContextImpl(null, {
@@ -4884,6 +6069,7 @@ test("InboxContextImpl.forwardActivity()", async (t) => {
4884
6069
  contextLoaderFactory: () => mockDocumentLoader,
4885
6070
  tracerProvider
4886
6071
  });
6072
+ federationWithTracing.allowPrivateAddress = true;
4887
6073
  await new InboxContextImpl(null, await signJsonLd({
4888
6074
  "@context": "https://www.w3.org/ns/activitystreams",
4889
6075
  "type": "Create",
@@ -4907,6 +6093,63 @@ test("InboxContextImpl.forwardActivity()", async (t) => {
4907
6093
  });
4908
6094
  esm_default.hardReset();
4909
6095
  });
6096
+ test("InboxContextImpl.forwardActivity() without created", async (t) => {
6097
+ for (const immediate of [true, false]) await t.step(immediate ? "immediate delivery" : "queued delivery", async () => {
6098
+ const delivered = [];
6099
+ const queued = [];
6100
+ esm_default.spyGlobal();
6101
+ esm_default.post("https://example.com/inbox", async (call) => {
6102
+ delivered.push(await call.request.json());
6103
+ return new Response(null, { status: 202 });
6104
+ });
6105
+ try {
6106
+ const federation = new FederationImpl({
6107
+ kv: new MemoryKvStore(),
6108
+ allowPrivateAddress: true,
6109
+ manuallyStartQueue: true,
6110
+ queue: { outbox: {
6111
+ enqueue(message) {
6112
+ queued.push(message);
6113
+ return Promise.resolve();
6114
+ },
6115
+ async listen() {}
6116
+ } }
6117
+ });
6118
+ const activity = structuredClone(ldSignatureWithoutCreated);
6119
+ assert(await verifyJsonLd(activity, {
6120
+ documentLoader: mockDocumentLoader,
6121
+ contextLoader: mockDocumentLoader
6122
+ }));
6123
+ await new InboxContextImpl(null, activity, activity.id, "https://www.w3.org/ns/activitystreams#Create", {
6124
+ data: void 0,
6125
+ federation,
6126
+ url: new URL("https://example.com/"),
6127
+ documentLoader: mockDocumentLoader,
6128
+ contextLoader: mockDocumentLoader
6129
+ }).forwardActivity([{
6130
+ privateKey: rsaPrivateKey2,
6131
+ keyId: rsaPublicKey2.id
6132
+ }], {
6133
+ id: new URL("https://example.com/recipient"),
6134
+ inboxId: new URL("https://example.com/inbox")
6135
+ }, {
6136
+ skipIfUnsigned: true,
6137
+ immediate
6138
+ });
6139
+ if (immediate) {
6140
+ assertEquals(delivered, [activity]);
6141
+ assertEquals(queued, []);
6142
+ } else {
6143
+ assertEquals(delivered, []);
6144
+ assertEquals(queued.length, 1);
6145
+ assertEquals(queued[0].type, "outbox");
6146
+ assertEquals(queued[0].activity, activity);
6147
+ }
6148
+ } finally {
6149
+ esm_default.hardReset();
6150
+ }
6151
+ });
6152
+ });
4910
6153
  test("KvSpecDeterminer", async (t) => {
4911
6154
  await t.step("should use default spec when not found in KV", async () => {
4912
6155
  assertEquals(await new KvSpecDeterminer(new MemoryKvStore(), ["test", "spec"]).determineSpec("example.com"), "rfc9421");
@@ -4961,6 +6204,286 @@ test("ContextImpl.sendActivity() honors the private-address policy", async (t) =
4961
6204
  }
4962
6205
  });
4963
6206
  });
6207
+ function deferredSignal() {
6208
+ let resolve;
6209
+ return {
6210
+ promise: new Promise((r) => resolve = r),
6211
+ resolve
6212
+ };
6213
+ }
6214
+ test("ContextImpl.sendActivity() waits for sibling deliveries on failure", async () => {
6215
+ const failingInbox = "http://127.0.0.1:3001/inbox/fail";
6216
+ const slowInbox = "http://127.0.0.1:3002/inbox/slow";
6217
+ const failingEntered = deferredSignal();
6218
+ const slowEntered = deferredSignal();
6219
+ const slowCompleted = deferredSignal();
6220
+ let releaseSlow;
6221
+ const slowGate = new Promise((resolve) => releaseSlow = resolve);
6222
+ let slowStarted = false;
6223
+ let slowSettled = false;
6224
+ esm_default.spyGlobal();
6225
+ esm_default.post(failingInbox, () => {
6226
+ failingEntered.resolve();
6227
+ return new Response(null, { status: 500 });
6228
+ });
6229
+ esm_default.post(slowInbox, async () => {
6230
+ slowStarted = true;
6231
+ slowEntered.resolve();
6232
+ await slowGate;
6233
+ slowSettled = true;
6234
+ slowCompleted.resolve();
6235
+ return new Response(null, { status: 202 });
6236
+ });
6237
+ let observed;
6238
+ let released = false;
6239
+ try {
6240
+ const ctx = createFederation({
6241
+ kv: new MemoryKvStore(),
6242
+ allowPrivateAddress: true
6243
+ }).createContext(new URL("https://example.com/"));
6244
+ const activity = new Create({
6245
+ id: new URL("https://example.com/activity/fanout"),
6246
+ actor: new URL("https://example.com/person")
6247
+ });
6248
+ let outerSettled = false;
6249
+ let outerError;
6250
+ observed = ctx.sendActivity([{
6251
+ privateKey: ed25519PrivateKey,
6252
+ keyId: ed25519Multikey.id
6253
+ }], [new Person({
6254
+ id: new URL("https://example.com/recipients/failing"),
6255
+ inbox: new URL(failingInbox)
6256
+ }), new Person({
6257
+ id: new URL("https://example.com/recipients/slow"),
6258
+ inbox: new URL(slowInbox)
6259
+ })], activity, { immediate: true }).then(() => {
6260
+ outerSettled = true;
6261
+ }, (error) => {
6262
+ outerSettled = true;
6263
+ outerError = error;
6264
+ });
6265
+ await Promise.all([failingEntered.promise, slowEntered.promise]);
6266
+ await new Promise((resolve) => setTimeout(resolve, 0));
6267
+ assertFalse(outerSettled, "sendActivity() must wait for sibling deliveries before rejecting");
6268
+ releaseSlow();
6269
+ released = true;
6270
+ await observed;
6271
+ assert(slowSettled, "the delayed delivery should have settled");
6272
+ assertInstanceOf(outerError, SendActivityError);
6273
+ } finally {
6274
+ if (!released) releaseSlow();
6275
+ if (slowStarted) await slowCompleted.promise;
6276
+ await observed;
6277
+ esm_default.hardReset();
6278
+ }
6279
+ });
6280
+ test("InboxContextImpl.forwardActivity() waits for sibling deliveries on failure", async () => {
6281
+ const failingInbox = "http://127.0.0.1:3003/inbox/fail";
6282
+ const slowInbox = "http://127.0.0.1:3004/inbox/slow";
6283
+ const failingEntered = deferredSignal();
6284
+ const slowEntered = deferredSignal();
6285
+ const slowCompleted = deferredSignal();
6286
+ let releaseSlow;
6287
+ const slowGate = new Promise((resolve) => releaseSlow = resolve);
6288
+ let slowStarted = false;
6289
+ let slowSettled = false;
6290
+ esm_default.spyGlobal();
6291
+ esm_default.post(failingInbox, () => {
6292
+ failingEntered.resolve();
6293
+ return new Response(null, { status: 500 });
6294
+ });
6295
+ esm_default.post(slowInbox, async () => {
6296
+ slowStarted = true;
6297
+ slowEntered.resolve();
6298
+ await slowGate;
6299
+ slowSettled = true;
6300
+ slowCompleted.resolve();
6301
+ return new Response(null, { status: 202 });
6302
+ });
6303
+ let observed;
6304
+ let released = false;
6305
+ try {
6306
+ const federation = new FederationImpl({
6307
+ kv: new MemoryKvStore(),
6308
+ allowPrivateAddress: true
6309
+ });
6310
+ const activity = await signObject(new vocab.Create({
6311
+ id: new URL("https://example.com/activity/forward"),
6312
+ actor: new URL("https://example.com/person2")
6313
+ }), ed25519PrivateKey, ed25519Multikey.id, {
6314
+ contextLoader: mockDocumentLoader,
6315
+ documentLoader: mockDocumentLoader
6316
+ });
6317
+ const ctx = new InboxContextImpl(null, await activity.toJsonLd({ contextLoader: mockDocumentLoader }), activity.id?.href, getTypeId(activity).href, {
6318
+ data: void 0,
6319
+ federation,
6320
+ url: new URL("https://example.com/"),
6321
+ documentLoader: mockDocumentLoader,
6322
+ contextLoader: mockDocumentLoader
6323
+ });
6324
+ let outerSettled = false;
6325
+ let outerError;
6326
+ observed = ctx.forwardActivity([{
6327
+ privateKey: ed25519PrivateKey,
6328
+ keyId: ed25519Multikey.id
6329
+ }], [{
6330
+ id: new URL("https://example.com/recipients/failing"),
6331
+ inboxId: new URL(failingInbox)
6332
+ }, {
6333
+ id: new URL("https://example.com/recipients/slow"),
6334
+ inboxId: new URL(slowInbox)
6335
+ }], {
6336
+ immediate: true,
6337
+ skipIfUnsigned: true
6338
+ }).then(() => {
6339
+ outerSettled = true;
6340
+ }, (error) => {
6341
+ outerSettled = true;
6342
+ outerError = error;
6343
+ });
6344
+ await Promise.all([failingEntered.promise, slowEntered.promise]);
6345
+ await new Promise((resolve) => setTimeout(resolve, 0));
6346
+ assertFalse(outerSettled, "forwardActivity() must wait for sibling deliveries before rejecting");
6347
+ releaseSlow();
6348
+ released = true;
6349
+ await observed;
6350
+ assert(slowSettled, "the delayed delivery should have settled");
6351
+ assertInstanceOf(outerError, SendActivityError);
6352
+ } finally {
6353
+ if (!released) releaseSlow();
6354
+ if (slowStarted) await slowCompleted.promise;
6355
+ await observed;
6356
+ esm_default.hardReset();
6357
+ }
6358
+ });
6359
+ test("FederationImpl.sendActivity() drains deliveries when fan-out setup fails", async () => {
6360
+ const slowInbox = "http://127.0.0.1:3005/inbox/slow";
6361
+ const slowEntered = deferredSignal();
6362
+ const slowCompleted = deferredSignal();
6363
+ let releaseSlow;
6364
+ const slowGate = new Promise((resolve) => releaseSlow = resolve);
6365
+ let slowStarted = false;
6366
+ let slowSettled = false;
6367
+ esm_default.spyGlobal();
6368
+ esm_default.post(slowInbox, async () => {
6369
+ slowStarted = true;
6370
+ slowEntered.resolve();
6371
+ await slowGate;
6372
+ slowSettled = true;
6373
+ slowCompleted.resolve();
6374
+ return new Response(null, { status: 202 });
6375
+ });
6376
+ let observed;
6377
+ let released = false;
6378
+ try {
6379
+ const federation = new FederationImpl({
6380
+ kv: new MemoryKvStore(),
6381
+ allowPrivateAddress: true
6382
+ });
6383
+ const context = federation.createContext(new URL("https://example.com/"));
6384
+ const activity = new Create({
6385
+ id: new URL("https://example.com/activity/setup-failure"),
6386
+ actor: new URL("https://example.com/person")
6387
+ });
6388
+ let outerSettled = false;
6389
+ let outerError;
6390
+ observed = federation.sendActivity([{
6391
+ privateKey: ed25519PrivateKey,
6392
+ keyId: ed25519Multikey.id
6393
+ }], {
6394
+ [slowInbox]: {
6395
+ actorIds: ["https://example.com/recipients/slow"],
6396
+ sharedInbox: false
6397
+ },
6398
+ "not a url": {
6399
+ actorIds: ["https://example.com/recipients/invalid"],
6400
+ sharedInbox: false
6401
+ }
6402
+ }, activity, {
6403
+ context,
6404
+ immediate: true
6405
+ }).then(() => {
6406
+ outerSettled = true;
6407
+ }, (error) => {
6408
+ outerSettled = true;
6409
+ outerError = error;
6410
+ });
6411
+ await slowEntered.promise;
6412
+ await new Promise((resolve) => setTimeout(resolve, 0));
6413
+ assertFalse(outerSettled, "sendActivity() must drain started deliveries when fan-out setup fails");
6414
+ releaseSlow();
6415
+ released = true;
6416
+ await observed;
6417
+ assert(slowSettled, "the started delivery should have settled");
6418
+ assertInstanceOf(outerError, TypeError);
6419
+ } finally {
6420
+ if (!released) releaseSlow();
6421
+ if (slowStarted) await slowCompleted.promise;
6422
+ await observed;
6423
+ esm_default.hardReset();
6424
+ }
6425
+ });
6426
+ test("FederationImpl.sendActivity() handles rejections while building headers", async () => {
6427
+ const federation = new FederationImpl({ kv: new MemoryKvStore() });
6428
+ const context = federation.createContext(new URL("https://example.com/"));
6429
+ const activity = await signObject(new Create({
6430
+ id: new URL("https://example.com/activity/header-failure"),
6431
+ actor: new URL("https://example.com/person")
6432
+ }), ed25519PrivateKey, ed25519Multikey.id, {
6433
+ contextLoader: mockDocumentLoader,
6434
+ documentLoader: mockDocumentLoader
6435
+ });
6436
+ const subtle = crypto.subtle;
6437
+ const originalDigest = subtle.digest;
6438
+ let digestCalls = 0;
6439
+ let releaseSecondDigest;
6440
+ const secondDigestGate = new Promise((resolve) => {
6441
+ releaseSecondDigest = resolve;
6442
+ });
6443
+ let secondDigestStarted;
6444
+ const secondDigestEntered = new Promise((resolve) => {
6445
+ secondDigestStarted = resolve;
6446
+ });
6447
+ subtle.digest = async (algorithm, data) => {
6448
+ digestCalls++;
6449
+ if (digestCalls === 2) {
6450
+ secondDigestStarted();
6451
+ await secondDigestGate;
6452
+ }
6453
+ return await originalDigest.call(subtle, algorithm, data);
6454
+ };
6455
+ const capture = captureUnhandledRejections();
6456
+ let released = false;
6457
+ try {
6458
+ const observed = federation.sendActivity([{
6459
+ privateKey: ed25519PrivateKey,
6460
+ keyId: ed25519Multikey.id
6461
+ }], {
6462
+ "ftp://example.com/fail": {
6463
+ actorIds: ["https://example.com/recipients/failing"],
6464
+ sharedInbox: false
6465
+ },
6466
+ "http://127.0.0.1:3006/inbox": {
6467
+ actorIds: ["https://example.com/recipients/slow"],
6468
+ sharedInbox: false
6469
+ }
6470
+ }, activity, {
6471
+ context,
6472
+ immediate: true,
6473
+ collectionSync: "https://example.com/followers"
6474
+ }).catch((error) => error);
6475
+ await secondDigestEntered;
6476
+ await capture.settle();
6477
+ assertEquals(capture.reasons, [], "an early rejection must not surface as an unhandled rejection");
6478
+ releaseSecondDigest();
6479
+ released = true;
6480
+ await observed;
6481
+ } finally {
6482
+ if (!released) releaseSecondDigest();
6483
+ subtle.digest = originalDigest;
6484
+ capture.stop();
6485
+ }
6486
+ });
4964
6487
  test("Federation.fetch() bounds inbox bodies before dispatch", async () => {
4965
6488
  let dispatched = false;
4966
6489
  const json = JSON.stringify({
@@ -5018,5 +6541,19 @@ test("Federation.fetch() bounds inbox bodies before dispatch", async () => {
5018
6541
  }), { contextData: void 0 })).status, 202);
5019
6542
  assert(dispatched);
5020
6543
  });
6544
+ /**
6545
+ * Runs the given function while `node:dns/promises`' `lookup()`, which the
6546
+ * default public fetch resolves hostnames with, is replaced, so that no test
6547
+ * depends on the real DNS.
6548
+ */
6549
+ async function withDnsLookup(lookup, fn) {
6550
+ const originalLookup = dns.lookup;
6551
+ dns.lookup = lookup;
6552
+ try {
6553
+ return await fn();
6554
+ } finally {
6555
+ dns.lookup = originalLookup;
6556
+ }
6557
+ }
5021
6558
  //#endregion
5022
6559
  export {};