@fedify/fedify 2.4.0-dev.2093 → 2.4.0-dev.2099

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 (79) hide show
  1. package/dist/{builder-Ld4Y9ymR.mjs → builder-Bno54o_-.mjs} +2 -2
  2. package/dist/compat/mod.d.cts +1 -1
  3. package/dist/compat/mod.d.ts +1 -1
  4. package/dist/compat/transformers.test.mjs +1 -1
  5. package/dist/{compound-proof-CTx_lewQ.mjs → compound-proof-X3SxXVbc.mjs} +2 -2
  6. package/dist/{context-CZjZYXFC.d.cts → context-C43spTGI.d.cts} +5 -2
  7. package/dist/{context-BSywYspi.d.ts → context-MORIQJIh.d.ts} +5 -2
  8. package/dist/{deno-8t8k_6Yv.mjs → deno-dxdvl2XZ.mjs} +1 -1
  9. package/dist/{docloader-DJKcsAiF.mjs → docloader-eBxQDsk9.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/compound-fanout.test.mjs +3 -3
  12. package/dist/federation/handler-compound-proof.test.mjs +3 -3
  13. package/dist/federation/handler.test.mjs +5 -5
  14. package/dist/federation/hashlink-media.test.mjs +2 -2
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/metrics.test.mjs +1 -1
  17. package/dist/federation/middleware.test.mjs +7 -7
  18. package/dist/federation/mod.cjs +1 -1
  19. package/dist/federation/mod.d.cts +2 -2
  20. package/dist/federation/mod.d.ts +2 -2
  21. package/dist/federation/mod.js +1 -1
  22. package/dist/federation/outgoing-proof.test.mjs +5 -5
  23. package/dist/federation/portable-gateway-keys.test.mjs +3 -3
  24. package/dist/federation/portable-inbox.test.mjs +375 -10
  25. package/dist/federation/portable.test.mjs +3 -3
  26. package/dist/federation/send.test.mjs +3 -3
  27. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  28. package/dist/federation/tasks/tasks.test.mjs +2 -2
  29. package/dist/federation/temporal.test.mjs +1 -1
  30. package/dist/federation/webfinger.test.mjs +1 -1
  31. package/dist/{federation-aSHO04ob.cjs → federation-C4Ef3JKa.cjs} +1211 -1089
  32. package/dist/{http-DSaSAN7X.cjs → http-C8cZTE3Y.cjs} +89 -2
  33. package/dist/{http-DyT7DP1Y.js → http-D-rbr_Sy.js} +78 -3
  34. package/dist/{http-B2ftY0Ha.mjs → http-DsgawTd8.mjs} +82 -7
  35. package/dist/{key-Dwm4VswT.mjs → key-DYfmjnmp.mjs} +2 -2
  36. package/dist/{kv-cache-DmroAz3M.js → kv-cache-DIxwMeNi.js} +1 -1
  37. package/dist/{kv-cache-BSJAlP4C.cjs → kv-cache-Dvd-Q-E2.cjs} +1 -1
  38. package/dist/{kv-cache-D0yYukqk.mjs → kv-cache-EvOgrFsS.mjs} +1 -1
  39. package/dist/{ld-BYZOoDzZ.mjs → ld-B00wWHzc.mjs} +3 -3
  40. package/dist/{metrics-B7YwKTFr.mjs → metrics-BP3vdBpb.mjs} +1 -1
  41. package/dist/{middleware-E_0IH72m.mjs → middleware-Br1_d-Ga.mjs} +627 -505
  42. package/dist/{middleware-Blq0882d.js → middleware-CcXMe400.js} +1307 -1185
  43. package/dist/{middleware-BNeqKSsL.mjs → middleware-CeBVBa61.mjs} +1 -1
  44. package/dist/{mod-B2h2KY0q.d.ts → mod-BL5BQHCq.d.ts} +1 -1
  45. package/dist/{mod-JzkaEXsi.d.cts → mod-DMI4DbOo.d.cts} +1 -1
  46. package/dist/mod.cjs +5 -5
  47. package/dist/mod.d.cts +2 -2
  48. package/dist/mod.d.ts +2 -2
  49. package/dist/mod.js +5 -5
  50. package/dist/nodeinfo/handler.test.mjs +1 -1
  51. package/dist/{owner-Cgx2Dc7I.mjs → owner-BJPDRDRq.mjs} +3 -3
  52. package/dist/{owner-szIZl4qI.cjs → owner-DSzH7wro.cjs} +1 -1
  53. package/dist/{owner-DAGSC5gX.js → owner-U12fDpQW.js} +1 -1
  54. package/dist/{portable-key-Cn1WJSN1.mjs → portable-key-D0mWbV9G.mjs} +1 -1
  55. package/dist/{proof-DVXC6nYz.mjs → proof-ChjBwnep.mjs} +4 -4
  56. package/dist/{send-D-hOvYKy.mjs → send-yFX0E-ye.mjs} +3 -3
  57. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  58. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  59. package/dist/sig/compound-proof-verification.test.mjs +2 -2
  60. package/dist/sig/compound-proof.test.mjs +2 -2
  61. package/dist/sig/http.test.mjs +72 -2
  62. package/dist/sig/key.test.mjs +1 -1
  63. package/dist/sig/ld.test.mjs +2 -2
  64. package/dist/sig/mod.cjs +3 -3
  65. package/dist/sig/mod.js +3 -3
  66. package/dist/sig/owner.test.mjs +1 -1
  67. package/dist/sig/portable-collection.test.mjs +2 -2
  68. package/dist/sig/portable-key.test.mjs +3 -3
  69. package/dist/sig/proof.test.mjs +3 -3
  70. package/dist/{sig-CXOKN4Br.cjs → sig-B689Nj7y.cjs} +2 -2
  71. package/dist/{sig-B5Ell7pO.js → sig-C85KqAcx.js} +2 -2
  72. package/dist/{temporal-CqpKGEPk.mjs → temporal-Dl9x-Qw4.mjs} +1 -1
  73. package/dist/testing/kv.test.mjs +1 -1
  74. package/dist/testing/mod.d.mts +5 -2
  75. package/dist/utils/docloader.test.mjs +2 -2
  76. package/dist/utils/kv-cache.test.mjs +1 -1
  77. package/dist/utils/mod.cjs +1 -1
  78. package/dist/utils/mod.js +1 -1
  79. package/package.json +6 -6
@@ -2,10 +2,10 @@ import { Temporal } from "temporal-polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./rolldown-runtime-BC-Eo5Mj.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-DAtXl_Kc.js";
5
- import { $ as recordFanoutRecipients, A as verifyCompactJsonLd, B as validateCryptoKey, C as detachSignature, D as isClearlyMalformedContextReference, E as hasSignatureLike, G as instrumentDocumentLoader, H as getDurationMs, J as recordCollectionDispatchDuration, K as isAbortError, N as wrapContextLoaderForJsonLd, O as isInvalidUrlTypeError, P as exportJwk, T as hasSignature, U as getFederationMetrics, W as getRemoteHost, X as recordCollectionRequest, Y as recordCollectionPageItems, Z as recordCollectionTotalItems, _ as normalizeOutgoingActivityJsonLd, a as verifyRequestDetailed, at as preloadedOnlyDocumentLoader, d as verifyMapLocalProof, dt as getGatewayKeyBase, et as recordInboxActivity, f as verifyObject, ft as getPortableDid, gt as isPortableUri, h as verifyPortableObjectProofWithRoot, ht as isPortableId, i as verifyRequest, it as registerQueueDepthGauge, k as signJsonLd, l as hasProofLike, m as verifyPortableObjectProofPolicy, mt as isCompatibleKeyId, n as parseRfc9421SignatureInput, nt as recordOutboxEnqueue, ot as formatAcceptSignature, p as verifyPortableObjectProof, pt as hasPortableActor, q as recordCircuitBreakerStateChange, rt as recordWebFingerHandle, s as InvalidPortableObjectIdError, t as doubleKnock, tt as recordOutboxActivity, u as signObject, ut as getCanonicalPortableId, v as InvalidContextReferenceError, vt as name, w as getNormalizationContextLoader, x as compactJsonLd, y as assertSafeJsonLd, yt as version, z as importJwk } from "./http-DyT7DP1Y.js";
5
+ import { $ as recordCollectionTotalItems, A as isInvalidUrlTypeError, C as compactJsonLd, D as hasSignature, E as getNormalizationContextLoader, F as wrapContextLoaderForJsonLd, G as getFederationMetrics, H as validateCryptoKey, I as exportJwk, J as isAbortError, K as getRemoteHost, M as verifyCompactJsonLd, O as hasSignatureLike, Q as recordCollectionRequest, T as detachSignature, V as importJwk, W as getDurationMs, X as recordCollectionDispatchDuration, Y as recordCircuitBreakerStateChange, Z as recordCollectionPageItems, _ as verifyPortableObjectProofWithRoot, _t as isPortableId, at as recordWebFingerHandle, b as InvalidContextReferenceError, bt as name, ct as formatAcceptSignature, d as hasProofLike, f as signObject, ft as getCanonicalPortableId, g as verifyPortableObjectProofPolicy, gt as isCompatibleKeyId, h as verifyPortableObjectProof, ht as hasPortableActor, i as selectRequestSignature, it as recordOutboxEnqueue, j as signJsonLd, k as isClearlyMalformedContextReference, l as InvalidPortableObjectIdError, m as verifyObject, mt as getPortableDid, n as listRequestSignatures, nt as recordInboxActivity, o as verifyRequest, ot as registerQueueDepthGauge, p as verifyMapLocalProof, pt as getGatewayKeyBase, q as instrumentDocumentLoader, r as parseRfc9421SignatureInput, rt as recordOutboxActivity, s as verifyRequestDetailed, st as preloadedOnlyDocumentLoader, t as doubleKnock, tt as recordFanoutRecipients, vt as isPortableUri, x as assertSafeJsonLd, xt as version, y as normalizeOutgoingActivityJsonLd } from "./http-D-rbr_Sy.js";
6
6
  import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-C_cNlNVK.js";
7
- import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-DAGSC5gX.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-DmroAz3M.js";
7
+ import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-U12fDpQW.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-DIxwMeNi.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
10
  import { Router, RouterError, assertPath } from "@fedify/uri-template";
11
11
  import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
@@ -2518,323 +2518,1022 @@ function parseHashlinkGatewayRequest(url) {
2518
2518
  };
2519
2519
  }
2520
2520
  //#endregion
