@fedify/fedify 2.3.16-dev.2841 → 2.3.16

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 (108) hide show
  1. package/dist/attachment-arrays-BlfpZlWF.mjs +16 -0
  2. package/dist/{builder-G4wSHQX-.mjs → builder-D4GE1Gmi.mjs} +3 -3
  3. package/dist/callback-kR_sx2zZ.d.mts +2661 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-jE7oGvRh.d.ts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-DpUNYKla.mjs → client-DFgYVbUA.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +255 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  12. package/dist/compat/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-CE_Tj_Oc.d.cts → context-CEE8vl-b.d.cts} +31 -14
  15. package/dist/{context-H_5tZXg-.d.ts → context-CTJwXHRu.d.ts} +31 -14
  16. package/dist/{deno-DmDVx5sE.mjs → deno-FtdqgHJA.mjs} +1 -1
  17. package/dist/{docloader-0fjyUmvI.mjs → docloader-B9iU4DP2.mjs} +2 -2
  18. package/dist/federation/attachment-responses.test.d.mts +2 -0
  19. package/dist/federation/attachment-responses.test.mjs +182 -0
  20. package/dist/federation/builder.test.mjs +1 -1
  21. package/dist/federation/circuit-breaker.test.mjs +2 -2
  22. package/dist/federation/collection.test.mjs +1 -1
  23. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  24. package/dist/federation/delivery-attachments.test.mjs +288 -0
  25. package/dist/federation/handler.test.mjs +208 -16
  26. package/dist/federation/idempotency.test.mjs +2 -2
  27. package/dist/federation/inbox.test.mjs +2 -2
  28. package/dist/federation/metrics.test.mjs +1 -1
  29. package/dist/federation/middleware.test.mjs +1191 -16
  30. package/dist/federation/mod.cjs +1 -1
  31. package/dist/federation/mod.d.cts +2 -2
  32. package/dist/federation/mod.d.ts +2 -2
  33. package/dist/federation/mod.js +1 -1
  34. package/dist/federation/negotiation.test.mjs +1 -1
  35. package/dist/federation/retry.test.mjs +1 -1
  36. package/dist/federation/send.test.mjs +293 -3
  37. package/dist/federation/temporal.test.mjs +25 -1
  38. package/dist/federation/webfinger.test.mjs +1 -1
  39. package/dist/{http-CKX94hfh.cjs → http-2RyDQ0tE.cjs} +6 -4
  40. package/dist/{http-DmP0sr2l.d.ts → http-Bs5mXWlH.d.ts} +3 -3
  41. package/dist/{http-CZPYFK3b.d.cts → http-D8DgRhHU.d.cts} +3 -3
  42. package/dist/{http-DCK-QQfE.mjs → http-D8tiOrZf.mjs} +7 -5
  43. package/dist/{http-DwIMsxu9.js → http-mLeLYFj-.js} +6 -4
  44. package/dist/{inbox-Bx6PCMeE.mjs → inbox-Dy8awbi8.mjs} +2 -2
  45. package/dist/{key-SkLDUmPM.mjs → key-o1SmN5s0.mjs} +4 -3
  46. package/dist/{kv-cache-BaJOO6O3.mjs → kv-cache-BwUrzCVO.mjs} +1 -1
  47. package/dist/{kv-cache-BnZ4KLMY.cjs → kv-cache-CI6Z0WiS.cjs} +1 -1
  48. package/dist/{kv-cache-xIexNacM.js → kv-cache-Dsq8C8D8.js} +1 -1
  49. package/dist/{ld-DUG6cq9q.mjs → ld-DCKrqj9y.mjs} +155 -22
  50. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  51. package/dist/{metrics-D3OnAgfj.mjs → metrics-CaoYRhNH.mjs} +1 -1
  52. package/dist/{middleware-CUwjLKp3.mjs → middleware-4p3opEMT.mjs} +1 -1
  53. package/dist/{middleware-C9RexCTx.cjs → middleware-CP-8P7kk.cjs} +492 -117
  54. package/dist/{middleware-DU2jy5eY.js → middleware-Cce0nLDw.js} +491 -117
  55. package/dist/{middleware-zEy-wJYI.mjs → middleware-D31fNcY4.mjs} +399 -109
  56. package/dist/{mod-C_gFmeNq.d.cts → mod-BD0-_vya.d.ts} +31 -13
  57. package/dist/{mod-HQXFvOHs.d.ts → mod-BMX6nsHP.d.cts} +31 -13
  58. package/dist/{mod-CDFFESfL.d.ts → mod-BTvP5Hva.d.ts} +1 -1
  59. package/dist/{mod-DMjhnFbg.d.ts → mod-DgMTlwUO.d.ts} +3 -3
  60. package/dist/{mod-DDVkmZ_h.d.cts → mod-Q1Fo3FJk.d.cts} +3 -3
  61. package/dist/{mod-DDjtbkZO.d.cts → mod-n51LED4J.d.cts} +1 -1
  62. package/dist/mod.cjs +5 -5
  63. package/dist/mod.d.cts +8 -8
  64. package/dist/mod.d.ts +8 -8
  65. package/dist/mod.js +5 -5
  66. package/dist/nodeinfo/client.test.mjs +432 -4
  67. package/dist/nodeinfo/handler.test.mjs +1 -1
  68. package/dist/nodeinfo/mod.cjs +1 -1
  69. package/dist/nodeinfo/mod.d.cts +1 -1
  70. package/dist/nodeinfo/mod.d.ts +1 -1
  71. package/dist/nodeinfo/mod.js +1 -1
  72. package/dist/nodeinfo/types.test.mjs +1 -1
  73. package/dist/{outgoing-jsonld-D4iTv7uM.mjs → outgoing-jsonld-BZEAVK_Q.mjs} +38 -8
  74. package/dist/{owner-Baf_LRb2.mjs → owner-Bdj0nHhf.mjs} +2 -2
  75. package/dist/{proof-CNGy7TJL.js → proof-B9XJiyz-.js} +1030 -858
  76. package/dist/{proof-BdAFbOFg.cjs → proof-CmcP8yqP.cjs} +1243 -1059
  77. package/dist/{proof-LTsbjXnQ.mjs → proof-DrbjYma9.mjs} +41 -16
  78. package/dist/{send-DOf5y1nB.mjs → send-VD_WG3dN.mjs} +100 -22
  79. package/dist/sig/http.test.mjs +2 -2
  80. package/dist/sig/key-types.test.d.mts +218 -0
  81. package/dist/sig/key-types.test.mjs +8 -0
  82. package/dist/sig/key.test.mjs +2 -2
  83. package/dist/sig/ld.test.mjs +573 -8
  84. package/dist/sig/mod.cjs +2 -2
  85. package/dist/sig/mod.d.cts +3 -3
  86. package/dist/sig/mod.d.ts +3 -3
  87. package/dist/sig/mod.js +2 -2
  88. package/dist/sig/owner.test.mjs +1 -1
  89. package/dist/sig/proof.test.mjs +96 -4
  90. package/dist/{temporal-fl4sM1Gs.mjs → temporal-CMvoB-vD.mjs} +3 -5
  91. package/dist/testing/mod.d.mts +2 -2476
  92. package/dist/{types-DOvyymM4.cjs → types-BWx7zw3Y.cjs} +85 -10
  93. package/dist/{types-B1_pRFE_.js → types-Dx_w2JSM.js} +86 -11
  94. package/dist/utils/docloader.test.mjs +2 -2
  95. package/dist/utils/kv-cache.test.mjs +1 -1
  96. package/dist/utils/mod.cjs +1 -1
  97. package/dist/utils/mod.d.cts +1 -1
  98. package/dist/utils/mod.d.ts +1 -1
  99. package/dist/utils/mod.js +1 -1
  100. package/package.json +7 -7
  101. /package/dist/{activity-listener-tztVvlNb.mjs → activity-listener-BeTGV3wc.mjs} +0 -0
  102. /package/dist/{circuit-breaker-D1fxthDI.mjs → circuit-breaker-B1fLHmg2.mjs} +0 -0
  103. /package/dist/{circuit-breaker-test-utils-CAdwjgMi.mjs → circuit-breaker-test-utils-BGHm_MsT.mjs} +0 -0
  104. /package/dist/{collection-Cc3DVAhE.mjs → collection-Dp5ky45w.mjs} +0 -0
  105. /package/dist/{negotiation-DDstyBvc.mjs → negotiation-DC8nG6J_.mjs} +0 -0
  106. /package/dist/{public-audience-Dp4ZScSr.mjs → public-audience-rnYUGj8a.mjs} +0 -0
  107. /package/dist/{retry-CXg_MBI-.mjs → retry-C4G_vIgv.mjs} +0 -0
  108. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -1,14 +1,15 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-DmDVx5sE.mjs";
