@fedify/fedify 2.4.0-dev.2065 → 2.4.0-dev.2071

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 (93) hide show
  1. package/dist/{builder-CMkrnYbY.mjs → builder-DVQ0yhKJ.mjs} +6 -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-Dj3DCsoj.mjs → compound-proof-KmXDfWFp.mjs} +1 -1
  6. package/dist/{context-b36TpPoG.d.cts → context-DijrgHDe.d.cts} +45 -2
  7. package/dist/{context-D_gg4M0n.d.ts → context-DsB9kF6q.d.ts} +45 -2
  8. package/dist/{deno-BuRFI7wk.mjs → deno-B-NtYZVW.mjs} +1 -1
  9. package/dist/{docloader-_aSNLA90.mjs → docloader-C6yOVoaF.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/compound-fanout.test.mjs +4 -4
  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 +8 -8
  18. package/dist/federation/mod.cjs +1 -1
  19. package/dist/federation/mod.d.cts +3 -3
  20. package/dist/federation/mod.d.ts +3 -3
  21. package/dist/federation/mod.js +1 -1
  22. package/dist/federation/outgoing-proof.test.mjs +6 -6
  23. package/dist/federation/portable-gateway-keys.test.d.mts +2 -0
  24. package/dist/federation/portable-gateway-keys.test.mjs +363 -0
  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-Coi_bg12.cjs → federation-CUiHc7dP.cjs} +182 -76
  32. package/dist/http-BoWBwC0g.js +5087 -0
  33. package/dist/{http-BGShIsd6.cjs → http-CuLWIJdf.cjs} +2684 -48
  34. package/dist/{http-f1qaBtOh.mjs → http-DKWi8RjI.mjs} +20 -5
  35. package/dist/{http-65PYi9jY.d.ts → http-n2v6DPxu.d.ts} +52 -2
  36. package/dist/{http-CP-7OdSq.d.cts → http-xlG-jRdB.d.cts} +52 -2
  37. package/dist/{key-BxHsA1s9.mjs → key-lfcx_NaE.mjs} +147 -7
  38. package/dist/{kv-cache-Cgj-kpQS.js → kv-cache-BdnmnAVc.js} +1 -1
  39. package/dist/{kv-cache-CY6pDNoS.cjs → kv-cache-DE8kSNQU.cjs} +1 -1
  40. package/dist/{kv-cache-C9IY-FMN.mjs → kv-cache-d8EjO29d.mjs} +1 -1
  41. package/dist/{ld-CqJq5erX.mjs → ld-jyjdrWjG.mjs} +3 -3
  42. package/dist/{metrics-DOqknlZd.mjs → metrics-B5Rei-HC.mjs} +1 -1
  43. package/dist/{middleware-1h_LgwXC.js → middleware-CAObohey.js} +149 -43
  44. package/dist/{middleware-s-AZzx4r.mjs → middleware-CPx4ZWwt.mjs} +155 -53
  45. package/dist/{middleware-VOCZN3SO.mjs → middleware-CdVnCDXD.mjs} +1 -1
  46. package/dist/{mod-Dhm7SqyE.d.ts → mod-C9WSpZWm.d.ts} +1 -1
  47. package/dist/{mod-C0BYc0OU.d.ts → mod-CVZrXSdm.d.ts} +1 -1
  48. package/dist/{mod-BhMvsgdF.d.ts → mod-DMkflQdF.d.ts} +1 -1
  49. package/dist/{mod-Bfenkg_c.d.cts → mod-DTAaBwiY.d.cts} +1 -1
  50. package/dist/{mod-pLbeNwcC.d.cts → mod-HDSvS-ww.d.cts} +1 -1
  51. package/dist/{mod-CyiSjRkk.d.cts → mod-xGFCHqq_.d.cts} +1 -1
  52. package/dist/mod.cjs +18 -18
  53. package/dist/mod.d.cts +7 -7
  54. package/dist/mod.d.ts +7 -7
  55. package/dist/mod.js +5 -5
  56. package/dist/nodeinfo/handler.test.mjs +1 -1
  57. package/dist/owner-1TFakcTF.js +215 -0
  58. package/dist/owner-BXufwAzm.cjs +225 -0
  59. package/dist/{owner-D_F22lfM.mjs → owner-ByqNQVaa.mjs} +45 -2
  60. package/dist/portable-key-Cw_ow5vn.mjs +194 -0
  61. package/dist/{proof-B03JXhrk.mjs → proof-B6gwdhN5.mjs} +5 -5
  62. package/dist/{send-NNkfKtVN.mjs → send-DsK7xevO.mjs} +3 -3
  63. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  64. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  65. package/dist/sig/compound-proof-verification.test.mjs +2 -2
  66. package/dist/sig/compound-proof.test.mjs +3 -3
  67. package/dist/sig/http.test.mjs +2 -2
  68. package/dist/sig/key.test.mjs +1 -1
  69. package/dist/sig/ld.test.mjs +2 -2
  70. package/dist/sig/mod.cjs +16 -16
  71. package/dist/sig/mod.d.cts +2 -2
  72. package/dist/sig/mod.d.ts +2 -2
  73. package/dist/sig/mod.js +3 -3
  74. package/dist/sig/owner.test.mjs +1 -1
  75. package/dist/sig/portable-collection.test.mjs +3 -3
  76. package/dist/sig/portable-key.test.d.mts +2 -0
  77. package/dist/sig/portable-key.test.mjs +275 -0
  78. package/dist/sig/proof.test.mjs +4 -4
  79. package/dist/{sig-Bb20Pyrd.js → sig-BR_Z6mpY.js} +2 -2
  80. package/dist/{sig-B1E2uyhQ.cjs → sig-TTn9wYrE.cjs} +4 -4
  81. package/dist/{temporal-VVVSuruq.mjs → temporal-Bw5jtrBY.mjs} +1 -1
  82. package/dist/testing/kv.test.mjs +1 -1
  83. package/dist/testing/mod.d.mts +43 -0
  84. package/dist/utils/docloader.test.mjs +2 -2
  85. package/dist/utils/kv-cache.test.mjs +1 -1
  86. package/dist/utils/mod.cjs +1 -1
  87. package/dist/utils/mod.d.cts +1 -1
  88. package/dist/utils/mod.d.ts +1 -1
  89. package/dist/utils/mod.js +1 -1
  90. package/package.json +6 -6
  91. package/dist/http-z5n7chWw.js +0 -2647
  92. package/dist/owner-BLBWXCNt.js +0 -2276
  93. package/dist/owner-D8ZpRusc.cjs +0 -2446
@@ -1,15 +1,21 @@
1
1
  const { URLPattern } = require("urlpattern-polyfill");
2
+ const require_rolldown_runtime = require("./rolldown-runtime-Dmm3t92W.cjs");
2
3
  let _logtape_logtape = require("@logtape/logtape");
3
4
  let _fedify_vocab = require("@fedify/vocab");
4
5
  let _opentelemetry_api = require("@opentelemetry/api");
5
6
  let byte_encodings_hex = require("byte-encodings/hex");
6
7
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
8
+ let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
9
+ _fedify_vocab_runtime_jsonld = require_rolldown_runtime.__toESM(_fedify_vocab_runtime_jsonld, 1);
7
10
  let structured_field_values = require("structured-field-values");
11
+ let _fedify_vocab_runtime_internal_signed_representation = require("@fedify/vocab-runtime/internal/signed-representation");
12
+ let json_canon = require("json-canon");
13
+ json_canon = require_rolldown_runtime.__toESM(json_canon, 1);
8
14
  let byte_encodings_base64 = require("byte-encodings/base64");
9
15
  let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
10
16
  //#region deno.json
11
17
  var name = "@fedify/fedify";
12
- var version = "2.4.0-dev.2065+b09fdd33";
18
+ var version = "2.4.0-dev.2071+8b9dccb9";
13
19
  //#endregion
14
20
  //#region ../../node_modules/.pnpm/temporal-polyfill@1.0.1/node_modules/temporal-polyfill/chunks/root.js
15
21
  const NativeTemporal = globalThis.Temporal;
@@ -3556,7 +3562,7 @@ const Now = /*@__PURE__*/ Object.defineProperties({}, {
3556
3562
  }
3557
3563
  })
3558
3564
  });
