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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/dist/federation/mod.cjs +1 -1
  2. package/dist/federation/mod.js +1 -1
  3. package/dist/{federation-pFFwPyoZ.cjs → federation-C0zalE9W.cjs} +8 -3
  4. package/dist/{http-T7h9GBAN.js → http-BC5Bd3-E.js} +1 -1
  5. package/dist/{http-CXX-QPzs.cjs → http-Dqzgc4Rj.cjs} +1 -1
  6. package/dist/{kv-cache-EFcb1kkU.js → kv-cache-CQ0u0Ry0.js} +1 -1
  7. package/dist/{kv-cache-C6XX_fwz.cjs → kv-cache-ihEHdx1v.cjs} +1 -1
  8. package/dist/{middleware-Bj91r7r2.js → middleware-Bgm3A90j.js} +8 -3
  9. package/dist/mod.cjs +4 -4
  10. package/dist/mod.js +4 -4
  11. package/dist/{portable-collection-Do5QA2oy.js → portable-collection-DZ_XqNUM.js} +1 -1
  12. package/dist/{portable-collection-BOl9oKrt.cjs → portable-collection-nvog8lS6.cjs} +1 -1
  13. package/dist/sig/mod.cjs +2 -2
  14. package/dist/sig/mod.js +2 -2
  15. package/dist/utils/mod.cjs +1 -1
  16. package/dist/utils/mod.js +1 -1
  17. package/package.json +22 -9
  18. package/skills/fedify/SKILL.md +35 -0
  19. package/dist/accept-CPVqki78.mjs +0 -145
  20. package/dist/activity-listener-CELFAodc.mjs +0 -44
  21. package/dist/assert-D1Eafmd_.mjs +0 -23
  22. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  23. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  24. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  25. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  26. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  27. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  28. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  29. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  30. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  31. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  32. package/dist/audience-CHQ-FlLD.mjs +0 -95
  33. package/dist/builder-D1FP_5nQ.mjs +0 -911
  34. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  35. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  36. package/dist/client-5SIFzW3q.mjs +0 -441
  37. package/dist/codec-C6rTrpIp.mjs +0 -147
  38. package/dist/collection-CnnP1UAv.mjs +0 -44
  39. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  40. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  41. package/dist/compat/public-audience.test.d.mts +0 -2
  42. package/dist/compat/public-audience.test.mjs +0 -187
  43. package/dist/compat/secured-document.test.d.mts +0 -2
  44. package/dist/compat/secured-document.test.mjs +0 -58
  45. package/dist/compat/transformers.test.d.mts +0 -2
  46. package/dist/compat/transformers.test.mjs +0 -62
  47. package/dist/compound-proof-DSHhnOEW.mjs +0 -1019
  48. package/dist/context-LgGFFSz7.mjs +0 -146
  49. package/dist/deno-C50ikGBU.mjs +0 -8
  50. package/dist/dist-_geWsuaI.mjs +0 -189
  51. package/dist/docloader-BY-SEID0.mjs +0 -136
  52. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  53. package/dist/exporter-DVG68ozH.mjs +0 -263
  54. package/dist/federation/audience.test.d.mts +0 -2
  55. package/dist/federation/audience.test.mjs +0 -130
  56. package/dist/federation/builder.test.d.mts +0 -2
  57. package/dist/federation/builder.test.mjs +0 -396
  58. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  59. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  60. package/dist/federation/collection.test.d.mts +0 -2
  61. package/dist/federation/collection.test.mjs +0 -21
  62. package/dist/federation/compound-fanout.test.d.mts +0 -2
  63. package/dist/federation/compound-fanout.test.mjs +0 -231
  64. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  65. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  66. package/dist/federation/handler.test.d.mts +0 -2
  67. package/dist/federation/handler.test.mjs +0 -5445
  68. package/dist/federation/hashlink-media.test.d.mts +0 -2
  69. package/dist/federation/hashlink-media.test.mjs +0 -422
  70. package/dist/federation/idempotency.test.d.mts +0 -2
  71. package/dist/federation/idempotency.test.mjs +0 -207
  72. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  73. package/dist/federation/inbox-actorless.test.mjs +0 -522
  74. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  75. package/dist/federation/inbox-authentication.test.mjs +0 -220
  76. package/dist/federation/inbox-report.test.d.mts +0 -2
  77. package/dist/federation/inbox-report.test.mjs +0 -719
  78. package/dist/federation/inbox-view.test.d.mts +0 -2
  79. package/dist/federation/inbox-view.test.mjs +0 -369
  80. package/dist/federation/inbox.test.d.mts +0 -2
  81. package/dist/federation/inbox.test.mjs +0 -139
  82. package/dist/federation/keycache.test.d.mts +0 -2
  83. package/dist/federation/keycache.test.mjs +0 -337
  84. package/dist/federation/kv.test.d.mts +0 -2
  85. package/dist/federation/kv.test.mjs +0 -88
  86. package/dist/federation/metrics.test.d.mts +0 -2
  87. package/dist/federation/metrics.test.mjs +0 -634
  88. package/dist/federation/middleware.test.d.mts +0 -2
  89. package/dist/federation/middleware.test.mjs +0 -9314
  90. package/dist/federation/mq.test.d.mts +0 -2
  91. package/dist/federation/mq.test.mjs +0 -591
  92. package/dist/federation/negotiation.test.d.mts +0 -2
  93. package/dist/federation/negotiation.test.mjs +0 -18
  94. package/dist/federation/outbound-body.test.d.mts +0 -2
  95. package/dist/federation/outbound-body.test.mjs +0 -149
  96. package/dist/federation/outbound-capture.test.d.mts +0 -2
  97. package/dist/federation/outbound-capture.test.mjs +0 -394
  98. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  99. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  100. package/dist/federation/outbound-document.test.d.mts +0 -2
  101. package/dist/federation/outbound-document.test.mjs +0 -171
  102. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  103. package/dist/federation/outbound-provenance.test.mjs +0 -543
  104. package/dist/federation/outbound-report.test.d.mts +0 -2
  105. package/dist/federation/outbound-report.test.mjs +0 -5475
  106. package/dist/federation/outbound-workers.test.d.mts +0 -2
  107. package/dist/federation/outbound-workers.test.mjs +0 -64
  108. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  109. package/dist/federation/outbound-workflow.test.mjs +0 -154
  110. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  111. package/dist/federation/outgoing-proof.test.mjs +0 -933
  112. package/dist/federation/portable-actor.test.d.mts +0 -2
  113. package/dist/federation/portable-actor.test.mjs +0 -496
  114. package/dist/federation/portable-chain.test.d.mts +0 -2
  115. package/dist/federation/portable-chain.test.mjs +0 -370
  116. package/dist/federation/portable-collection.test.d.mts +0 -2
  117. package/dist/federation/portable-collection.test.mjs +0 -832
  118. package/dist/federation/portable-delivery.test.d.mts +0 -2
  119. package/dist/federation/portable-delivery.test.mjs +0 -845
  120. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  121. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  122. package/dist/federation/portable-inbox.test.d.mts +0 -2
  123. package/dist/federation/portable-inbox.test.mjs +0 -1960
  124. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  125. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  126. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  127. package/dist/federation/portable-route-activity.test.mjs +0 -259
  128. package/dist/federation/portable.test.d.mts +0 -2
  129. package/dist/federation/portable.test.mjs +0 -1072
  130. package/dist/federation/retry.test.d.mts +0 -2
  131. package/dist/federation/retry.test.mjs +0 -42
  132. package/dist/federation/router.test.d.mts +0 -2
  133. package/dist/federation/router.test.mjs +0 -123
  134. package/dist/federation/send.test.d.mts +0 -2
  135. package/dist/federation/send.test.mjs +0 -1421
  136. package/dist/federation/tasks/codec.test.d.mts +0 -2
  137. package/dist/federation/tasks/codec.test.mjs +0 -302
  138. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  139. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  140. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  141. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  142. package/dist/federation/temporal.test.d.mts +0 -2
  143. package/dist/federation/temporal.test.mjs +0 -71
  144. package/dist/federation/webfinger.test.d.mts +0 -2
  145. package/dist/federation/webfinger.test.mjs +0 -944
  146. package/dist/http-BXbQQZDM.mjs +0 -1449
  147. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  148. package/dist/inbox-cS97XzOD.mjs +0 -399
  149. package/dist/inbox-view-D-d0Ar6o.mjs +0 -385
  150. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  151. package/dist/keycache-N2opu4-3.mjs +0 -221
  152. package/dist/keys-DIJNHW-Y.mjs +0 -120
  153. package/dist/kv-DBRWVx3Q.mjs +0 -104
  154. package/dist/kv-DCHkaJ9-.mjs +0 -92
  155. package/dist/kv-cache-fgbLHGVL.mjs +0 -121
  156. package/dist/ld-BpkhkDGj.mjs +0 -1752
  157. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  158. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  159. package/dist/metrics-Uqf8GomB.mjs +0 -818
  160. package/dist/middleware-DcXzz-YK.mjs +0 -9971
  161. package/dist/middleware-DgwZkvJR.mjs +0 -5
  162. package/dist/mq-eF96QxUT.mjs +0 -288
  163. package/dist/negotiation-BAKO9nih.mjs +0 -96
  164. package/dist/nodeinfo/client.test.d.mts +0 -2
  165. package/dist/nodeinfo/client.test.mjs +0 -1364
  166. package/dist/nodeinfo/handler.test.d.mts +0 -2
  167. package/dist/nodeinfo/handler.test.mjs +0 -94
  168. package/dist/nodeinfo/types.test.d.mts +0 -2
  169. package/dist/nodeinfo/types.test.mjs +0 -192
  170. package/dist/otel/exporter.test.d.mts +0 -2
  171. package/dist/otel/exporter.test.mjs +0 -887
  172. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  173. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  174. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  175. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  176. package/dist/owner-BVenIFg1.mjs +0 -267
  177. package/dist/portable-collection-DIk9gpjL.mjs +0 -418
  178. package/dist/portable-key-C7pVaHNR.mjs +0 -549
  179. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  180. package/dist/proof-BlfZ95--.mjs +0 -1420
  181. package/dist/public-audience--klBIOk1.mjs +0 -197
  182. package/dist/retry-zX5xw5e0.mjs +0 -34
  183. package/dist/router-u5O5KCQr.mjs +0 -156
  184. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  185. package/dist/send-DEGHPGFk.mjs +0 -710
  186. package/dist/sig/accept.test.d.mts +0 -2
  187. package/dist/sig/accept.test.mjs +0 -416
  188. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  189. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  190. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  191. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  192. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  193. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  194. package/dist/sig/compound-proof.test.d.mts +0 -2
  195. package/dist/sig/compound-proof.test.mjs +0 -411
  196. package/dist/sig/http.test.d.mts +0 -2
  197. package/dist/sig/http.test.mjs +0 -3328
  198. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  199. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  200. package/dist/sig/key.test.d.mts +0 -2
  201. package/dist/sig/key.test.mjs +0 -1250
  202. package/dist/sig/ld.test.d.mts +0 -2
  203. package/dist/sig/ld.test.mjs +0 -1044
  204. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  205. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  206. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  207. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  208. package/dist/sig/owner.test.d.mts +0 -2
  209. package/dist/sig/owner.test.mjs +0 -202
  210. package/dist/sig/portable-collection.test.d.mts +0 -2
  211. package/dist/sig/portable-collection.test.mjs +0 -697
  212. package/dist/sig/portable-interop.test.d.mts +0 -2
  213. package/dist/sig/portable-interop.test.mjs +0 -156
  214. package/dist/sig/portable-key-id.test.d.mts +0 -2
  215. package/dist/sig/portable-key-id.test.mjs +0 -67
  216. package/dist/sig/portable-key.test.d.mts +0 -2
  217. package/dist/sig/portable-key.test.mjs +0 -1438
  218. package/dist/sig/proof.test.d.mts +0 -2
  219. package/dist/sig/proof.test.mjs +0 -2638
  220. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  221. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  222. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  223. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  224. package/dist/sig/verification.test.d.mts +0 -2
  225. package/dist/sig/verification.test.mjs +0 -310
  226. package/dist/std__assert-DvMDRPes.mjs +0 -8
  227. package/dist/tasks-BCUmQbbz.mjs +0 -77
  228. package/dist/temporal-B4oQ8HpW.mjs +0 -95
  229. package/dist/testing/context.test.d.mts +0 -2
  230. package/dist/testing/context.test.mjs +0 -19
  231. package/dist/testing/kv.test.d.mts +0 -2
  232. package/dist/testing/kv.test.mjs +0 -101
  233. package/dist/testing/mod.d.mts +0 -6099
  234. package/dist/testing/mod.mjs +0 -9
  235. package/dist/testing-vrnD5Uaa.mjs +0 -8
  236. package/dist/types-DE_LV1JB.mjs +0 -46
  237. package/dist/utils/docloader.test.d.mts +0 -2
  238. package/dist/utils/docloader.test.mjs +0 -1076
  239. package/dist/utils/kv-cache.test.d.mts +0 -2
  240. package/dist/utils/kv-cache.test.mjs +0 -261
  241. package/dist/verification-C3954hQh.mjs +0 -5
  242. package/dist/verification-Dpfcw8ml.mjs +0 -105
  243. package/dist/vocab/cjs.test.d.mts +0 -2
  244. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,3328 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { t as esm_default } from "../esm-BHXXx4Wx.mjs";