5
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-D3OnAgfj.mjs";
6
- import { r as fetchKey, s as validateCryptoKey } from "./key-SkLDUmPM.mjs";
7
- import { n as preloadedOnlyDocumentLoader } from "./public-audience-Dp4ZScSr.mjs";
8
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-D4iTv7uM.mjs";
4
+ import { n as version, t as name } from "./deno-FtdqgHJA.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-CaoYRhNH.mjs";
6
+ import { r as fetchKey, s as validateCryptoKey } from "./key-o1SmN5s0.mjs";
7
+ import { n as preloadedOnlyDocumentLoader } from "./public-audience-rnYUGj8a.mjs";
8
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-BZEAVK_Q.mjs";
9
9
  import { getLogger } from "@logtape/logtape";
10
10
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
11
11
  import { SpanStatusCode, trace } from "@opentelemetry/api";
12
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
12
13
  import { encodeHex } from "byte-encodings/hex";
13
14
  import serialize from "json-canon";
14
15
  //#region src/sig/proof.ts
@@ -65,7 +66,10 @@ function hasProofLike(jsonLd) {
65
66
  * @throws {TypeError} If the private key is invalid or unsupported.
66
67
  * @since 0.10.0
67
68
  */
68
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
69
+ async function createProof(object, privateKey, keyId, options = {}) {
70
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
71
+ }
72
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
69
73
  validateCryptoKey(privateKey, "private");
70
74
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
71
75
  let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -92,14 +96,26 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
92
96
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
93
97
  digest.set(new Uint8Array(proofDigest), 0);
94
98
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
95
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
96
- return new DataIntegrityProof({
97
- cryptosuite: "eddsa-jcs-2022",
98
- verificationMethod: keyId,
99
- proofPurpose: "assertionMethod",
100
- created: created ?? Temporal.Now.instant(),
101
- proofValue: new Uint8Array(sig)
102
- });
99
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
100
+ return {
101
+ proof: new DataIntegrityProof({
102
+ cryptosuite: "eddsa-jcs-2022",
103
+ verificationMethod: keyId,
104
+ proofPurpose: "assertionMethod",
105
+ created: created ?? Temporal.Now.instant(),
106
+ proofValue: new Uint8Array(sig)
107
+ }),
108
+ jsonLd: compactMsg
109
+ };
110
+ }
111
+ function getJsonLdContextKey(value) {
112
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
113
+ return JSON.stringify(sortJsonKeys(context));
114
+ }
115
+ function sortJsonKeys(value) {
116
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
117
+ if (typeof value !== "object" || value == null) return value;
118
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
103
119
  }
