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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/dist/compat/mod.d.cts +1 -1
  2. package/dist/compat/mod.d.ts +1 -1
  3. package/dist/{context-xrqq4Hrq.d.ts → context-CuLvR1Os.d.ts} +2 -2
  4. package/dist/{context-C1NqcIct.d.cts → context-apq0IBg2.d.cts} +2 -2
  5. package/dist/federation/mod.cjs +1 -1
  6. package/dist/federation/mod.d.cts +3 -3
  7. package/dist/federation/mod.d.ts +3 -3
  8. package/dist/federation/mod.js +1 -1
  9. package/dist/{federation-FbwcnRHg.cjs → federation-JvzYDx0P.cjs} +5 -5
  10. package/dist/{http-DbvOPsFZ.cjs → http-BG5cDmTS.cjs} +1 -1
  11. package/dist/{http-CWn0K5jD.js → http-MUf125Jc.js} +1 -1
  12. package/dist/{key-dwwAg5bA.d.ts → key-BZw-YiK5.d.ts} +2 -2
  13. package/dist/{key-DlHT4R6k.d.cts → key-D5fbQkKM.d.cts} +2 -2
  14. package/dist/{kv-cache-B-fOrhb-.cjs → kv-cache-A2po7h0_.cjs} +1 -1
  15. package/dist/{kv-cache-BC837EqC.js → kv-cache-CbWc1BZA.js} +1 -1
  16. package/dist/{ld-CWVpo_NM.d.cts → ld-DEi9ERHf.d.cts} +1 -1
  17. package/dist/{ld-o4LnhCYY.d.ts → ld-DlC78ioJ.d.ts} +1 -1
  18. package/dist/{middleware-n2UrG62B.js → middleware-DzzdJ7Wz.js} +5 -5
  19. package/dist/{mod-D22ZsiKi.d.ts → mod-BJRtsw7l.d.ts} +1 -1
  20. package/dist/{mod-C1nT74IG.d.cts → mod-BamwZjJx.d.cts} +1 -1
  21. package/dist/{mod-DO0epJGH.d.ts → mod-BkTi19dI.d.ts} +1 -1
  22. package/dist/{mod-CQC9xlLZ.d.ts → mod-CMtF0VVy.d.ts} +1 -1
  23. package/dist/{mod-YvA4Rk8J.d.cts → mod-D2Z9MiCm.d.cts} +1 -1
  24. package/dist/{mod-TwiQgEf3.d.cts → mod-DB2NOzQF.d.cts} +1 -1
  25. package/dist/mod.cjs +4 -4
  26. package/dist/mod.d.cts +6 -6
  27. package/dist/mod.d.ts +6 -6
  28. package/dist/mod.js +4 -4
  29. package/dist/{portable-collection-DQhIkX5a.js → portable-collection-CAer9RWN.js} +1 -1
  30. package/dist/{portable-collection-DseoiPPj.cjs → portable-collection-d8w7TCn9.cjs} +1 -1
  31. package/dist/sig/mod.cjs +2 -2
  32. package/dist/sig/mod.d.cts +3 -3
  33. package/dist/sig/mod.d.ts +3 -3
  34. package/dist/sig/mod.js +2 -2
  35. package/dist/utils/mod.cjs +1 -1
  36. package/dist/utils/mod.d.cts +1 -1
  37. package/dist/utils/mod.d.ts +1 -1
  38. package/dist/utils/mod.js +1 -1
  39. package/package.json +22 -9
  40. package/skills/fedify/SKILL.md +10 -0
  41. package/dist/accept-CPVqki78.mjs +0 -145
  42. package/dist/activity-listener-CELFAodc.mjs +0 -44
  43. package/dist/assert-D1Eafmd_.mjs +0 -23
  44. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  45. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  46. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  47. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  48. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  49. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  50. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  51. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  52. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  53. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  54. package/dist/audience-CHQ-FlLD.mjs +0 -95
  55. package/dist/builder-CGJ-NXcZ.mjs +0 -911
  56. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  57. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  58. package/dist/client-5SIFzW3q.mjs +0 -441
  59. package/dist/codec-C6rTrpIp.mjs +0 -147
  60. package/dist/collection-CnnP1UAv.mjs +0 -44
  61. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  62. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  63. package/dist/compat/public-audience.test.d.mts +0 -2
  64. package/dist/compat/public-audience.test.mjs +0 -187
  65. package/dist/compat/secured-document.test.d.mts +0 -2
  66. package/dist/compat/secured-document.test.mjs +0 -58
  67. package/dist/compat/transformers.test.d.mts +0 -2
  68. package/dist/compat/transformers.test.mjs +0 -62
  69. package/dist/compound-proof-CnzwOddk.mjs +0 -1019
  70. package/dist/context-LgGFFSz7.mjs +0 -146
  71. package/dist/deno-eoFpPk7W.mjs +0 -8
  72. package/dist/dist-_geWsuaI.mjs +0 -189
  73. package/dist/docloader-DwkipyL1.mjs +0 -136
  74. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  75. package/dist/exporter-DVG68ozH.mjs +0 -263
  76. package/dist/federation/audience.test.d.mts +0 -2
  77. package/dist/federation/audience.test.mjs +0 -130
  78. package/dist/federation/builder.test.d.mts +0 -2
  79. package/dist/federation/builder.test.mjs +0 -396
  80. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  81. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  82. package/dist/federation/collection.test.d.mts +0 -2
  83. package/dist/federation/collection.test.mjs +0 -21
  84. package/dist/federation/compound-fanout.test.d.mts +0 -2
  85. package/dist/federation/compound-fanout.test.mjs +0 -231
  86. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  87. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  88. package/dist/federation/handler.test.d.mts +0 -2
  89. package/dist/federation/handler.test.mjs +0 -5445
  90. package/dist/federation/hashlink-media.test.d.mts +0 -2
  91. package/dist/federation/hashlink-media.test.mjs +0 -422
  92. package/dist/federation/idempotency.test.d.mts +0 -2
  93. package/dist/federation/idempotency.test.mjs +0 -207
  94. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  95. package/dist/federation/inbox-actorless.test.mjs +0 -522
  96. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  97. package/dist/federation/inbox-authentication.test.mjs +0 -220
  98. package/dist/federation/inbox-report.test.d.mts +0 -2
  99. package/dist/federation/inbox-report.test.mjs +0 -719
  100. package/dist/federation/inbox-view.test.d.mts +0 -2
  101. package/dist/federation/inbox-view.test.mjs +0 -369
  102. package/dist/federation/inbox.test.d.mts +0 -2
  103. package/dist/federation/inbox.test.mjs +0 -139
  104. package/dist/federation/keycache.test.d.mts +0 -2
  105. package/dist/federation/keycache.test.mjs +0 -337
  106. package/dist/federation/kv.test.d.mts +0 -2
  107. package/dist/federation/kv.test.mjs +0 -88
  108. package/dist/federation/metrics.test.d.mts +0 -2
  109. package/dist/federation/metrics.test.mjs +0 -634
  110. package/dist/federation/middleware.test.d.mts +0 -2
  111. package/dist/federation/middleware.test.mjs +0 -9314
  112. package/dist/federation/mq.test.d.mts +0 -2
  113. package/dist/federation/mq.test.mjs +0 -591
  114. package/dist/federation/negotiation.test.d.mts +0 -2
  115. package/dist/federation/negotiation.test.mjs +0 -18
  116. package/dist/federation/outbound-body.test.d.mts +0 -2
  117. package/dist/federation/outbound-body.test.mjs +0 -149
  118. package/dist/federation/outbound-capture.test.d.mts +0 -2
  119. package/dist/federation/outbound-capture.test.mjs +0 -394
  120. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  121. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  122. package/dist/federation/outbound-document.test.d.mts +0 -2
  123. package/dist/federation/outbound-document.test.mjs +0 -171
  124. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  125. package/dist/federation/outbound-provenance.test.mjs +0 -543
  126. package/dist/federation/outbound-report.test.d.mts +0 -2
  127. package/dist/federation/outbound-report.test.mjs +0 -5475
  128. package/dist/federation/outbound-workers.test.d.mts +0 -2
  129. package/dist/federation/outbound-workers.test.mjs +0 -64
  130. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  131. package/dist/federation/outbound-workflow.test.mjs +0 -154
  132. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  133. package/dist/federation/outgoing-proof.test.mjs +0 -933
  134. package/dist/federation/portable-actor.test.d.mts +0 -2
  135. package/dist/federation/portable-actor.test.mjs +0 -496
  136. package/dist/federation/portable-chain.test.d.mts +0 -2
  137. package/dist/federation/portable-chain.test.mjs +0 -370
  138. package/dist/federation/portable-collection.test.d.mts +0 -2
  139. package/dist/federation/portable-collection.test.mjs +0 -832
  140. package/dist/federation/portable-delivery.test.d.mts +0 -2
  141. package/dist/federation/portable-delivery.test.mjs +0 -845
  142. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  143. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  144. package/dist/federation/portable-inbox.test.d.mts +0 -2
  145. package/dist/federation/portable-inbox.test.mjs +0 -1960
  146. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  147. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  148. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  149. package/dist/federation/portable-route-activity.test.mjs +0 -259
  150. package/dist/federation/portable.test.d.mts +0 -2
  151. package/dist/federation/portable.test.mjs +0 -1072
  152. package/dist/federation/retry.test.d.mts +0 -2
  153. package/dist/federation/retry.test.mjs +0 -42
  154. package/dist/federation/router.test.d.mts +0 -2
  155. package/dist/federation/router.test.mjs +0 -123
  156. package/dist/federation/send.test.d.mts +0 -2
  157. package/dist/federation/send.test.mjs +0 -1421
  158. package/dist/federation/tasks/codec.test.d.mts +0 -2
  159. package/dist/federation/tasks/codec.test.mjs +0 -302
  160. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  161. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  162. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  163. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  164. package/dist/federation/temporal.test.d.mts +0 -2
  165. package/dist/federation/temporal.test.mjs +0 -71
  166. package/dist/federation/webfinger.test.d.mts +0 -2
  167. package/dist/federation/webfinger.test.mjs +0 -944
  168. package/dist/http-l1zKGCll.mjs +0 -1449
  169. package/dist/inbox-CWX3EBTO.mjs +0 -399
  170. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  171. package/dist/inbox-view-DkPCF71K.mjs +0 -385
  172. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  173. package/dist/keycache-N2opu4-3.mjs +0 -221
  174. package/dist/keys-DIJNHW-Y.mjs +0 -120
  175. package/dist/kv-DBRWVx3Q.mjs +0 -104
  176. package/dist/kv-DCHkaJ9-.mjs +0 -92
  177. package/dist/kv-cache-8eJh4Xum.mjs +0 -121
  178. package/dist/ld-Cdt8qD-r.mjs +0 -1752
  179. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  180. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  181. package/dist/metrics-BnfvSPj9.mjs +0 -818
  182. package/dist/middleware-CwnXJze2.mjs +0 -5
  183. package/dist/middleware-D_W_LdJN.mjs +0 -9971
  184. package/dist/mq-eF96QxUT.mjs +0 -288
  185. package/dist/negotiation-BAKO9nih.mjs +0 -96
  186. package/dist/nodeinfo/client.test.d.mts +0 -2
  187. package/dist/nodeinfo/client.test.mjs +0 -1364
  188. package/dist/nodeinfo/handler.test.d.mts +0 -2
  189. package/dist/nodeinfo/handler.test.mjs +0 -94
  190. package/dist/nodeinfo/types.test.d.mts +0 -2
  191. package/dist/nodeinfo/types.test.mjs +0 -192
  192. package/dist/otel/exporter.test.d.mts +0 -2
  193. package/dist/otel/exporter.test.mjs +0 -887
  194. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  195. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  196. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  197. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  198. package/dist/owner-DukEQnv3.mjs +0 -267
  199. package/dist/portable-collection-OHaqa11n.mjs +0 -418
  200. package/dist/portable-key-BkOLJxVz.mjs +0 -549
  201. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  202. package/dist/proof-Y7omSVvc.mjs +0 -1420
  203. package/dist/public-audience--klBIOk1.mjs +0 -197
  204. package/dist/retry-zX5xw5e0.mjs +0 -34
  205. package/dist/router-u5O5KCQr.mjs +0 -156
  206. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  207. package/dist/send-ccQynabr.mjs +0 -710
  208. package/dist/sig/accept.test.d.mts +0 -2
  209. package/dist/sig/accept.test.mjs +0 -416
  210. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  211. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  212. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  213. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  214. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  215. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  216. package/dist/sig/compound-proof.test.d.mts +0 -2
  217. package/dist/sig/compound-proof.test.mjs +0 -411
  218. package/dist/sig/http.test.d.mts +0 -2
  219. package/dist/sig/http.test.mjs +0 -3328
  220. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  221. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  222. package/dist/sig/key.test.d.mts +0 -2
  223. package/dist/sig/key.test.mjs +0 -1250
  224. package/dist/sig/ld.test.d.mts +0 -2
  225. package/dist/sig/ld.test.mjs +0 -1044
  226. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  227. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  228. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  229. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  230. package/dist/sig/owner.test.d.mts +0 -2
  231. package/dist/sig/owner.test.mjs +0 -202
  232. package/dist/sig/portable-collection.test.d.mts +0 -2
  233. package/dist/sig/portable-collection.test.mjs +0 -697
  234. package/dist/sig/portable-interop.test.d.mts +0 -2
  235. package/dist/sig/portable-interop.test.mjs +0 -156
  236. package/dist/sig/portable-key-id.test.d.mts +0 -2
  237. package/dist/sig/portable-key-id.test.mjs +0 -67
  238. package/dist/sig/portable-key.test.d.mts +0 -2
  239. package/dist/sig/portable-key.test.mjs +0 -1438
  240. package/dist/sig/proof.test.d.mts +0 -2
  241. package/dist/sig/proof.test.mjs +0 -2638
  242. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  243. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  244. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  245. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  246. package/dist/sig/verification.test.d.mts +0 -2
  247. package/dist/sig/verification.test.mjs +0 -310
  248. package/dist/std__assert-DvMDRPes.mjs +0 -8
  249. package/dist/tasks-BCUmQbbz.mjs +0 -77
  250. package/dist/temporal-f_K4lAVR.mjs +0 -95
  251. package/dist/testing/context.test.d.mts +0 -2
  252. package/dist/testing/context.test.mjs +0 -19
  253. package/dist/testing/kv.test.d.mts +0 -2
  254. package/dist/testing/kv.test.mjs +0 -101
  255. package/dist/testing/mod.d.mts +0 -6099
  256. package/dist/testing/mod.mjs +0 -9
  257. package/dist/testing-vrnD5Uaa.mjs +0 -8
  258. package/dist/types-DE_LV1JB.mjs +0 -46
  259. package/dist/utils/docloader.test.d.mts +0 -2
  260. package/dist/utils/docloader.test.mjs +0 -1076
  261. package/dist/utils/kv-cache.test.d.mts +0 -2
  262. package/dist/utils/kv-cache.test.mjs +0 -261
  263. package/dist/verification-C3954hQh.mjs +0 -5
  264. package/dist/verification-Dpfcw8ml.mjs +0 -105
  265. package/dist/vocab/cjs.test.d.mts +0 -2
  266. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,1449 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { m as parseKeyIdString } from "./portable-key-id-Ca30-hOa.mjs";