3559
- const Temporal$2 = /*@__PURE__*/ Object.defineProperties({}, {
3565
+ const Temporal$3 = /*@__PURE__*/ Object.defineProperties({}, {
3560
3566
  ...createStringTagDescriptors("Temporal"),
3561
3567
  ...createPropDescriptors({
3562
3568
  PlainYearMonth,
@@ -3572,7 +3578,7 @@ const Temporal$2 = /*@__PURE__*/ Object.defineProperties({}, {
3572
3578
  });
3573
3579
  //#endregion
3574
3580
  //#region ../../node_modules/.pnpm/temporal-polyfill@1.0.1/node_modules/temporal-polyfill/index.js
3575
- const Temporal$1 = NativeTemporal || Temporal$2;
3581
+ const Temporal$2 = NativeTemporal || Temporal$3;
3576
3582
  NativeTemporal && Date.prototype.toTemporalInstant;
3577
3583
  //#endregion
3578
3584
  //#region src/sig/accept.ts
@@ -3714,6 +3720,421 @@ function fulfillAcceptSignature(entry, localKeyId, localAlg) {
3714
3720
  };
3715
3721
  }
3716
3722
  //#endregion
3723
+ //#region src/compat/preloaded-context-loader.ts
3724
+ /**
3725
+ * A restricted JSON-LD document loader that resolves only contexts bundled
3726
+ * with Fedify.
3727
+ *
3728
+ * This is intentionally narrower than `getDocumentLoader()`: normalization
3729
+ * helpers are also reached from verification paths that operate on inbound,
3730
+ * attacker-controlled JSON-LD, so the default fallback must never fetch
3731
+ * attacker-supplied context URLs.
3732
+ */
3733
+ const preloadedOnlyDocumentLoader = (url) => {
3734
+ if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
3735
+ contextUrl: null,
3736
+ documentUrl: url,
3737
+ document: _fedify_vocab_runtime.preloadedContexts[url]
3738
+ });
3739
+ return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
3740
+ };
3741
+ //#endregion
3742
+ //#region src/compat/secured-document.ts
3743
+ function isJsonMap$1(value) {
3744
+ return typeof value === "object" && value != null && !Array.isArray(value);
3745
+ }
3746
+ function isNonEmptyString(value) {
3747
+ return typeof value === "string" && value.length > 0;
3748
+ }
3749
+ function hasDataIntegrityProofType(value) {
3750
+ return (Array.isArray(value) ? value : [value]).some((type) => type === "DataIntegrityProof" || type === "https://w3id.org/security#DataIntegrityProof");
3751
+ }
3752
+ /**
3753
+ * Checks whether a JSON value is a complete, self-contained secured document:
3754
+ * a map with its own `@context` and exactly one direct, map-valued `proof`
3755
+ * that carries every member `eddsa-jcs-2022` proof generation produces.
3756
+ *
3757
+ * This is deliberately stricter than {@link hasProofLike}, which exists to
3758
+ * decide whether a document is worth verifying. Here a false positive would
3759
+ * silently suppress a wire-compatibility fix on an ordinary document, so a
3760
+ * partial or malformed proof does not qualify.
3761
+ *
3762
+ * @internal
3763
+ */
3764
+ function isSelfContainedSecuredDocument(value) {
3765
+ if (!isJsonMap$1(value)) return false;
3766
+ if (!Object.hasOwn(value, "@context") || value["@context"] == null) return false;
3767
+ if (!Object.hasOwn(value, "proof")) return false;
3768
+ const proof = value.proof;
3769
+ if (!isJsonMap$1(proof)) return false;
3770
+ return hasDataIntegrityProofType(proof.type) && isNonEmptyString(proof.cryptosuite) && isNonEmptyString(proof.created) && isNonEmptyString(proof.verificationMethod) && isNonEmptyString(proof.proofPurpose) && isNonEmptyString(proof.proofValue);
3771
+ }
3772
+ //#endregion
3773
+ //#region src/compat/public-audience.ts
3774
+ const logger$4 = (0, _logtape_logtape.getLogger)([
3775
+ "fedify",
3776
+ "compat",
3777
+ "public-audience"
3778
+ ]);
3779
+ const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
3780
+ "to",
3781
+ "cc",
3782
+ "bto",
3783
+ "bcc",
3784
+ "audience"
3785
+ ]);
3786
+ const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
3787
+ const MAX_TRAVERSAL_DEPTH$1 = 64;
3788
+ const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
3789
+ function hasPublicCurieInAddressing(value, preserveSecured, parentKey, depth = 0) {
3790
+ if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
3791
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
3792
+ if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, preserveSecured, parentKey, depth + 1));
3793
+ if (typeof value !== "object" || value == null) return false;
3794
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return false;
3795
+ const record = value;
3796
+ for (const key of Object.keys(record)) {
3797
+ if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
3798
+ if (key === "@context") continue;
3799
+ if (hasPublicCurieInAddressing(record[key], preserveSecured, key, depth + 1)) return true;
3800
+ }
3801
+ return false;
3802
+ }
3803
+ function rewritePublicAudience(value, preserveSecured, parentKey, depth = 0) {
3804
+ if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
3805
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
3806
+ if (Array.isArray(value)) {
3807
+ let changed = false;
3808
+ const mapped = value.map((item) => {
3809
+ const rewritten = rewritePublicAudience(item, preserveSecured, parentKey, depth + 1);
3810
+ if (rewritten !== item) changed = true;
3811
+ return rewritten;
3812
+ });
3813
+ return changed ? mapped : value;
3814
+ }
3815
+ if (typeof value !== "object" || value == null) return value;
3816
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return value;
3817
+ const record = value;
3818
+ let changed = false;
3819
+ const normalized = Object.create(null);
3820
+ for (const key of Object.keys(record)) {
3821
+ const rewritten = key === "@context" ? record[key] : record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public") ? _fedify_vocab.PUBLIC_COLLECTION.href : rewritePublicAudience(record[key], preserveSecured, key, depth + 1);
3822
+ if (rewritten !== record[key]) changed = true;
3823
+ normalized[key] = rewritten;
3824
+ }
3825
+ return changed ? normalized : value;
3826
+ }
3827
+ /**
3828
+ * Reports whether `value` carries an `@context` property anywhere inside
3829
+ * its subtree (not counting the value itself). A nested `@context` can
3830
+ * introduce a local term-definition scope that redefines `as:` or `Public`
3831
+ * even when the top-level `@context` is safe, so the fast path must defer
3832
+ * to the URDNA2015 equivalence check whenever one is present.
3833
+ */
3834
+ function hasNestedContext$1(value, depth = 0) {
3835
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
3836
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
3837
+ if (typeof value !== "object" || value == null) return false;
3838
+ const record = value;
3839
+ for (const key of Object.keys(record)) {
3840
+ if (key === "@context") return true;
3841
+ if (hasNestedContext$1(record[key], depth + 1)) return true;
3842
+ }
3843
+ return false;
3844
+ }
3845
+ /**
3846
+ * Checks whether the `@context` of a JSON-LD document is guaranteed not
3847
+ * to redefine the `as:` prefix or the bare `Public` term. Only documents
3848
+ * whose `@context` is a string, or an array of strings, drawn from Fedify's
3849
+ * preloaded context set AND including the ActivityStreams URL qualify,
3850
+ * AND no nested subtree carries its own `@context` that might redefine
3851
+ * those terms within a local scope. When all of that holds the rewrite
3852
+ * is provably semantics-preserving and the URDNA2015 equivalence check
3853
+ * can be skipped. Any other shape (unknown external URLs, inline
3854
+ * objects at the top level, nested `@context` blocks) is treated as
3855
+ * potentially unsafe.
3856
+ */
3857
+ function hasKnownSafeContext$1(jsonLd) {
3858
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
3859
+ const record = jsonLd;
3860
+ if (!Object.hasOwn(record, "@context")) return false;
3861
+ const ctx = record["@context"];
3862
+ const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
3863
+ if (entries == null || entries.length === 0) return false;
3864
+ let hasAs = false;
3865
+ for (const entry of entries) {
3866
+ if (typeof entry !== "string") return false;
3867
+ if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
3868
+ if (entry === AS_CONTEXT_URL$1) hasAs = true;
3869
+ }
3870
+ if (!hasAs) return false;
3871
+ for (const key of Object.keys(record)) {
3872
+ if (key === "@context") continue;
3873
+ if (hasNestedContext$1(record[key])) return false;
3874
+ }
3875
+ return true;
3876
+ }
3877
+ /**
3878
+ * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
3879
+ * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
3880
+ * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
3881
+ *
3882
+ * Several ActivityPub implementations, Lemmy among them, match these
3883
+ * fields as plain URLs without running JSON-LD expansion, and silently
3884
+ * drop activities whose public addressing appears in CURIE form. This
3885
+ * helper works around that gap.
3886
+ *
3887
+ * For documents whose `@context` is drawn entirely from Fedify's
3888
+ * preloaded context set and includes the ActivityStreams URL, the
3889
+ * rewrite is applied directly: the content of every preloaded non-AS
3890
+ * context is known not to redefine the `as:` prefix or the bare `Public`
3891
+ * term, so the semantics are preserved by construction. Any other
3892
+ * shape (an inline object, an unknown external URL, and so on) is
3893
+ * treated as potentially unsafe and gated on a JSON-LD equivalence
3894
+ * check; both forms are canonicalized with URDNA2015 and the resulting
3895
+ * N-Quads are compared. When they differ, the original document is
3896
+ * returned unchanged. Canonicalization failures also fall back to the
3897
+ * original document.
3898
+ *
3899
+ * When no `contextLoader` is supplied the helper falls back to an
3900
+ * internal loader that resolves only the URLs in Fedify's
3901
+ * preloaded-contexts set and rejects every other URL without issuing a
3902
+ * network request. That behaviour is deliberately narrower than
3903
+ * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
3904
+ * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
3905
+ * helper is reached from verification paths (`verifyProof()` /
3906
+ * `verifyObject()`) that operate on inbound, potentially adversarial
3907
+ * JSON-LD, and a default loader that fetches attacker-supplied
3908
+ * `@context` URLs on the caller's behalf would be an SSRF vector.
3909
+ * Canonicalization failures against the restricted loader fall back to
3910
+ * the original document, same as any other canonicalization error.
3911
+ * Callers that genuinely need the remote-fetch loader (for example
3912
+ * applications that sign local JSON-LD against a custom vocabulary)
3913
+ * should pass a `contextLoader` explicitly.
3914
+ *
3915
+ * Must be called before any signing step that canonicalizes the
3916
+ * compact form byte-for-byte (for example, Object Integrity Proofs
3917
+ * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
3918
+ * matches what is sent on the wire.
3919
+ */
3920
+ async function normalizePublicAudience(jsonLd, contextLoader, options = {}) {
3921
+ const preserveSecured = options.preserveNestedSecuredDocuments ?? false;
3922
+ if (!hasPublicCurieInAddressing(jsonLd, preserveSecured)) return jsonLd;
3923
+ const normalized = rewritePublicAudience(jsonLd, preserveSecured);
3924
+ if (hasKnownSafeContext$1(jsonLd)) return normalized;
3925
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
3926
+ try {
3927
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
3928
+ format: "application/n-quads",
3929
+ documentLoader: loader
3930
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
3931
+ format: "application/n-quads",
3932
+ documentLoader: loader
3933
+ })]);
3934
+ if (before === after) return normalized;
3935
+ logger$4.warn("Expanding the public audience CURIE to its full URI would change the canonical form of the activity; sending the activity as is. This usually means the active JSON-LD context redefines the `as:` prefix or the bare `Public` term.");
3936
+ } catch (error) {
3937
+ logger$4.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
3938
+ }
3939
+ return jsonLd;
3940
+ }
3941
+ //#endregion
3942
+ //#region src/compat/outgoing-jsonld.ts
3943
+ const logger$3 = (0, _logtape_logtape.getLogger)([
3944
+ "fedify",
3945
+ "compat",
3946
+ "outgoing-jsonld"
3947
+ ]);
3948
+ const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
3949
+ const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
3950
+ const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
3951
+ const MAX_TRAVERSAL_DEPTH = 64;
3952
+ function isJsonLdListObject(value) {
3953
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
3954
+ }
3955
+ function isJsonLdValueObject(value) {
3956
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
3957
+ }
3958
+ function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
3959
+ if (Array.isArray(value)) {
3960
+ if (seen.has(value)) return;
3961
+ seen.add(value);
3962
+ for (const item of value) yield* getContextObjects(item, seen);
3963
+ return;
3964
+ }
3965
+ if (typeof value === "object" && value != null) {
3966
+ if (seen.has(value)) return;
3967
+ seen.add(value);
3968
+ const record = value;
3969
+ yield record;
3970
+ for (const definition of Object.values(record)) {
3971
+ if (typeof definition !== "object" || definition == null) continue;
3972
+ const nestedContext = definition["@context"];
3973
+ if (nestedContext == null) continue;
3974
+ yield* getContextObjects(nestedContext, seen);
3975
+ }
3976
+ }
3977
+ }
3978
+ function isActivityStreamsAttachmentTerm(value) {
3979
+ return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
3980
+ }
3981
+ /** @internal */
3982
+ function isPreloadedContextAttachmentSafe(document) {
3983
+ if (typeof document !== "object" || document == null) return true;
3984
+ const context = document["@context"];
3985
+ for (const contextObject of getContextObjects(context)) {
3986
+ if (!Object.hasOwn(contextObject, "attachment")) continue;
3987
+ if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
3988
+ return false;
3989
+ }
3990
+ return true;
3991
+ }
3992
+ function getKnownSafeContextUrls() {
3993
+ const urls = /* @__PURE__ */ new Set();
3994
+ for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
3995
+ else logger$3.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
3996
+ return urls;
3997
+ }
3998
+ /**
3999
+ * Wraps scalar ActivityStreams attachment properties in arrays.
4000
+ */
4001
+ function wrapScalarAttachments(jsonLd, preserveSecured, depth = 0) {
4002
+ if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
4003
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(jsonLd)) return jsonLd;
4004
+ if (Array.isArray(jsonLd)) {
4005
+ let normalized = null;
4006
+ for (let i = 0; i < jsonLd.length; i++) {
4007
+ const item = jsonLd[i];
4008
+ const next = wrapScalarAttachments(item, preserveSecured, depth + 1);
4009
+ if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
4010
+ if (normalized != null) normalized[i] = next;
4011
+ }
4012
+ return normalized ?? jsonLd;
4013
+ }
4014
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
4015
+ const record = jsonLd;
4016
+ const keys = Object.keys(record);
4017
+ let normalized = null;
4018
+ for (let i = 0; i < keys.length; i++) {
4019
+ const key = keys[i];
4020
+ const value = record[key];
4021
+ const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, preserveSecured, depth + 1);
4022
+ const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
4023
+ if (normalized == null && output !== value) {
4024
+ const cloned = Object.create(null);
4025
+ for (let j = 0; j < i; j++) {
4026
+ const previousKey = keys[j];
4027
+ cloned[previousKey] = record[previousKey];
4028
+ }
4029
+ normalized = cloned;
4030
+ }
4031
+ if (normalized != null) normalized[key] = output;
4032
+ }
4033
+ return normalized ?? jsonLd;
4034
+ }
4035
+ function hasNestedContext(value, depth = 0) {
4036
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
4037
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
4038
+ if (typeof value !== "object" || value == null) return false;
4039
+ const record = value;
4040
+ for (const key of Object.keys(record)) {
4041
+ if (key === "@context") return true;
4042
+ if (key === "@value" && isJsonLdValueObject(value)) continue;
4043
+ if (hasNestedContext(record[key], depth + 1)) return true;
4044
+ }
4045
+ return false;
4046
+ }
4047
+ function exceedsTraversalDepth(value, depth = 0) {
4048
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
4049
+ if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
4050
+ if (typeof value !== "object" || value == null) return false;
4051
+ const record = value;
4052
+ for (const key of Object.keys(record)) {
4053
+ if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
4054
+ if (exceedsTraversalDepth(record[key], depth + 1)) return true;
4055
+ }
4056
+ return false;
4057
+ }
4058
+ function hasKnownSafeContext(jsonLd) {
4059
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
4060
+ const record = jsonLd;
4061
+ if (!Object.hasOwn(record, "@context")) return false;
4062
+ const context = record["@context"];
4063
+ const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
4064
+ if (entries == null || entries.length < 1) return false;
4065
+ let hasActivityStreamsContext = false;
4066
+ for (const entry of entries) {
4067
+ if (typeof entry !== "string") return false;
4068
+ if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
4069
+ if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
4070
+ }
4071
+ if (!hasActivityStreamsContext) return false;
4072
+ for (const key of Object.keys(record)) {
4073
+ if (key === "@context") continue;
4074
+ if (hasNestedContext(record[key])) return false;
4075
+ }
4076
+ return true;
4077
+ }
4078
+ function getLogSafeJsonLdMetadata(jsonLd) {
4079
+ if (typeof jsonLd !== "object" || jsonLd == null) return {};
4080
+ const record = jsonLd;
4081
+ const context = record["@context"];
4082
+ return {
4083
+ id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
4084
+ type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
4085
+ context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
4086
+ };
4087
+ }
4088
+ /**
4089
+ * Ensures ActivityStreams attachment properties are represented as arrays
4090
+ * when doing so preserves the JSON-LD semantics.
4091
+ *
4092
+ * JSON-LD compaction collapses single-item arrays into scalar values by
4093
+ * default. Some ActivityPub implementations, Pixelfed among them, parse
4094
+ * `attachment` as a plain JSON array rather than a JSON-LD property and reject
4095
+ * otherwise valid objects whose single attachment is emitted as a scalar.
4096
+ *
4097
+ * When no `contextLoader` is supplied, the helper falls back to a restricted
4098
+ * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
4099
+ * every other URL without network access. Documents with custom, inline, or
4100
+ * otherwise uncached contexts should pass a real `contextLoader` if they need
4101
+ * the semantic-preservation check to succeed; otherwise canonicalization
4102
+ * failures leave the original document unchanged.
4103
+ */
4104
+ async function normalizeAttachmentArrays(jsonLd, contextLoader, options = {}) {
4105
+ const normalized = wrapScalarAttachments(jsonLd, options.preserveNestedSecuredDocuments ?? false);
4106
+ if (normalized === jsonLd) return jsonLd;
4107
+ if (exceedsTraversalDepth(jsonLd)) {
4108
+ logger$3.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
4109
+ return jsonLd;
4110
+ }
4111
+ if (hasKnownSafeContext(jsonLd)) return normalized;
4112
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
4113
+ try {
4114
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
4115
+ format: "application/n-quads",
4116
+ documentLoader: loader
4117
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
4118
+ format: "application/n-quads",
4119
+ documentLoader: loader
4120
+ })]);
4121
+ if (before === after) return normalized;
4122
+ logger$3.warn("Wrapping scalar attachment values in arrays would change the canonical form of the JSON-LD document; leaving it unchanged. This usually means the active JSON-LD context redefines the `attachment` term. Document: {id}; type: {type}; context: {context}.", getLogSafeJsonLdMetadata(jsonLd));
4123
+ } catch (error) {
4124
+ logger$3.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
4125
+ }
4126
+ return jsonLd;
4127
+ }
4128
+ /**
4129
+ * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
4130
+ * to locally generated outgoing activities before they are signed, enqueued,
4131
+ * or sent.
4132
+ */
4133
+ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, options = {}) {
4134
+ jsonLd = await normalizePublicAudience(jsonLd, contextLoader, options);
4135
+ return await normalizeAttachmentArrays(jsonLd, contextLoader, options);
4136
+ }
4137
+ //#endregion
3717
4138
  //#region src/federation/metrics.ts
