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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/dist/federation/mod.cjs +1 -1
  2. package/dist/federation/mod.js +1 -1
  3. package/dist/{federation-pFFwPyoZ.cjs → federation-JvzYDx0P.cjs} +3 -3
  4. package/dist/{http-CXX-QPzs.cjs → http-BG5cDmTS.cjs} +1 -1
  5. package/dist/{http-T7h9GBAN.js → http-MUf125Jc.js} +1 -1
  6. package/dist/{kv-cache-C6XX_fwz.cjs → kv-cache-A2po7h0_.cjs} +1 -1
  7. package/dist/{kv-cache-EFcb1kkU.js → kv-cache-CbWc1BZA.js} +1 -1
  8. package/dist/{middleware-Bj91r7r2.js → middleware-DzzdJ7Wz.js} +3 -3
  9. package/dist/mod.cjs +4 -4
  10. package/dist/mod.js +4 -4
  11. package/dist/{portable-collection-Do5QA2oy.js → portable-collection-CAer9RWN.js} +1 -1
  12. package/dist/{portable-collection-BOl9oKrt.cjs → portable-collection-d8w7TCn9.cjs} +1 -1
  13. package/dist/sig/mod.cjs +2 -2
  14. package/dist/sig/mod.js +2 -2
  15. package/dist/utils/mod.cjs +1 -1
  16. package/dist/utils/mod.js +1 -1
  17. package/package.json +22 -9
  18. package/skills/fedify/SKILL.md +10 -0
  19. package/dist/accept-CPVqki78.mjs +0 -145
  20. package/dist/activity-listener-CELFAodc.mjs +0 -44
  21. package/dist/assert-D1Eafmd_.mjs +0 -23
  22. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  23. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  24. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  25. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  26. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  27. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  28. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  29. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  30. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  31. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  32. package/dist/audience-CHQ-FlLD.mjs +0 -95
  33. package/dist/builder-D1FP_5nQ.mjs +0 -911
  34. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  35. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  36. package/dist/client-5SIFzW3q.mjs +0 -441
  37. package/dist/codec-C6rTrpIp.mjs +0 -147
  38. package/dist/collection-CnnP1UAv.mjs +0 -44
  39. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  40. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  41. package/dist/compat/public-audience.test.d.mts +0 -2
  42. package/dist/compat/public-audience.test.mjs +0 -187
  43. package/dist/compat/secured-document.test.d.mts +0 -2
  44. package/dist/compat/secured-document.test.mjs +0 -58
  45. package/dist/compat/transformers.test.d.mts +0 -2
  46. package/dist/compat/transformers.test.mjs +0 -62
  47. package/dist/compound-proof-DSHhnOEW.mjs +0 -1019
  48. package/dist/context-LgGFFSz7.mjs +0 -146
  49. package/dist/deno-C50ikGBU.mjs +0 -8
  50. package/dist/dist-_geWsuaI.mjs +0 -189
  51. package/dist/docloader-BY-SEID0.mjs +0 -136
  52. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  53. package/dist/exporter-DVG68ozH.mjs +0 -263
  54. package/dist/federation/audience.test.d.mts +0 -2
  55. package/dist/federation/audience.test.mjs +0 -130
  56. package/dist/federation/builder.test.d.mts +0 -2
  57. package/dist/federation/builder.test.mjs +0 -396
  58. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  59. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  60. package/dist/federation/collection.test.d.mts +0 -2
  61. package/dist/federation/collection.test.mjs +0 -21
  62. package/dist/federation/compound-fanout.test.d.mts +0 -2
  63. package/dist/federation/compound-fanout.test.mjs +0 -231
  64. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  65. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  66. package/dist/federation/handler.test.d.mts +0 -2
  67. package/dist/federation/handler.test.mjs +0 -5445
  68. package/dist/federation/hashlink-media.test.d.mts +0 -2
  69. package/dist/federation/hashlink-media.test.mjs +0 -422
  70. package/dist/federation/idempotency.test.d.mts +0 -2
  71. package/dist/federation/idempotency.test.mjs +0 -207
  72. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  73. package/dist/federation/inbox-actorless.test.mjs +0 -522
  74. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  75. package/dist/federation/inbox-authentication.test.mjs +0 -220
  76. package/dist/federation/inbox-report.test.d.mts +0 -2
  77. package/dist/federation/inbox-report.test.mjs +0 -719
  78. package/dist/federation/inbox-view.test.d.mts +0 -2
  79. package/dist/federation/inbox-view.test.mjs +0 -369
  80. package/dist/federation/inbox.test.d.mts +0 -2
  81. package/dist/federation/inbox.test.mjs +0 -139
  82. package/dist/federation/keycache.test.d.mts +0 -2
  83. package/dist/federation/keycache.test.mjs +0 -337
  84. package/dist/federation/kv.test.d.mts +0 -2
  85. package/dist/federation/kv.test.mjs +0 -88
  86. package/dist/federation/metrics.test.d.mts +0 -2
  87. package/dist/federation/metrics.test.mjs +0 -634
  88. package/dist/federation/middleware.test.d.mts +0 -2
  89. package/dist/federation/middleware.test.mjs +0 -9314
  90. package/dist/federation/mq.test.d.mts +0 -2
  91. package/dist/federation/mq.test.mjs +0 -591
  92. package/dist/federation/negotiation.test.d.mts +0 -2
  93. package/dist/federation/negotiation.test.mjs +0 -18
  94. package/dist/federation/outbound-body.test.d.mts +0 -2
  95. package/dist/federation/outbound-body.test.mjs +0 -149
  96. package/dist/federation/outbound-capture.test.d.mts +0 -2
  97. package/dist/federation/outbound-capture.test.mjs +0 -394
  98. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  99. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  100. package/dist/federation/outbound-document.test.d.mts +0 -2
  101. package/dist/federation/outbound-document.test.mjs +0 -171
  102. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  103. package/dist/federation/outbound-provenance.test.mjs +0 -543
  104. package/dist/federation/outbound-report.test.d.mts +0 -2
  105. package/dist/federation/outbound-report.test.mjs +0 -5475
  106. package/dist/federation/outbound-workers.test.d.mts +0 -2
  107. package/dist/federation/outbound-workers.test.mjs +0 -64
  108. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  109. package/dist/federation/outbound-workflow.test.mjs +0 -154
  110. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  111. package/dist/federation/outgoing-proof.test.mjs +0 -933
  112. package/dist/federation/portable-actor.test.d.mts +0 -2
  113. package/dist/federation/portable-actor.test.mjs +0 -496
  114. package/dist/federation/portable-chain.test.d.mts +0 -2
  115. package/dist/federation/portable-chain.test.mjs +0 -370
  116. package/dist/federation/portable-collection.test.d.mts +0 -2
  117. package/dist/federation/portable-collection.test.mjs +0 -832
  118. package/dist/federation/portable-delivery.test.d.mts +0 -2
  119. package/dist/federation/portable-delivery.test.mjs +0 -845
  120. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  121. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  122. package/dist/federation/portable-inbox.test.d.mts +0 -2
  123. package/dist/federation/portable-inbox.test.mjs +0 -1960
  124. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  125. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  126. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  127. package/dist/federation/portable-route-activity.test.mjs +0 -259
  128. package/dist/federation/portable.test.d.mts +0 -2
  129. package/dist/federation/portable.test.mjs +0 -1072
  130. package/dist/federation/retry.test.d.mts +0 -2
  131. package/dist/federation/retry.test.mjs +0 -42
  132. package/dist/federation/router.test.d.mts +0 -2
  133. package/dist/federation/router.test.mjs +0 -123
  134. package/dist/federation/send.test.d.mts +0 -2
  135. package/dist/federation/send.test.mjs +0 -1421
  136. package/dist/federation/tasks/codec.test.d.mts +0 -2
  137. package/dist/federation/tasks/codec.test.mjs +0 -302
  138. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  139. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  140. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  141. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  142. package/dist/federation/temporal.test.d.mts +0 -2
  143. package/dist/federation/temporal.test.mjs +0 -71
  144. package/dist/federation/webfinger.test.d.mts +0 -2
  145. package/dist/federation/webfinger.test.mjs +0 -944
  146. package/dist/http-BXbQQZDM.mjs +0 -1449
  147. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  148. package/dist/inbox-cS97XzOD.mjs +0 -399
  149. package/dist/inbox-view-D-d0Ar6o.mjs +0 -385
  150. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  151. package/dist/keycache-N2opu4-3.mjs +0 -221
  152. package/dist/keys-DIJNHW-Y.mjs +0 -120
  153. package/dist/kv-DBRWVx3Q.mjs +0 -104
  154. package/dist/kv-DCHkaJ9-.mjs +0 -92
  155. package/dist/kv-cache-fgbLHGVL.mjs +0 -121
  156. package/dist/ld-BpkhkDGj.mjs +0 -1752
  157. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  158. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  159. package/dist/metrics-Uqf8GomB.mjs +0 -818
  160. package/dist/middleware-DcXzz-YK.mjs +0 -9971
  161. package/dist/middleware-DgwZkvJR.mjs +0 -5
  162. package/dist/mq-eF96QxUT.mjs +0 -288
  163. package/dist/negotiation-BAKO9nih.mjs +0 -96
  164. package/dist/nodeinfo/client.test.d.mts +0 -2
  165. package/dist/nodeinfo/client.test.mjs +0 -1364
  166. package/dist/nodeinfo/handler.test.d.mts +0 -2
  167. package/dist/nodeinfo/handler.test.mjs +0 -94
  168. package/dist/nodeinfo/types.test.d.mts +0 -2
  169. package/dist/nodeinfo/types.test.mjs +0 -192
  170. package/dist/otel/exporter.test.d.mts +0 -2
  171. package/dist/otel/exporter.test.mjs +0 -887
  172. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  173. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  174. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  175. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  176. package/dist/owner-BVenIFg1.mjs +0 -267
  177. package/dist/portable-collection-DIk9gpjL.mjs +0 -418
  178. package/dist/portable-key-C7pVaHNR.mjs +0 -549
  179. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  180. package/dist/proof-BlfZ95--.mjs +0 -1420
  181. package/dist/public-audience--klBIOk1.mjs +0 -197
  182. package/dist/retry-zX5xw5e0.mjs +0 -34
  183. package/dist/router-u5O5KCQr.mjs +0 -156
  184. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  185. package/dist/send-DEGHPGFk.mjs +0 -710
  186. package/dist/sig/accept.test.d.mts +0 -2
  187. package/dist/sig/accept.test.mjs +0 -416
  188. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  189. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  190. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  191. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  192. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  193. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  194. package/dist/sig/compound-proof.test.d.mts +0 -2
  195. package/dist/sig/compound-proof.test.mjs +0 -411
  196. package/dist/sig/http.test.d.mts +0 -2
  197. package/dist/sig/http.test.mjs +0 -3328
  198. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  199. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  200. package/dist/sig/key.test.d.mts +0 -2
  201. package/dist/sig/key.test.mjs +0 -1250
  202. package/dist/sig/ld.test.d.mts +0 -2
  203. package/dist/sig/ld.test.mjs +0 -1044
  204. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  205. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  206. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  207. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  208. package/dist/sig/owner.test.d.mts +0 -2
  209. package/dist/sig/owner.test.mjs +0 -202
  210. package/dist/sig/portable-collection.test.d.mts +0 -2
  211. package/dist/sig/portable-collection.test.mjs +0 -697
  212. package/dist/sig/portable-interop.test.d.mts +0 -2
  213. package/dist/sig/portable-interop.test.mjs +0 -156
  214. package/dist/sig/portable-key-id.test.d.mts +0 -2
  215. package/dist/sig/portable-key-id.test.mjs +0 -67
  216. package/dist/sig/portable-key.test.d.mts +0 -2
  217. package/dist/sig/portable-key.test.mjs +0 -1438
  218. package/dist/sig/proof.test.d.mts +0 -2
  219. package/dist/sig/proof.test.mjs +0 -2638
  220. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  221. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  222. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  223. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  224. package/dist/sig/verification.test.d.mts +0 -2
  225. package/dist/sig/verification.test.mjs +0 -310
  226. package/dist/std__assert-DvMDRPes.mjs +0 -8
  227. package/dist/tasks-BCUmQbbz.mjs +0 -77
  228. package/dist/temporal-B4oQ8HpW.mjs +0 -95
  229. package/dist/testing/context.test.d.mts +0 -2
  230. package/dist/testing/context.test.mjs +0 -19
  231. package/dist/testing/kv.test.d.mts +0 -2
  232. package/dist/testing/kv.test.mjs +0 -101
  233. package/dist/testing/mod.d.mts +0 -6099
  234. package/dist/testing/mod.mjs +0 -9
  235. package/dist/testing-vrnD5Uaa.mjs +0 -8
  236. package/dist/types-DE_LV1JB.mjs +0 -46
  237. package/dist/utils/docloader.test.d.mts +0 -2
  238. package/dist/utils/docloader.test.mjs +0 -1076
  239. package/dist/utils/kv-cache.test.d.mts +0 -2
  240. package/dist/utils/kv-cache.test.mjs +0 -261
  241. package/dist/verification-C3954hQh.mjs +0 -5
  242. package/dist/verification-Dpfcw8ml.mjs +0 -105
  243. package/dist/vocab/cjs.test.d.mts +0 -2
  244. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,1076 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { t as esm_default } from "../esm-BHXXx4Wx.mjs";