5
- import { a as verificationObservation, i as triedKey, n as observeCheck, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
6
- import { n as version, t as name } from "./deno-eoFpPk7W.mjs";
7
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-BnfvSPj9.mjs";
8
- import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature } from "./accept-CPVqki78.mjs";
9
- import { a as promoteKeyOwnerEvidence } from "./key-owner-evidence-APB6NpSk.mjs";
10
- import { D as validateCryptoKey, b as bypassKeyCacheReads, w as fetchKeyDetailed } from "./ld-Cdt8qD-r.mjs";
11
- import { n as resolvePortableActorKey, r as verifyPortableGatewayKeyDocument } from "./portable-key-BkOLJxVz.mjs";
12
- import { getLogger } from "@logtape/logtape";
13
- import { CryptographicKey } from "@fedify/vocab";
14
- import { SpanStatusCode, trace } from "@opentelemetry/api";
15
- import { FetchError } from "@fedify/vocab-runtime";
16
- import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
17
- import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
18
- import { encodeHex } from "byte-encodings/hex";
19
- import { Item, decodeDict, encodeDict, encodeItem } from "structured-field-values";
20
- //#region src/sig/http.ts
21
- const DEFAULT_MAX_REDIRECTION = 20;
22
- const DOUBLE_KNOCK_TRANSPORT_RETRY_DELAY_MS = 100;
23
- /**
24
- * Signs a request using the given private key.
25
- * @param request The request to sign.
26
- * @param privateKey The private key to use for signing.
27
- * @param keyId The key ID to use for the signature. It will be used by the
28
- * verifier.
29
- * @returns The signed request.
30
- * @throws {TypeError} If the private key is invalid or unsupported.
31
- */
32
- async function signRequest(request, privateKey, keyId, options = {}) {
33
- validateCryptoKey(privateKey, "private");
34
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("http_signatures.sign", async (span) => {
35
- try {
36
- const spec = options.spec ?? "draft-cavage-http-signatures-12";
37
- let signed;
38
- if (spec === "rfc9421") signed = await signRequestRfc9421(request, privateKey, keyId, span, options.currentTime, options.body, options.rfc9421);
39
- else signed = await signRequestDraft(request, privateKey, keyId, span, options.currentTime, options.body);
40
- if (span.isRecording()) {
41
- span.setAttribute(ATTR_HTTP_REQUEST_METHOD, signed.method);
42
- span.setAttribute(ATTR_URL_FULL, signed.url);
43
- for (const [name, value] of signed.headers) span.setAttribute(ATTR_HTTP_REQUEST_HEADER(name), value);
44
- span.setAttribute("http_signatures.key_id", keyId.href);
45
- }
46
- return signed;
47
- } catch (error) {
48
- span.setStatus({
49
- code: SpanStatusCode.ERROR,
50
- message: String(error)
51
- });
52
- throw error;
53
- } finally {
54
- span.end();
55
- }
56
- });
57
- }
58
- async function signRequestDraft(request, privateKey, keyId, span, currentTime, bodyBuffer) {
59
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
60
- const url = new URL(request.url);
61
- const body = bodyBuffer !== void 0 ? bodyBuffer : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
62
- const headers = new Headers(request.headers);
63
- if (!headers.has("Host")) headers.set("Host", url.host);
64
- if (!headers.has("Digest") && body != null) {
65
- const digest = await crypto.subtle.digest("SHA-256", body);
66
- headers.set("Digest", `SHA-256=${encodeBase64(digest)}`);
67
- if (span.isRecording()) span.setAttribute("http_signatures.digest.sha-256", encodeHex(digest));
68
- }
69
- if (!headers.has("Date")) headers.set("Date", currentTime == null ? (/* @__PURE__ */ new Date()).toUTCString() : new Date(currentTime.toString()).toUTCString());
70
- const serialized = [["(request-target)", `${request.method.toLowerCase()} ${url.pathname}`], ...headers];
71
- const headerNames = serialized.map(([name]) => name);
72
- const message = serialized.map(([name, value]) => `${name}: ${value.trim()}`).join("\n");
73
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, new TextEncoder().encode(message));
74
- const sigHeader = `keyId="${keyId.href}",algorithm="rsa-sha256",headers="${headerNames.join(" ")}",signature="${encodeBase64(signature)}"`;
75
- headers.set("Signature", sigHeader);
76
- if (span.isRecording()) {
77
- span.setAttribute("http_signatures.algorithm", "rsa-sha256");
78
- span.setAttribute("http_signatures.signature", encodeHex(signature));
79
- }
80
- return new Request(request, {
81
- headers,
82
- body
83
- });
84
- }
85
- function formatRfc9421SignatureParameters(params) {
86
- return Array.from(iterRfc9421(params)).join(";");
87
- }
88
- function* iterRfc9421(params) {
89
- yield `alg="${params.algorithm}"`;
90
- yield `keyid="${params.keyId.href}"`;
91
- yield `created=${params.created}`;
92
- if (params.expires != null) yield `expires=${params.expires}`;
93
- if (params.nonce != null) yield `nonce="${escapeSfString(params.nonce)}"`;
94
- if (params.tag != null) yield `tag="${escapeSfString(params.tag)}"`;
95
- }
96
- const escapeSfString = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
97
- function formatComponentId(component) {
98
- return encodeItem(new Item(component.value, component.params));
99
- }
100
- /**
101
- * Creates a signature base for a request according to RFC 9421.
102
- * @param request The request to create a signature base for.
103
- * @param components The components to include in the signature base.
104
- * @param parameters The signature parameters to include in the signature base.
105
- * @returns The signature base as a string.
106
- */
107
- function createRfc9421SignatureBase(request, components, parameters) {
108
- const url = new URL(request.url);
109
- return components.map((component) => {
110
- const id = formatComponentId(component);
111
- const derived = derivedComponents[component.value]?.(request, url);
112
- if (derived != null) return `${id}: ${derived}`;
113
- if (component.value.startsWith("@")) throw new Error(`Unsupported derived component: ${component.value}`);
114
- const header = request.headers.get(component.value);
115
- if (header == null) throw new Error(`Missing header: ${component.value}`);
116
- return `${id}: ${header}`;
117
- }).concat([`"@signature-params": (${components.map((c) => formatComponentId(c)).join(" ")});${parameters}`]).join("\n");
118
- }
119
- const derivedComponents = {
120
- "@method": (request) => request.method.toUpperCase(),
121
- "@target-uri": (_, url) => url.href,
122
- "@authority": (_, url) => url.host,
123
- "@scheme": (_, url) => url.protocol.slice(0, -1),
124
- "@request-target": (request, url) => `${request.method.toLowerCase()} ${url.pathname}${url.search}`,
125
- "@path": (_, url) => url.pathname,
126
- "@query": (_, { search }) => search.startsWith("?") ? search.slice(1) : search,
127
- "@query-param": () => {
128
- throw new Error("@query-param requires a parameter name");
129
- },
130
- "@status": () => {
131
- throw new Error("@status is only valid for responses");
132
- }
133
- };
134
- /**
135
- * Formats a signature using rfc9421 format.
136
- * @param signature The raw signature bytes.
137
- * @param components The components that were signed.
138
- * @param parameters The signature parameters.
139
- * @returns The formatted signature string.
140
- */
141
- function formatRfc9421Signature(signature, components, parameters, label = "sig1") {
142
- return [`${label}=(${components.map((c) => formatComponentId(c)).join(" ")});${parameters}`, `${label}=:${encodeBase64(signature)}:`];
143
- }
144
- /**
145
- * Parse RFC 9421 Signature-Input header.
146
- * @param signatureInput The Signature-Input header value.
147
- * @returns Parsed signature input parameters.
148
- */
149
- function parseRfc9421SignatureInput(signatureInput) {
150
- let dict;
151
- try {
152
- dict = decodeDict(signatureInput);
153
- } catch (error) {
154
- getLogger([
155
- "fedify",
156
- "sig",
157
- "http"
158
- ]).debug("Failed to parse Signature-Input header: {signatureInput}", {
159
- signatureInput,
160
- error
161
- });
162
- return {};
163
- }
164
- const result = {};
165
- for (const [label, item] of Object.entries(dict)) {
166
- if (!Array.isArray(item.value) || typeof item.params.keyid !== "string" || typeof item.params.created !== "number") continue;
167
- const components = item.value.filter((subitem) => typeof subitem.value === "string").map((subitem) => ({
168
- value: subitem.value,
169
- params: subitem.params ?? {}
170
- }));
171
- const params = encodeItem(new Item(0, item.params));
172
- result[label] = {
173
- keyId: item.params.keyid,
174
- alg: item.params.alg,
175
- created: item.params.created,
176
- nonce: typeof item.params.nonce === "string" ? item.params.nonce : void 0,
177
- tag: typeof item.params.tag === "string" ? item.params.tag : void 0,
178
- components,
179
- parameters: params.slice(params.indexOf(";") + 1)
180
- };
181
- }
182
- return result;
183
- }
184
- /**
185
- * Parse RFC 9421 Signature header.
186
- * @param signature The Signature header value.
187
- * @returns Parsed signature values.
188
- */
189
- function parseRfc9421Signature(signature) {
190
- let dict;
191
- try {
192
- dict = decodeDict(signature);
193
- } catch (error) {
194
- getLogger([
195
- "fedify",
196
- "sig",
197
- "http"
198
- ]).debug("Failed to parse Signature header: {signature}", {
199
- signature,
200
- error
201
- });
202
- return {};
203
- }
204
- const result = {};
205
- for (const [key, value] of Object.entries(dict)) if (value.value instanceof Uint8Array) result[key] = value.value;
206
- return result;
207
- }
208
- /**
209
- * Parses the `Signature` header of draft-cavage HTTP Signatures into its
210
- * fields, e.g., `keyId` and `headers`.
211
- */
212
- function parseDraftSignature(signature) {
213
- return Object.fromEntries(signature.split(",").map((pair) => pair.match(/^\s*([A-Za-z]+)=(?:"([^"]*)"|(\d+))\s*$/)).filter((m) => m != null).map((m) => [m[1], m[2] ?? m[3]]));
214
- }
215
- /**
216
- * Lists the HTTP Signatures that a request claims to carry, without verifying
217
- * any of them. Signatures whose key IDs are not URLs are left out.
218
- * @param request The request.
219
- * @param maxSignatures The maximum number of RFC 9421 signatures to consider,
220
- * counted the same way as by {@link verifyRequest}, so
221
- * that the signatures it ignores are not listed either.
222
- * @returns The signatures; RFC 9421 ones if the request has
223
- * a `Signature-Input` header, or a draft-cavage one otherwise.
224
- * @internal
225
- */
226
- function listRequestSignatures(request, maxSignatures = 3) {
227
- const signatureInput = request.headers.get("Signature-Input");
228
- if (signatureInput != null) {
229
- const signatures = [];
230
- const inputs = Object.entries(parseRfc9421SignatureInput(signatureInput));
231
- for (const [label, input] of inputs.slice(0, maxSignatures)) {
232
- const keyId = parseKeyId(input.keyId);
233
- if (keyId == null) continue;
234
- signatures.push({
235
- keyId,
236
- label,
237
- components: input.components
238
- });
239
- }
240
- return signatures;
241
- }
242
- const signature = request.headers.get("Signature");
243
- if (signature == null) return [];
244
- const values = parseDraftSignature(signature);
245
- const keyId = parseKeyId(values.keyId);
246
- if (keyId == null) return [];
247
- return [{
248
- keyId,
249
- label: null,
250
- components: (values.headers ?? "").split(/\s+/g).filter((name) => name !== "").map((name) => ({
251
- value: name,
252
- params: {}
253
- }))
254
- }];
255
- }
256
- /**
257
- * Makes a copy of a request that carries only one of its RFC 9421 signatures,
258
- * so that verifying the copy verifies that signature and no other.
259
- * A draft-cavage signature is the only one in its request, so the request is
260
- * just copied.
261
- * @param request The request, whose body must not be consumed.
262
- * @param signature One of the signatures that {@link listRequestSignatures}
263
- * lists for the request.
264
- * @returns The copy of the request.
265
- * @internal
266
- */
267
- function selectRequestSignature(request, signature) {
268
- const copy = request.clone();
269
- if (signature.label == null) return copy;
270
- const { label } = signature;
271
- const pick = (header) => {
272
- if (header == null) return "";
273
- let dict;
274
- try {
275
- dict = decodeDict(header);
276
- } catch {
277
- return "";
278
- }
279
- return Object.hasOwn(dict, label) ? encodeDict({ [label]: dict[label] }) : "";
280
- };
281
- const headers = new Headers(copy.headers);
282
- headers.set("Signature-Input", pick(headers.get("Signature-Input")));
283
- headers.set("Signature", pick(headers.get("Signature")));
284
- return new Request(copy, { headers });
285
- }
286
- async function signRequestRfc9421(request, privateKey, keyId, span, currentTime, bodyBuffer, rfc9421Options) {
287
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
288
- const url = new URL(request.url);
289
- const body = bodyBuffer !== void 0 ? bodyBuffer : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
290
- const headers = new Headers(request.headers);
291
- if (!headers.has("Host")) headers.set("Host", url.host);
292
- if (!headers.has("Content-Digest") && body != null) {
293
- const digest = await crypto.subtle.digest("SHA-256", body);
294
- headers.set("Content-Digest", `sha-256=:${encodeBase64(digest)}:`);
295
- if (span.isRecording()) span.setAttribute("http_signatures.digest.sha-256", encodeHex(digest));
296
- }
297
- currentTime ??= Temporal.Now.instant();
298
- const created = currentTime.epochMilliseconds / 1e3 | 0;
299
- if (!headers.has("Date")) headers.set("Date", new Date(currentTime.toString()).toUTCString());
300
- const label = rfc9421Options?.label ?? "sig1";
301
- const components = [...rfc9421Options?.components ?? [
302
- {
303
- value: "@method",
304
- params: {}
305
- },
306
- {
307
- value: "@target-uri",
308
- params: {}
309
- },
310
- {
311
- value: "@authority",
312
- params: {}
313
- },
314
- {
315
- value: "host",
316
- params: {}
317
- },
318
- {
319
- value: "date",
320
- params: {}
321
- }
322
- ], ...body != null ? [{
323
- value: "content-digest",
324
- params: {}
325
- }] : []];
326
- const signatureParams = formatRfc9421SignatureParameters({
327
- algorithm: "rsa-v1_5-sha256",
328
- keyId,
329
- created,
330
- expires: rfc9421Options?.expires === true ? (currentTime.epochMilliseconds / 1e3 | 0) + 3600 : void 0,
331
- nonce: rfc9421Options?.nonce,
332
- tag: rfc9421Options?.tag
333
- });
334
- let signatureBase;
335
- try {
336
- signatureBase = createRfc9421SignatureBase(new Request(request.url, {
337
- method: request.method,
338
- headers
339
- }), components, signatureParams);
340
- } catch (error) {
341
- throw new TypeError(`Failed to create signature base: ${String(error)}; it is probably a bug in the implementation. Please report it at Fedify's issue tracker.`);
342
- }
343
- const signatureBytes = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, new TextEncoder().encode(signatureBase));
344
- const [signatureInput, signature] = formatRfc9421Signature(signatureBytes, components, signatureParams, label);
345
- const existingInput = headers.get("Signature-Input");
346
- headers.set("Signature-Input", existingInput != null ? `${existingInput}, ${signatureInput}` : signatureInput);
347
- const existingSignature = headers.get("Signature");
348
- headers.set("Signature", existingSignature != null ? `${existingSignature}, ${signature}` : signature);
349
- if (span.isRecording()) {
350
- span.setAttribute("http_signatures.algorithm", "rsa-v1_5-sha256");
351
- span.setAttribute("http_signatures.signature", encodeHex(signatureBytes));
352
- span.setAttribute("http_signatures.created", created.toString());
353
- }
354
- return new Request(request, {
355
- headers,
356
- body
357
- });
358
- }
359
- /**
360
- * Checks that a maximum number of signatures to verify is a positive safe
361
- * integer or `Infinity`.
362
- * @param value The value to check.
363
- * @param name The name of the option, used in the error message.
364
- * @throws {RangeError} Thrown if the value is not valid.
365
- * @internal
366
- */
367
- function validateMaxSignatures(value, name) {
368
- if (value === Infinity || Number.isSafeInteger(value) && value >= 1) return;
369
- throw new RangeError(`${name} must be a positive integer or Infinity.`);
370
- }
371
- const supportedHashAlgorithms = {
372
- "sha": "SHA-1",
373
- "sha-256": "SHA-256",
374
- "sha-512": "SHA-512"
375
- };
376
- function noSignatureResult() {
377
- return {
378
- verified: false,
379
- reason: { type: "noSignature" }
380
- };
381
- }
382
- function invalidSignatureResult(keyId) {
383
- return keyId == null ? {
384
- verified: false,
385
- reason: { type: "invalidSignature" }
386
- } : {
387
- verified: false,
388
- reason: {
389
- type: "invalidSignature",
390
- keyId
391
- }
392
- };
393
- }
394
- function keyFetchErrorResult(keyId, result) {
395
- return {
396
- verified: false,
397
- reason: {
398
- type: "keyFetchError",
399
- keyId,
400
- result
401
- }
402
- };
403
- }
404
- /**
405
- * Creates the resolvers of keys of FEP-ef61 portable actors, which HTTP
406
- * Signature verification alone passes to key lookups.
407
- */
408
- function createPortableKeyResolvers(options) {
409
- return {
410
- gatewayKey: (document, actor, keyId) => verifyPortableGatewayKeyDocument(document, actor, keyId, options),
411
- actorKey: (keyId) => resolvePortableActorKey(keyId, options)
412
- };
413
- }
414
- function parseKeyId(value) {
415
- return value == null ? null : parseKeyIdString(value);
416
- }
417
- function getKeyFetchErrorName(error) {
418
- return error.name || error.constructor.name || "Error";
419
- }
420
- /**
421
- * Known draft-cavage `algorithm` parameter values, used to keep the
422
- * `http_signatures.algorithm` metric attribute on a bounded set. The header
423
- * field is attacker-controlled and not used to select the verification
424
- * algorithm, so unknown values are dropped from the metric to prevent
425
- * cardinality blow-up.
426
- */
427
- const DRAFT_KNOWN_ALGORITHMS = /* @__PURE__ */ new Set([
428
- "ecdsa-sha256",
429
- "ecdsa-sha384",
430
- "ecdsa-sha512",
431
- "ed25519",
432
- "hs2019",
433
- "rsa-sha1",
434
- "rsa-sha256",
435
- "rsa-sha512"
436
- ]);
437
- function classifyHttpVerifyResult(result) {
438
- if (result.verified) return "verified";
439
- return result.reason.type === "noSignature" ? "missing" : "rejected";
440
- }
441
- function recordVerificationResult(span, result) {
442
- span.setAttribute("http_signatures.verified", result.verified);
443
- if (result.verified === true) return;
444
- const reason = result.reason;
445
- span.setAttribute("http_signatures.failure_reason", reason.type);
446
- if ("keyId" in reason && reason.keyId != null) span.setAttribute("http_signatures.key_id", reason.keyId.href);
447
- if (reason.type !== "keyFetchError") return;
448
- if ("status" in reason.result) span.setAttribute("http_signatures.key_fetch_status", reason.result.status);
449
- else span.setAttribute("http_signatures.key_fetch_error", getKeyFetchErrorName(reason.result.error));
450
- }
451
- /**
452
- * Verifies the signature of a request.
453
- *
454
- * Note that this function consumes the request body, so it should not be used
455
- * if the request body is already consumed. Consuming the request body after
456
- * calling this function is okay, since this function clones the request
457
- * under the hood.
458
- *
459
- * @param request The request to verify.
460
- * @param options Options for verifying the request.
461
- * @returns The public key of the verified signature, or `null` if the signature
462
- * could not be verified.
463
- * @throws {RangeError} Thrown if {@link VerifyRequestOptions.maxSignatures}
464
- * is not a positive integer or `Infinity`.
465
- */
466
- async function verifyRequest(request, options = {}) {
467
- const result = await verifyRequestDetailed(request, options);
468
- return result.verified ? result.key : null;
469
- }
470
- /**
471
- * Verifies the signature of a request and returns a structured failure reason
472
- * when verification does not succeed.
473
- *
474
- * @param request The request to verify.
475
- * @param options Options for verifying the request.
476
- * @returns The verified public key, or a structured verification failure.
477
- * @throws {RangeError} Thrown if {@link VerifyRequestOptions.maxSignatures}
478
- * is not a positive integer or `Infinity`.
479
- * @since 2.1.0
480
- */
481
- async function verifyRequestDetailed(request, options = {}) {
482
- if (options[verificationObservation] != null && options[verificationObservation]?.attempt == null) return await observeAttempt(options, "http", async (observation) => {
483
- const result = await verifyRequestDetailed(request, {
484
- ...options,
485
- [verificationObservation]: observation
486
- });
487
- if (!result.verified) observation.attempt.reason = result.reason.type === "noSignature" ? { type: "noSignature" } : { type: "signatureVerificationFailed" };
488
- return result;
489
- }, (result) => result.verified);
490
- if (options.maxSignatures !== void 0) validateMaxSignatures(options.maxSignatures, "maxSignatures");
491
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("http_signatures.verify", async (span) => {
492
- if (span.isRecording()) {
493
- span.setAttribute(ATTR_HTTP_REQUEST_METHOD, request.method);
494
- span.setAttribute(ATTR_URL_FULL, request.url);
495
- for (const [name, value] of request.headers) span.setAttribute(ATTR_HTTP_REQUEST_HEADER(name), value);
496
- }
497
- const start = performance.now();
498
- const metricsContext = {};
499
- let result;
500
- let threw = false;
501
- try {
502
- let spec = options.spec;
503
- if (spec == null) spec = request.headers.has("Signature-Input") ? "rfc9421" : "draft-cavage-http-signatures-12";
504
- if (spec === "rfc9421") result = await verifyRequestRfc9421(request, span, metricsContext, options);
505
- else result = await verifyRequestDraft(request, span, metricsContext, options);
506
- recordVerificationResult(span, result);
507
- if (result.verified) promoteKeyOwnerEvidence(result.key);
508
- else span.setStatus({ code: SpanStatusCode.ERROR });
509
- return result;
510
- } catch (error) {
511
- threw = true;
512
- span.setStatus({
513
- code: SpanStatusCode.ERROR,
514
- message: String(error)
515
- });
516
- throw error;
517
- } finally {
518
- const classified = threw ? "error" : classifyHttpVerifyResult(result);
519
- const failureReason = result != null && !result.verified && result.reason.type !== "noSignature" ? result.reason.type : void 0;
520
- getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "http", classified, {
521
- algorithm: metricsContext.algorithm,
522
- failureReason
523
- });
524
- span.end();
525
- }
526
- });
527
- }
528
- async function verifyRequestDraft(request, span, metricsContext, options = {}) {
529
- if (options[verificationObservation]?.check != null) return await verifyRequestDraftInternal(request, span, metricsContext, options);
530
- let result = noSignatureResult();
531
- const raw = request.headers.get("Signature");
532
- const declared = raw == null ? null : parseDraftSignature(raw)?.keyId ?? null;
533
- if (raw == null) return result;
534
- await observeCheck(options, {
535
- mechanism: "http",
536
- spec: "draft-cavage-http-signatures-12",
537
- label: null
538
- }, declared, async (observation) => {
539
- result = await verifyRequestDraftInternal(request, span, metricsContext, {
540
- ...options,
541
- [verificationObservation]: observation
542
- });
543
- if (!result.verified && result.reason.type === "keyFetchError" && observation.check != null) observation.check.reason = result.reason;
544
- return result.verified ? result.key : null;
545
- });
546
- return result;
547
- }
548
- async function verifyRequestDraftInternal(request, span, metricsContext, { documentLoader, contextLoader, timeWindow, currentTime, keyCache, meterProvider, tracerProvider, [verificationObservation]: observation } = {}) {
549
- const logger = getLogger([
550
- "fedify",
551
- "sig",
552
- "http"
553
- ]);
554
- if (request.bodyUsed) {
555
- logger.error("Failed to verify; the request body is already consumed.", { url: request.url });
556
- return noSignatureResult();
557
- } else if (request.body?.locked) {
558
- logger.error("Failed to verify; the request body is locked.", { url: request.url });
559
- return noSignatureResult();
560
- }
561
- const originalRequest = request;
562
- request = request.clone();
563
- const sigHeader = request.headers.get("Signature");
564
- if (sigHeader == null) {
565
- logger.debug("Failed to verify; no Signature header found.", { headers: Object.fromEntries(request.headers.entries()) });
566
- return noSignatureResult();
567
- }
568
- const sigValues = parseDraftSignature(sigHeader);
569
- const parsedKeyId = parseKeyId(sigValues.keyId);
570
- const dateHeader = request.headers.get("Date");
571
- if (dateHeader == null) {
572
- logger.debug("Failed to verify; no Date header found.", { headers: Object.fromEntries(request.headers.entries()) });
573
- return invalidSignatureResult(parsedKeyId);
574
- }
575
- const digestHeader = request.headers.get("Digest");
576
- if (request.method !== "GET" && request.method !== "HEAD" && digestHeader == null) {
577
- logger.debug("Failed to verify; no Digest header found.", { headers: Object.fromEntries(request.headers.entries()) });
578
- return invalidSignatureResult(parsedKeyId);
579
- }
580
- let body = null;
581
- if (digestHeader != null) {
582
- body = await request.arrayBuffer();
583
- const digests = digestHeader.split(",").map((pair) => pair.includes("=") ? pair.split("=", 2) : [pair, ""]);
584
- let matched = false;
585
- for (let [algo, digestBase64] of digests) {
586
- algo = algo.trim().toLowerCase();
587
- if (!(algo in supportedHashAlgorithms)) continue;
588
- let digest;
589
- try {
590
- digest = decodeBase64(digestBase64);
591
- } catch (error) {
592
- logger.debug("Failed to verify; invalid base64 encoding: {digest}.", {
593
- digest: digestBase64,
594
- error
595
- });
596
- return invalidSignatureResult(parsedKeyId);
597
- }
598
- if (span.isRecording()) span.setAttribute(`http_signatures.digest.${algo}`, encodeHex(digest));
599
- const expectedDigest = await crypto.subtle.digest(supportedHashAlgorithms[algo], body);
600
- if (!timingSafeEqual(digest, new Uint8Array(expectedDigest))) {
601
- logger.debug("Failed to verify; digest mismatch ({algorithm}): {digest} != {expectedDigest}.", {
602
- algorithm: algo,
603
- digest: digestBase64,
604
- expectedDigest: encodeBase64(expectedDigest)
605
- });
606
- return invalidSignatureResult(parsedKeyId);
607
- }
608
- matched = true;
609
- }
610
- if (!matched) {
611
- logger.debug("Failed to verify; no supported digest algorithm found. Supported: {supportedAlgorithms}; found: {algorithms}.", {
612
- supportedAlgorithms: Object.keys(supportedHashAlgorithms),
613
- algorithms: digests.map(([algo]) => algo)
614
- });
615
- return invalidSignatureResult(parsedKeyId);
616
- }
617
- }
618
- const date = Temporal.Instant.from(new Date(dateHeader).toISOString());
619
- const now = currentTime ?? Temporal.Now.instant();
620
- if (timeWindow !== false) {
621
- const tw = timeWindow ?? { hours: 1 };
622
- if (Temporal.Instant.compare(date, now.add(tw)) > 0) {
623
- logger.debug("Failed to verify; Date is too far in the future.", {
624
- date: date.toString(),
625
- now: now.toString()
626
- });
627
- return invalidSignatureResult(parsedKeyId);
628
- } else if (Temporal.Instant.compare(date, now.subtract(tw)) < 0) {
629
- logger.debug("Failed to verify; Date is too far in the past.", {
630
- date: date.toString(),
631
- now: now.toString()
632
- });
633
- return invalidSignatureResult(parsedKeyId);
634
- }
635
- }
636
- if (!("keyId" in sigValues)) {
637
- logger.debug("Failed to verify; no keyId field found in the Signature header.", { signature: sigHeader });
638
- return invalidSignatureResult(null);
639
- } else if (!("headers" in sigValues)) {
640
- logger.debug("Failed to verify; no headers field found in the Signature header.", { signature: sigHeader });
641
- return invalidSignatureResult(parsedKeyId);
642
- } else if (!("signature" in sigValues)) {
643
- logger.debug("Failed to verify; no signature field found in the Signature header.", { signature: sigHeader });
644
- return invalidSignatureResult(parsedKeyId);
645
- }
646
- if ("expires" in sigValues) {
647
- const expiresSeconds = parseInt(sigValues.expires);
648
- if (!Number.isInteger(expiresSeconds)) {
649
- logger.debug("Failed to verify; invalid expires field in the Signature header: {expires}.", {
650
- expires: sigValues.expires,
651
- signature: sigHeader
652
- });
653
- return invalidSignatureResult(parsedKeyId);
654
- }
655
- const expires = Temporal.Instant.fromEpochMilliseconds(expiresSeconds * 1e3);
656
- if (Temporal.Instant.compare(now, expires) > 0) {
657
- logger.debug("Failed to verify; signature expired at {expires} (now: {now}).", {
658
- expires: expires.toString(),
659
- now: now.toString(),
660
- signature: sigHeader
661
- });
662
- return invalidSignatureResult(parsedKeyId);
663
- }
664
- }
665
- if ("created" in sigValues) {
666
- const createdSeconds = parseInt(sigValues.created);
667
- if (!Number.isInteger(createdSeconds)) {
668
- logger.debug("Failed to verify; invalid created field in the Signature header: {created}.", {
669
- created: sigValues.created,
670
- signature: sigHeader
671
- });
672
- return invalidSignatureResult(parsedKeyId);
673
- }
674
- if (timeWindow !== false) {
675
- const created = Temporal.Instant.fromEpochMilliseconds(createdSeconds * 1e3);
676
- const tw = timeWindow ?? { minutes: 1 };
677
- if (Temporal.Instant.compare(created, now.add(tw)) > 0) {
678
- logger.debug("Failed to verify; created is too far in the future.", {
679
- created: created.toString(),
680
- now: now.toString()
681
- });
682
- return invalidSignatureResult(parsedKeyId);
683
- } else if (Temporal.Instant.compare(created, now.subtract(tw)) < 0) {
684
- logger.debug("Failed to verify; created is too far in the past.", {
685
- created: created.toString(),
686
- now: now.toString()
687
- });
688
- return invalidSignatureResult(parsedKeyId);
689
- }
690
- }
691
- }
692
- const { keyId, headers, signature } = sigValues;
693
- const keyIdUrl = parseKeyId(keyId);
694
- if (keyIdUrl == null) return invalidSignatureResult(null);
695
- span?.setAttribute("http_signatures.key_id", keyId);
696
- if ("algorithm" in sigValues) {
697
- span?.setAttribute("http_signatures.algorithm", sigValues.algorithm);
698
- const normalizedAlgorithm = sigValues.algorithm.toLowerCase();
699
- if (DRAFT_KNOWN_ALGORITHMS.has(normalizedAlgorithm)) metricsContext.algorithm = normalizedAlgorithm;
700
- }
701
- const { key, cached, fetchError } = await measureSignatureKeyFetch(meterProvider, "http", () => fetchKeyDetailed(keyIdUrl, CryptographicKey, {
702
- documentLoader,
703
- contextLoader,
704
- keyCache,
705
- tracerProvider,
706
- meterProvider,
707
- portableKeyResolvers: createPortableKeyResolvers({
708
- documentLoader,
709
- contextLoader,
710
- keyCache,
711
- tracerProvider,
712
- meterProvider
713
- })
714
- }));
715
- if (fetchError != null) return keyFetchErrorResult(keyIdUrl, fetchError);
716
- if (key == null) return invalidSignatureResult(keyIdUrl);
717
- const headerNames = headers.split(/\s+/g);
718
- if (!headerNames.includes("(request-target)") || !headerNames.includes("date")) {
719
- logger.debug("Failed to verify; required headers missing in the Signature header: {headers}.", { headers });
720
- return invalidSignatureResult(keyIdUrl);
721
- }
722
- if (body != null && !headerNames.includes("digest")) {
723
- logger.debug("Failed to verify; required headers missing in the Signature header: {headers}.", { headers });
724
- return invalidSignatureResult(keyIdUrl);
725
- }
726
- const message = headerNames.map((name) => `${name}: ` + (name === "(request-target)" ? `${request.method.toLowerCase()} ${new URL(request.url).pathname}` : name === "(created)" ? sigValues.created ?? "" : name === "(expires)" ? sigValues.expires ?? "" : name === "host" ? request.headers.get("host") ?? new URL(request.url).host : request.headers.get(name))).join("\n");
727
- const sig = decodeBase64(signature);
728
- span?.setAttribute("http_signatures.signature", encodeHex(sig));
729
- triedKey({ [verificationObservation]: observation }, key);
730
- if (!await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, sig, new TextEncoder().encode(message))) {
731
- if (cached) {
732
- logger.debug("Failed to verify with the cached key {keyId}; signature {signature} is invalid. Retrying with the freshly fetched key...", {
733
- keyId,
734
- signature,
735
- message
736
- });
737
- return await verifyRequestDraft(originalRequest, span, metricsContext, {
738
- documentLoader,
739
- contextLoader,
740
- timeWindow,
741
- currentTime,
742
- keyCache: bypassKeyCacheReads(keyCache),
743
- meterProvider,
744
- tracerProvider,
745
- [verificationObservation]: observation
746
- });
747
- }
748
- logger.debug("Failed to verify with the fetched key {keyId}; signature {signature} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
749
- keyId,
750
- signature,
751
- message
752
- });
753
- return invalidSignatureResult(keyIdUrl);
754
- }
755
- return {
756
- verified: true,
757
- key
758
- };
759
- }
760
- /**
761
- * RFC 9421 map of algorithm identifiers to WebCrypto algorithms
762
- */
763
- const rfc9421AlgorithmMap = {
764
- "rsa-v1_5-sha256": {
765
- name: "RSASSA-PKCS1-v1_5",
766
- hash: "SHA-256"
767
- },
768
- "rsa-v1_5-sha512": {
769
- name: "RSASSA-PKCS1-v1_5",
770
- hash: "SHA-512"
771
- },
772
- "rsa-pss-sha512": {
773
- name: "RSA-PSS",
774
- hash: "SHA-512"
775
- },
776
- "ecdsa-p256-sha256": {
777
- name: "ECDSA",
778
- hash: "SHA-256"
779
- },
780
- "ecdsa-p384-sha384": {
781
- name: "ECDSA",
782
- hash: "SHA-384"
783
- },
784
- "ed25519": { name: "Ed25519" }
785
- };
786
- /**
787
- * Verifies a Content-Digest header according to RFC 9421.
788
- * @param digestHeader The Content-Digest header value.
789
- * @param body The message body to verify against.
790
- * @returns Whether the digest is valid.
791
- */
792
- async function verifyRfc9421ContentDigest(digestHeader, body) {
793
- const digests = digestHeader.split(",").map((pair) => {
794
- pair = pair.trim();
795
- const pos = pair.indexOf("=");
796
- const algo = pos < 0 ? pair : pair.slice(0, pos);
797
- const value = pos < 0 ? "" : pair.slice(pos + 1);
798
- return {
799
- algo: algo.trim().toLowerCase(),
800
- value: value.trim()
801
- };
802
- });
803
- for (const { algo, value } of digests) {
804
- let hashAlgo;
805
- if (algo === "sha-256") hashAlgo = "SHA-256";
806
- else if (algo === "sha-512") hashAlgo = "SHA-512";
807
- else continue;
808
- const base64Match = value.match(/^:([^:]+):$/);
809
- if (!base64Match) continue;
810
- let digest;
811
- try {
812
- digest = decodeBase64(base64Match[1]);
813
- } catch {
814
- continue;
815
- }
816
- const calculatedDigest = await crypto.subtle.digest(hashAlgo, body);
817
- if (timingSafeEqual(digest, new Uint8Array(calculatedDigest))) return true;
818
- }
819
- return false;
820
- }
821
- /**
822
- * Verifies one RFC 9421 signature of a request with a key.
823
- * @param request The request, whose body may be consumed already.
824
- * @param sigInput The parsed `Signature-Input` member of the signature.
825
- * @param sigBytes The bytes of the signature.
826
- * @param key The public key named by the signature.
827
- * @param span The span to record the algorithm and the signature on.
828
- * @returns Whether the signature is verified, and the algorithm of the
829
- * signature if it is supported.
830
- */
831
- async function verifyRfc9421SignatureWithKey(request, sigInput, sigBytes, key, span, observationOptions = {}) {
832
- const logger = getLogger([
833
- "fedify",
834
- "sig",
835
- "http"
836
- ]);
837
- let alg = sigInput.alg?.toLowerCase();
838
- if (alg == null) {
839
- if (key.publicKey.algorithm.name === "RSASSA-PKCS1-v1_5") alg = "hash" in key.publicKey.algorithm ? key.publicKey.algorithm.hash === "SHA-512" ? "rsa-v1_5-sha512" : "rsa-v1_5-sha256" : "rsa-v1_5-sha256";
840
- else if (key.publicKey.algorithm.name === "RSA-PSS") alg = "rsa-pss-sha512";
841
- else if (key.publicKey.algorithm.name === "ECDSA") alg = "namedCurve" in key.publicKey.algorithm && key.publicKey.algorithm.namedCurve === "P-256" ? "ecdsa-p256-sha256" : "ecdsa-p384-sha384";
842
- else if (key.publicKey.algorithm.name === "Ed25519") alg = "ed25519";
843
- }
844
- if (alg) span?.setAttribute("http_signatures.algorithm", alg);
845
- const algorithm = alg && rfc9421AlgorithmMap[alg];
846
- if (!algorithm) {
847
- logger.debug("Failed to verify; unsupported algorithm: {algorithm}", {
848
- algorithm: sigInput.alg,
849
- supported: Object.keys(rfc9421AlgorithmMap)
850
- });
851
- return {
852
- verified: false,
853
- mismatched: false
854
- };
855
- }
856
- const metricAlgorithm = alg;
857
- let signatureBase;
858
- try {
859
- signatureBase = createRfc9421SignatureBase(request, sigInput.components, sigInput.parameters);
860
- } catch (error) {
861
- logger.debug("Failed to create signature base for verification: {error}", {
862
- error,
863
- signatureInput: sigInput
864
- });
865
- return {
866
- verified: false,
867
- algorithm: metricAlgorithm,
868
- mismatched: false
869
- };
870
- }
871
- const signatureBaseBytes = new TextEncoder().encode(signatureBase);
872
- span?.setAttribute("http_signatures.signature", encodeHex(sigBytes));
873
- const algorithmName = typeof algorithm === "string" ? algorithm : algorithm.name;
874
- if (key.publicKey.algorithm.name !== algorithmName) {
875
- logger.debug("Failed to verify; key {keyId} is not a key for algorithm {algorithm}.", {
876
- keyId: sigInput.keyId,
877
- algorithm: alg
878
- });
879
- return {
880
- verified: false,
881
- algorithm: metricAlgorithm,
882
- mismatched: true
883
- };
884
- }
885
- let verified;
886
- try {
887
- triedKey(observationOptions, key);
888
- verified = await crypto.subtle.verify(algorithm, key.publicKey, sigBytes.slice(), signatureBaseBytes);
889
- } catch (error) {
890
- logger.debug("Error during signature verification: {error}", {
891
- error,
892
- keyId: sigInput.keyId,
893
- algorithm: sigInput.alg
894
- });
895
- return {
896
- verified: false,
897
- algorithm: metricAlgorithm,
898
- mismatched: false
899
- };
900
- }
901
- if (verified) return {
902
- verified: true,
903
- algorithm: metricAlgorithm
904
- };
905
- logger.debug("Failed to verify signature with key {keyId}; signature invalid.", {
906
- keyId: sigInput.keyId,
907
- signatureBase
908
- });
909
- return {
910
- verified: false,
911
- algorithm: metricAlgorithm,
912
- mismatched: true
913
- };
914
- }
915
- async function verifyRequestRfc9421(request, span, metricsContext, { documentLoader, contextLoader, timeWindow, currentTime, keyCache, maxSignatures = 3, [verificationObservation]: observation, meterProvider, tracerProvider } = {}) {
916
- const logger = getLogger([
917
- "fedify",
918
- "sig",
919
- "http"
920
- ]);
921
- if (request.bodyUsed) {
922
- logger.error("Failed to verify; the request body is already consumed.", { url: request.url });
923
- return noSignatureResult();
924
- } else if (request.body?.locked) {
925
- logger.error("Failed to verify; the request body is locked.", { url: request.url });
926
- return noSignatureResult();
927
- }
928
- request = request.clone();
929
- const signatureInputHeader = request.headers.get("Signature-Input");
930
- if (!signatureInputHeader) {
931
- logger.debug("Failed to verify; no Signature-Input header found.", { headers: Object.fromEntries(request.headers.entries()) });
932
- return noSignatureResult();
933
- }
934
- const signatureHeader = request.headers.get("Signature");
935
- if (!signatureHeader) {
936
- logger.debug("Failed to verify; no Signature header found.", { headers: Object.fromEntries(request.headers.entries()) });
937
- return noSignatureResult();
938
- }
939
- const signatureInputs = parseRfc9421SignatureInput(signatureInputHeader);
940
- logger.debug("Parsed Signature-Input header: {signatureInputs}", { signatureInputs });
941
- const signatures = parseRfc9421Signature(signatureHeader);
942
- const signatureNames = Object.keys(signatureInputs);
943
- if (signatureNames.length === 0) {
944
- logger.debug("Failed to verify; no valid signatures found in Signature-Input header.", { header: signatureInputHeader });
945
- return invalidSignatureResult(null);
946
- }
947
- if (signatureNames.length > maxSignatures) {
948
- logger.debug("Verifying only the first {maxSignatures} of the {count} signatures in the Signature-Input header; the rest are ignored.", {
949
- maxSignatures,
950
- count: signatureNames.length
951
- });
952
- signatureNames.splice(maxSignatures);
953
- }
954
- const keyLookups = /* @__PURE__ */ new Map();
955
- const refreshedKeyIds = /* @__PURE__ */ new Set();
956
- const lookUpKey = (keyId, keyCache) => measureSignatureKeyFetch(meterProvider, "http", () => fetchKeyDetailed(keyId, CryptographicKey, {
957
- documentLoader,
958
- contextLoader,
959
- keyCache,
960
- tracerProvider,
961
- meterProvider,
962
- portableKeyResolvers: createPortableKeyResolvers({
963
- documentLoader,
964
- contextLoader,
965
- keyCache,
966
- tracerProvider,
967
- meterProvider
968
- })
969
- }));
970
- let failure = noSignatureResult();
971
- let failureAlgorithm;
972
- const setFailure = (result, algorithm) => {
973
- failure = result;
974
- failureAlgorithm = algorithm;
975
- };
976
- let body = null;
977
- let digestValid = null;
978
- for (const sigName of signatureNames) {
979
- let winning;
980
- await observeCheck({ [verificationObservation]: observation }, {
981
- mechanism: "http",
982
- spec: "rfc9421",
983
- label: sigName
984
- }, signatureInputs[sigName]?.keyId ?? null, async (candidateObservation) => {
985
- if (!signatures[sigName]) {
986
- setFailure(invalidSignatureResult(parseKeyId(signatureInputs[sigName]?.keyId)));
987
- return null;
988
- }
989
- const sigInput = signatureInputs[sigName];
990
- const sigBytes = signatures[sigName];
991
- const keyId = parseKeyId(sigInput.keyId);
992
- if (!sigInput.keyId) {
993
- logger.debug("Failed to verify; missing keyId in signature {signatureName}.", {
994
- signatureName: sigName,
995
- signatureInput: signatureInputHeader
996
- });
997
- setFailure(invalidSignatureResult(null));
998
- return null;
999
- }
1000
- if (!sigInput.created) {
1001
- logger.debug("Failed to verify; missing created timestamp in signature {signatureName}.", {
1002
- signatureName: sigName,
1003
- signatureInput: signatureInputHeader
1004
- });
1005
- setFailure(invalidSignatureResult(keyId));
1006
- return null;
1007
- }
1008
- const signatureCreated = Temporal.Instant.fromEpochMilliseconds(sigInput.created * 1e3);
1009
- const now = currentTime ?? Temporal.Now.instant();
1010
- if (timeWindow !== false) {
1011
- const tw = timeWindow ?? { hours: 1 };
1012
- if (Temporal.Instant.compare(signatureCreated, now.add(tw)) > 0) {
1013
- logger.debug("Failed to verify; signature created time is too far in the future.", {
1014
- created: signatureCreated.toString(),
1015
- now: now.toString()
1016
- });
1017
- setFailure(invalidSignatureResult(keyId));
1018
- return null;
1019
- } else if (Temporal.Instant.compare(signatureCreated, now.subtract(tw)) < 0) {
1020
- logger.debug("Failed to verify; signature created time is too far in the past.", {
1021
- created: signatureCreated.toString(),
1022
- now: now.toString()
1023
- });
1024
- setFailure(invalidSignatureResult(keyId));
1025
- return null;
1026
- }
1027
- }
1028
- if (request.method !== "GET" && request.method !== "HEAD" && sigInput.components.some((c) => c.value === "content-digest")) {
1029
- const contentDigestHeader = request.headers.get("Content-Digest");
1030
- if (!contentDigestHeader) {
1031
- logger.debug("Failed to verify; Content-Digest header required but not found.", { components: sigInput.components });
1032
- setFailure(invalidSignatureResult(keyId));
1033
- return null;
1034
- }
1035
- body ??= await request.arrayBuffer();
1036
- digestValid ??= await verifyRfc9421ContentDigest(contentDigestHeader, body);
1037
- if (!digestValid) {
1038
- logger.debug("Failed to verify; Content-Digest verification failed.", { contentDigest: contentDigestHeader });
1039
- setFailure(invalidSignatureResult(keyId));
1040
- return null;
1041
- }
1042
- }
1043
- span?.setAttribute("http_signatures.key_id", sigInput.keyId);
1044
- span?.setAttribute("http_signatures.created", sigInput.created.toString());
1045
- if (keyId == null) {
1046
- setFailure(invalidSignatureResult(null));
1047
- return null;
1048
- }
1049
- let lookup = keyLookups.get(keyId.href);
1050
- if (lookup == null) {
1051
- lookup = await lookUpKey(keyId, keyCache);
1052
- keyLookups.set(keyId.href, lookup);
1053
- }
1054
- while (true) {
1055
- const { key, cached, fetchError } = lookup;
1056
- if (fetchError != null) {
1057
- setFailure(keyFetchErrorResult(keyId, fetchError));
1058
- break;
1059
- }
1060
- if (!key) {
1061
- logger.debug("Failed to fetch key: {keyId}", { keyId: sigInput.keyId });
1062
- setFailure(invalidSignatureResult(keyId));
1063
- break;
1064
- }
1065
- const result = await verifyRfc9421SignatureWithKey(request, sigInput, sigBytes, key, span, { [verificationObservation]: candidateObservation });
1066
- if (result.verified) {
1067
- metricsContext.algorithm = result.algorithm;
1068
- winning = {
1069
- verified: true,
1070
- key,
1071
- signatureLabel: sigName
1072
- };
1073
- return key;
1074
- }
1075
- if (result.mismatched && cached && !refreshedKeyIds.has(keyId.href)) {
1076
- logger.debug("Failed to verify with cached key {keyId}; retrying with fresh key...", { keyId: sigInput.keyId });
1077
- refreshedKeyIds.add(keyId.href);
1078
- lookup = await lookUpKey(keyId, bypassKeyCacheReads(keyCache));
1079
- keyLookups.set(keyId.href, lookup);
1080
- continue;
1081
- }
1082
- setFailure(invalidSignatureResult(keyId), result.algorithm);
1083
- break;
1084
- }
1085
- if (!failure.verified && failure.reason.type === "keyFetchError" && candidateObservation.check != null) candidateObservation.check.reason = failure.reason;
1086
- return null;
1087
- });
1088
- if (winning != null) return winning;
1089
- }
1090
- metricsContext.algorithm = failureAlgorithm;
1091
- return failure;
1092
- }
1093
- /**
1094
- * Helper function to create a new Request for redirect handling.
1095
- * @param request The original request.
1096
- * @param location The redirect location.
1097
- * @param body The request body as ArrayBuffer or null.
1098
- * @param validateRedirect The function to validate the redirect URL.
1099
- * @returns A new Request object for the redirect.
1100
- */
1101
- async function createRedirectRequest(request, location, body, validateRedirect) {
1102
- const url = new URL(location, request.url);
1103
- await validateRedirect?.(url.href);
1104
- return new Request(url, {
1105
- method: request.method,
1106
- headers: request.headers,
1107
- body,
1108
- redirect: "manual",
1109
- signal: request.signal,
1110
- mode: request.mode,
1111
- credentials: request.credentials,
1112
- referrer: request.referrer,
1113
- referrerPolicy: request.referrerPolicy,
1114
- integrity: request.integrity,
1115
- keepalive: request.keepalive,
1116
- cache: request.cache
1117
- });
1118
- }
1119
- function observeDoubleKnockOperation(observation, phase, operation) {
1120
- if (observation == null) return operation();
1121
- try {
1122
- return Promise.resolve(operation()).catch((error) => {
1123
- observation.error(phase, error);
1124
- throw error;
1125
- });
1126
- } catch (error) {
1127
- observation.error(phase, error);
1128
- throw error;
1129
- }
1130
- }
1131
- function submitDoubleKnockRequest(session, request, signal, observation) {
1132
- const submit = () => session.fetch(request, {
1133
- redirect: "manual",
1134
- signal
1135
- });
1136
- return observation == null ? submit() : observation.fetch(request, submit);
1137
- }
1138
- async function fetchDoubleKnockRequest(session, request, signedRequest, signal, observation) {
1139
- const maxAttempts = request.method === "GET" || request.method === "HEAD" ? 2 : 1;
1140
- for (let attempt = 1;; attempt++) try {
1141
- return await submitDoubleKnockRequest(session, signedRequest, signal, observation);
1142
- } catch (error) {
1143
- const abortedSignal = getAbortedSignal(signal, request.signal, signedRequest.signal);
1144
- if (abortedSignal != null) throw getAbortReason(abortedSignal);
1145
- if (isAbortError(error)) throw error;
1146
- if (attempt >= maxAttempts) throw createFetchError(request.url, error);
1147
- await sleep(DOUBLE_KNOCK_TRANSPORT_RETRY_DELAY_MS, signal, request.signal, signedRequest.signal);
1148
- }
1149
- }
1150
- function createFetchError(url, cause) {
1151
- const error = new FetchError(url, cause instanceof Error ? cause.message : String(cause));
1152
- error.cause = cause;
1153
- return error;
1154
- }
1155
- function isAbortError(error) {
1156
- return error instanceof Error && error.name === "AbortError";
1157
- }
1158
- async function sleep(ms, ...signals) {
1159
- const abortSignals = signals.filter((signal) => signal != null);
1160
- const abortedSignal = getAbortedSignal(...abortSignals);
1161
- if (abortedSignal != null) throw getAbortReason(abortedSignal);
1162
- if (abortSignals.length < 1) {
1163
- await new Promise((resolve) => setTimeout(resolve, ms));
1164
- return;
1165
- }
1166
- await new Promise((resolve, reject) => {
1167
- const removeAbortListeners = () => {
1168
- for (const signal of abortSignals) signal.removeEventListener("abort", handleAbort);
1169
- };
1170
- const timeout = setTimeout(() => {
1171
- removeAbortListeners();
1172
- resolve();
1173
- }, ms);
1174
- function handleAbort(event) {
1175
- clearTimeout(timeout);
1176
- removeAbortListeners();
1177
- reject(getAbortReason(event.currentTarget));
1178
- }
1179
- for (const signal of abortSignals) signal.addEventListener("abort", handleAbort, { once: true });
1180
- });
1181
- }
1182
- function getAbortedSignal(...signals) {
1183
- return signals.find((signal) => signal?.aborted);
1184
- }
1185
- function getAbortReason(signal) {
1186
- return signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
1187
- }
1188
- /**
1189
- * Performs a double-knock request to the given URL. For the details of
1190
- * double-knocking, see
1191
- * <https://swicg.github.io/activitypub-http-signature/#how-to-upgrade-supported-versions>.
1192
- * @param request The request to send.
1193
- * @param identity The identity to use for signing the request.
1194
- * @param options The options for double-knock requests.
1195
- * @returns The response to the request.
1196
- * @since 1.6.0
1197
- */
1198
- async function doubleKnock(request, identity, options = {}) {
1199
- const { response } = await doubleKnockCore(request, identity, options, openGlobalFetchHop);
1200
- return response;
1201
- }
1202
- /**
1203
- * Performs a double-knock request like {@link doubleKnock}, opening a session
1204
- * for every hop with the given function, and passes the final response to
1205
- * the given function. The final session is closed after `consume` settles,
1206
- * so `consume` must read or cancel the response body before it returns.
1207
- * This is not exported from any entry point.
1208
- * @param request The request to send.
1209
- * @param identity The identity to use for signing the request.
1210
- * @param options The options for double-knock requests.
1211
- * @param openHop The function to open a session for each hop. The session of
1212
- * a hop is closed before the next hop is opened.
1213
- * @param consume The function to consume the final response.
1214
- * @param observation The in-process transport/finality hooks, if registered.
1215
- * @returns The value returned by `consume`.
1216
- */
1217
- async function doubleKnockScoped(request, identity, options, openHop, consume, observation) {
1218
- const { response, session } = await doubleKnockCore(request, identity, options, openHop, observation);
1219
- try {
1220
- return await consume(response);
1221
- } catch (error) {
1222
- getLogger([
1223
- "fedify",
1224
- "sig",
1225
- "http"
1226
- ]).debug("Failed to consume the response from {url}; closing the session: {error}", {
1227
- url: request.url,
1228
- error
1229
- });
1230
- throw error;
1231
- } finally {
1232
- await session.close();
1233
- }
1234
- }
1235
- /**
1236
- * A hop session for {@link doubleKnock}: it uses the global `fetch()` without
1237
- * validating or pinning addresses, and its `close()` does nothing, so that
1238
- * the final response can be returned to the caller.
1239
- */
1240
- function openGlobalFetchHop(url) {
1241
- const sessionUrl = new URL(url);
1242
- return Promise.resolve({
1243
- get url() {
1244
- return new URL(sessionUrl);
1245
- },
1246
- fetch: (input, init) => fetch(input, init),
1247
- close: () => Promise.resolve()
1248
- });
1249
- }
1250
- function isRedirectResponse(response) {
1251
- return response.status >= 300 && response.status < 400 && response.headers.has("Location");
1252
- }
1253
- /**
1254
- * Starts cancelling the body of a response that is not passed to the caller,
1255
- * without waiting for it to settle. The cancellation of a branch of a tee
1256
- * (e.g., a body cloned by a fetch mock) settles only after the other branch
1257
- * is cancelled too, per the Streams standard, so awaiting it could block
1258
- * forever. Failures are only logged.
1259
- */
1260
- function cancelResponseBody(response, url) {
1261
- response.body?.cancel().catch((error) => {
1262
- getLogger([
1263
- "fedify",
1264
- "sig",
1265
- "http"
1266
- ]).debug("Failed to cancel the response body from {url}: {error}", {
1267
- url,
1268
- error
1269
- });
1270
- });
1271
- }
1272
- async function doubleKnockCore(request, identity, options, openHop, observation) {
1273
- const { specDeterminer, log, tracerProvider, signal } = options;
1274
- signal?.throwIfAborted();
1275
- const maximumRedirection = options.maxRedirection ?? DEFAULT_MAX_REDIRECTION;
1276
- const visited = /* @__PURE__ */ new Set();
1277
- const body = options.body !== void 0 ? options.body : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
1278
- let session = await openHop(request.url);
1279
- try {
1280
- for (let redirected = 0;; redirected++) {
1281
- visited.add(request.url);
1282
- const origin = new URL(request.url).origin;
1283
- const firstTrySpec = specDeterminer == null ? "rfc9421" : await observeDoubleKnockOperation(observation, "spec-lookup", () => specDeterminer.determineSpec(origin));
1284
- signal?.throwIfAborted();
1285
- let signedRequest = await observeDoubleKnockOperation(observation, "signing", () => signRequest(request, identity.privateKey, identity.keyId, {
1286
- spec: firstTrySpec,
1287
- tracerProvider,
1288
- body
1289
- }));
1290
- signal?.throwIfAborted();
1291
- log?.(signedRequest);
1292
- let response = await fetchDoubleKnockRequest(session, request, signedRequest, signal, observation);
1293
- const firstRedirected = isRedirectResponse(response);
1294
- if (!firstRedirected && (response.status === 400 || response.status === 401 || response.status > 401)) {
1295
- const logger = getLogger([
1296
- "fedify",
1297
- "sig",
1298
- "http"
1299
- ]);
1300
- const acceptSigHeader = response.headers.get("Accept-Signature");
1301
- if (acceptSigHeader != null) {
1302
- const entries = validateAcceptSignature(parseAcceptSignature(acceptSigHeader));
1303
- const localKeyId = identity.keyId.href;
1304
- const localAlg = "rsa-v1_5-sha256";
1305
- let fulfilled = false;
1306
- let challengeRequest;
1307
- for (const entry of entries) {
1308
- signal?.throwIfAborted();
1309
- const rfc9421 = fulfillAcceptSignature(entry, localKeyId, localAlg);
1310
- if (rfc9421 == null) continue;
1311
- logger.debug("Received Accept-Signature challenge; accumulating label {label} and components {components}.", {
1312
- label: rfc9421.label,
1313
- components: rfc9421.components
1314
- });
1315
- try {
1316
- challengeRequest = await signRequest(challengeRequest ?? request, identity.privateKey, identity.keyId, {
1317
- spec: "rfc9421",
1318
- tracerProvider,
1319
- body,
1320
- rfc9421
1321
- });
1322
- fulfilled = true;
1323
- } catch (error) {
1324
- logger.debug("Failed to fulfill Accept-Signature challenge entry {label}: {error}", {
1325
- label: entry.label,
1326
- error
1327
- });
1328
- }
1329
- }
1330
- if (fulfilled && challengeRequest != null) {
1331
- observation?.response(response, "intermediate");
1332
- signal?.throwIfAborted();
1333
- cancelResponseBody(response, request.url);
1334
- signedRequest = challengeRequest;
1335
- log?.(signedRequest);
1336
- response = await submitDoubleKnockRequest(session, signedRequest, signal, observation);
1337
- }
1338
- if (fulfilled && !isRedirectResponse(response)) {
1339
- if (response.status < 300) {
1340
- observation?.response(response, "final");
1341
- await observeDoubleKnockOperation(observation, "post-response", () => specDeterminer?.rememberSpec(origin, "rfc9421") ?? Promise.resolve());
1342
- return {
1343
- response,
1344
- session
1345
- };
1346
- }
1347
- if (response.status !== 400 && response.status !== 401) {
1348
- observation?.response(response, "final");
1349
- return {
1350
- response,
1351
- session
1352
- };
1353
- }
1354
- }
1355
- }
1356
- if (!isRedirectResponse(response)) {
1357
- observation?.response(response, "intermediate");
1358
- const spec = firstTrySpec === "draft-cavage-http-signatures-12" ? "rfc9421" : "draft-cavage-http-signatures-12";
1359
- getLogger([
1360
- "fedify",
1361
- "sig",
1362
- "http"
1363
- ]).debug("Failed to verify with the spec {spec} ({status} {statusText}); retrying with spec {secondSpec}... (double-knocking)", {
1364
- spec: firstTrySpec,
1365
- secondSpec: spec,
1366
- status: response.status,
1367
- statusText: response.statusText
1368
- });
1369
- cancelResponseBody(response, request.url);
1370
- signal?.throwIfAborted();
1371
- signedRequest = await observeDoubleKnockOperation(observation, "signing", () => signRequest(request, identity.privateKey, identity.keyId, {
1372
- spec,
1373
- tracerProvider,
1374
- body
1375
- }));
1376
- signal?.throwIfAborted();
1377
- log?.(signedRequest);
1378
- response = await fetchDoubleKnockRequest(session, request, signedRequest, signal, observation);
1379
- if (!isRedirectResponse(response) && response.status !== 400 && response.status !== 401) {
1380
- observation?.response(response, "final");
1381
- await observeDoubleKnockOperation(observation, "post-response", () => specDeterminer?.rememberSpec(origin, spec) ?? Promise.resolve());
1382
- }
1383
- }
1384
- } else if (!firstRedirected) {
1385
- observation?.response(response, "final");
1386
- await observeDoubleKnockOperation(observation, "post-response", () => specDeterminer?.rememberSpec(origin, firstTrySpec) ?? Promise.resolve());
1387
- }
1388
- if (!isRedirectResponse(response)) {
1389
- observation?.response(response, "final");
1390
- return {
1391
- response,
1392
- session
1393
- };
1394
- }
1395
- observation?.response(response, "intermediate");
1396
- cancelResponseBody(response, request.url);
1397
- await session.close();
1398
- if (redirected >= maximumRedirection) throw new FetchError(request.url, `Too many redirections (${redirected + 1})`);
1399
- const location = response.headers.get("Location");
1400
- const redirectRequest = await createRedirectRequest(request, location, body, options.validateRedirect);
1401
- if (visited.has(redirectRequest.url)) throw new FetchError(request.url, `Redirect loop detected: ${redirectRequest.url}`);
1402
- request = redirectRequest;
1403
- session = await openHop(request.url);
1404
- }
1405
- } catch (error) {
1406
- try {
1407
- await session.close();
1408
- } catch (closeError) {
1409
- getLogger([
1410
- "fedify",
1411
- "sig",
1412
- "http"
1413
- ]).debug("Failed to close the session for {url}: {error}", {
1414
- url: request.url,
1415
- error: closeError
1416
- });
1417
- }
1418
- throw error;
1419
- }
1420
- }
1421
- /**
1422
- * Performs a timing-safe equality comparison between two `Uint8Array` values.
1423
- *
1424
- * This function is designed to take a constant amount of time to execute,
1425
- * dependent only on the length of the longer of the two arrays,
1426
- * regardless of where the first difference in bytes occurs. This helps
1427
- * prevent timing attacks.
1428
- *
1429
- * @param a The first bytes.
1430
- * @param b The second bytes.
1431
- * @returns `true` if the arrays are of the same length and contain the same
1432
- * bytes, `false` otherwise.
1433
- * @since 1.6.0
1434
- */
1435
- function timingSafeEqual(a, b) {
1436
- const lenA = a.length;
1437
- const lenB = b.length;
1438
- const commonLength = Math.max(lenA, lenB);
1439
- let result = 0;
1440
- for (let i = 0; i < commonLength; i++) {
1441
- const byteA = i < lenA ? a[i] : 0;
1442
- const byteB = i < lenB ? b[i] : 0;
1443
- result |= byteA ^ byteB;
1444
- }
1445
- result |= lenA ^ lenB;
1446
- return result === 0;
1447
- }
1448
- //#endregion
1449
- export { formatRfc9421SignatureParameters as a, parseRfc9421SignatureInput as c, timingSafeEqual as d, validateMaxSignatures as f, formatRfc9421Signature as i, selectRequestSignature as l, verifyRequestDetailed as m, doubleKnock as n, listRequestSignatures as o, verifyRequest as p, doubleKnockScoped as r, parseRfc9421Signature as s, createRfc9421SignatureBase as t, signRequest as u };