3718
4139
  var FederationMetrics = class {
3719
4140
  deliverySent;
@@ -4524,6 +4945,99 @@ function getDurationMs(start) {
4524
4945
  return Math.max(0, performance.now() - start);
4525
4946
  }
4526
4947
  //#endregion
4948
+ //#region src/sig/portable-key-id.ts
4949
+ const COMPATIBLE_KEY_ID_PATH_PATTERN = /^\/\.well-known\/apgateway\/did(?::|%3A)/i;
4950
+ /**
4951
+ * Checks whether the URL is an `ap:` or `ap+ef61:` URI.
4952
+ * @internal
4953
+ */
4954
+ function isPortableUri(url) {
4955
+ return url.protocol === "ap:" || url.protocol === "ap+ef61:";
4956
+ }
4957
+ /**
4958
+ * Checks whether an activity is performed by an FEP-ef61 portable actor,
4959
+ * i.e., any of its actors has an `ap:` or `ap+ef61:` ID.
4960
+ * @internal
4961
+ */
4962
+ function hasPortableActor(activity) {
4963
+ return activity.actorIds.some(isPortableUri);
4964
+ }
4965
+ /**
4966
+ * Checks whether a key ID looks like an [FEP-ef61] compatible identifier,
4967
+ * i.e., an HTTP(S) URL under a gateway's `/.well-known/apgateway/did:` path.
4968
+ * Such a key ID names a key that a gateway holds for a portable actor, so it
4969
+ * is resolved only as a gateway key, and never cached in a key cache.
4970
+ *
4971
+ * [FEP-ef61]: https://w3id.org/fep/ef61
4972
+ * @internal
4973
+ */
4974
+ function isCompatibleKeyId(keyId) {
4975
+ return (keyId.protocol === "http:" || keyId.protocol === "https:") && COMPATIBLE_KEY_ID_PATH_PATTERN.test(keyId.pathname);
4976
+ }
4977
+ /**
4978
+ * Gets the canonical portable ID of an actor ID that is either an `ap:` or
4979
+ * `ap+ef61:` URI or a compatible identifier.
4980
+ * @returns The canonical portable ID, or `null` if the ID is neither, or is
4981
+ * malformed.
4982
+ * @internal
4983
+ */
4984
+ function getCanonicalPortableId(id) {
4985
+ try {
4986
+ if (isPortableUri(id)) return (0, _fedify_vocab_runtime.canonicalizePortableUri)((0, _fedify_vocab_runtime.formatIri)(id));
4987
+ const portable = (0, _fedify_vocab_runtime.fromCompatibleEf61Id)(id);
4988
+ if (portable == null) return null;
4989
+ return (0, _fedify_vocab_runtime.canonicalizePortableUri)((0, _fedify_vocab_runtime.formatIri)(portable));
4990
+ } catch (error) {
4991
+ if (error instanceof TypeError) return null;
4992
+ throw error;
4993
+ }
4994
+ }
4995
+ /**
4996
+ * Builds the base of the key IDs of a gateway's keys for a portable actor:
4997
+ * the actor's compatible identifier on the gateway.
4998
+ * @param actorId The portable actor's ID, either an `ap:` or `ap+ef61:` URI
4999
+ * or a compatible identifier. It must not have a fragment.
5000
+ * @param gateway The gateway's origin, e.g., `https://example.com`.
5001
+ * @returns The compatible identifier without query and fragment.
5002
+ * @throws {TypeError} If the actor ID is not a portable ID, or has
5003
+ * a fragment.
5004
+ * @internal
5005
+ */
5006
+ function getGatewayKeyBase(actorId, gateway) {
5007
+ let portable;
5008
+ if (isPortableUri(actorId)) portable = actorId;
5009
+ else try {
5010
+ portable = (0, _fedify_vocab_runtime.fromCompatibleEf61Id)(actorId);
5011
+ } catch (error) {
5012
+ if (!(error instanceof TypeError)) throw error;
5013
+ portable = null;
5014
+ }
5015
+ if (portable == null) throw new TypeError(`The portable actor ID ${actorId.href} must be an ap: or ap+ef61: URI, or an FEP-ef61 compatible identifier.`);
5016
+ if (portable.hash !== "") throw new TypeError(`The portable actor ID ${actorId.href} must not have a fragment.`);
5017
+ const base = (0, _fedify_vocab_runtime.toCompatibleEf61Id)(portable, gateway);
5018
+ base.search = "";
5019
+ base.hash = "";
5020
+ return base;
5021
+ }
5022
+ /**
5023
+ * Tells whether a parsed document at a compatible key ID is a portable actor,
5024
+ * which makes the key a gateway key that only
5025
+ * {@link verifyPortableGatewayKeyDocument} can vouch for.
5026
+ * @internal
5027
+ */
5028
+ function isPortableActorDocument(object) {
5029
+ return (0, _fedify_vocab.isActor)(object) && object.id != null && isPortableUri(object.id);
5030
+ }
5031
+ /**
5032
+ * Compares two public keys by their key material.
5033
+ * @internal
5034
+ */
5035
+ async function isSamePublicKey(a, b) {
5036
+ if (a.algorithm.name !== b.algorithm.name) return false;
5037
+ const [x, y] = await Promise.all([crypto.subtle.exportKey("jwk", a), crypto.subtle.exportKey("jwk", b)]);
5038
+ return x.kty === y.kty && x.crv === y.crv && x.n === y.n && x.e === y.e && x.x === y.x && x.y === y.y;
5039
+ }
5040
+ //#endregion
4527
5041
  //#region src/sig/key.ts
4528
5042
  /**
4529
5043
  * Checks if the given key is valid and supported. No-op if the key is valid,
@@ -4747,7 +5261,15 @@ async function withFetchKeySpan(keyId, tracerProvider, fetcher) {
4747
5261
  /**
4748
5262
  * Fetches a {@link CryptographicKey} or {@link Multikey} from the given URL.
4749
5263
  * If the given URL contains an {@link Actor} object, it tries to find
4750
- * the corresponding key in the `publicKey` or `assertionMethod` property.
5264
+ * the corresponding key in the `publicKey` or `assertionMethod` property. *
5265
+ * Gateway keys of [FEP-ef61] portable actors, i.e., keys whose IDs are
5266
+ * compatible identifiers that dereference to portable actor documents, are
5267
+ * not resolved by this function, as they only authenticate HTTP requests;
5268
+ * use `verifyRequest()` or `getKeyOwner()` for them instead. Keys
5269
+ * whose IDs are compatible identifiers are never read from or written to
5270
+ * the key cache.
5271
+ *
5272
+ * [FEP-ef61]: https://w3id.org/fep/ef61
4751
5273
  * @template T The type of the key to fetch. Either {@link CryptographicKey}
4752
5274
  * or {@link Multikey}.
4753
5275
  * @param keyId The URL of the key.
@@ -4764,7 +5286,15 @@ function fetchKey(keyId, cls, options = {}) {
4764
5286
  /**
4765
5287
  * Fetches a {@link CryptographicKey} or {@link Multikey} from the given URL,
4766
5288
  * preserving transport-level fetch failures for callers that need to inspect
4767
- * why the key could not be loaded.
5289
+ * why the key could not be loaded. *
5290
+ * Gateway keys of [FEP-ef61] portable actors, i.e., keys whose IDs are
5291
+ * compatible identifiers that dereference to portable actor documents, are
5292
+ * not resolved by this function, as they only authenticate HTTP requests;
5293
+ * use `verifyRequest()` or `getKeyOwner()` for them instead. Keys
5294
+ * whose IDs are compatible identifiers are never read from or written to
5295
+ * the key cache.
5296
+ *
5297
+ * [FEP-ef61]: https://w3id.org/fep/ef61
4768
5298
  *
4769
5299
  * @template T The type of the key to fetch. Either {@link CryptographicKey}
4770
5300
  * or {@link Multikey}.
@@ -4915,7 +5445,7 @@ async function resolveDidKey(cacheKey, cls, keyCache, logger) {
4915
5445
  cached: false
4916
5446
  };
4917
5447
  }
4918
- async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, { documentLoader, contextLoader, keyCache, tracerProvider, keyIdBoundByCaller }, logger) {
5448
+ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, { documentLoader, contextLoader, keyCache, tracerProvider, keyIdBoundByCaller, portableGatewayKeyResolver }, logger) {
4919
5449
  let object;
4920
5450
  try {
4921
5451
  object = await _fedify_vocab.Object.fromJsonLd(document, {
@@ -4944,6 +5474,33 @@ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, {
4944
5474
  throw e;
4945
5475
  }
4946
5476
  }
5477
+ if (isCompatibleKeyId(cacheKey) && isPortableActorDocument(object)) {
5478
+ if (portableGatewayKeyResolver == null || cls !== _fedify_vocab.CryptographicKey) {
5479
+ logger.debug("Failed to verify; key {keyId} is a gateway key of the portable actor {actorId}, which is only accepted for HTTP Signatures.", {
5480
+ keyId,
5481
+ actorId: object.id?.href
5482
+ });
5483
+ return {
5484
+ key: null,
5485
+ cached: false
5486
+ };
5487
+ }
5488
+ const resolution = await portableGatewayKeyResolver(document, object, cacheKey);
5489
+ if (resolution.type !== "verified") {
5490
+ logger.debug("Failed to verify; the portable actor {actorId} does not vouch for its gateway key {keyId}.", {
5491
+ keyId,
5492
+ actorId: object.id?.href
5493
+ });
5494
+ return {
5495
+ key: null,
5496
+ cached: false
5497
+ };
5498
+ }
5499
+ return {
5500
+ key: resolution.key,
5501
+ cached: false
5502
+ };
5503
+ }
4947
5504
  let key = null;
4948
5505
  let ownerDocument = null;
4949
5506
  if (object instanceof cls && (object.id == null || object.id.href === keyId)) key = object.id == null ? object.clone({ id: cacheKey }) : object;
@@ -5063,6 +5620,10 @@ async function fetchKeyWithResult(cacheKey, cls, options, onCachedUnavailable, o
5063
5620
  "key"
5064
5621
  ]);
5065
5622
  const keyId = cacheKey.href;
5623
+ if (isCompatibleKeyId(cacheKey)) options = {
5624
+ ...options,
5625
+ keyCache: void 0
5626
+ };
5066
5627
  const keyCache = options.keyCache;
5067
5628
  const didKey = await resolveDidKey(cacheKey, cls, keyCache, logger);
5068
5629
  if (didKey != null) {
@@ -5129,34 +5690,362 @@ async function fetchKeyInternal(keyId, cls, options = {}) {
5129
5690
  });
5130
5691
  }
5131
5692
  //#endregion
5132
- //#region src/sig/http.ts
5133
- const Temporal = Temporal$1;
5134
- const DEFAULT_MAX_REDIRECTION = 20;
5135
- const DOUBLE_KNOCK_TRANSPORT_RETRY_DELAY_MS = 100;
5693
+ //#region src/sig/ld.ts
5694
+ const logger$2 = (0, _logtape_logtape.getLogger)([
5695
+ "fedify",
5696
+ "sig",
5697
+ "ld"
5698
+ ]);
5699
+ const localContext = [
5700
+ "https://w3id.org/identity/v1",
5701
+ "https://www.w3.org/ns/activitystreams",
5702
+ "https://w3id.org/security/v1",
5703
+ "https://w3id.org/security/data-integrity/v1"
5704
+ ];
5705
+ const localContextUrls = new Set(localContext);
5706
+ const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
5707
+ const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
5708
+ "@graph",
5709
+ "@included",
5710
+ "@reverse"
5711
+ ]);
5712
+ /** @internal */
5713
+ var UnsafeJsonLdError = class extends TypeError {
5714
+ keyword;
5715
+ constructor(keyword) {
5716
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
5717
+ this.keyword = keyword;
5718
+ this.name = "UnsafeJsonLdError";
5719
+ }
5720
+ };
5721
+ /** @internal */
5722
+ var InvalidContextReferenceError = class extends TypeError {
5723
+ reference;
5724
+ constructor(reference) {
5725
+ super(`Invalid JSON-LD context reference: ${reference}.`);
5726
+ this.reference = reference;
5727
+ this.name = "InvalidContextReferenceError";
5728
+ }
5729
+ };
5730
+ function createLoadingRemoteContextFailedError(reference, cause) {
5731
+ const message = cause instanceof Error ? cause.message : String(cause);
5732
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
5733
+ error.name = "jsonld.InvalidUrl";
5734
+ error.details = {
5735
+ code: "loading remote context failed",
5736
+ url: reference
5737
+ };
5738
+ error.cause = cause;
5739
+ return error;
5740
+ }
5741
+ /** @internal */
5742
+ function isClearlyMalformedContextReference(reference) {
5743
+ for (const char of reference) {
5744
+ const code = char.charCodeAt(0);
5745
+ if (code <= 32 || code === 127) return true;
5746
+ }
5747
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
5748
+ for (let i = 0; i < reference.length; i++) {
5749
+ if (reference[i] !== "%") continue;
5750
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
5751
+ i += 2;
5752
+ }
5753
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
5754
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
5755
+ }
5756
+ return false;
5757
+ }
5758
+ function cloneRemoteDocument(remoteDocument) {
5759
+ return structuredClone(remoteDocument);
5760
+ }
5761
+ function createMemoizedDocumentLoader(documentLoader) {
5762
+ const cache = /* @__PURE__ */ new Map();
5763
+ return async (url, options) => {
5764
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
5765
+ let remoteDocument = cache.get(cacheKey);
5766
+ if (remoteDocument == null) {
5767
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
5768
+ remoteDocument.catch(() => {
5769
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
5770
+ });
5771
+ cache.set(cacheKey, remoteDocument);
5772
+ }
5773
+ return cloneRemoteDocument(await remoteDocument);
5774
+ };
5775
+ }
5776
+ /** @internal */
5777
+ function wrapContextLoaderForJsonLd(contextLoader) {
5778
+ const loader = contextLoader ?? builtInContextLoader;
5779
+ return async (url, options) => {
5780
+ try {
5781
+ return await loader(url, options);
5782
+ } catch (error) {
5783
+ if (!isInvalidUrlTypeError(error)) throw error;
5784
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
5785
+ throw createLoadingRemoteContextFailedError(url, error);
5786
+ }
5787
+ };
5788
+ }
5789
+ /** @internal */
5790
+ function getNormalizationContextLoader(contextLoader) {
5791
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
5792
+ return createMemoizedDocumentLoader(async (url, options) => {
5793
+ if (URL.canParse(url)) {
5794
+ const normalizedUrl = new URL(url).href;
5795
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
5796
+ }
5797
+ return await loader(url, options);
5798
+ });
5799
+ }
5800
+ /** @internal */
5801
+ async function compactJsonLd(jsonLd, contextLoader) {
5802
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
5803
+ const signature = hasLds ? jsonLd.signature : void 0;
5804
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
5805
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
5806
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
5807
+ const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
5808
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
5809
+ assertSafeJsonLd(compacted);
5810
+ return compacted;
5811
+ }
5812
+ function createInvalidRemoteContextError(reference) {
5813
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${reference}".`);
5814
+ error.name = "jsonld.InvalidUrl";
5815
+ error.details = {
5816
+ code: "invalid remote context",
5817
+ url: reference
5818
+ };
5819
+ return error;
5820
+ }
5821
+ function getRemoteContext(remoteDocument, reference) {
5822
+ const { contextUrl, documentUrl } = remoteDocument;
5823
+ let { document } = remoteDocument;
5824
+ if (typeof document === "string") document = JSON.parse(document);
5825
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
5826
+ let context = "@context" in document ? document["@context"] : {};
5827
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
5828
+ return {
5829
+ context,
5830
+ baseUrl: documentUrl ?? reference
5831
+ };
5832
+ }
5833
+ function createGraphAliasContextState() {
5834
+ return {
5835
+ graphTerms: /* @__PURE__ */ new Set(),
5836
+ jsonTerms: /* @__PURE__ */ new Set(),
5837
+ propertyContexts: /* @__PURE__ */ new Map(),
5838
+ termTargets: /* @__PURE__ */ new Map()
5839
+ };
5840
+ }
5841
+ function cloneGraphAliasContextState(state) {
5842
+ return {
5843
+ graphTerms: new Set(state.graphTerms),
5844
+ jsonTerms: new Set(state.jsonTerms),
5845
+ propertyContexts: new Map(state.propertyContexts),
5846
+ termTargets: new Map(state.termTargets)
5847
+ };
5848
+ }
5849
+ function resolveContextTarget(target, state) {
5850
+ if (target === "@graph") return target;
5851
+ const mapped = state.termTargets.get(target);
5852
+ if (mapped == null) return target;
5853
+ return mapped;
5854
+ }
5855
+ function getDirectContextTarget(definition) {
5856
+ if (definition === null) return null;
5857
+ if (typeof definition === "string") return definition;
5858
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
5859
+ const id = definition["@id"];
5860
+ if (id === null) return null;
5861
+ if (typeof id === "string") return id;
5862
+ }
5863
+ }
5864
+ function isJsonTypedDefinition(definition) {
5865
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
5866
+ }
5867
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
5868
+ if (target === "@graph") return target;
5869
+ if (seen.has(target)) return target;
5870
+ seen.add(target);
5871
+ if (localTargets.has(target)) {
5872
+ const localTarget = localTargets.get(target);
5873
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
5874
+ }
5875
+ return resolveContextTarget(target, state);
5876
+ }
5877
+ function refreshGraphAliases(state) {
5878
+ state.graphTerms.clear();
5879
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
5880
+ }
5881
+ function normalizeContextReference(reference, baseUrl) {
5882
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
5883
+ return URL.canParse(reference) ? new URL(reference).href : reference;
5884
+ }
5885
+ /** @internal */
5886
+ function isInvalidUrlTypeError(error) {
5887
+ const code = error.code;
5888
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
5889
+ }
5890
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
5891
+ if (context === null) return createGraphAliasContextState();
5892
+ let nextState = cloneGraphAliasContextState(state);
5893
+ if (Array.isArray(context)) {
5894
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
5895
+ return nextState;
5896
+ }
5897
+ if (typeof context === "string") {
5898
+ const reference = normalizeContextReference(context, baseUrl);
5899
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
5900
+ if (processingContexts.has(cacheKey)) return nextState;
5901
+ processingContexts.add(cacheKey);
5902
+ try {
5903
+ let remoteContext = remoteContextCache.get(cacheKey);
5904
+ if (remoteContext == null) {
5905
+ remoteContext = (async () => {
5906
+ try {
5907
+ return getRemoteContext(await documentLoader(reference), reference);
5908
+ } catch (error) {
5909
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
5910
+ throw error;
5911
+ }
5912
+ })();
5913
+ remoteContextCache.set(cacheKey, remoteContext);
5914
+ }
5915
+ const loadedRemoteContext = await remoteContext;
5916
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
5917
+ } finally {
5918
+ processingContexts.delete(cacheKey);
5919
+ }
5920
+ }
5921
+ if (typeof context === "object" && context != null) {
5922
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
5923
+ const localTargets = /* @__PURE__ */ new Map();
5924
+ for (const [term, definition] of globalThis.Object.entries(context)) {
5925
+ if (term.startsWith("@")) continue;
5926
+ const target = getDirectContextTarget(definition);
5927
+ if (target == null) localTargets.set(term, null);
5928
+ else if (typeof target === "string") localTargets.set(term, target);
5929
+ else localTargets.delete(term);
5930
+ }
5931
+ for (const [term, definition] of globalThis.Object.entries(context)) {
5932
+ if (term.startsWith("@")) continue;
5933
+ if (localTargets.has(term)) {
5934
+ const directTarget = localTargets.get(term);
5935
+ if (directTarget == null) nextState.termTargets.set(term, null);
5936
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
5937
+ } else nextState.termTargets.delete(term);
5938
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
5939
+ context: definition["@context"],
5940
+ baseUrl
5941
+ });
5942
+ else nextState.propertyContexts.delete(term);
5943
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
5944
+ else nextState.jsonTerms.delete(term);
5945
+ }
5946
+ refreshGraphAliases(nextState);
5947
+ }
5948
+ return nextState;
5949
+ }
5950
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
5951
+ if (Array.isArray(jsonLd)) {
5952
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
5953
+ return;
5954
+ }
5955
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
5956
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
5957
+ let state = inheritedState;
5958
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
5959
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
5960
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
5961
+ if (key === "@context") continue;
5962
+ if (jsonLiteralWrapper && key === "@value") continue;
5963
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
5964
+ if (state.jsonTerms.has(key)) continue;
5965
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
5966
+ }
5967
+ }
5968
+ function isJsonLiteralWrapper(value) {
5969
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
5970
+ }
5971
+ /** @internal */
5972
+ function assertSafeJsonLd(jsonLd) {
5973
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
5974
+ else if (typeof jsonLd === "object" && jsonLd != null) {
5975
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
5976
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
5977
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
5978
+ if (jsonLiteralWrapper && key === "@value") continue;
5979
+ assertSafeJsonLd(value);
5980
+ }
5981
+ }
5982
+ }
5136
5983
  /**
5137
- * Signs a request using the given private key.
5138
- * @param request The request to sign.
5139
- * @param privateKey The private key to use for signing.
5140
- * @param keyId The key ID to use for the signature. It will be used by the
5141
- * verifier.
5142
- * @returns The signed request.
5984
+ * Attaches a LD signature to the given JSON-LD document.
5985
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
5986
+ * modified.
5987
+ * @param signature The signature to attach.
5988
+ * @returns The JSON-LD document with the attached signature.
5989
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
5990
+ * @since 1.0.0
5991
+ */
5992
+ function attachSignature(jsonLd, signature) {
5993
+ if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
5994
+ return {
5995
+ ...jsonLd,
5996
+ signature
5997
+ };
5998
+ }
5999
+ /**
6000
+ * Creates a LD signature for the given JSON-LD document.
6001
+ * @param jsonLd The JSON-LD document to sign.
6002
+ * @param privateKey The private key to sign the document.
6003
+ * @param keyId The ID of the public key that corresponds to the private key.
6004
+ * @param options Additional options for creating the signature.
6005
+ * See also {@link CreateSignatureOptions}.
6006
+ * @return The created signature.
5143
6007
  * @throws {TypeError} If the private key is invalid or unsupported.
6008
+ * @since 1.0.0
5144
6009
  */