5
- import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
6
- import "../std__assert-DvMDRPes.mjs";
7
- import { t as assertRejects } from "../assert_rejects-CTptdYck.mjs";
8
- import { p as verifyRequest } from "../http-BXbQQZDM.mjs";
9
- import { i as rsaPrivateKey2 } from "../keys-DIJNHW-Y.mjs";
10
- import { n as getAuthenticatedDocumentLoader, t as createAuthenticatedDocumentLoader } from "../docloader-BY-SEID0.mjs";
11
- import { configure, reset } from "@logtape/logtape";
12
- import { FetchError, UrlError } from "@fedify/vocab-runtime";
13
- import { mockDocumentLoader, test } from "@fedify/fixture";
14
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
15
- import { deepStrictEqual, ok, rejects } from "node:assert/strict";
16
- //#region src/utils/docloader.test.ts
17
- const identity = {
18
- keyId: new URL("https://example.com/key2"),
19
- privateKey: rsaPrivateKey2
20
- };
21
- const directDeps = { openHop: openDirectFetch };
22
- function publicPolicyHop(lookup) {
23
- return async (url) => {
24
- await (await openPublicFetch(url, { lookup })).close();
25
- return openDirectFetch(url);
26
- };
27
- }
28
- const publicLookup = () => Promise.resolve([{
29
- address: "8.8.8.8",
30
- family: 4
31
- }]);
32
- test("getAuthenticatedDocumentLoader()", async (t) => {
33
- esm_default.spyGlobal();
34
- esm_default.get("begin:https://example.com/object", async (cl) => {
35
- const v = await verifyRequest(cl.request, {
36
- documentLoader: mockDocumentLoader,
37
- contextLoader: mockDocumentLoader,
38
- currentTime: Temporal.Now.instant()
39
- });
40
- return new Response(JSON.stringify(v != null), { headers: { "Content-Type": "application/json" } });
41
- });
42
- await t.step("test", async () => {
43
- assertEquals(await createAuthenticatedDocumentLoader(identity, {}, directDeps)("https://example.com/object"), {
44
- contextUrl: null,
45
- documentUrl: "https://example.com/object",
46
- document: true
47
- });
48
- });
49
- esm_default.hardReset();
50
- await t.step("deny non-HTTP/HTTPS", async () => {
51
- const loader = await getAuthenticatedDocumentLoader({
52
- keyId: new URL("https://example.com/key2"),
53
- privateKey: rsaPrivateKey2
54
- });
55
- assertRejects(() => loader("ftp://localhost"), UrlError);
56
- });
57
- await t.step("deny private network", async () => {
58
- const loader = await getAuthenticatedDocumentLoader({
59
- keyId: new URL("https://example.com/key2"),
60
- privateKey: rsaPrivateKey2
61
- });
62
- assertRejects(() => loader("http://localhost"), UrlError);
63
- });
64
- await t.step("custom max redirection", async () => {
65
- esm_default.spyGlobal();
66
- let requestCount = 0;
67
- esm_default.get("begin:https://example.com/custom-too-many-redirects/", (cl) => {
68
- requestCount++;
69
- const index = Number(cl.url.split("/").at(-1));
70
- return Response.redirect(`https://example.com/custom-too-many-redirects/${index + 1}`, 302);
71
- });
72
- const loader = createAuthenticatedDocumentLoader({
73
- keyId: new URL("https://example.com/key2"),
74
- privateKey: rsaPrivateKey2
75
- }, { maxRedirection: 1 }, directDeps);
76
- await assertRejects(() => loader("https://example.com/custom-too-many-redirects/0"), Error, "Too many redirections");
77
- assertEquals(requestCount, 2);
78
- esm_default.hardReset();
79
- });
80
- });
81
- test("getAuthenticatedDocumentLoader() validates redirects", async (t) => {
82
- esm_default.spyGlobal();
83
- let privateRequestCount = 0;
84
- esm_default.get("https://example.com/redirect-to-private", () => Response.redirect("http://localhost/private", 302));
85
- esm_default.get("http://localhost/private", () => {
86
- privateRequestCount++;
87
- return Response.json({ private: true });
88
- });
89
- const policyDeps = { openHop: publicPolicyHop(publicLookup) };
90
- await t.step("deny public-to-private redirects", async () => {
91
- const loader = createAuthenticatedDocumentLoader(identity, {}, policyDeps);
92
- await assertRejects(() => loader("https://example.com/redirect-to-private"), UrlError);
93
- assertEquals(privateRequestCount, 0);
94
- });
95
- esm_default.get("https://example.com/redirect-to-public", () => Response.redirect("https://www.example.com/document", 302));
96
- esm_default.get("https://www.example.com/document", () => Response.json({ public: true }));
97
- await t.step("allow public-to-public redirects", async () => {
98
- assertEquals((await createAuthenticatedDocumentLoader(identity, {}, policyDeps)("https://example.com/redirect-to-public")).document, { public: true });
99
- });
100
- await t.step("allow private redirects when explicitly enabled", async () => {
101
- assertEquals((await getAuthenticatedDocumentLoader({
102
- keyId: new URL("https://example.com/key2"),
103
- privateKey: rsaPrivateKey2
104
- }, { allowPrivateAddress: true })("https://example.com/redirect-to-private")).document, { private: true });
105
- assertEquals(privateRequestCount, 1);
106
- });
107
- esm_default.hardReset();
108
- });
109
- test("getAuthenticatedDocumentLoader() cancellation", async (t) => {
110
- esm_default.spyGlobal();
111
- try {
112
- await t.step("document loader cancellation", async () => {
113
- let responseTimer;
114
- try {
115
- esm_default.get("https://example.com/slow-object", () => new Promise((resolve) => {
116
- responseTimer = setTimeout(() => {
117
- resolve({
118
- status: 200,
119
- headers: { "Content-Type": "application/activity+json" },
120
- body: {
121
- "@context": "https://www.w3.org/ns/activitystreams",
122
- type: "Note",
123
- content: "Slow response"
124
- }
125
- });
126
- }, 1e3);
127
- }));
128
- const loader = createAuthenticatedDocumentLoader(identity, {}, directDeps);
129
- const controller = new AbortController();
130
- const promise = loader("https://example.com/slow-object", { signal: controller.signal });
131
- controller.abort();
132
- await assertRejects(() => promise, Error);
133
- await assertRejects(() => loader("https://example.com/object", { signal: controller.signal }), Error);
134
- } finally {
135
- clearTimeout(responseTimer);
136
- }
137
- });
138
- await t.step("immediate cancellation", async () => {
139
- const loader = createAuthenticatedDocumentLoader(identity, {}, directDeps);
140
- const controller = new AbortController();
141
- controller.abort();
142
- await assertRejects(() => loader("https://example.com/object", { signal: controller.signal }), Error);
143
- });
144
- } finally {
145
- esm_default.hardReset();
146
- }
147
- });
148
- test("getAuthenticatedDocumentLoader() bounds JSON after redirects", async () => {
149
- esm_default.mockGlobal();
150
- let oversized = true;
151
- try {
152
- const url = "https://example.com/bounded";
153
- esm_default.get(url, {
154
- status: 302,
155
- headers: { Location: `${url}/document` }
156
- });
157
- esm_default.get(`${url}/document`, () => new Response("{\"name\":\"hello\"}", { headers: {
158
- "Content-Type": "application/activity+json",
159
- ...oversized ? { "Content-Length": String(16777217) } : {}
160
- } }));
161
- const loader = getAuthenticatedDocumentLoader({
162
- privateKey: rsaPrivateKey2,
163
- keyId: new URL("https://example.com/key2")
164
- }, { allowPrivateAddress: true });
165
- await assertRejects(() => loader(url), FetchError);
166
- oversized = false;
167
- assertEquals((await loader(url)).document, { name: "hello" });
168
- } finally {
169
- esm_default.hardReset();
170
- }
171
- });
172
- test("authenticated document loader suppresses HTTP failure logs", async () => {
173
- const records = [];
174
- const url = "https://example.com/missing-authenticated-document";
175
- const loader = getAuthenticatedDocumentLoader({
176
- keyId: new URL("https://example.com/key2"),
177
- privateKey: rsaPrivateKey2
178
- }, { allowPrivateAddress: true });
179
- await reset();
180
- await configure({
181
- sinks: { capture: (record) => records.push(record) },
182
- loggers: [{
183
- category: ["fedify"],
184
- lowestLevel: "debug",
185
- sinks: ["capture"]
186
- }]
187
- });
188
- esm_default.mockGlobal();
189
- esm_default.get(url, { status: 404 });
190
- try {
191
- for (const suppressError of [
192
- true,
193
- false,
194
- void 0
195
- ]) {
196
- records.length = 0;
197
- assertEquals((await assertRejects(() => loader(url, { suppressError }), FetchError)).response?.status, 404);
198
- const failures = records.filter((record) => record.rawMessage === "Failed to fetch document: {status} {url} {headers}");
199
- assertEquals(failures.length, 1);
200
- assertEquals(failures[0].level, suppressError ? "warning" : "error");
201
- if (suppressError) assertEquals(records.filter((record) => record.level === "error"), []);
202
- }
203
- } finally {
204
- esm_default.hardReset();
205
- await reset();
206
- }
207
- });
208
- test("authenticated document loader suppresses private URL logs", async () => {
209
- const records = [];
210
- const loader = createAuthenticatedDocumentLoader({
211
- keyId: new URL("https://example.com/key2"),
212
- privateKey: rsaPrivateKey2
213
- }, {}, { openHop: publicPolicyHop(publicLookup) });
214
- await reset();
215
- await configure({
216
- sinks: { capture: (record) => {
217
- records.push(record);
218
- } },
219
- loggers: [{
220
- category: ["fedify"],
221
- lowestLevel: "debug",
222
- sinks: ["capture"]
223
- }]
224
- });
225
- esm_default.spyGlobal();
226
- let requests = 0;
227
- esm_default.get("https://example.com/private-redirect", () => {
228
- requests++;
229
- return Response.redirect("http://127.0.0.1/private", 302);
230
- });
231
- try {
232
- for (const url of ["http://127.0.0.1/private", "https://example.com/private-redirect"]) for (const suppressError of [
233
- true,
234
- false,
235
- void 0
236
- ]) {
237
- records.length = 0;
238
- requests = 0;
239
- await assertRejects(() => loader(url, { suppressError }), UrlError);
240
- const failures = records.filter((r) => r.rawMessage === "Disallowed private URL: {url}");
241
- assertEquals(failures.length, 1);
242
- assertEquals(failures[0].level, suppressError ? "warning" : "error");
243
- assertEquals(requests, url.startsWith("http://127") ? 0 : 1);
244
- }
245
- } finally {
246
- esm_default.hardReset();
247
- await reset();
248
- }
249
- });
250
- test("getAuthenticatedDocumentLoader() logs DNS failures as such", async (t) => {
251
- for (const result of [
252
- "throws",
253
- "empty",
254
- "private"
255
- ]) await t.step(result, async () => {
256
- const lookup = () => result === "throws" ? Promise.reject(/* @__PURE__ */ new Error("Resolver unavailable")) : Promise.resolve(result === "empty" ? [] : [{
257
- address: "127.0.0.1",
258
- family: 4
259
- }]);
260
- const loader = createAuthenticatedDocumentLoader(identity, {}, { openHop: (url) => openPublicFetch(url, { lookup }) });
261
- const records = [];
262
- await configure({
263
- sinks: { buffer: (record) => records.push(record) },
264
- loggers: [{
265
- category: "fedify",
266
- sinks: ["buffer"],
267
- lowestLevel: "debug"
268
- }, {
269
- category: ["logtape", "meta"],
270
- sinks: []
271
- }],
272
- reset: true
273
- });
274
- try {
275
- const url = "https://dns-failure.invalid/object";
276
- const error = await assertRejects(() => loader(url), UrlError);
277
- assertEquals(error.reason, result === "private" ? "disallowed" : "dns");
278
- assertEquals(records.map((r) => [
279
- r.level,
280
- r.rawMessage,
281
- r.properties.url
282
- ]), [result === "private" ? [
283
- "error",
284
- "Disallowed private URL: {url}",
285
- url
286
- ] : [
287
- "debug",
288
- "DNS lookup failed for {url}",
289
- url
290
- ]]);
291
- assertEquals(records[0].properties.error, error);
292
- } finally {
293
- await reset();
294
- }
295
- });
296
- });
297
- test("getAuthenticatedDocumentLoader() bounds alternate document chains", async (t) => {
298
- const base = "https://example.com/alternate-chain/";
299
- const loader = getAuthenticatedDocumentLoader({
300
- keyId: new URL("https://example.com/key2"),
301
- privateKey: rsaPrivateKey2
302
- }, { allowPrivateAddress: true });
303
- for (const mode of [
304
- "header",
305
- "html",
306
- "mixed"
307
- ]) for (const hops of [20, 21]) await t.step(`${mode}: ${hops} hops`, async () => {
308
- esm_default.mockGlobal();
309
- let requests = 0;
310
- esm_default.get(`begin:${base}`, ({ url }) => {
311
- requests++;
312
- const index = Number(new URL(url).pathname.split("/").at(-1));
313
- if (index === hops || requests > 30) return Response.json({ done: true });
314
- const next = `${base}${index + 1}`;
315
- if (mode === "mixed" && index % 2 === 1) return Response.redirect(next, 302);
316
- return alternate(next, mode === "html");
317
- });
318
- try {
319
- if (hops === 20) deepStrictEqual((await loader(`${base}0`)).document, { done: true });
320
- else await rejects(loader(`${base}0`), (error) => {
321
- ok(error instanceof FetchError);
322
- ok(error.message.includes("Too many redirections (21)"));
323
- return true;
324
- });
325
- deepStrictEqual(requests, 21);
326
- } finally {
327
- esm_default.hardReset();
328
- }
329
- });
330
- for (const mode of [
331
- "header",
332
- "html",
333
- "alternate-redirect",
334
- "redirect-alternate",
335
- "redirect-intermediate"
336
- ]) await t.step(`${mode}: cycle`, async () => {
337
- esm_default.mockGlobal();
338
- let requests = 0;
339
- esm_default.get(`begin:${base}`, ({ url }) => {
340
- requests++;
341
- if (requests > 30) return Response.json({ stopped: true });
342
- const index = Number(new URL(url).pathname.split("/").at(-1));
343
- const next = `${base}${mode === "redirect-intermediate" ? index === 0 ? 1 : index === 1 ? 2 : 1 : 1 - index}`;
344
- if (mode === "alternate-redirect" && index === 1 || (mode === "redirect-alternate" || mode === "redirect-intermediate") && index === 0) return Response.redirect(next, 302);
345
- return alternate(next, mode === "html");
346
- });
347
- try {
348
- await rejects(loader(`${base}0`), (error) => {
349
- ok(error instanceof FetchError);
350
- ok(error.message.includes("Redirect loop detected:"));
351
- return true;
352
- });
353
- deepStrictEqual(requests, mode === "redirect-intermediate" ? 3 : 2);
354
- } finally {
355
- esm_default.hardReset();
356
- }
357
- });
358
- await t.step("alternate followed by 20 redirects shares the limit", async () => {
359
- esm_default.mockGlobal();
360
- let requests = 0;
361
- esm_default.get(`begin:${base}`, ({ url }) => {
362
- requests++;
363
- const index = Number(new URL(url).pathname.split("/").at(-1));
364
- if (index === 21) return Response.json({ done: true });
365
- return index === 0 ? alternate(`${base}1`, false) : Response.redirect(`${base}${index + 1}`, 302);
366
- });
367
- try {
368
- await rejects(loader(`${base}0`), (error) => {
369
- ok(error instanceof FetchError);
370
- ok(error.message.includes("Too many redirections (21)"));
371
- return true;
372
- });
373
- deepStrictEqual(requests, 21);
374
- } finally {
375
- esm_default.hardReset();
376
- }
377
- });
378
- await t.step("relative alternate after redirect and isolated calls", async () => {
379
- esm_default.mockGlobal();
380
- esm_default.get(`${base}start`, Response.redirect(`${base}html`, 302));
381
- esm_default.get(`${base}html`, alternate("./document", true));
382
- esm_default.get(`${base}document`, Response.json({ done: true }));
383
- try {
384
- for (let i = 0; i < 2; i++) {
385
- const results = await Promise.all([loader(`${base}start`), loader(`${base}start`)]);
386
- for (const result of results) {
387
- deepStrictEqual(result.document, { done: true });
388
- deepStrictEqual(result.documentUrl, `${base}document`);
389
- }
390
- }
391
- } finally {
392
- esm_default.hardReset();
393
- }
394
- });
395
- function alternate(next, html) {
396
- return html ? new Response(`<link rel="alternate" type="application/activity+json" href="${next}">`, { headers: { "Content-Type": "text/html" } }) : new Response("not JSON", { headers: {
397
- "Content-Type": "text/plain",
398
- Link: `<${next}>; rel="alternate"; type="application/activity+json"`
399
- } });
400
- }
401
- });
402
- test("getAuthenticatedDocumentLoader() preserves cancellation across alternates", async (t) => {
403
- const base = "https://example.com/alternate-abort/";
404
- const loader = getAuthenticatedDocumentLoader({
405
- keyId: new URL("https://example.com/key2"),
406
- privateKey: rsaPrivateKey2
407
- }, { allowPrivateAddress: true });
408
- for (const html of [false, true]) await t.step(html ? "HTML" : "Link header", async () => {
409
- esm_default.mockGlobal();
410
- const controller = new AbortController();
411
- const reason = /* @__PURE__ */ new Error("Alternate document loading cancelled");
412
- let requests = 0;
413
- esm_default.get(`begin:${base}`, ({ url }) => {
414
- requests++;
415
- const index = Number(new URL(url).pathname.split("/").at(-1));
416
- if (index === 2) return Response.json({ done: true });
417
- if (index === 1) controller.abort(reason);
418
- const next = `${base}${index + 1}`;
419
- return new Response(html ? `<link rel="alternate" type="application/activity+json" href="${next}">` : "not JSON", { headers: html ? { "Content-Type": "text/html" } : {
420
- "Content-Type": "text/plain",
421
- Link: `<${next}>; rel="alternate"; type="application/activity+json"`
422
- } });
423
- });
424
- try {
425
- await rejects(loader(`${base}0`, { signal: controller.signal }), (error) => {
426
- ok(error === reason);
427
- return true;
428
- });
429
- deepStrictEqual(requests, 2);
430
- } finally {
431
- esm_default.hardReset();
432
- }
433
- });
434
- });
435
- test("getAuthenticatedDocumentLoader() tracks fallback redirects after alternates", async () => {
436
- esm_default.mockGlobal();
437
- let requests = 0;
438
- let knocks = 0;
439
- const first = "https://example.com/fallback-alternate/a";
440
- const second = "https://example.com/fallback-alternate/b";
441
- esm_default.get(first, () => {
442
- requests++;
443
- if (requests > 30) return Response.json({ stopped: true });
444
- return new Response("", { headers: {
445
- "Content-Type": "text/plain",
446
- Link: `<${second}>; rel="alternate"; type="application/activity+json"`
447
- } });
448
- });
449
- esm_default.get(second, () => {
450
- requests++;
451
- return ++knocks % 2 === 1 ? new Response("", { status: 401 }) : Response.redirect(first, 302);
452
- });
453
- try {
454
- const loader = getAuthenticatedDocumentLoader({
455
- keyId: new URL("https://example.com/key2"),
456
- privateKey: rsaPrivateKey2
457
- }, { allowPrivateAddress: true });
458
- await assertRejects(() => loader(first), FetchError, "Redirect loop detected:");
459
- assertEquals(requests, 3);
460
- } finally {
461
- esm_default.hardReset();
462
- }
463
- });
464
- test("getAuthenticatedDocumentLoader() resolves relative alternates without response URLs", async () => {
465
- const originalFetch = globalThis.fetch;
466
- const base = "https://example.com/empty-response-url/";
467
- const urls = [];
468
- globalThis.fetch = (input) => {
469
- const url = input instanceof Request ? input.url : String(input);
470
- urls.push(url);
471
- if (url === `${base}start`) return Promise.resolve(Response.redirect(`${base}nested/page`, 302));
472
- if (url === `${base}nested/page`) return Promise.resolve(new Response("<link rel=\"alternate\" type=\"application/activity+json\" href=\"document\">", { headers: { "Content-Type": "text/html" } }));
473
- assertEquals(url, `${base}nested/document`);
474
- return Promise.resolve(Response.json({ done: true }));
475
- };
476
- try {
477
- assertEquals(await getAuthenticatedDocumentLoader({
478
- keyId: new URL("https://example.com/key2"),
479
- privateKey: rsaPrivateKey2
480
- }, { allowPrivateAddress: true })(`${base}start`), {
481
- contextUrl: null,
482
- document: { done: true },
483
- documentUrl: `${base}nested/document`
484
- });
485
- assertEquals(urls, [
486
- `${base}start`,
487
- `${base}nested/page`,
488
- `${base}nested/document`
489
- ]);
490
- } finally {
491
- globalThis.fetch = originalFetch;
492
- }
493
- });
494
- test("getAuthenticatedDocumentLoader() validates alternate addresses", async () => {
495
- esm_default.mockGlobal();
496
- let privateRequests = 0;
497
- const url = "https://8.8.8.8/alternate";
498
- esm_default.get(url, new Response("", { headers: {
499
- "Content-Type": "text/plain",
500
- Link: "<http://127.0.0.1/private>; rel=\"alternate\"; type=\"application/activity+json\""
501
- } }));
502
- esm_default.get("http://127.0.0.1/private", () => {
503
- privateRequests++;
504
- return Response.json({ private: true });
505
- });
506
- try {
507
- const loader = getAuthenticatedDocumentLoader({
508
- keyId: new URL("https://example.com/key2"),
509
- privateKey: rsaPrivateKey2
510
- });
511
- await assertRejects(() => loader(url), UrlError);
512
- assertEquals(privateRequests, 0);
513
- } finally {
514
- esm_default.hardReset();
515
- }
516
- });
517
- test("getAuthenticatedDocumentLoader() rejects cancellation before fetching", async () => {
518
- esm_default.mockGlobal();
519
- let requests = 0;
520
- const url = "https://example.com/pre-aborted-alternate";
521
- esm_default.get(url, () => {
522
- requests++;
523
- return Response.json({ done: true });
524
- });
525
- try {
526
- const loader = getAuthenticatedDocumentLoader({
527
- keyId: new URL("https://example.com/key2"),
528
- privateKey: rsaPrivateKey2
529
- }, { allowPrivateAddress: true });
530
- const controller = new AbortController();
531
- controller.abort();
532
- await rejects(loader(url, { signal: controller.signal }), { name: "AbortError" });
533
- deepStrictEqual(requests, 0);
534
- } finally {
535
- esm_default.hardReset();
536
- }
537
- });
538
- function assertTimeoutFetchError(error, url) {
539
- ok(error instanceof FetchError, String(error));
540
- deepStrictEqual(error.url.href, url);
541
- deepStrictEqual(error.response, void 0);
542
- ok(error.cause instanceof DOMException);
543
- deepStrictEqual(error.cause.name, "TimeoutError");
544
- return true;
545
- }
546
- test("getAuthenticatedDocumentLoader() times out", async (t) => {
547
- const identity = {
548
- keyId: new URL("https://example.com/key2"),
549
- privateKey: rsaPrivateKey2
550
- };
551
- const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
552
- await t.step("a request without a response", async () => {
553
- esm_default.mockGlobal();
554
- const url = "https://example.com/hang";
555
- esm_default.get(url, () => new Promise(() => {}));
556
- try {
557
- await rejects(getAuthenticatedDocumentLoader(identity, {
558
- allowPrivateAddress: true,
559
- timeout: 100
560
- })(url), (e) => assertTimeoutFetchError(e, url));
561
- } finally {
562
- esm_default.hardReset();
563
- }
564
- });
565
- await t.step("double-knocking shares the timeout", async () => {
566
- esm_default.mockGlobal();
567
- const url = "https://example.com/double-knock";
568
- let requests = 0;
569
- esm_default.get(url, async () => {
570
- requests++;
571
- await delay(200);
572
- return new Response(null, { status: 401 });
573
- });
574
- try {
575
- await rejects(getAuthenticatedDocumentLoader(identity, {
576
- allowPrivateAddress: true,
577
- timeout: 300
578
- })(url), (e) => assertTimeoutFetchError(e, url));
579
- deepStrictEqual(requests, 2);
580
- await delay(250);
581
- deepStrictEqual(requests, 2);
582
- } finally {
583
- esm_default.hardReset();
584
- }
585
- });
586
- for (const step of ["determineSpec", "rememberSpec"]) await t.step(`a slow ${step}()`, async () => {
587
- esm_default.mockGlobal();
588
- const url = `https://example.com/slow-${step}`;
589
- let requests = 0;
590
- esm_default.get(url, () => {
591
- requests++;
592
- return Response.json({ parsed: true });
593
- });
594
- try {
595
- await rejects(getAuthenticatedDocumentLoader(identity, {
596
- allowPrivateAddress: true,
597
- timeout: 50,
598
- specDeterminer: {
599
- async determineSpec() {
600
- if (step === "determineSpec") await delay(150);
601
- return "rfc9421";
602
- },
603
- async rememberSpec() {
604
- if (step === "rememberSpec") await delay(150);
605
- }
606
- }
607
- })(url), (e) => assertTimeoutFetchError(e, url));
608
- await delay(200);
609
- deepStrictEqual(requests, step === "determineSpec" ? 0 : 1);
610
- } finally {
611
- esm_default.hardReset();
612
- }
613
- });
614
- await t.step("the caller's signal still aborts", async () => {
615
- esm_default.mockGlobal();
616
- const url = "https://example.com/hang";
617
- esm_default.get(url, () => new Promise(() => {}));
618
- try {
619
- const loader = getAuthenticatedDocumentLoader(identity, { allowPrivateAddress: true });
620
- const controller = new AbortController();
621
- const reason = /* @__PURE__ */ new Error("Canceled by the caller");
622
- setTimeout(() => controller.abort(reason), 50);
623
- await rejects(loader(url, { signal: controller.signal }), (e) => e === reason);
624
- } finally {
625
- esm_default.hardReset();
626
- }
627
- });
628
- });
629
- test("getAuthenticatedDocumentLoader() closes each hop before opening the next", async (t) => {
630
- await t.step("redirect", async () => {
631
- const start = "https://example.com/lifecycle/start";
632
- const next = "https://example.com/lifecycle/document";
633
- const hops = recordHops((request) => request.url === start ? {
634
- status: 302,
635
- headers: { Location: next },
636
- body: "Found"
637
- } : {
638
- headers: { "Content-Type": "application/activity+json" },
639
- body: "{\"done\":true}"
640
- });
641
- deepStrictEqual(await createAuthenticatedDocumentLoader(identity, {}, hops)(start), {
642
- contextUrl: null,
643
- document: { done: true },
644
- documentUrl: next
645
- });
646
- deepStrictEqual(hops.events, [
647
- `open ${start}`,
648
- `fetch #1 ${start}`,
649
- "cancel #1",
650
- `close ${start}`,
651
- `open ${next}`,
652
- `fetch #2 ${next}`,
653
- "consumed #2",
654
- `close ${next}`
655
- ]);
656
- hops.assertInvariants();
657
- });
658
- await t.step("Link header alternate", async () => {
659
- const start = "https://example.com/lifecycle/page";
660
- const next = "https://example.com/lifecycle/alternate";
661
- const hops = recordHops((request) => request.url === start ? {
662
- headers: {
663
- "Content-Type": "text/plain",
664
- Link: `<${next}>; rel="alternate"; type="application/activity+json"`
665
- },
666
- body: "not JSON"
667
- } : {
668
- headers: { "Content-Type": "application/activity+json" },
669
- body: "{\"done\":true}"
670
- });
671
- deepStrictEqual((await createAuthenticatedDocumentLoader(identity, {}, hops)(start)).document, { done: true });
672
- deepStrictEqual(hops.events, [
673
- `open ${start}`,
674
- `fetch #1 ${start}`,
675
- "cancel #1",
676
- `close ${start}`,
677
- `open ${next}`,
678
- `fetch #2 ${next}`,
679
- "consumed #2",
680
- `close ${next}`
681
- ]);
682
- hops.assertInvariants();
683
- });
684
- await t.step("one lookup per hop", async () => {
685
- const start = "https://first.example/start";
686
- const next = "https://second.example/document";
687
- const lookups = [];
688
- const lookup = (hostname) => {
689
- lookups.push(hostname);
690
- return Promise.resolve([{
691
- address: "8.8.8.8",
692
- family: 4
693
- }]);
694
- };
695
- await withFetchStub((request) => new URL(request.url).pathname === "/start" ? Response.redirect(next, 302) : Response.json({ done: true }), async (fetched) => {
696
- deepStrictEqual((await createAuthenticatedDocumentLoader(identity, {}, { openHop: (url) => openPublicFetch(url, { lookup }) })(start)).document, { done: true });
697
- deepStrictEqual(lookups, ["first.example", "second.example"]);
698
- deepStrictEqual(fetched.length, 2);
699
- });
700
- });
701
- });
702
- async function captureLogs(fn) {
703
- const records = [];
704
- await configure({
705
- sinks: { buffer: (record) => records.push(record) },
706
- loggers: [{
707
- category: "fedify",
708
- sinks: ["buffer"],
709
- lowestLevel: "debug"
710
- }, {
711
- category: ["logtape", "meta"],
712
- sinks: []
713
- }],
714
- reset: true
715
- });
716
- try {
717
- await fn();
718
- await new Promise((resolve) => setTimeout(resolve, 0));
719
- } finally {
720
- await reset();
721
- }
722
- return records;
723
- }
724
- function getCancelFailures(records) {
725
- return records.flatMap((r) => r.rawMessage === "Failed to cancel the response body from {url}: {error}" ? [r.properties.error.message] : []);
726
- }
727
- const linkAlternate = (next) => ({
728
- headers: {
729
- "Content-Type": "text/plain",
730
- Link: `<${next}>; rel="alternate"; type="application/activity+json"`
731
- },
732
- body: "not JSON"
733
- });
734
- const jsonDocument = {
735
- headers: { "Content-Type": "application/activity+json" },
736
- body: "{\"done\":true}"
737
- };
738
- test("getAuthenticatedDocumentLoader() logs bodies failing to cancel and loads the next hop", async (t) => {
739
- for (const kind of ["redirect", "Link header alternate"]) await t.step(kind, async () => {
740
- const start = "https://example.com/lifecycle/cancel-failure";
741
- const next = "https://example.com/lifecycle/cancel-failure-next";
742
- const hops = recordHops((request) => request.url === start ? {
743
- ...kind === "redirect" ? {
744
- status: 302,
745
- headers: { Location: next },
746
- body: "Found"
747
- } : linkAlternate(next),
748
- failCancel: true
749
- } : jsonDocument);
750
- const loader = createAuthenticatedDocumentLoader(identity, {}, hops);
751
- let document;
752
- const records = await captureLogs(async () => {
753
- document = (await loader(start)).document;
754
- });
755
- deepStrictEqual(document, { done: true });
756
- deepStrictEqual(hops.events, [
757
- `open ${start}`,
758
- `fetch #1 ${start}`,
759
- "cancel #1",
760
- `close ${start}`,
761
- `open ${next}`,
762
- `fetch #2 ${next}`,
763
- "consumed #2",
764
- `close ${next}`
765
- ]);
766
- deepStrictEqual(getCancelFailures(records), ["cancel #1 failed"]);
767
- hops.assertInvariants();
768
- });
769
- });
770
- test("getAuthenticatedDocumentLoader() is not blocked by a body cancellation that never settles", async (t) => {
771
- await t.step("redirect and Link header alternate", async () => {
772
- const start = "https://example.com/lifecycle/hanging-start";
773
- const page = "https://example.com/lifecycle/hanging-page";
774
- const next = "https://example.com/lifecycle/hanging-document";
775
- const hops = recordHops((request) => ({
776
- ...request.url === start ? {
777
- status: 302,
778
- headers: { Location: page },
779
- body: "Found"
780
- } : request.url === page ? linkAlternate(next) : jsonDocument,
781
- hangCancel: true
782
- }));
783
- deepStrictEqual((await createAuthenticatedDocumentLoader(identity, {}, hops)(start)).document, { done: true });
784
- deepStrictEqual(hops.events, [
785
- `open ${start}`,
786
- `fetch #1 ${start}`,
787
- "cancel #1",
788
- `close ${start}`,
789
- `open ${page}`,
790
- `fetch #2 ${page}`,
791
- "cancel #2",
792
- `close ${page}`,
793
- `open ${next}`,
794
- `fetch #3 ${next}`,
795
- "consumed #3",
796
- `close ${next}`
797
- ]);
798
- hops.assertInvariants();
799
- });
800
- await t.step("not found", async () => {
801
- const url = "https://example.com/lifecycle/hanging-missing";
802
- const hops = recordHops(() => ({
803
- status: 404,
804
- body: "Not Found",
805
- hangCancel: true
806
- }));
807
- await rejects(createAuthenticatedDocumentLoader(identity, {}, hops)(url), FetchError);
808
- deepStrictEqual(hops.events.slice(0, 2), [`open ${url}`, `fetch #1 ${url}`]);
809
- deepStrictEqual(hops.events.at(-1), `close ${url}`);
810
- hops.assertInvariants();
811
- });
812
- });
813
- test("getAuthenticatedDocumentLoader() completes with responses cloned by fetch-mock", async () => {
814
- esm_default.mockGlobal();
815
- try {
816
- const base = "https://example.com/tee/";
817
- esm_default.get(`${base}start`, () => new Response("Found", {
818
- status: 302,
819
- headers: { Location: `${base}page` }
820
- }));
821
- esm_default.get(`${base}page`, () => new Response("not JSON", { headers: {
822
- "Content-Type": "text/plain",
823
- Link: `<${base}document>; rel="alternate"; type="application/activity+json"`
824
- } }));
825
- esm_default.get(`${base}document`, () => new Response("{\"done\":true}", { headers: { "Content-Type": "application/activity+json" } }));
826
- esm_default.get(`${base}missing`, () => new Response("Not Found", { status: 404 }));
827
- const loader = createAuthenticatedDocumentLoader(identity, {}, directDeps);
828
- deepStrictEqual((await loader(`${base}start`)).document, { done: true });
829
- await rejects(loader(`${base}missing`), FetchError);
830
- } finally {
831
- esm_default.hardReset();
832
- }
833
- });
834
- const unsupportedUrls = [
835
- "ftp://example.com/collection",
836
- "file:///collection",
837
- `data:application/ld+json,${encodeURIComponent(JSON.stringify({ id: "https://example.com/data" }))}`
838
- ];
839
- function isCredentialUrlError(error) {
840
- return error instanceof UrlError && error.reason === "disallowed" && error.message === "URLs with credentials are not allowed";
841
- }
842
- test("getAuthenticatedDocumentLoader() rejects URLs with credentials", async (t) => {
843
- const identity = {
844
- keyId: new URL("https://example.com/key2"),
845
- privateKey: rsaPrivateKey2
846
- };
847
- const start = "https://8.8.8.8/start";
848
- const target = "https://user:pass@8.8.8.8/document";
849
- for (const allowPrivateAddress of [false, true]) {
850
- const loader = getAuthenticatedDocumentLoader(identity, { allowPrivateAddress });
851
- for (const path of [
852
- "direct",
853
- "redirect",
854
- "Link",
855
- "HTML"
856
- ]) await t.step(`${path}, allowPrivateAddress=${allowPrivateAddress}`, async () => {
857
- await withFetchStub((request) => {
858
- if (request.url !== start) return Response.json({});
859
- if (path === "redirect") return Response.redirect(target, 302);
860
- if (path === "HTML") return new Response(`<link rel="alternate" type="application/activity+json" href="${target}">`, { headers: { "Content-Type": "text/html" } });
861
- return new Response("", { headers: {
862
- "Content-Type": "text/plain",
863
- Link: `<${target}>; rel="alternate"; type="application/activity+json"`
864
- } });
865
- }, async (fetched) => {
866
- await rejects(loader(path === "direct" ? target : start), isCredentialUrlError);
867
- deepStrictEqual(fetched.map((r) => r.url), path === "direct" ? [] : [start]);
868
- });
869
- });
870
- for (const url of [
871
- "https://user@8.8.8.8/document",
872
- "https://:pass@8.8.8.8/document",
873
- "https://%75ser:p%40ss@8.8.8.8/document",
874
- "http://user:pass@8.8.8.8/document"
875
- ]) await t.step(`${url}, allowPrivateAddress=${allowPrivateAddress}`, async () => {
876
- await withFetchStub(() => Response.json({}), async (fetched) => {
877
- await rejects(loader(url), isCredentialUrlError);
878
- deepStrictEqual(fetched, []);
879
- });
880
- });
881
- for (const url of ["https://:@8.8.8.8/document", "https://8.8.8.8/@user?q=@pass"]) await t.step(`allows ${url}, allowPrivateAddress=${allowPrivateAddress}`, async () => {
882
- await withFetchStub(() => Response.json({ done: true }), async (fetched) => {
883
- deepStrictEqual((await loader(url)).document, { done: true });
884
- deepStrictEqual(fetched.map((r) => r.url), [new URL(url).href]);
885
- });
886
- });
887
- }
888
- for (const firstSpec of ["rfc9421", "draft-cavage-http-signatures-12"]) await t.step(`redirect after fallback from ${firstSpec}`, async () => {
889
- const loader = getAuthenticatedDocumentLoader(identity, {
890
- allowPrivateAddress: true,
891
- specDeterminer: {
892
- determineSpec: () => firstSpec,
893
- rememberSpec: () => {}
894
- }
895
- });
896
- await withFetchStub((request) => request.url !== start ? Response.json({}) : request.headers.has("Signature-Input") === (firstSpec === "rfc9421") ? new Response(null, { status: 401 }) : Response.redirect(target, 302), async (fetched) => {
897
- await rejects(loader(start), isCredentialUrlError);
898
- deepStrictEqual(fetched.map((r) => r.url), [start, start]);
899
- deepStrictEqual(fetched.map((r) => r.headers.has("Signature-Input")), [firstSpec === "rfc9421", firstSpec !== "rfc9421"]);
900
- });
901
- });
902
- });
903
- function isUnsupportedProtocolError(error, url) {
904
- return error instanceof UrlError && error.message === `Unsupported protocol: ${new URL(url).protocol}` && error.reason === "disallowed";
905
- }
906
- async function withFetchStub(respond, callback) {
907
- const fetched = [];
908
- const originalFetch = globalThis.fetch;
909
- globalThis.fetch = ((input, init) => {
910
- const request = input instanceof Request && init == null ? input : new Request(input, init);
911
- fetched.push(request);
912
- return Promise.resolve(respond(request));
913
- });
914
- try {
915
- await callback(fetched);
916
- } finally {
917
- globalThis.fetch = originalFetch;
918
- }
919
- }
920
- for (const url of unsupportedUrls) {
921
- const scheme = new URL(url).protocol;
922
- const loader = getAuthenticatedDocumentLoader({
923
- keyId: new URL("https://example.com/key2"),
924
- privateKey: rsaPrivateKey2
925
- }, { allowPrivateAddress: true });
926
- test(`getAuthenticatedDocumentLoader() rejects ${scheme} URLs with private addresses allowed before fetching`, async () => {
927
- await withFetchStub(() => Response.json({}), async (fetched) => {
928
- await rejects(loader(url), (e) => isUnsupportedProtocolError(e, url));
929
- deepStrictEqual(fetched, []);
930
- });
931
- });
932
- test(`getAuthenticatedDocumentLoader() rejects redirects to ${scheme} URLs with private addresses allowed`, async () => {
933
- const start = "https://example.com/redirect-to-unsupported";
934
- await withFetchStub(() => Response.redirect(url, 302), async (fetched) => {
935
- await rejects(loader(start), (e) => isUnsupportedProtocolError(e, url));
936
- deepStrictEqual(fetched.map((r) => r.url), [start]);
937
- });
938
- });
939
- for (const firstSpec of ["rfc9421", "draft-cavage-http-signatures-12"]) test(`getAuthenticatedDocumentLoader() rejects redirects to ${scheme} URLs after signature fallback from ${firstSpec}`, async () => {
940
- const start = "https://example.com/fallback-redirect-to-unsupported";
941
- const fallbackLoader = getAuthenticatedDocumentLoader({
942
- keyId: new URL("https://example.com/key2"),
943
- privateKey: rsaPrivateKey2
944
- }, {
945
- allowPrivateAddress: true,
946
- specDeterminer: {
947
- determineSpec: () => firstSpec,
948
- rememberSpec: () => {}
949
- }
950
- });
951
- await withFetchStub((request) => request.headers.has("Signature-Input") === (firstSpec === "rfc9421") ? new Response("Unauthorized", { status: 401 }) : Response.redirect(url, 302), async (fetched) => {
952
- await rejects(fallbackLoader(start), (e) => isUnsupportedProtocolError(e, url));
953
- deepStrictEqual(fetched.map((r) => r.url), [start, start]);
954
- deepStrictEqual(fetched.map((r) => r.headers.has("Signature-Input")), [firstSpec === "rfc9421", firstSpec !== "rfc9421"]);
955
- });
956
- });
957
- for (const html of [false, true]) test(`getAuthenticatedDocumentLoader() rejects ${html ? "HTML" : "Link header"} alternates to ${scheme} URLs with private addresses allowed`, async () => {
958
- const start = "https://example.com/alternate-to-unsupported";
959
- await withFetchStub(() => html ? new Response(`<link rel="alternate" type="application/activity+json" href="${url}">`, { headers: { "Content-Type": "text/html" } }) : new Response("", { headers: {
960
- "Content-Type": "text/plain",
961
- Link: `<${url}>; rel="alternate"; type="application/activity+json"`
962
- } }), async (fetched) => {
963
- await rejects(loader(start), (e) => isUnsupportedProtocolError(e, url));
964
- deepStrictEqual(fetched.map((r) => r.url), [start]);
965
- });
966
- });
967
- }
968
- function createRecordedResponse(events, index, init, cancelSuffix = () => "") {
969
- const bytes = new TextEncoder().encode(init.body ?? "");
970
- const chunkSize = init.chunkSize ?? 256;
971
- let offset = 0;
972
- let settled = false;
973
- const body = new ReadableStream({
974
- pull(controller) {
975
- if (offset >= bytes.length) {
976
- settled = true;
977
- events.push(`consumed #${index}`);
978
- controller.close();
979
- return;
980
- }
981
- controller.enqueue(bytes.slice(offset, offset + chunkSize));
982
- offset += chunkSize;
983
- },
984
- cancel() {
985
- settled = true;
986
- events.push(`cancel #${index}${cancelSuffix()}`);
987
- if (init.failCancel) throw new Error(`cancel #${index} failed`);
988
- if (init.hangCancel) return new Promise(() => {});
989
- }
990
- }, { highWaterMark: 0 });
991
- return {
992
- response: new Response(body, {
993
- status: init.status ?? 200,
994
- headers: init.headers
995
- }),
996
- settled: () => settled
997
- };
998
- }
999
- function recordHops(respond) {
1000
- const events = [];
1001
- const requests = [];
1002
- const unsettledAtClose = [];
1003
- let opens = 0;
1004
- let closes = 0;
1005
- let fetches = 0;
1006
- return {
1007
- events,
1008
- requests,
1009
- openHop(url) {
1010
- opens++;
1011
- events.push(`open ${url}`);
1012
- const tracked = [];
1013
- let closed = false;
1014
- let closing = false;
1015
- return Promise.resolve({
1016
- url: new URL(url),
1017
- async fetch(input, init) {
1018
- if (closed) throw new TypeError("The session is closed.");
1019
- const request = new Request(input instanceof Request ? input.clone() : input, init);
1020
- const index = ++fetches;
1021
- requests.push(request);
1022
- events.push(`fetch #${index} ${request.url}`);
1023
- const recorded = createRecordedResponse(events, index, await respond(request, index), () => closing ? " by close" : "");
1024
- tracked.push({
1025
- ...recorded,
1026
- index
1027
- });
1028
- return recorded.response;
1029
- },
1030
- close() {
1031
- if (closed) return Promise.resolve();
1032
- closed = true;
1033
- closes++;
1034
- closing = true;
1035
- for (const { response, settled, index } of tracked) {
1036
- if (settled()) continue;
1037
- if (response.body?.locked) unsettledAtClose.push(index);
1038
- else response.body?.cancel().catch(() => {});
1039
- }
1040
- events.push(`close ${url}`);
1041
- return Promise.resolve();
1042
- }
1043
- });
1044
- },
1045
- assertInvariants() {
1046
- deepStrictEqual(opens, closes);
1047
- deepStrictEqual(unsettledAtClose, []);
1048
- }
1049
- };
1050
- }
1051
- test("authenticated loader closes a hop that opens after its timeout", async () => {
1052
- const url = "https://example.com/late-open";
1053
- let release = () => {};
1054
- const opened = new Promise((resolve) => release = resolve);
1055
- let closed = () => {};
1056
- const closure = new Promise((resolve) => closed = resolve);
1057
- const hops = recordHops(() => jsonDocument);
1058
- await rejects(createAuthenticatedDocumentLoader(identity, { timeout: 20 }, { async openHop(url) {
1059
- await opened;
1060
- const session = await hops.openHop(url);
1061
- return {
1062
- ...session,
1063
- async close() {
1064
- await session.close();
1065
- closed();
1066
- }
1067
- };
1068
- } })(url), (error) => assertTimeoutFetchError(error, url));
1069
- release();
1070
- await closure;
1071
- deepStrictEqual(hops.requests, []);
1072
- deepStrictEqual(hops.events, [`open ${url}`, `close ${url}`]);
1073
- hops.assertInvariants();
1074
- });
1075
- //#endregion
1076
- export {};