104
120
  /**
105
121
  * Signs the given object with the private key and returns the signed object.
@@ -115,9 +131,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
115
131
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
116
132
  try {
117
133
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
134
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
118
135
  const existingProofs = [];
119
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
120
- const proof = await createProof(object, privateKey, keyId, options);
136
+ let hasProofs = object.proofIds.length > 0;
137
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
138
+ hasProofs = true;
139
+ break;
140
+ }
141
+ if (hasProofs) {
142
+ let sameContext = true;
143
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
144
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
145
+ }
121
146
  if (span.isRecording()) {
122
147
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
123
148
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -1,9 +1,9 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-DmDVx5sE.mjs";
5
- import { n as getDurationMs, r as getFederationMetrics } from "./metrics-D3OnAgfj.mjs";
6
- import { r as doubleKnockScoped } from "./http-DCK-QQfE.mjs";
4
+ import { n as version, t as name } from "./deno-FtdqgHJA.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics } from "./metrics-CaoYRhNH.mjs";
6
+ import { r as doubleKnockScoped } from "./http-D8tiOrZf.mjs";
7
7
  import { getLogger } from "@logtape/logtape";
8
8
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
9
9
  import { FetchError, UrlError } from "@fedify/vocab-runtime";
@@ -41,7 +41,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
41
41
  * @param parameters The parameters for sending the activity.
42
42
  * See also {@link SendActivityParameters}.
43
43
  * @param deps The dependencies, for tests.
44
- * @throws {Error} If the activity fails to send.
44
+ * @throws {FetchError} If the delivery times out before receiving a response.
45
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
45
46
  */
46
47
  function sendActivity(options, deps = {}) {
47
48
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -68,6 +69,24 @@ function sendActivity(options, deps = {}) {
68
69
  });
69
70
  }