5145
- async function signRequest(request, privateKey, keyId, options = {}) {
6010
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
5146
6011
  validateCryptoKey(privateKey, "private");
5147
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("http_signatures.sign", async (span) => {
6012
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
6013
+ const options = {
6014
+ "@context": "https://w3id.org/identity/v1",
6015
+ creator: keyId.href,
6016
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
6017
+ };
6018
+ const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
6019
+ const messageBytes = new TextEncoder().encode(message);
6020
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
6021
+ return {
6022
+ ...options,
6023
+ type: "RsaSignature2017",
6024
+ signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
6025
+ };
6026
+ }
6027
+ /**
6028
+ * Signs the given JSON-LD document with the private key and returns the signed
6029
+ * JSON-LD document.
6030
+ * @param jsonLd The JSON-LD document to sign.
6031
+ * @param privateKey The private key to sign the document.
6032
+ * @param keyId The key ID to use in the signature. It will be used by the
6033
+ * verifier to fetch the corresponding public key.
6034
+ * @param options Additional options for signing the document.
6035
+ * See also {@link SignJsonLdOptions}.
6036
+ * @returns The signed JSON-LD document.
6037
+ * @throws {TypeError} If the private key is invalid or unsupported.
6038
+ * @since 1.0.0
6039
+ */
6040
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
6041
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
5148
6042
  try {
5149
- const spec = options.spec ?? "draft-cavage-http-signatures-12";
5150
- let signed;
5151
- if (spec === "rfc9421") signed = await signRequestRfc9421(request, privateKey, keyId, span, options.currentTime, options.body, options.rfc9421);
5152
- else signed = await signRequestDraft(request, privateKey, keyId, span, options.currentTime, options.body);
6043
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
5153
6044
  if (span.isRecording()) {
5154
- span.setAttribute(_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD, signed.method);
5155
- span.setAttribute(_opentelemetry_semantic_conventions.ATTR_URL_FULL, signed.url);
5156
- for (const [name, value] of signed.headers) span.setAttribute((0, _opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_HEADER)(name), value);
5157
- span.setAttribute("http_signatures.key_id", keyId.href);
6045
+ span.setAttribute("ld_signatures.type", signature.type);
6046
+ span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
5158
6047
  }
5159
- return signed;
6048
+ return attachSignature(jsonLd, signature);
5160
6049
  } catch (error) {
5161
6050
  span.setStatus({
5162
6051
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -5168,23 +6057,1564 @@ async function signRequest(request, privateKey, keyId, options = {}) {
5168
6057
  }
5169
6058
  });
5170
6059
  }
5171
- async function signRequestDraft(request, privateKey, keyId, span, currentTime, bodyBuffer) {
5172
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
5173
- const url = new URL(request.url);
5174
- const body = bodyBuffer !== void 0 ? bodyBuffer : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
5175
- const headers = new Headers(request.headers);
5176
- if (!headers.has("Host")) headers.set("Host", url.host);
5177
- if (!headers.has("Digest") && body != null) {
5178
- const digest = await crypto.subtle.digest("SHA-256", body);
5179
- headers.set("Digest", `SHA-256=${(0, byte_encodings_base64.encodeBase64)(digest)}`);
5180
- if (span.isRecording()) span.setAttribute("http_signatures.digest.sha-256", (0, byte_encodings_hex.encodeHex)(digest));
6060
+ /**
6061
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
6062
+ * object, without restricting it to a single suite-specific shape.
6063
+ * @param jsonLd The JSON-LD document to check.
6064
+ * @returns `true` if the document has a signature-like object; `false`
6065
+ * otherwise.
6066
+ * @since 2.2.0
6067
+ */
6068
+ function hasSignatureLike(jsonLd) {
6069
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
6070
+ const signature = jsonLd.signature;
6071
+ const hasReference = (value) => {
6072
+ if (typeof value === "string") return true;
6073
+ if (Array.isArray(value)) return value.some(hasReference);
6074
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
6075
+ };
6076
+ const hasSignatureObject = (value) => {
6077
+ if (typeof value !== "object" || value == null) return false;
6078
+ const signatureRecord = value;
6079
+ return (typeof signatureRecord.type === "string" || Array.isArray(signatureRecord.type) && signatureRecord.type.some((item) => typeof item === "string")) && (hasReference(signatureRecord.creator) || hasReference(signatureRecord.verificationMethod)) && (typeof signatureRecord.signatureValue === "string" || typeof signatureRecord.jws === "string");
6080
+ };
6081
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
6082
+ }
6083
+ /**
6084
+ * Checks if the given JSON-LD document has a Linked Data Signature.
6085
+ * @param jsonLd The JSON-LD document to check.
6086
+ * @returns `true` if the document has a signature; `false` otherwise.
6087
+ * @since 1.0.0
6088
+ */
6089
+ function hasSignature(jsonLd) {
6090
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
6091
+ if ("signature" in jsonLd) {
6092
+ const signature = jsonLd.signature;
6093
+ if (typeof signature !== "object" || signature == null) return false;
6094
+ return "type" in signature && signature.type === "RsaSignature2017" && "creator" in signature && typeof signature.creator === "string" && "created" in signature && typeof signature.created === "string" && "signatureValue" in signature && typeof signature.signatureValue === "string";
5181
6095
  }
5182
- if (!headers.has("Date")) headers.set("Date", currentTime == null ? (/* @__PURE__ */ new Date()).toUTCString() : new Date(currentTime.toString()).toUTCString());
5183
- const serialized = [["(request-target)", `${request.method.toLowerCase()} ${url.pathname}`], ...headers];
5184
- const headerNames = serialized.map(([name]) => name);
5185
- const message = serialized.map(([name, value]) => `${name}: ${value.trim()}`).join("\n");
5186
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, new TextEncoder().encode(message));
5187
- const sigHeader = `keyId="${keyId.href}",algorithm="rsa-sha256",headers="${headerNames.join(" ")}",signature="${(0, byte_encodings_base64.encodeBase64)(signature)}"`;
6096
+ return false;
6097
+ }
6098
+ /**
6099
+ * Detaches Linked Data Signatures from the given JSON-LD document.
6100
+ * @param jsonLd The JSON-LD document to modify.
6101
+ * @returns The modified JSON-LD document. If the input document does not
6102
+ * contain a signature, the original document is returned.
6103
+ * @since 1.0.0
6104
+ */
6105
+ function detachSignature(jsonLd) {
6106
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
6107
+ const doc = { ...jsonLd };
6108
+ delete doc.signature;
6109
+ return doc;
6110
+ }
6111
+ /**
6112
+ * Verifies Linked Data Signatures of the given JSON-LD document.
6113
+ *
6114
+ * This is a low-level utility that only checks the cryptographic signature
6115
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
6116
+ * attribution, and owner checks that a complete inbound LD verification
6117
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
6118
+ * the public verification entry point and the one that emits the
6119
+ * `activitypub.signature.verification.duration` metric for the LD path.
6120
+ * `verifySignature` itself only emits
6121
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
6122
+ * that the verification-duration metric is meant to cover happens in
6123
+ * `verifyJsonLd`.
6124
+ * @param jsonLd The JSON-LD document to verify.
6125
+ * @param options Options for verifying the signature.
6126
+ * @returns The public key that signed the document or `null` if the signature
6127
+ * is invalid or the key is not found.
6128
+ * @since 1.0.0
6129
+ */
6130
+ async function verifySignature(jsonLd, options = {}) {
6131
+ if (!hasSignature(jsonLd)) return null;
6132
+ const sig = jsonLd.signature;
6133
+ let signature;
6134
+ try {
6135
+ signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
6136
+ } catch (error) {
6137
+ logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
6138
+ ...sig,
6139
+ error
6140
+ });
6141
+ return null;
6142
+ }
6143
+ const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options));
6144
+ if (key == null) return null;
6145
+ const sigOpts = {
6146
+ ...sig,
6147
+ "@context": "https://w3id.org/identity/v1"
6148
+ };
6149
+ delete sigOpts.type;
6150
+ delete sigOpts.id;
6151
+ delete sigOpts.signatureValue;
6152
+ let sigOptsHash;
6153
+ try {
6154
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
6155
+ } catch (error) {
6156
+ logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
6157
+ signatureOptions: sigOpts,
6158
+ error
6159
+ });
6160
+ return null;
6161
+ }
6162
+ const document = { ...jsonLd };
6163
+ delete document.signature;
6164
+ let docHash;
6165
+ try {
6166
+ docHash = await hashJsonLd(document, options.contextLoader);
6167
+ } catch (error) {
6168
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
6169
+ document,
6170
+ error
6171
+ });
6172
+ return null;
6173
+ }
6174
+ const encoder = new TextEncoder();
6175
+ const message = sigOptsHash + docHash;
6176
+ const messageBytes = encoder.encode(message);
6177
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
6178
+ if (cached) {
6179
+ logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
6180
+ keyId: sig.creator,
6181
+ ...sig
6182
+ });
6183
+ const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
6184
+ ...options,
6185
+ keyCache: {
6186
+ get: () => Promise.resolve(void 0),
6187
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
6188
+ }
6189
+ }));
6190
+ if (key == null) return null;
6191
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
6192
+ }
6193
+ logger$2.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
6194
+ keyId: sig.creator,
6195
+ ...sig,
6196
+ message
6197
+ });
6198
+ return null;
6199
+ }
6200
+ /**
6201
+ * Known Linked Data Signature `type` values, used to keep
6202
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
6203
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
6204
+ * only from external documents and are dropped from the metric attribute to
6205
+ * avoid attacker-controlled cardinality.
6206
+ */
6207
+ const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
6208
+ /**
6209
+ * Reports only whether a `signature` key is present on the document, with
6210
+ * no shape check on its value. This is intentionally looser than
6211
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
6212
+ * and {@link hasSignatureLike} (which structurally accepts several known
6213
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
6214
+ * unsupported signature payload (classified as `rejected`) apart from a
6215
+ * truly unsigned document (classified as `missing`), and only this
6216
+ * presence-only check captures both cases.
6217
+ */
6218
+ function hasLdSignatureProperty(jsonLd) {
6219
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
6220
+ }
6221
+ function getLdSignatureObject(jsonLd) {
6222
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
6223
+ const { signature } = jsonLd;
6224
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
6225
+ return signature;
6226
+ }
6227
+ /**
6228
+ * Verify the authenticity of the given JSON-LD document using Linked Data
6229
+ * Signatures. If the document is signed, this function verifies the signature
6230
+ * and checks if the document is attributed to the owner of the public key.
6231
+ * If the document is not signed, this function returns `false`.
6232
+ * @param jsonLd The JSON-LD document to verify.
6233
+ * @param options Options for verifying the document.
6234
+ * @returns `true` if the document is authentic; `false` otherwise.
6235
+ */
6236
+ async function verifyJsonLd(jsonLd, options = {}) {
6237
+ return await verifyJsonLdInternal(jsonLd, options, true);
6238
+ }
6239
+ /** @internal */
6240
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
6241
+ return await verifyJsonLdInternal(jsonLd, options, false);
6242
+ }
6243
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
6244
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
6245
+ const start = performance.now();
6246
+ let verified = false;
6247
+ let threw = false;
6248
+ let signatureType;
6249
+ try {
6250
+ const verificationOptions = hasSignature(jsonLd) ? {
6251
+ ...options,
6252
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
6253
+ } : options;
6254
+ const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
6255
+ const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
6256
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
6257
+ span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
6258
+ const sig = getLdSignatureObject(jsonLd);
6259
+ if (sig != null) {
6260
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
6261
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
6262
+ if (typeof sig.type === "string") {
6263
+ span.setAttribute("ld_signatures.type", sig.type);
6264
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
6265
+ }
6266
+ }
6267
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
6268
+ if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
6269
+ const key = await verifySignature(compacted, verificationOptions);
6270
+ if (key == null) return false;
6271
+ if (key.ownerId == null) {
6272
+ logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
6273
+ return false;
6274
+ }
6275
+ attributions.delete(key.ownerId.href);
6276
+ if (attributions.size > 0) {
6277
+ logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
6278
+ return false;
6279
+ }
6280
+ verified = true;
6281
+ return true;
6282
+ } catch (error) {
6283
+ threw = true;
6284
+ span.setStatus({
6285
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
6286
+ message: String(error)
6287
+ });
6288
+ throw error;
6289
+ } finally {
6290
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
6291
+ getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
6292
+ span.end();
6293
+ }
6294
+ });
6295
+ }
6296
+ async function hashJsonLd(jsonLd, contextLoader) {
6297
+ const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
6298
+ format: "application/n-quads",
6299
+ documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
6300
+ });
6301
+ const encoder = new TextEncoder();
6302
+ return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
6303
+ }
6304
+ //#endregion
6305
+ //#region src/sig/proof.ts
6306
+ const Temporal$1 = Temporal$2;
6307
+ /**
6308
+ * Known Object Integrity Proof `cryptosuite` values, used to keep
6309
+ * `object_integrity_proofs.cryptosuite` on a bounded set of spec-defined
6310
+ * string values. Fedify currently signs and verifies only
6311
+ * `eddsa-jcs-2022`; other values come in only from external proofs and are
6312
+ * dropped from the metric attribute to avoid attacker-controlled
6313
+ * cardinality.
6314
+ */
6315
+ const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
6316
+ const logger$1 = (0, _logtape_logtape.getLogger)([
6317
+ "fedify",
6318
+ "sig",
6319
+ "proof"
6320
+ ]);
6321
+ const SECURITY_NAMESPACE = "https://w3id.org/security#";
6322
+ const SECURITY_PROOF = `${SECURITY_NAMESPACE}proof`;
6323
+ const SECURITY_PROOF_VALUE = `${SECURITY_NAMESPACE}proofValue`;
6324
+ const DATA_INTEGRITY_PROOF = `${SECURITY_NAMESPACE}DataIntegrityProof`;
6325
+ const SECURITY_VERIFICATION_METHOD = `${SECURITY_NAMESPACE}verificationMethod`;
6326
+ const SECURITY_EXPIRATION = `${SECURITY_NAMESPACE}expiration`;
6327
+ const SECURITY_DOMAIN = `${SECURITY_NAMESPACE}domain`;
6328
+ const SECURITY_CHALLENGE = `${SECURITY_NAMESPACE}challenge`;
6329
+ const SECURITY_NONCE = `${SECURITY_NAMESPACE}nonce`;
6330
+ const SECURITY_PREVIOUS_PROOF = `${SECURITY_NAMESPACE}previousProof`;
6331
+ /**
6332
+ * Checks if the given JSON-LD document has a DataIntegrityProof-like object,
6333
+ * without fully deserializing it into vocabulary classes.
6334
+ * @param jsonLd The JSON-LD document to check.
6335
+ * @returns `true` if the document has a proof-like object; `false` otherwise.
6336
+ * @since 2.2.0
6337
+ */
6338
+ function hasProofLike(jsonLd) {
6339
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
6340
+ const record = jsonLd;
6341
+ const proof = record.proof ?? record["https://w3id.org/security#proof"];
6342
+ const getField = (source, compact, expanded) => source[compact] ?? source[expanded];
6343
+ const isReference = (value) => {
6344
+ if (typeof value === "string") return true;
6345
+ if (Array.isArray(value)) return value.some(isReference);
6346
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string" || "@value" in value && typeof value["@value"] === "string");
6347
+ };
6348
+ const hasType = (value) => {
6349
+ if (typeof value === "string") return value === "DataIntegrityProof" || value === "https://w3id.org/security#DataIntegrityProof";
6350
+ if (Array.isArray(value)) return value.some(hasType);
6351
+ return false;
6352
+ };
6353
+ const isProofLike = (value) => {
6354
+ if (typeof value !== "object" || value == null) return false;
6355
+ const proofRecord = value;
6356
+ return hasType(proofRecord.type ?? proofRecord["@type"]) && isReference(getField(proofRecord, "verificationMethod", "https://w3id.org/security#verificationMethod")) && isReference(getField(proofRecord, "proofPurpose", "https://w3id.org/security#proofPurpose")) && isReference(getField(proofRecord, "proofValue", "https://w3id.org/security#proofValue"));
6357
+ };
6358
+ return Array.isArray(proof) ? proof.some(isProofLike) : isProofLike(proof);
6359
+ }
6360
+ function isJsonMap(value) {
6361
+ return typeof value === "object" && value != null && !Array.isArray(value);
6362
+ }
6363
+ /**
6364
+ * Assembles the secured JSON document from the bytes that were just signed.
6365
+ *
6366
+ * The document is not re-derived from the vocabulary object: it is
6367
+ * `compactMsg`, the value whose JCS form was hashed, with the serialized
6368
+ * proof added. Every part of it is then checked against the digests and the
6369
+ * signature that {@link createProofInternal} produced, so a document that is
6370
+ * returned verifies under the map-local compound-proof profile by
6371
+ * construction. Anything that does not check out yields `null`, and the
6372
+ * caller simply does not retain a representation.
6373
+ */
6374
+ async function captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, proofValue, contextLoader) {
6375
+ if (!isJsonMap(compactMsg)) return null;
6376
+ const documentContext = compactMsg["@context"];
6377
+ if (documentContext == null) return null;
6378
+ if (globalThis.Object.hasOwn(compactMsg, "proof")) return null;
6379
+ try {
6380
+ const proofJson = await proof.toJsonLd({
6381
+ format: "compact",
6382
+ contextLoader,
6383
+ context: documentContext
6384
+ });
6385
+ if (!isJsonMap(proofJson)) return null;
6386
+ const { proofValue: serializedProofValue, ...proofConfiguration } = proofJson;
6387
+ if (serializedProofValue !== proofValue) return null;
6388
+ if ((0, json_canon.default)(proofConfiguration) !== proofCanon) return null;
6389
+ const securedDocument = {
6390
+ ...structuredClone(compactMsg),
6391
+ proof: structuredClone(proofJson)
6392
+ };
6393
+ const { proof: _embeddedProof, ...unsecuredDocument } = securedDocument;
6394
+ if ((0, json_canon.default)(unsecuredDocument) !== msgCanon) return null;
6395
+ if (!(0, _fedify_vocab_runtime_internal_signed_representation.isPlainJsonTree)(securedDocument)) return null;
6396
+ return securedDocument;
6397
+ } catch (error) {
6398
+ logger$1.debug("Failed to capture the secured JSON document for a created proof; the signed object will not preserve its representation when it is embedded in another object.\n{error}", { error });
6399
+ return null;
6400
+ }
6401
+ }
6402
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}, capture = false) {
6403
+ validateCryptoKey(privateKey, "private");
6404
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
6405
+ let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
6406
+ format: "compact",
6407
+ contextLoader,
6408
+ context
6409
+ });
6410
+ compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader, { preserveNestedSecuredDocuments: true });
6411
+ const msgCanon = (0, json_canon.default)(compactMsg);
6412
+ const encoder = new TextEncoder();
6413
+ const msgBytes = encoder.encode(msgCanon);
6414
+ const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
6415
+ created ??= Temporal$1.Now.instant();
6416
+ const proofCanon = (0, json_canon.default)({
6417
+ "@context": compactMsg["@context"],
6418
+ type: "DataIntegrityProof",
6419
+ cryptosuite: "eddsa-jcs-2022",
6420
+ verificationMethod: keyId.href,
6421
+ proofPurpose: "assertionMethod",
6422
+ created: created.toString()
6423
+ });
6424
+ const proofBytes = encoder.encode(proofCanon);
6425
+ const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
6426
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
6427
+ digest.set(new Uint8Array(proofDigest), 0);
6428
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
6429
+ const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", privateKey, digest));
6430
+ const proof = new _fedify_vocab.DataIntegrityProof({
6431
+ cryptosuite: "eddsa-jcs-2022",
6432
+ verificationMethod: keyId,
6433
+ proofPurpose: "assertionMethod",
6434
+ created,
6435
+ proofValue: sig
6436
+ });
6437
+ return {
6438
+ proof,
6439
+ securedDocument: capture ? await captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, new TextDecoder().decode((0, _fedify_vocab_runtime.encodeMultibase)("base58btc", sig)), contextLoader) : null
6440
+ };
6441
+ }
6442
+ /**
6443
+ * Creates a proof for the given object.
6444
+ * @param object The object to create a proof for.
6445
+ * @param privateKey The private key to sign the proof with.
6446
+ * @param keyId The key ID to use in the proof. It will be used by the verifier.
6447
+ * @param options Additional options. See also {@link CreateProofOptions}.
6448
+ * @returns The created proof.
6449
+ * @throws {TypeError} If the private key is invalid or unsupported.
6450
+ * @since 0.10.0
6451
+ */
6452
+ async function createProof(object, privateKey, keyId, options = {}) {
6453
+ const { proof } = await createProofInternal(object, privateKey, keyId, options);
6454
+ return proof;
6455
+ }
6456
+ /**
6457
+ * Signs the given object with the private key and returns the signed object.
6458
+ * @param object The object to create a proof for.
6459
+ * @param privateKey The private key to sign the proof with.
6460
+ * @param keyId The key ID to use in the proof. It will be used by the verifier.
6461
+ * @param options Additional options. See also {@link SignObjectOptions}.
6462
+ * @returns The signed object.
6463
+ * @throws {TypeError} If the private key is invalid or unsupported.
6464
+ * @since 0.10.0
6465
+ */
6466
+ async function signObject(object, privateKey, keyId, options = {}) {
6467
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(object).href } }, async (span) => {
6468
+ try {
6469
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
6470
+ const existingProofs = [];
6471
+ for await (const proof of object.getProofs(options)) existingProofs.push(proof);
6472
+ const { proof, securedDocument } = await createProofInternal(object, privateKey, keyId, options, existingProofs.length < 1);
6473
+ if (span.isRecording()) {
6474
+ if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
6475
+ if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
6476
+ if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
6477
+ }
6478
+ const signed = object.clone({ proofs: [...existingProofs, proof] });
6479
+ if (securedDocument != null) (0, _fedify_vocab_runtime_internal_signed_representation.retainSignedRepresentation)(signed, securedDocument);
6480
+ else if (existingProofs.length > 0) logger$1.debug("The object {objectId} already had {proofCount} proof(s), so its signed representation is not retained for embedding; the map-local compound-proof profile accepts exactly one direct proof per map.", {
6481
+ objectId: object.id?.href,
6482
+ proofCount: existingProofs.length
6483
+ });
6484
+ return signed;
6485
+ } catch (error) {
6486
+ span.setStatus({
6487
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
6488
+ message: String(error)
6489
+ });
6490
+ throw error;
6491
+ } finally {
6492
+ span.end();
6493
+ }
6494
+ });
6495
+ }
6496
+ /**
6497
+ * Verifies the given proof for the object.
6498
+ * @param jsonLd The JSON-LD object to verify the proof for. Its proof
6499
+ * properties are excluded from the message, but matching proof
6500
+ * occurrences are used to authenticate the received proof
6501
+ * configuration.
6502
+ * @param proof The proof to verify.
6503
+ * @param options Additional options. See also {@link VerifyProofOptions}.
6504
+ * @returns The public key that was used to sign the proof, or `null` if the
6505
+ * proof is invalid.
6506
+ * @since 0.10.0
6507
+ * @since 2.4.0 Matching proof configurations are authenticated.
6508
+ */
6509
+ async function verifyProof(jsonLd, proof, options = {}) {
6510
+ return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
6511
+ }
6512
+ /**
6513
+ * Verifies the one direct literal proof on a map-local secured document.
6514
+ *
6515
+ * Unlike {@link verifyProof}, this removes only the literal `proof` member
6516
+ * from the message digest. JSON-LD aliases remain part of the signed input,
6517
+ * and the document's received `@context` is not replaced by the proof
6518
+ * configuration context.
6519
+ *
6520
+ * @internal
6521
+ */
6522
+ async function verifyMapLocalProof(jsonLd, options = {}) {
6523
+ if (!isJsonLdNode(jsonLd) || !globalThis.Object.hasOwn(jsonLd, "proof") || !isJsonLdNode(jsonLd.proof)) return null;
6524
+ const proofContextLoader = getNormalizationContextLoader(preloadedOnlyDocumentLoader);
6525
+ try {
6526
+ const [candidate] = await parseRawProofCandidates(jsonLd, [jsonLd.proof], options, proofContextLoader);
6527
+ if (candidate.proof == null) return null;
6528
+ return await verifyProofWithMessageDigestCache(jsonLd, candidate.proof, options, {
6529
+ proofContextLoader,
6530
+ proofPropertyMode: "literal"
6531
+ }, candidate);
6532
+ } catch {
6533
+ return null;
6534
+ }
6535
+ }
6536
+ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
6537
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
6538
+ const start = performance.now();
6539
+ let verified = false;
6540
+ let threw = false;
6541
+ const cryptosuite = proof.cryptosuite != null && OIP_KNOWN_CRYPTOSUITES.has(proof.cryptosuite) ? proof.cryptosuite : void 0;
6542
+ if (span.isRecording()) {
6543
+ if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
6544
+ if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
6545
+ if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
6546
+ }
6547
+ try {
6548
+ const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
6549
+ if (key == null) span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
6550
+ else verified = true;
6551
+ return key;
6552
+ } catch (error) {
6553
+ threw = true;
6554
+ span.setStatus({
6555
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
6556
+ message: String(error)
6557
+ });
6558
+ throw error;
6559
+ } finally {
6560
+ const classified = threw ? "error" : verified ? "verified" : "rejected";
6561
+ getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "object_integrity", classified, { cryptosuite });
6562
+ span.end();
6563
+ }
6564
+ });
6565
+ }
6566
+ function expandContextPropertyIri(activeContext, key) {
6567
+ const termId = _fedify_vocab_runtime_jsonld.default.getContextValue(activeContext, key, "@id");
6568
+ if (termId != null) return termId;
6569
+ const colon = key.indexOf(":");
6570
+ if (colon < 1) return key;
6571
+ const prefix = key.substring(0, colon);
6572
+ const suffix = key.substring(colon + 1);
6573
+ if (prefix === "_" || suffix.startsWith("//")) return key;
6574
+ const mapping = _fedify_vocab_runtime_jsonld.default.getContextValue(activeContext, prefix);
6575
+ if (typeof mapping === "object" && mapping != null && mapping._prefix === true && typeof mapping["@id"] === "string") return mapping["@id"] + suffix;
6576
+ return key;
6577
+ }
6578
+ async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoader = preloadedOnlyDocumentLoader, inheritedContext, rejectOnContextError = false) {
6579
+ const names = new Set(defaults);
6580
+ const context = jsonLd["@context"] ?? inheritedContext;
6581
+ if (context == null) return names;
6582
+ try {
6583
+ const options = { documentLoader };
6584
+ let activeContext = await _fedify_vocab_runtime_jsonld.default.processContext(null, null, options);
6585
+ activeContext = await _fedify_vocab_runtime_jsonld.default.processContext(activeContext, context, options);
6586
+ const typeScopedContext = activeContext;
6587
+ for (const key of globalThis.Object.keys(jsonLd).sort()) {
6588
+ if (key !== "@type" && expandContextPropertyIri(activeContext, key) !== "@type") continue;
6589
+ const value = jsonLd[key];
6590
+ const types = Array.isArray(value) ? value.slice().sort() : [value];
6591
+ for (const type of types) {
6592
+ if (typeof type !== "string") continue;
6593
+ const scopedContext = _fedify_vocab_runtime_jsonld.default.getContextValue(typeScopedContext, type, "@context");
6594
+ if (scopedContext != null) activeContext = await _fedify_vocab_runtime_jsonld.default.processContext(activeContext, scopedContext, options);
6595
+ }
6596
+ }
6597
+ for (const key of globalThis.Object.keys(jsonLd)) if (expandContextPropertyIri(activeContext, key) === propertyIri) names.add(key);
6598
+ } catch {
6599
+ if (rejectOnContextError) return null;
6600
+ }
6601
+ return names;
6602
+ }
6603
+ async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
6604
+ return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
6605
+ }
6606
+ async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
6607
+ const msg = { ...jsonLd };
6608
+ if (proofPropertyMode === "literal") delete msg.proof;
6609
+ else for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
6610
+ if (proofPropertyMode === "jsonLd" && context != null) msg["@context"] = structuredClone(context);
6611
+ const encoder = new TextEncoder();
6612
+ const digest = async (value) => {
6613
+ const bytes = encoder.encode((0, json_canon.default)(value));
6614
+ return await crypto.subtle.digest("SHA-256", bytes);
6615
+ };
6616
+ const onWire = await digest(msg);
6617
+ let normalizedPromise;
6618
+ return {
6619
+ onWire,
6620
+ normalized() {
6621
+ normalizedPromise ??= (async () => {
6622
+ const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
6623
+ return normalized === msg ? null : await digest(normalized);
6624
+ })();
6625
+ return normalizedPromise;
6626
+ }
6627
+ };
6628
+ }
6629
+ function contextValues(context) {
6630
+ return Array.isArray(context) ? context : [context];
6631
+ }
6632
+ function equalJsonValues(left, right) {
6633
+ try {
6634
+ return (0, json_canon.default)(left) === (0, json_canon.default)(right);
6635
+ } catch {
6636
+ return false;
6637
+ }
6638
+ }
6639
+ function contextStartsWith(documentContext, proofContext) {
6640
+ if (documentContext == null) return false;
6641
+ const documentValues = contextValues(documentContext);
6642
+ const proofValues = contextValues(proofContext);
6643
+ return proofValues.length <= documentValues.length && proofValues.every((value, index) => equalJsonValues(value, documentValues[index]));
6644
+ }
6645
+ function appendProofValues(values, value) {
6646
+ if (Array.isArray(value)) for (const item of value) appendProofValues(values, item);
6647
+ else if (isJsonLdNode(value) && Array.isArray(value["@graph"])) for (const item of value["@graph"]) appendProofValues(values, item);
6648
+ else values.push(value);
6649
+ }
6650
+ async function getRawProofValues(jsonLd, documentLoader) {
6651
+ const propertyNames = await getProofPropertyNames(jsonLd, documentLoader);
6652
+ const values = [];
6653
+ for (const [property, value] of globalThis.Object.entries(jsonLd)) if (propertyNames.has(property)) appendProofValues(values, value);
6654
+ return values;
6655
+ }
6656
+ function sameBytes(left, right) {
6657
+ if (left == null || right == null) return left === right;
6658
+ return left.length === right.length && left.every((value, index) => value === right[index]);
6659
+ }
6660
+ function sameProof(left, right) {
6661
+ return left.cryptosuite === right.cryptosuite && left.verificationMethodId?.href === right.verificationMethodId?.href && left.proofPurpose === right.proofPurpose && sameBytes(left.proofValue, right.proofValue) && left.created?.toString() === right.created?.toString();
6662
+ }
6663
+ function normalizeDocumentUrl(url) {
6664
+ try {
6665
+ return (0, _fedify_vocab_runtime.formatIri)((0, _fedify_vocab_runtime.parseIri)(url));
6666
+ } catch {
6667
+ return URL.canParse(url) ? new URL(url).href : url;
6668
+ }
6669
+ }
6670
+ function getRawProofReference(value) {
6671
+ const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
6672
+ if (typeof node === "string") return normalizeDocumentUrl(node);
6673
+ if (!isJsonLdNode(node)) return void 0;
6674
+ const id = node["@id"] ?? node.id;
6675
+ return typeof id === "string" ? normalizeDocumentUrl(id) : void 0;
6676
+ }
6677
+ async function parseRawProofCandidates(jsonLd, values, options, documentLoader) {
6678
+ const candidates = [];
6679
+ for (const value of values) {
6680
+ let parsed = null;
6681
+ if (isJsonLdNode(value)) {
6682
+ const proofJsonLd = value["@context"] == null && jsonLd["@context"] != null ? {
6683
+ "@context": jsonLd["@context"],
6684
+ ...value
6685
+ } : value;
6686
+ try {
6687
+ parsed = await _fedify_vocab.DataIntegrityProof.fromJsonLd(proofJsonLd, {
6688
+ ...options,
6689
+ contextLoader: documentLoader
6690
+ });
6691
+ } catch {}
6692
+ }
6693
+ candidates.push({
6694
+ value,
6695
+ proof: parsed,
6696
+ reference: getRawProofReference(value) ?? parsed?.id?.href
6697
+ });
6698
+ }
6699
+ return candidates;
6700
+ }
6701
+ async function findRawProofCandidate(jsonLd, proof, options, documentLoader) {
6702
+ const candidates = await parseRawProofCandidates(jsonLd, await getRawProofValues(jsonLd, documentLoader), options, documentLoader);
6703
+ const matches = [];
6704
+ for (const candidate of candidates) if (candidate.proof != null && sameProof(candidate.proof, proof)) matches.push(candidate);
6705
+ if (matches.length < 1) return void 0;
6706
+ const first = matches[0];
6707
+ const configurations = await Promise.all(matches.map((candidate) => normalizeProofConfiguration(candidate.value, jsonLd["@context"], documentLoader)));
6708
+ const firstConfiguration = configurations[0];
6709
+ return firstConfiguration != null && configurations.every((configuration) => configuration != null && equalJsonValues(configuration.value, firstConfiguration.value)) ? first : null;
6710
+ }
6711
+ function takeRawProofCandidate(pool, proof) {
6712
+ for (let index = 0; index < pool.candidates.length; index++) {
6713
+ if (pool.used.has(index)) continue;
6714
+ const candidate = pool.candidates[index];
6715
+ if (candidate.proof != null && sameProof(candidate.proof, proof)) {
6716
+ pool.used.add(index);
6717
+ return candidate;
6718
+ }
6719
+ }
6720
+ }
6721
+ const STANDARD_COMPACT_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
6722
+ "@context",
6723
+ "type",
6724
+ "cryptosuite",
6725
+ "verificationMethod",
6726
+ "proofPurpose",
6727
+ "proofValue",
6728
+ "created"
6729
+ ]);
6730
+ const STANDARD_EXPANDED_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
6731
+ "@context",
6732
+ "@type",
6733
+ `${SECURITY_NAMESPACE}cryptosuite`,
6734
+ SECURITY_VERIFICATION_METHOD,
6735
+ `${SECURITY_NAMESPACE}proofPurpose`,
6736
+ `${SECURITY_NAMESPACE}proofValue`,
6737
+ "http://purl.org/dc/terms/created"
6738
+ ]);
6739
+ function hasAdditionalProofOptions(value) {
6740
+ const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
6741
+ return isJsonLdNode(node) && globalThis.Object.keys(node).some((property) => !STANDARD_COMPACT_PROOF_PROPERTIES.has(property) && !STANDARD_EXPANDED_PROOF_PROPERTIES.has(property));
6742
+ }
6743
+ function isExpandedJsonLdNode(value) {
6744
+ const properties = globalThis.Object.keys(value).filter((key) => !key.startsWith("@"));
6745
+ return properties.length > 0 && properties.every((property) => URL.canParse(property));
6746
+ }
6747
+ async function normalizeProofConfiguration(rawProof, documentContext, documentLoader) {
6748
+ let node = Array.isArray(rawProof) && rawProof.length === 1 ? rawProof[0] : rawProof;
6749
+ if (!isJsonLdNode(node)) return null;
6750
+ if (isExpandedJsonLdNode(node)) {
6751
+ if (documentContext == null) return null;
6752
+ node = await _fedify_vocab_runtime_jsonld.default.compact(node, documentContext, { documentLoader });
6753
+ if (!isJsonLdNode(node)) return null;
6754
+ } else node = structuredClone(node);
6755
+ const receivedContext = node["@context"];
6756
+ if (receivedContext != null && !contextStartsWith(documentContext, receivedContext)) return null;
6757
+ const context = receivedContext ?? documentContext;
6758
+ if (context != null) node["@context"] = structuredClone(context);
6759
+ const proofValueProperties = await getJsonLdPropertyNames(node, SECURITY_PROOF_VALUE, ["proofValue", SECURITY_PROOF_VALUE], documentLoader, context) ?? /* @__PURE__ */ new Set(["proofValue", SECURITY_PROOF_VALUE]);
6760
+ for (const property of proofValueProperties) delete node[property];
6761
+ return {
6762
+ value: node,
6763
+ context
6764
+ };
6765
+ }
6766
+ async function createProofConfiguration(jsonLd, proof, options, documentLoader, rawProofCandidate) {
6767
+ let rawProof;
6768
+ if (rawProofCandidate == null) {
6769
+ const match = await findRawProofCandidate(jsonLd, proof, options, documentLoader);
6770
+ if (match === null) return null;
6771
+ rawProof = match?.value;
6772
+ } else rawProof = rawProofCandidate.value;
6773
+ if (rawProof == null) {
6774
+ const serializedProof = await proof.toJsonLd();
6775
+ if (hasAdditionalProofOptions(serializedProof)) rawProof = serializedProof;
6776
+ }
6777
+ if (rawProof != null) return await normalizeProofConfiguration(rawProof, jsonLd["@context"], documentLoader);
6778
+ const context = jsonLd["@context"];
6779
+ return {
6780
+ value: {
6781
+ ...context == null ? {} : { "@context": context },
6782
+ type: "DataIntegrityProof",
6783
+ cryptosuite: proof.cryptosuite,
6784
+ verificationMethod: proof.verificationMethodId.href,
6785
+ proofPurpose: proof.proofPurpose,
6786
+ created: proof.created.toString()
6787
+ },
6788
+ context
6789
+ };
6790
+ }
6791
+ const KNOWN_PROOF_CONFIGURATION_PROPERTIES = /* @__PURE__ */ new Set([
6792
+ "@context",
6793
+ "@id",
6794
+ "@type",
6795
+ "id",
6796
+ "type",
6797
+ "cryptosuite",
6798
+ `${SECURITY_NAMESPACE}cryptosuite`,
6799
+ "verificationMethod",
6800
+ SECURITY_VERIFICATION_METHOD,
6801
+ "proofPurpose",
6802
+ `${SECURITY_NAMESPACE}proofPurpose`,
6803
+ "created",
6804
+ "http://purl.org/dc/terms/created",
6805
+ "expires",
6806
+ SECURITY_EXPIRATION,
6807
+ "domain",
6808
+ SECURITY_DOMAIN,
6809
+ "challenge",
6810
+ SECURITY_CHALLENGE,
6811
+ "nonce",
6812
+ SECURITY_NONCE,
6813
+ "previousProof",
6814
+ SECURITY_PREVIOUS_PROOF
6815
+ ]);
6816
+ async function getProofOption(proofConfig, propertyIri, defaults, documentLoader) {
6817
+ let names = await getJsonLdPropertyNames(proofConfig, propertyIri, defaults, documentLoader, proofConfig["@context"], true);
6818
+ if (names == null) {
6819
+ if (globalThis.Object.keys(proofConfig).some((property) => !KNOWN_PROOF_CONFIGURATION_PROPERTIES.has(property))) return null;
6820
+ names = new Set(defaults);
6821
+ }
6822
+ const present = globalThis.Object.keys(proofConfig).filter((property) => names.has(property));
6823
+ if (present.length > 1) return null;
6824
+ return present.length < 1 ? { present: false } : {
6825
+ present: true,
6826
+ value: proofConfig[present[0]]
6827
+ };
6828
+ }
6829
+ function parseStringSet(value) {
6830
+ if (typeof value === "string") return /* @__PURE__ */ new Set([value]);
6831
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) return null;
6832
+ return new Set(value);
6833
+ }
6834
+ function equalStringSets(left, right) {
6835
+ return left.size === right.size && [...left].every((value) => right.has(value));
6836
+ }
6837
+ async function hasValidProofOptions(proofConfig, options, documentLoader) {
6838
+ const expires = await getProofOption(proofConfig, SECURITY_EXPIRATION, ["expires", SECURITY_EXPIRATION], documentLoader);
6839
+ if (expires == null) return false;
6840
+ if (expires.present) {
6841
+ if (typeof expires.value !== "string") return false;
6842
+ let expiration;
6843
+ try {
6844
+ expiration = Temporal$1.Instant.from(expires.value);
6845
+ } catch {
6846
+ return false;
6847
+ }
6848
+ if (Temporal$1.Instant.compare(Temporal$1.Now.instant(), expiration) >= 0) return false;
6849
+ }
6850
+ const domain = await getProofOption(proofConfig, SECURITY_DOMAIN, ["domain", SECURITY_DOMAIN], documentLoader);
6851
+ if (domain == null) return false;
6852
+ const proofDomains = domain.present ? parseStringSet(domain.value) : null;
6853
+ if (domain.present && proofDomains == null) return false;
6854
+ if (options.domain != null) {
6855
+ const expectedDomains = parseStringSet(options.domain);
6856
+ if (expectedDomains == null || proofDomains == null || !equalStringSets(proofDomains, expectedDomains)) return false;
6857
+ }
6858
+ const challenge = await getProofOption(proofConfig, SECURITY_CHALLENGE, ["challenge", SECURITY_CHALLENGE], documentLoader);
6859
+ if (challenge == null || challenge.present && typeof challenge.value !== "string" || options.challenge != null && (!challenge.present || challenge.value !== options.challenge)) return false;
6860
+ const nonce = await getProofOption(proofConfig, SECURITY_NONCE, ["nonce", SECURITY_NONCE], documentLoader);
6861
+ if (nonce == null || nonce.present && typeof nonce.value !== "string") return false;
6862
+ const previousProof = await getProofOption(proofConfig, SECURITY_PREVIOUS_PROOF, ["previousProof", SECURITY_PREVIOUS_PROOF], documentLoader);
6863
+ if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return false;
6864
+ return true;
6865
+ }
6866
+ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
6867
+ if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
6868
+ const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
6869
+ const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
6870
+ if (proofConfiguration == null || !await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader)) return null;
6871
+ const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, _fedify_vocab.Multikey, {
6872
+ ...options,
6873
+ keyIdBoundByCaller
6874
+ }));
6875
+ const proofBytes = new TextEncoder().encode((0, json_canon.default)(proofConfiguration.value));
6876
+ const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
6877
+ let fetchedKey;
6878
+ try {
6879
+ fetchedKey = await publicKeyPromise;
6880
+ } catch (error) {
6881
+ logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
6882
+ proof,
6883
+ keyId: proof.verificationMethodId.href,
6884
+ error
6885
+ });
6886
+ return null;
6887
+ }
6888
+ const publicKey = fetchedKey.key;
6889
+ if (publicKey == null) {
6890
+ logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
6891
+ proof,
6892
+ keyId: proof.verificationMethodId.href
6893
+ });
6894
+ return null;
6895
+ }
6896
+ if (publicKey.publicKey.algorithm.name !== "Ed25519") {
6897
+ if (fetchedKey.cached) {
6898
+ logger$1.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
6899
+ proof,
6900
+ keyId: proof.verificationMethodId.href
6901
+ });
6902
+ return await verifyProofInternal(jsonLd, proof, {
6903
+ ...options,
6904
+ keyCache: {
6905
+ get: () => Promise.resolve(void 0),
6906
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
6907
+ }
6908
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
6909
+ }
6910
+ logger$1.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
6911
+ proof,
6912
+ keyId: proof.verificationMethodId.href
6913
+ });
6914
+ return null;
6915
+ }
6916
+ const digest = new Uint8Array(proofDigest.byteLength + 32);
6917
+ digest.set(new Uint8Array(proofDigest), 0);
6918
+ const proofValue = proof.proofValue;
6919
+ const verifyCandidate = async (msgDigest) => {
6920
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
6921
+ return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
6922
+ };
6923
+ const messageDigestKey = (0, json_canon.default)(proofConfiguration.context ?? null);
6924
+ const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
6925
+ let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
6926
+ if (messageDigestsPromise == null) {
6927
+ messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
6928
+ messageDigestValues.set(messageDigestKey, messageDigestsPromise);
6929
+ }
6930
+ const messageDigests = await messageDigestsPromise;
6931
+ if (await verifyCandidate(messageDigests.onWire)) return publicKey;
6932
+ if (messageDigestCache.proofPropertyMode !== "literal") {
6933
+ const normalizedDigest = await messageDigests.normalized();
6934
+ if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
6935
+ }
6936
+ if (fetchedKey.cached) {
6937
+ logger$1.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
6938
+ keyId: proof.verificationMethodId.href,
6939
+ proof
6940
+ });
6941
+ return await verifyProofInternal(jsonLd, proof, {
6942
+ ...options,
6943
+ keyCache: {
6944
+ get: () => Promise.resolve(void 0),
6945
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
6946
+ }
6947
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
6948
+ }
6949
+ logger$1.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
6950
+ keyId: proof.verificationMethodId.href,
6951
+ proof
6952
+ });
6953
+ return null;
6954
+ }
6955
+ const AS_NAMESPACE = "https://www.w3.org/ns/activitystreams#";
6956
+ const FEP_2277_ACTOR_PROPERTIES = ["http://www.w3.org/ns/ldp#inbox", `${AS_NAMESPACE}outbox`];
6957
+ const FEP_2277_COLLECTION_PROPERTIES = [
6958
+ "items",
6959
+ "orderedItems",
6960
+ "totalItems",
6961
+ "partOf",
6962
+ "first",
6963
+ "last",
6964
+ "next",
6965
+ "prev",
6966
+ "current"
6967
+ ].map((property) => AS_NAMESPACE + property);
6968
+ const PORTABLE_OBJECT_ID_PATTERN = /^ap(?:\+ef61)?:\/\//i;
6969
+ const FUNCTIONAL_PROOF_PROPERTIES = [
6970
+ `${SECURITY_NAMESPACE}cryptosuite`,
6971
+ SECURITY_VERIFICATION_METHOD,
6972
+ `${SECURITY_NAMESPACE}proofPurpose`,
6973
+ `${SECURITY_NAMESPACE}proofValue`,
6974
+ "http://purl.org/dc/terms/created"
6975
+ ];
6976
+ function isJsonLdNode(value) {
6977
+ return typeof value === "object" && value != null && !Array.isArray(value);
6978
+ }
6979
+ function hasValidPortableProofShape(proofValue) {
6980
+ if (!isJsonLdNode(proofValue)) return false;
6981
+ let proofNode = proofValue;
6982
+ if ("@graph" in proofNode) {
6983
+ const graph = proofNode["@graph"];
6984
+ if (!Array.isArray(graph) || graph.length !== 1 || !isJsonLdNode(graph[0])) return false;
6985
+ proofNode = graph[0];
6986
+ }
6987
+ const types = proofNode["@type"];
6988
+ return Array.isArray(types) && types.length === 1 && types[0] === DATA_INTEGRITY_PROOF && FUNCTIONAL_PROOF_PROPERTIES.every((property) => {
6989
+ const values = proofNode[property];
6990
+ return Array.isArray(values) && values.length === 1 && !(isJsonLdNode(values[0]) && "@list" in values[0]);
6991
+ });
6992
+ }
6993
+ function classifyFep2277CoreType(node) {
6994
+ if (FEP_2277_ACTOR_PROPERTIES.every((property) => property in node)) return "actor";
6995
+ if (`${SECURITY_NAMESPACE}publicKeyMultibase` in node) return "verificationMethod";
6996
+ if (`${SECURITY_NAMESPACE}publicKeyPem` in node) return "publicKey";
6997
+ if (`${AS_NAMESPACE}href` in node) return "link";
6998
+ if (`${AS_NAMESPACE}actor` in node) return "activity";
6999
+ if (FEP_2277_COLLECTION_PROPERTIES.some((property) => property in node)) return "collection";
7000
+ return "object";
7001
+ }
7002
+ async function expandPortableObjectRoot(jsonLd, contextLoader) {
7003
+ if (!isJsonLdNode(jsonLd)) throw new TypeError("Expected a single JSON-LD object.");
7004
+ const loadedContexts = /* @__PURE__ */ new Map();
7005
+ const loader = getNormalizationContextLoader(contextLoader);
7006
+ const recordingLoader = async (url, options) => {
7007
+ const remoteDocument = await loader(url, options);
7008
+ const key = URL.canParse(url) ? new URL(url).href : url;
7009
+ loadedContexts.set(key, structuredClone(remoteDocument));
7010
+ return remoteDocument;
7011
+ };
7012
+ const expanded = await _fedify_vocab_runtime_jsonld.default.expand(jsonLd, {
7013
+ documentLoader: recordingLoader,
7014
+ keepFreeFloatingNodes: true
7015
+ });
7016
+ if (expanded.length !== 1 || !isJsonLdNode(expanded[0])) throw new TypeError("Expected a single JSON-LD object.");
7017
+ return {
7018
+ root: expanded[0],
7019
+ proofContextLoader: async (url, options) => {
7020
+ const key = URL.canParse(url) ? new URL(url).href : url;
7021
+ const remoteDocument = loadedContexts.get(key);
7022
+ if (remoteDocument != null) return structuredClone(remoteDocument);
7023
+ return await preloadedOnlyDocumentLoader(url, options);
7024
+ }
7025
+ };
7026
+ }
7027
+ async function preparePortableObjectProof(jsonLd, options) {
7028
+ if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
7029
+ prepared: false,
7030
+ result: {
7031
+ verified: false,
7032
+ reason: { type: "notPortableObject" }
7033
+ }
7034
+ };
7035
+ const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
7036
+ const id = root["@id"];
7037
+ if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
7038
+ prepared: false,
7039
+ result: {
7040
+ verified: false,
7041
+ reason: { type: "notPortableObject" }
7042
+ }
7043
+ };
7044
+ const objectId = (0, _fedify_vocab_runtime.parseIri)(id);
7045
+ (0, _fedify_vocab_runtime.getFe34Origin)(objectId);
7046
+ const objectType = classifyFep2277CoreType(root);
7047
+ if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
7048
+ prepared: false,
7049
+ result: {
7050
+ verified: false,
7051
+ reason: {
7052
+ type: "unsupportedObjectType",
7053
+ objectType
7054
+ }
7055
+ }
7056
+ };
7057
+ const proofValues = root[SECURITY_PROOF];
7058
+ if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return {
7059
+ prepared: false,
7060
+ root,
7061
+ objectType,
7062
+ result: objectType === "collection" ? {
7063
+ verified: false,
7064
+ reason: { type: "unsecuredCollection" }
7065
+ } : {
7066
+ verified: false,
7067
+ reason: { type: "missingProof" }
7068
+ }
7069
+ };
7070
+ if (!Array.isArray(proofValues)) return {
7071
+ prepared: false,
7072
+ result: {
7073
+ verified: false,
7074
+ reason: {
7075
+ type: "invalidProof",
7076
+ proofIndex: 0
7077
+ }
7078
+ }
7079
+ };
7080
+ const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
7081
+ const proofs = [];
7082
+ for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
7083
+ const proofValue = proofValues[proofIndex];
7084
+ if (!hasValidPortableProofShape(proofValue)) return {
7085
+ prepared: false,
7086
+ result: {
7087
+ verified: false,
7088
+ reason: {
7089
+ type: "invalidProof",
7090
+ proofIndex
7091
+ }
7092
+ }
7093
+ };
7094
+ let proof;
7095
+ try {
7096
+ proof = await _fedify_vocab.DataIntegrityProof.fromJsonLd(proofValue, options);
7097
+ } catch {
7098
+ return {
7099
+ prepared: false,
7100
+ result: {
7101
+ verified: false,
7102
+ reason: {
7103
+ type: "invalidProof",
7104
+ proofIndex
7105
+ }
7106
+ }
7107
+ };
7108
+ }
7109
+ proofs.push(proof);
7110
+ }
7111
+ for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
7112
+ const verificationMethod = proofs[proofIndex].verificationMethodId;
7113
+ if (verificationMethod == null) return {
7114
+ prepared: false,
7115
+ result: {
7116
+ verified: false,
7117
+ reason: {
7118
+ type: "invalidProof",
7119
+ proofIndex
7120
+ }
7121
+ }
7122
+ };
7123
+ if (verificationMethod.protocol !== "did:") return {
7124
+ prepared: false,
7125
+ result: {
7126
+ verified: false,
7127
+ reason: {
7128
+ type: "unsupportedVerificationMethod",
7129
+ proofIndex,
7130
+ verificationMethod
7131
+ }
7132
+ }
7133
+ };
7134
+ try {
7135
+ (0, _fedify_vocab_runtime.getFe34Origin)(verificationMethod);
7136
+ } catch (error) {
7137
+ if (!(error instanceof TypeError)) throw error;
7138
+ return {
7139
+ prepared: false,
7140
+ result: {
7141
+ verified: false,
7142
+ reason: {
7143
+ type: "unsupportedVerificationMethod",
7144
+ proofIndex,
7145
+ verificationMethod
7146
+ }
7147
+ }
7148
+ };
7149
+ }
7150
+ if (!(0, _fedify_vocab_runtime.haveSameFe34Origin)(objectId, verificationMethod)) return {
7151
+ prepared: false,
7152
+ result: {
7153
+ verified: false,
7154
+ reason: {
7155
+ type: "verificationMethodMismatch",
7156
+ proofIndex,
7157
+ objectId,
7158
+ verificationMethod
7159
+ }
7160
+ }
7161
+ };
7162
+ }
7163
+ return {
7164
+ prepared: true,
7165
+ root,
7166
+ objectType,
7167
+ objectId,
7168
+ proofs,
7169
+ rawProofValues,
7170
+ proofContextLoader
7171
+ };
7172
+ }
7173
+ /**
7174
+ * Applies portable-object proof policy to one map-local cryptographic result.
7175
+ *
7176
+ * @internal
7177
+ */
7178
+ async function verifyPortableObjectProofPolicy(jsonLd, key, options = {}) {
7179
+ const policyOptions = {
7180
+ ...options,
7181
+ contextLoader: preloadedOnlyDocumentLoader
7182
+ };
7183
+ const prepared = await preparePortableObjectProof(jsonLd, policyOptions);
7184
+ if (!prepared.prepared) return prepared.result;
7185
+ const policyProof = prepared.proofs[0];
7186
+ const literalProof = isJsonLdNode(jsonLd) && isJsonLdNode(jsonLd.proof) ? (await parseRawProofCandidates(jsonLd, [jsonLd.proof], policyOptions, prepared.proofContextLoader))[0]?.proof : null;
7187
+ const verificationMethod = policyProof?.verificationMethodId;
7188
+ if (prepared.proofs.length !== 1 || key == null || policyProof == null || literalProof == null || !sameProof(policyProof, literalProof) || verificationMethod == null || key.id?.href !== verificationMethod.href) return {
7189
+ verified: false,
7190
+ reason: {
7191
+ type: "invalidProof",
7192
+ proofIndex: prepared.proofs.length > 1 ? 1 : 0
7193
+ }
7194
+ };
7195
+ return {
7196
+ verified: true,
7197
+ keys: [key],
7198
+ objectId: (0, _fedify_vocab_runtime.formatIri)(prepared.objectId)
7199
+ };
7200
+ }
7201
+ /**
7202
+ * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
7203
+ *
7204
+ * This applies the FEP-2277 core-type classification to the top-level JSON-LD
7205
+ * node. Portable actors, activities, and objects require proofs. A portable
7206
+ * collection without a proof is reported separately so a caller can apply a
7207
+ * gateway trust policy. Embedded portable objects are not traversed.
7208
+ *
7209
+ * Every proof must use a DID URL whose DID matches the portable object's
7210
+ * authority, and every proof must pass {@link verifyProof}.
7211
+ *
7212
+ * @param jsonLd The JSON-LD document to verify.
7213
+ * @param options Additional options. See also
7214
+ * {@link VerifyPortableObjectProofOptions}.
7215
+ * @returns The detailed portable proof-policy result.
7216
+ * @throws {TypeError} If the input is not a single JSON-LD object or has a
7217
+ * malformed portable ID.
7218
+ * @since 2.4.0
7219
+ */
7220
+ async function verifyPortableObjectProof(jsonLd, options = {}) {
7221
+ return (await verifyPortableObjectProofWithRoot(jsonLd, options)).result;
7222
+ }
7223
+ /**
7224
+ * Same as {@link verifyPortableObjectProof}, but also returns the expanded
7225
+ * root node and its FEP-2277 core type, so that a caller can apply further
7226
+ * policy, such as the gateway trust policy for unsecured collections, to the
7227
+ * same interpretation of the document.
7228
+ * @internal
7229
+ */
7230
+ async function verifyPortableObjectProofWithRoot(jsonLd, options = {}) {
7231
+ const prepared = await preparePortableObjectProof(jsonLd, options);
7232
+ if (!prepared.prepared) return {
7233
+ result: prepared.result,
7234
+ ...prepared.root == null ? {} : { root: prepared.root },
7235
+ ...prepared.objectType == null ? {} : { objectType: prepared.objectType }
7236
+ };
7237
+ const { root, objectType } = prepared;
7238
+ return {
7239
+ result: await verifyPreparedPortableObjectProof(jsonLd, prepared, options),
7240
+ root,
7241
+ objectType
7242
+ };
7243
+ }
7244
+ async function verifyPreparedPortableObjectProof(jsonLd, prepared, options) {
7245
+ const { proofs, rawProofValues, proofContextLoader } = prepared;
7246
+ const keys = [];
7247
+ const rawProofCandidatePool = {
7248
+ candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
7249
+ used: /* @__PURE__ */ new Set()
7250
+ };
7251
+ const messageDigestCache = { proofContextLoader };
7252
+ for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
7253
+ const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proofs[proofIndex]);
7254
+ if (rawProofCandidate == null) return {
7255
+ verified: false,
7256
+ reason: {
7257
+ type: "invalidProof",
7258
+ proofIndex
7259
+ }
7260
+ };
7261
+ const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
7262
+ if (key == null) return {
7263
+ verified: false,
7264
+ reason: {
7265
+ type: "invalidProof",
7266
+ proofIndex
7267
+ }
7268
+ };
7269
+ keys.push(key);
7270
+ }
7271
+ return {
7272
+ verified: true,
7273
+ keys
7274
+ };
7275
+ }
7276
+ /**
7277
+ * Verifies the given object. It will verify all the proofs in the object,
7278
+ * and succeed only if all the proofs are valid and all attributions and
7279
+ * actors are authenticated by the proofs.
7280
+ * @template T The type of the object to verify.
7281
+ * @param cls The class of the object to verify. It must be a subclass of
7282
+ * the {@link Object}.
7283
+ * @param jsonLd The JSON-LD object to verify. It's assumed that the object
7284
+ * is a compacted JSON-LD representation of a `T` with `@context`.
7285
+ * @param options Additional options. See also {@link VerifyObjectOptions}.
7286
+ * @returns The object if it's verified, or `null` if it's not.
7287
+ * @throws {TypeError} If the object is invalid or unsupported.
7288
+ * @since 0.10.0
7289
+ */
7290
+ async function verifyObject(cls, jsonLd, options = {}) {
7291
+ const logger = (0, _logtape_logtape.getLogger)([
7292
+ "fedify",
7293
+ "sig",
7294
+ "proof"
7295
+ ]);
7296
+ const object = await cls.fromJsonLd(jsonLd, options);
7297
+ const defaultDocumentLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
7298
+ const proofContextLoader = options.contextLoader ?? defaultDocumentLoader;
7299
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
7300
+ if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
7301
+ const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
7302
+ const rawProofCandidates = isJsonLdNode(jsonLd) ? await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader) : [];
7303
+ const rawProofCandidatePool = {
7304
+ candidates: rawProofCandidates,
7305
+ used: /* @__PURE__ */ new Set()
7306
+ };
7307
+ const baseDocumentLoader = options.documentLoader ?? defaultDocumentLoader;
7308
+ const hydratedCandidates = /* @__PURE__ */ new Set();
7309
+ let loadedPortableProofs = 0;
7310
+ let acceptedPortableProofs = 0;
7311
+ const acceptPortableProofDocument = async () => {
7312
+ acceptedPortableProofs++;
7313
+ return { verified: true };
7314
+ };
7315
+ const proofDocumentLoader = async (url, loaderOptions) => {
7316
+ const remoteDocument = await baseDocumentLoader(url, loaderOptions);
7317
+ if (PORTABLE_OBJECT_ID_PATTERN.test(url)) loadedPortableProofs++;
7318
+ const reference = normalizeDocumentUrl(url);
7319
+ const candidateIndex = rawProofCandidates.findIndex((candidate, index) => !hydratedCandidates.has(index) && !rawProofCandidatePool.used.has(index) && candidate.reference === reference);
7320
+ if (candidateIndex >= 0) {
7321
+ hydratedCandidates.add(candidateIndex);
7322
+ let parsed = null;
7323
+ try {
7324
+ parsed = await _fedify_vocab.DataIntegrityProof.fromJsonLd(remoteDocument.document, {
7325
+ documentLoader: baseDocumentLoader,
7326
+ contextLoader: proofContextLoader,
7327
+ tracerProvider: options.tracerProvider,
7328
+ baseUrl: (0, _fedify_vocab_runtime.parseIri)(remoteDocument.documentUrl)
7329
+ });
7330
+ } catch {}
7331
+ rawProofCandidates[candidateIndex] = {
7332
+ value: structuredClone(remoteDocument.document),
7333
+ proof: parsed,
7334
+ reference
7335
+ };
7336
+ }
7337
+ return remoteDocument;
7338
+ };
7339
+ for await (const proof of object.getProofs({
7340
+ ...options,
7341
+ documentLoader: proofDocumentLoader,
7342
+ gateways: [],
7343
+ verifyPortableObject: acceptPortableProofDocument
7344
+ })) {
7345
+ const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proof);
7346
+ if (rawProofCandidate == null) return null;
7347
+ const key = await verifyProofWithMessageDigestCache(jsonLd, proof, options, { proofContextLoader }, rawProofCandidate);
7348
+ if (key === null) return null;
7349
+ if (proof.verificationMethodId == null) return null;
7350
+ if (key.controllerId == null) {
7351
+ logger.debug("Key {keyId} does not have a controller.", { keyId: key.id?.href });
7352
+ continue;
7353
+ }
7354
+ deleteAuthenticatedAttribution(attributions, key.controllerId, proof.verificationMethodId);
7355
+ }
7356
+ if (acceptedPortableProofs < loadedPortableProofs) {
7357
+ logger.debug("Some portable proof references could not be dereferenced.");
7358
+ return null;
7359
+ }
7360
+ if (attributions.size > 0) {
7361
+ logger.debug("Some attributions are not authenticated by the proofs: {attributions}.", { attributions: [...attributions] });
7362
+ return null;
7363
+ }
7364
+ return object;
7365
+ }
7366
+ function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
7367
+ const controllerHasCryptographicOrigin = hasCryptographicOrigin(controllerId.href);
7368
+ const verificationMethodMatchesController = controllerHasCryptographicOrigin && hasCryptographicOrigin(verificationMethodId.href) && (0, _fedify_vocab_runtime.haveSameFe34Origin)(controllerId, verificationMethodId);
7369
+ if (!controllerHasCryptographicOrigin || verificationMethodMatchesController) attributions.delete(controllerId.href);
7370
+ if (!verificationMethodMatchesController) return;
7371
+ for (const attribution of [...attributions]) if (hasCryptographicOrigin(attribution) && (0, _fedify_vocab_runtime.haveSameFe34Origin)(controllerId, attribution)) attributions.delete(attribution);
7372
+ }
7373
+ function hasCryptographicOrigin(iri) {
7374
+ return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
7375
+ }
7376
+ //#endregion
7377
+ //#region src/sig/portable-key.ts
7378
+ const logger = (0, _logtape_logtape.getLogger)([
7379
+ "fedify",
7380
+ "sig",
7381
+ "key"
7382
+ ]);
7383
+ const SEC = "https://w3id.org/security#";
7384
+ /**
7385
+ * Verifies that the signed document of a portable actor vouches for
7386
+ * the gateway key with the given ID.
7387
+ *
7388
+ * A gateway key is accepted only if:
7389
+ *
7390
+ * - the document is an actor whose portable ID is the one the key ID is
7391
+ * the compatible identifier of;
7392
+ * - the document has a valid [FEP-8b32] Object Integrity Proof made by
7393
+ * the DID of its ID, i.e., it satisfies the [FEP-ef61] proof policy;
7394
+ * - the document embeds a `Multikey` with that ID in its `assertionMethod`,
7395
+ * whose `controller` is the actor, as [FEP-521a] requires; a key
7396
+ * embedded in its `publicKey` with the same ID must agree with it; and
7397
+ * - the key ID's origin is one of the actor's `gateways`.
7398
+ *
7399
+ * [FEP-8b32]: https://w3id.org/fep/8b32
7400
+ * [FEP-ef61]: https://w3id.org/fep/ef61
7401
+ * [FEP-521a]: https://w3id.org/fep/521a
7402
+ *
7403
+ * @param document The raw JSON-LD document served at the key ID.
7404
+ * @param actor The parsed document, which must be a portable actor.
7405
+ * @param keyId The key ID, which must be a compatible key ID.
7406
+ * @param options Loaders and telemetry providers.
7407
+ * @returns The verification result, which is never `legacy`.
7408
+ * @internal
7409
+ */
7410
+ async function verifyPortableGatewayKeyDocument(document, actor, keyId, options = {}) {
7411
+ const reject = (reason) => {
7412
+ logger.debug("Failed to verify gateway key {keyId} of the portable actor {actorId}: {reason}", {
7413
+ keyId: keyId.href,
7414
+ actorId: actor.id?.href,
7415
+ reason
7416
+ });
7417
+ return {
7418
+ type: "rejected",
7419
+ reason
7420
+ };
7421
+ };
7422
+ const keyBase = new URL(keyId.href);
7423
+ keyBase.hash = "";
7424
+ const claimedActorId = getCanonicalPortableId(keyBase);
7425
+ const actorId = actor.id == null ? null : getCanonicalPortableId(actor.id);
7426
+ if (claimedActorId == null || actorId == null) return reject("The key ID or the actor ID is not a valid portable ID.");
7427
+ if (claimedActorId !== actorId) return reject("The key ID is not a compatible identifier of the actor it dereferences to.");
7428
+ let verification;
7429
+ try {
7430
+ verification = await verifyPortableObjectProofWithRoot(document, {
7431
+ documentLoader: options.documentLoader,
7432
+ contextLoader: options.contextLoader,
7433
+ keyCache: options.keyCache,
7434
+ tracerProvider: options.tracerProvider,
7435
+ meterProvider: options.meterProvider
7436
+ });
7437
+ } catch (error) {
7438
+ if (!(error instanceof TypeError)) throw error;
7439
+ return reject(`The actor document is malformed: ${error.message}`);
7440
+ }
7441
+ const { result, root } = verification;
7442
+ if (!result.verified) return reject("The actor document does not satisfy the FEP-ef61 proof policy: " + result.reason.type);
7443
+ if (root == null) return reject("The actor document could not be expanded.");
7444
+ const refuse = (url) => Promise.reject(/* @__PURE__ */ new Error(`Refusing to fetch ${url}.`));
7445
+ let verifiedActor;
7446
+ try {
7447
+ verifiedActor = await _fedify_vocab.Object.fromJsonLd(root, {
7448
+ documentLoader: refuse,
7449
+ contextLoader: options.contextLoader,
7450
+ tracerProvider: options.tracerProvider
7451
+ });
7452
+ } catch (error) {
7453
+ if (!(error instanceof TypeError)) throw error;
7454
+ return reject("The verified actor document is malformed.");
7455
+ }
7456
+ if (!isPortableActorDocument(verifiedActor) || getCanonicalPortableId(verifiedActor.id) !== claimedActorId) return reject("The key ID is not a compatible identifier of the actor whose document is signed.");
7457
+ actor = verifiedActor;
7458
+ const multikeyNode = findEmbeddedNode(root[`${SEC}assertionMethod`], keyId);
7459
+ if (multikeyNode == null) return reject("The actor document does not embed the key in its assertionMethod.");
7460
+ let multikey;
7461
+ try {
7462
+ multikey = await _fedify_vocab.Multikey.fromJsonLd(multikeyNode, {
7463
+ documentLoader: refuse,
7464
+ contextLoader: options.contextLoader,
7465
+ tracerProvider: options.tracerProvider
7466
+ });
7467
+ } catch (error) {
7468
+ if (!(error instanceof TypeError)) throw error;
7469
+ return reject("The key in the assertionMethod is malformed.");
7470
+ }
7471
+ if (multikey.publicKey == null) return reject("The key in the assertionMethod has no public key.");
7472
+ if (multikey.controllerId == null || getCanonicalPortableId(multikey.controllerId) !== actorId) return reject("The controller of the key is not the actor.");
7473
+ const publicKeyNode = findEmbeddedNode(root[`${SEC}publicKey`], keyId);
7474
+ if (publicKeyNode != null) {
7475
+ let publicKey;
7476
+ try {
7477
+ publicKey = await _fedify_vocab.CryptographicKey.fromJsonLd(publicKeyNode, {
7478
+ documentLoader: refuse,
7479
+ contextLoader: options.contextLoader,
7480
+ tracerProvider: options.tracerProvider
7481
+ });
7482
+ } catch (error) {
7483
+ if (!(error instanceof TypeError)) throw error;
7484
+ return reject("The key in the publicKey is malformed.");
7485
+ }
7486
+ if (publicKey.publicKey == null || !await isSamePublicKey(publicKey.publicKey, multikey.publicKey) || publicKey.ownerId != null && getCanonicalPortableId(publicKey.ownerId) !== actorId) return reject("The key in the publicKey does not agree with the one in the assertionMethod.");
7487
+ }
7488
+ if (!actor.gateways.some((gateway) => (0, _fedify_vocab_runtime.isGatewayUrl)(gateway) && gateway.origin === keyId.origin)) return reject(`The gateway ${keyId.origin} is not listed in the actor's gateways.`);
7489
+ const key = new _fedify_vocab.CryptographicKey({
7490
+ id: keyId,
7491
+ owner: actor.id,
7492
+ publicKey: multikey.publicKey
7493
+ });
7494
+ return {
7495
+ type: "verified",
7496
+ actor,
7497
+ key
7498
+ };
7499
+ }
7500
+ /**
7501
+ * Fetches the document at a compatible key ID, and resolves the key as
7502
+ * a gateway key if the document is a portable actor.
7503
+ *
7504
+ * @param keyId The key ID, which must be a compatible key ID.
7505
+ * @param options Loaders and telemetry providers.
7506
+ * @returns `legacy` if the document cannot be fetched or is not a portable
7507
+ * actor, which leaves the key to the usual resolution; otherwise,
7508
+ * the result of {@link verifyPortableGatewayKeyDocument}.
7509
+ * @internal
7510
+ */
7511
+ async function fetchPortableGatewayKey(keyId, options = {}) {
7512
+ const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
7513
+ const contextLoader = options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
7514
+ let remoteDocument;
7515
+ try {
7516
+ remoteDocument = await documentLoader(keyId.href);
7517
+ } catch (error) {
7518
+ logger.debug("Failed to fetch key {keyId}: {error}", {
7519
+ keyId: keyId.href,
7520
+ error
7521
+ });
7522
+ return { type: "legacy" };
7523
+ }
7524
+ let object;
7525
+ try {
7526
+ object = await _fedify_vocab.Object.fromJsonLd(remoteDocument.document, {
7527
+ documentLoader,
7528
+ contextLoader,
7529
+ tracerProvider: options.tracerProvider
7530
+ });
7531
+ } catch (error) {
7532
+ if (!(error instanceof TypeError)) throw error;
7533
+ return { type: "legacy" };
7534
+ }
7535
+ if (!isPortableActorDocument(object)) return { type: "legacy" };
7536
+ return await verifyPortableGatewayKeyDocument(remoteDocument.document, object, keyId, {
7537
+ ...options,
7538
+ documentLoader,
7539
+ contextLoader
7540
+ });
7541
+ }
7542
+ function findEmbeddedNode(values, id) {
7543
+ if (!Array.isArray(values)) return null;
7544
+ for (const value of values) {
7545
+ if (value == null || typeof value !== "object" || Array.isArray(value)) continue;
7546
+ const node = value;
7547
+ const nodeId = node["@id"];
7548
+ if (typeof nodeId !== "string") continue;
7549
+ let parsed;
7550
+ try {
7551
+ parsed = new URL(nodeId);
7552
+ } catch {
7553
+ continue;
7554
+ }
7555
+ if (parsed.href !== id.href) continue;
7556
+ if (Object.keys(node).every((key) => key === "@id")) continue;
7557
+ return node;
7558
+ }
7559
+ return null;
7560
+ }
7561
+ //#endregion
7562
+ //#region src/sig/http.ts
7563
+ const Temporal = Temporal$2;
7564
+ const DEFAULT_MAX_REDIRECTION = 20;
7565
+ const DOUBLE_KNOCK_TRANSPORT_RETRY_DELAY_MS = 100;
7566
+ /**
7567
+ * Signs a request using the given private key.
7568
+ * @param request The request to sign.
7569
+ * @param privateKey The private key to use for signing.
7570
+ * @param keyId The key ID to use for the signature. It will be used by the
7571
+ * verifier.
7572
+ * @returns The signed request.
7573
+ * @throws {TypeError} If the private key is invalid or unsupported.
7574
+ */
7575
+ async function signRequest(request, privateKey, keyId, options = {}) {
7576
+ validateCryptoKey(privateKey, "private");
7577
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(name, version).startActiveSpan("http_signatures.sign", async (span) => {
7578
+ try {
7579
+ const spec = options.spec ?? "draft-cavage-http-signatures-12";
7580
+ let signed;
7581
+ if (spec === "rfc9421") signed = await signRequestRfc9421(request, privateKey, keyId, span, options.currentTime, options.body, options.rfc9421);
7582
+ else signed = await signRequestDraft(request, privateKey, keyId, span, options.currentTime, options.body);
7583
+ if (span.isRecording()) {
7584
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD, signed.method);
7585
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_URL_FULL, signed.url);
7586
+ for (const [name, value] of signed.headers) span.setAttribute((0, _opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_HEADER)(name), value);
7587
+ span.setAttribute("http_signatures.key_id", keyId.href);
7588
+ }
7589
+ return signed;
7590
+ } catch (error) {
7591
+ span.setStatus({
7592
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
7593
+ message: String(error)
7594
+ });
7595
+ throw error;
7596
+ } finally {
7597
+ span.end();
7598
+ }
7599
+ });
7600
+ }
7601
+ async function signRequestDraft(request, privateKey, keyId, span, currentTime, bodyBuffer) {
7602
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
7603
+ const url = new URL(request.url);
7604
+ const body = bodyBuffer !== void 0 ? bodyBuffer : request.method !== "GET" && request.method !== "HEAD" ? await request.clone().arrayBuffer() : null;
7605
+ const headers = new Headers(request.headers);
7606
+ if (!headers.has("Host")) headers.set("Host", url.host);
7607
+ if (!headers.has("Digest") && body != null) {
7608
+ const digest = await crypto.subtle.digest("SHA-256", body);
7609
+ headers.set("Digest", `SHA-256=${(0, byte_encodings_base64.encodeBase64)(digest)}`);
7610
+ if (span.isRecording()) span.setAttribute("http_signatures.digest.sha-256", (0, byte_encodings_hex.encodeHex)(digest));
7611
+ }
7612
+ if (!headers.has("Date")) headers.set("Date", currentTime == null ? (/* @__PURE__ */ new Date()).toUTCString() : new Date(currentTime.toString()).toUTCString());
7613
+ const serialized = [["(request-target)", `${request.method.toLowerCase()} ${url.pathname}`], ...headers];
7614
+ const headerNames = serialized.map(([name]) => name);
7615
+ const message = serialized.map(([name, value]) => `${name}: ${value.trim()}`).join("\n");
7616
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, new TextEncoder().encode(message));
7617
+ const sigHeader = `keyId="${keyId.href}",algorithm="rsa-sha256",headers="${headerNames.join(" ")}",signature="${(0, byte_encodings_base64.encodeBase64)(signature)}"`;
5188
7618
  headers.set("Signature", sigHeader);
