@fedify/fedify 2.1.30 → 2.1.32

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 (104) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-CTpfuuVp.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-CAM_bQXx.d.cts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CSddvgWN.d.ts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-CjDMsn4a.mjs → client-cpPaW7Ww.mjs} +189 -65
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +254 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/transformers.test.mjs +1 -1
  12. package/dist/{context-DLLaDau8.d.ts → context-DE2YrQwM.d.ts} +56 -13
  13. package/dist/{context-BNwv9Q1v.d.cts → context-y6ZUQCMf.d.cts} +56 -13
  14. package/dist/{deno-BATJ1hq6.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/docloader-DUXr9k_O.mjs +124 -0
  16. package/dist/federation/attachment-responses.test.d.mts +2 -0
  17. package/dist/federation/attachment-responses.test.mjs +182 -0
  18. package/dist/federation/builder.test.mjs +1 -1
  19. package/dist/federation/collection.test.mjs +1 -1
  20. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  21. package/dist/federation/delivery-attachments.test.mjs +280 -0
  22. package/dist/federation/handler.test.mjs +208 -16
  23. package/dist/federation/idempotency.test.mjs +2 -2
  24. package/dist/federation/inbox.test.mjs +1 -1
  25. package/dist/federation/middleware.test.mjs +1559 -26
  26. package/dist/federation/mod.cjs +1 -1
  27. package/dist/federation/mod.d.cts +2 -2
  28. package/dist/federation/mod.d.ts +2 -2
  29. package/dist/federation/mod.js +1 -1
  30. package/dist/federation/negotiation.test.mjs +1 -1
  31. package/dist/federation/retry.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +723 -68
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-CK3efjgM.js → http-BtbMAgTA.js} +176 -105
  36. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  37. package/dist/{http-BoR1M3W7.cjs → http-D5woFKA_.cjs} +177 -106
  38. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  39. package/dist/{http-Bjd6I92u.mjs → http-HX6wVyJh.mjs} +198 -98
  40. package/dist/{inbox-9MlBGgs9.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-ClQh9Qqh.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-BxSx_Iyp.cjs → kv-cache-B0V_e231.cjs} +59 -17
  43. package/dist/{kv-cache-ImApO425.js → kv-cache-BsDg-cT8.js} +60 -18
  44. package/dist/{ld-Crg0Xmwr.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-jL9p9V9G.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-CmD3lpy4.cjs → middleware-CrfRuKCf.cjs} +728 -143
  48. package/dist/{middleware-CE0b69gj.mjs → middleware-DiquMgtt.mjs} +444 -115
  49. package/dist/{middleware-C2AJFk8W.js → middleware-DunNtbo9.js} +727 -143
  50. package/dist/{middleware-Bi5D6DBT.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-DiuFTYUt.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CWJNbyju.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-BLDHhuW0.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-DNEgTI8M.d.ts → mod-REfljt0T.d.ts} +4 -9
  55. package/dist/{mod-Cn9GJ5ex.d.cts → mod-UvIGUHqW.d.cts} +4 -9
  56. package/dist/{mod-BmlfRBmU.d.cts → mod-sTa1Zzxk.d.cts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +8 -8
  59. package/dist/mod.d.ts +8 -8
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +764 -19
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.d.cts +1 -1
  65. package/dist/nodeinfo/mod.d.ts +1 -1
  66. package/dist/nodeinfo/mod.js +1 -1
  67. package/dist/nodeinfo/types.test.mjs +1 -1
  68. package/dist/otel/exporter.test.mjs +292 -30
  69. package/dist/otel/mod.cjs +36 -30
  70. package/dist/otel/mod.d.cts +13 -0
  71. package/dist/otel/mod.d.ts +13 -0
  72. package/dist/otel/mod.js +36 -30
  73. package/dist/{owner-BRoKojK1.mjs → owner-DwyDorZI.mjs} +2 -2
  74. package/dist/{proof-CHXVlsH_.cjs → proof-Be-4K4jn.cjs} +193 -46
  75. package/dist/{proof-DMIAezxz.mjs → proof-DYjmyrHh.mjs} +38 -13
  76. package/dist/{proof-7R4s10TJ.js → proof-Du4-5SHY.js} +187 -46
  77. package/dist/send-BGSfQkIK.mjs +416 -0
  78. package/dist/sig/http.test.mjs +506 -2
  79. package/dist/sig/key-types.test.d.mts +218 -0
  80. package/dist/sig/key-types.test.mjs +8 -0
  81. package/dist/sig/key.test.mjs +2 -2
  82. package/dist/sig/ld.test.mjs +573 -8
  83. package/dist/sig/mod.cjs +2 -2
  84. package/dist/sig/mod.d.cts +3 -3
  85. package/dist/sig/mod.d.ts +3 -3
  86. package/dist/sig/mod.js +2 -2
  87. package/dist/sig/owner.test.mjs +1 -1
  88. package/dist/sig/proof.test.mjs +95 -3
  89. package/dist/{temporal-DR0JahMu.mjs → temporal-CNCchWly.mjs} +3 -5
  90. package/dist/testing/mod.d.mts +1 -2177
  91. package/dist/{types-DRPjmHVV.cjs → types-B5wRhemi.cjs} +187 -63
  92. package/dist/{types-miAYfiGO.js → types-CXy2lRVU.js} +188 -64
  93. package/dist/utils/docloader.test.mjs +316 -32
  94. package/dist/utils/mod.cjs +1 -1
  95. package/dist/utils/mod.d.cts +1 -1
  96. package/dist/utils/mod.d.ts +1 -1
  97. package/dist/utils/mod.js +1 -1
  98. package/package.json +7 -7
  99. package/dist/docloader-OLWc7P2D.mjs +0 -82
  100. package/dist/send-BHIt_8ia.mjs +0 -260
  101. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  102. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  103. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  104. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -8,15 +8,19 @@ import { r as assertFalse } from "../assert_throws-D4DNWrux.mjs";
8
8
  import { n as assertInstanceOf, t as assert } from "../assert-BhQd8QHP.mjs";
9
9
  import { t as assertNotEquals } from "../assert_not_equals-BkxW5QJI.mjs";
10
10
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
11
- import { l as verifyRequest } from "../http-Bjd6I92u.mjs";
11
+ import { u as verifyRequest } from "../http-HX6wVyJh.mjs";
12
12
  import { i as rsaPrivateKey2, n as ed25519PrivateKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CtZLJq76.mjs";
13
- import { t as doesActorOwnKey } from "../owner-BRoKojK1.mjs";
14
- import { n as extractInboxes, r as sendActivity, t as SendActivityError } from "../send-BHIt_8ia.mjs";
13
+ import { t as doesActorOwnKey } from "../owner-DwyDorZI.mjs";
14
+ import { i as sendActivity, n as extractInboxes, r as fetchWithValidatedRedirects, t as SendActivityError } from "../send-BGSfQkIK.mjs";
15
15
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
16
16
  import { Activity, Application, Endpoints, Group, Person, Service } from "@fedify/vocab";
17
17
  import { FetchError, UrlError } from "@fedify/vocab-runtime";
18
- import dns from "node:dns/promises";
18
+ import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
19
+ import { configure, reset } from "@logtape/logtape";
19
20
  //#region src/federation/send.test.ts
21
+ function sendDirect(options) {
22
+ return sendActivity(options, { openHop: openDirectFetch });
23
+ }
20
24
  test("extractInboxes()", () => {
21
25
  const recipients = [
22
26
  new Person({
@@ -152,7 +156,7 @@ test("sendActivity()", async (t) => {
152
156
  "id": "https://example.com/activity",
153
157
  "actor": "https://example.com/person"
154
158
  };
155
- await sendActivity({
159
+ await sendDirect({
156
160
  activity,
157
161
  keys: [{
158
162
  privateKey: rsaPrivateKey2,
@@ -168,7 +172,7 @@ test("sendActivity()", async (t) => {
168
172
  assertEquals(request?.headers.get("Content-Type"), "application/activity+json");
169
173
  assertEquals(request?.headers.get("X-Test"), "test");
170
174
  httpSigVerified = null;
171
- await assertRejects(() => sendActivity({
175
+ await assertRejects(() => sendDirect({
172
176
  activity: {
173
177
  ...activity,
174
178
  actor: "https://example.com/person2"
@@ -196,7 +200,7 @@ test("sendActivity()", async (t) => {
196
200
  "id": "https://example.com/activity",
197
201
  "actor": "https://example.com/person"
198
202
  };
199
- await assertRejects(() => sendActivity({
203
+ await assertRejects(() => sendDirect({
200
204
  activity,
201
205
  activityId: "https://example.com/activity",
202
206
  keys: [{
@@ -214,7 +218,7 @@ test("sendActivity()", async (t) => {
214
218
  "actor": "https://example.com/person"
215
219
  };
216
220
  try {
217
- await sendActivity({
221
+ await sendDirect({
218
222
  activity,
219
223
  activityId: "https://example.com/activity",
220
224
  keys: [{
@@ -243,7 +247,7 @@ test("sendActivity()", async (t) => {
243
247
  "actor": "https://example.com/person"
244
248
  };
245
249
  try {
246
- await sendActivity({
250
+ await sendDirect({
247
251
  activity,
248
252
  activityId: "https://example.com/activity",
249
253
  keys: [{
@@ -272,7 +276,7 @@ test("sendActivity()", async (t) => {
272
276
  "actor": "https://example.com/person"
273
277
  };
274
278
  try {
275
- await sendActivity({
279
+ await sendDirect({
276
280
  activity,
277
281
  activityId: "https://example.com/activity",
278
282
  keys: [{
@@ -302,7 +306,7 @@ test("sendActivity()", async (t) => {
302
306
  "actor": "https://example.com/person"
303
307
  };
304
308
  try {
305
- await sendActivity({
309
+ await sendDirect({
306
310
  activity,
307
311
  activityId: "https://example.com/activity",
308
312
  keys: [{
@@ -329,7 +333,7 @@ test("sendActivity()", async (t) => {
329
333
  "actor": "https://example.com/person"
330
334
  };
331
335
  try {
332
- await sendActivity({
336
+ await sendDirect({
333
337
  activity,
334
338
  activityId: "https://example.com/activity",
335
339
  keys: [{
@@ -358,7 +362,7 @@ test("sendActivity()", async (t) => {
358
362
  "actor": "https://example.com/person"
359
363
  };
360
364
  try {
361
- await sendActivity({
365
+ await sendDirect({
362
366
  activity,
363
367
  activityId: "https://example.com/activity",
364
368
  keys: [{
@@ -382,7 +386,7 @@ test("sendActivity() records OpenTelemetry span events", async (t) => {
382
386
  await t.step("successful send", async () => {
383
387
  esm_default.get("https://example.com/", { status: 404 });
384
388
  esm_default.post("https://example.com/inbox", { status: 202 });
385
- await sendActivity({
389
+ await sendDirect({
386
390
  activity: {
387
391
  "@context": "https://www.w3.org/ns/activitystreams",
388
392
  type: "Create",
@@ -549,67 +553,718 @@ for (const signed of [false, true]) {
549
553
  });
550
554
  });
551
555
  }
552
- for (const signed of [false, true]) test({
553
- name: `sendActivity() classifies DNS failures (signed: ${signed})`,
554
- ignore: "Deno" in globalThis && (await Deno.permissions.query({ name: "net" })).state !== "granted",
555
- async fn(t) {
556
- const activity = {
557
- type: "Create",
558
- id: "https://example.com/activity"
556
+ for (const signed of [false, true]) test(`sendActivity() classifies DNS failures (signed: ${signed})`, async (t) => {
557
+ const activity = {
558
+ type: "Create",
559
+ id: "https://example.com/activity"
560
+ };
561
+ const destination = "https://delivery.invalid/inbox";
562
+ const publicInbox = "https://8.8.8.8/inbox";
563
+ const keys = signed ? [{
564
+ privateKey: rsaPrivateKey2,
565
+ keyId: rsaPublicKey2.id
566
+ }] : [];
567
+ for (const result of [
568
+ "throws",
569
+ "empty",
570
+ "cname",
571
+ "private"
572
+ ]) for (const redirected of [false, true]) await t.step(`${result}, redirected: ${redirected}`, async () => {
573
+ const resolverError = /* @__PURE__ */ new Error("Resolver unavailable");
574
+ const lookups = [];
575
+ const lookup = (hostname) => {
576
+ lookups.push(hostname);
577
+ assertEquals(hostname, "delivery.invalid");
578
+ if (result === "throws") return Promise.reject(resolverError);
579
+ return Promise.resolve(result === "empty" ? [] : [{
580
+ address: result === "private" ? "127.0.0.1" : "alias.invalid.",
581
+ family: 4
582
+ }]);
559
583
  };
560
- const destination = "https://delivery.invalid/inbox";
561
- const publicInbox = "https://8.8.8.8/inbox";
562
- const keys = signed ? [{
563
- privateKey: rsaPrivateKey2,
564
- keyId: rsaPublicKey2.id
565
- }] : [];
566
- for (const result of [
567
- "throws",
568
- "empty",
569
- "cname",
570
- "private"
571
- ]) for (const redirected of [false, true]) await t.step(`${result}, redirected: ${redirected}`, async () => {
572
- const originalLookup = dns.lookup;
573
- const resolverError = /* @__PURE__ */ new Error("Resolver unavailable");
574
- const lookups = [];
575
- dns.lookup = ((hostname, options) => {
576
- lookups.push(hostname);
577
- assertEquals(hostname, "delivery.invalid");
578
- assertEquals(options, { all: true });
579
- if (result === "throws") return Promise.reject(resolverError);
580
- return Promise.resolve(result === "empty" ? [] : [{
581
- address: result === "private" ? "127.0.0.1" : "alias.invalid.",
582
- family: 4
583
- }]);
584
+ try {
585
+ esm_default.mockGlobal().catch(202);
586
+ if (redirected) esm_default.route(publicInbox, {
587
+ status: 307,
588
+ headers: { Location: destination }
584
589
  });
585
- try {
586
- esm_default.mockGlobal().catch(202);
587
- if (redirected) esm_default.route(publicInbox, {
588
- status: 307,
589
- headers: { Location: destination }
590
- });
591
- const send = () => sendActivity({
592
- activity,
593
- keys,
594
- inbox: new URL(redirected ? publicInbox : destination)
590
+ const send = () => sendActivity({
591
+ activity,
592
+ keys,
593
+ inbox: new URL(redirected ? publicInbox : destination)
594
+ }, { openHop: (url) => openPublicFetch(url, { lookup }) });
595
+ if (result === "private") assertEquals((await assertRejects(send, UrlError)).reason, "disallowed");
596
+ else {
597
+ const error = await assertRejects(send, FetchError);
598
+ assertEquals(error.url.href, destination);
599
+ assertInstanceOf(error.cause, UrlError);
600
+ assertEquals(error.cause.reason, "dns");
601
+ assertEquals(error.cause.cause, result === "throws" ? resolverError : void 0);
602
+ }
603
+ assertEquals(lookups, ["delivery.invalid"]);
604
+ assertEquals(esm_default.callHistory.calls(destination).length, 0);
605
+ assertEquals(esm_default.callHistory.calls().length, redirected ? 1 : 0);
606
+ } finally {
607
+ esm_default.hardReset();
608
+ }
609
+ });
610
+ });
611
+ const lifecycleActivity = {
612
+ "@context": "https://www.w3.org/ns/activitystreams",
613
+ type: "Create",
614
+ id: "https://example.com/activity",
615
+ actor: "https://example.com/person"
616
+ };
617
+ const signedKeys = [{
618
+ privateKey: rsaPrivateKey2,
619
+ keyId: rsaPublicKey2.id
620
+ }];
621
+ const unsignedKeys = [{
622
+ privateKey: ed25519PrivateKey,
623
+ keyId: ed25519Multikey.id
624
+ }];
625
+ test("sendActivity() bounds slow response headers on both signing paths", async (t) => {
626
+ for (const signed of [false, true]) await t.step(`signed: ${signed}`, async () => {
627
+ let requests = 0;
628
+ let closes = 0;
629
+ const error = await assertRejects(() => sendActivity({
630
+ activity: lifecycleActivity,
631
+ keys: signed ? signedKeys : unsignedKeys,
632
+ inbox: new URL("https://example.com/slow-headers")
633
+ }, {
634
+ timeoutMs: 100,
635
+ openHop: (url) => Promise.resolve({
636
+ url: new URL(url),
637
+ fetch(input, init) {
638
+ requests++;
639
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
640
+ assert(signal != null);
641
+ return new Promise((_, reject) => {
642
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
643
+ });
644
+ },
645
+ close() {
646
+ closes++;
647
+ return Promise.resolve();
648
+ }
649
+ })
650
+ }), FetchError);
651
+ assert(error.message.includes("Timed out after 100 ms"));
652
+ assertInstanceOf(error.cause, DOMException);
653
+ assertEquals(error.cause.name, "TimeoutError");
654
+ assertEquals(requests, 1);
655
+ assertEquals(closes, 1);
656
+ });
657
+ });
658
+ test("sendActivity() closes a session opened after the deadline", async () => {
659
+ let resolveOpen;
660
+ let closes = 0;
661
+ const error = await assertRejects(() => sendActivity({
662
+ activity: lifecycleActivity,
663
+ keys: unsignedKeys,
664
+ inbox: new URL("https://example.com/late-open")
665
+ }, {
666
+ timeoutMs: 20,
667
+ openHop: () => new Promise((resolve) => resolveOpen = resolve)
668
+ }), FetchError);
669
+ assertInstanceOf(error.cause, DOMException);
670
+ assertEquals(error.cause.name, "TimeoutError");
671
+ assert(resolveOpen != null);
672
+ resolveOpen({
673
+ url: new URL("https://example.com/late-open"),
674
+ fetch: () => Promise.reject(/* @__PURE__ */ new Error("A late session must not fetch")),
675
+ close: () => {
676
+ closes++;
677
+ return Promise.resolve();
678
+ }
679
+ });
680
+ await Promise.resolve();
681
+ assertEquals(closes, 1);
682
+ });
683
+ test("sendActivity() keeps its deadline across redirects", async (t) => {
684
+ for (const signed of [false, true]) await t.step(`signed: ${signed}`, async () => {
685
+ const first = "https://example.com/first-inbox";
686
+ const second = "https://example.com/second-inbox";
687
+ const requests = [];
688
+ let closes = 0;
689
+ await assertRejects(() => sendActivity({
690
+ activity: lifecycleActivity,
691
+ keys: signed ? signedKeys : unsignedKeys,
692
+ inbox: new URL(first)
693
+ }, {
694
+ timeoutMs: 100,
695
+ openHop: (url) => Promise.resolve({
696
+ url: new URL(url),
697
+ async fetch(input, init) {
698
+ const request = new Request(input, init);
699
+ requests.push(request);
700
+ if (url === first) {
701
+ await new Promise((resolve) => setTimeout(resolve, 30));
702
+ return new Response(null, {
703
+ status: 307,
704
+ headers: { Location: second }
705
+ });
706
+ }
707
+ return await new Promise((_, reject) => {
708
+ request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true });
709
+ });
710
+ },
711
+ close() {
712
+ closes++;
713
+ return Promise.resolve();
714
+ }
715
+ })
716
+ }), FetchError);
717
+ assertEquals(requests.map((request) => request.url), [first, second]);
718
+ assert(requests.every((request) => request.signal.aborted));
719
+ assertEquals(closes, 2);
720
+ });
721
+ });
722
+ test("sendActivity() keeps its deadline across signature attempts", async () => {
723
+ let requests = 0;
724
+ let closes = 0;
725
+ await assertRejects(() => sendActivity({
726
+ activity: lifecycleActivity,
727
+ keys: signedKeys,
728
+ inbox: new URL("https://example.com/double-knock-timeout")
729
+ }, {
730
+ timeoutMs: 100,
731
+ openHop: (url) => Promise.resolve({
732
+ url: new URL(url),
733
+ fetch(input, init) {
734
+ requests++;
735
+ if (requests === 1) return Promise.resolve(new Response(null, { status: 401 }));
736
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
737
+ assert(signal != null);
738
+ return new Promise((_, reject) => {
739
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
595
740
  });
596
- if (result === "private") assertEquals((await assertRejects(send, UrlError)).reason, "disallowed");
597
- else {
598
- const error = await assertRejects(send, FetchError);
599
- assertEquals(error.url.href, destination);
600
- assertInstanceOf(error.cause, UrlError);
601
- assertEquals(error.cause.reason, "dns");
602
- assertEquals(error.cause.cause, result === "throws" ? resolverError : void 0);
741
+ },
742
+ close() {
743
+ closes++;
744
+ return Promise.resolve();
745
+ }
746
+ })
747
+ }), FetchError);
748
+ assertEquals(requests, 2);
749
+ assertEquals(closes, 1);
750
+ });
751
+ test("sendActivity() preserves an error status when its body stalls", async (t) => {
752
+ for (const signed of [false, true]) for (const status of [410, 500]) await t.step(`signed: ${signed}, status: ${status}`, async () => {
753
+ let requests = 0;
754
+ let closes = 0;
755
+ const error = await assertRejects(() => sendActivity({
756
+ activity: lifecycleActivity,
757
+ keys: signed ? signedKeys : unsignedKeys,
758
+ inbox: new URL("https://example.com/slow-body")
759
+ }, {
760
+ timeoutMs: 100,
761
+ openHop: (url) => Promise.resolve({
762
+ url: new URL(url),
763
+ fetch() {
764
+ requests++;
765
+ return Promise.resolve(new Response(new ReadableStream({ pull: () => new Promise(() => {}) }), { status }));
766
+ },
767
+ close() {
768
+ closes++;
769
+ return Promise.resolve();
603
770
  }
604
- assertEquals(lookups, ["delivery.invalid"]);
605
- assertEquals(esm_default.callHistory.calls(destination).length, 0);
606
- assertEquals(esm_default.callHistory.calls().length, redirected ? 1 : 0);
607
- } finally {
608
- dns.lookup = originalLookup;
609
- esm_default.hardReset();
771
+ })
772
+ }), SendActivityError);
773
+ assertEquals(error.statusCode, status);
774
+ assertEquals(error.responseBody, "(timed out reading response body)");
775
+ assertEquals(requests, signed ? 2 : 1);
776
+ assertEquals(closes, 1);
777
+ });
778
+ });
779
+ test("sendActivity() does not read a body after its deadline", async () => {
780
+ let reads = 0;
781
+ let closes = 0;
782
+ const error = await assertRejects(() => sendActivity({
783
+ activity: lifecycleActivity,
784
+ keys: unsignedKeys,
785
+ inbox: new URL("https://example.com/late-error")
786
+ }, {
787
+ timeoutMs: 10,
788
+ openHop: (url) => Promise.resolve({
789
+ url: new URL(url),
790
+ async fetch() {
791
+ await new Promise((resolve) => setTimeout(resolve, 30));
792
+ return new Response(new ReadableStream({ pull() {
793
+ reads++;
794
+ throw new Error("The expired response must not be read");
795
+ } }, { highWaterMark: 0 }), { status: 500 });
796
+ },
797
+ close() {
798
+ closes++;
799
+ return Promise.resolve();
800
+ }
801
+ })
802
+ }), SendActivityError);
803
+ assertEquals(error.statusCode, 500);
804
+ assertEquals(error.responseBody, "(timed out reading response body)");
805
+ assertEquals(reads, 0);
806
+ assertEquals(closes, 1);
807
+ });
808
+ test("sendActivity() bounds signature spec lookup", async () => {
809
+ let resolveLookup;
810
+ const lookup = new Promise((resolve) => resolveLookup = resolve);
811
+ let lookupReleased = false;
812
+ let lookups = 0;
813
+ let closes = 0;
814
+ const release = setTimeout(() => {
815
+ lookupReleased = true;
816
+ resolveLookup("rfc9421");
817
+ }, 100);
818
+ try {
819
+ const error = await assertRejects(() => sendActivity({
820
+ activity: lifecycleActivity,
821
+ keys: signedKeys,
822
+ inbox: new URL("https://example.com/stalled-spec-lookup"),
823
+ specDeterminer: {
824
+ determineSpec() {
825
+ lookups++;
826
+ return lookup;
827
+ },
828
+ rememberSpec: () => {}
610
829
  }
830
+ }, {
831
+ timeoutMs: 20,
832
+ openHop: (url) => Promise.resolve({
833
+ url: new URL(url),
834
+ fetch: () => Promise.resolve(new Response(null, { status: 202 })),
835
+ close() {
836
+ closes++;
837
+ return Promise.resolve();
838
+ }
839
+ })
840
+ }), FetchError);
841
+ assertInstanceOf(error.cause, DOMException);
842
+ assertEquals(error.cause.name, "TimeoutError");
843
+ assertEquals(lookups, 1);
844
+ assertFalse(lookupReleased);
845
+ assertEquals(closes, 1);
846
+ } finally {
847
+ clearTimeout(release);
848
+ resolveLookup("rfc9421");
849
+ }
850
+ });
851
+ test("sendActivity() does not wait for signature spec storage", async () => {
852
+ let resolveStorage;
853
+ const storage = new Promise((resolve) => resolveStorage = resolve);
854
+ let storageReleased = false;
855
+ let writes = 0;
856
+ let closes = 0;
857
+ const release = setTimeout(() => {
858
+ storageReleased = true;
859
+ resolveStorage();
860
+ }, 100);
861
+ try {
862
+ await sendActivity({
863
+ activity: lifecycleActivity,
864
+ keys: signedKeys,
865
+ inbox: new URL("https://example.com/stalled-spec-storage"),
866
+ specDeterminer: {
867
+ determineSpec: () => "rfc9421",
868
+ rememberSpec() {
869
+ writes++;
870
+ return storage;
871
+ }
872
+ }
873
+ }, {
874
+ timeoutMs: 20,
875
+ openHop: (url) => Promise.resolve({
876
+ url: new URL(url),
877
+ fetch: () => Promise.resolve(new Response(null, { status: 202 })),
878
+ close() {
879
+ closes++;
880
+ return Promise.resolve();
881
+ }
882
+ })
883
+ });
884
+ assertEquals(writes, 1);
885
+ assertFalse(storageReleased);
886
+ assertEquals(closes, 1);
887
+ } finally {
888
+ clearTimeout(release);
889
+ resolveStorage();
890
+ }
891
+ });
892
+ test("sendActivity() keeps an empty error body distinct from a timeout", async () => {
893
+ const error = await assertRejects(() => sendActivity({
894
+ activity: lifecycleActivity,
895
+ keys: unsignedKeys,
896
+ inbox: new URL("https://example.com/empty-error")
897
+ }, { openHop: (url) => Promise.resolve({
898
+ url: new URL(url),
899
+ fetch: () => Promise.resolve(new Response(null, { status: 500 })),
900
+ close: () => Promise.resolve()
901
+ }) }), SendActivityError);
902
+ assertEquals(error.statusCode, 500);
903
+ assertEquals(error.responseBody, "");
904
+ });
905
+ test("sendActivity() cancels a successful response body", async (t) => {
906
+ for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
907
+ const inbox = "https://example.com/lifecycle/inbox";
908
+ const hops = recordHops(() => ({
909
+ status: 202,
910
+ body: "Accepted"
911
+ }));
912
+ await sendActivity({
913
+ activity: lifecycleActivity,
914
+ keys: signed ? signedKeys : unsignedKeys,
915
+ inbox: new URL(inbox)
916
+ }, { openHop: hops.openHop });
917
+ assertEquals(hops.events, [
918
+ `open ${inbox}`,
919
+ `fetch #1 ${inbox}`,
920
+ "cancel #1",
921
+ `close ${inbox}`
922
+ ]);
923
+ hops.assertInvariants();
924
+ });
925
+ });
926
+ test("sendActivity() reads at most 1 KiB of an error response body", async (t) => {
927
+ for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
928
+ const inbox = "https://example.com/lifecycle/error";
929
+ const hops = recordHops(() => ({
930
+ status: 500,
931
+ body: "x".repeat(4096)
932
+ }));
933
+ const error = await assertRejects(() => sendActivity({
934
+ activity: lifecycleActivity,
935
+ activityId: lifecycleActivity.id,
936
+ keys: signed ? signedKeys : unsignedKeys,
937
+ inbox: new URL(inbox)
938
+ }, { openHop: hops.openHop }), SendActivityError);
939
+ assertEquals(error.responseBody, "x".repeat(1024) + "… (truncated)");
940
+ assert(error.message.includes("… (truncated)"));
941
+ assertEquals(hops.events, [
942
+ `open ${inbox}`,
943
+ `fetch #1 ${inbox}`,
944
+ "cancel #1",
945
+ ...signed ? [`fetch #2 ${inbox}`, "cancel #2"] : [],
946
+ `close ${inbox}`
947
+ ]);
948
+ hops.assertInvariants();
949
+ });
950
+ });
951
+ test("sendActivity() closes each redirect hop before opening the next", async (t) => {
952
+ for (const [signed, status] of [[true, 307], [false, 308]]) await t.step(`signed: ${signed}, ${status}`, async () => {
953
+ const inbox = "https://example.com/lifecycle/redirect";
954
+ const next = "https://example.com/lifecycle/redirected";
955
+ const hops = recordHops((request) => request.url === inbox ? {
956
+ status,
957
+ headers: { Location: next },
958
+ body: "Moved"
959
+ } : {
960
+ status: 202,
961
+ body: "Accepted"
611
962
  });
963
+ await sendActivity({
964
+ activity: lifecycleActivity,
965
+ keys: signed ? signedKeys : unsignedKeys,
966
+ inbox: new URL(inbox)
967
+ }, { openHop: hops.openHop });
968
+ assertEquals(hops.events, [
969
+ `open ${inbox}`,
970
+ `fetch #1 ${inbox}`,
971
+ "cancel #1",
972
+ `close ${inbox}`,
973
+ `open ${next}`,
974
+ `fetch #2 ${next}`,
975
+ "cancel #2",
976
+ `close ${next}`
977
+ ]);
978
+ assertEquals(hops.requests[1].method, "POST");
979
+ assertEquals(await hops.requests[1].text(), JSON.stringify(lifecycleActivity));
980
+ hops.assertInvariants();
981
+ });
982
+ });
983
+ async function captureLogs(fn) {
984
+ const records = [];
985
+ await configure({
986
+ sinks: { buffer: (record) => records.push(record) },
987
+ loggers: [{
988
+ category: "fedify",
989
+ sinks: ["buffer"],
990
+ lowestLevel: "debug"
991
+ }, {
992
+ category: ["logtape", "meta"],
993
+ sinks: []
994
+ }],
995
+ reset: true
996
+ });
997
+ try {
998
+ await fn();
999
+ await new Promise((resolve) => setTimeout(resolve, 0));
1000
+ } finally {
1001
+ await reset();
612
1002
  }
1003
+ return records;
1004
+ }
1005
+ function getCancelFailureUrls(records) {
1006
+ return records.filter((r) => r.rawMessage === "Failed to cancel the response body from {url}: {error}").map((r) => r.properties.url);
1007
+ }
1008
+ test("fetchWithValidatedRedirects() logs a redirect body failing to cancel and follows the redirect", async (t) => {
1009
+ const url = "https://example.com/lifecycle/cancel-failure";
1010
+ const next = "https://example.com/lifecycle/cancel-failure-final";
1011
+ const respond = (_, index) => index === 1 ? {
1012
+ status: 302,
1013
+ headers: { Location: next },
1014
+ body: "Found",
1015
+ failCancel: true
1016
+ } : {
1017
+ status: 202,
1018
+ body: "Accepted"
1019
+ };
1020
+ await t.step("fetchWithValidatedRedirects()", async () => {
1021
+ const hops = recordHops(respond);
1022
+ let result;
1023
+ const records = await captureLogs(async () => {
1024
+ result = await fetchWithValidatedRedirects(new Request(url, {
1025
+ method: "POST",
1026
+ body: "activity"
1027
+ }), hops.openHop, (response) => response.text());
1028
+ });
1029
+ assertEquals(result, "Accepted");
1030
+ assertEquals(hops.events, [
1031
+ `open ${url}`,
1032
+ `fetch #1 ${url}`,
1033
+ "cancel #1",
1034
+ `close ${url}`,
1035
+ `open ${next}`,
1036
+ `fetch #2 ${next}`,
1037
+ "consumed #2",
1038
+ `close ${next}`
1039
+ ]);
1040
+ assertEquals(getCancelFailureUrls(records), [url]);
1041
+ hops.assertInvariants();
1042
+ });
1043
+ for (const signed of [true, false]) await t.step(`signed sendActivity(): ${signed}`, async () => {
1044
+ const hops = recordHops(respond);
1045
+ const records = await captureLogs(() => sendActivity({
1046
+ activity: lifecycleActivity,
1047
+ keys: signed ? signedKeys : unsignedKeys,
1048
+ inbox: new URL(url)
1049
+ }, { openHop: hops.openHop }));
1050
+ assertEquals(hops.events, [
1051
+ `open ${url}`,
1052
+ `fetch #1 ${url}`,
1053
+ "cancel #1",
1054
+ `close ${url}`,
1055
+ `open ${next}`,
1056
+ `fetch #2 ${next}`,
1057
+ "cancel #2",
1058
+ `close ${next}`
1059
+ ]);
1060
+ assertEquals(getCancelFailureUrls(records), [url]);
1061
+ hops.assertInvariants();
1062
+ });
1063
+ });
1064
+ test("fetchWithValidatedRedirects() closes the session when consuming fails", async () => {
1065
+ const url = "https://example.com/lifecycle/consume-failure";
1066
+ const hops = recordHops(() => ({
1067
+ status: 200,
1068
+ body: "x".repeat(1024)
1069
+ }));
1070
+ await assertRejects(() => fetchWithValidatedRedirects(new Request(url, {
1071
+ method: "POST",
1072
+ body: "activity"
1073
+ }), hops.openHop, () => Promise.reject(/* @__PURE__ */ new Error("consume failed"))), Error, "consume failed");
1074
+ assertEquals(hops.events, [
1075
+ `open ${url}`,
1076
+ `fetch #1 ${url}`,
1077
+ "cancel #1 by close",
1078
+ `close ${url}`
1079
+ ]);
1080
+ hops.assertInvariants();
1081
+ });
1082
+ test("sendActivity() logs a successful response body failing to cancel", async (t) => {
1083
+ for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1084
+ const inbox = "https://example.com/lifecycle/cancel-failure-inbox";
1085
+ const hops = recordHops(() => ({
1086
+ status: 202,
1087
+ body: "Accepted",
1088
+ failCancel: true
1089
+ }));
1090
+ const records = await captureLogs(() => sendActivity({
1091
+ activity: lifecycleActivity,
1092
+ keys: signed ? signedKeys : unsignedKeys,
1093
+ inbox: new URL(inbox)
1094
+ }, { openHop: hops.openHop }));
1095
+ assertEquals(hops.events, [
1096
+ `open ${inbox}`,
1097
+ `fetch #1 ${inbox}`,
1098
+ "cancel #1",
1099
+ `close ${inbox}`
1100
+ ]);
1101
+ assertEquals(getCancelFailureUrls(records), [inbox]);
1102
+ hops.assertInvariants();
1103
+ });
1104
+ });
1105
+ test("sendActivity() is not blocked by a body cancellation that never settles", async (t) => {
1106
+ for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1107
+ const inbox = "https://example.com/lifecycle/hanging-cancel";
1108
+ const next = "https://example.com/lifecycle/hanging-cancel-final";
1109
+ const hops = recordHops((request) => request.url === inbox ? {
1110
+ status: 302,
1111
+ headers: { Location: next },
1112
+ body: "Found",
1113
+ hangCancel: true
1114
+ } : {
1115
+ status: 202,
1116
+ body: "Accepted",
1117
+ hangCancel: true
1118
+ });
1119
+ await sendActivity({
1120
+ activity: lifecycleActivity,
1121
+ keys: signed ? signedKeys : unsignedKeys,
1122
+ inbox: new URL(inbox)
1123
+ }, { openHop: hops.openHop });
1124
+ assertEquals(hops.events, [
1125
+ `open ${inbox}`,
1126
+ `fetch #1 ${inbox}`,
1127
+ "cancel #1",
1128
+ `close ${inbox}`,
1129
+ `open ${next}`,
1130
+ `fetch #2 ${next}`,
1131
+ "cancel #2",
1132
+ `close ${next}`
1133
+ ]);
1134
+ hops.assertInvariants();
1135
+ });
1136
+ await t.step("truncated error body", async () => {
1137
+ const inbox = "https://example.com/lifecycle/hanging-error";
1138
+ const hops = recordHops(() => ({
1139
+ status: 500,
1140
+ body: "x".repeat(4096),
1141
+ hangCancel: true
1142
+ }));
1143
+ assertEquals((await assertRejects(() => sendActivity({
1144
+ activity: lifecycleActivity,
1145
+ keys: unsignedKeys,
1146
+ inbox: new URL(inbox)
1147
+ }, { openHop: hops.openHop }), SendActivityError)).responseBody, "x".repeat(1024) + "… (truncated)");
1148
+ assertEquals(hops.events, [
1149
+ `open ${inbox}`,
1150
+ `fetch #1 ${inbox}`,
1151
+ "cancel #1",
1152
+ `close ${inbox}`
1153
+ ]);
1154
+ hops.assertInvariants();
1155
+ });
1156
+ });
1157
+ test("sendActivity() completes with responses cloned by fetch-mock", async (t) => {
1158
+ for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1159
+ esm_default.spyGlobal();
1160
+ try {
1161
+ esm_default.post("https://example.com/tee/inbox", () => new Response("Moved", {
1162
+ status: 307,
1163
+ headers: { Location: "https://example.com/tee/final" }
1164
+ }));
1165
+ esm_default.post("https://example.com/tee/final", () => new Response("Accepted", { status: 202 }));
1166
+ esm_default.post("https://example.com/tee/error", () => new Response("x".repeat(4096), { status: 404 }));
1167
+ const keys = signed ? signedKeys : unsignedKeys;
1168
+ await sendDirect({
1169
+ activity: lifecycleActivity,
1170
+ keys,
1171
+ inbox: new URL("https://example.com/tee/inbox")
1172
+ });
1173
+ assertEquals(esm_default.callHistory.calls("https://example.com/tee/final").length, 1);
1174
+ const error = await assertRejects(() => sendDirect({
1175
+ activity: lifecycleActivity,
1176
+ keys,
1177
+ inbox: new URL("https://example.com/tee/error")
1178
+ }), SendActivityError);
1179
+ assertEquals(error.statusCode, 404);
1180
+ assertEquals(error.responseBody, "x".repeat(1024) + "… (truncated)");
1181
+ } finally {
1182
+ esm_default.hardReset();
1183
+ }
1184
+ });
613
1185
  });
1186
+ function createRecordedResponse(events, index, init, cancelSuffix = () => "") {
1187
+ const bytes = new TextEncoder().encode(init.body ?? "");
1188
+ const chunkSize = init.chunkSize ?? 256;
1189
+ let offset = 0;
1190
+ let settled = false;
1191
+ const body = new ReadableStream({
1192
+ pull(controller) {
1193
+ if (offset >= bytes.length) {
1194
+ settled = true;
1195
+ events.push(`consumed #${index}`);
1196
+ controller.close();
1197
+ return;
1198
+ }
1199
+ controller.enqueue(bytes.slice(offset, offset + chunkSize));
1200
+ offset += chunkSize;
1201
+ },
1202
+ cancel() {
1203
+ settled = true;
1204
+ events.push(`cancel #${index}${cancelSuffix()}`);
1205
+ if (init.failCancel) throw new Error(`cancel #${index} failed`);
1206
+ if (init.hangCancel) return new Promise(() => {});
1207
+ }
1208
+ }, { highWaterMark: 0 });
1209
+ return {
1210
+ response: new Response(body, {
1211
+ status: init.status ?? 200,
1212
+ headers: init.headers
1213
+ }),
1214
+ settled: () => settled
1215
+ };
1216
+ }
1217
+ function recordHops(respond) {
1218
+ const events = [];
1219
+ const requests = [];
1220
+ const unsettledAtClose = [];
1221
+ let opens = 0;
1222
+ let closes = 0;
1223
+ let fetches = 0;
1224
+ return {
1225
+ events,
1226
+ requests,
1227
+ openHop(url) {
1228
+ opens++;
1229
+ events.push(`open ${url}`);
1230
+ const tracked = [];
1231
+ let closed = false;
1232
+ let closing = false;
1233
+ return Promise.resolve({
1234
+ url: new URL(url),
1235
+ async fetch(input, init) {
1236
+ if (closed) throw new TypeError("The session is closed.");
1237
+ const request = new Request(input instanceof Request ? input.clone() : input, init);
1238
+ const index = ++fetches;
1239
+ requests.push(request);
1240
+ events.push(`fetch #${index} ${request.url}`);
1241
+ const recorded = createRecordedResponse(events, index, await respond(request, index), () => closing ? " by close" : "");
1242
+ tracked.push({
1243
+ ...recorded,
1244
+ index
1245
+ });
1246
+ return recorded.response;
1247
+ },
1248
+ close() {
1249
+ if (closed) return Promise.resolve();
1250
+ closed = true;
1251
+ closes++;
1252
+ closing = true;
1253
+ for (const { response, settled, index } of tracked) {
1254
+ if (settled()) continue;
1255
+ if (response.body?.locked) unsettledAtClose.push(index);
1256
+ else response.body?.cancel().catch(() => {});
1257
+ }
1258
+ events.push(`close ${url}`);
1259
+ return Promise.resolve();
1260
+ }
1261
+ });
1262
+ },
1263
+ assertInvariants() {
1264
+ assertEquals(opens, closes);
1265
+ assertEquals(unsettledAtClose, []);
1266
+ }
1267
+ };
1268
+ }
614
1269
  //#endregion
615
1270
  export {};