70
71
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
72
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
73
+ function raceWithAbort(promise, signal) {
74
+ if (signal.aborted) return Promise.reject(signal.reason);
75
+ return new Promise((resolve, reject) => {
76
+ const onAbort = () => {
77
+ signal.removeEventListener("abort", onAbort);
78
+ reject(signal.reason);
79
+ };
80
+ signal.addEventListener("abort", onAbort, { once: true });
81
+ promise.then((value) => {
82
+ signal.removeEventListener("abort", onAbort);
83
+ resolve(value);
84
+ }, (error) => {
85
+ signal.removeEventListener("abort", onAbort);
86
+ reject(error);
87
+ });
88
+ });
89
+ }
71
90
  function getActivityActorId(activity) {
72
91
  if (!isRecord(activity)) return void 0;
73
92
  return getIdValue(activity.actor);
@@ -87,7 +106,7 @@ function getIdValue(value) {
87
106
  function isRecord(value) {
88
107
  return typeof value === "object" && value != null;
89
108
  }
90
- async function readLimitedResponseBody(response, maxBytes) {
109
+ async function readLimitedResponseBody(response, maxBytes, signal) {
91
110
  if (response.body == null) return "";
92
111
  const reader = response.body.getReader();
93
112
  const decoder = new TextDecoder();
@@ -96,7 +115,8 @@ async function readLimitedResponseBody(response, maxBytes) {
96
115
  let truncated = false;
97
116
  try {
98
117
  while (true) {
99
- const { done, value } = await reader.read();
118
+ signal.throwIfAborted();
119
+ const { done, value } = await raceWithAbort(reader.read(), signal);
100
120
  if (done) break;
101
121
  if (totalBytes + value.length > maxBytes) {
102
122
  const remaining = maxBytes - totalBytes;
@@ -108,8 +128,10 @@ async function readLimitedResponseBody(response, maxBytes) {
108
128
  totalBytes += value.length;
109
129
  }
110
130
  } finally {
111
- if (truncated) reader.cancel().catch(() => {});
112
- reader.releaseLock();
131
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
132
+ try {
133
+ reader.releaseLock();
134
+ } catch (_) {}
113
135
  }
114
136
  let result = chunks.join("");
115
137
  if (truncated) result += "… (truncated)";
@@ -124,11 +146,30 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
124
146
  const federationMetrics = getFederationMetrics(meterProvider);
125
147
  const started = performance.now();
126
148
  let deliverySuccess = false;
127
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url));
149
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
150
+ const controller = new AbortController();
151
+ const { signal } = controller;
152
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
153
+ function timeoutFailure(error) {
154
+ if (!signal.aborted || error instanceof SendActivityError) return error;
155
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
156
+ failure.cause = signal.reason;
157
+ return failure;
158
+ }
159
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
128
160
  async function openHop(url) {
129
161
  let session;
130
162
  try {
131
- session = await openUnvalidatedHop(url);
163
+ signal.throwIfAborted();
164
+ const opening = openUnvalidatedHop(url);
165
+ opening.then((lateSession) => {
166
+ if (signal.aborted) closeAfterError(lateSession, logger);
167
+ }, () => {});
168
+ session = await raceWithAbort(opening, signal);
169
+ if (signal.aborted) {
170
+ closeAfterError(session, logger);
171
+ signal.throwIfAborted();
172
+ }
132
173
  } catch (error) {
133
174
  if (error instanceof UrlError && error.reason === "dns") {
134
175
  logger.error("DNS resolution failed for URL: {url}", {
@@ -151,8 +192,15 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
151
192
  try {
152
193
  initialSession = await openHop(inbox.href);
153
194
  } catch (error) {
154
- if (error instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
155
- throw error;
195
+ const failure = timeoutFailure(error);
196
+ if (failure instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
197
+ if (signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
198
+ activityId,
199
+ inbox: inbox.href,
200
+ error: failure
201
+ });
202
+ clearTimeout(timer);
203
+ throw failure;
156
204
  }
157
205
  let initialPending = true;
158
206
  const openDeliveryHop = (url) => {
@@ -169,7 +217,8 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
169
217
  method: "POST",
170
218
  headers,
171
219
  body: JSON.stringify(activity),
172
- redirect: "manual"
220
+ redirect: "manual",
221
+ signal
173
222
  });
174
223
  let rsaKey = null;
175
224
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -184,13 +233,35 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
184
233
  }))
185
234
  });
186
235
  let outcome;
236
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
237
+ determineSpec(origin) {
238
+ signal.throwIfAborted();
239
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
240
+ },
241
+ rememberSpec(origin, spec) {
242
+ if (signal.aborted) return;
243
+ try {
244
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
245
+ origin,
246
+ error
247
+ }));
248
+ } catch (error) {
249
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
250
+ origin,
251
+ error
252
+ });
253
+ }
254
+ }
255
+ };
187
256
  try {
188
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
257
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
189
258
  tracerProvider,
190
- specDeterminer
191
- }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox));
259
+ specDeterminer: boundedSpecDeterminer,
260
+ signal
261
+ }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal));
192
262
  } catch (error) {
193
- const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
263
+ const boundedError = timeoutFailure(error);
264
+ const failure = boundedError instanceof FetchError || boundedError instanceof UrlError ? boundedError : createFetchError(inbox.href, boundedError);
194
265
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
195
266
  activityId,
196
267
  inbox: inbox.href,
@@ -224,6 +295,7 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
224
295
  federationMetrics.recordDelivery(inbox, getDurationMs(started), deliverySuccess, activityType);
225
296
  }