5189
7619
  if (span.isRecording()) {
5190
7620
  span.setAttribute("http_signatures.algorithm", "rsa-sha256");
@@ -5687,7 +8117,14 @@ async function verifyRequestDraft(request, span, metricsContext, { documentLoade
5687
8117
  contextLoader,
5688
8118
  keyCache,
5689
8119
  tracerProvider,
5690
- meterProvider
8120
+ meterProvider,
8121
+ portableGatewayKeyResolver: (document, actor, keyId) => verifyPortableGatewayKeyDocument(document, actor, keyId, {
8122
+ documentLoader,
8123
+ contextLoader,
8124
+ keyCache,
8125
+ tracerProvider,
8126
+ meterProvider
8127
+ })
5691
8128
  }));
5692
8129
  if (fetchError != null) return keyFetchErrorResult(keyIdUrl, fetchError);
5693
8130
  if (key == null) return invalidSignatureResult(keyIdUrl);
@@ -5903,7 +8340,14 @@ async function verifyRequestRfc9421(request, span, metricsContext, { documentLoa
5903
8340
  contextLoader,
5904
8341
  keyCache,
5905
8342
  tracerProvider,
5906
- meterProvider
8343
+ meterProvider,
8344
+ portableGatewayKeyResolver: (document, actor, gatewayKeyId) => verifyPortableGatewayKeyDocument(document, actor, gatewayKeyId, {
8345
+ documentLoader,
8346
+ contextLoader,
8347
+ keyCache,
8348
+ tracerProvider,
8349
+ meterProvider
8350
+ })
5907
8351
  }));