2521
- //#region src/federation/temporal.ts
2522
- function isPlainObject$1(value) {
2523
- return typeof value === "object" && value != null && !Array.isArray(value);
2524
- }
2525
- function normalizeDateTimeLiteral(value) {
2526
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
2527
- }
2528
- function isMalformedDateTimeLiteral(value) {
2529
- if (typeof value !== "string") return false;
2530
- try {
2531
- Temporal.Instant.from(normalizeDateTimeLiteral(value));
2532
- return false;
2533
- } catch {
2534
- return true;
2535
- }
2536
- }
2537
- function isMalformedDurationLiteral(value) {
2538
- if (typeof value !== "string") return false;
2539
- try {
2540
- Temporal.Duration.from(value);
2541
- return false;
2542
- } catch {
2543
- return true;
2521
+ //#region src/federation/send.ts
2522
+ /**
2523
+ * Extracts the inbox URLs from recipients.
2524
+ * @param parameters The parameters to extract the inboxes.
2525
+ * See also {@link ExtractInboxesParameters}.
2526
+ * @returns The inboxes as a map of inbox URL to actor URIs.
2527
+ */
2528
+ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2529
+ const inboxes = {};
2530
+ for (const recipient of recipients) {
2531
+ let inbox;
2532
+ let sharedInbox = false;
2533
+ if (preferSharedInbox && recipient.endpoints?.sharedInbox != null) {
2534
+ inbox = recipient.endpoints.sharedInbox;
2535
+ sharedInbox = true;
2536
+ } else inbox = recipient.inboxId;
2537
+ if (inbox != null && recipient.id != null) {
2538
+ if (excludeBaseUris != null && excludeBaseUris.some((u) => u.origin === inbox?.origin)) continue;
2539
+ inboxes[inbox.href] ??= {
2540
+ actorIds: /* @__PURE__ */ new Set(),
2541
+ sharedInbox
2542
+ };
2543
+ inboxes[inbox.href].actorIds.add(recipient.id.href);
2544
+ }
2544
2545
  }
2546
+ return inboxes;
2545
2547
  }
2546
- const TEMPORAL_DATE_TIME_IRIS = /* @__PURE__ */ new Set([
2547
- "https://www.w3.org/ns/activitystreams#deleted",
2548
- "https://www.w3.org/ns/activitystreams#endTime",
2549
- "https://www.w3.org/ns/activitystreams#published",
2550
- "https://www.w3.org/ns/activitystreams#startTime",
2551
- "https://www.w3.org/ns/activitystreams#updated",
2552
- "http://purl.org/dc/terms/created",
2553
- "https://w3id.org/security#created"
2554
- ]);
2555
- const TEMPORAL_DURATION_IRIS = /* @__PURE__ */ new Set(["https://www.w3.org/ns/activitystreams#duration"]);
2556
- const QUESTION_CLOSED_IRI = "https://www.w3.org/ns/activitystreams#closed";
2557
- const XSD_DATE_TIME_IRI = "http://www.w3.org/2001/XMLSchema#dateTime";
2558
- function hasMalformedExpandedDateTimeLiteral(value) {
2559
- if (Array.isArray(value)) return value.some(hasMalformedExpandedDateTimeLiteral);
2560
- return isPlainObject$1(value) && "@value" in value && isMalformedDateTimeLiteral(value["@value"]);
2561
- }
2562
- function hasMalformedExpandedQuestionClosedLiteral(value) {
2563
- if (Array.isArray(value)) return value.some(hasMalformedExpandedQuestionClosedLiteral);
2564
- if (!isPlainObject$1(value) || !("@value" in value)) return false;
2565
- const literal = value["@value"];
2566
- if (typeof literal === "boolean") return false;
2567
- if (typeof literal !== "string") return false;
2568
- if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
2569
- if (new Date(literal).toString() === "Invalid Date") return false;
2570
- return isMalformedDateTimeLiteral(literal);
2548
+ /**
2549
+ * Sends an {@link Activity} to an inbox.
2550
+ *
2551
+ * @param parameters The parameters for sending the activity.
2552
+ * See also {@link SendActivityParameters}.
2553
+ * @throws {Error} If the activity fails to send.
2554
+ */
2555
+ function sendActivity(options) {
2556
+ const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
2557
+ return tracerProvider.getTracer(name, version).startActiveSpan("activitypub.send_activity", {
2558
+ kind: SpanKind.CLIENT,
2559
+ attributes: { "activitypub.shared_inbox": options.sharedInbox ?? false }
2560
+ }, async (span) => {
2561
+ if (options.activityId != null) span.setAttribute("activitypub.activity.id", options.activityId);
2562
+ if (options.activityType != null) span.setAttribute("activitypub.activity.type", options.activityType);
2563
+ try {
2564
+ await sendActivityInternal({
2565
+ ...options,
2566
+ tracerProvider
2567
+ }, span);
2568
+ } catch (e) {
2569
+ span.setStatus({
2570
+ code: SpanStatusCode.ERROR,
2571
+ message: String(e)
2572
+ });
2573
+ throw e;
2574
+ } finally {
2575
+ span.end();
2576
+ }
2577
+ });
2571
2578
  }
2572
- function hasMalformedExpandedDurationLiteral(value) {
2573
- if (Array.isArray(value)) return value.some(hasMalformedExpandedDurationLiteral);
2574
- return isPlainObject$1(value) && "@value" in value && isMalformedDurationLiteral(value["@value"]);
2579
+ const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2580
+ function getActivityActorId(activity) {
2581
+ if (!isRecord(activity)) return void 0;
2582
+ return getIdValue(activity.actor);
2575
2583
  }
2576
- function hasMalformedKnownTemporalLiteralInternal(value, visited) {
2577
- if (Array.isArray(value)) return value.some((item) => hasMalformedKnownTemporalLiteralInternal(item, visited));
2578
- if (!isPlainObject$1(value)) return false;
2579
- if (visited.has(value)) return false;
2580
- visited.add(value);
2581
- if ("@value" in value) return false;
2582
- for (const [key, child] of Object.entries(value)) {
2583
- if (TEMPORAL_DATE_TIME_IRIS.has(key)) {
2584
- if (hasMalformedExpandedDateTimeLiteral(child)) return true;
2585
- continue;
2586
- }
2587
- if (key === QUESTION_CLOSED_IRI) {
2588
- if (hasMalformedExpandedQuestionClosedLiteral(child)) return true;
2589
- continue;
2590
- }
2591
- if (TEMPORAL_DURATION_IRIS.has(key)) {
2592
- if (hasMalformedExpandedDurationLiteral(child)) return true;
2593
- continue;
2584
+ function getIdValue(value) {
2585
+ if (typeof value === "string" && value !== "") return value;
2586
+ if (value instanceof URL) return value.href;
2587
+ if (Array.isArray(value)) {
2588
+ for (const item of value) {
2589
+ const id = getIdValue(item);
2590
+ if (id != null) return id;
2594
2591
  }
2595
- if (hasMalformedKnownTemporalLiteralInternal(child, visited)) return true;
2592
+ return;
2596
2593
  }
2597
- return false;
2594
+ if (isRecord(value)) return getIdValue(value.id);
2598
2595
  }
2599
- async function hasMalformedKnownTemporalLiteral(value, contextLoader) {
2596
+ function isRecord(value) {
2597
+ return typeof value === "object" && value != null;
2598
+ }
2599
+ async function readLimitedResponseBody(response, maxBytes) {
2600
+ if (response.body == null) return "";
2601
+ const reader = response.body.getReader();
2602
+ const decoder = new TextDecoder();
2603
+ const chunks = [];
2604
+ let totalBytes = 0;
2605
+ let truncated = false;
2600
2606
  try {
2601
- return hasMalformedKnownTemporalLiteralInternal(await jsonld.expand(value, {
2602
- documentLoader: getNormalizationContextLoader(contextLoader),
2603
- keepFreeFloatingNodes: true
2604
- }), /* @__PURE__ */ new Set());
2605
- } catch {
2606
- return false;
2607
+ while (true) {
2608
+ const { done, value } = await reader.read();
2609
+ if (done) break;
2610
+ if (totalBytes + value.length > maxBytes) {
2611
+ const remaining = maxBytes - totalBytes;
2612
+ if (remaining > 0) chunks.push(decoder.decode(value.slice(0, remaining), { stream: true }));
2613
+ truncated = true;
2614
+ break;
2615
+ }
2616
+ chunks.push(decoder.decode(value, { stream: true }));
2617
+ totalBytes += value.length;
2618
+ }
2619
+ } finally {
2620
+ reader.releaseLock();
2607
2621
  }
2622
+ let result = chunks.join("");
2623
+ if (truncated) result += "… (truncated)";
2624
+ return result;
2608
2625
  }
2609
- //#endregion
2610
- //#region src/federation/handler.ts
2611
- const rawInboxContextFactorySymbol = Symbol("fedify.rawInboxContextFactory");
2612
- const INBOX_COMPOUND_PROOF_LIMITS = {
2613
- maxDepth: 64,
2614
- maxMaps: 1e4,
2615
- maxProofs: 32,
2616
- maxBytes: 10 * 1024 * 1024
2617
- };
2618
- function isRemoteContextLoadingFailure$1(error) {
2619
- return error instanceof Error && typeof error.details === "object" && error.details != null && error.details.code === "loading remote context failed";
2620
- }
2621
- function isPermanentRemoteContextError$1(error) {
2622
- if (!(error instanceof Error) || error.name !== "jsonld.InvalidUrl") return false;
2623
- const details = error.details;
2624
- if (details?.code === "invalid remote context") return true;
2625
- return isRemoteContextLoadingFailure$1(error) && typeof details?.url === "string" && !URL.canParse(details.url) && isClearlyMalformedContextReference(details.url);
2626
- }
2627
- function isInvalidJsonLdError(error) {
2628
- if (!(error instanceof Error)) return false;
2629
- const name = error.name;
2630
- return name === "UnsafeJsonLdError" || error instanceof InvalidContextReferenceError || isPermanentRemoteContextError$1(error) || name === "jsonld.SyntaxError" && !isRemoteContextLoadingFailure$1(error);
2631
- }
2632
- function isValidationTypeError(error) {
2633
- return error instanceof TypeError && (/^(Invalid JSON-LD:|Invalid type:|Unexpected type:|Invalid @id:)/.test(error.message) || isInvalidUrlTypeError(error));
2634
- }
2635
- function isPermanentActivityParseError(error) {
2636
- return isInvalidJsonLdError(error) || isValidationTypeError(error);
2637
- }
2638
- function hasHttpSignatureHeaders(request) {
2639
- return request.headers.has("Signature") || request.headers.has("Signature-Input");
2640
- }
2641
- function hasObjectIntegrityProof(json) {
2642
- return typeof json === "object" && json != null && "proof" in json;
2643
- }
2644
- /**
2645
- * Handles an actor request.
2646
- * @template TContextData The context data to pass to the context.
2647
- * @param request The HTTP request.
2648
- * @param parameters The parameters for handling the actor.
2649
- * @returns A promise that resolves to an HTTP response.
2650
- */
2651
- async function handleActor(request, { identifier, context, actorDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
2626
+ async function sendActivityInternal({ activity, activityId, activityType, keys, inbox, allowPrivateAddress, headers, specDeterminer, meterProvider, tracerProvider }, span) {
2652
2627
  const logger = getLogger([
2653
2628
  "fedify",
2654
2629
  "federation",
2655
- "actor"
2630
+ "outbox"
2656
2631
  ]);
2657
- if (actorDispatcher == null) {
2658
- logger.debug("Actor dispatcher is not set.", { identifier });
2659
- return await onNotFound(request);
2660
- }
2661
- const actor = await actorDispatcher(context, identifier);
2662
- if (actor == null) {
2663
- logger.debug("Actor {identifier} not found.", { identifier });
2664
- return await onNotFound(request);
2632
+ const federationMetrics = getFederationMetrics(meterProvider);
2633
+ const started = performance.now();
2634
+ let deliverySuccess = false;
2635
+ async function validateUrl(url) {
2636
+ if (!allowPrivateAddress) try {
2637
+ await validatePublicUrl(url);
2638
+ } catch (error) {
2639
+ if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
2640
+ url,
2641
+ error
2642
+ });
2643
+ throw error;
2644
+ }
2665
2645
  }
2666
- if (authorizePredicate != null) {
2667
- if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
2646
+ await validateUrl(inbox.href);
2647
+ headers = new Headers(headers);
2648
+ headers.set("Content-Type", "application/activity+json");
2649
+ const request = new Request(inbox, {
2650
+ method: "POST",
2651
+ headers,
2652
+ body: JSON.stringify(activity),
2653
+ redirect: "manual"
2654
+ });
2655
+ let rsaKey = null;
2656
+ for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
2657
+ rsaKey = key;
2658
+ break;
2668
2659
  }
2669
- if (actor instanceof Tombstone) {
2670
- const jsonLd = await actor.toJsonLd(context);
2671
- return new Response(JSON.stringify(jsonLd), {
2672
- status: 410,
2673
- headers: {
2674
- "Content-Type": "application/activity+json",
2675
- Vary: "Accept"
2676
- }
2677
- });
2678
- }
2679
- const jsonLd = await actor.toJsonLd(context);
2680
- return new Response(JSON.stringify(jsonLd), { headers: {
2681
- "Content-Type": "application/activity+json",
2682
- Vary: "Accept"
2683
- } });
2684
- }
2685
- /**
2686
- * Handles an object request.
2687
- * @template TContextData The context data to pass to the context.
2688
- * @param request The HTTP request.
2689
- * @param parameters The parameters for handling the object.
2690
- * @returns A promise that resolves to an HTTP response.
2691
- */
2692
- async function handleObject(request, { values, context, objectDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
2693
- if (objectDispatcher == null) return await onNotFound(request);
2694
- const object = await objectDispatcher(context, values);
2695
- if (object == null) return await onNotFound(request);
2696
- if (authorizePredicate != null) {
2697
- if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
2698
- }
2699
- const jsonLd = await object.toJsonLd(context);
2700
- return new Response(JSON.stringify(jsonLd), { headers: {
2701
- "Content-Type": "application/activity+json",
2702
- Vary: "Accept"
2703
- } });
2704
- }
2705
- /**
2706
- * Handles an FEP-ef61 gateway request for a portable object through an object
2707
- * dispatcher. The object is served only if its ID canonically matches the
2708
- * requested portable ID and it satisfies the FEP-ef61 proof policy.
2709
- * @template TContextData The context data to pass to the context.
2710
- * @param request The HTTP request.
2711
- * @param parameters The parameters for handling the portable object.
2712
- * @returns A promise that resolves to an HTTP response.
2713
- */
2714
- async function handlePortableObject(request, { values, context, objectDispatcher, authorizePredicate, canonicalId, onNotFound, onUnauthorized }) {
2715
- const logger = getLogger([
2716
- "fedify",
2717
- "federation",
2718
- "object"
2719
- ]);
2720
- if (objectDispatcher == null) return await onNotFound(request);
2721
- const object = await objectDispatcher(context, values);
2722
- if (object == null) return await onNotFound(request);
2723
- if (!isRequestedPortableObject(object, canonicalId)) {
2724
- logger.debug("The object {objectId} does not match the requested portable object {portableId}.", {
2725
- objectId: object.id?.href,
2726
- portableId: canonicalId
2727
- });
2728
- return await onNotFound(request);
2729
- }
2730
- if (authorizePredicate != null) {
2731
- if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
2732
- }
2733
- let jsonLd;
2734
- let servedId;
2735
- let result;
2660
+ if (rsaKey == null && keys.length < 1) logger.debug("Sending the activity {activityId} to {inbox} without a signature.", {
2661
+ activityId,
2662
+ inbox: inbox.href
2663
+ });
2664
+ else if (rsaKey == null) logger.warn("No supported key found to sign the request to {inbox}. The request will be sent without a signature. In order to sign the request, at least one RSASSA-PKCS1-v1_5 key must be provided.", {
2665
+ inbox: inbox.href,
2666
+ keys: keys.map((pair) => ({
2667
+ keyId: pair.keyId.href,
2668
+ privateKey: pair.privateKey
2669
+ }))
2670
+ });
2671
+ let response;
2736
2672
  try {
2737
- jsonLd = await object.toJsonLd(context);
2738
- servedId = await getJsonLdRootId(jsonLd, context.contextLoader);
2739
- result = await verifyPortableObjectProof(jsonLd, {
2740
- contextLoader: context.contextLoader,
2741
- documentLoader: context.documentLoader,
2742
- tracerProvider: context.tracerProvider,
2743
- meterProvider: context.meterProvider
2673
+ response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
2674
+ tracerProvider,
2675
+ specDeterminer,
2676
+ validateRedirect: validateUrl
2744
2677
  });
2745
2678
  } catch (error) {
2746
- logger.error("Failed to verify the Object Integrity Proofs of the portable object {portableId}:\n{error}", {
2747
- portableId: canonicalId,
2748
- error
2749
- });
2750
- return portableObjectInternalServerError(request);
2751
- }
2752
- if (servedId == null || !isRequestedPortableId(servedId, canonicalId)) {
2753
- logger.debug("The serialized object does not match the requested portable object {portableId}.", { portableId: canonicalId });
2754
- return await onNotFound(request);
2755
- }
2756
- if (!result.verified && result.reason.type !== "unsecuredCollection" && result.reason.type !== "unsupportedObjectType") {
2757
- logger.error("Refusing to serve the portable object {portableId}, as it does not satisfy the FEP-ef61 proof policy: {reason}. Portable actors, activities, and objects need an Object Integrity Proof made with a key of the DID in their ID.", {
2758
- portableId: canonicalId,
2759
- reason: result.reason.type
2679
+ const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
2680
+ logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2681
+ activityId,
2682
+ inbox: inbox.href,
2683
+ error: failure
2760
2684
  });
2761
- return portableObjectInternalServerError(request);
2685
+ federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
2686
+ throw failure;
2762
2687
  }
2763
- return new Response(request.method === "HEAD" ? null : JSON.stringify(jsonLd), { headers: {
2764
- "Content-Type": PORTABLE_OBJECT_CONTENT_TYPE,
2765
- Vary: "Accept"
2766
- } });
2767
- }
2768
- function isRequestedPortableObject(object, canonicalId) {
2769
- return object.id != null && getCanonicalPortableId(object.id) === canonicalId;
2770
- }
2771
- async function getJsonLdRootId(jsonLd, contextLoader) {
2772
- const expanded = await jsonld.expand(jsonLd, {
2773
- documentLoader: getNormalizationContextLoader(contextLoader),
2774
- keepFreeFloatingNodes: true
2775
- });
2776
- if (expanded.length !== 1) return null;
2777
- const id = expanded[0]["@id"];
2778
- return typeof id === "string" ? id : null;
2779
- }
2780
- function isRequestedPortableId(id, canonicalId) {
2781
- if (!/^ap(?:\+ef61)?:\/\//i.test(id)) return URL.canParse(id) && getCanonicalPortableId(new URL(id)) === canonicalId;
2782
2688
  try {
2783
- return canonicalizePortableUri(id) === canonicalId;
2784
- } catch (error) {
2785
- if (error instanceof TypeError) return false;
2786
- throw error;
2689
+ if (!response.ok) {
2690
+ let error;
2691
+ try {
2692
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2693
+ } catch (_) {
2694
+ error = "";
2695
+ }
2696
+ logger.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
2697
+ activityId,
2698
+ inbox: inbox.href,
2699
+ status: response.status,
2700
+ statusText: response.statusText,
2701
+ error
2702
+ });
2703
+ throw new SendActivityError(inbox, response.status, `Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`, error, response.headers);
2704
+ }
2705
+ deliverySuccess = true;
2706
+ const eventAttributes = {
2707
+ "activitypub.inbox.url": inbox.href,
2708
+ "activitypub.activity.id": activityId ?? ""
2709
+ };
2710
+ if (activityType != null) eventAttributes["activitypub.activity.type"] = activityType;
2711
+ const actorId = getActivityActorId(activity);
2712
+ if (actorId != null) eventAttributes["activitypub.actor.id"] = actorId;
2713
+ span.addEvent("activitypub.activity.sent", eventAttributes);
2714
+ } finally {
2715
+ federationMetrics.recordDelivery(inbox, getDurationMs(started), deliverySuccess, activityType);
2787
2716
  }
2788
2717
  }
2789
- function portableObjectInternalServerError(request) {
2790
- return new Response(request.method === "HEAD" ? null : "Internal server error.", {
2791
- status: 500,
2792
- headers: { "Content-Type": "text/plain; charset=utf-8" }
2793
- });
2794
- }
2795
- const BUILT_IN_COLLECTION_METRIC_KINDS = /* @__PURE__ */ new Set([
2796
- "inbox",
2797
- "outbox",
2798
- "following",
2799
- "followers",
2800
- "liked",
2801
- "featured",
2802
- "featured_tags"
2803
- ]);
2804
- function getCollectionMetricKind(name) {
2805
- const normalized = name.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/\s+/g, "_");
2806
- return BUILT_IN_COLLECTION_METRIC_KINDS.has(normalized) ? normalized : "custom";
2807
- }
2808
- function collectionAttributes(base, result, response) {
2809
- return {
2810
- ...base,
2811
- result,
2812
- ...response == null ? {} : { statusCode: response.status }
2813
- };
2718
+ function createFetchError(url, cause) {
2719
+ const error = new FetchError(url, cause instanceof Error ? cause.message : String(cause));
2720
+ error.cause = cause;
2721
+ return error;
2814
2722
  }
2815
- function recordCollectionMetrics(meterProvider, base, result, options = {}) {
2816
- const attrs = collectionAttributes(base, result, options.response);
2817
- recordCollectionRequest(meterProvider, attrs);
2818
- if (options.dispatchDurationMs != null) recordCollectionDispatchDuration(meterProvider, options.dispatchDurationMs, attrs);
2819
- if (options.itemCount != null) recordCollectionPageItems(meterProvider, options.itemCount, attrs);
2820
- if (options.totalItems != null) recordCollectionTotalItems(meterProvider, options.totalItems, attrs);
2723
+ async function fetchWithValidatedRedirects(request, validateUrl) {
2724
+ let body = await request.clone().text();
2725
+ for (let redirects = 0;; redirects++) {
2726
+ const response = await fetch(request, { redirect: "manual" });
2727
+ const location = response.headers.get("Location");
2728
+ if (![
2729
+ 301,
2730
+ 302,
2731
+ 303,
2732
+ 307,
2733
+ 308
2734
+ ].includes(response.status) || location == null) return response;
2735
+ await response.body?.cancel();
2736
+ if (redirects >= 20) throw new TypeError("Too many redirects");
2737
+ const url = new URL(location, request.url);
2738
+ await validateUrl(url.href);
2739
+ const headers = new Headers(request.headers);
2740
+ if (url.origin !== new URL(request.url).origin) {
2741
+ headers.delete("Authorization");
2742
+ headers.delete("Proxy-Authorization");
2743
+ headers.delete("Cookie");
2744
+ headers.delete("Host");
2745
+ }
2746
+ let method = request.method;
2747
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
2748
+ method = "GET";
2749
+ body = void 0;
2750
+ for (const name of [
2751
+ "Content-Encoding",
2752
+ "Content-Language",
2753
+ "Content-Length",
2754
+ "Content-Location",
2755
+ "Content-Type"
2756
+ ]) headers.delete(name);
2757
+ }
2758
+ request = new Request(url, {
2759
+ method,
2760
+ headers,
2761
+ body,
2762
+ redirect: "manual"
2763
+ });
2764
+ }
2821
2765
  }
2822
2766
  /**
2823
- * Handles a collection request.
2824
- * @template TItem The type of items in the collection.
2825
- * @template TContext The type of the context, extending {@link RequestContext}.
2826
- * @template TContextData The context data to pass to the `TContext`.
2827
- * @template TFilter The type of the filter.
2828
- * @param request The HTTP request.
2829
- * @param parameters The parameters for handling the collection.
2830
- * @returns A promise that resolves to an HTTP response.
2767
+ * An error that is thrown when an activity fails to send to a remote inbox.
2768
+ * It contains structured information about the failure, including the HTTP
2769
+ * status code, the inbox URL, and the response body.
2770
+ * @since 2.0.0
2831
2771
  */
2832
- async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
2833
- const spanName = name$2.trim().replace(/\s+/g, "_");
2834
- tracerProvider = tracerProvider ?? trace.getTracerProvider();
2835
- const tracer = tracerProvider.getTracer(name, version);
2836
- const cursor = new URL(request.url).searchParams.get("cursor");
2837
- const metricBase = {
2772
+ var SendActivityError = class extends Error {
2773
+ /**
2774
+ * The inbox URL that the activity was being sent to.
2775
+ */
2776
+ inbox;
2777
+ /**
2778
+ * The HTTP status code returned by the inbox.
2779
+ */
2780
+ statusCode;
2781
+ /**
2782
+ * The response body from the inbox, if any. Note that this may be
2783
+ * truncated to a maximum of 1 KiB to prevent excessive memory consumption
2784
+ * when remote servers return large error pages (e.g., Cloudflare error pages).
2785
+ * If truncated, the string will end with `"… (truncated)"`.
2786
+ */
2787
+ responseBody;
2788
+ /**
2789
+ * The response headers from the inbox.
2790
+ * @since 2.3.0
2791
+ */
2792
+ responseHeaders;
2793
+ /**
2794
+ * Creates a new {@link SendActivityError}.
2795
+ * @param inbox The inbox URL.
2796
+ * @param statusCode The HTTP status code.
2797
+ * @param message The error message.
2798
+ * @param responseBody The response body.
2799
+ * @param responseHeaders The response headers.
2800
+ */
2801
+ constructor(inbox, statusCode, message, responseBody, responseHeaders) {
2802
+ super(message);
2803
+ this.name = "SendActivityError";
2804
+ this.inbox = inbox;
2805
+ this.statusCode = statusCode;
2806
+ this.responseBody = responseBody;
2807
+ this.responseHeaders = new Headers(responseHeaders);
2808
+ }
2809
+ };
2810
+ //#endregion
2811
+ //#region src/federation/portable-inbox.ts
2812
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
2813
+ /**
2814
+ * Fills in the defaults of {@link PortableInboxForwardingOptions} and
2815
+ * validates them.
2816
+ * @param options The options.
2817
+ * @returns The resolved options.
2818
+ * @throws {RangeError} If `maxTargets` is not a non-negative integer, if `ttl`
2819
+ * is not positive, if `deadline` is negative or longer
2820
+ * than 2,147,483,647 milliseconds (about 24.8 days), or
2821
+ * if either duration has calendar units, i.e., weeks,
2822
+ * months, or years, whose length depends on the date.
2823
+ */
2824
+ function resolvePortableInboxForwardingOptions(options = {}) {
2825
+ const maxTargets = options.maxTargets ?? 10;
2826
+ if (!Number.isInteger(maxTargets) || maxTargets < 0) throw new RangeError("portableInboxForwarding.maxTargets must be a non-negative integer.");
2827
+ const ttl = Temporal.Duration.from(options.ttl ?? { days: 30 });
2828
+ if (ttl.total("millisecond") <= 0) throw new RangeError("portableInboxForwarding.ttl must be positive.");
2829
+ const deadline = Temporal.Duration.from(options.deadline ?? { seconds: 10 });
2830
+ const deadlineMs = deadline.total("millisecond");
2831
+ if (deadlineMs < 0 || deadlineMs > MAX_TIMEOUT_MS) throw new RangeError(`portableInboxForwarding.deadline must be between 0 and ${MAX_TIMEOUT_MS} milliseconds.`);
2832
+ return {
2833
+ maxTargets,
2834
+ ttl,
2835
+ deadline
2836
+ };
2837
+ }
2838
+ /**
2839
+ * Decides whether this server accepts a delivery to a portable inbox on behalf
2840
+ * of the given actor, which the actor dispatcher returned for the identifier
2841
+ * in the requested inbox path.
2842
+ *
2843
+ * The actor document comes from the application, so it is trusted as is and
2844
+ * its proof is not verified here.
2845
+ * @param actor The actor the actor dispatcher returned.
2846
+ * @param options The requested DID, the canonical form of the requested inbox
2847
+ * ID, and the origin of this server.
2848
+ * @returns The resolution.
2849
+ */
2850
+ function resolvePortableInboxRecipient(actor, { authority, canonicalInboxId, localOrigin }) {
2851
+ if (actor == null) return {
2852
+ status: "rejected",
2853
+ reason: "notFound"
2854
+ };
2855
+ const id = actor.id;
2856
+ const did = id == null || !isPortableId(id) ? null : getPortableDid(id);
2857
+ if (id == null || did == null) return {
2858
+ status: "rejected",
2859
+ reason: "notPortable"
2860
+ };
2861
+ if (did !== authority) return {
2862
+ status: "rejected",
2863
+ reason: "authorityMismatch"
2864
+ };
2865
+ const inboxId = actor.inboxId == null ? null : toPortableUri(actor.inboxId);
2866
+ if (inboxId == null || getCanonicalPortableId(inboxId) !== canonicalInboxId) return {
2867
+ status: "rejected",
2868
+ reason: "inboxMismatch"
2869
+ };
2870
+ const gateways = actor.gateways;
2871
+ if (!gateways.some((g) => isGatewayUrl(g) && g.origin === localOrigin)) return {
2872
+ status: "rejected",
2873
+ reason: "notGateway"
2874
+ };
2875
+ return {
2876
+ status: "accepted",
2877
+ recipient: {
2878
+ actorId: id,
2879
+ inboxId,
2880
+ canonicalInboxId,
2881
+ gateways
2882
+ }
2883
+ };
2884
+ }
2885
+ /**
2886
+ * Gets the portable form of an `ap:` or `ap+ef61:` URI or a compatible
2887
+ * identifier, keeping its query.
2888
+ * @returns The portable URI, or `null` if the ID is neither, or is malformed.
2889
+ */
2890
+ function toPortableUri(id) {
2891
+ if (isPortableUri(id)) return id;
2892
+ try {
2893
+ return fromCompatibleEf61Id(id);
2894
+ } catch (error) {
2895
+ if (error instanceof TypeError) return null;
2896
+ throw error;
2897
+ }
2898
+ }
2899
+ const RFC9421_DELIVERY_COMPONENTS = [
2900
+ "@method",
2901
+ "@target-uri",
2902
+ "content-digest"
2903
+ ];
2904
+ const DRAFT_DELIVERY_COMPONENTS = [
2905
+ "(request-target)",
2906
+ "host",
2907
+ "digest"
2908
+ ];
2909
+ /**
2910
+ * Checks whether an HTTP Signature covers the method, the target URI, and the
2911
+ * body of a request, which both Fedify and Mitra sign when forwarding.
2912
+ * @param signature The signature.
2913
+ * @returns `true` if the signature covers them.
2914
+ */
2915
+ function coversDelivery(signature) {
2916
+ return (signature.label == null ? DRAFT_DELIVERY_COMPONENTS : RFC9421_DELIVERY_COMPONENTS).every((name) => signature.components.some((c) => c.value === name && Object.keys(c.params).length < 1));
2917
+ }
2918
+ /**
2919
+ * Forwards an activity received in a portable inbox to the inboxes of the same
2920
+ * portable actor on its other gateways, as FEP-ef61 recommends.
2921
+ *
2922
+ * FEP-ef61 forbids forwarding an activity from an inbox more than once, so
2923
+ * each target gateway is claimed with an atomic compare-and-swap before the
2924
+ * activity is handed off, and a claim is never released, even if the hand-off
2925
+ * fails, since a failed hand-off does not prove that nothing was delivered.
2926
+ * Forwarding is therefore best effort. Without {@link KvStore.cas}, nothing is
2927
+ * forwarded.
2928
+ *
2929
+ * Forwarded requests are signed with HTTP Signatures by the RSA key among
2930
+ * {@link ForwardPortableInboxActivityParameters.getKeys}, if any, so that
2931
+ * servers requiring HTTP Signatures accept them, and are sent unsigned
2932
+ * otherwise. Either way, the receiving gateways authenticate the activity by
2933
+ * its own proof.
2934
+ *
2935
+ * If the delivery is signed with a gateway key of the recipient by one of its
2936
+ * other gateways, that gateway has the activity already, so it is claimed
2937
+ * without forwarding the activity to it. See {@link identifySendingGateway}.
2938
+ * @param parameters The parameters.
2939
+ * @returns The target inbox URLs that the activity was handed off to.
2940
+ */
2941
+ async function forwardPortableInboxActivity(parameters) {
2942
+ const logger = getLogger([
2943
+ "fedify",
2944
+ "federation",
2945
+ "inbox"
2946
+ ]);
2947
+ const { recipient, activityId, excludedOrigins, kv, kvPrefix, outboxQueue } = parameters;
2948
+ const options = parameters.options ?? resolvePortableInboxForwardingOptions();
2949
+ const { maxTargets, ttl } = options;
2950
+ if (kv.cas == null || maxTargets < 1) return [];
2951
+ const deadline = Date.now() + options.deadline.total("millisecond");
2952
+ const canonicalActivityId = getCanonicalPortableId(activityId) ?? activityId.href;
2953
+ const claimKey = (gateway) => [
2954
+ ...kvPrefix,
2955
+ recipient.canonicalInboxId,
2956
+ canonicalActivityId,
2957
+ gateway
2958
+ ];
2959
+ let targets = getForwardingTargets(recipient, excludedOrigins);
2960
+ const sender = await identifySendingGateway(parameters, targets.map((t) => t.gateway), claimKey, deadline);
2961
+ if (sender != null) {
2962
+ logger.debug("Not forwarding activity {activityId} from the portable inbox {inbox} back to the gateway {gateway}, which delivered it.", {
2963
+ activityId: activityId.href,
2964
+ inbox: recipient.canonicalInboxId,
2965
+ gateway: sender
2966
+ });
2967
+ await kv.cas(claimKey(sender), void 0, true, { ttl });
2968
+ targets = targets.filter((t) => t.gateway !== sender);
2969
+ }
2970
+ if (targets.length > maxTargets) {
2971
+ logger.warn("The portable actor that owns the inbox {inbox} has more than {max} other gateways; the activity {activityId} is forwarded only to the first {max} of them.", {
2972
+ inbox: recipient.canonicalInboxId,
2973
+ activityId: activityId.href,
2974
+ max: maxTargets
2975
+ });
2976
+ targets.length = maxTargets;
2977
+ }
2978
+ const claimed = [];
2979
+ for (const { gateway, inbox } of targets) if (await kv.cas(claimKey(gateway), void 0, true, { ttl })) claimed.push(inbox);
2980
+ if (claimed.length < 1) return [];
2981
+ logger.debug("Forwarding activity {activityId} from the portable inbox {inbox} to other gateways:\n{targets}", {
2982
+ activityId: activityId.href,
2983
+ inbox: recipient.canonicalInboxId,
2984
+ targets: claimed.map((t) => t.href)
2985
+ });
2986
+ if (outboxQueue == null) await forwardImmediately(parameters, claimed, deadline);
2987
+ else await enqueueForwarding(parameters, outboxQueue, claimed);
2988
+ return claimed;
2989
+ }
2990
+ /**
2991
+ * Identifies the gateway of the recipient that forwarded a delivery to its
2992
+ * portable inbox, by the delivery's HTTP Signature made with the recipient's
2993
+ * gateway key, which FEP-ef61 has each gateway use for requests on behalf of
2994
+ * an actor. Since the activity is authenticated by its own proof, the
2995
+ * signature only tells which gateway to skip, and a delivery whose signature
2996
+ * is invalid or cannot be verified is still forwarded to every gateway.
2997
+ *
2998
+ * Verifying the signature fetches the recipient's actor document from the
2999
+ * sending gateway, as gateway keys are not cached, so only the first signature
3000
+ * that may save a request is verified: one that covers the delivery and names
3001
+ * a gateway key of the recipient on one of the forwarding targets that the
3002
+ * activity has not been forwarded to yet.
3003
+ * @param parameters The forwarding parameters.
3004
+ * @param targets The origins of the gateways to forward to.
3005
+ * @param claimKey Gets the key of the claim for a gateway.
3006
+ * @param deadline The time by which identification has to finish, in
3007
+ * milliseconds since the epoch; afterwards, the sending
3008
+ * gateway is left unidentified.
3009
+ * @returns The origin of the sending gateway, or `null` if it is not
3010
+ * identified.
3011
+ */
3012
+ async function identifySendingGateway({ recipient, activityId, kv, signatures }, targets, claimKey, deadline) {
3013
+ if (signatures == null || signatures.length < 1) return null;
3014
+ const logger = getLogger([
3015
+ "fedify",
3016
+ "federation",
3017
+ "inbox"
3018
+ ]);
3019
+ const actorId = getCanonicalPortableId(recipient.actorId);
3020
+ if (actorId == null) return null;
3021
+ const isGatewayKeyOfRecipient = (keyId) => {
3022
+ if (!isCompatibleKeyId(keyId) || !targets.includes(keyId.origin)) return false;
3023
+ const base = new URL(keyId.href);
3024
+ base.hash = "";
3025
+ return getCanonicalPortableId(base) === actorId;
3026
+ };
3027
+ let signature;
3028
+ for (const candidate of signatures) if (candidate.coversDelivery && isGatewayKeyOfRecipient(candidate.keyId) && await kv.get(claimKey(candidate.keyId.origin)) === void 0) {
3029
+ signature = candidate;
3030
+ break;
3031
+ }
3032
+ if (signature == null) return null;
3033
+ const { keyId } = signature;
3034
+ const logProperties = {
3035
+ activityId: activityId.href,
3036
+ inbox: recipient.canonicalInboxId,
3037
+ keyId: keyId.href
3038
+ };
3039
+ const verification = Promise.resolve().then(() => signature.verify()).then((key) => {
3040
+ if (key == null) logger.debug("The HTTP Signature of the delivery of activity {activityId} to the portable inbox {inbox} is not verified with the key {keyId}; forwarding it without identifying the sending gateway.", logProperties);
3041
+ return key;
3042
+ }, (error) => {
3043
+ logger.debug("Failed to verify the HTTP Signature of the delivery of activity {activityId} to the portable inbox {inbox} with the key {keyId}; forwarding it without identifying the sending gateway:\n{error}", {
3044
+ ...logProperties,
3045
+ error
3046
+ });
3047
+ return null;
3048
+ });
3049
+ let timer;
3050
+ const key = await Promise.race([verification, new Promise((resolve) => {
3051
+ timer = setTimeout(() => {
3052
+ logger.debug("Verifying the HTTP Signature of the delivery of activity {activityId} to the portable inbox {inbox} did not finish in time; forwarding it without identifying the sending gateway.", logProperties);
3053
+ resolve(null);
3054
+ }, Math.max(0, deadline - Date.now()));
3055
+ })]);
3056
+ clearTimeout(timer);
3057
+ if (key == null) return null;
3058
+ if (key.id == null || key.id.href !== keyId.href || !isGatewayKeyOfRecipient(key.id) || key.ownerId == null || !isPortableId(key.ownerId) || getCanonicalPortableId(key.ownerId) !== actorId) {
3059
+ logger.debug("The delivery of activity {activityId} to the portable inbox {inbox} is not signed with a gateway key of the recipient; forwarding it without identifying the sending gateway.", logProperties);
3060
+ return null;
3061
+ }
3062
+ return key.id.origin;
3063
+ }
3064
+ function getForwardingTargets(recipient, excludedOrigins) {
3065
+ const logger = getLogger([
3066
+ "fedify",
3067
+ "federation",
3068
+ "inbox"
3069
+ ]);
3070
+ const seen = new Set(excludedOrigins);
3071
+ const targets = [];
3072
+ for (const gateway of recipient.gateways) {
3073
+ if (!isGatewayUrl(gateway) || seen.has(gateway.origin)) continue;
3074
+ seen.add(gateway.origin);
3075
+ let inbox;
3076
+ try {
3077
+ inbox = toCompatibleEf61Id(recipient.inboxId, gateway.origin);
3078
+ } catch (error) {
3079
+ if (!(error instanceof TypeError)) throw error;
3080
+ logger.warn("Cannot forward to the gateway {gateway}, as the portable inbox {inbox} cannot be represented as its compatible identifier.", {
3081
+ gateway: gateway.origin,
3082
+ inbox: recipient.canonicalInboxId
3083
+ });
3084
+ continue;
3085
+ }
3086
+ targets.push({
3087
+ gateway: gateway.origin,
3088
+ inbox
3089
+ });
3090
+ }
3091
+ return targets;
3092
+ }
3093
+ /**
3094
+ * Resolves the key that signs forwarded requests: the first RSASSA-PKCS1-v1_5
3095
+ * key, as {@link sendActivity} signs requests only with such a key. Since
3096
+ * the targets have already been claimed, the activity is forwarded unsigned
3097
+ * rather than not at all if the key cannot be resolved or used.
3098
+ */
3099
+ async function resolveForwardingKey({ getKeys, activityId }) {
3100
+ if (getKeys == null) return null;
3101
+ const logger = getLogger([
3102
+ "fedify",
3103
+ "federation",
3104
+ "inbox"
3105
+ ]);
3106
+ let key;
3107
+ try {
3108
+ key = (await getKeys()).find((k) => k.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5");
3109
+ } catch (error) {
3110
+ logger.error("Failed to get the gateway keys to sign forwarded requests with; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
3111
+ activityId: activityId.href,
3112
+ error
3113
+ });
3114
+ return null;
3115
+ }
3116
+ if (key == null) return null;
3117
+ try {
3118
+ validateCryptoKey(key.privateKey, "private");
3119
+ } catch (error) {
3120
+ if (!(error instanceof TypeError)) throw error;
3121
+ logger.warn("The gateway key {keyId} cannot sign forwarded requests; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
3122
+ keyId: key.keyId.href,
3123
+ activityId: activityId.href,
3124
+ error
3125
+ });
3126
+ return null;
3127
+ }
3128
+ return key;
3129
+ }
3130
+ async function forwardImmediately(parameters, inboxes, deadlineAt) {
3131
+ const { activity, activityId, activityType, allowPrivateAddress, specDeterminer, meterProvider, tracerProvider } = parameters;
3132
+ const logger = getLogger([
3133
+ "fedify",
3134
+ "federation",
3135
+ "inbox"
3136
+ ]);
3137
+ const deadline = Math.max(0, deadlineAt - Date.now());
3138
+ const forwarding = resolveForwardingKey(parameters).then((key) => Promise.all(inboxes.map((inbox) => sendActivity({
3139
+ activity,
3140
+ activityId: activityId.href,
3141
+ activityType,
3142
+ keys: key == null ? [] : [key],
3143
+ inbox,
3144
+ allowPrivateAddress,
3145
+ specDeterminer,
3146
+ meterProvider,
3147
+ tracerProvider
3148
+ }).catch((error) => {
3149
+ logger.error("Failed to forward activity {activityId} to {inbox}; it will not be forwarded to the inbox again:\n{error}", {
3150
+ activityId: activityId.href,
3151
+ inbox: inbox.href,
3152
+ error
3153
+ });
3154
+ }))));
3155
+ let timer;
3156
+ const timedOut = await Promise.race([forwarding.then(() => false), new Promise((resolve) => {
3157
+ timer = setTimeout(() => resolve(true), deadline);
3158
+ })]);
3159
+ clearTimeout(timer);
3160
+ if (timedOut) logger.warn("Forwarding activity {activityId} to other gateways did not finish in {deadline} ms; responding to the delivery without waiting for it.", {
3161
+ activityId: activityId.href,
3162
+ deadline
3163
+ });
3164
+ }
3165
+ async function enqueueForwarding(parameters, outboxQueue, inboxes) {
3166
+ const { activity, activityId, activityType, baseUrl, startQueue, meterProvider } = parameters;
3167
+ const logger = getLogger([
3168
+ "fedify",
3169
+ "federation",
3170
+ "inbox"
3171
+ ]);
3172
+ const key = await resolveForwardingKey(parameters);
3173
+ const keys = [];
3174
+ if (key != null) try {
3175
+ keys.push({
3176
+ keyId: key.keyId.href,
3177
+ privateKey: await exportJwk(key.privateKey)
3178
+ });
3179
+ } catch (error) {
3180
+ logger.error("Failed to export the gateway key {keyId}; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
3181
+ keyId: key.keyId.href,
3182
+ activityId: activityId.href,
3183
+ error
3184
+ });
3185
+ }
3186
+ startQueue?.();
3187
+ const started = (/* @__PURE__ */ new Date()).toISOString();
3188
+ const traceContext = {};
3189
+ propagation.inject(context.active(), traceContext);
3190
+ await Promise.all(inboxes.map(async (inbox) => {
3191
+ const message = {
3192
+ type: "outbox",
3193
+ id: crypto.randomUUID(),
3194
+ baseUrl,
3195
+ keys,
3196
+ activity,
3197
+ activityId: activityId.href,
3198
+ activityType,
3199
+ inbox: inbox.href,
3200
+ sharedInbox: false,
3201
+ started,
3202
+ attempt: 0,
3203
+ headers: {},
3204
+ traceContext
3205
+ };
3206
+ try {
3207
+ await outboxQueue.enqueue(message);
3208
+ } catch (error) {
3209
+ logger.error("Failed to enqueue activity {activityId} to forward to {inbox}; it will not be forwarded to the inbox again:\n{error}", {
3210
+ activityId: activityId.href,
3211
+ inbox: inbox.href,
3212
+ error
3213
+ });
3214
+ return;
3215
+ }
3216
+ recordOutboxEnqueue(meterProvider, outboxQueue, message);
3217
+ }));
3218
+ }
3219
+ //#endregion
3220
+ //#region src/federation/temporal.ts
3221
+ function isPlainObject$1(value) {
3222
+ return typeof value === "object" && value != null && !Array.isArray(value);
3223
+ }
3224
+ function normalizeDateTimeLiteral(value) {
3225
+ return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
3226
+ }
3227
+ function isMalformedDateTimeLiteral(value) {
3228
+ if (typeof value !== "string") return false;
3229
+ try {
3230
+ Temporal.Instant.from(normalizeDateTimeLiteral(value));
3231
+ return false;
3232
+ } catch {
3233
+ return true;
3234
+ }
3235
+ }
3236
+ function isMalformedDurationLiteral(value) {
3237
+ if (typeof value !== "string") return false;
3238
+ try {
3239
+ Temporal.Duration.from(value);
3240
+ return false;
3241
+ } catch {
3242
+ return true;
3243
+ }
3244
+ }
3245
+ const TEMPORAL_DATE_TIME_IRIS = /* @__PURE__ */ new Set([
3246
+ "https://www.w3.org/ns/activitystreams#deleted",
3247
+ "https://www.w3.org/ns/activitystreams#endTime",
3248
+ "https://www.w3.org/ns/activitystreams#published",
3249
+ "https://www.w3.org/ns/activitystreams#startTime",
3250
+ "https://www.w3.org/ns/activitystreams#updated",
3251
+ "http://purl.org/dc/terms/created",
3252
+ "https://w3id.org/security#created"
3253
+ ]);
3254
+ const TEMPORAL_DURATION_IRIS = /* @__PURE__ */ new Set(["https://www.w3.org/ns/activitystreams#duration"]);
3255
+ const QUESTION_CLOSED_IRI = "https://www.w3.org/ns/activitystreams#closed";
3256
+ const XSD_DATE_TIME_IRI = "http://www.w3.org/2001/XMLSchema#dateTime";
3257
+ function hasMalformedExpandedDateTimeLiteral(value) {
3258
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedDateTimeLiteral);
3259
+ return isPlainObject$1(value) && "@value" in value && isMalformedDateTimeLiteral(value["@value"]);
3260
+ }
3261
+ function hasMalformedExpandedQuestionClosedLiteral(value) {
3262
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedQuestionClosedLiteral);
3263
+ if (!isPlainObject$1(value) || !("@value" in value)) return false;
3264
+ const literal = value["@value"];
3265
+ if (typeof literal === "boolean") return false;
3266
+ if (typeof literal !== "string") return false;
3267
+ if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
3268
+ if (new Date(literal).toString() === "Invalid Date") return false;
3269
+ return isMalformedDateTimeLiteral(literal);
3270
+ }
3271
+ function hasMalformedExpandedDurationLiteral(value) {
3272
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedDurationLiteral);
3273
+ return isPlainObject$1(value) && "@value" in value && isMalformedDurationLiteral(value["@value"]);
3274
+ }
3275
+ function hasMalformedKnownTemporalLiteralInternal(value, visited) {
3276
+ if (Array.isArray(value)) return value.some((item) => hasMalformedKnownTemporalLiteralInternal(item, visited));
3277
+ if (!isPlainObject$1(value)) return false;
3278
+ if (visited.has(value)) return false;
3279
+ visited.add(value);
3280
+ if ("@value" in value) return false;
3281
+ for (const [key, child] of Object.entries(value)) {
3282
+ if (TEMPORAL_DATE_TIME_IRIS.has(key)) {
3283
+ if (hasMalformedExpandedDateTimeLiteral(child)) return true;
3284
+ continue;
3285
+ }
3286
+ if (key === QUESTION_CLOSED_IRI) {
3287
+ if (hasMalformedExpandedQuestionClosedLiteral(child)) return true;
3288
+ continue;
3289
+ }
3290
+ if (TEMPORAL_DURATION_IRIS.has(key)) {
3291
+ if (hasMalformedExpandedDurationLiteral(child)) return true;
3292
+ continue;
3293
+ }
3294
+ if (hasMalformedKnownTemporalLiteralInternal(child, visited)) return true;
3295
+ }
3296
+ return false;
3297
+ }
3298
+ async function hasMalformedKnownTemporalLiteral(value, contextLoader) {
3299
+ try {
3300
+ return hasMalformedKnownTemporalLiteralInternal(await jsonld.expand(value, {
3301
+ documentLoader: getNormalizationContextLoader(contextLoader),
3302
+ keepFreeFloatingNodes: true
3303
+ }), /* @__PURE__ */ new Set());
3304
+ } catch {
3305
+ return false;
3306
+ }
3307
+ }
3308
+ //#endregion
3309
+ //#region src/federation/handler.ts
3310
+ const rawInboxContextFactorySymbol = Symbol("fedify.rawInboxContextFactory");
3311
+ const INBOX_COMPOUND_PROOF_LIMITS = {
3312
+ maxDepth: 64,
3313
+ maxMaps: 1e4,
3314
+ maxProofs: 32,
3315
+ maxBytes: 10 * 1024 * 1024
3316
+ };
3317
+ function isRemoteContextLoadingFailure$1(error) {
3318
+ return error instanceof Error && typeof error.details === "object" && error.details != null && error.details.code === "loading remote context failed";
3319
+ }
3320
+ function isPermanentRemoteContextError$1(error) {
3321
+ if (!(error instanceof Error) || error.name !== "jsonld.InvalidUrl") return false;
3322
+ const details = error.details;
3323
+ if (details?.code === "invalid remote context") return true;
3324
+ return isRemoteContextLoadingFailure$1(error) && typeof details?.url === "string" && !URL.canParse(details.url) && isClearlyMalformedContextReference(details.url);
3325
+ }
3326
+ function isInvalidJsonLdError(error) {
3327
+ if (!(error instanceof Error)) return false;
3328
+ const name = error.name;
3329
+ return name === "UnsafeJsonLdError" || error instanceof InvalidContextReferenceError || isPermanentRemoteContextError$1(error) || name === "jsonld.SyntaxError" && !isRemoteContextLoadingFailure$1(error);
3330
+ }
3331
+ function isValidationTypeError(error) {
3332
+ return error instanceof TypeError && (/^(Invalid JSON-LD:|Invalid type:|Unexpected type:|Invalid @id:)/.test(error.message) || isInvalidUrlTypeError(error));
3333
+ }
3334
+ function isPermanentActivityParseError(error) {
3335
+ return isInvalidJsonLdError(error) || isValidationTypeError(error);
3336
+ }
3337
+ function hasHttpSignatureHeaders(request) {
3338
+ return request.headers.has("Signature") || request.headers.has("Signature-Input");
3339
+ }
3340
+ function hasObjectIntegrityProof(json) {
3341
+ return typeof json === "object" && json != null && "proof" in json;
3342
+ }
3343
+ /**
3344
+ * Handles an actor request.
3345
+ * @template TContextData The context data to pass to the context.
3346
+ * @param request The HTTP request.
3347
+ * @param parameters The parameters for handling the actor.
3348
+ * @returns A promise that resolves to an HTTP response.
3349
+ */
3350
+ async function handleActor(request, { identifier, context, actorDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
3351
+ const logger = getLogger([
3352
+ "fedify",
3353
+ "federation",
3354
+ "actor"
3355
+ ]);
3356
+ if (actorDispatcher == null) {
3357
+ logger.debug("Actor dispatcher is not set.", { identifier });
3358
+ return await onNotFound(request);
3359
+ }
3360
+ const actor = await actorDispatcher(context, identifier);
3361
+ if (actor == null) {
3362
+ logger.debug("Actor {identifier} not found.", { identifier });
3363
+ return await onNotFound(request);
3364
+ }
3365
+ if (authorizePredicate != null) {
3366
+ if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
3367
+ }
3368
+ if (actor instanceof Tombstone) {
3369
+ const jsonLd = await actor.toJsonLd(context);
3370
+ return new Response(JSON.stringify(jsonLd), {
3371
+ status: 410,
3372
+ headers: {
3373
+ "Content-Type": "application/activity+json",
3374
+ Vary: "Accept"
3375
+ }
3376
+ });
3377
+ }
3378
+ const jsonLd = await actor.toJsonLd(context);
3379
+ return new Response(JSON.stringify(jsonLd), { headers: {
3380
+ "Content-Type": "application/activity+json",
3381
+ Vary: "Accept"
3382
+ } });
3383
+ }
3384
+ /**
3385
+ * Handles an object request.
3386
+ * @template TContextData The context data to pass to the context.
3387
+ * @param request The HTTP request.
3388
+ * @param parameters The parameters for handling the object.
3389
+ * @returns A promise that resolves to an HTTP response.
3390
+ */
3391
+ async function handleObject(request, { values, context, objectDispatcher, authorizePredicate, onNotFound, onUnauthorized }) {
3392
+ if (objectDispatcher == null) return await onNotFound(request);
3393
+ const object = await objectDispatcher(context, values);
3394
+ if (object == null) return await onNotFound(request);
3395
+ if (authorizePredicate != null) {
3396
+ if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
3397
+ }
3398
+ const jsonLd = await object.toJsonLd(context);
3399
+ return new Response(JSON.stringify(jsonLd), { headers: {
3400
+ "Content-Type": "application/activity+json",
3401
+ Vary: "Accept"
3402
+ } });
3403
+ }
3404
+ /**
3405
+ * Handles an FEP-ef61 gateway request for a portable object through an object
3406
+ * dispatcher. The object is served only if its ID canonically matches the
3407
+ * requested portable ID and it satisfies the FEP-ef61 proof policy.
3408
+ * @template TContextData The context data to pass to the context.
3409
+ * @param request The HTTP request.
3410
+ * @param parameters The parameters for handling the portable object.
3411
+ * @returns A promise that resolves to an HTTP response.
3412
+ */
3413
+ async function handlePortableObject(request, { values, context, objectDispatcher, authorizePredicate, canonicalId, onNotFound, onUnauthorized }) {
3414
+ const logger = getLogger([
3415
+ "fedify",
3416
+ "federation",
3417
+ "object"
3418
+ ]);
3419
+ if (objectDispatcher == null) return await onNotFound(request);
3420
+ const object = await objectDispatcher(context, values);
3421
+ if (object == null) return await onNotFound(request);
3422
+ if (!isRequestedPortableObject(object, canonicalId)) {
3423
+ logger.debug("The object {objectId} does not match the requested portable object {portableId}.", {
3424
+ objectId: object.id?.href,
3425
+ portableId: canonicalId
3426
+ });
3427
+ return await onNotFound(request);
3428
+ }
3429
+ if (authorizePredicate != null) {
3430
+ if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
3431
+ }
3432
+ let jsonLd;
3433
+ let servedId;
3434
+ let result;
3435
+ try {
3436
+ jsonLd = await object.toJsonLd(context);
3437
+ servedId = await getJsonLdRootId(jsonLd, context.contextLoader);
3438
+ result = await verifyPortableObjectProof(jsonLd, {
3439
+ contextLoader: context.contextLoader,
3440
+ documentLoader: context.documentLoader,
3441
+ tracerProvider: context.tracerProvider,
3442
+ meterProvider: context.meterProvider
3443
+ });
3444
+ } catch (error) {
3445
+ logger.error("Failed to verify the Object Integrity Proofs of the portable object {portableId}:\n{error}", {
3446
+ portableId: canonicalId,
3447
+ error
3448
+ });
3449
+ return portableObjectInternalServerError(request);
3450
+ }
3451
+ if (servedId == null || !isRequestedPortableId(servedId, canonicalId)) {
3452
+ logger.debug("The serialized object does not match the requested portable object {portableId}.", { portableId: canonicalId });
3453
+ return await onNotFound(request);
3454
+ }
3455
+ if (!result.verified && result.reason.type !== "unsecuredCollection" && result.reason.type !== "unsupportedObjectType") {
3456
+ logger.error("Refusing to serve the portable object {portableId}, as it does not satisfy the FEP-ef61 proof policy: {reason}. Portable actors, activities, and objects need an Object Integrity Proof made with a key of the DID in their ID.", {
3457
+ portableId: canonicalId,
3458
+ reason: result.reason.type
3459
+ });
3460
+ return portableObjectInternalServerError(request);
3461
+ }
3462
+ return new Response(request.method === "HEAD" ? null : JSON.stringify(jsonLd), { headers: {
3463
+ "Content-Type": PORTABLE_OBJECT_CONTENT_TYPE,
3464
+ Vary: "Accept"
3465
+ } });
3466
+ }
3467
+ function isRequestedPortableObject(object, canonicalId) {
3468
+ return object.id != null && getCanonicalPortableId(object.id) === canonicalId;
3469
+ }
3470
+ async function getJsonLdRootId(jsonLd, contextLoader) {
3471
+ const expanded = await jsonld.expand(jsonLd, {
3472
+ documentLoader: getNormalizationContextLoader(contextLoader),
3473
+ keepFreeFloatingNodes: true
3474
+ });
3475
+ if (expanded.length !== 1) return null;
3476
+ const id = expanded[0]["@id"];
3477
+ return typeof id === "string" ? id : null;
3478
+ }
3479
+ function isRequestedPortableId(id, canonicalId) {
3480
+ if (!/^ap(?:\+ef61)?:\/\//i.test(id)) return URL.canParse(id) && getCanonicalPortableId(new URL(id)) === canonicalId;
3481
+ try {
3482
+ return canonicalizePortableUri(id) === canonicalId;
3483
+ } catch (error) {
3484
+ if (error instanceof TypeError) return false;
3485
+ throw error;
3486
+ }
3487
+ }
3488
+ function portableObjectInternalServerError(request) {
3489
+ return new Response(request.method === "HEAD" ? null : "Internal server error.", {
3490
+ status: 500,
3491
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
3492
+ });
3493
+ }
3494
+ const BUILT_IN_COLLECTION_METRIC_KINDS = /* @__PURE__ */ new Set([
3495
+ "inbox",
3496
+ "outbox",
3497
+ "following",
3498
+ "followers",
3499
+ "liked",
3500
+ "featured",
3501
+ "featured_tags"
3502
+ ]);
3503
+ function getCollectionMetricKind(name) {
3504
+ const normalized = name.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/\s+/g, "_");
3505
+ return BUILT_IN_COLLECTION_METRIC_KINDS.has(normalized) ? normalized : "custom";
3506
+ }
3507
+ function collectionAttributes(base, result, response) {
3508
+ return {
3509
+ ...base,
3510
+ result,
3511
+ ...response == null ? {} : { statusCode: response.status }
3512
+ };
3513
+ }
3514
+ function recordCollectionMetrics(meterProvider, base, result, options = {}) {
3515
+ const attrs = collectionAttributes(base, result, options.response);
3516
+ recordCollectionRequest(meterProvider, attrs);
3517
+ if (options.dispatchDurationMs != null) recordCollectionDispatchDuration(meterProvider, options.dispatchDurationMs, attrs);
3518
+ if (options.itemCount != null) recordCollectionPageItems(meterProvider, options.itemCount, attrs);
3519
+ if (options.totalItems != null) recordCollectionTotalItems(meterProvider, options.totalItems, attrs);
3520
+ }
3521
+ /**
3522
+ * Handles a collection request.
3523
+ * @template TItem The type of items in the collection.
3524
+ * @template TContext The type of the context, extending {@link RequestContext}.
3525
+ * @template TContextData The context data to pass to the `TContext`.
3526
+ * @template TFilter The type of the filter.
3527
+ * @param request The HTTP request.
3528
+ * @param parameters The parameters for handling the collection.
3529
+ * @returns A promise that resolves to an HTTP response.
3530
+ */
3531
+ async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
3532
+ const spanName = name$2.trim().replace(/\s+/g, "_");
3533
+ tracerProvider = tracerProvider ?? trace.getTracerProvider();
3534
+ const tracer = tracerProvider.getTracer(name, version);
3535
+ const cursor = new URL(request.url).searchParams.get("cursor");
3536
+ const metricBase = {
2838
3537
  kind: getCollectionMetricKind(name$2),
2839
3538
  page: cursor != null,
2840
3539
  dispatcher: "built_in"
@@ -3945,7 +4644,21 @@ async function handleInboxInternal(request, parameters, span) {
3945
4644
  inbox: portableInbox.recipient.canonicalInboxId
3946
4645
  });
3947
4646
  else try {
3948
- await portableInbox.forward(json, activity.id, getTypeId(activity).href);
4647
+ await portableInbox.forward(json, activity.id, getTypeId(activity).href, listRequestSignatures(request).map((signature) => ({
4648
+ keyId: signature.keyId,
4649
+ coversDelivery: coversDelivery(signature),
4650
+ verify: async () => {
4651
+ const verification = await verifyRequestDetailed(selectRequestSignature(request, signature), {
4652
+ contextLoader: ctx.contextLoader,
4653
+ documentLoader: ctx.documentLoader,
4654
+ timeWindow: signatureTimeWindow,
4655
+ keyCache,
4656
+ meterProvider,
4657
+ tracerProvider
4658
+ });
4659
+ return verification.verified ? verification.key : null;
4660
+ }
4661
+ })));
3949
4662
  } catch (error) {
3950
4663
  logger.error("Failed to forward activity {activityId} to the other gateways of the portable inbox {inbox}:\n{error}", {
3951
4664
  activityId: activity.id.href,
@@ -4449,516 +5162,226 @@ const appendCursorIfExists = (url, cursor) => {
4449
5162
  if (cursor === null || cursor === void 0) return null;
4450
5163
  const copied = new URL(url);
4451
5164
  copied.searchParams.set("cursor", cursor);
4452
- return copied;
4453
- };
4454
- /**
4455
- * Creates an HTTP response for ActivityPub data.
4456
- * @param {unknown} data The data to serialize as JSON-LD.
4457
- * @returns {Response} An HTTP response with the data as ActivityPub JSON.
4458
- * @since 1.8.0
4459
- */
4460
- const respondAsActivity = (data) => new Response(JSON.stringify(data), { headers: {
4461
- "Content-Type": "application/activity+json",
4462
- Vary: "Accept"
4463
- } });
4464
- /**
4465
- * Base class for handler errors.
4466
- * @since 1.8.0
4467
- */
4468
- var HandlerError = class extends Error {
4469
- constructor(message) {
4470
- super(message);
4471
- }
4472
- /**
4473
- * Throws this error.
4474
- * @returns Never returns, always throws.
4475
- */
4476
- throw() {
4477
- throw this;
4478
- }
4479
- };
4480
- /**
4481
- * Error thrown when items are not found in a collection.
4482
- * @since 1.8.0
4483
- */
4484
- var ItemsNotFoundError = class extends HandlerError {
4485
- constructor() {
4486
- super("Items not found in the collection.");
4487
- }
4488
- };
4489
- /**
4490
- * Error thrown when access to a collection is unauthorized.
4491
- * @since 1.8.0
4492
- */
4493
- var UnauthorizedError = class extends HandlerError {
4494
- constructor() {
4495
- super("Unauthorized access to the collection.");
4496
- }
4497
- };
4498
- /**
4499
- * Responds with the given object in JSON-LD format.
4500
- *
4501
- * @param object The object to respond with.
4502
- * @param options Options.
4503
- * @since 0.3.0
4504
- */
4505
- async function respondWithObject(object, options) {
4506
- const jsonLd = await object.toJsonLd(options);
4507
- return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
4508
- }
4509
- /**
4510
- * Responds with the given object in JSON-LD format if the request accepts
4511
- * JSON-LD.
4512
- *
4513
- * @param object The object to respond with.
4514
- * @param request The request to check for JSON-LD acceptability.
4515
- * @param options Options.
4516
- * @since 0.3.0
4517
- */
4518
- async function respondWithObjectIfAcceptable(object, request, options) {
4519
- if (!acceptsJsonLd(request)) return null;
4520
- const response = await respondWithObject(object, options);
4521
- response.headers.set("Vary", "Accept");
4522
- return response;
4523
- }
4524
- function generateNonce() {
4525
- const bytes = /* @__PURE__ */ new Uint8Array(16);
4526
- crypto.getRandomValues(bytes);
4527
- return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4528
- }
4529
- async function verifySignatureNonce(request, kv, noncePrefix, verifiedLabel) {
4530
- const signatureInput = request.headers.get("Signature-Input");
4531
- if (signatureInput == null) return false;
4532
- const parsed = parseRfc9421SignatureInput(signatureInput);
4533
- if (verifiedLabel == null) return false;
4534
- const sig = parsed[verifiedLabel];
4535
- if (sig == null) return false;
4536
- const nonce = sig.nonce;
4537
- if (nonce == null) return false;
4538
- const key = [...noncePrefix, nonce];
4539
- if (kv.cas != null) return await kv.cas(key, true, void 0);
4540
- if (await kv.get(key) != null) {
4541
- await kv.delete(key);
4542
- return true;
4543
- }
4544
- return false;
4545
- }
4546
- const getFailedSignatureResponse = async (policy, kv, kvPrefixes) => {
4547
- const headers = await getFailedSignatureHeaders(policy, kv, kvPrefixes);
4548
- return new Response("Failed to verify the request signature.", {
4549
- status: 401,
4550
- headers
4551
- });
4552
- };
4553
- const getFailedSignatureHeaders = async (policy, kv, kvPrefixes) => ({
4554
- "Content-Type": "text/plain; charset=utf-8",
4555
- ...policy?.enabled && {
4556
- "Accept-Signature": await buildAcceptSignatureHeader(policy, kv, kvPrefixes.acceptSignatureNonce),
4557
- "Cache-Control": "no-store",
4558
- "Vary": "Accept, Signature"
4559
- }
4560
- });
4561
- async function buildAcceptSignatureHeader(policy, kv, noncePrefix) {
4562
- const parameters = { created: true };
4563
- if (policy.requestNonce) {
4564
- const nonce = generateNonce();
4565
- await setKey(kv, [...noncePrefix, nonce], policy);
4566
- parameters.nonce = nonce;
4567
- }
4568
- const baseComponents = policy.components ?? DEF_COMPONENTS;
4569
- return formatAcceptSignature([{
4570
- label: "sig1",
4571
- components: uniq(MIN_COMPONENTS.concat(baseComponents)).filter((c) => c !== "@status").map((v) => ({
4572
- value: v,
4573
- params: {}
4574
- })),
4575
- parameters
4576
- }]);
4577
- }
4578
- async function setKey(kv, key, policy) {
4579
- const seconds = policy.nonceTtlSeconds ?? 300;
4580
- const ttl = Temporal.Duration.from({ seconds });
4581
- await kv.set(key, true, { ttl });
4582
- }
4583
- const DEF_COMPONENTS = [
4584
- "@method",
4585
- "@target-uri",
4586
- "@authority",
4587
- "content-digest"
4588
- ];
4589
- const MIN_COMPONENTS = [
4590
- "@method",
4591
- "@target-uri",
4592
- "@authority"
4593
- ];
4594
- /**
4595
- * Checks whether an HTTP Signature key is a gateway key of an FEP-ef61
4596
- * portable actor, i.e., its ID is a compatible identifier and it is owned by
4597
- * a portable actor, which only the portable actor's signed document can
4598
- * establish.
4599
- */
4600
- function isPortableGatewayKey(key) {
4601
- return key?.id != null && isCompatibleKeyId(key.id) && key.ownerId != null && isPortableId(key.ownerId);
4602
- }
5165
+ return copied;
5166
+ };
4603
5167
  /**
4604
- * Checks whether an activity needs an Object Integrity Proof by its DID:
4605
- * either it is performed by an [FEP-ef61] portable actor, or its own ID is
4606
- * portable. Both `ap:` URIs and compatible identifiers count as portable.
4607
- *
4608
- * [FEP-ef61]: https://w3id.org/fep/ef61
5168
+ * Creates an HTTP response for ActivityPub data.
5169
+ * @param {unknown} data The data to serialize as JSON-LD.
5170
+ * @returns {Response} An HTTP response with the data as ActivityPub JSON.
5171
+ * @since 1.8.0
4609
5172
  */
4610
- function isPortableActivity(activity) {
4611
- return hasPortableActor(activity) || activity.id != null && isPortableId(activity.id);
4612
- }
5173
+ const respondAsActivity = (data) => new Response(JSON.stringify(data), { headers: {
5174
+ "Content-Type": "application/activity+json",
5175
+ Vary: "Accept"
5176
+ } });
4613
5177
  /**
4614
- * Verifies that a portable activity's own ID belongs to the DID that signed
4615
- * it, on the JSON-LD document received. The ID the proof policy checks has
4616
- * to be the parsed activity's ID, so that a remote context that changes
4617
- * between loads cannot make the two name different objects.
4618
- * @returns `null` if the ID is verified, or the reason why it is not.
5178
+ * Base class for handler errors.
5179
+ * @since 1.8.0
4619
5180
  */
4620
- async function verifyPortableActivityId(activityId, jsonLd, options) {
4621
- const expectedId = getCanonicalPortableId(activityId);
4622
- if (expectedId == null) return "malformed portable ID";
4623
- let verification;
4624
- try {
4625
- verification = await verifyPortableObjectProofWithRoot(jsonLd, options);
4626
- } catch (error) {
4627
- if (error instanceof InvalidPortableObjectIdError) return "malformed portable ID";
4628
- if (!isPermanentActivityParseError(error)) throw error;
4629
- return "malformed document";
5181
+ var HandlerError = class extends Error {
5182
+ constructor(message) {
5183
+ super(message);
4630
5184
  }
4631
- const { result, root } = verification;
4632
- if (!result.verified) return result.reason.type;
4633
- const rootId = root?.["@id"];
4634
- if (typeof rootId !== "string" || getCanonicalPortableId(parseIri(rootId)) !== expectedId) return "the verified document has another ID";
4635
- return null;
4636
- }
4637
- //#endregion
4638
- //#region src/nodeinfo/handler.ts
5185
+ /**
5186
+ * Throws this error.
5187
+ * @returns Never returns, always throws.
5188
+ */
5189
+ throw() {
5190
+ throw this;
5191
+ }
5192
+ };
4639
5193
  /**
4640
- * Handles a NodeInfo request. You would not typically call this function
4641
- * directly, but instead use {@link Federation.handle} method.
4642
- * @param request The NodeInfo request to handle.
4643
- * @param parameters The parameters for handling the request.
4644
- * @returns The response to the request.
5194
+ * Error thrown when items are not found in a collection.
5195
+ * @since 1.8.0
4645
5196
  */
4646
- async function handleNodeInfo(_request, { context, nodeInfoDispatcher }) {
4647
- const promise = nodeInfoDispatcher(context);
4648
- const json = nodeInfoToJson(promise instanceof Promise ? await promise : promise);
4649
- return new Response(JSON.stringify(json), { headers: { "Content-Type": "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\"" } });
4650
- }
5197
+ var ItemsNotFoundError = class extends HandlerError {
5198
+ constructor() {
5199
+ super("Items not found in the collection.");
5200
+ }
5201
+ };
4651
5202
  /**
4652
- * Handles a request to `/.well-known/nodeinfo`. You would not typically call
4653
- * this function directly, but instead use {@link Federation.handle} method.
4654
- * @param request The request to handle.
4655
- * @param context The request context.
4656
- * @returns The response to the request.
5203
+ * Error thrown when access to a collection is unauthorized.
5204
+ * @since 1.8.0
4657
5205
  */
4658
- function handleNodeInfoJrd(_request, context) {
4659
- const links = [];
4660
- try {
4661
- links.push({
4662
- rel: "http://nodeinfo.diaspora.software/ns/schema/2.1",
4663
- href: context.getNodeInfoUri().href,
4664
- type: "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\""
4665
- });
4666
- } catch (e) {
4667
- if (!(e instanceof RouterError)) throw e;
5206
+ var UnauthorizedError = class extends HandlerError {
5207
+ constructor() {
5208
+ super("Unauthorized access to the collection.");
4668
5209
  }
4669
- const response = new Response(JSON.stringify({ links }), { headers: { "Content-Type": "application/jrd+json" } });
4670
- return Promise.resolve(response);
4671
- }
4672
- //#endregion
4673
- //#region src/federation/send.ts
5210
+ };
4674
5211
  /**
4675
- * Extracts the inbox URLs from recipients.
4676
- * @param parameters The parameters to extract the inboxes.
4677
- * See also {@link ExtractInboxesParameters}.
4678
- * @returns The inboxes as a map of inbox URL to actor URIs.
5212
+ * Responds with the given object in JSON-LD format.
5213
+ *
5214
+ * @param object The object to respond with.
5215
+ * @param options Options.
5216
+ * @since 0.3.0
4679
5217
  */
4680
- function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
4681
- const inboxes = {};
4682
- for (const recipient of recipients) {
4683
- let inbox;
4684
- let sharedInbox = false;
4685
- if (preferSharedInbox && recipient.endpoints?.sharedInbox != null) {
4686
- inbox = recipient.endpoints.sharedInbox;
4687
- sharedInbox = true;
4688
- } else inbox = recipient.inboxId;
4689
- if (inbox != null && recipient.id != null) {
4690
- if (excludeBaseUris != null && excludeBaseUris.some((u) => u.origin === inbox?.origin)) continue;
4691
- inboxes[inbox.href] ??= {
4692
- actorIds: /* @__PURE__ */ new Set(),
4693
- sharedInbox
4694
- };
4695
- inboxes[inbox.href].actorIds.add(recipient.id.href);
4696
- }
4697
- }
4698
- return inboxes;
5218
+ async function respondWithObject(object, options) {
5219
+ const jsonLd = await object.toJsonLd(options);
5220
+ return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
4699
5221
  }
4700
5222
  /**
4701
- * Sends an {@link Activity} to an inbox.
5223
+ * Responds with the given object in JSON-LD format if the request accepts
5224
+ * JSON-LD.
4702
5225
  *
4703
- * @param parameters The parameters for sending the activity.
4704
- * See also {@link SendActivityParameters}.
4705
- * @throws {Error} If the activity fails to send.
5226
+ * @param object The object to respond with.
5227
+ * @param request The request to check for JSON-LD acceptability.
5228
+ * @param options Options.
5229
+ * @since 0.3.0
4706
5230
  */
4707
- function sendActivity(options) {
4708
- const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
4709
- return tracerProvider.getTracer(name, version).startActiveSpan("activitypub.send_activity", {
4710
- kind: SpanKind.CLIENT,
4711
- attributes: { "activitypub.shared_inbox": options.sharedInbox ?? false }
4712
- }, async (span) => {
4713
- if (options.activityId != null) span.setAttribute("activitypub.activity.id", options.activityId);
4714
- if (options.activityType != null) span.setAttribute("activitypub.activity.type", options.activityType);
4715
- try {
4716
- await sendActivityInternal({
4717
- ...options,
4718
- tracerProvider
4719
- }, span);
4720
- } catch (e) {
4721
- span.setStatus({
4722
- code: SpanStatusCode.ERROR,
4723
- message: String(e)
4724
- });
4725
- throw e;
4726
- } finally {
4727
- span.end();
4728
- }
4729
- });
4730
- }
4731
- const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
4732
- function getActivityActorId(activity) {
4733
- if (!isRecord(activity)) return void 0;
4734
- return getIdValue(activity.actor);
4735
- }
4736
- function getIdValue(value) {
4737
- if (typeof value === "string" && value !== "") return value;
4738
- if (value instanceof URL) return value.href;
4739
- if (Array.isArray(value)) {
4740
- for (const item of value) {
4741
- const id = getIdValue(item);
4742
- if (id != null) return id;
4743
- }
4744
- return;
4745
- }
4746
- if (isRecord(value)) return getIdValue(value.id);
4747
- }
4748
- function isRecord(value) {
4749
- return typeof value === "object" && value != null;
5231
+ async function respondWithObjectIfAcceptable(object, request, options) {
5232
+ if (!acceptsJsonLd(request)) return null;
5233
+ const response = await respondWithObject(object, options);
5234
+ response.headers.set("Vary", "Accept");
5235
+ return response;
4750
5236
  }
4751
- async function readLimitedResponseBody(response, maxBytes) {
4752
- if (response.body == null) return "";
4753
- const reader = response.body.getReader();
4754
- const decoder = new TextDecoder();
4755
- const chunks = [];
4756
- let totalBytes = 0;
4757
- let truncated = false;
4758
- try {
4759
- while (true) {
4760
- const { done, value } = await reader.read();
4761
- if (done) break;
4762
- if (totalBytes + value.length > maxBytes) {
4763
- const remaining = maxBytes - totalBytes;
4764
- if (remaining > 0) chunks.push(decoder.decode(value.slice(0, remaining), { stream: true }));
4765
- truncated = true;
4766
- break;
4767
- }
4768
- chunks.push(decoder.decode(value, { stream: true }));
4769
- totalBytes += value.length;
4770
- }
4771
- } finally {
4772
- reader.releaseLock();
4773
- }
4774
- let result = chunks.join("");
4775
- if (truncated) result += "… (truncated)";
4776
- return result;
5237
+ function generateNonce() {
5238
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
5239
+ crypto.getRandomValues(bytes);
5240
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4777
5241
  }
4778
- async function sendActivityInternal({ activity, activityId, activityType, keys, inbox, allowPrivateAddress, headers, specDeterminer, meterProvider, tracerProvider }, span) {
4779
- const logger = getLogger([
4780
- "fedify",
4781
- "federation",
4782
- "outbox"
4783
- ]);
4784
- const federationMetrics = getFederationMetrics(meterProvider);
4785
- const started = performance.now();
4786
- let deliverySuccess = false;
4787
- async function validateUrl(url) {
4788
- if (!allowPrivateAddress) try {
4789
- await validatePublicUrl(url);
4790
- } catch (error) {
4791
- if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
4792
- url,
4793
- error
4794
- });
4795
- throw error;
4796
- }
4797
- }
4798
- await validateUrl(inbox.href);
4799
- headers = new Headers(headers);
4800
- headers.set("Content-Type", "application/activity+json");
4801
- const request = new Request(inbox, {
4802
- method: "POST",
4803
- headers,
4804
- body: JSON.stringify(activity),
4805
- redirect: "manual"
4806
- });
4807
- let rsaKey = null;
4808
- for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
4809
- rsaKey = key;
4810
- break;
5242
+ async function verifySignatureNonce(request, kv, noncePrefix, verifiedLabel) {
5243
+ const signatureInput = request.headers.get("Signature-Input");
5244
+ if (signatureInput == null) return false;
5245
+ const parsed = parseRfc9421SignatureInput(signatureInput);
5246
+ if (verifiedLabel == null) return false;
5247
+ const sig = parsed[verifiedLabel];
5248
+ if (sig == null) return false;
5249
+ const nonce = sig.nonce;
5250
+ if (nonce == null) return false;
5251
+ const key = [...noncePrefix, nonce];
5252
+ if (kv.cas != null) return await kv.cas(key, true, void 0);
5253
+ if (await kv.get(key) != null) {
5254
+ await kv.delete(key);
5255
+ return true;
4811
5256
  }
4812
- if (rsaKey == null && keys.length < 1) logger.debug("Sending the activity {activityId} to {inbox} without a signature.", {
4813
- activityId,
4814
- inbox: inbox.href
4815
- });
4816
- else if (rsaKey == null) logger.warn("No supported key found to sign the request to {inbox}. The request will be sent without a signature. In order to sign the request, at least one RSASSA-PKCS1-v1_5 key must be provided.", {
4817
- inbox: inbox.href,
4818
- keys: keys.map((pair) => ({
4819
- keyId: pair.keyId.href,
4820
- privateKey: pair.privateKey
4821
- }))
5257
+ return false;
5258
+ }
5259
+ const getFailedSignatureResponse = async (policy, kv, kvPrefixes) => {
5260
+ const headers = await getFailedSignatureHeaders(policy, kv, kvPrefixes);
5261
+ return new Response("Failed to verify the request signature.", {
5262
+ status: 401,
5263
+ headers
4822
5264
  });
4823
- let response;
4824
- try {
4825
- response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
4826
- tracerProvider,
4827
- specDeterminer,
4828
- validateRedirect: validateUrl
4829
- });
4830
- } catch (error) {
4831
- const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
4832
- logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
4833
- activityId,
4834
- inbox: inbox.href,
4835
- error: failure
4836
- });
4837
- federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
4838
- throw failure;
5265
+ };
5266
+ const getFailedSignatureHeaders = async (policy, kv, kvPrefixes) => ({
5267
+ "Content-Type": "text/plain; charset=utf-8",
5268
+ ...policy?.enabled && {
5269
+ "Accept-Signature": await buildAcceptSignatureHeader(policy, kv, kvPrefixes.acceptSignatureNonce),
5270
+ "Cache-Control": "no-store",
5271
+ "Vary": "Accept, Signature"
4839
5272
  }
4840
- try {
4841
- if (!response.ok) {
4842
- let error;
4843
- try {
4844
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
4845
- } catch (_) {
4846
- error = "";
4847
- }
4848
- logger.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
4849
- activityId,
4850
- inbox: inbox.href,
4851
- status: response.status,
4852
- statusText: response.statusText,
4853
- error
4854
- });
4855
- throw new SendActivityError(inbox, response.status, `Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`, error, response.headers);
4856
- }
4857
- deliverySuccess = true;
4858
- const eventAttributes = {
4859
- "activitypub.inbox.url": inbox.href,
4860
- "activitypub.activity.id": activityId ?? ""
4861
- };
4862
- if (activityType != null) eventAttributes["activitypub.activity.type"] = activityType;
4863
- const actorId = getActivityActorId(activity);
4864
- if (actorId != null) eventAttributes["activitypub.actor.id"] = actorId;
4865
- span.addEvent("activitypub.activity.sent", eventAttributes);
4866
- } finally {
4867
- federationMetrics.recordDelivery(inbox, getDurationMs(started), deliverySuccess, activityType);
5273
+ });
5274
+ async function buildAcceptSignatureHeader(policy, kv, noncePrefix) {
5275
+ const parameters = { created: true };
5276
+ if (policy.requestNonce) {
5277
+ const nonce = generateNonce();
5278
+ await setKey(kv, [...noncePrefix, nonce], policy);
5279
+ parameters.nonce = nonce;
4868
5280
  }
5281
+ const baseComponents = policy.components ?? DEF_COMPONENTS;
5282
+ return formatAcceptSignature([{
5283
+ label: "sig1",
5284
+ components: uniq(MIN_COMPONENTS.concat(baseComponents)).filter((c) => c !== "@status").map((v) => ({
5285
+ value: v,
5286
+ params: {}
5287
+ })),
5288
+ parameters
5289
+ }]);
4869
5290
  }
4870
- function createFetchError(url, cause) {
4871
- const error = new FetchError(url, cause instanceof Error ? cause.message : String(cause));
4872
- error.cause = cause;
4873
- return error;
5291
+ async function setKey(kv, key, policy) {
5292
+ const seconds = policy.nonceTtlSeconds ?? 300;
5293
+ const ttl = Temporal.Duration.from({ seconds });
5294
+ await kv.set(key, true, { ttl });
4874
5295
  }
4875
- async function fetchWithValidatedRedirects(request, validateUrl) {
4876
- let body = await request.clone().text();
4877
- for (let redirects = 0;; redirects++) {
4878
- const response = await fetch(request, { redirect: "manual" });
4879
- const location = response.headers.get("Location");
4880
- if (![
4881
- 301,
4882
- 302,
4883
- 303,
4884
- 307,
4885
- 308
4886
- ].includes(response.status) || location == null) return response;
4887
- await response.body?.cancel();
4888
- if (redirects >= 20) throw new TypeError("Too many redirects");
4889
- const url = new URL(location, request.url);
4890
- await validateUrl(url.href);
4891
- const headers = new Headers(request.headers);
4892
- if (url.origin !== new URL(request.url).origin) {
4893
- headers.delete("Authorization");
4894
- headers.delete("Proxy-Authorization");
4895
- headers.delete("Cookie");
4896
- headers.delete("Host");
4897
- }
4898
- let method = request.method;
4899
- if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
4900
- method = "GET";
4901
- body = void 0;
4902
- for (const name of [
4903
- "Content-Encoding",
4904
- "Content-Language",
4905
- "Content-Length",
4906
- "Content-Location",
4907
- "Content-Type"
4908
- ]) headers.delete(name);
4909
- }
4910
- request = new Request(url, {
4911
- method,
4912
- headers,
4913
- body,
4914
- redirect: "manual"
4915
- });
5296
+ const DEF_COMPONENTS = [
5297
+ "@method",
5298
+ "@target-uri",
5299
+ "@authority",
5300
+ "content-digest"
5301
+ ];
5302
+ const MIN_COMPONENTS = [
5303
+ "@method",
5304
+ "@target-uri",
5305
+ "@authority"
5306
+ ];
5307
+ /**
5308
+ * Checks whether an HTTP Signature key is a gateway key of an FEP-ef61
5309
+ * portable actor, i.e., its ID is a compatible identifier and it is owned by
5310
+ * a portable actor, which only the portable actor's signed document can
5311
+ * establish.
5312
+ */
5313
+ function isPortableGatewayKey(key) {
5314
+ return key?.id != null && isCompatibleKeyId(key.id) && key.ownerId != null && isPortableId(key.ownerId);
5315
+ }
5316
+ /**
5317
+ * Checks whether an activity needs an Object Integrity Proof by its DID:
5318
+ * either it is performed by an [FEP-ef61] portable actor, or its own ID is
5319
+ * portable. Both `ap:` URIs and compatible identifiers count as portable.
5320
+ *
5321
+ * [FEP-ef61]: https://w3id.org/fep/ef61
5322
+ */
5323
+ function isPortableActivity(activity) {
5324
+ return hasPortableActor(activity) || activity.id != null && isPortableId(activity.id);
5325
+ }
5326
+ /**
5327
+ * Verifies that a portable activity's own ID belongs to the DID that signed
5328
+ * it, on the JSON-LD document received. The ID the proof policy checks has
5329
+ * to be the parsed activity's ID, so that a remote context that changes
5330
+ * between loads cannot make the two name different objects.
5331
+ * @returns `null` if the ID is verified, or the reason why it is not.
5332
+ */
5333
+ async function verifyPortableActivityId(activityId, jsonLd, options) {
5334
+ const expectedId = getCanonicalPortableId(activityId);
5335
+ if (expectedId == null) return "malformed portable ID";
5336
+ let verification;
5337
+ try {
5338
+ verification = await verifyPortableObjectProofWithRoot(jsonLd, options);
5339
+ } catch (error) {
5340
+ if (error instanceof InvalidPortableObjectIdError) return "malformed portable ID";
5341
+ if (!isPermanentActivityParseError(error)) throw error;
5342
+ return "malformed document";
4916
5343
  }
5344
+ const { result, root } = verification;
5345
+ if (!result.verified) return result.reason.type;
5346
+ const rootId = root?.["@id"];
5347
+ if (typeof rootId !== "string" || getCanonicalPortableId(parseIri(rootId)) !== expectedId) return "the verified document has another ID";
5348
+ return null;
4917
5349
  }
5350
+ //#endregion
5351
+ //#region src/nodeinfo/handler.ts
4918
5352
  /**
4919
- * An error that is thrown when an activity fails to send to a remote inbox.
4920
- * It contains structured information about the failure, including the HTTP
4921
- * status code, the inbox URL, and the response body.
4922
- * @since 2.0.0
5353
+ * Handles a NodeInfo request. You would not typically call this function
5354
+ * directly, but instead use {@link Federation.handle} method.
5355
+ * @param request The NodeInfo request to handle.
5356
+ * @param parameters The parameters for handling the request.
5357
+ * @returns The response to the request.
4923
5358
  */
4924
- var SendActivityError = class extends Error {
4925
- /**
4926
- * The inbox URL that the activity was being sent to.
4927
- */
4928
- inbox;
4929
- /**
4930
- * The HTTP status code returned by the inbox.
4931
- */
4932
- statusCode;
4933
- /**
4934
- * The response body from the inbox, if any. Note that this may be
4935
- * truncated to a maximum of 1 KiB to prevent excessive memory consumption
4936
- * when remote servers return large error pages (e.g., Cloudflare error pages).
4937
- * If truncated, the string will end with `"… (truncated)"`.
4938
- */
4939
- responseBody;
4940
- /**
4941
- * The response headers from the inbox.
4942
- * @since 2.3.0
4943
- */
4944
- responseHeaders;
4945
- /**
4946
- * Creates a new {@link SendActivityError}.
4947
- * @param inbox The inbox URL.
4948
- * @param statusCode The HTTP status code.
4949
- * @param message The error message.
4950
- * @param responseBody The response body.
4951
- * @param responseHeaders The response headers.
4952
- */
4953
- constructor(inbox, statusCode, message, responseBody, responseHeaders) {
4954
- super(message);
4955
- this.name = "SendActivityError";
4956
- this.inbox = inbox;
4957
- this.statusCode = statusCode;
4958
- this.responseBody = responseBody;
4959
- this.responseHeaders = new Headers(responseHeaders);
5359
+ async function handleNodeInfo(_request, { context, nodeInfoDispatcher }) {
5360
+ const promise = nodeInfoDispatcher(context);
5361
+ const json = nodeInfoToJson(promise instanceof Promise ? await promise : promise);
5362
+ return new Response(JSON.stringify(json), { headers: { "Content-Type": "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\"" } });
5363
+ }
5364
+ /**
5365
+ * Handles a request to `/.well-known/nodeinfo`. You would not typically call
5366
+ * this function directly, but instead use {@link Federation.handle} method.
5367
+ * @param request The request to handle.
5368
+ * @param context The request context.
5369
+ * @returns The response to the request.
5370
+ */
5371
+ function handleNodeInfoJrd(_request, context) {
5372
+ const links = [];
5373
+ try {
5374
+ links.push({
5375
+ rel: "http://nodeinfo.diaspora.software/ns/schema/2.1",
5376
+ href: context.getNodeInfoUri().href,
5377
+ type: "application/json; profile=\"http://nodeinfo.diaspora.software/ns/schema/2.1#\""
5378
+ });
5379
+ } catch (e) {
5380
+ if (!(e instanceof RouterError)) throw e;
4960
5381
  }
4961
- };
5382
+ const response = new Response(JSON.stringify({ links }), { headers: { "Content-Type": "application/jrd+json" } });
5383
+ return Promise.resolve(response);
5384
+ }
4962
5385
  //#endregion
4963
5386
  //#region src/federation/bench.ts
4964
5387
  /**
@@ -5031,430 +5454,128 @@ async function handleBenchmarkTrigger(request, context, options = {}) {
5031
5454
  if (request.method !== "POST") return new Response("Method not allowed", {
5032
5455
  status: 405,
5033
5456
  headers: { "Allow": "POST" }
5034
- });
5035
- let json;
5036
- try {
5037
- json = await request.json();
5038
- } catch {
5039
- return jsonResponse({ error: "Invalid JSON request body." }, 400);
5040
- }
5041
- try {
5042
- const body = asRecord(json, "request body");
5043
- const sender = parseSender(body.sender);
5044
- const recipients = await parseRecipients(body.recipients, context);
5045
- const activity = await parseActivity(body.activity, context);
5046
- if (activity.id == null) throw new BenchmarkTriggerError("activity must have an id.");
5047
- const activityId = activity.id.href;
5048
- const inboxes = extractInboxes({ recipients });
5049
- const inboxUrls = Object.keys(inboxes);
5050
- if (inboxUrls.length < 1) throw new BenchmarkTriggerError("No valid recipient inboxes found. The recipients list must not be empty.");
5051
- const unsafeInboxes = options.allowUnsafeRecipients ? [] : inboxUrls.filter((inbox) => !options.sinks?.has(inbox));
5052
- if (unsafeInboxes.length > 0) return jsonResponse({
5053
- error: "unsafe_recipient",
5054
- unsafeInboxes
5055
- }, 403);
5056
- await context.sendActivity(sender, recipients, activity);
5057
- return jsonResponse({
5058
- version: 1,
5059
- activityId,
5060
- queueCorrelationId: activityId,
5061
- recipientCount: recipients.length,
5062
- inboxCount: inboxUrls.length
5063
- }, 202);
5064
- } catch (error) {
5065
- if (error instanceof BenchmarkTriggerError) return jsonResponse({ error: error.message }, error.status);
5066
- throw error;
5067
- }
5068
- }
5069
- var BenchmarkTriggerError = class extends Error {
5070
- status;
5071
- constructor(message, status = 400) {
5072
- super(message);
5073
- this.status = status;
5074
- }
5075
- };
5076
- function parseSender(value) {
5077
- const sender = asRecord(value, "sender");
5078
- if (typeof sender.identifier === "string") return { identifier: sender.identifier };
5079
- if (typeof sender.username === "string") return { username: sender.username };
5080
- throw new BenchmarkTriggerError("sender must be { identifier } or { username }.");
5081
- }
5082
- async function parseRecipients(value, context) {
5083
- if (!Array.isArray(value)) throw new BenchmarkTriggerError("recipients must be an array.");
5084
- return await Promise.all(value.map(async (item) => {
5085
- let object;
5086
- try {
5087
- object = await Object$1.fromJsonLd(item, {
5088
- documentLoader: context.documentLoader,
5089
- contextLoader: context.contextLoader
5090
- });
5091
- } catch (error) {
5092
- throw new BenchmarkTriggerError(`Invalid ActivityPub recipient: ${error}`);
5093
- }
5094
- if (!isRecipient(object)) throw new BenchmarkTriggerError("each recipient must be an ActivityPub actor.");
5095
- const recipient = object;
5096
- if (recipient.id == null || recipient.inboxId == null) throw new BenchmarkTriggerError("each recipient must have id and inbox properties.");
5097
- return recipient;
5098
- }));
5099
- }
5100
- function isRecipient(value) {
5101
- return value != null && typeof value === "object" && "id" in value && "inboxId" in value;
5102
- }
5103
- async function parseActivity(value, context) {
5104
- try {
5105
- return await Activity.fromJsonLd(value, {
5106
- documentLoader: context.documentLoader,
5107
- contextLoader: context.contextLoader
5108
- });
5109
- } catch (error) {
5110
- throw new BenchmarkTriggerError(`Invalid ActivityPub activity: ${error}`);
5111
- }
5112
- }
5113
- function asRecord(value, name) {
5114
- if (value == null || typeof value !== "object" || Array.isArray(value)) throw new BenchmarkTriggerError(`${name} must be an object.`);
5115
- return value;
5116
- }
5117
- function jsonResponse(body, status = 200) {
5118
- return new Response(JSON.stringify(body), {
5119
- status,
5120
- headers: { "Content-Type": "application/json" }
5121
- });
5122
- }
5123
- function serializeScopeMetrics(resourceMetrics) {
5124
- return resourceMetrics.scopeMetrics.map(serializeScope);
5125
- }
5126
- function serializeScope(scopeMetrics) {
5127
- return {
5128
- scope: {
5129
- name: scopeMetrics.scope.name,
5130
- version: scopeMetrics.scope.version
5131
- },
5132
- metrics: scopeMetrics.metrics.map(serializeMetric)
5133
- };
5134
- }
5135
- function serializeMetric(metric) {
5136
- return {
5137
- name: metric.descriptor.name,
5138
- description: metric.descriptor.description,
5139
- unit: metric.descriptor.unit,
5140
- dataPointType: serializeDataPointType(metric.dataPointType),
5141
- dataPoints: metric.dataPoints.map((point) => ({
5142
- attributes: { ...point.attributes },
5143
- startTime: point.startTime,
5144
- endTime: point.endTime,
5145
- value: point.value
5146
- }))
5147
- };
5148
- }
5149
- function serializeDataPointType(dataPointType) {
5150
- switch (dataPointType) {
5151
- case DataPointType.HISTOGRAM: return "histogram";
5152
- case DataPointType.EXPONENTIAL_HISTOGRAM: return "exponential_histogram";
5153
- case DataPointType.GAUGE: return "gauge";
5154
- case DataPointType.SUM: return "sum";
5155
- }
5156
- }
5157
- //#endregion
5158
- //#region src/federation/portable-inbox.ts
5159
- const MAX_TIMEOUT_MS = 2 ** 31 - 1;
5160
- /**
5161
- * Fills in the defaults of {@link PortableInboxForwardingOptions} and
5162
- * validates them.
5163
- * @param options The options.
5164
- * @returns The resolved options.
5165
- * @throws {RangeError} If `maxTargets` is not a non-negative integer, if `ttl`
5166
- * is not positive, if `deadline` is negative or longer
5167
- * than 2,147,483,647 milliseconds (about 24.8 days), or
5168
- * if either duration has calendar units, i.e., weeks,
5169
- * months, or years, whose length depends on the date.
5170
- */
5171
- function resolvePortableInboxForwardingOptions(options = {}) {
5172
- const maxTargets = options.maxTargets ?? 10;
5173
- if (!Number.isInteger(maxTargets) || maxTargets < 0) throw new RangeError("portableInboxForwarding.maxTargets must be a non-negative integer.");
5174
- const ttl = Temporal.Duration.from(options.ttl ?? { days: 30 });
5175
- if (ttl.total("millisecond") <= 0) throw new RangeError("portableInboxForwarding.ttl must be positive.");
5176
- const deadline = Temporal.Duration.from(options.deadline ?? { seconds: 10 });
5177
- const deadlineMs = deadline.total("millisecond");
5178
- if (deadlineMs < 0 || deadlineMs > MAX_TIMEOUT_MS) throw new RangeError(`portableInboxForwarding.deadline must be between 0 and ${MAX_TIMEOUT_MS} milliseconds.`);
5179
- return {
5180
- maxTargets,
5181
- ttl,
5182
- deadline
5183
- };
5184
- }
5185
- /**
5186
- * Decides whether this server accepts a delivery to a portable inbox on behalf
5187
- * of the given actor, which the actor dispatcher returned for the identifier
5188
- * in the requested inbox path.
5189
- *
5190
- * The actor document comes from the application, so it is trusted as is and
5191
- * its proof is not verified here.
5192
- * @param actor The actor the actor dispatcher returned.
5193
- * @param options The requested DID, the canonical form of the requested inbox
5194
- * ID, and the origin of this server.
5195
- * @returns The resolution.
5196
- */
5197
- function resolvePortableInboxRecipient(actor, { authority, canonicalInboxId, localOrigin }) {
5198
- if (actor == null) return {
5199
- status: "rejected",
5200
- reason: "notFound"
5201
- };
5202
- const id = actor.id;
5203
- const did = id == null || !isPortableId(id) ? null : getPortableDid(id);
5204
- if (id == null || did == null) return {
5205
- status: "rejected",
5206
- reason: "notPortable"
5207
- };
5208
- if (did !== authority) return {
5209
- status: "rejected",
5210
- reason: "authorityMismatch"
5211
- };
5212
- const inboxId = actor.inboxId == null ? null : toPortableUri(actor.inboxId);
5213
- if (inboxId == null || getCanonicalPortableId(inboxId) !== canonicalInboxId) return {
5214
- status: "rejected",
5215
- reason: "inboxMismatch"
5216
- };
5217
- const gateways = actor.gateways;
5218
- if (!gateways.some((g) => isGatewayUrl(g) && g.origin === localOrigin)) return {
5219
- status: "rejected",
5220
- reason: "notGateway"
5221
- };
5222
- return {
5223
- status: "accepted",
5224
- recipient: {
5225
- actorId: id,
5226
- inboxId,
5227
- canonicalInboxId,
5228
- gateways
5229
- }
5230
- };
5231
- }
5232
- /**
5233
- * Gets the portable form of an `ap:` or `ap+ef61:` URI or a compatible
5234
- * identifier, keeping its query.
5235
- * @returns The portable URI, or `null` if the ID is neither, or is malformed.
5236
- */
5237
- function toPortableUri(id) {
5238
- if (isPortableUri(id)) return id;
5239
- try {
5240
- return fromCompatibleEf61Id(id);
5241
- } catch (error) {
5242
- if (error instanceof TypeError) return null;
5243
- throw error;
5244
- }
5245
- }
5246
- /**
5247
- * Forwards an activity received in a portable inbox to the inboxes of the same
5248
- * portable actor on its other gateways, as FEP-ef61 recommends.
5249
- *
5250
- * FEP-ef61 forbids forwarding an activity from an inbox more than once, so
5251
- * each target gateway is claimed with an atomic compare-and-swap before the
5252
- * activity is handed off, and a claim is never released, even if the hand-off
5253
- * fails, since a failed hand-off does not prove that nothing was delivered.
5254
- * Forwarding is therefore best effort. Without {@link KvStore.cas}, nothing is
5255
- * forwarded.
5256
- *
5257
- * Forwarded requests are signed with HTTP Signatures by the RSA key among
5258
- * {@link ForwardPortableInboxActivityParameters.getKeys}, if any, so that
5259
- * servers requiring HTTP Signatures accept them, and are sent unsigned
5260
- * otherwise. Either way, the receiving gateways authenticate the activity by
5261
- * its own proof.
5262
- * @param parameters The parameters.
5263
- * @returns The target inbox URLs that the activity was handed off to.
5264
- */
5265
- async function forwardPortableInboxActivity(parameters) {
5266
- const logger = getLogger([
5267
- "fedify",
5268
- "federation",
5269
- "inbox"
5270
- ]);
5271
- const { recipient, activityId, excludedOrigins, kv, kvPrefix, outboxQueue } = parameters;
5272
- const { maxTargets, ttl } = parameters.options ?? resolvePortableInboxForwardingOptions();
5273
- if (kv.cas == null || maxTargets < 1) return [];
5274
- const canonicalActivityId = getCanonicalPortableId(activityId) ?? activityId.href;
5275
- const targets = getForwardingTargets(recipient, excludedOrigins);
5276
- if (targets.length > maxTargets) {
5277
- logger.warn("The portable actor that owns the inbox {inbox} has more than {max} other gateways; the activity {activityId} is forwarded only to the first {max} of them.", {
5278
- inbox: recipient.canonicalInboxId,
5279
- activityId: activityId.href,
5280
- max: maxTargets
5281
- });
5282
- targets.length = maxTargets;
5457
+ });
5458
+ let json;
5459
+ try {
5460
+ json = await request.json();
5461
+ } catch {
5462
+ return jsonResponse({ error: "Invalid JSON request body." }, 400);
5283
5463
  }
5284
- const claimed = [];
5285
- for (const { gateway, inbox } of targets) {
5286
- const key = [
5287
- ...kvPrefix,
5288
- recipient.canonicalInboxId,
5289
- canonicalActivityId,
5290
- gateway
5291
- ];
5292
- if (await kv.cas(key, void 0, true, { ttl })) claimed.push(inbox);
5464
+ try {
5465
+ const body = asRecord(json, "request body");
5466
+ const sender = parseSender(body.sender);
5467
+ const recipients = await parseRecipients(body.recipients, context);
5468
+ const activity = await parseActivity(body.activity, context);
5469
+ if (activity.id == null) throw new BenchmarkTriggerError("activity must have an id.");
5470
+ const activityId = activity.id.href;
5471
+ const inboxes = extractInboxes({ recipients });
5472
+ const inboxUrls = Object.keys(inboxes);
5473
+ if (inboxUrls.length < 1) throw new BenchmarkTriggerError("No valid recipient inboxes found. The recipients list must not be empty.");
5474
+ const unsafeInboxes = options.allowUnsafeRecipients ? [] : inboxUrls.filter((inbox) => !options.sinks?.has(inbox));
5475
+ if (unsafeInboxes.length > 0) return jsonResponse({
5476
+ error: "unsafe_recipient",
5477
+ unsafeInboxes
5478
+ }, 403);
5479
+ await context.sendActivity(sender, recipients, activity);
5480
+ return jsonResponse({
5481
+ version: 1,
5482
+ activityId,
5483
+ queueCorrelationId: activityId,
5484
+ recipientCount: recipients.length,
5485
+ inboxCount: inboxUrls.length
5486
+ }, 202);
5487
+ } catch (error) {
5488
+ if (error instanceof BenchmarkTriggerError) return jsonResponse({ error: error.message }, error.status);
5489
+ throw error;
5293
5490
  }
5294
- if (claimed.length < 1) return [];
5295
- logger.debug("Forwarding activity {activityId} from the portable inbox {inbox} to other gateways:\n{targets}", {
5296
- activityId: activityId.href,
5297
- inbox: recipient.canonicalInboxId,
5298
- targets: claimed.map((t) => t.href)
5299
- });
5300
- if (outboxQueue == null) await forwardImmediately(parameters, claimed);
5301
- else await enqueueForwarding(parameters, outboxQueue, claimed);
5302
- return claimed;
5303
5491
  }
5304
- function getForwardingTargets(recipient, excludedOrigins) {
5305
- const logger = getLogger([
5306
- "fedify",
5307
- "federation",
5308
- "inbox"
5309
- ]);
5310
- const seen = new Set(excludedOrigins);
5311
- const targets = [];
5312
- for (const gateway of recipient.gateways) {
5313
- if (!isGatewayUrl(gateway) || seen.has(gateway.origin)) continue;
5314
- seen.add(gateway.origin);
5315
- let inbox;
5492
+ var BenchmarkTriggerError = class extends Error {
5493
+ status;
5494
+ constructor(message, status = 400) {
5495
+ super(message);
5496
+ this.status = status;
5497
+ }
5498
+ };
5499
+ function parseSender(value) {
5500
+ const sender = asRecord(value, "sender");
5501
+ if (typeof sender.identifier === "string") return { identifier: sender.identifier };
5502
+ if (typeof sender.username === "string") return { username: sender.username };
5503
+ throw new BenchmarkTriggerError("sender must be { identifier } or { username }.");
5504
+ }
5505
+ async function parseRecipients(value, context) {
5506
+ if (!Array.isArray(value)) throw new BenchmarkTriggerError("recipients must be an array.");
5507
+ return await Promise.all(value.map(async (item) => {
5508
+ let object;
5316
5509
  try {
5317
- inbox = toCompatibleEf61Id(recipient.inboxId, gateway.origin);
5318
- } catch (error) {
5319
- if (!(error instanceof TypeError)) throw error;
5320
- logger.warn("Cannot forward to the gateway {gateway}, as the portable inbox {inbox} cannot be represented as its compatible identifier.", {
5321
- gateway: gateway.origin,
5322
- inbox: recipient.canonicalInboxId
5510
+ object = await Object$1.fromJsonLd(item, {
5511
+ documentLoader: context.documentLoader,
5512
+ contextLoader: context.contextLoader
5323
5513
  });
5324
- continue;
5514
+ } catch (error) {
5515
+ throw new BenchmarkTriggerError(`Invalid ActivityPub recipient: ${error}`);
5325
5516
  }
5326
- targets.push({
5327
- gateway: gateway.origin,
5328
- inbox
5329
- });
5330
- }
5331
- return targets;
5517
+ if (!isRecipient(object)) throw new BenchmarkTriggerError("each recipient must be an ActivityPub actor.");
5518
+ const recipient = object;
5519
+ if (recipient.id == null || recipient.inboxId == null) throw new BenchmarkTriggerError("each recipient must have id and inbox properties.");
5520
+ return recipient;
5521
+ }));
5332
5522
  }
5333
- /**
5334
- * Resolves the key that signs forwarded requests: the first RSASSA-PKCS1-v1_5
5335
- * key, as {@link sendActivity} signs requests only with such a key. Since
5336
- * the targets have already been claimed, the activity is forwarded unsigned
5337
- * rather than not at all if the key cannot be resolved or used.
5338
- */
5339
- async function resolveForwardingKey({ getKeys, activityId }) {
5340
- if (getKeys == null) return null;
5341
- const logger = getLogger([
5342
- "fedify",
5343
- "federation",
5344
- "inbox"
5345
- ]);
5346
- let key;
5523
+ function isRecipient(value) {
5524
+ return value != null && typeof value === "object" && "id" in value && "inboxId" in value;
5525
+ }
5526
+ async function parseActivity(value, context) {
5347
5527
  try {
5348
- key = (await getKeys()).find((k) => k.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5");
5349
- } catch (error) {
5350
- logger.error("Failed to get the gateway keys to sign forwarded requests with; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
5351
- activityId: activityId.href,
5352
- error
5528
+ return await Activity.fromJsonLd(value, {
5529
+ documentLoader: context.documentLoader,
5530
+ contextLoader: context.contextLoader
5353
5531
  });
5354
- return null;
5355
- }
5356
- if (key == null) return null;
5357
- try {
5358
- validateCryptoKey(key.privateKey, "private");
5359
5532
  } catch (error) {
5360
- if (!(error instanceof TypeError)) throw error;
5361
- logger.warn("The gateway key {keyId} cannot sign forwarded requests; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
5362
- keyId: key.keyId.href,
5363
- activityId: activityId.href,
5364
- error
5365
- });
5366
- return null;
5533
+ throw new BenchmarkTriggerError(`Invalid ActivityPub activity: ${error}`);
5367
5534
  }
5368
- return key;
5369
5535
  }
5370
- async function forwardImmediately(parameters, inboxes) {
5371
- const { activity, activityId, activityType, allowPrivateAddress, specDeterminer, options, meterProvider, tracerProvider } = parameters;
5372
- const logger = getLogger([
5373
- "fedify",
5374
- "federation",
5375
- "inbox"
5376
- ]);
5377
- const deadline = (options ?? resolvePortableInboxForwardingOptions()).deadline.total("millisecond");
5378
- const forwarding = resolveForwardingKey(parameters).then((key) => Promise.all(inboxes.map((inbox) => sendActivity({
5379
- activity,
5380
- activityId: activityId.href,
5381
- activityType,
5382
- keys: key == null ? [] : [key],
5383
- inbox,
5384
- allowPrivateAddress,
5385
- specDeterminer,
5386
- meterProvider,
5387
- tracerProvider
5388
- }).catch((error) => {
5389
- logger.error("Failed to forward activity {activityId} to {inbox}; it will not be forwarded to the inbox again:\n{error}", {
5390
- activityId: activityId.href,
5391
- inbox: inbox.href,
5392
- error
5393
- });
5394
- }))));
5395
- let timer;
5396
- const timedOut = await Promise.race([forwarding.then(() => false), new Promise((resolve) => {
5397
- timer = setTimeout(() => resolve(true), deadline);
5398
- })]);
5399
- clearTimeout(timer);
5400
- if (timedOut) logger.warn("Forwarding activity {activityId} to other gateways did not finish in {deadline} ms; responding to the delivery without waiting for it.", {
5401
- activityId: activityId.href,
5402
- deadline
5536
+ function asRecord(value, name) {
5537
+ if (value == null || typeof value !== "object" || Array.isArray(value)) throw new BenchmarkTriggerError(`${name} must be an object.`);
5538
+ return value;
5539
+ }
5540
+ function jsonResponse(body, status = 200) {
5541
+ return new Response(JSON.stringify(body), {
5542
+ status,
5543
+ headers: { "Content-Type": "application/json" }
5403
5544
  });
5404
5545
  }
5405
- async function enqueueForwarding(parameters, outboxQueue, inboxes) {
5406
- const { activity, activityId, activityType, baseUrl, startQueue, meterProvider } = parameters;
5407
- const logger = getLogger([
5408
- "fedify",
5409
- "federation",
5410
- "inbox"
5411
- ]);
5412
- const key = await resolveForwardingKey(parameters);
5413
- const keys = [];
5414
- if (key != null) try {
5415
- keys.push({
5416
- keyId: key.keyId.href,
5417
- privateKey: await exportJwk(key.privateKey)
5418
- });
5419
- } catch (error) {
5420
- logger.error("Failed to export the gateway key {keyId}; forwarding activity {activityId} without HTTP Signatures:\n{error}", {
5421
- keyId: key.keyId.href,
5422
- activityId: activityId.href,
5423
- error
5424
- });
5546
+ function serializeScopeMetrics(resourceMetrics) {
5547
+ return resourceMetrics.scopeMetrics.map(serializeScope);
5548
+ }
5549
+ function serializeScope(scopeMetrics) {
5550
+ return {
5551
+ scope: {
5552
+ name: scopeMetrics.scope.name,
5553
+ version: scopeMetrics.scope.version
5554
+ },
5555
+ metrics: scopeMetrics.metrics.map(serializeMetric)
5556
+ };
5557
+ }
5558
+ function serializeMetric(metric) {
5559
+ return {
5560
+ name: metric.descriptor.name,
5561
+ description: metric.descriptor.description,
5562
+ unit: metric.descriptor.unit,
5563
+ dataPointType: serializeDataPointType(metric.dataPointType),
5564
+ dataPoints: metric.dataPoints.map((point) => ({
5565
+ attributes: { ...point.attributes },
5566
+ startTime: point.startTime,
5567
+ endTime: point.endTime,
5568
+ value: point.value
5569
+ }))
5570
+ };
5571
+ }
5572
+ function serializeDataPointType(dataPointType) {
5573
+ switch (dataPointType) {
5574
+ case DataPointType.HISTOGRAM: return "histogram";
5575
+ case DataPointType.EXPONENTIAL_HISTOGRAM: return "exponential_histogram";
5576
+ case DataPointType.GAUGE: return "gauge";
5577
+ case DataPointType.SUM: return "sum";
5425
5578
  }
5426
- startQueue?.();
5427
- const started = (/* @__PURE__ */ new Date()).toISOString();
5428
- const traceContext = {};
5429
- propagation.inject(context.active(), traceContext);
5430
- await Promise.all(inboxes.map(async (inbox) => {
5431
- const message = {
5432
- type: "outbox",
5433
- id: crypto.randomUUID(),
5434
- baseUrl,
5435
- keys,
5436
- activity,
5437
- activityId: activityId.href,
5438
- activityType,
5439
- inbox: inbox.href,
5440
- sharedInbox: false,
5441
- started,
5442
- attempt: 0,
5443
- headers: {},
5444
- traceContext
5445
- };
5446
- try {
5447
- await outboxQueue.enqueue(message);
5448
- } catch (error) {
5449
- logger.error("Failed to enqueue activity {activityId} to forward to {inbox}; it will not be forwarded to the inbox again:\n{error}", {
5450
- activityId: activityId.href,
5451
- inbox: inbox.href,
5452
- error
5453
- });
5454
- return;
5455
- }
5456
- recordOutboxEnqueue(meterProvider, outboxQueue, message);
5457
- }));
5458
5579
  }
5459
5580
  //#endregion
5460
5581
  //#region src/federation/outgoing-proof.ts
@@ -8131,7 +8252,7 @@ var FederationImpl = class extends FederationBuilderImpl {
8131
8252
  onNotFound,
8132
8253
  portableInbox: {
8133
8254
  recipient,
8134
- forward: async (activity, activityId, activityType) => {
8255
+ forward: async (activity, activityId, activityType, signatures) => {
8135
8256
  if (this.portableInboxForwarding.maxTargets < 1) return;
8136
8257
  if (this.kv.cas == null) {
8137
8258
  if (!this.#portableInboxForwardingWarned) {
@@ -8154,6 +8275,7 @@ var FederationImpl = class extends FederationBuilderImpl {
8154
8275
  allowPrivateAddress: this.allowPrivateAddress,
8155
8276
  getKeys: () => this.#getPortableGatewayKeyPairs(context, identifier, recipient),
8156
8277
  specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock, { specTtl: this.httpMessageSignaturesSpecTtl }),
8278
+ signatures,
8157
8279
  options: this.portableInboxForwarding,
8158
8280
  meterProvider: this.meterProvider,
8159
8281
  tracerProvider: this.tracerProvider
@@ -9436,4 +9558,4 @@ function getRequestId(request) {
9436
9558
  return `req_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
9437
9559
  }
9438
9560
  //#endregion
9439
- export { respondWithObject as a, digest as c, parseCircuitBreakerKvState as d, createFederationBuilder as f, SendActivityError as i, CircuitBreaker as l, handleWebFinger as n, respondWithObjectIfAcceptable as o, createExponentialBackoffPolicy as r, buildCollectionSynchronizationHeader as s, createFederation as t, normalizeCircuitBreakerOptions as u };
9561
+ export { respondWithObjectIfAcceptable as a, digest as c, parseCircuitBreakerKvState as d, createFederationBuilder as f, respondWithObject as i, CircuitBreaker as l, handleWebFinger as n, SendActivityError as o, createExponentialBackoffPolicy as r, buildCollectionSynchronizationHeader as s, createFederation as t, normalizeCircuitBreakerOptions as u };