226
297
  } finally {
298
+ clearTimeout(timer);
227
299
  if (initialPending) await initialSession.close();
228
300
  }
229
301
  }
@@ -255,17 +327,18 @@ function cancelResponseBody(response, url) {
255
327
  * session is open: the body of a successful response is cancelled, and at
256
328
  * most 1 KiB of an error response body is read.
257
329
  */
258
- async function consumeSendActivityResponse(response, inbox) {
330
+ async function consumeSendActivityResponse(response, inbox, signal) {
259
331
  if (response.ok) {
260
332
  cancelResponseBody(response, response.url || inbox.href);
261
333
  return { ok: true };
262
334
  }
263
335
  let error;
264
336
  try {
265
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
337
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
266
338
  } catch (_) {
267
339
  error = "";
268
340
  }
341
+ if (signal.aborted) error = "(timed out reading response body)";
269
342
  return {
270
343
  ok: false,
271
344
  status: response.status,
@@ -285,7 +358,7 @@ async function consumeSendActivityResponse(response, inbox) {
285
358
  * @param consume The function to consume the final response.
286
359
  * @returns The value returned by `consume`.
287
360
  */
288
- async function fetchWithValidatedRedirects(request, openHop, consume) {
361
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
289
362
  const logger = getLogger([
290
363
  "fedify",
291
364
  "federation",
@@ -293,10 +366,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
293
366
  ]);
294
367
  let body = await request.clone().text();
295
368
  for (let redirects = 0;; redirects++) {
369
+ signal?.throwIfAborted();
296
370
  const session = await openHop(request.url);
297
371
  let response;
298
372
  try {
299
- response = await session.fetch(request, { redirect: "manual" });
373
+ response = await session.fetch(request, {
374
+ redirect: "manual",
375
+ signal
376
+ });
300
377
  } catch (error) {
301
378
  await closeAfterError(session, logger);
302
379
  throw error;
@@ -346,7 +423,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
346
423
  method,
347
424
  headers,
348
425
  body,
349
- redirect: "manual"
426
+ redirect: "manual",
427
+ signal: signal ?? request.signal
350
428
  });
351
429
  }
352
430
  }
@@ -7,8 +7,8 @@ import { n as assertExists, t as assertStringIncludes } from "../std__assert-BjJ
7
7
  import { r as assertFalse, t as assertThrows } from "../assert_throws-BbSMEFKo.mjs";
8
8
  import { n as assertGreaterOrEqual, t as assertRejects } from "../assert_rejects-D1HYAik3.mjs";
9
9
  import { t as assert } from "../assert-CEO06XCw.mjs";
10
- import { t as exportJwk } from "../key-SkLDUmPM.mjs";
11
- import { a as formatRfc9421SignatureParameters, c as signRequest, d as verifyRequestDetailed, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-DCK-QQfE.mjs";
10
+ import { t as exportJwk } from "../key-o1SmN5s0.mjs";
11
+ import { a as formatRfc9421SignatureParameters, c as signRequest, d as verifyRequestDetailed, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-D8tiOrZf.mjs";
12
12
  import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-BAK-tUlf.mjs";
13
13
  import { t as KvKeyCache } from "../keycache-BimEQucx.mjs";
14
14
  import { t as MemoryKvStore } from "../kv-mI4Ix2EU.mjs";
@@ -0,0 +1,218 @@
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
+ import { c as InboxListenerSetters, d as signRequest, f as exportJwk, l as SenderKeyPair, n as Context, o as ActorCallbackSetters, r as InboxContext, t as ActorKeyPairsDispatcher, u as HttpMessageSignaturesSpecDeterminer } from "../callback-kR_sx2zZ.mjs";
4
+ import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, Recipient } from "@fedify/vocab";
5
+ import { MeterProvider, TracerProvider } from "@opentelemetry/api";
6
+ import { AuthenticatedDocumentLoaderFactory, CryptoKeyLike, CryptoKeyPairLike, DocumentLoader, DocumentLoaderFactoryOptions, exportMultibaseKey, exportSpki } from "@fedify/vocab-runtime";
7
+
8
+ //#region src/utils/docloader.d.ts
9
+ /**
10
+ * Options for {@link getAuthenticatedDocumentLoader}.
11
+ * @see {@link getAuthenticatedDocumentLoader}
12
+ * @since 1.3.0
13
+ */
14
+ interface GetAuthenticatedDocumentLoaderOptions extends DocumentLoaderFactoryOptions {
15
+ /**
16
+ * An optional spec determiner for HTTP Message Signatures.
17
+ * It determines the spec to use for signing requests.
18
+ * It is used for double-knocking
19
+ * (see <https://swicg.github.io/activitypub-http-signature/#how-to-upgrade-supported-versions>).
20
+ * @since 1.6.0
21
+ */
22
+ specDeterminer?: HttpMessageSignaturesSpecDeterminer;
23
+ /**
24
+ * The OpenTelemetry tracer provider. If omitted, the global tracer provider
25
+ * is used.
26
+ * @since 1.6.0
27
+ */
28
+ tracerProvider?: TracerProvider;
29
+ }
30
+ /**
31
+ * Gets an authenticated {@link DocumentLoader} for the given identity.
32
+ * Note that an authenticated document loader intentionally does not cache
33
+ * the fetched documents.
34
+ * At most 20 HTTP redirects and alternate document links are followed in total
35
+ * per call. Revisiting a URL within that chain throws a {@link FetchError}.
36
+ * @param identity The identity to get the document loader for.
37
+ * The actor's key pair.
38
+ * @param options The options for the document loader.
39
+ * @returns The authenticated document loader.
40
+ * @throws {TypeError} If the key is invalid or unsupported.
41
+ * @since 0.4.0
42
+ */
43
+ declare function getAuthenticatedDocumentLoader(identity: {
44
+ keyId: URL;
45
+ privateKey: CryptoKeyLike;
46
+ }, options?: GetAuthenticatedDocumentLoaderOptions): DocumentLoader;
47
+ //#endregion
48
+ //#region src/sig/ld.d.ts
49
+ /**
50
+ * A signature of a JSON-LD document.
51
+ * @since 1.0.0
52
+ */
53
+ interface Signature {
54
+ "@context"?: "https://w3id.org/identity/v1" | "https://w3id.org/security/v1";
55
+ type: "RsaSignature2017";
56
+ id?: string;
57
+ creator: string;
58
+ created: string;
59
+ signatureValue: string;
60
+ }
61
+ /**
62
+ * Options for creating Linked Data Signatures.
63
+ * @since 1.0.0
64
+ */
65
+ interface CreateSignatureOptions {
66
+ /**
67
+ * The context loader for loading remote JSON-LD contexts.
68
+ */
69
+ contextLoader?: DocumentLoader;
70
+ /**
71
+ * The time when the signature was created. If not specified, the current
72
+ * time will be used.
73
+ */
74
+ created?: Temporal.Instant;
75
+ }
76
+ /**
77
+ * Creates a LD signature for the given JSON-LD document.
78
+ *
79
+ * If the document's context does not define the `signature` property, the
80
+ * signature is computed over the document with a minimal inline definition
81
+ * added. Use {@link attachSignature} to attach the signature to that exact
82
+ * document. Documents that already carry a `proof`, or whose context includes
83
+ * an unrecognized remote context, are hashed unchanged.
84
+ * @param jsonLd The JSON-LD document to sign.
85
+ * @param privateKey The private key to sign the document.
86
+ * @param keyId The ID of the public key that corresponds to the private key.
87
+ * @param options Additional options for creating the signature.
88
+ * See also {@link CreateSignatureOptions}.
89
+ * @return The created signature.
90
+ * @throws {TypeError} If the private key is invalid or unsupported.
91
+ * @since 1.0.0
92
+ */
93
+ declare function createSignature(jsonLd: unknown, privateKey: CryptoKeyLike, keyId: URL, {
94
+ contextLoader,
95
+ created
96
+ }?: CreateSignatureOptions): Promise<Signature>;
97
+ /**
98
+ * Options for signing JSON-LD documents.
99
+ * @since 1.0.0
100
+ */
101
+ interface SignJsonLdOptions extends CreateSignatureOptions {
102
+ /**
103
+ * The OpenTelemetry tracer provider for tracing the signing process.
104
+ * If omitted, the global tracer provider is used.
105
+ * @since 1.3.0
106
+ */
107
+ tracerProvider?: TracerProvider;
108
+ }
109
+ /**
110
+ * Signs the given JSON-LD document with the private key and returns the signed
111
+ * JSON-LD document.
112
+ * @param jsonLd The JSON-LD document to sign.
113
+ * @param privateKey The private key to sign the document.
114
+ * @param keyId The key ID to use in the signature. It will be used by the
115
+ * verifier to fetch the corresponding public key.
116
+ * @param options Additional options for signing the document.
117
+ * See also {@link SignJsonLdOptions}.
118
+ * @returns The signed JSON-LD document.
119
+ * @throws {TypeError} If the private key is invalid or unsupported.
120
+ * @since 1.0.0
121
+ */
122
+ declare function signJsonLd(jsonLd: unknown, privateKey: CryptoKeyLike, keyId: URL, options: SignJsonLdOptions): Promise<{
123
+ signature: Signature;
124
+ }>;
125
+ //#endregion
126
+ //#region src/sig/proof.d.ts
127
+ /**
128
+ * Options for {@link createProof}.
129
+ * @since 0.10.0
130
+ */
131
+ interface CreateProofOptions {
132
+ /**
133
+ * The context loader for loading remote JSON-LD contexts.
134
+ */
135
+ contextLoader?: DocumentLoader;
136
+ /**
137
+ * The JSON-LD context to use for serializing the object to sign.
138
+ */
139
+ context?: string | Record<string, string> | (string | Record<string, string>)[];
140
+ /**
141
+ * The time when the proof was created. If not specified, the current time
142
+ * will be used.
143
+ */
144
+ created?: Temporal.Instant;
145
+ }
146
+ /**
147
+ * Creates a proof for the given object.
148
+ * @param object The object to create a proof for.
149
+ * @param privateKey The private key to sign the proof with.
150
+ * @param keyId The key ID to use in the proof. It will be used by the verifier.
151
+ * @param options Additional options. See also {@link CreateProofOptions}.
152
+ * @returns The created proof.
153
+ * @throws {TypeError} If the private key is invalid or unsupported.
154
+ * @since 0.10.0
155
+ */
156
+ declare function createProof(object: Object$1, privateKey: CryptoKeyLike, keyId: URL, options?: CreateProofOptions): Promise<DataIntegrityProof>;
157
+ /**
158
+ * Options for {@link signObject}.
159
+ * @since 0.10.0
160
+ */
161
+ interface SignObjectOptions extends CreateProofOptions {
162
+ /**
163
+ * The document loader for loading remote JSON-LD documents.
164
+ */
165
+ documentLoader?: DocumentLoader;
166
+ /**
167
+ * The OpenTelemetry tracer provider. If omitted, the global tracer provider
168
+ * is used.
169
+ * @since 1.3.0
170
+ */
171
+ tracerProvider?: TracerProvider;
172
+ }
173
+ /**
174
+ * Signs the given object with the private key and returns the signed object.
175
+ * @param object The object to create a proof for.
176
+ * @param privateKey The private key to sign the proof with.
177
+ * @param keyId The key ID to use in the proof. It will be used by the verifier.
178
+ * @param options Additional options. See also {@link SignObjectOptions}.
179
+ * @returns The signed object.
180
+ * @throws {TypeError} If the private key is invalid or unsupported.
181
+ * @since 0.10.0
182
+ */
183
+ declare function signObject<T extends Object$1>(object: T, privateKey: CryptoKeyLike, keyId: URL, options?: SignObjectOptions): Promise<T>;
184
+ //#endregion
185
+ //#region src/sig/key-types.test.d.ts
186
+ /**
187
+ * Asserts at compile time that `T` is assignable to `U`.
188
+ */
189
+ type AssertAssignable<T extends U, U> = T;
190
+ /**
191
+ * The key usages Node.js adds on top of the DOM and Web Worker ones since
192
+ * Node.js 24.7, when ML-KEM support was added to its Web Crypto API.
193
+ */
194
+ type NodeKeyUsage = KeyUsage | "encapsulateBits" | "decapsulateBits" | "encapsulateKey" | "decapsulateKey";
195
+ /**
196
+ * Mirrors `import("node:crypto").webcrypto.CryptoKey`, whose `usages` array
197
+ * has a wider element type than the ambient `CryptoKey`.
198
+ */
199
+ interface NodeCryptoKey extends Omit<CryptoKey, "usages"> {
200
+ readonly usages: NodeKeyUsage[];
201
+ }
202
+ /**
203
+ * Mirrors `import("node:crypto").webcrypto.CryptoKeyPair`.
204
+ */
205
+ interface NodeCryptoKeyPair {
206
+ readonly privateKey: NodeCryptoKey;
207
+ readonly publicKey: NodeCryptoKey;
208
+ }
209
+ /**
210
+ * These are compile-time assertions. A regression in any of the public
211
+ * signatures fails `deno check` even though nothing here runs.
212
+ */
213
+ type NodeKeyTypeChecks = [AssertAssignable<NodeCryptoKey, CryptoKeyLike>, AssertAssignable<NodeCryptoKeyPair, CryptoKeyPairLike>, AssertAssignable<(context: Context<void>, identifier: string) => NodeCryptoKeyPair[] | Promise<NodeCryptoKeyPair[]>, ActorKeyPairsDispatcher<void, CryptoKeyPairLike>>, AssertAssignable<ActorKeyPairsDispatcher<void, CryptoKeyPairLike>, Parameters<ActorCallbackSetters<void>["setKeyPairsDispatcher"]>[0]>, AssertAssignable<SenderKeyPair["privateKey"], CryptoKey>, AssertAssignable<NodeCryptoKey, SenderKeyPair<CryptoKeyLike>["privateKey"]>, AssertAssignable<(context: Context<void>) => SenderKeyPair<CryptoKeyLike>, Parameters<InboxListenerSetters<void>["setSharedKeyDispatcher"]>[0]>, AssertAssignable<Parameters<AuthenticatedDocumentLoaderFactory>[0]["privateKey"], CryptoKey>, AssertAssignable<NodeCryptoKey, Parameters<typeof getAuthenticatedDocumentLoader>[0]["privateKey"]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signRequest>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof createProof>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signObject>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof createSignature>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signJsonLd>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportJwk>[0]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportSpki>[0]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportMultibaseKey>[0]>, AssertAssignable<NodeCryptoKey, NonNullable<ConstructorParameters<typeof CryptographicKey>[0]["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<ConstructorParameters<typeof Multikey>[0]["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<NonNullable<Parameters<CryptographicKey["clone"]>[0]>["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<NonNullable<Parameters<Multikey["clone"]>[0]>["publicKey"]>>, AssertAssignable<Context<void>["getDocumentLoader"], (identity: {
214
+ keyId: URL;
215
+ privateKey: NodeCryptoKey;
216
+ }) => unknown>, AssertAssignable<Context<void>["sendActivity"], (sender: SenderKeyPair<NodeCryptoKey>, recipients: Recipient, activity: Activity) => Promise<void>>, AssertAssignable<InboxContext<void>["forwardActivity"], (forwarder: SenderKeyPair<NodeCryptoKey>, recipients: Recipient) => Promise<void>>];
217
+ //#endregion
218
+ export { NodeKeyTypeChecks };
@@ -0,0 +1,8 @@
1
+ import "@js-temporal/polyfill";
2
+ import "urlpattern-polyfill";
3
+ globalThis.addEventListener = () => {};
4
+ import { test } from "@fedify/fixture";
5
+ //#region src/sig/key-types.test.ts
6
+ test("Node.js Web Crypto keys are accepted by the public key types", () => {});
7
+ //#endregion
8
+ export {};
@@ -7,9 +7,9 @@ import { r as assertFalse, t as assertThrows } from "../assert_throws-BbSMEFKo.m
7
7
  import { t as assertRejects } from "../assert_rejects-D1HYAik3.mjs";
8
8
  import { t as assert } from "../assert-CEO06XCw.mjs";
9
9
  import { t as assertStrictEquals } from "../assert_strict_equals-XEgZAlrj.mjs";
10
- import { a as generateCryptoKeyPair, i as fetchKeyDetailed, o as importJwk, r as fetchKey, s as validateCryptoKey, t as exportJwk } from "../key-SkLDUmPM.mjs";
10
+ import { a as generateCryptoKeyPair, i as fetchKeyDetailed, o as importJwk, r as fetchKey, s as validateCryptoKey, t as exportJwk } from "../key-o1SmN5s0.mjs";
11
11
  import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-BAK-tUlf.mjs";
12
- import { _ as wrapContextLoaderForJsonLd } from "../ld-DUG6cq9q.mjs";
12
+ import { y as wrapContextLoaderForJsonLd } from "../ld-DCKrqj9y.mjs";
13
13
  import { CryptographicKey, Multikey, Person } from "@fedify/vocab";
14
14
  import { createTestMeterProvider, createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
15
15
  import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";