5908
8352
  if (fetchError != null) {
5909
8353
  setFailure(keyFetchErrorResult(keyId, fetchError));
@@ -6208,10 +8652,52 @@ function timingSafeEqual(a, b) {
6208
8652
  return result === 0;
6209
8653
  }
6210
8654
  //#endregion
8655
+ Object.defineProperty(exports, "InvalidContextReferenceError", {
8656
+ enumerable: true,
8657
+ get: function() {
8658
+ return InvalidContextReferenceError;
8659
+ }
8660
+ });
6211
8661
  Object.defineProperty(exports, "Temporal", {
6212
8662
  enumerable: true,
6213
8663
  get: function() {
6214
- return Temporal$1;
8664
+ return Temporal$2;
8665
+ }
8666
+ });
8667
+ Object.defineProperty(exports, "assertSafeJsonLd", {
8668
+ enumerable: true,
8669
+ get: function() {
8670
+ return assertSafeJsonLd;
8671
+ }
8672
+ });
8673
+ Object.defineProperty(exports, "attachSignature", {
8674
+ enumerable: true,
8675
+ get: function() {
8676
+ return attachSignature;
8677
+ }
8678
+ });
8679
+ Object.defineProperty(exports, "compactJsonLd", {
8680
+ enumerable: true,
8681
+ get: function() {
8682
+ return compactJsonLd;
8683
+ }
8684
+ });
8685
+ Object.defineProperty(exports, "createProof", {
8686
+ enumerable: true,
8687
+ get: function() {
8688
+ return createProof;
8689
+ }
8690
+ });
8691
+ Object.defineProperty(exports, "createSignature", {
8692
+ enumerable: true,
8693
+ get: function() {
8694
+ return createSignature;
8695
+ }
8696
+ });
8697
+ Object.defineProperty(exports, "detachSignature", {
8698
+ enumerable: true,
8699
+ get: function() {
8700
+ return detachSignature;
6215
8701
  }
6216
8702
  });
6217
8703
  Object.defineProperty(exports, "doubleKnock", {
@@ -6244,6 +8730,12 @@ Object.defineProperty(exports, "fetchKeyDetailed", {
6244
8730
  return fetchKeyDetailed;
6245
8731
  }
6246
8732
  });
8733
+ Object.defineProperty(exports, "fetchPortableGatewayKey", {
8734
+ enumerable: true,
8735
+ get: function() {
8736
+ return fetchPortableGatewayKey;
8737
+ }
8738
+ });
6247
8739
  Object.defineProperty(exports, "formatAcceptSignature", {
6248
8740
  enumerable: true,
6249
8741
  get: function() {
@@ -6262,6 +8754,12 @@ Object.defineProperty(exports, "generateCryptoKeyPair", {
6262
8754
  return generateCryptoKeyPair;
6263
8755
  }
6264
8756
  });
8757
+ Object.defineProperty(exports, "getCanonicalPortableId", {
8758
+ enumerable: true,
8759
+ get: function() {
8760
+ return getCanonicalPortableId;
8761
+ }
8762
+ });
6265
8763
  Object.defineProperty(exports, "getDurationMs", {
6266
8764
  enumerable: true,
6267
8765
  get: function() {
@@ -6274,12 +8772,48 @@ Object.defineProperty(exports, "getFederationMetrics", {
6274
8772
  return getFederationMetrics;
6275
8773
  }
6276
8774
  });
8775
+ Object.defineProperty(exports, "getGatewayKeyBase", {
8776
+ enumerable: true,
8777
+ get: function() {
8778
+ return getGatewayKeyBase;
8779
+ }
8780
+ });
8781
+ Object.defineProperty(exports, "getNormalizationContextLoader", {
8782
+ enumerable: true,
8783
+ get: function() {
8784
+ return getNormalizationContextLoader;
8785
+ }
8786
+ });
6277
8787
  Object.defineProperty(exports, "getRemoteHost", {
6278
8788
  enumerable: true,
6279
8789
  get: function() {
6280
8790
  return getRemoteHost;
6281
8791
  }
6282
8792
  });
8793
+ Object.defineProperty(exports, "hasPortableActor", {
8794
+ enumerable: true,
8795
+ get: function() {
8796
+ return hasPortableActor;
8797
+ }
8798
+ });
8799
+ Object.defineProperty(exports, "hasProofLike", {
8800
+ enumerable: true,
8801
+ get: function() {
8802
+ return hasProofLike;
8803
+ }
8804
+ });
8805
+ Object.defineProperty(exports, "hasSignature", {
8806
+ enumerable: true,
8807
+ get: function() {
8808
+ return hasSignature;
8809
+ }
8810
+ });
8811
+ Object.defineProperty(exports, "hasSignatureLike", {
8812
+ enumerable: true,
8813
+ get: function() {
8814
+ return hasSignatureLike;
8815
+ }
8816
+ });
6283
8817
  Object.defineProperty(exports, "importJwk", {
6284
8818
  enumerable: true,
6285
8819
  get: function() {
@@ -6298,10 +8832,34 @@ Object.defineProperty(exports, "isAbortError", {
6298
8832
  return isAbortError$1;
6299
8833
  }
6300
8834
  });
6301
- Object.defineProperty(exports, "measureSignatureKeyFetch", {
8835
+ Object.defineProperty(exports, "isClearlyMalformedContextReference", {
8836
+ enumerable: true,
8837
+ get: function() {
8838
+ return isClearlyMalformedContextReference;
8839
+ }
8840
+ });
8841
+ Object.defineProperty(exports, "isCompatibleKeyId", {
6302
8842
  enumerable: true,
6303
8843
  get: function() {
6304
- return measureSignatureKeyFetch;
8844
+ return isCompatibleKeyId;
8845
+ }
8846
+ });
8847
+ Object.defineProperty(exports, "isInvalidUrlTypeError", {
8848
+ enumerable: true,
8849
+ get: function() {
8850
+ return isInvalidUrlTypeError;
8851
+ }
8852
+ });
8853
+ Object.defineProperty(exports, "isPortableUri", {
8854
+ enumerable: true,
8855
+ get: function() {
8856
+ return isPortableUri;
8857
+ }
8858
+ });
8859
+ Object.defineProperty(exports, "isSamePublicKey", {
8860
+ enumerable: true,
8861
+ get: function() {
8862
+ return isSamePublicKey;
6305
8863
  }
6306
8864
  });
6307
8865
  Object.defineProperty(exports, "name", {
@@ -6310,6 +8868,12 @@ Object.defineProperty(exports, "name", {
6310
8868
  return name;
6311
8869
  }
6312
8870
  });
8871
+ Object.defineProperty(exports, "normalizeOutgoingActivityJsonLd", {
8872
+ enumerable: true,
8873
+ get: function() {
8874
+ return normalizeOutgoingActivityJsonLd;
8875
+ }
8876
+ });
6313
8877
  Object.defineProperty(exports, "parseAcceptSignature", {
6314
8878
  enumerable: true,
6315
8879
  get: function() {
@@ -6394,6 +8958,18 @@ Object.defineProperty(exports, "registerQueueDepthGauge", {
6394
8958
  return registerQueueDepthGauge;
6395
8959
  }
6396
8960
  });
8961
+ Object.defineProperty(exports, "signJsonLd", {
8962
+ enumerable: true,
8963
+ get: function() {
8964
+ return signJsonLd;
8965
+ }
8966
+ });
8967
+ Object.defineProperty(exports, "signObject", {
8968
+ enumerable: true,
8969
+ get: function() {
8970
+ return signObject;
8971
+ }
8972
+ });
6397
8973
  Object.defineProperty(exports, "signRequest", {
6398
8974
  enumerable: true,
6399
8975
  get: function() {
@@ -6412,12 +8988,60 @@ Object.defineProperty(exports, "validateCryptoKey", {
6412
8988
  return validateCryptoKey;
6413
8989
  }
6414
8990
  });
8991
+ Object.defineProperty(exports, "verifyCompactJsonLd", {
8992
+ enumerable: true,
8993
+ get: function() {
8994
+ return verifyCompactJsonLd;
8995
+ }
8996
+ });
8997
+ Object.defineProperty(exports, "verifyJsonLd", {
8998
+ enumerable: true,
8999
+ get: function() {
9000
+ return verifyJsonLd;
9001
+ }
9002
+ });
6415
9003
  Object.defineProperty(exports, "verifyKeyOwnership", {
6416
9004
  enumerable: true,
6417
9005
  get: function() {
6418
9006
  return verifyKeyOwnership;
6419
9007
  }
6420
9008
  });
9009
+ Object.defineProperty(exports, "verifyMapLocalProof", {
9010
+ enumerable: true,
9011
+ get: function() {
9012
+ return verifyMapLocalProof;
9013
+ }
9014
+ });
9015
+ Object.defineProperty(exports, "verifyObject", {
9016
+ enumerable: true,
9017
+ get: function() {
9018
+ return verifyObject;
9019
+ }
9020
+ });
9021
+ Object.defineProperty(exports, "verifyPortableObjectProof", {
9022
+ enumerable: true,
9023
+ get: function() {
9024
+ return verifyPortableObjectProof;
9025
+ }
9026
+ });
9027
+ Object.defineProperty(exports, "verifyPortableObjectProofPolicy", {
9028
+ enumerable: true,
9029
+ get: function() {
9030
+ return verifyPortableObjectProofPolicy;
9031
+ }
9032
+ });
9033
+ Object.defineProperty(exports, "verifyPortableObjectProofWithRoot", {
9034
+ enumerable: true,
9035
+ get: function() {
9036
+ return verifyPortableObjectProofWithRoot;
9037
+ }
9038
+ });
9039
+ Object.defineProperty(exports, "verifyProof", {
9040
+ enumerable: true,
9041
+ get: function() {
9042
+ return verifyProof;
9043
+ }
9044
+ });
6421
9045
  Object.defineProperty(exports, "verifyRequest", {
6422
9046
  enumerable: true,
6423
9047
  get: function() {
@@ -6430,9 +9054,21 @@ Object.defineProperty(exports, "verifyRequestDetailed", {
6430
9054
  return verifyRequestDetailed;
6431
9055
  }
6432
9056
  });
9057
+ Object.defineProperty(exports, "verifySignature", {
9058
+ enumerable: true,
9059
+ get: function() {
9060
+ return verifySignature;
9061
+ }
9062
+ });
6433
9063
  Object.defineProperty(exports, "version", {
6434
9064
  enumerable: true,
6435
9065
  get: function() {
6436
9066
  return version;
6437
9067
  }
6438
9068
  });
9069
+ Object.defineProperty(exports, "wrapContextLoaderForJsonLd", {
9070
+ enumerable: true,
9071
+ get: function() {
9072
+ return wrapContextLoaderForJsonLd;
9073
+ }
9074
+ });