5
- import { t as MemoryKvStore } from "../kv-DCHkaJ9-.mjs";
6
- import { t as AssertionError } from "../assertion_error-B-cx0fFA.mjs";
7
- import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
8
- import { t as assertExists } from "../assert_exists-cffSpJ7X.mjs";
9
- import { t as assertFalse } from "../assert_false-CPdRnc3E.mjs";
10
- import { t as assertGreaterOrEqual } from "../assert_greater_or_equal-BlafOF4-.mjs";
11
- import { t as assertThrows } from "../assert_throws-BYITOvPO.mjs";
12
- import "../std__assert-DvMDRPes.mjs";
13
- import { t as assertRejects } from "../assert_rejects-CTptdYck.mjs";
14
- import { t as assert } from "../assert-D1Eafmd_.mjs";
15
- import { x as exportJwk } from "../ld-BpkhkDGj.mjs";
16
- import { a as formatRfc9421SignatureParameters, c as parseRfc9421SignatureInput, d as timingSafeEqual, i as formatRfc9421Signature, l as selectRequestSignature, m as verifyRequestDetailed, n as doubleKnock, o as listRequestSignatures, p as verifyRequest, r as doubleKnockScoped, s as parseRfc9421Signature, t as createRfc9421SignatureBase, u as signRequest } from "../http-BXbQQZDM.mjs";
17
- import { a as rsaPrivateKey3, i as rsaPrivateKey2, l as rsaPublicKey5, n as ed25519PrivateKey, o as rsaPublicKey1, r as ed25519PublicKey, s as rsaPublicKey2 } from "../keys-DIJNHW-Y.mjs";
18
- import { t as KvKeyCache } from "../keycache-N2opu4-3.mjs";
19
- import { configure, reset } from "@logtape/logtape";
20
- import { FetchError, UrlError, exportSpki, getDocumentLoader } from "@fedify/vocab-runtime";
21
- import { createTestMeterProvider, createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
22
- import { openDirectFetch } from "@fedify/vocab-runtime/internal";
23
- import { encodeBase64 } from "byte-encodings/base64";
24
- //#region ../../node_modules/.pnpm/@jsr+std__assert@0.226.0/node_modules/@jsr/std__assert/assert_string_includes.js
25
- /**
26
- * Make an assertion that actual includes expected. If not
27
- * then throw.
28
- *
29
- * @example Usage
30
- * ```ts no-eval
31
- * import { assertStringIncludes } from "@std/assert/assert-string-includes";
32
- *
33
- * assertStringIncludes("Hello", "ello"); // Doesn't throw
34
- * assertStringIncludes("Hello", "world"); // Throws
35
- * ```
36
- *
37
- * @param actual The actual string to check for inclusion.
38
- * @param expected The expected string to check for inclusion.
39
- * @param msg The optional message to display if the assertion fails.
40
- */ function assertStringIncludes(actual, expected, msg) {
41
- if (!actual.includes(expected)) {
42
- msg = `Expected actual: "${actual}" to contain: "${expected}"${msg ? `: ${msg}` : "."}`;
43
- throw new AssertionError(msg);
44
- }
45
- }
46
- //#endregion
47
- //#region src/sig/http.test.ts
48
- test("signRequest() [draft-cavage]", async () => {
49
- assertEquals(await verifyRequest(await signRequest(new Request("https://example.com/", {
50
- method: "POST",
51
- body: "Hello, world!",
52
- headers: {
53
- "Content-Type": "text/plain; charset=utf-8",
54
- Accept: "text/plain"
55
- }
56
- }), rsaPrivateKey2, new URL("https://example.com/key2")), {
57
- contextLoader: mockDocumentLoader,
58
- documentLoader: mockDocumentLoader
59
- }), rsaPublicKey2);
60
- });
61
- test("verifyRequest() [draft-cavage]", async () => {
62
- const request = new Request("https://example.com/", {
63
- method: "POST",
64
- body: "Hello, world!",
65
- headers: {
66
- Accept: "text/plain",
67
- "Content-Type": "text/plain; charset=utf-8",
68
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
69
- Digest: "sha-256=MV9b23bQeMQ7isAGTkoBZGErH853yGk0W/yUx1iU7dM=",
70
- Signature: "keyId=\"https://example.com/key\",headers=\"(request-target) accept content-type date digest host\",signature=\"ZDeMzjBKPfJvkv4QaxAdOQxKCJ96pOzOCFhhGgGnlsw4N80oN4GEZ/n8nNKjpoW95Bcs8N0dZVSQHj3g08AReKIOXpun0tgmaWGKRcRT4kEhAW+uP1wVZPbuOIvVCEhMYv6+SbnttgX0GvN365BTZpxh7+gRrRC4mns5qV69cv45I5iJB0aw24GJW9u7lUAm6yDEh4N0aXfNqNRq3LHiuPqlDzSenfXbHr0UnAMaGuI4v9/uflu/jNi3hRX4Y/T+ngM1zvLvi/BjKK4I1rh520qnkrWpxz9ikLCjIMO7Dwh1nOsPzrZE2t43XHD3evdvm1RM5Ppes+M6DrfkfQuUBw==\""
71
- }
72
- });
73
- const cache = {};
74
- const options = {
75
- contextLoader: mockDocumentLoader,
76
- documentLoader: mockDocumentLoader,
77
- currentTime: Temporal.Instant.from("2024-03-05T07:49:44Z"),
78
- keyCache: {
79
- get(keyId) {
80
- return Promise.resolve(cache[keyId.href]);
81
- },
82
- set(keyId, key) {
83
- cache[keyId.href] = key;
84
- return Promise.resolve();
85
- }
86
- }
87
- };
88
- let key = await verifyRequest(request, options);
89
- assertEquals(key, rsaPublicKey1);
90
- assertEquals(cache, { "https://example.com/key": rsaPublicKey1 });
91
- cache["https://example.com/key"] = rsaPublicKey2;
92
- key = await verifyRequest(request, options);
93
- assertEquals(key, rsaPublicKey1);
94
- assertEquals(cache, { "https://example.com/key": rsaPublicKey1 });
95
- assertEquals(await verifyRequest(new Request("https://example.com/"), {
96
- documentLoader: mockDocumentLoader,
97
- contextLoader: mockDocumentLoader
98
- }), null);
99
- assertEquals(await verifyRequest(new Request("https://example.com/", { headers: { Date: "Tue, 05 Mar 2024 07:49:44 GMT" } }), {
100
- documentLoader: mockDocumentLoader,
101
- contextLoader: mockDocumentLoader
102
- }), null);
103
- assertEquals(await verifyRequest(new Request("https://example.com/", {
104
- method: "POST",
105
- headers: {
106
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
107
- Signature: "asdf"
108
- }
109
- }), {
110
- documentLoader: mockDocumentLoader,
111
- contextLoader: mockDocumentLoader
112
- }), null);
113
- assertEquals(await verifyRequest(new Request("https://example.com/", {
114
- method: "POST",
115
- headers: {
116
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
117
- Signature: "asdf",
118
- Digest: "invalid"
119
- },
120
- body: ""
121
- }), {
122
- documentLoader: mockDocumentLoader,
123
- contextLoader: mockDocumentLoader
124
- }), null);
125
- assertEquals(await verifyRequest(new Request("https://example.com/", {
126
- method: "POST",
127
- headers: {
128
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
129
- Signature: "asdf",
130
- Digest: "sha-256=MV9b23bQeMQ7isAGTkoBZGErH853yGk0W/yUx1iU7dM="
131
- },
132
- body: ""
133
- }), {
134
- documentLoader: mockDocumentLoader,
135
- contextLoader: mockDocumentLoader
136
- }), null);
137
- assertEquals(await verifyRequest(request, {
138
- documentLoader: mockDocumentLoader,
139
- contextLoader: mockDocumentLoader,
140
- currentTime: Temporal.Instant.from("2024-03-05T06:49:43.9999Z")
141
- }), null);
142
- assertEquals(await verifyRequest(request, {
143
- documentLoader: mockDocumentLoader,
144
- contextLoader: mockDocumentLoader,
145
- currentTime: Temporal.Instant.from("2024-03-05T07:49:13.9999Z"),
146
- timeWindow: { seconds: 30 }
147
- }), null);
148
- assertEquals(await verifyRequest(request, {
149
- documentLoader: mockDocumentLoader,
150
- contextLoader: mockDocumentLoader,
151
- currentTime: Temporal.Instant.from("2024-03-05T08:49:44.0001Z")
152
- }), null);
153
- assertEquals(await verifyRequest(request, {
154
- documentLoader: mockDocumentLoader,
155
- contextLoader: mockDocumentLoader,
156
- currentTime: Temporal.Instant.from("2024-03-05T07:50:14.0001Z"),
157
- timeWindow: { seconds: 30 }
158
- }), null);
159
- assertEquals(await verifyRequest(request, {
160
- documentLoader: mockDocumentLoader,
161
- contextLoader: mockDocumentLoader,
162
- currentTime: Temporal.Instant.from("2024-01-01T00:00:00.0000Z"),
163
- timeWindow: false
164
- }), rsaPublicKey1);
165
- assertEquals(await verifyRequest(request, {
166
- documentLoader: mockDocumentLoader,
167
- contextLoader: mockDocumentLoader,
168
- currentTime: Temporal.Instant.from("2025-01-01T00:00:00.0000Z"),
169
- timeWindow: false
170
- }), rsaPublicKey1);
171
- assert(await verifyRequest(new Request("https://c27a97f98d5f.ngrok.app/i/inbox", {
172
- method: "POST",
173
- body: "{\"@context\":[\"https://www.w3.org/ns/activitystreams\",\"https://w3id.org/security/v1\"],\"actor\":\"https://oeee.cafe/ap/users/3609fd4e-d51d-4db8-9f04-4189815864dd\",\"object\":{\"actor\":\"https://c27a97f98d5f.ngrok.app/i\",\"object\":\"https://oeee.cafe/ap/users/3609fd4e-d51d-4db8-9f04-4189815864dd\",\"type\":\"Follow\",\"id\":\"https://c27a97f98d5f.ngrok.app/i#follows/https://oeee.cafe/ap/users/3609fd4e-d51d-4db8-9f04-4189815864dd\"},\"type\":\"Accept\",\"id\":\"https://oeee.cafe/objects/0fc2608f-5660-4b91-b8c7-63c0c2ac2e20\"}",
174
- headers: {
175
- Host: "c27a97f98d5f.ngrok.app",
176
- "Content-Type": "application/activity+json",
177
- Date: "Mon, 25 Aug 2025 12:58:14 GMT",
178
- Digest: "SHA-256=YZyjeVQW5GwliJowASkteBJhFBTq3eQk/AMqRETc//A=",
179
- Signature: "keyId=\"https://oeee.cafe/ap/users/3609fd4e-d51d-4db8-9f04-4189815864dd#main-key\",algorithm=\"hs2019\",created=\"1756126694\",expires=\"1756130294\",headers=\"(request-target) (created) (expires) content-type date digest host\",signature=\"XFb0jl2uMhE7RhbneE9sK9Zls2qZec8iy6+9O8UgDQeBGJThORFLjXKlps4QO1WAf1YSVB/i5aV6yF+h73Lm3ZiuAJDx1h+00iLsxoYuIw1CZvF0V2jELoo3sQ2/ZzqeoO6H5TbK7tKnU+ulFAPTuJgjIvPwYl11OMRouVS34NiaHP9Yx9pU813TLv37thG/hUKanyq8kk0IJWtDWteY/zxDvzoe7VOkBXVBHslMyrNAI/5JGulVQAQp/E61dJAhTHHIyGxkc/7iutWFZuqFXIiPJ9KR2OuKDj/B32hEzlsf5xH/CjqOJPIg1qMK8FzDiALCq6zjiKIBEnW8HQc/hQ==\""
180
- }
181
- }), {
182
- ...options,
183
- currentTime: Temporal.Instant.from("2025-08-25T12:58:14Z")
184
- }) != null);
185
- });
186
- test("verifyRequestDetailed() classifies malformed signatures as invalid", async () => {
187
- const draftMissingKeyId = await verifyRequestDetailed(new Request("https://example.com/", {
188
- method: "POST",
189
- headers: {
190
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
191
- Digest: "sha-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
192
- Signature: "headers=\"(request-target) date digest\",signature=\"AAAA\""
193
- },
194
- body: ""
195
- }), {
196
- documentLoader: mockDocumentLoader,
197
- contextLoader: mockDocumentLoader
198
- });
199
- assertFalse(draftMissingKeyId.verified);
200
- assertEquals(draftMissingKeyId.reason.type, "invalidSignature");
201
- assertFalse("keyId" in draftMissingKeyId.reason);
202
- const draftInvalidKeyId = await verifyRequestDetailed(new Request("https://example.com/", {
203
- method: "POST",
204
- headers: {
205
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
206
- Digest: "sha-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
207
- Signature: "keyId=\"not a url\",headers=\"(request-target) date digest\",signature=\"AAAA\""
208
- },
209
- body: ""
210
- }), {
211
- documentLoader: mockDocumentLoader,
212
- contextLoader: mockDocumentLoader
213
- });
214
- assertFalse(draftInvalidKeyId.verified);
215
- assertEquals(draftInvalidKeyId.reason.type, "invalidSignature");
216
- assertFalse("keyId" in draftInvalidKeyId.reason);
217
- const rfcMissingKeyId = await verifyRequestDetailed(new Request("https://example.com/api/resource", {
218
- method: "GET",
219
- headers: {
220
- Host: "example.com",
221
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
222
- "Signature-Input": "sig1=(\"@method\" \"@target-uri\" \"@authority\");created=1709626184",
223
- Signature: "sig1=:AAAA:"
224
- }
225
- }), {
226
- documentLoader: mockDocumentLoader,
227
- contextLoader: mockDocumentLoader,
228
- spec: "rfc9421"
229
- });
230
- assertFalse(rfcMissingKeyId.verified);
231
- assertEquals(rfcMissingKeyId.reason.type, "invalidSignature");
232
- assertFalse("keyId" in rfcMissingKeyId.reason);
233
- });
234
- test("verifyRequestDetailed() records failure details on span", async () => {
235
- const [tracerProvider, exporter] = createTestTracerProvider();
236
- const keyId = new URL("https://gone.example/actors/alice#main-key");
237
- assertFalse((await verifyRequestDetailed(await signRequest(new Request("https://example.com/inbox", {
238
- method: "POST",
239
- headers: {
240
- "Content-Type": "application/activity+json",
241
- accept: "application/ld+json"
242
- },
243
- body: JSON.stringify({
244
- "@context": "https://www.w3.org/ns/activitystreams",
245
- type: "Create",
246
- actor: "https://gone.example/actors/alice"
247
- })
248
- }), rsaPrivateKey2, keyId), {
249
- tracerProvider,
250
- contextLoader: mockDocumentLoader,
251
- documentLoader(url) {
252
- if (url === keyId.href) throw new FetchError(keyId, `HTTP 410: ${keyId.href}`, new Response(null, { status: 410 }));
253
- return mockDocumentLoader(url);
254
- }
255
- })).verified);
256
- const spans = exporter.getSpans("http_signatures.verify");
257
- assertEquals(spans.length, 1);
258
- const span = spans[0];
259
- assertEquals(span.attributes["http_signatures.verified"], false);
260
- assertEquals(span.attributes["http_signatures.failure_reason"], "keyFetchError");
261
- assertEquals(span.attributes["http_signatures.key_id"], keyId.href);
262
- assertEquals(span.attributes["http_signatures.key_fetch_status"], 410);
263
- });
264
- test("verifyRequestDetailed() records verification duration metric", async (t) => {
265
- const buildSignedRequest = (spec) => signRequest(new Request("https://example.com/inbox", {
266
- method: "POST",
267
- headers: {
268
- "Content-Type": "application/activity+json",
269
- accept: "application/ld+json"
270
- },
271
- body: JSON.stringify({
272
- "@context": "https://www.w3.org/ns/activitystreams",
273
- type: "Create",
274
- actor: "https://example.com/key2"
275
- })
276
- }), rsaPrivateKey2, new URL("https://example.com/key2"), { spec });
277
- await t.step("verified path emits one measurement", async () => {
278
- const [meterProvider, recorder] = createTestMeterProvider();
279
- assert((await verifyRequestDetailed(await buildSignedRequest(), {
280
- contextLoader: mockDocumentLoader,
281
- documentLoader: mockDocumentLoader,
282
- meterProvider
283
- })).verified);
284
- const measurements = recorder.getMeasurements("activitypub.signature.verification.duration");
285
- assertEquals(measurements.length, 1);
286
- const measurement = measurements[0];
287
- assertEquals(measurement.type, "histogram");
288
- assertGreaterOrEqual(measurement.value, 0);
289
- assertEquals(measurement.attributes["activitypub.signature.kind"], "http");
290
- assertEquals(measurement.attributes["activitypub.signature.result"], "verified");
291
- assertEquals(measurement.attributes["http_signatures.algorithm"], "rsa-sha256");
292
- assertFalse("http_signatures.failure_reason" in measurement.attributes);
293
- const keyLookups = recorder.getMeasurements("activitypub.key.lookup");
294
- assertEquals(keyLookups.length, 1);
295
- assertEquals(keyLookups[0].attributes["activitypub.lookup.kind"], "public_key");
296
- assertEquals(keyLookups[0].attributes["activitypub.lookup.result"], "fetched");
297
- });
298
- await t.step("missing signature is recorded as result=missing", async () => {
299
- const [meterProvider, recorder] = createTestMeterProvider();
300
- const result = await verifyRequestDetailed(new Request("https://example.com/inbox", {
301
- method: "POST",
302
- headers: { "Content-Type": "application/activity+json" },
303
- body: "{}"
304
- }), {
305
- contextLoader: mockDocumentLoader,
306
- documentLoader: mockDocumentLoader,
307
- meterProvider
308
- });
309
- assertFalse(result.verified);
310
- assertEquals(result.reason.type, "noSignature");
311
- const measurements = recorder.getMeasurements("activitypub.signature.verification.duration");
312
- assertEquals(measurements.length, 1);
313
- assertEquals(measurements[0].attributes["activitypub.signature.kind"], "http");
314
- assertEquals(measurements[0].attributes["activitypub.signature.result"], "missing");
315
- assertFalse("http_signatures.failure_reason" in measurements[0].attributes);
316
- });
317
- await t.step("invalid signature is recorded as result=rejected with failure_reason", async () => {
318
- const [meterProvider, recorder] = createTestMeterProvider();
319
- const result = await verifyRequestDetailed(new Request("https://example.com/", {
320
- method: "POST",
321
- headers: {
322
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
323
- Digest: "sha-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
324
- Signature: "keyId=\"https://example.com/key2\",headers=\"(request-target) date digest\",signature=\"AAAA\""
325
- },
326
- body: ""
327
- }), {
328
- documentLoader: mockDocumentLoader,
329
- contextLoader: mockDocumentLoader,
330
- meterProvider
331
- });
332
- assertFalse(result.verified);
333
- assertEquals(result.reason.type, "invalidSignature");
334
- const measurements = recorder.getMeasurements("activitypub.signature.verification.duration");
335
- assertEquals(measurements.length, 1);
336
- assertEquals(measurements[0].attributes["activitypub.signature.kind"], "http");
337
- assertEquals(measurements[0].attributes["activitypub.signature.result"], "rejected");
338
- assertEquals(measurements[0].attributes["http_signatures.failure_reason"], "invalidSignature");
339
- });
340
- await t.step("key fetch failure is recorded as result=rejected with failure_reason=keyFetchError", async () => {
341
- const [meterProvider, recorder] = createTestMeterProvider();
342
- const keyId = new URL("https://gone.example/actors/alice#main-key");
343
- const result = await verifyRequestDetailed(await signRequest(new Request("https://example.com/inbox", {
344
- method: "POST",
345
- headers: {
346
- "Content-Type": "application/activity+json",
347
- accept: "application/ld+json"
348
- },
349
- body: JSON.stringify({
350
- "@context": "https://www.w3.org/ns/activitystreams",
351
- type: "Create",
352
- actor: "https://gone.example/actors/alice"
353
- })
354
- }), rsaPrivateKey2, keyId), {
355
- contextLoader: mockDocumentLoader,
356
- documentLoader(url) {
357
- if (url === keyId.href) throw new FetchError(keyId, `HTTP 410: ${keyId.href}`, new Response(null, { status: 410 }));
358
- return mockDocumentLoader(url);
359
- },
360
- meterProvider
361
- });
362
- assertFalse(result.verified);
363
- assertEquals(result.reason.type, "keyFetchError");
364
- const measurements = recorder.getMeasurements("activitypub.signature.verification.duration");
365
- assertEquals(measurements.length, 1);
366
- assertEquals(measurements[0].attributes["activitypub.signature.result"], "rejected");
367
- assertEquals(measurements[0].attributes["http_signatures.failure_reason"], "keyFetchError");
368
- });
369
- await t.step("verifyRequest() wrapper emits exactly one measurement, not two", async () => {
370
- const [meterProvider, recorder] = createTestMeterProvider();
371
- assertExists(await verifyRequest(await buildSignedRequest(), {
372
- contextLoader: mockDocumentLoader,
373
- documentLoader: mockDocumentLoader,
374
- meterProvider
375
- }));
376
- assertEquals(recorder.getMeasurements("activitypub.signature.verification.duration").length, 1);
377
- });
378
- await t.step("cached-key retry emits one measurement, not two", async () => {
379
- for (const spec of ["draft-cavage-http-signatures-12", "rfc9421"]) {
380
- const [meterProvider, recorder] = createTestMeterProvider();
381
- const cache = { "https://example.com/key2": rsaPublicKey1 };
382
- assertExists(await verifyRequest(await buildSignedRequest(spec), {
383
- contextLoader: mockDocumentLoader,
384
- documentLoader: mockDocumentLoader,
385
- meterProvider,
386
- keyCache: {
387
- get(keyId) {
388
- return Promise.resolve(cache[keyId.href]);
389
- },
390
- set(keyId, k) {
391
- cache[keyId.href] = k;
392
- return Promise.resolve();
393
- }
394
- }
395
- }), spec);
396
- assertEquals(recorder.getMeasurements("activitypub.signature.verification.duration").length, 1, spec);
397
- assertEquals(recorder.getMeasurements("activitypub.signature.key_fetch.duration").length, 2, spec);
398
- }
399
- });
400
- await t.step("key fetch records result=fetched on a cold cache", async () => {
401
- const [meterProvider, recorder] = createTestMeterProvider();
402
- assertExists(await verifyRequest(await buildSignedRequest(), {
403
- contextLoader: mockDocumentLoader,
404
- documentLoader: mockDocumentLoader,
405
- meterProvider
406
- }));
407
- const measurements = recorder.getMeasurements("activitypub.signature.key_fetch.duration");
408
- assertEquals(measurements.length, 1);
409
- assertEquals(measurements[0].type, "histogram");
410
- assertGreaterOrEqual(measurements[0].value, 0);
411
- assertEquals(measurements[0].attributes["activitypub.signature.kind"], "http");
412
- assertEquals(measurements[0].attributes["activitypub.signature.key_fetch.result"], "fetched");
413
- });
414
- await t.step("key fetch records result=hit when served from the key cache", async () => {
415
- const [meterProvider, recorder] = createTestMeterProvider();
416
- const cache = { "https://example.com/key2": rsaPublicKey2 };
417
- assertExists(await verifyRequest(await buildSignedRequest(), {
418
- contextLoader: mockDocumentLoader,
419
- documentLoader: mockDocumentLoader,
420
- meterProvider,
421
- keyCache: {
422
- get(keyId) {
423
- return Promise.resolve(cache[keyId.href]);
424
- },
425
- set(keyId, k) {
426
- cache[keyId.href] = k;
427
- return Promise.resolve();
428
- }
429
- }
430
- }));
431
- const measurements = recorder.getMeasurements("activitypub.signature.key_fetch.duration");
432
- assertEquals(measurements.length, 1);
433
- assertEquals(measurements[0].attributes["activitypub.signature.key_fetch.result"], "hit");
434
- });
435
- await t.step("key fetch records result=error when the remote key returns HTTP 410", async () => {
436
- const [meterProvider, recorder] = createTestMeterProvider();
437
- const keyId = new URL("https://gone.example/actors/alice#main-key");
438
- assertFalse((await verifyRequestDetailed(await signRequest(new Request("https://example.com/inbox", {
439
- method: "POST",
440
- headers: {
441
- "Content-Type": "application/activity+json",
442
- accept: "application/ld+json"
443
- },
444
- body: "{}"
445
- }), rsaPrivateKey2, keyId), {
446
- contextLoader: mockDocumentLoader,
447
- documentLoader(url) {
448
- if (url === keyId.href) throw new FetchError(keyId, `HTTP 410: ${keyId.href}`, new Response(null, { status: 410 }));
449
- return mockDocumentLoader(url);
450
- },
451
- meterProvider
452
- })).verified);
453
- const measurements = recorder.getMeasurements("activitypub.signature.key_fetch.duration");
454
- assertEquals(measurements.length, 1);
455
- assertEquals(measurements[0].attributes["activitypub.signature.key_fetch.result"], "error");
456
- });
457
- await t.step("draft-cavage with unknown algorithm omits the algorithm metric attribute", async () => {
458
- const [meterProvider, recorder] = createTestMeterProvider();
459
- assertFalse((await verifyRequestDetailed(new Request("https://example.com/", {
460
- method: "POST",
461
- headers: {
462
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
463
- Digest: "sha-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
464
- Signature: "keyId=\"https://example.com/key2\",algorithm=\"x-attacker-supplied\",headers=\"(request-target) date digest\",signature=\"AAAA\""
465
- },
466
- body: ""
467
- }), {
468
- documentLoader: mockDocumentLoader,
469
- contextLoader: mockDocumentLoader,
470
- meterProvider
471
- })).verified);
472
- const measurements = recorder.getMeasurements("activitypub.signature.verification.duration");
473
- assertEquals(measurements.length, 1);
474
- assertFalse("http_signatures.algorithm" in measurements[0].attributes);
475
- });
476
- });
477
- test("verifyRequestDetailed() preserves cached key fetch errors", async (t) => {
478
- const keyId = new URL("https://unreachable.example/actors/alice#main-key");
479
- const timeout = new FetchError("https://unreachable.example/resolved-key", "Timed out after 100 ms");
480
- timeout.cause = new DOMException("The operation timed out", "TimeoutError");
481
- const failures = [
482
- timeout,
483
- new UrlError("DNS lookup failed", {
484
- reason: "dns",
485
- cause: /* @__PURE__ */ new TypeError("No usable IP addresses")
486
- }),
487
- new UrlError("Private IP address is not allowed")
488
- ];
489
- for (const failure of failures) await t.step(failure.message, async () => {
490
- const kv = new MemoryKvStore();
491
- let fetches = 0;
492
- const documentLoader = (url) => {
493
- if (url === keyId.href) {
494
- fetches++;
495
- throw failure;
496
- }
497
- return mockDocumentLoader(url);
498
- };
499
- for (const cached of [false, true]) {
500
- const result = await verifyRequestDetailed(await signRequest(new Request("https://example.com/inbox", {
501
- method: "POST",
502
- body: "Test activity"
503
- }), rsaPrivateKey2, keyId), {
504
- documentLoader,
505
- contextLoader: mockDocumentLoader,
506
- keyCache: new KvKeyCache(kv, ["pk"])
507
- });
508
- assertFalse(result.verified);
509
- assert(result.reason.type === "keyFetchError");
510
- assert("error" in result.reason.result);
511
- const error = result.reason.result.error;
512
- assertEquals(error.name, failure.name);
513
- assertEquals(error.message, failure.message);
514
- if (failure instanceof FetchError) {
515
- assert(error instanceof FetchError);
516
- assertEquals(error.url.href, failure.url.href);
517
- assertEquals(error.response, void 0);
518
- assert(error.cause instanceof DOMException);
519
- assertEquals(error.cause.name, "TimeoutError");
520
- assertEquals(error.cause.message, "The operation timed out");
521
- } else {
522
- assert(error instanceof UrlError);
523
- assertEquals(error.reason, failure.reason);
524
- if (failure.cause instanceof Error) {
525
- assert(error.cause instanceof Error);
526
- assertEquals(error.cause.name, failure.cause.name);
527
- assertEquals(error.cause.message, failure.cause.message);
528
- } else assertEquals(error.cause, void 0);
529
- }
530
- assertEquals(fetches, 1, cached ? "Cached failure was refetched" : "");
531
- }
532
- });
533
- });
534
- test("signRequest() and verifyRequest() [rfc9421] implementation", async () => {
535
- const currentTimestamp = 1709626184;
536
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
537
- const requestBody = "Test content for signature verification";
538
- const request = new Request("https://example.com/api/resource", {
539
- method: "POST",
540
- body: requestBody,
541
- headers: {
542
- "Content-Type": "text/plain; charset=utf-8",
543
- "Accept": "application/json",
544
- "Host": "example.com",
545
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
546
- }
547
- });
548
- const signed = await signRequest(request, rsaPrivateKey2, new URL("https://example.com/key2"), {
549
- spec: "rfc9421",
550
- currentTime
551
- });
552
- assertEquals(signed.headers.has("Signature-Input"), true);
553
- assertEquals(signed.headers.has("Signature"), true);
554
- const signatureInput = signed.headers.get("Signature-Input");
555
- assertExists(signatureInput);
556
- assertStringIncludes(signatureInput, "sig1=", "Should have a signature ID");
557
- assertStringIncludes(signatureInput, "keyid=\"https://example.com/key2\"", "Should contain the exact keyId");
558
- assertStringIncludes(signatureInput, "alg=\"rsa-v1_5-sha256\"", "Should specify the correct algorithm");
559
- assertStringIncludes(signatureInput, `created=${currentTimestamp}`, "Should contain the exact timestamp");
560
- const expectedComponents = [
561
- "@method",
562
- "@target-uri",
563
- "@authority",
564
- "host",
565
- "date",
566
- "content-digest"
567
- ];
568
- for (const component of expectedComponents) assertStringIncludes(signatureInput, `"${component}"`, `Should include component: ${component}`);
569
- assertEquals(signed.headers.has("Content-Digest"), true, "Should include Content-Digest for POST with body");
570
- const contentDigest = signed.headers.get("Content-Digest");
571
- assertExists(contentDigest);
572
- assert(contentDigest.startsWith("sha-256=:"), "Content-Digest should use RFC 9421 format");
573
- assertEquals(contentDigest, `sha-256=:${encodeBase64(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(requestBody)))}:`, "Content-Digest should have correct value");
574
- const signature = signed.headers.get("Signature");
575
- assertExists(signature);
576
- const sigFormat = /^sig1=:([A-Za-z0-9+/]+=*):/;
577
- assert(sigFormat.test(signature), `Signature format (${signature}) should match RFC 9421 format`);
578
- const sigMatch = signature.match(sigFormat);
579
- assertExists(sigMatch);
580
- const sigValue = sigMatch[1];
581
- assert(sigValue.length > 10, "Signature value should be a substantial base64 string");
582
- const parsedInput = parseRfc9421SignatureInput(signatureInput);
583
- assertExists(parsedInput.sig1);
584
- assertEquals(parsedInput.sig1.keyId, "https://example.com/key2");
585
- assertEquals(parsedInput.sig1.alg, "rsa-v1_5-sha256");
586
- assertEquals(parsedInput.sig1.created, currentTimestamp);
587
- assertEquals(parsedInput.sig1.components.length, expectedComponents.length, "Should have all expected components");
588
- for (const component of expectedComponents) assert(parsedInput.sig1.components.some((c) => c.value === component), `Components should include ${component}`);
589
- const parsedSig = parseRfc9421Signature(signature);
590
- assertExists(parsedSig.sig1);
591
- assertEquals(parsedSig.sig1.byteLength > 0, true, "Signature value should be a non-empty Uint8Array");
592
- const verifyHeaders = new Headers();
593
- for (const [name, value] of signed.headers.entries()) if (name !== "Signature" && name !== "Signature-Input") verifyHeaders.set(name, value);
594
- const reconstructedBase = createRfc9421SignatureBase(new Request(request.url, {
595
- method: request.method,
596
- headers: verifyHeaders
597
- }), parsedInput.sig1.components, parsedInput.sig1.parameters);
598
- const signatureBytes = new Uint8Array(parsedSig.sig1);
599
- assert(await crypto.subtle.verify("RSASSA-PKCS1-v1_5", rsaPublicKey2.publicKey, signatureBytes, new TextEncoder().encode(reconstructedBase)), "Manual verification of signature should succeed");
600
- });
601
- test("createRfc9421SignatureBase()", () => {
602
- assertEquals(createRfc9421SignatureBase(new Request("https://example.com/path?query=value", {
603
- method: "POST",
604
- headers: {
605
- Host: "example.com",
606
- Date: "Tue, 05 Mar 2024 07:49:44 GMT",
607
- "Content-Type": "text/plain"
608
- }
609
- }), [
610
- {
611
- value: "@method",
612
- params: {}
613
- },
614
- {
615
- value: "@target-uri",
616
- params: {}
617
- },
618
- {
619
- value: "host",
620
- params: {}
621
- },
622
- {
623
- value: "date",
624
- params: {}
625
- }
626
- ], formatRfc9421SignatureParameters({
627
- algorithm: "rsa-v1_5-sha256",
628
- keyId: new URL("https://example.com/key"),
629
- created: 1709626184
630
- })), [
631
- `"@method": POST`,
632
- `"@target-uri": https://example.com/path?query=value`,
633
- `"host": example.com`,
634
- `"date": Tue, 05 Mar 2024 07:49:44 GMT`,
635
- `"@signature-params": ("@method" "@target-uri" "host" "date");alg="rsa-v1_5-sha256";keyid="https://example.com/key";created=1709626184`
636
- ].join("\n"));
637
- });
638
- test("formatRfc9421Signature()", () => {
639
- const [signatureInput, signatureHeader] = formatRfc9421Signature(new Uint8Array([
640
- 1,
641
- 2,
642
- 3,
643
- 4
644
- ]), [
645
- {
646
- "value": "@method",
647
- params: {}
648
- },
649
- {
650
- "value": "@target-uri",
651
- params: {}
652
- },
653
- {
654
- "value": "host",
655
- params: {}
656
- }
657
- ], formatRfc9421SignatureParameters({
658
- algorithm: "rsa-v1_5-sha256",
659
- keyId: new URL("https://example.com/key"),
660
- created: 1709626184
661
- }));
662
- assertEquals(signatureInput, `sig1=("@method" "@target-uri" "host");alg="rsa-v1_5-sha256";keyid="https://example.com/key";created=1709626184`);
663
- assertEquals(signatureHeader, `sig1=:AQIDBA==:`);
664
- });
665
- test("parseRfc9421SignatureInput()", () => {
666
- const parsed = parseRfc9421SignatureInput(`sig1=("@method" "@target-uri" "host" "date");keyid="https://example.com/key";alg="rsa-v1_5-sha256";created=1709626184`);
667
- assertEquals(parsed.sig1.keyId, "https://example.com/key");
668
- assertEquals(parsed.sig1.alg, "rsa-v1_5-sha256");
669
- assertEquals(parsed.sig1.created, 1709626184);
670
- assertEquals(parsed.sig1.components, [
671
- {
672
- value: "@method",
673
- params: {}
674
- },
675
- {
676
- value: "@target-uri",
677
- params: {}
678
- },
679
- {
680
- value: "host",
681
- params: {}
682
- },
683
- {
684
- value: "date",
685
- params: {}
686
- }
687
- ]);
688
- assertEquals(parsed.sig1.parameters, "keyid=\"https://example.com/key\";alg=\"rsa-v1_5-sha256\";created=1709626184");
689
- });
690
- test("parseRfc9421Signature()", () => {
691
- const parsed = parseRfc9421Signature(`sig1=:AQIDBA==:,sig2=:Zm9vYmFy:`);
692
- assertExists(parsed.sig1);
693
- assertExists(parsed.sig2);
694
- const sig1Bytes = new Uint8Array(parsed.sig1);
695
- assertEquals(sig1Bytes.length, 4);
696
- assertEquals(sig1Bytes[0], 1);
697
- assertEquals(sig1Bytes[1], 2);
698
- assertEquals(sig1Bytes[2], 3);
699
- assertEquals(sig1Bytes[3], 4);
700
- assertEquals(new TextDecoder().decode(parsed.sig2), "foobar");
701
- });
702
- test("verifyRequest() [rfc9421] successful GET verification", async () => {
703
- const currentTimestamp = 1709626184;
704
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
705
- assertEquals(await verifyRequest(await signRequest(new Request("https://example.com/api/resource", {
706
- method: "GET",
707
- headers: {
708
- "Accept": "application/json",
709
- "Host": "example.com",
710
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
711
- }
712
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
713
- spec: "rfc9421",
714
- currentTime
715
- }), {
716
- contextLoader: mockDocumentLoader,
717
- documentLoader: mockDocumentLoader,
718
- spec: "rfc9421",
719
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date(currentTimestamp * 1e3)).toISOString()}`)
720
- }), rsaPublicKey2, "Valid signature should verify to the correct public key");
721
- });
722
- for (const failure of [
723
- "missing key",
724
- "invalid signature",
725
- "digest mismatch",
726
- "empty body",
727
- "cached key"
728
- ]) test(`verifyRequest() [rfc9421] multiple POST signatures: ${failure}`, async () => {
729
- const body = failure === "empty body" ? "" : "Hello, world!";
730
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
731
- const signed = await signRequest(new Request("https://example.com/inbox", {
732
- method: "POST",
733
- body
734
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
735
- spec: "rfc9421",
736
- currentTime
737
- });
738
- const input = signed.headers.get("Signature-Input");
739
- const signature = signed.headers.get("Signature");
740
- const firstInput = failure === "missing key" ? input.replace("https://example.com/key2", "https://example.com/missing-key") : input;
741
- signed.headers.set("Signature-Input", `${firstInput}, ${input.replace(/^sig1=/, "sig2=")}`);
742
- signed.headers.set("Signature", `sig1=:AAAAAA==:, ${signature.replace(/^sig1=/, "sig2=")}`);
743
- const request = failure === "digest mismatch" ? new Request(signed, { body: "Tampered body" }) : signed;
744
- const loaded = [];
745
- assertEquals(await verifyRequest(request, {
746
- keyCache: failure === "cached key" ? {
747
- get: () => Promise.resolve(rsaPublicKey1),
748
- set: async () => {}
749
- } : void 0,
750
- spec: "rfc9421",
751
- currentTime,
752
- contextLoader: mockDocumentLoader,
753
- documentLoader: (url, options) => {
754
- loaded.push(url);
755
- return mockDocumentLoader(url, options);
756
- }
757
- }), failure === "digest mismatch" ? null : rsaPublicKey2);
758
- assertEquals(loaded, failure === "digest mismatch" ? [] : failure === "missing key" ? ["https://example.com/missing-key", "https://example.com/key2"] : ["https://example.com/key2"]);
759
- assertFalse(request.bodyUsed);
760
- assertEquals(await request.text(), failure === "digest mismatch" ? "Tampered body" : body);
761
- });
762
- async function signRfc9421Many(signatures, currentTime) {
763
- let request = new Request("https://example.com/inbox", {
764
- method: "POST",
765
- body: "Hello, world!"
766
- });
767
- let i = 0;
768
- for (const signature of signatures) {
769
- const { label, keyId, privateKey } = typeof signature === "string" ? { keyId: signature } : signature;
770
- i++;
771
- request = await signRequest(request, privateKey ?? rsaPrivateKey2, new URL(keyId), {
772
- spec: "rfc9421",
773
- currentTime,
774
- rfc9421: { label: label ?? `sig${i}` }
775
- });
776
- }
777
- return request;
778
- }
779
- function splitRfc9421Header(header) {
780
- return Object.fromEntries(header.split(/,\s*/).map((member) => [member.slice(0, member.indexOf("=")), member]));
781
- }
782
- function createCountingKeyLoader() {
783
- const loaded = [];
784
- const loader = (url, options) => {
785
- loaded.push(url);
786
- if (url === "https://example.com/key2") return mockDocumentLoader(url, options);
787
- return Promise.reject(new FetchError(url, `Not found: ${url}`));
788
- };
789
- return Object.assign(loader, { loaded });
790
- }
791
- test("verifyRequestDetailed() [rfc9421] caps the number of signatures", async (t) => {
792
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
793
- const missing = (n) => `https://example.com/missing-${n}`;
794
- const valid = "https://example.com/key2";
795
- await t.step("fetches only the keys of the first signatures", async () => {
796
- const request = await signRfc9421Many([
797
- 1,
798
- 2,
799
- 3,
800
- 4,
801
- 5
802
- ].map(missing), currentTime);
803
- for (const [maxSignatures, count] of [
804
- [void 0, 3],
805
- [1, 1],
806
- [5, 5],
807
- [Infinity, 5]
808
- ]) {
809
- const documentLoader = createCountingKeyLoader();
810
- const result = await verifyRequestDetailed(request, {
811
- documentLoader,
812
- contextLoader: mockDocumentLoader,
813
- currentTime,
814
- maxSignatures
815
- });
816
- assertFalse(result.verified);
817
- assertEquals(result.reason.type, "keyFetchError");
818
- assertEquals("keyId" in result.reason ? result.reason.keyId?.href : void 0, missing(count));
819
- assertEquals(documentLoader.loaded, [
820
- 1,
821
- 2,
822
- 3,
823
- 4,
824
- 5
825
- ].slice(0, count).map(missing));
826
- }
827
- });
828
- await t.step("accepts a valid signature within the cap", async () => {
829
- const documentLoader = createCountingKeyLoader();
830
- const result = await verifyRequestDetailed(await signRfc9421Many([
831
- missing(1),
832
- missing(2),
833
- valid,
834
- missing(4)
835
- ], currentTime), {
836
- documentLoader,
837
- contextLoader: mockDocumentLoader,
838
- currentTime
839
- });
840
- assert(result.verified);
841
- assertEquals(result.key, rsaPublicKey2);
842
- assertEquals(result.signatureLabel, "sig3");
843
- assertEquals(documentLoader.loaded, [
844
- missing(1),
845
- missing(2),
846
- valid
847
- ]);
848
- });
849
- await t.step("ignores a valid signature beyond the cap", async () => {
850
- const request = await signRfc9421Many([
851
- missing(1),
852
- missing(2),
853
- missing(3),
854
- valid
855
- ], currentTime);
856
- const documentLoader = createCountingKeyLoader();
857
- const result = await verifyRequestDetailed(request, {
858
- documentLoader,
859
- contextLoader: mockDocumentLoader,
860
- currentTime
861
- });
862
- assertFalse(result.verified);
863
- assertEquals(result.reason.type, "keyFetchError");
864
- assertEquals("keyId" in result.reason ? result.reason.keyId?.href : void 0, missing(3));
865
- assertEquals(documentLoader.loaded, [
866
- 1,
867
- 2,
868
- 3
869
- ].map(missing));
870
- assertEquals(await verifyRequest(request, {
871
- documentLoader: createCountingKeyLoader(),
872
- contextLoader: mockDocumentLoader,
873
- currentTime,
874
- maxSignatures: 4
875
- }), rsaPublicKey2);
876
- });
877
- await t.step("tries signatures in the header order", async () => {
878
- const request = await signRfc9421Many([
879
- {
880
- label: "z",
881
- keyId: missing(1)
882
- },
883
- {
884
- label: "a",
885
- keyId: valid
886
- },
887
- {
888
- label: "m",
889
- keyId: missing(3)
890
- }
891
- ], currentTime);
892
- const documentLoader = createCountingKeyLoader();
893
- assertEquals(await verifyRequest(request, {
894
- documentLoader,
895
- contextLoader: mockDocumentLoader,
896
- currentTime,
897
- maxSignatures: 1
898
- }), null);
899
- assertEquals(documentLoader.loaded, [missing(1)]);
900
- });
901
- await t.step("counts signatures that fail before their keys are fetched", async () => {
902
- const outdated = await signRfc9421Many([{
903
- label: "old",
904
- keyId: missing(1)
905
- }], currentTime.subtract({ hours: 2 }));
906
- const signed = await signRfc9421Many([
907
- {
908
- label: "nobytes1",
909
- keyId: missing(2)
910
- },
911
- {
912
- label: "nobytes2",
913
- keyId: missing(3)
914
- },
915
- {
916
- label: "valid",
917
- keyId: valid
918
- }
919
- ], currentTime);
920
- const inputs = {
921
- ...splitRfc9421Header(outdated.headers.get("Signature-Input")),
922
- ...splitRfc9421Header(signed.headers.get("Signature-Input"))
923
- };
924
- const signatures = {
925
- ...splitRfc9421Header(outdated.headers.get("Signature")),
926
- ...splitRfc9421Header(signed.headers.get("Signature"))
927
- };
928
- const build = (labels) => {
929
- const headers = new Headers(signed.headers);
930
- headers.set("Signature-Input", [`dropped=("@method");keyid="${missing(0)}"`, ...labels.map((label) => inputs[label])].join(", "));
931
- headers.set("Signature", labels.flatMap((label) => label.startsWith("nobytes") ? [] : [signatures[label]]).join(", "));
932
- return new Request(signed.url, {
933
- method: "POST",
934
- headers,
935
- body: "Hello, world!"
936
- });
937
- };
938
- let documentLoader = createCountingKeyLoader();
939
- let result = await verifyRequestDetailed(build([
940
- "old",
941
- "nobytes1",
942
- "valid"
943
- ]), {
944
- documentLoader,
945
- contextLoader: mockDocumentLoader,
946
- currentTime
947
- });
948
- assert(result.verified);
949
- assertEquals(result.signatureLabel, "valid");
950
- assertEquals(documentLoader.loaded, [valid]);
951
- documentLoader = createCountingKeyLoader();
952
- result = await verifyRequestDetailed(build([
953
- "old",
954
- "nobytes1",
955
- "nobytes2",
956
- "valid"
957
- ]), {
958
- documentLoader,
959
- contextLoader: mockDocumentLoader,
960
- currentTime
961
- });
962
- assertFalse(result.verified);
963
- assertEquals(documentLoader.loaded, []);
964
- });
965
- await t.step("rejects an invalid maxSignatures", async () => {
966
- const unsigned = new Request("https://example.com/inbox");
967
- for (const maxSignatures of [
968
- 0,
969
- -1,
970
- 1.5,
971
- NaN,
972
- 2 ** 53,
973
- -Infinity
974
- ]) {
975
- await assertRejects(() => verifyRequestDetailed(unsigned, { maxSignatures }), RangeError);
976
- await assertRejects(() => verifyRequest(unsigned, { maxSignatures }), RangeError);
977
- }
978
- await assertRejects(() => verifyRequestDetailed(unsigned, { maxSignatures: null }), RangeError);
979
- });
980
- });
981
- test("verifyRequestDetailed() [rfc9421] looks up each key once per request", async (t) => {
982
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
983
- const missing = (n) => `https://example.com/missing-${n}`;
984
- const valid = "https://example.com/key2";
985
- const forged = {
986
- keyId: valid,
987
- privateKey: rsaPrivateKey3
988
- };
989
- await t.step("signatures naming the same key", async () => {
990
- const request = await signRfc9421Many([
991
- forged,
992
- forged,
993
- valid
994
- ], currentTime);
995
- for (const keyCache of [void 0, new KvKeyCache(new MemoryKvStore(), ["pk"])]) {
996
- const documentLoader = createCountingKeyLoader();
997
- const result = await verifyRequestDetailed(request, {
998
- documentLoader,
999
- contextLoader: mockDocumentLoader,
1000
- currentTime,
1001
- keyCache
1002
- });
1003
- assert(result.verified);
1004
- assertEquals(result.signatureLabel, "sig3");
1005
- assertEquals(documentLoader.loaded, [valid]);
1006
- }
1007
- });
1008
- await t.step("signatures naming the same missing key", async () => {
1009
- const documentLoader = createCountingKeyLoader();
1010
- const result = await verifyRequestDetailed(await signRfc9421Many([
1011
- missing(1),
1012
- missing(1),
1013
- missing(1)
1014
- ], currentTime), {
1015
- documentLoader,
1016
- contextLoader: mockDocumentLoader,
1017
- currentTime
1018
- });
1019
- assertFalse(result.verified);
1020
- assertEquals(result.reason.type, "keyFetchError");
1021
- assertEquals(documentLoader.loaded, [missing(1)]);
1022
- });
1023
- await t.step("separate requests", async () => {
1024
- const request = await signRfc9421Many([valid], currentTime);
1025
- const documentLoader = createCountingKeyLoader();
1026
- const options = {
1027
- documentLoader,
1028
- contextLoader: mockDocumentLoader,
1029
- currentTime
1030
- };
1031
- assertEquals(await verifyRequest(request, options), rsaPublicKey2);
1032
- assertEquals(await verifyRequest(request, options), rsaPublicKey2);
1033
- assertEquals(documentLoader.loaded, [valid, valid]);
1034
- });
1035
- const createStaleKeyCache = () => {
1036
- const gets = [];
1037
- return {
1038
- keyCache: {
1039
- get(keyId) {
1040
- gets.push(keyId.href);
1041
- return Promise.resolve(keyId.href === valid ? rsaPublicKey1 : keyId.href === missing(1) ? null : void 0);
1042
- },
1043
- set: () => Promise.resolve(),
1044
- getFetchError: (keyId) => Promise.resolve(keyId.href === missing(1) ? { error: new FetchError(keyId, "Cached failure") } : void 0),
1045
- setFetchError: () => Promise.resolve()
1046
- },
1047
- gets
1048
- };
1049
- };
1050
- await t.step("refreshes a stale cached key once, only for its signature", async () => {
1051
- const { keyCache, gets } = createStaleKeyCache();
1052
- const documentLoader = createCountingKeyLoader();
1053
- const result = await verifyRequestDetailed(await signRfc9421Many([
1054
- missing(1),
1055
- missing(2),
1056
- forged,
1057
- valid
1058
- ], currentTime), {
1059
- documentLoader,
1060
- contextLoader: mockDocumentLoader,
1061
- currentTime,
1062
- keyCache,
1063
- maxSignatures: 4
1064
- });
1065
- assert(result.verified);
1066
- assertEquals(result.key, rsaPublicKey2);
1067
- assertEquals(result.signatureLabel, "sig4");
1068
- assertEquals(documentLoader.loaded, [missing(2), valid]);
1069
- assertEquals(gets, [
1070
- missing(1),
1071
- missing(2),
1072
- valid
1073
- ]);
1074
- });
1075
- await t.step("refreshes each stale cached key at most once", async () => {
1076
- const stale = (n) => `https://example.com/stale-${n}`;
1077
- const gets = [];
1078
- const keyCache = {
1079
- get(keyId) {
1080
- gets.push(keyId.href);
1081
- return Promise.resolve(rsaPublicKey1);
1082
- },
1083
- set: () => Promise.resolve()
1084
- };
1085
- const documentLoader = createCountingKeyLoader();
1086
- const result = await verifyRequestDetailed(await signRfc9421Many([
1087
- stale(1),
1088
- stale(2),
1089
- stale(1),
1090
- stale(4)
1091
- ], currentTime), {
1092
- documentLoader,
1093
- contextLoader: mockDocumentLoader,
1094
- currentTime,
1095
- keyCache
1096
- });
1097
- assertFalse(result.verified);
1098
- assertEquals(result.reason.type, "keyFetchError");
1099
- assertEquals("keyId" in result.reason ? result.reason.keyId?.href : void 0, stale(1));
1100
- assertEquals(documentLoader.loaded, [stale(1), stale(2)]);
1101
- assertEquals(gets, [stale(1), stale(2)]);
1102
- });
1103
- await t.step("does not refresh a cached key for other failures", async () => {
1104
- const [input] = Object.values(splitRfc9421Header((await signRfc9421Many([valid], currentTime)).headers.get("Signature-Input")));
1105
- const withAlg = (alg) => /;alg="[^"]*"/.test(input) ? input.replace(/;alg="[^"]*"/, `;alg="${alg}"`) : `${input};alg="${alg}"`;
1106
- for (const signatureInput of [withAlg("unknown"), input.replace(/^sig1=\([^)]*\)/, "sig1=(\"@unsupported\")")]) {
1107
- const request = await signRfc9421Many([valid], currentTime);
1108
- request.headers.set("Signature-Input", signatureInput);
1109
- const { keyCache } = createStaleKeyCache();
1110
- const documentLoader = createCountingKeyLoader();
1111
- assertEquals(await verifyRequest(request, {
1112
- documentLoader,
1113
- contextLoader: mockDocumentLoader,
1114
- currentTime,
1115
- keyCache
1116
- }), null, signatureInput);
1117
- assertEquals(documentLoader.loaded, [], signatureInput);
1118
- }
1119
- });
1120
- await t.step("refreshes a cached key of another algorithm family", async () => {
1121
- const keyId = ed25519PublicKey.id.href;
1122
- const request = await signRfc9421Many([keyId], currentTime);
1123
- const input = request.headers.get("Signature-Input");
1124
- request.headers.set("Signature-Input", /;alg="[^"]*"/.test(input) ? input.replace(/;alg="[^"]*"/, ";alg=\"ed25519\"") : `${input};alg="ed25519"`);
1125
- const { sig1 } = parseRfc9421SignatureInput(request.headers.get("Signature-Input"));
1126
- const signature = await crypto.subtle.sign("Ed25519", ed25519PrivateKey, new TextEncoder().encode(createRfc9421SignatureBase(request, sig1.components, sig1.parameters)));
1127
- request.headers.set("Signature", `sig1=:${encodeBase64(new Uint8Array(signature))}:`);
1128
- const loaded = [];
1129
- const result = await verifyRequestDetailed(request, {
1130
- documentLoader: (url, options) => {
1131
- loaded.push(url);
1132
- return mockDocumentLoader(url, options);
1133
- },
1134
- contextLoader: mockDocumentLoader,
1135
- currentTime,
1136
- keyCache: {
1137
- get: (id) => Promise.resolve(id.href === keyId ? rsaPublicKey1 : void 0),
1138
- set: () => Promise.resolve()
1139
- }
1140
- });
1141
- assert(result.verified);
1142
- assertEquals(result.key.id?.href, keyId);
1143
- assertEquals(loaded.length, 1);
1144
- });
1145
- });
1146
- test("verifyRequest() [rfc9421] manual POST verification", async () => {
1147
- const currentTimestamp = 1709626184;
1148
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
1149
- const postBody = "Test content for signature verification";
1150
- const signedPostRequest = await signRequest(new Request("https://example.com/api/resource", {
1151
- method: "POST",
1152
- body: postBody,
1153
- headers: {
1154
- "Content-Type": "text/plain; charset=utf-8",
1155
- "Accept": "application/json",
1156
- "Host": "example.com",
1157
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
1158
- }
1159
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
1160
- spec: "rfc9421",
1161
- currentTime
1162
- });
1163
- const signedKey = await verifyRequest(signedPostRequest, {
1164
- spec: "rfc9421",
1165
- documentLoader: mockDocumentLoader,
1166
- contextLoader: mockDocumentLoader,
1167
- currentTime
1168
- });
1169
- assertExists(signedKey);
1170
- assertEquals(signedKey, rsaPublicKey2);
1171
- assertExists(signedKey.publicKey);
1172
- assertEquals(await exportJwk(signedKey.publicKey), await exportJwk(rsaPublicKey2.publicKey));
1173
- const signatureInputHeader = signedPostRequest.headers.get("Signature-Input") || "";
1174
- const signatureHeader = signedPostRequest.headers.get("Signature") || "";
1175
- const parsedInput = parseRfc9421SignatureInput(signatureInputHeader);
1176
- const parsedSignature = parseRfc9421Signature(signatureHeader);
1177
- assertExists(parsedInput.sig1, "Should have a valid signature input");
1178
- assertExists(parsedSignature.sig1, "Should have a valid signature value");
1179
- assertEquals(parsedInput.sig1.keyId, "https://example.com/key2", "Signature should have the correct key ID");
1180
- assertEquals(parsedInput.sig1.created, currentTimestamp, "Signature should have the correct timestamp");
1181
- const signatureBase = createRfc9421SignatureBase(new Request("https://example.com/api/resource", {
1182
- method: "POST",
1183
- body: postBody,
1184
- headers: new Headers(signedPostRequest.headers)
1185
- }), parsedInput.sig1.components, parsedInput.sig1.parameters);
1186
- assert(await crypto.subtle.verify("RSASSA-PKCS1-v1_5", rsaPublicKey2.publicKey, parsedSignature.sig1.slice(), new TextEncoder().encode(signatureBase)), "Manual verification of POST signature should succeed");
1187
- });
1188
- test("verifyRequest() [rfc9421] error cases and edge cases", async () => {
1189
- const currentTimestamp = 1709626184;
1190
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
1191
- const signedRequest = await signRequest(new Request("https://example.com/api/resource", {
1192
- method: "GET",
1193
- headers: {
1194
- "Accept": "application/json",
1195
- "Host": "example.com",
1196
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
1197
- }
1198
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
1199
- spec: "rfc9421",
1200
- currentTime
1201
- });
1202
- const validSignatureInput = signedRequest.headers.get("Signature-Input") || "";
1203
- const validSignature = signedRequest.headers.get("Signature") || "";
1204
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1205
- method: "GET",
1206
- headers: new Headers({
1207
- "Accept": "application/json",
1208
- "Host": "example.com",
1209
- "Signature": validSignature
1210
- })
1211
- }), {
1212
- contextLoader: mockDocumentLoader,
1213
- documentLoader: mockDocumentLoader,
1214
- spec: "rfc9421"
1215
- }), null, "Should fail verification when Signature-Input header is missing");
1216
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1217
- method: "GET",
1218
- headers: new Headers({
1219
- "Accept": "application/json",
1220
- "Host": "example.com",
1221
- "Signature-Input": validSignatureInput
1222
- })
1223
- }), {
1224
- contextLoader: mockDocumentLoader,
1225
- documentLoader: mockDocumentLoader,
1226
- spec: "rfc9421"
1227
- }), null, "Should fail verification when Signature header is missing");
1228
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1229
- method: "GET",
1230
- headers: new Headers({
1231
- "Accept": "application/json",
1232
- "Host": "example.com",
1233
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1234
- "Signature-Input": validSignatureInput,
1235
- "Signature": "sig1=:AAAAAA==:"
1236
- })
1237
- }), {
1238
- contextLoader: mockDocumentLoader,
1239
- documentLoader: mockDocumentLoader,
1240
- spec: "rfc9421"
1241
- }), null, "Should fail verification when signature is tampered");
1242
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1243
- method: "GET",
1244
- headers: new Headers({
1245
- "Accept": "application/json",
1246
- "Host": "example.com",
1247
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1248
- "Signature-Input": validSignatureInput,
1249
- "Signature": validSignature
1250
- })
1251
- }), {
1252
- contextLoader: mockDocumentLoader,
1253
- documentLoader: mockDocumentLoader,
1254
- spec: "rfc9421",
1255
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date(1712218184 * 1e3)).toISOString()}`),
1256
- timeWindow: { hours: 1 }
1257
- }), null, "Should fail verification when signature timestamp is too old");
1258
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1259
- method: "GET",
1260
- headers: new Headers({
1261
- "Accept": "application/json",
1262
- "Host": "example.com",
1263
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1264
- "Signature-Input": validSignatureInput,
1265
- "Signature": validSignature
1266
- })
1267
- }), {
1268
- contextLoader: mockDocumentLoader,
1269
- documentLoader: mockDocumentLoader,
1270
- spec: "rfc9421",
1271
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date((currentTimestamp - 2592e3) * 1e3)).toISOString()}`),
1272
- timeWindow: { hours: 1 }
1273
- }), null, "Should fail verification when signature timestamp is in the future");
1274
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1275
- method: "GET",
1276
- headers: new Headers({
1277
- "Accept": "application/json",
1278
- "Host": "example.com",
1279
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1280
- "Signature-Input": validSignatureInput,
1281
- "Signature": validSignature
1282
- })
1283
- }), {
1284
- contextLoader: mockDocumentLoader,
1285
- documentLoader: mockDocumentLoader,
1286
- spec: "rfc9421",
1287
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date(1741162184 * 1e3)).toISOString()}`),
1288
- timeWindow: false
1289
- }), rsaPublicKey2, "Should verify signature when time checking is disabled");
1290
- const freshSignedPostRequest = await signRequest(new Request("https://example.com/api/resource", {
1291
- method: "POST",
1292
- body: "Test content for signature verification",
1293
- headers: {
1294
- "Content-Type": "text/plain; charset=utf-8",
1295
- "Accept": "application/json",
1296
- "Host": "example.com",
1297
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
1298
- }
1299
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
1300
- spec: "rfc9421",
1301
- currentTime
1302
- });
1303
- const postSignatureInput = freshSignedPostRequest.headers.get("Signature-Input") || "";
1304
- const postSignature = freshSignedPostRequest.headers.get("Signature") || "";
1305
- const postContentDigest = freshSignedPostRequest.headers.get("Content-Digest") || "";
1306
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1307
- method: "POST",
1308
- body: "This content won't match the digest",
1309
- headers: new Headers({
1310
- "Accept": "application/json",
1311
- "Host": "example.com",
1312
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1313
- "Signature-Input": postSignatureInput,
1314
- "Signature": postSignature,
1315
- "Content-Digest": postContentDigest
1316
- })
1317
- }), {
1318
- contextLoader: mockDocumentLoader,
1319
- documentLoader: mockDocumentLoader,
1320
- spec: "rfc9421",
1321
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date(currentTimestamp * 1e3)).toISOString()}`)
1322
- }), null, "Should fail verification with invalid Content-Digest");
1323
- const testRequest = new Request("https://example.com/", { headers: new Headers({
1324
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1325
- "Host": "example.com",
1326
- "Signature-Input": `sig1=("@method" "@target-uri" "host" "date");keyid="https://example.com/key";alg="rsa-v1_5-sha256";created=1709626184`,
1327
- "Signature": `sig1=:YXNkZmprc2RmaGprc2RoZmprc2hkZmtqaHNkZg==:`
1328
- }) });
1329
- const parsedInput = parseRfc9421SignatureInput(testRequest.headers.get("Signature-Input") || "");
1330
- assertExists(parsedInput.sig1);
1331
- assertEquals(parsedInput.sig1.keyId, "https://example.com/key");
1332
- assertEquals(parsedInput.sig1.alg, "rsa-v1_5-sha256");
1333
- assertEquals(parsedInput.sig1.created, 1709626184);
1334
- assertEquals(parsedInput.sig1.components, [
1335
- {
1336
- value: "@method",
1337
- params: {}
1338
- },
1339
- {
1340
- value: "@target-uri",
1341
- params: {}
1342
- },
1343
- {
1344
- value: "host",
1345
- params: {}
1346
- },
1347
- {
1348
- value: "date",
1349
- params: {}
1350
- }
1351
- ]);
1352
- const parsedSig = parseRfc9421Signature(testRequest.headers.get("Signature") || "");
1353
- assertExists(parsedSig.sig1);
1354
- assert(new TextDecoder().decode(parsedSig.sig1).length > 0, "Signature base64 should decode to non-empty string");
1355
- const complexParsedInput = parseRfc9421SignatureInput("sig1=(\"@method\" \"@target-uri\" \"host\" \"content-type\" \"value with \\\"quotes\\\" and spaces\");keyid=\"https://example.com/key with spaces\";alg=\"rsa-v1_5-sha256\";created=1709626184");
1356
- assertExists(complexParsedInput.sig1);
1357
- assertEquals(complexParsedInput.sig1.keyId, "https://example.com/key with spaces");
1358
- assertEquals(complexParsedInput.sig1.alg, "rsa-v1_5-sha256");
1359
- assertEquals(complexParsedInput.sig1.created, 1709626184);
1360
- assert(complexParsedInput.sig1.components.some((c) => c.value === "content-type"));
1361
- assert(complexParsedInput.sig1.components.some((c) => c.value === "value with \"quotes\" and spaces"));
1362
- const multiSigRequest = new Request("https://example.com/", { headers: new Headers({
1363
- "Signature-Input": `sig1=("@method");keyid="key1";alg="rsa-v1_5-sha256";created=1709626184,sig2=("@target-uri");keyid="key2";alg="rsa-pss-sha512";created=1709626185`,
1364
- "Signature": `sig1=:AQIDBA==:,sig2=:Zm9vYmFy:`
1365
- }) });
1366
- const multiParsedInput = parseRfc9421SignatureInput(multiSigRequest.headers.get("Signature-Input") || "");
1367
- assertEquals(Object.keys(multiParsedInput).length, 2, "Should parse multiple signatures");
1368
- assertEquals(multiParsedInput.sig1.keyId, "key1");
1369
- assertEquals(multiParsedInput.sig2.keyId, "key2");
1370
- assertEquals(multiParsedInput.sig1.alg, "rsa-v1_5-sha256");
1371
- assertEquals(multiParsedInput.sig2.alg, "rsa-pss-sha512");
1372
- const multiParsedSig = parseRfc9421Signature(multiSigRequest.headers.get("Signature") || "");
1373
- assertEquals(Object.keys(multiParsedSig).length, 2, "Should parse multiple signature values");
1374
- const parsedInvalidInput = parseRfc9421SignatureInput("this is not a valid signature-input format");
1375
- assertEquals(Object.keys(parsedInvalidInput).length, 0, "Should handle invalid Signature-Input format");
1376
- const parsedInvalidSig = parseRfc9421Signature("this is not a valid signature format");
1377
- assertEquals(Object.keys(parsedInvalidSig).length, 0, "Should handle invalid Signature format");
1378
- const parsedInvalidBase64 = parseRfc9421Signature("sig1=:!@#$%%^&*():");
1379
- assertEquals(Object.keys(parsedInvalidBase64).length, 0, "Should handle invalid base64 in signature");
1380
- assertEquals(await verifyRequest(new Request("https://example.com/api/resource", {
1381
- method: "GET",
1382
- headers: new Headers({
1383
- "Accept": "application/json",
1384
- "Host": "example.com",
1385
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT",
1386
- "Signature-Input": `${validSignatureInput},sig2=("@method" "@target-uri" "host" "date");keyid="https://example.com/invalid-key";alg="rsa-v1_5-sha256";created=${currentTimestamp}`,
1387
- "Signature": `${validSignature},sig2=:AAAAAA==:`
1388
- })
1389
- }), {
1390
- contextLoader: mockDocumentLoader,
1391
- documentLoader: mockDocumentLoader,
1392
- spec: "rfc9421",
1393
- currentTime: Temporal.Instant.from(`${(/* @__PURE__ */ new Date(currentTimestamp * 1e3)).toISOString()}`)
1394
- }), rsaPublicKey2, "Should verify when at least one signature is valid");
1395
- });
1396
- test("verifyRequest() [rfc9421] test vector from Mastodon", async () => {
1397
- const signedRequest = new Request("https://www.example.com/activitypub/success", {
1398
- method: "GET",
1399
- headers: {
1400
- Host: "www.example.com",
1401
- "Signature-Input": "sig1=(\"@method\" \"@target-uri\");created=1703066400;keyid=\"https://remote.domain/users/bob#main-key\"",
1402
- Signature: "sig1=:WfM6q/qBqhUyqPUDt9metjadJGtLLpmMTBzk/t+R3byKe4/TGAXC6vBB/M6NsD5qv8GCmQGtisCMQxJQO0IGODGzi+Jv+eqDJ50agMVXNV6nUOzY44c4/XTPoI98qyx1oEMa4Hefy3vSYKq96iDVAc+RDLCMTeGP3wn9wizjD1SNmU0RZI1bTB+eCkywMP9mM5zXzUOYF+Qkuf+WdEpPR1XUGPlnqfdvPalcKVfaI/VThBjI91D/lmUGoa69x4EBEHM+aJmW6086e7/dVh+FndKkdGfXslZXFZKi2flTGQZgEWLn948SqAaJQROkJg8B14Sb1NONS1qZBhK3Mum8Pg==:"
1403
- }
1404
- });
1405
- const result = await verifyRequest(signedRequest, {
1406
- contextLoader: mockDocumentLoader,
1407
- documentLoader: mockDocumentLoader,
1408
- currentTime: Temporal.Instant.from("2023-12-20T10:00:00.0000Z"),
1409
- spec: "rfc9421"
1410
- });
1411
- assertExists(result);
1412
- assertExists(result.publicKey);
1413
- assertEquals(result, rsaPublicKey5);
1414
- assertEquals(await exportSpki(result.publicKey), await exportSpki(rsaPublicKey5.publicKey));
1415
- const result2 = await verifyRequest(signedRequest, {
1416
- contextLoader: mockDocumentLoader,
1417
- documentLoader: mockDocumentLoader,
1418
- currentTime: Temporal.Instant.from("2023-12-20T10:00:00.0000Z")
1419
- });
1420
- assertExists(result2);
1421
- assertExists(result2.publicKey);
1422
- assertEquals(result2, rsaPublicKey5);
1423
- assertEquals(await exportSpki(result2.publicKey), await exportSpki(rsaPublicKey5.publicKey));
1424
- });
1425
- test("doubleKnock() function with successful first attempt", async () => {
1426
- esm_default.spyGlobal();
1427
- let requestCount = 0;
1428
- let firstRequestSpec = null;
1429
- esm_default.post("https://example.com/inbox-accepts-rfc9421", (cl) => {
1430
- requestCount++;
1431
- const req = cl.request;
1432
- const signatureInputHeader = req.headers.get("Signature-Input");
1433
- const signatureHeader = req.headers.get("Signature");
1434
- if (signatureInputHeader && signatureHeader) {
1435
- firstRequestSpec = "rfc9421";
1436
- return new Response("", { status: 202 });
1437
- } else return new Response("Unauthorized", { status: 401 });
1438
- });
1439
- const request = new Request("https://example.com/inbox-accepts-rfc9421", {
1440
- method: "POST",
1441
- body: "Hello, world!",
1442
- headers: { "Content-Type": "text/plain" }
1443
- });
1444
- const specDeterminer = {
1445
- usedSpec: null,
1446
- determineSpec(_origin) {
1447
- return "rfc9421";
1448
- },
1449
- rememberSpec(_origin, spec) {
1450
- this.usedSpec = spec;
1451
- }
1452
- };
1453
- let loggedRequest;
1454
- const logFunction = (req) => {
1455
- loggedRequest = req;
1456
- };
1457
- assertEquals((await doubleKnock(request, {
1458
- keyId: rsaPublicKey2.id,
1459
- privateKey: rsaPrivateKey2
1460
- }, {
1461
- specDeterminer,
1462
- log: logFunction
1463
- })).status, 202, "Response status should be 202 Accepted");
1464
- assertEquals(requestCount, 1, "Only one request should have been made");
1465
- assertEquals(firstRequestSpec, "rfc9421", "First attempt should use RFC 9421");
1466
- assertEquals(specDeterminer.usedSpec, "rfc9421", "Spec should be remembered");
1467
- assertExists(loggedRequest, "Request should be logged");
1468
- assert(loggedRequest?.headers.has("Signature-Input"), "Logged request should have RFC 9421 Signature-Input header");
1469
- assert(loggedRequest?.headers.has("Signature"), "Logged request should have RFC 9421 Signature header");
1470
- esm_default.hardReset();
1471
- });
1472
- test("doubleKnock() function with fallback to draft-cavage", async () => {
1473
- esm_default.spyGlobal();
1474
- let requestCount = 0;
1475
- let firstSpec = null;
1476
- let secondSpec = null;
1477
- esm_default.post("https://example.com/inbox-accepts-draft-cavage", (cl) => {
1478
- const req = cl.request;
1479
- requestCount++;
1480
- if (req.headers.has("Signature-Input")) {
1481
- firstSpec = "rfc9421";
1482
- return new Response("Not Authorized", { status: 401 });
1483
- } else if (req.headers.has("Signature")) {
1484
- secondSpec = "draft-cavage-http-signatures-12";
1485
- return new Response("", { status: 202 });
1486
- } else return new Response("Bad Request", { status: 400 });
1487
- });
1488
- const request = new Request("https://example.com/inbox-accepts-draft-cavage", {
1489
- method: "POST",
1490
- body: "Test message for double-knocking",
1491
- headers: { "Content-Type": "text/plain" }
1492
- });
1493
- const specDeterminer = {
1494
- rememberedOrigin: null,
1495
- rememberedSpec: null,
1496
- determineSpec(_origin) {
1497
- return "rfc9421";
1498
- },
1499
- rememberSpec(origin, spec) {
1500
- this.rememberedOrigin = origin;
1501
- this.rememberedSpec = spec;
1502
- }
1503
- };
1504
- assertEquals((await doubleKnock(request, {
1505
- keyId: rsaPublicKey2.id,
1506
- privateKey: rsaPrivateKey2
1507
- }, { specDeterminer })).status, 202, "Response status should be 202 Accepted");
1508
- assertEquals(requestCount, 2, "Two requests should have been made");
1509
- assertEquals(firstSpec, "rfc9421", "First attempt should use RFC 9421");
1510
- assertEquals(secondSpec, "draft-cavage-http-signatures-12", "Second attempt should use draft-cavage");
1511
- assertEquals(specDeterminer.rememberedOrigin, "https://example.com", "Origin should be remembered");
1512
- assertEquals(specDeterminer.rememberedSpec, "draft-cavage-http-signatures-12", "Successful spec should be remembered");
1513
- esm_default.hardReset();
1514
- });
1515
- test("doubleKnock() function with redirect handling", async () => {
1516
- esm_default.spyGlobal();
1517
- const requestedUrls = [];
1518
- const responseCodes = [];
1519
- const validatedRedirects = [];
1520
- esm_default.post("https://example.com/redirect-endpoint", (cl) => {
1521
- requestedUrls.push(cl.url);
1522
- responseCodes.push(302);
1523
- return Response.redirect("https://example.com/final-endpoint", 302);
1524
- });
1525
- esm_default.post("https://example.com/final-endpoint", (cl) => {
1526
- requestedUrls.push(cl.url);
1527
- responseCodes.push(202);
1528
- return new Response("", { status: 202 });
1529
- });
1530
- assertEquals((await doubleKnock(new Request("https://example.com/redirect-endpoint", {
1531
- method: "POST",
1532
- body: "Test message that will be redirected",
1533
- headers: { "Content-Type": "text/plain" }
1534
- }), {
1535
- keyId: rsaPublicKey2.id,
1536
- privateKey: rsaPrivateKey2
1537
- }, { validateRedirect(url) {
1538
- validatedRedirects.push(url);
1539
- } })).status, 202, "Final response status should be 202 Accepted");
1540
- assertEquals(requestedUrls.length, 2, "Two URLs should have been requested");
1541
- assertEquals(requestedUrls[0], "https://example.com/redirect-endpoint", "First request should be to redirect-endpoint");
1542
- assertEquals(requestedUrls[1], "https://example.com/final-endpoint", "Second request should be to final-endpoint");
1543
- assertEquals(responseCodes, [302, 202], "Response status codes should match expected sequence");
1544
- assertEquals(validatedRedirects, ["https://example.com/final-endpoint"]);
1545
- esm_default.hardReset();
1546
- });
1547
- test("doubleKnock() validates redirects after signature fallback", async () => {
1548
- esm_default.spyGlobal();
1549
- let requestCount = 0;
1550
- let privateRequestCount = 0;
1551
- esm_default.post("https://example.com/redirect-after-fallback", (cl) => {
1552
- requestCount++;
1553
- if (cl.request.headers.has("Signature-Input")) return new Response("Unauthorized", { status: 401 });
1554
- return Response.redirect("http://localhost/private", 302);
1555
- });
1556
- esm_default.post("http://localhost/private", () => {
1557
- privateRequestCount++;
1558
- return new Response("", { status: 202 });
1559
- });
1560
- const request = new Request("https://example.com/redirect-after-fallback", {
1561
- method: "POST",
1562
- body: "Test message"
1563
- });
1564
- await assertRejects(() => doubleKnock(request, {
1565
- keyId: rsaPublicKey2.id,
1566
- privateKey: rsaPrivateKey2
1567
- }, { validateRedirect(url) {
1568
- throw new Error(`Disallowed redirect: ${url}`);
1569
- } }), Error, "Disallowed redirect: http://localhost/private");
1570
- assertEquals(requestCount, 2);
1571
- assertEquals(privateRequestCount, 0);
1572
- esm_default.hardReset();
1573
- });
1574
- test("doubleKnock() function with both specs rejected", async () => {
1575
- esm_default.spyGlobal();
1576
- let requestCount = 0;
1577
- const attempts = [];
1578
- esm_default.post("https://example.com/inbox-rejects-all", (cl) => {
1579
- const req = cl.request;
1580
- requestCount++;
1581
- if (req.headers.has("Signature-Input")) attempts.push("rfc9421");
1582
- else if (req.headers.has("Signature")) attempts.push("draft-cavage");
1583
- else attempts.push("unknown");
1584
- return new Response("Unauthorized", { status: 401 });
1585
- });
1586
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-rejects-all", {
1587
- method: "POST",
1588
- body: "Test message that will be rejected regardless of signature format",
1589
- headers: { "Content-Type": "text/plain" }
1590
- }), {
1591
- keyId: rsaPublicKey2.id,
1592
- privateKey: rsaPrivateKey2
1593
- })).status, 401, "Final response status should be 401 Unauthorized");
1594
- assertEquals(requestCount, 2, "Two requests should have been made");
1595
- assertEquals(attempts.length, 2, "Two signature attempts should have been made");
1596
- assertEquals(attempts[0], "rfc9421", "First attempt should use RFC 9421");
1597
- assertEquals(attempts[1], "draft-cavage", "Second attempt should use draft-cavage");
1598
- esm_default.hardReset();
1599
- });
1600
- test("doubleKnock() function with specDeterminer choosing draft-cavage first", async () => {
1601
- esm_default.spyGlobal();
1602
- let requestCount = 0;
1603
- let firstSpec = null;
1604
- esm_default.post("https://example.com/inbox-accepts-any", (cl) => {
1605
- const req = cl.request;
1606
- requestCount++;
1607
- if (req.headers.has("Signature-Input")) firstSpec = "rfc9421";
1608
- else if (req.headers.has("Signature")) firstSpec = "draft-cavage";
1609
- return new Response("", { status: 202 });
1610
- });
1611
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-accepts-any", {
1612
- method: "POST",
1613
- body: "Test message with draft-cavage preference",
1614
- headers: { "Content-Type": "text/plain" }
1615
- }), {
1616
- keyId: rsaPublicKey2.id,
1617
- privateKey: rsaPrivateKey2
1618
- }, { specDeterminer: {
1619
- determineSpec(_origin) {
1620
- return "draft-cavage-http-signatures-12";
1621
- },
1622
- rememberSpec(_origin, _spec) {}
1623
- } })).status, 202, "Response status should be 202 Accepted");
1624
- assertEquals(requestCount, 1, "Only one request should have been made");
1625
- assertEquals(firstSpec, "draft-cavage", "First attempt should use draft-cavage");
1626
- esm_default.hardReset();
1627
- });
1628
- test("doubleKnock() complex redirect chain test", async () => {
1629
- esm_default.spyGlobal();
1630
- const requestedUrls = [];
1631
- esm_default.post("https://example.com/redirect1", (cl) => {
1632
- requestedUrls.push(cl.url);
1633
- return Response.redirect("https://example.com/redirect2", 302);
1634
- });
1635
- esm_default.post("https://example.com/redirect2", (cl) => {
1636
- requestedUrls.push(cl.url);
1637
- return Response.redirect("https://example.com/redirect3", 307);
1638
- });
1639
- esm_default.post("https://example.com/redirect3", (cl) => {
1640
- requestedUrls.push(cl.url);
1641
- return Response.redirect("https://example.com/final", 301);
1642
- });
1643
- esm_default.post("https://example.com/final", (cl) => {
1644
- requestedUrls.push(cl.url);
1645
- return new Response("Success", { status: 200 });
1646
- });
1647
- const request = new Request("https://example.com/redirect1", {
1648
- method: "POST",
1649
- body: "Test message for redirect chain",
1650
- headers: { "Content-Type": "text/plain" }
1651
- });
1652
- const logs = [];
1653
- const logFunction = (req) => {
1654
- logs.push(req);
1655
- };
1656
- const response = await doubleKnock(request, {
1657
- keyId: rsaPublicKey2.id,
1658
- privateKey: rsaPrivateKey2
1659
- }, { log: logFunction });
1660
- assertEquals(response.status, 200, "Final response status should be 200 OK");
1661
- assertEquals(await response.text(), "Success", "Response body should be 'Success'");
1662
- assertEquals(requestedUrls.length, 4, "Four URLs should have been requested");
1663
- assertEquals(requestedUrls[0], "https://example.com/redirect1", "First request should be to redirect1");
1664
- assertEquals(requestedUrls[1], "https://example.com/redirect2", "Second request should be to redirect2");
1665
- assertEquals(requestedUrls[2], "https://example.com/redirect3", "Third request should be to redirect3");
1666
- assertEquals(requestedUrls[3], "https://example.com/final", "Fourth request should be to final");
1667
- assertEquals(logs.length, 4, "Four requests should have been logged");
1668
- for (const loggedReq of logs) assert(loggedReq.headers.has("Signature-Input") || loggedReq.headers.has("Signature"), "Each request should be signed with either RFC 9421 or draft-cavage");
1669
- esm_default.hardReset();
1670
- });
1671
- test("doubleKnock() throws on too many redirects", async () => {
1672
- esm_default.spyGlobal();
1673
- let requestCount = 0;
1674
- esm_default.post("begin:https://example.com/too-many-redirects/", (cl) => {
1675
- requestCount++;
1676
- const index = Number(cl.url.split("/").at(-1));
1677
- return Response.redirect(`https://example.com/too-many-redirects/${index + 1}`, 302);
1678
- });
1679
- const request = new Request("https://example.com/too-many-redirects/0", {
1680
- method: "POST",
1681
- body: "Redirect loop",
1682
- headers: { "Content-Type": "text/plain" }
1683
- });
1684
- await assertRejects(() => doubleKnock(request, {
1685
- keyId: rsaPublicKey2.id,
1686
- privateKey: rsaPrivateKey2
1687
- }), Error, "Too many redirections");
1688
- assertEquals(requestCount, 21);
1689
- esm_default.hardReset();
1690
- });
1691
- test("doubleKnock() respects maxRedirection option", async () => {
1692
- esm_default.spyGlobal();
1693
- let requestCount = 0;
1694
- esm_default.post("begin:https://example.com/custom-too-many-redirects/", (cl) => {
1695
- requestCount++;
1696
- const index = Number(cl.url.split("/").at(-1));
1697
- return Response.redirect(`https://example.com/custom-too-many-redirects/${index + 1}`, 302);
1698
- });
1699
- const request = new Request("https://example.com/custom-too-many-redirects/0", {
1700
- method: "POST",
1701
- body: "Redirect loop",
1702
- headers: { "Content-Type": "text/plain" }
1703
- });
1704
- await assertRejects(() => doubleKnock(request, {
1705
- keyId: rsaPublicKey2.id,
1706
- privateKey: rsaPrivateKey2
1707
- }, { maxRedirection: 1 }), Error, "Too many redirections");
1708
- assertEquals(requestCount, 2);
1709
- esm_default.hardReset();
1710
- });
1711
- test("doubleKnock() detects redirect loops", async () => {
1712
- esm_default.spyGlobal();
1713
- let requestCount = 0;
1714
- esm_default.post("https://example.com/redirect-loop-a", () => {
1715
- requestCount++;
1716
- return Response.redirect("https://example.com/redirect-loop-b", 302);
1717
- });
1718
- esm_default.post("https://example.com/redirect-loop-b", () => {
1719
- requestCount++;
1720
- return Response.redirect("https://example.com/redirect-loop-a", 302);
1721
- });
1722
- const request = new Request("https://example.com/redirect-loop-a", {
1723
- method: "POST",
1724
- body: "Redirect loop",
1725
- headers: { "Content-Type": "text/plain" }
1726
- });
1727
- await assertRejects(() => doubleKnock(request, {
1728
- keyId: rsaPublicKey2.id,
1729
- privateKey: rsaPrivateKey2
1730
- }), Error, "Redirect loop detected");
1731
- assertEquals(requestCount, 2);
1732
- esm_default.hardReset();
1733
- });
1734
- test("doubleKnock() retries idempotent request transport errors", async () => {
1735
- esm_default.spyGlobal();
1736
- try {
1737
- let requestCount = 0;
1738
- esm_default.get("https://example.com/flaky-document", () => {
1739
- requestCount++;
1740
- if (requestCount === 1) throw new TypeError("temporary DNS failure");
1741
- return new Response("Success", { status: 200 });
1742
- });
1743
- const response = await doubleKnock(new Request("https://example.com/flaky-document"), {
1744
- keyId: rsaPublicKey2.id,
1745
- privateKey: rsaPrivateKey2
1746
- });
1747
- assertEquals(response.status, 200);
1748
- assertEquals(await response.text(), "Success");
1749
- assertEquals(requestCount, 2);
1750
- } finally {
1751
- esm_default.hardReset();
1752
- }
1753
- });
1754
- test("doubleKnock() wraps repeated transport errors", async () => {
1755
- esm_default.spyGlobal();
1756
- try {
1757
- let requestCount = 0;
1758
- const failure = /* @__PURE__ */ new TypeError("DNS lookup failed");
1759
- esm_default.get("https://example.com/unreachable-document", () => {
1760
- requestCount++;
1761
- throw failure;
1762
- });
1763
- const request = new Request("https://example.com/unreachable-document");
1764
- const error = await assertRejects(() => doubleKnock(request, {
1765
- keyId: rsaPublicKey2.id,
1766
- privateKey: rsaPrivateKey2
1767
- }), FetchError, "DNS lookup failed");
1768
- assertEquals(error.url.href, "https://example.com/unreachable-document");
1769
- assertEquals(error.cause, failure);
1770
- assertEquals(requestCount, 2);
1771
- } finally {
1772
- esm_default.hardReset();
1773
- }
1774
- });
1775
- test("doubleKnock() does not retry non-idempotent transport errors", async () => {
1776
- esm_default.spyGlobal();
1777
- try {
1778
- let requestCount = 0;
1779
- const failure = /* @__PURE__ */ new TypeError("connection reset");
1780
- esm_default.post("https://example.com/flaky-inbox", () => {
1781
- requestCount++;
1782
- throw failure;
1783
- });
1784
- const request = new Request("https://example.com/flaky-inbox", {
1785
- method: "POST",
1786
- body: "Test activity content",
1787
- headers: { "Content-Type": "application/activity+json" }
1788
- });
1789
- const error = await assertRejects(() => doubleKnock(request, {
1790
- keyId: rsaPublicKey2.id,
1791
- privateKey: rsaPrivateKey2
1792
- }), FetchError, "connection reset");
1793
- assertEquals(error.url.href, "https://example.com/flaky-inbox");
1794
- assertEquals(error.cause, failure);
1795
- assertEquals(requestCount, 1);
1796
- } finally {
1797
- esm_default.hardReset();
1798
- }
1799
- });
1800
- test("doubleKnock() preserves Request signal abort reasons", async () => {
1801
- const controller = new AbortController();
1802
- const abortReason = "request aborted";
1803
- controller.abort(abortReason);
1804
- const request = new Request("https://example.com/request-abort", { signal: controller.signal });
1805
- assertEquals(await assertRejects(() => doubleKnock(request, {
1806
- keyId: rsaPublicKey2.id,
1807
- privateKey: rsaPrivateKey2
1808
- })), abortReason);
1809
- });
1810
- test("doubleKnock() preserves Request signal aborts during retry delay", async () => {
1811
- esm_default.spyGlobal();
1812
- try {
1813
- let requestCount = 0;
1814
- const controller = new AbortController();
1815
- const abortReason = "retry aborted";
1816
- esm_default.get("https://example.com/aborted-retry", () => {
1817
- requestCount++;
1818
- setTimeout(() => controller.abort(abortReason));
1819
- throw new TypeError("temporary DNS failure");
1820
- });
1821
- const request = new Request("https://example.com/aborted-retry", { signal: controller.signal });
1822
- assertEquals(await assertRejects(() => doubleKnock(request, {
1823
- keyId: rsaPublicKey2.id,
1824
- privateKey: rsaPrivateKey2
1825
- })), abortReason);
1826
- assertEquals(requestCount, 1);
1827
- } finally {
1828
- esm_default.hardReset();
1829
- }
1830
- });
1831
- test("doubleKnock() prefers Request aborts over transport errors", async () => {
1832
- esm_default.spyGlobal();
1833
- try {
1834
- let requestCount = 0;
1835
- const controller = new AbortController();
1836
- const abortReason = "transport aborted";
1837
- esm_default.get("https://example.com/abort-with-transport-error", () => {
1838
- requestCount++;
1839
- controller.abort(abortReason);
1840
- throw new TypeError("temporary DNS failure");
1841
- });
1842
- const request = new Request("https://example.com/abort-with-transport-error", { signal: controller.signal });
1843
- assertEquals(await assertRejects(() => doubleKnock(request, {
1844
- keyId: rsaPublicKey2.id,
1845
- privateKey: rsaPrivateKey2
1846
- })), abortReason);
1847
- assertEquals(requestCount, 1);
1848
- } finally {
1849
- esm_default.hardReset();
1850
- }
1851
- });
1852
- test("doubleKnock() async specDeterminer test", async () => {
1853
- esm_default.spyGlobal();
1854
- let requestCount = 0;
1855
- let specUsed = null;
1856
- esm_default.post("https://example.com/inbox-async-determiner", (cl) => {
1857
- const req = cl.request;
1858
- requestCount++;
1859
- if (req.headers.has("Signature-Input")) specUsed = "rfc9421";
1860
- else if (req.headers.has("Signature")) specUsed = "draft-cavage-http-signatures-12";
1861
- return new Response("", { status: 202 });
1862
- });
1863
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-async-determiner", {
1864
- method: "POST",
1865
- body: "Test message with async spec determiner",
1866
- headers: { "Content-Type": "text/plain" }
1867
- }), {
1868
- keyId: rsaPublicKey2.id,
1869
- privateKey: rsaPrivateKey2
1870
- }, { specDeterminer: {
1871
- async determineSpec(_origin) {
1872
- await new Promise((resolve) => setTimeout(resolve, 10));
1873
- return "draft-cavage-http-signatures-12";
1874
- },
1875
- async rememberSpec(_origin, _spec) {
1876
- await new Promise((resolve) => setTimeout(resolve, 10));
1877
- }
1878
- } })).status, 202, "Response status should be 202 Accepted");
1879
- assertEquals(requestCount, 1, "Only one request should have been made");
1880
- assertEquals(specUsed, "draft-cavage-http-signatures-12", "Should use spec from async determiner");
1881
- esm_default.hardReset();
1882
- });
1883
- const lifecycleIdentity = {
1884
- keyId: rsaPublicKey2.id,
1885
- privateKey: rsaPrivateKey2
1886
- };
1887
- test("doubleKnockScoped() observes each actual GET and HEAD transport retry", async (t) => {
1888
- for (const method of ["GET", "HEAD"]) await t.step(method, async () => {
1889
- const url = "https://example.com/transport-observation";
1890
- const observed = [];
1891
- let submissions = 0;
1892
- let closes = 0;
1893
- assertEquals(await doubleKnockScoped(new Request(url, { method }), {
1894
- keyId: rsaPublicKey2.id,
1895
- privateKey: rsaPrivateKey2
1896
- }, {}, () => Promise.resolve({
1897
- url: new URL(url),
1898
- fetch() {
1899
- submissions++;
1900
- return submissions === 1 ? Promise.reject(/* @__PURE__ */ new TypeError("temporary failure")) : Promise.resolve(new Response(null, { status: 202 }));
1901
- },
1902
- close() {
1903
- closes++;
1904
- return Promise.resolve();
1905
- }
1906
- }), (response) => Promise.resolve(response.status), {
1907
- fetch(request, submit) {
1908
- observed.push(request);
1909
- return submit();
1910
- },
1911
- response() {},
1912
- error() {
1913
- throw new Error("transport retry must not be a local failure");
1914
- }
1915
- }), 202);
1916
- assertEquals(submissions, 2);
1917
- assertEquals(observed.length, 2);
1918
- assert(observed[0] === observed[1], "transport retry reuses the signed request");
1919
- assertEquals(observed[0].method, method);
1920
- assertEquals(closes, 1);
1921
- });
1922
- });
1923
- test("doubleKnockScoped() keeps challenge retries and fallback in the validated hop", async () => {
1924
- const url = "https://example.com/lifecycle/challenge-fallback";
1925
- const hops = recordHops((_, index) => index === 1 ? {
1926
- status: 401,
1927
- headers: { "Accept-Signature": "challenge=(\"@method\");nonce=\"challenge-nonce\"" },
1928
- body: "Challenge"
1929
- } : index === 2 ? {
1930
- status: 401,
1931
- body: "Unauthorized"
1932
- } : {
1933
- status: 202,
1934
- body: "Accepted"
1935
- });
1936
- assertEquals(await doubleKnockScoped(new Request(url, {
1937
- method: "POST",
1938
- body: "activity"
1939
- }), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), "Accepted");
1940
- assertEquals(hops.events, [
1941
- `open ${url}`,
1942
- `fetch #1 ${url}`,
1943
- "cancel #1",
1944
- `fetch #2 ${url}`,
1945
- "cancel #2",
1946
- `fetch #3 ${url}`,
1947
- "consumed #3",
1948
- `close ${url}`
1949
- ]);
1950
- assertStringIncludes(hops.requests[1].headers.get("Signature-Input"), "nonce=\"challenge-nonce\"");
1951
- assertFalse(hops.requests[2].headers.has("Signature-Input"));
1952
- hops.assertInvariants();
1953
- });
1954
- test("doubleKnockScoped() reopens the session after challenge redirects", async () => {
1955
- const url = "https://example.com/lifecycle/challenge-redirect";
1956
- const next = "https://other.example/lifecycle/final";
1957
- const validated = [];
1958
- const hops = recordHops((_, index) => index === 1 ? {
1959
- status: 401,
1960
- headers: { "Accept-Signature": "challenge=(\"@method\");created" },
1961
- body: "Challenge"
1962
- } : index === 2 ? {
1963
- status: 307,
1964
- headers: { Location: next },
1965
- body: "Redirect"
1966
- } : {
1967
- status: 200,
1968
- body: "Done"
1969
- });
1970
- assertEquals(await doubleKnockScoped(new Request(url, {
1971
- method: "POST",
1972
- body: "activity"
1973
- }), lifecycleIdentity, { validateRedirect: (target) => {
1974
- validated.push(target);
1975
- } }, hops.openHop, (response) => response.text()), "Done");
1976
- assertEquals(validated, [next]);
1977
- assertEquals(hops.events, [
1978
- `open ${url}`,
1979
- `fetch #1 ${url}`,
1980
- "cancel #1",
1981
- `fetch #2 ${url}`,
1982
- "cancel #2",
1983
- `close ${url}`,
1984
- `open ${next}`,
1985
- `fetch #3 ${next}`,
1986
- "consumed #3",
1987
- `close ${next}`
1988
- ]);
1989
- assertEquals(await hops.requests[2].text(), "activity");
1990
- hops.assertInvariants();
1991
- });
1992
- test("doubleKnockScoped() preserves maxRedirection across challenge redirects", async (t) => {
1993
- for (const maxRedirection of [0, 1]) await t.step(`limit ${maxRedirection}`, async () => {
1994
- const url = "https://example.com/lifecycle/challenge-limit";
1995
- const hops = recordHops((request, index) => index % 2 === 1 ? {
1996
- status: 401,
1997
- headers: { "Accept-Signature": "challenge=(\"@method\");created" },
1998
- body: "Challenge"
1999
- } : {
2000
- status: 307,
2001
- headers: { Location: `${request.url}/next` },
2002
- body: "Redirect"
2003
- });
2004
- await assertRejects(() => doubleKnockScoped(new Request(url, {
2005
- method: "POST",
2006
- body: "activity"
2007
- }), lifecycleIdentity, { maxRedirection }, hops.openHop, (response) => response.text()), FetchError, `Too many redirections (${maxRedirection + 1})`);
2008
- assertEquals(hops.requests.length, 2 * (maxRedirection + 1));
2009
- assertEquals(hops.events.filter((event) => event.startsWith("open ")).length, maxRedirection + 1);
2010
- assertEquals(hops.events.filter((event) => event.startsWith("cancel #")).length, hops.requests.length);
2011
- hops.assertInvariants();
2012
- });
2013
- });
2014
- test("doubleKnockScoped() detects loops after challenge redirects", async () => {
2015
- const url = "https://example.com/lifecycle/challenge-loop";
2016
- const hops = recordHops((_, index) => index === 1 ? {
2017
- status: 401,
2018
- headers: { "Accept-Signature": "challenge=(\"@method\");created" },
2019
- body: "Challenge"
2020
- } : {
2021
- status: 307,
2022
- headers: { Location: url },
2023
- body: "Redirect"
2024
- });
2025
- await assertRejects(() => doubleKnockScoped(new Request(url, {
2026
- method: "POST",
2027
- body: "activity"
2028
- }), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), FetchError, "Redirect loop detected");
2029
- assertEquals(hops.requests.length, 2);
2030
- assertEquals(hops.events, [
2031
- `open ${url}`,
2032
- `fetch #1 ${url}`,
2033
- "cancel #1",
2034
- `fetch #2 ${url}`,
2035
- "cancel #2",
2036
- `close ${url}`
2037
- ]);
2038
- hops.assertInvariants();
2039
- });
2040
- test("doubleKnockScoped() closes the session when aborted while determining the spec", async () => {
2041
- const url = "https://example.com/lifecycle/aborted-spec";
2042
- const hops = recordHops(() => ({
2043
- status: 202,
2044
- body: "Accepted"
2045
- }));
2046
- const controller = new AbortController();
2047
- const reason = /* @__PURE__ */ new Error("spec determination aborted");
2048
- assertEquals(await assertRejects(() => doubleKnockScoped(new Request(url, {
2049
- method: "POST",
2050
- body: "activity"
2051
- }), lifecycleIdentity, {
2052
- signal: controller.signal,
2053
- specDeterminer: {
2054
- determineSpec() {
2055
- controller.abort(reason);
2056
- return Promise.resolve("rfc9421");
2057
- },
2058
- rememberSpec: () => Promise.resolve()
2059
- }
2060
- }, hops.openHop, (response) => response.text()), Error, "spec determination aborted"), reason);
2061
- assertEquals(hops.events, [`open ${url}`, `close ${url}`]);
2062
- assertEquals(hops.requests, []);
2063
- hops.assertInvariants();
2064
- });
2065
- test("doubleKnockScoped() retries another spec on the same hop", async () => {
2066
- const url = "https://example.com/lifecycle/retry";
2067
- const hops = recordHops((_, index) => index === 1 ? {
2068
- status: 401,
2069
- body: "Unauthorized"
2070
- } : {
2071
- status: 202,
2072
- body: "Accepted"
2073
- });
2074
- assertEquals(await doubleKnockScoped(new Request(url, {
2075
- method: "POST",
2076
- body: "activity"
2077
- }), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), "Accepted");
2078
- assertEquals(hops.events, [
2079
- `open ${url}`,
2080
- `fetch #1 ${url}`,
2081
- "cancel #1",
2082
- `fetch #2 ${url}`,
2083
- "consumed #2",
2084
- `close ${url}`
2085
- ]);
2086
- assertEquals(hops.requests.map((r) => r.headers.has("Signature-Input")), [true, false]);
2087
- hops.assertInvariants();
2088
- });
2089
- test("doubleKnockScoped() closes the retried hop before a redirect", async () => {
2090
- const url = "https://example.com/lifecycle/retry-redirect";
2091
- const next = "https://example.com/lifecycle/final";
2092
- const hops = recordHops((_, index) => index === 1 ? {
2093
- status: 401,
2094
- body: "Unauthorized"
2095
- } : index === 2 ? {
2096
- status: 302,
2097
- headers: { Location: next },
2098
- body: "Found"
2099
- } : {
2100
- status: 200,
2101
- body: "Done"
2102
- });
2103
- assertEquals(await doubleKnockScoped(new Request(url, {
2104
- method: "POST",
2105
- body: "activity"
2106
- }), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), "Done");
2107
- assertEquals(hops.events, [
2108
- `open ${url}`,
2109
- `fetch #1 ${url}`,
2110
- "cancel #1",
2111
- `fetch #2 ${url}`,
2112
- "cancel #2",
2113
- `close ${url}`,
2114
- `open ${next}`,
2115
- `fetch #3 ${next}`,
2116
- "consumed #3",
2117
- `close ${next}`
2118
- ]);
2119
- assertEquals(await hops.requests[2].text(), "activity");
2120
- hops.assertInvariants();
2121
- });
2122
- test("doubleKnockScoped() retries transport errors on the same hop", async (t) => {
2123
- await t.step("GET", async () => {
2124
- const url = "https://example.com/lifecycle/flaky";
2125
- const hops = recordHops((_, index) => {
2126
- if (index === 1) throw new TypeError("connection reset");
2127
- return { body: "Success" };
2128
- });
2129
- assertEquals(await doubleKnockScoped(new Request(url), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), "Success");
2130
- assertEquals(hops.events, [
2131
- `open ${url}`,
2132
- `fetch #1 ${url}`,
2133
- `fetch #2 ${url}`,
2134
- "consumed #2",
2135
- `close ${url}`
2136
- ]);
2137
- hops.assertInvariants();
2138
- });
2139
- await t.step("POST", async () => {
2140
- const url = "https://example.com/lifecycle/flaky-inbox";
2141
- const hops = recordHops(() => {
2142
- throw new TypeError("connection reset");
2143
- });
2144
- await assertRejects(() => doubleKnockScoped(new Request(url, {
2145
- method: "POST",
2146
- body: "activity"
2147
- }), lifecycleIdentity, {}, hops.openHop, (response) => response.text()), FetchError);
2148
- assertEquals(hops.events, [
2149
- `open ${url}`,
2150
- `fetch #1 ${url}`,
2151
- `close ${url}`
2152
- ]);
2153
- hops.assertInvariants();
2154
- });
2155
- });
2156
- async function captureLogs(fn) {
2157
- const records = [];
2158
- await configure({
2159
- sinks: { buffer: (record) => records.push(record) },
2160
- loggers: [{
2161
- category: "fedify",
2162
- sinks: ["buffer"],
2163
- lowestLevel: "debug"
2164
- }, {
2165
- category: ["logtape", "meta"],
2166
- sinks: []
2167
- }],
2168
- reset: true
2169
- });
2170
- try {
2171
- await fn();
2172
- await new Promise((resolve) => setTimeout(resolve, 0));
2173
- } finally {
2174
- await reset();
2175
- }
2176
- return records;
2177
- }
2178
- test("doubleKnockScoped() logs a redirect body failing to cancel and follows the redirect", async () => {
2179
- const url = "https://example.com/lifecycle/cancel-failure";
2180
- const next = "https://example.com/lifecycle/cancel-failure-final";
2181
- const hops = recordHops((_, index) => index === 1 ? {
2182
- status: 302,
2183
- headers: { Location: next },
2184
- body: "Found",
2185
- failCancel: true
2186
- } : {
2187
- status: 200,
2188
- body: "Done"
2189
- });
2190
- let result;
2191
- const records = await captureLogs(async () => {
2192
- result = await doubleKnockScoped(new Request(url), lifecycleIdentity, {}, hops.openHop, (response) => response.text());
2193
- });
2194
- assertEquals(result, "Done");
2195
- assertEquals(hops.events, [
2196
- `open ${url}`,
2197
- `fetch #1 ${url}`,
2198
- "cancel #1",
2199
- `close ${url}`,
2200
- `open ${next}`,
2201
- `fetch #2 ${next}`,
2202
- "consumed #2",
2203
- `close ${next}`
2204
- ]);
2205
- const failures = records.filter((r) => r.rawMessage === "Failed to cancel the response body from {url}: {error}");
2206
- assertEquals(failures.map((r) => [r.level, r.properties.url]), [["debug", url]]);
2207
- assertEquals(failures[0].properties.error.message, "cancel #1 failed");
2208
- hops.assertInvariants();
2209
- });
2210
- test("doubleKnockScoped() is not blocked by a body cancellation that never settles", async () => {
2211
- const url = "https://example.com/lifecycle/hanging-cancel";
2212
- const next = "https://example.com/lifecycle/hanging-cancel-final";
2213
- const hops = recordHops((_, index) => index === 1 ? {
2214
- status: 401,
2215
- body: "Unauthorized",
2216
- hangCancel: true
2217
- } : index === 2 ? {
2218
- status: 302,
2219
- headers: { Location: next },
2220
- body: "Found",
2221
- hangCancel: true
2222
- } : {
2223
- status: 200,
2224
- body: "Done",
2225
- hangCancel: true
2226
- });
2227
- assertEquals(await doubleKnockScoped(new Request(url, {
2228
- method: "POST",
2229
- body: "activity"
2230
- }), lifecycleIdentity, {}, hops.openHop, (response) => Promise.resolve(response.status)), 200);
2231
- assertEquals(hops.events, [
2232
- `open ${url}`,
2233
- `fetch #1 ${url}`,
2234
- "cancel #1",
2235
- `fetch #2 ${url}`,
2236
- "cancel #2",
2237
- `close ${url}`,
2238
- `open ${next}`,
2239
- `fetch #3 ${next}`,
2240
- "cancel #3 by close",
2241
- `close ${next}`
2242
- ]);
2243
- hops.assertInvariants();
2244
- });
2245
- test("doubleKnockScoped() completes with responses cloned by fetch-mock", async () => {
2246
- esm_default.spyGlobal();
2247
- try {
2248
- let attempts = 0;
2249
- esm_default.post("https://example.com/tee/redirect", () => {
2250
- attempts++;
2251
- return attempts === 1 ? new Response("Unauthorized", { status: 401 }) : new Response("Found", {
2252
- status: 302,
2253
- headers: { Location: "https://example.com/tee/final" }
2254
- });
2255
- });
2256
- esm_default.post("https://example.com/tee/final", () => new Response("Accepted", { status: 202 }));
2257
- const request = () => new Request("https://example.com/tee/redirect", {
2258
- method: "POST",
2259
- body: "activity"
2260
- });
2261
- assertEquals(await doubleKnockScoped(request(), lifecycleIdentity, {}, openDirectFetch, (response) => Promise.resolve(response.status)), 202);
2262
- assertEquals(attempts, 2);
2263
- attempts = 0;
2264
- const response = await doubleKnock(request(), lifecycleIdentity);
2265
- assertEquals(response.status, 202);
2266
- assertEquals(await response.text(), "Accepted");
2267
- assertEquals(attempts, 2);
2268
- } finally {
2269
- esm_default.hardReset();
2270
- }
2271
- });
2272
- test("doubleKnockScoped() closes the session when consuming fails", async (t) => {
2273
- const url = "https://example.com/lifecycle/consume";
2274
- await t.step("exception", async () => {
2275
- const hops = recordHops(() => ({ body: "x".repeat(1024) }));
2276
- const error = /* @__PURE__ */ new Error("consume failed");
2277
- await assertRejects(() => doubleKnockScoped(new Request(url), lifecycleIdentity, {}, hops.openHop, async (response) => {
2278
- const reader = response.body.getReader();
2279
- await reader.read();
2280
- reader.releaseLock();
2281
- throw error;
2282
- }), Error, "consume failed");
2283
- assertEquals(hops.events, [
2284
- `open ${url}`,
2285
- `fetch #1 ${url}`,
2286
- "cancel #1 by close",
2287
- `close ${url}`
2288
- ]);
2289
- hops.assertInvariants();
2290
- });
2291
- await t.step("abort", async () => {
2292
- const hops = recordHops(() => ({ body: "Success" }));
2293
- const controller = new AbortController();
2294
- const reason = /* @__PURE__ */ new Error("aborted while consuming");
2295
- assert(await assertRejects(() => doubleKnockScoped(new Request(url), lifecycleIdentity, { signal: controller.signal }, hops.openHop, () => {
2296
- controller.abort(reason);
2297
- controller.signal.throwIfAborted();
2298
- return Promise.resolve();
2299
- })) === reason);
2300
- assertEquals(hops.events, [
2301
- `open ${url}`,
2302
- `fetch #1 ${url}`,
2303
- "cancel #1 by close",
2304
- `close ${url}`
2305
- ]);
2306
- hops.assertInvariants();
2307
- });
2308
- });
2309
- test("doubleKnock() returns the final response without cancelling its body", async () => {
2310
- const url = "https://example.com/lifecycle/public";
2311
- const next = "https://example.com/lifecycle/public-final";
2312
- const events = [];
2313
- const responses = [];
2314
- const originalFetch = globalThis.fetch;
2315
- globalThis.fetch = ((input) => {
2316
- const requestUrl = input instanceof Request ? input.url : String(input);
2317
- const index = responses.length + 1;
2318
- events.push(`fetch #${index} ${requestUrl}`);
2319
- const recorded = createRecordedResponse(events, index, requestUrl === url ? {
2320
- status: 302,
2321
- headers: { Location: next },
2322
- body: "Found"
2323
- } : {
2324
- status: 200,
2325
- body: "Done"
2326
- });
2327
- responses.push(recorded);
2328
- return Promise.resolve(recorded.response);
2329
- });
2330
- try {
2331
- const response = await doubleKnock(new Request(url), lifecycleIdentity);
2332
- assertEquals(events, [
2333
- `fetch #1 ${url}`,
2334
- "cancel #1",
2335
- `fetch #2 ${next}`
2336
- ]);
2337
- assertFalse(responses[1].settled());
2338
- assertEquals(await response.text(), "Done");
2339
- assertEquals(events.at(-1), "consumed #2");
2340
- } finally {
2341
- globalThis.fetch = originalFetch;
2342
- }
2343
- });
2344
- test("doubleKnock() is not blocked by a body cancellation that never settles", async () => {
2345
- const url = "https://example.com/lifecycle/public-hanging";
2346
- const next = "https://example.com/lifecycle/public-hanging-final";
2347
- const events = [];
2348
- const originalFetch = globalThis.fetch;
2349
- let index = 0;
2350
- globalThis.fetch = ((input) => {
2351
- const requestUrl = input instanceof Request ? input.url : String(input);
2352
- index++;
2353
- events.push(`fetch #${index} ${requestUrl}`);
2354
- return Promise.resolve(createRecordedResponse(events, index, index === 1 ? {
2355
- status: 401,
2356
- body: "Unauthorized",
2357
- hangCancel: true
2358
- } : index === 2 ? {
2359
- status: 302,
2360
- headers: { Location: next },
2361
- body: "Found",
2362
- hangCancel: true
2363
- } : {
2364
- status: 200,
2365
- body: "Done"
2366
- }).response);
2367
- });
2368
- try {
2369
- const response = await doubleKnock(new Request(url, {
2370
- method: "POST",
2371
- body: "activity"
2372
- }), lifecycleIdentity);
2373
- assertEquals(events, [
2374
- `fetch #1 ${url}`,
2375
- "cancel #1",
2376
- `fetch #2 ${url}`,
2377
- "cancel #2",
2378
- `fetch #3 ${next}`
2379
- ]);
2380
- assertEquals(await response.text(), "Done");
2381
- } finally {
2382
- globalThis.fetch = originalFetch;
2383
- }
2384
- });
2385
- test("timingSafeEqual()", async (t) => {
2386
- await t.step("should return true for equal empty arrays", () => {
2387
- assert(timingSafeEqual(new Uint8Array([]), new Uint8Array([])));
2388
- });
2389
- await t.step("should return true for equal non-empty arrays", async (t2) => {
2390
- const testCases = [
2391
- {
2392
- a: [
2393
- 1,
2394
- 2,
2395
- 3
2396
- ],
2397
- b: [
2398
- 1,
2399
- 2,
2400
- 3
2401
- ],
2402
- name: "simple sequence"
2403
- },
2404
- {
2405
- a: [
2406
- 0,
2407
- 0,
2408
- 0
2409
- ],
2410
- b: [
2411
- 0,
2412
- 0,
2413
- 0
2414
- ],
2415
- name: "sequence of zeros"
2416
- },
2417
- {
2418
- a: [
2419
- 255,
2420
- 128,
2421
- 0,
2422
- 42
2423
- ],
2424
- b: [
2425
- 255,
2426
- 128,
2427
- 0,
2428
- 42
2429
- ],
2430
- name: "varied bytes"
2431
- },
2432
- {
2433
- a: Array.from({ length: 100 }, (_, i) => i),
2434
- b: Array.from({ length: 100 }, (_, i) => i),
2435
- name: "longer sequence (0-99)"
2436
- }
2437
- ];
2438
- for (const tc of testCases) await t2.step(tc.name, () => {
2439
- assert(timingSafeEqual(new Uint8Array(tc.a), new Uint8Array(tc.b)));
2440
- });
2441
- });
2442
- await t.step("should return true for reference equality", () => {
2443
- const arr = new Uint8Array([
2444
- 10,
2445
- 20,
2446
- 30,
2447
- 99,
2448
- 100,
2449
- 0
2450
- ]);
2451
- assert(timingSafeEqual(arr, arr), "Array should be equal to itself by reference");
2452
- });
2453
- await t.step("should return false for arrays with same length but different content", async (t2) => {
2454
- for (const tc of [
2455
- {
2456
- a: [
2457
- 1,
2458
- 2,
2459
- 3
2460
- ],
2461
- b: [
2462
- 0,
2463
- 2,
2464
- 3
2465
- ],
2466
- name: "difference at start"
2467
- },
2468
- {
2469
- a: [
2470
- 1,
2471
- 2,
2472
- 3
2473
- ],
2474
- b: [
2475
- 1,
2476
- 0,
2477
- 3
2478
- ],
2479
- name: "difference in middle"
2480
- },
2481
- {
2482
- a: [
2483
- 1,
2484
- 2,
2485
- 3
2486
- ],
2487
- b: [
2488
- 1,
2489
- 2,
2490
- 0
2491
- ],
2492
- name: "difference at end"
2493
- },
2494
- {
2495
- a: [0],
2496
- b: [1],
2497
- name: "single byte difference"
2498
- },
2499
- {
2500
- a: [
2501
- 255,
2502
- 0,
2503
- 255
2504
- ],
2505
- b: [
2506
- 255,
2507
- 1,
2508
- 255
2509
- ],
2510
- name: "middle byte differs with edge values"
2511
- }
2512
- ]) await t2.step(tc.name, () => {
2513
- assertFalse(timingSafeEqual(new Uint8Array(tc.a), new Uint8Array(tc.b)));
2514
- });
2515
- });
2516
- await t.step("should return false for arrays with different lengths", async (t2) => {
2517
- for (const tc of [
2518
- {
2519
- a: [
2520
- 1,
2521
- 2,
2522
- 3
2523
- ],
2524
- b: [1, 2],
2525
- name: "b shorter"
2526
- },
2527
- {
2528
- a: [1, 2],
2529
- b: [
2530
- 1,
2531
- 2,
2532
- 3
2533
- ],
2534
- name: "a shorter"
2535
- },
2536
- {
2537
- a: [],
2538
- b: [
2539
- 1,
2540
- 2,
2541
- 3
2542
- ],
2543
- name: "a empty, b non-empty"
2544
- },
2545
- {
2546
- a: [
2547
- 1,
2548
- 2,
2549
- 3
2550
- ],
2551
- b: [],
2552
- name: "a non-empty, b empty"
2553
- }
2554
- ]) await t2.step(tc.name, () => {
2555
- assertFalse(timingSafeEqual(new Uint8Array(tc.a), new Uint8Array(tc.b)));
2556
- });
2557
- });
2558
- await t.step("should return false where content matches up to shorter length", async (t2) => {
2559
- for (const tc of [
2560
- {
2561
- a: [1, 2],
2562
- b: [
2563
- 1,
2564
- 2,
2565
- 0
2566
- ],
2567
- name: "a is prefix, b has trailing zero"
2568
- },
2569
- {
2570
- a: [
2571
- 1,
2572
- 2,
2573
- 0
2574
- ],
2575
- b: [1, 2],
2576
- name: "b is prefix, a has trailing zero"
2577
- },
2578
- {
2579
- a: [0],
2580
- b: [0, 0],
2581
- name: "single zero vs two zeros"
2582
- },
2583
- {
2584
- a: [0, 0],
2585
- b: [0],
2586
- name: "two zeros vs single zero"
2587
- }
2588
- ]) await t2.step(tc.name, () => {
2589
- assertFalse(timingSafeEqual(new Uint8Array(tc.a), new Uint8Array(tc.b)));
2590
- });
2591
- });
2592
- await t.step("should correctly handle comparisons involving padding bytes", async (t2) => {
2593
- await t2.step("a=[1], b=[1,0] (b longer with trailing zero)", () => {
2594
- assertFalse(timingSafeEqual(new Uint8Array([1]), new Uint8Array([1, 0])));
2595
- });
2596
- await t2.step("a=[1,0], b=[1] (a longer with trailing zero)", () => {
2597
- assertFalse(timingSafeEqual(new Uint8Array([1, 0]), new Uint8Array([1])));
2598
- });
2599
- });
2600
- });
2601
- test("signRequest() [rfc9421] error handling for invalid signature base creation", async () => {
2602
- const request = new Request("https://example.com/test", {
2603
- method: "POST",
2604
- body: "test body"
2605
- });
2606
- await assertThrows(() => {
2607
- createRfc9421SignatureBase(request, [{
2608
- value: "@unsupported",
2609
- params: {}
2610
- }], "alg=\"rsa-pss-sha256\";keyid=\"https://example.com/key2\";created=1234567890");
2611
- }, Error, "Unsupported derived component: @unsupported");
2612
- const signedRequest = await signRequest(request, rsaPrivateKey2, new URL("https://example.com/key2"), { spec: "rfc9421" });
2613
- assertExists(signedRequest.headers.get("Signature-Input"));
2614
- assertExists(signedRequest.headers.get("Signature"));
2615
- });
2616
- test("verifyRequest() [rfc9421] error handling for invalid signature base creation", async () => {
2617
- assertEquals(await verifyRequest(new Request("https://example.com/test", {
2618
- method: "GET",
2619
- headers: {
2620
- "Accept": "application/json",
2621
- "Signature-Input": "sig1=(\"@unsupported\");alg=\"rsa-pss-sha256\";keyid=\"https://example.com/key2\";created=1234567890",
2622
- "Signature": "sig1=:invalid_signature_data:"
2623
- }
2624
- }), {
2625
- spec: "rfc9421",
2626
- documentLoader: mockDocumentLoader,
2627
- contextLoader: mockDocumentLoader
2628
- }), null, "Verification should fail gracefully for malformed signature inputs");
2629
- });
2630
- test("doubleKnock() regression test for TypeError: unusable bug #294", async () => {
2631
- esm_default.spyGlobal();
2632
- let requestCount = 0;
2633
- esm_default.post("https://example.com/inbox-retry-redirect", (_cl) => {
2634
- requestCount++;
2635
- if (requestCount === 1) return new Response("Unauthorized", { status: 401 });
2636
- else if (requestCount === 2) return Response.redirect("https://example.com/final-destination", 302);
2637
- return new Response("Should not reach here", { status: 500 });
2638
- });
2639
- esm_default.post("https://example.com/final-destination", () => {
2640
- return new Response("Success", { status: 200 });
2641
- });
2642
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-retry-redirect", {
2643
- method: "POST",
2644
- body: "Test activity content",
2645
- headers: { "Content-Type": "application/activity+json" }
2646
- }), {
2647
- keyId: rsaPublicKey2.id,
2648
- privateKey: rsaPrivateKey2
2649
- })).status, 200);
2650
- assertEquals(requestCount, 2, "Should make 2 requests before redirect");
2651
- esm_default.hardReset();
2652
- });
2653
- test("doubleKnock() regression test for redirect handling bug", async () => {
2654
- esm_default.spyGlobal();
2655
- esm_default.post("https://example.com/inbox-retry-redirect", (_cl) => {
2656
- return new Response(null, {
2657
- status: 302,
2658
- headers: { location: "/final-destination" }
2659
- });
2660
- });
2661
- esm_default.post("https://example.com/final-destination", () => {
2662
- return new Response("Success", { status: 200 });
2663
- });
2664
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-retry-redirect", {
2665
- method: "POST",
2666
- body: "Test activity content",
2667
- headers: { "Content-Type": "application/activity+json" }
2668
- }), {
2669
- keyId: rsaPublicKey2.id,
2670
- privateKey: rsaPrivateKey2
2671
- })).status, 200);
2672
- esm_default.hardReset();
2673
- });
2674
- test("signRequest() and verifyRequest() cancellation", {
2675
- sanitizeResources: false,
2676
- sanitizeOps: false
2677
- }, async (t) => {
2678
- esm_default.spyGlobal();
2679
- await t.step("doubleKnock cancellation", async () => {
2680
- esm_default.post("https://example.com/slow-endpoint", () => new Promise((resolve) => {
2681
- setTimeout(() => {
2682
- resolve(new Response("", { status: 202 }));
2683
- }, 1e3);
2684
- }));
2685
- const request = new Request("https://example.com/slow-endpoint", {
2686
- method: "POST",
2687
- body: "Test message",
2688
- headers: { "Content-Type": "text/plain" }
2689
- });
2690
- const controller = new AbortController();
2691
- const promise = doubleKnock(request, {
2692
- keyId: rsaPublicKey2.id,
2693
- privateKey: rsaPrivateKey2
2694
- }, { signal: controller.signal });
2695
- controller.abort();
2696
- await assertRejects(() => promise, Error);
2697
- });
2698
- await t.step("doubleKnock immediate cancellation", async () => {
2699
- const request = new Request("https://example.com/", {
2700
- method: "POST",
2701
- body: "Hello, world!",
2702
- headers: {
2703
- "Content-Type": "text/plain; charset=utf-8",
2704
- Accept: "text/plain"
2705
- }
2706
- });
2707
- const controller = new AbortController();
2708
- controller.abort();
2709
- await assertRejects(() => doubleKnock(request, {
2710
- keyId: rsaPublicKey2.id,
2711
- privateKey: rsaPrivateKey2
2712
- }, { signal: controller.signal }), Error);
2713
- });
2714
- esm_default.hardReset();
2715
- });
2716
- test("signRequest() with custom label", async () => {
2717
- const signed = await signRequest(new Request("https://example.com/api", {
2718
- method: "POST",
2719
- body: "test",
2720
- headers: { "Content-Type": "text/plain" }
2721
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
2722
- spec: "rfc9421",
2723
- rfc9421: { label: "mysig" }
2724
- });
2725
- assertStringIncludes(signed.headers.get("Signature-Input"), "mysig=");
2726
- assertStringIncludes(signed.headers.get("Signature"), "mysig=");
2727
- });
2728
- test("signRequest() with custom components", async () => {
2729
- const sigInput = (await signRequest(new Request("https://example.com/api", {
2730
- method: "POST",
2731
- body: "test",
2732
- headers: {
2733
- "Content-Type": "text/plain",
2734
- "Host": "example.com",
2735
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
2736
- }
2737
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
2738
- spec: "rfc9421",
2739
- rfc9421: { components: [
2740
- {
2741
- value: "@method",
2742
- params: {}
2743
- },
2744
- {
2745
- value: "@target-uri",
2746
- params: {}
2747
- },
2748
- {
2749
- value: "@authority",
2750
- params: {}
2751
- }
2752
- ] }
2753
- })).headers.get("Signature-Input");
2754
- assertStringIncludes(sigInput, "\"@method\"");
2755
- assertStringIncludes(sigInput, "\"@target-uri\"");
2756
- assertStringIncludes(sigInput, "\"@authority\"");
2757
- assertStringIncludes(sigInput, "\"content-digest\"");
2758
- });
2759
- test("signRequest() with nonce and tag", async () => {
2760
- const sigInput = (await signRequest(new Request("https://example.com/api", {
2761
- method: "GET",
2762
- headers: {
2763
- "Host": "example.com",
2764
- "Date": "Tue, 05 Mar 2024 07:49:44 GMT"
2765
- }
2766
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
2767
- spec: "rfc9421",
2768
- rfc9421: {
2769
- nonce: "test-nonce-123",
2770
- tag: "app-v1"
2771
- }
2772
- })).headers.get("Signature-Input");
2773
- assertStringIncludes(sigInput, "nonce=\"test-nonce-123\"");
2774
- assertStringIncludes(sigInput, "tag=\"app-v1\"");
2775
- });
2776
- test("formatRfc9421SignatureParameters() escapes nonce and tag", () => {
2777
- const commonParams = {
2778
- algorithm: "rsa-v1_5-sha256",
2779
- keyId: new URL("https://example.com/key"),
2780
- created: 1709626184
2781
- };
2782
- assertStringIncludes(formatRfc9421SignatureParameters({
2783
- ...commonParams,
2784
- nonce: "x\\y"
2785
- }), "nonce=\"x\\\\y\"");
2786
- assertStringIncludes(formatRfc9421SignatureParameters({
2787
- ...commonParams,
2788
- nonce: "a\"b"
2789
- }), "nonce=\"a\\\"b\"");
2790
- assertStringIncludes(formatRfc9421SignatureParameters({
2791
- ...commonParams,
2792
- tag: "x\\y"
2793
- }), "tag=\"x\\\\y\"");
2794
- assertStringIncludes(formatRfc9421SignatureParameters({
2795
- ...commonParams,
2796
- tag: "a\"b"
2797
- }), "tag=\"a\\\"b\"");
2798
- const mixed = formatRfc9421SignatureParameters({
2799
- ...commonParams,
2800
- nonce: "n\"o\\nce",
2801
- tag: "t\"ag\\value"
2802
- });
2803
- assertStringIncludes(mixed, "nonce=\"n\\\"o\\\\nce\"");
2804
- assertStringIncludes(mixed, "tag=\"t\\\"ag\\\\value\"");
2805
- });
2806
- test("signRequest() [rfc9421] accumulates multiple signatures when called sequentially", async () => {
2807
- const twiceSigned = await signRequest(await signRequest(new Request("https://example.com/inbox", {
2808
- method: "POST",
2809
- body: "Hello",
2810
- headers: { "Content-Type": "text/plain" }
2811
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
2812
- spec: "rfc9421",
2813
- rfc9421: {
2814
- label: "sig1",
2815
- components: [{
2816
- value: "@method",
2817
- params: {}
2818
- }, {
2819
- value: "@target-uri",
2820
- params: {}
2821
- }]
2822
- }
2823
- }), rsaPrivateKey2, new URL("https://example.com/key2"), {
2824
- spec: "rfc9421",
2825
- rfc9421: {
2826
- label: "sig2",
2827
- components: [{
2828
- value: "@authority",
2829
- params: {}
2830
- }]
2831
- }
2832
- });
2833
- const sigInput = twiceSigned.headers.get("Signature-Input") ?? "";
2834
- const sig = twiceSigned.headers.get("Signature") ?? "";
2835
- assertStringIncludes(sigInput, "sig1=");
2836
- assertStringIncludes(sigInput, "sig2=");
2837
- assertStringIncludes(sig, "sig1=");
2838
- assertStringIncludes(sig, "sig2=");
2839
- });
2840
- test("doubleKnock(): Accept-Signature challenge retry succeeds", async () => {
2841
- esm_default.spyGlobal();
2842
- let requestCount = 0;
2843
- esm_default.post("https://example.com/inbox-challenge-ok", (cl) => {
2844
- const req = cl.request;
2845
- requestCount++;
2846
- if (requestCount === 1) return new Response("Not Authorized", {
2847
- status: 401,
2848
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\" \"@authority\" \"content-digest\");created;nonce=\"challenge-nonce-1\"" }
2849
- });
2850
- if ((req.headers.get("Signature-Input") ?? "").includes("challenge-nonce-1")) return new Response("", { status: 202 });
2851
- return new Response("Bad", { status: 400 });
2852
- });
2853
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-challenge-ok", {
2854
- method: "POST",
2855
- body: "Test message",
2856
- headers: { "Content-Type": "text/plain" }
2857
- }), {
2858
- keyId: rsaPublicKey2.id,
2859
- privateKey: rsaPrivateKey2
2860
- })).status, 202);
2861
- assertEquals(requestCount, 2);
2862
- esm_default.hardReset();
2863
- });
2864
- test("doubleKnock(): validates redirects after Accept-Signature challenge retry", async () => {
2865
- esm_default.spyGlobal();
2866
- let requestCount = 0;
2867
- let privateRequestCount = 0;
2868
- esm_default.post("https://example.com/inbox-challenge-redirect", () => {
2869
- requestCount++;
2870
- if (requestCount === 1) return new Response("Not Authorized", {
2871
- status: 401,
2872
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\" \"@authority\" \"content-digest\");created;nonce=\"challenge-nonce-redirect\"" }
2873
- });
2874
- return Response.redirect("http://localhost/private", 302);
2875
- });
2876
- esm_default.post("http://localhost/private", () => {
2877
- privateRequestCount++;
2878
- return new Response("", { status: 202 });
2879
- });
2880
- const request = new Request("https://example.com/inbox-challenge-redirect", {
2881
- method: "POST",
2882
- body: "Test message",
2883
- headers: { "Content-Type": "text/plain" }
2884
- });
2885
- await assertRejects(() => doubleKnock(request, {
2886
- keyId: rsaPublicKey2.id,
2887
- privateKey: rsaPrivateKey2
2888
- }, { validateRedirect(url) {
2889
- throw new Error(`Disallowed redirect: ${url}`);
2890
- } }), Error, "Disallowed redirect: http://localhost/private");
2891
- assertEquals(requestCount, 2);
2892
- assertEquals(privateRequestCount, 0);
2893
- esm_default.hardReset();
2894
- });
2895
- test("doubleKnock(): unfulfillable Accept-Signature falls to legacy fallback", async () => {
2896
- esm_default.spyGlobal();
2897
- let requestCount = 0;
2898
- esm_default.post("https://example.com/inbox-unfulfillable", (cl) => {
2899
- const req = cl.request;
2900
- requestCount++;
2901
- if (requestCount === 1) return new Response("Not Authorized", {
2902
- status: 401,
2903
- headers: { "Accept-Signature": "sig1=(\"@method\");alg=\"ecdsa-p256-sha256\"" }
2904
- });
2905
- if (req.headers.has("Signature") && !req.headers.has("Signature-Input")) return new Response("", { status: 202 });
2906
- return new Response("Bad", { status: 400 });
2907
- });
2908
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-unfulfillable", {
2909
- method: "POST",
2910
- body: "Test message",
2911
- headers: { "Content-Type": "text/plain" }
2912
- }), {
2913
- keyId: rsaPublicKey2.id,
2914
- privateKey: rsaPrivateKey2
2915
- })).status, 202);
2916
- assertEquals(requestCount, 2);
2917
- esm_default.hardReset();
2918
- });
2919
- test("doubleKnock(): no Accept-Signature falls to legacy fallback", async () => {
2920
- esm_default.spyGlobal();
2921
- let requestCount = 0;
2922
- esm_default.post("https://example.com/inbox-no-challenge", (cl) => {
2923
- const req = cl.request;
2924
- requestCount++;
2925
- if (requestCount === 1) return new Response("Not Authorized", { status: 401 });
2926
- if (req.headers.has("Signature")) return new Response("", { status: 202 });
2927
- return new Response("Bad", { status: 400 });
2928
- });
2929
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-no-challenge", {
2930
- method: "POST",
2931
- body: "Test message",
2932
- headers: { "Content-Type": "text/plain" }
2933
- }), {
2934
- keyId: rsaPublicKey2.id,
2935
- privateKey: rsaPrivateKey2
2936
- })).status, 202);
2937
- assertEquals(requestCount, 2);
2938
- esm_default.hardReset();
2939
- });
2940
- test("doubleKnock(): challenge retry also fails → legacy fallback attempted", async () => {
2941
- esm_default.spyGlobal();
2942
- let requestCount = 0;
2943
- esm_default.post("https://example.com/inbox-challenge-fails", (cl) => {
2944
- const req = cl.request;
2945
- requestCount++;
2946
- if (requestCount === 1) return new Response("Not Authorized", {
2947
- status: 401,
2948
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\");created" }
2949
- });
2950
- if (requestCount === 2) return new Response("Still Not Authorized", { status: 401 });
2951
- if (req.headers.has("Signature") && !req.headers.has("Signature-Input")) return new Response("", { status: 202 });
2952
- return new Response("Bad", { status: 400 });
2953
- });
2954
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-challenge-fails", {
2955
- method: "POST",
2956
- body: "Test message",
2957
- headers: { "Content-Type": "text/plain" }
2958
- }), {
2959
- keyId: rsaPublicKey2.id,
2960
- privateKey: rsaPrivateKey2
2961
- })).status, 202);
2962
- assertEquals(requestCount, 3);
2963
- esm_default.hardReset();
2964
- });
2965
- test("doubleKnock(): challenge retry returns another challenge → not followed", async () => {
2966
- esm_default.spyGlobal();
2967
- let requestCount = 0;
2968
- esm_default.post("https://example.com/inbox-challenge-loop", (cl) => {
2969
- const req = cl.request;
2970
- requestCount++;
2971
- if (requestCount === 1) return new Response("Not Authorized", {
2972
- status: 401,
2973
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\");created;nonce=\"nonce-1\"" }
2974
- });
2975
- if (requestCount === 2) return new Response("Still Not Authorized", {
2976
- status: 401,
2977
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\");created;nonce=\"nonce-2\"" }
2978
- });
2979
- if (req.headers.has("Signature") && !req.headers.has("Signature-Input")) return new Response("", { status: 202 });
2980
- return new Response("Bad", { status: 400 });
2981
- });
2982
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-challenge-loop", {
2983
- method: "POST",
2984
- body: "Test message",
2985
- headers: { "Content-Type": "text/plain" }
2986
- }), {
2987
- keyId: rsaPublicKey2.id,
2988
- privateKey: rsaPrivateKey2
2989
- })).status, 202);
2990
- assertEquals(requestCount, 3);
2991
- esm_default.hardReset();
2992
- });
2993
- test("doubleKnock(): Accept-Signature with unsupported component falls to legacy fallback", async () => {
2994
- esm_default.spyGlobal();
2995
- let requestCount = 0;
2996
- esm_default.post("https://example.com/inbox-bad-challenge", (cl) => {
2997
- const req = cl.request;
2998
- requestCount++;
2999
- if (requestCount === 1) return new Response("Not Authorized", {
3000
- status: 401,
3001
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\" \"x-custom-required\");created" }
3002
- });
3003
- if (req.headers.has("Signature") && !req.headers.has("Signature-Input")) return new Response("", { status: 202 });
3004
- return new Response("Bad", { status: 400 });
3005
- });
3006
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-bad-challenge", {
3007
- method: "POST",
3008
- body: "Test message",
3009
- headers: { "Content-Type": "text/plain" }
3010
- }), {
3011
- keyId: rsaPublicKey2.id,
3012
- privateKey: rsaPrivateKey2
3013
- })).status, 202);
3014
- assertEquals(requestCount, 2);
3015
- esm_default.hardReset();
3016
- });
3017
- test("doubleKnock(): Accept-Signature with unsupported derived component falls to legacy fallback", async () => {
3018
- esm_default.spyGlobal();
3019
- let requestCount = 0;
3020
- esm_default.post("https://example.com/inbox-bad-derived", (cl) => {
3021
- const req = cl.request;
3022
- requestCount++;
3023
- if (requestCount === 1) return new Response("Not Authorized", {
3024
- status: 401,
3025
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@query-param\");created" }
3026
- });
3027
- if (req.headers.has("Signature") && !req.headers.has("Signature-Input")) return new Response("", { status: 202 });
3028
- return new Response("Bad", { status: 400 });
3029
- });
3030
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-bad-derived", {
3031
- method: "POST",
3032
- body: "Test message",
3033
- headers: { "Content-Type": "text/plain" }
3034
- }), {
3035
- keyId: rsaPublicKey2.id,
3036
- privateKey: rsaPrivateKey2
3037
- })).status, 202);
3038
- assertEquals(requestCount, 2);
3039
- esm_default.hardReset();
3040
- });
3041
- test("doubleKnock(): Accept-Signature with multiple entries where first throws falls to next entry", async () => {
3042
- esm_default.spyGlobal();
3043
- let requestCount = 0;
3044
- esm_default.post("https://example.com/inbox-multi-challenge", (cl) => {
3045
- const req = cl.request;
3046
- requestCount++;
3047
- if (requestCount === 1) return new Response("Not Authorized", {
3048
- status: 401,
3049
- headers: { "Accept-Signature": "sig1=(\"@method\" \"x-nonexistent\");created,sig2=(\"@method\" \"@target-uri\" \"@authority\");created" }
3050
- });
3051
- if (req.headers.has("Signature-Input")) return new Response("", { status: 202 });
3052
- return new Response("Bad", { status: 400 });
3053
- });
3054
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-multi-challenge", {
3055
- method: "POST",
3056
- body: "Test message",
3057
- headers: { "Content-Type": "text/plain" }
3058
- }), {
3059
- keyId: rsaPublicKey2.id,
3060
- privateKey: rsaPrivateKey2
3061
- })).status, 202);
3062
- assertEquals(requestCount, 2);
3063
- esm_default.hardReset();
3064
- });
3065
- test("doubleKnock(): Accept-Signature with multiple compatible entries fulfills all (RFC 9421 §5 MUST)", async () => {
3066
- esm_default.spyGlobal();
3067
- let requestCount = 0;
3068
- esm_default.post("https://example.com/inbox-multi-compat", (cl) => {
3069
- const req = cl.request;
3070
- requestCount++;
3071
- if (requestCount === 1) return new Response("Not Authorized", {
3072
- status: 401,
3073
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\");created,sig2=(\"@authority\");created;nonce=\"nonce-for-sig2\"" }
3074
- });
3075
- const sigInput = req.headers.get("Signature-Input") ?? "";
3076
- const sig = req.headers.get("Signature") ?? "";
3077
- if (sigInput.includes("sig1=") && sigInput.includes("sig2=") && sig.includes("sig1=") && sig.includes("sig2=")) return new Response("", { status: 202 });
3078
- return new Response("Missing signatures", { status: 400 });
3079
- });
3080
- assertEquals((await doubleKnock(new Request("https://example.com/inbox-multi-compat", {
3081
- method: "POST",
3082
- body: "Test message",
3083
- headers: { "Content-Type": "text/plain" }
3084
- }), {
3085
- keyId: rsaPublicKey2.id,
3086
- privateKey: rsaPrivateKey2
3087
- })).status, 202);
3088
- assertEquals(requestCount, 2);
3089
- esm_default.hardReset();
3090
- });
3091
- test("listRequestSignatures()", async (t) => {
3092
- const request = () => new Request("https://example.com/inbox", {
3093
- method: "POST",
3094
- body: "Test message"
3095
- });
3096
- await t.step("draft-cavage", async () => {
3097
- const signed = await signRequest(request(), rsaPrivateKey2, rsaPublicKey2.id);
3098
- const signatures = listRequestSignatures(signed);
3099
- assertEquals(signatures.map((s) => [s.keyId.href, s.label]), [[rsaPublicKey2.id.href, null]]);
3100
- const components = signatures[0].components;
3101
- assertEquals(components.map((c) => c.value), signed.headers.get("Signature").match(/headers="([^"]*)"/)[1].split(" "));
3102
- assert(components.every((c) => Object.keys(c.params).length < 1));
3103
- });
3104
- await t.step("RFC 9421", async () => {
3105
- const signatures = listRequestSignatures(await signRequest(request(), rsaPrivateKey2, rsaPublicKey2.id, {
3106
- spec: "rfc9421",
3107
- rfc9421: { label: "a" }
3108
- }));
3109
- assertEquals(signatures.map((s) => [s.keyId.href, s.label]), [[rsaPublicKey2.id.href, "a"]]);
3110
- assertEquals(signatures[0].components.map((c) => c.value), [
3111
- "@method",
3112
- "@target-uri",
3113
- "@authority",
3114
- "host",
3115
- "date",
3116
- "content-digest"
3117
- ]);
3118
- });
3119
- await t.step("RFC 9421 beyond the limit", async () => {
3120
- const currentTime = Temporal.Instant.from("2024-03-05T08:09:44Z");
3121
- const signed = await signRfc9421Many([
3122
- 1,
3123
- 2,
3124
- 3,
3125
- 4
3126
- ].map((n) => `https://example.com/key-${n}`), currentTime);
3127
- const headers = new Headers(signed.headers);
3128
- headers.set("Signature-Input", headers.get("Signature-Input").replace("https://example.com/key-1", "not a URL"));
3129
- const request = new Request(signed.url, {
3130
- method: "POST",
3131
- headers
3132
- });
3133
- const keyIds = (maxSignatures) => listRequestSignatures(request, maxSignatures).map((s) => s.keyId.href);
3134
- assertEquals(keyIds(), ["https://example.com/key-2", "https://example.com/key-3"]);
3135
- assertEquals(keyIds(1), []);
3136
- assertEquals(keyIds(Infinity), [
3137
- "https://example.com/key-2",
3138
- "https://example.com/key-3",
3139
- "https://example.com/key-4"
3140
- ]);
3141
- });
3142
- await t.step("unsigned or malformed", () => {
3143
- assertEquals(listRequestSignatures(request()), []);
3144
- const malformed = request();
3145
- malformed.headers.set("Signature", "keyId=\"not a URL\",signature=\"AA==\"");
3146
- assertEquals(listRequestSignatures(malformed), []);
3147
- const garbage = request();
3148
- garbage.headers.set("Signature-Input", "((");
3149
- garbage.headers.set("Signature", "((");
3150
- assertEquals(listRequestSignatures(garbage), []);
3151
- });
3152
- });
3153
- test("selectRequestSignature()", async () => {
3154
- const body = "Test message";
3155
- const sign = (label, keyId) => signRequest(new Request("https://example.com/inbox", {
3156
- method: "POST",
3157
- body
3158
- }), rsaPrivateKey2, keyId, {
3159
- spec: "rfc9421",
3160
- rfc9421: { label }
3161
- });
3162
- const first = await sign("a", new URL("https://example.com/other#key"));
3163
- const second = await sign("b", rsaPublicKey2.id);
3164
- const headers = new Headers(second.headers);
3165
- for (const name of ["Signature-Input", "Signature"]) headers.set(name, `${first.headers.get(name)}, ${second.headers.get(name)}`);
3166
- const request = new Request(second.url, {
3167
- method: "POST",
3168
- headers,
3169
- body
3170
- });
3171
- const signatures = listRequestSignatures(request);
3172
- assertEquals(signatures.map((s) => s.label), ["a", "b"]);
3173
- const selected = selectRequestSignature(request, signatures[1]);
3174
- assertEquals(listRequestSignatures(selected).map((s) => [s.label, s.keyId.href]), [["b", rsaPublicKey2.id.href]]);
3175
- const result = await verifyRequestDetailed(selected, {
3176
- documentLoader: mockDocumentLoader,
3177
- contextLoader: mockDocumentLoader
3178
- });
3179
- assert(result.verified);
3180
- assertEquals(result.key.id, rsaPublicKey2.id);
3181
- assertEquals(await selected.text(), body);
3182
- assertEquals(await request.text(), body);
3183
- });
3184
- test("verifyRequestDetailed() reports a timed-out key fetch", async (t) => {
3185
- for (const stall of ["headers", "body"]) await t.step(`stalled ${stall}`, async () => {
3186
- esm_default.mockGlobal();
3187
- const keyId = new URL(`https://slow.example/actors/alice#${stall}`);
3188
- let requests = 0;
3189
- esm_default.get(`begin:https://slow.example/actors/alice`, () => {
3190
- requests++;
3191
- if (stall === "headers") return new Promise(() => {});
3192
- return new Response(new ReadableStream({ pull: () => new Promise(() => {}) }), { status: 404 });
3193
- });
3194
- const loader = getDocumentLoader({
3195
- allowPrivateAddress: true,
3196
- timeout: 100
3197
- });
3198
- const documentLoader = (url, options) => url.startsWith("https://slow.example/") ? loader(url, options) : mockDocumentLoader(url);
3199
- const kv = new MemoryKvStore();
3200
- try {
3201
- const sign = () => signRequest(new Request("https://example.com/inbox", {
3202
- method: "POST",
3203
- headers: {
3204
- "Content-Type": "application/activity+json",
3205
- accept: "application/ld+json"
3206
- },
3207
- body: JSON.stringify({
3208
- "@context": "https://www.w3.org/ns/activitystreams",
3209
- type: "Create",
3210
- actor: "https://slow.example/actors/alice"
3211
- })
3212
- }), rsaPrivateKey2, keyId);
3213
- const result = await verifyRequestDetailed(await sign(), {
3214
- contextLoader: mockDocumentLoader,
3215
- documentLoader,
3216
- keyCache: new KvKeyCache(kv, ["pk"])
3217
- });
3218
- assertFalse(result.verified);
3219
- assert(result.reason.type === "keyFetchError");
3220
- assertEquals(result.reason.keyId, keyId);
3221
- assert("error" in result.reason.result);
3222
- const error = result.reason.result.error;
3223
- assert(error instanceof FetchError);
3224
- assertEquals(error.response, void 0);
3225
- assert(error.cause instanceof DOMException);
3226
- assertEquals(error.cause.name, "TimeoutError");
3227
- assertEquals(requests, 1);
3228
- const cached = await verifyRequestDetailed(await sign(), {
3229
- contextLoader: mockDocumentLoader,
3230
- documentLoader,
3231
- keyCache: new KvKeyCache(kv, ["pk"])
3232
- });
3233
- assertFalse(cached.verified);
3234
- assert(cached.reason.type === "keyFetchError");
3235
- assert("error" in cached.reason.result);
3236
- assertEquals(cached.reason.result.error.name, "FetchError");
3237
- assertStringIncludes(cached.reason.result.error.message, "Timed out after 100 ms");
3238
- assertEquals(requests, 1);
3239
- } finally {
3240
- esm_default.hardReset();
3241
- }
3242
- });
3243
- });
3244
- function createRecordedResponse(events, index, init, cancelSuffix = () => "") {
3245
- const bytes = new TextEncoder().encode(init.body ?? "");
3246
- const chunkSize = init.chunkSize ?? 256;
3247
- let offset = 0;
3248
- let settled = false;
3249
- const body = new ReadableStream({
3250
- pull(controller) {
3251
- if (offset >= bytes.length) {
3252
- settled = true;
3253
- events.push(`consumed #${index}`);
3254
- controller.close();
3255
- return;
3256
- }
3257
- controller.enqueue(bytes.slice(offset, offset + chunkSize));
3258
- offset += chunkSize;
3259
- },
3260
- cancel() {
3261
- settled = true;
3262
- events.push(`cancel #${index}${cancelSuffix()}`);
3263
- if (init.failCancel) throw new Error(`cancel #${index} failed`);
3264
- if (init.hangCancel) return new Promise(() => {});
3265
- }
3266
- }, { highWaterMark: 0 });
3267
- return {
3268
- response: new Response(body, {
3269
- status: init.status ?? 200,
3270
- headers: init.headers
3271
- }),
3272
- settled: () => settled
3273
- };
3274
- }
3275
- function recordHops(respond) {
3276
- const events = [];
3277
- const requests = [];
3278
- const unsettledAtClose = [];
3279
- let opens = 0;
3280
- let closes = 0;
3281
- let fetches = 0;
3282
- return {
3283
- events,
3284
- requests,
3285
- openHop(url) {
3286
- opens++;
3287
- events.push(`open ${url}`);
3288
- const tracked = [];
3289
- let closed = false;
3290
- let closing = false;
3291
- return Promise.resolve({
3292
- url: new URL(url),
3293
- async fetch(input, init) {
3294
- if (closed) throw new TypeError("The session is closed.");
3295
- const request = new Request(input instanceof Request ? input.clone() : input, init);
3296
- const index = ++fetches;
3297
- requests.push(request);
3298
- events.push(`fetch #${index} ${request.url}`);
3299
- const recorded = createRecordedResponse(events, index, await respond(request, index), () => closing ? " by close" : "");
3300
- tracked.push({
3301
- ...recorded,
3302
- index
3303
- });
3304
- return recorded.response;
3305
- },
3306
- close() {
3307
- if (closed) return Promise.resolve();
3308
- closed = true;
3309
- closes++;
3310
- closing = true;
3311
- for (const { response, settled, index } of tracked) {
3312
- if (settled()) continue;
3313
- if (response.body?.locked) unsettledAtClose.push(index);
3314
- else response.body?.cancel().catch(() => {});
3315
- }
3316
- events.push(`close ${url}`);
3317
- return Promise.resolve();
3318
- }
3319
- });
3320
- },
3321
- assertInvariants() {
3322
- assertEquals(opens, closes);
3323
- assertEquals(unsettledAtClose, []);
3324
- }
3325
- };
3326
- }
3327
- //#endregion
3328
- export {};