@fedify/fedify 2.5.0-dev.2364 → 2.5.0-dev.2378

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 (101) hide show
  1. package/dist/{builder-ClDm_1c7.mjs → builder-J1K0IJj6.mjs} +2 -2
  2. package/dist/compat/mod.d.cts +1 -1
  3. package/dist/compat/mod.d.ts +1 -1
  4. package/dist/compat/transformers.test.mjs +1 -1
  5. package/dist/{compound-proof-D03g5HXz.mjs → compound-proof-DtmVrMV7.mjs} +47 -19
  6. package/dist/{context-tsYPJ2Ew.d.cts → context-BjD_CTxh.d.cts} +1 -1
  7. package/dist/{context-7NyiqIcg.d.ts → context-C2-UDo2c.d.ts} +1 -1
  8. package/dist/{deno-Bp8q024B.mjs → deno-Ci6tSK9-.mjs} +1 -1
  9. package/dist/{docloader-DarxdYmj.mjs → docloader-DZ9h6KJS.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/compound-fanout.test.mjs +3 -3
  12. package/dist/federation/handler-compound-proof.test.mjs +3 -3
  13. package/dist/federation/handler.test.mjs +4 -5
  14. package/dist/federation/hashlink-media.test.mjs +2 -2
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/inbox-report.test.mjs +5 -5
  17. package/dist/federation/metrics.test.mjs +1 -1
  18. package/dist/federation/middleware.test.mjs +7 -7
  19. package/dist/federation/mod.cjs +1 -1
  20. package/dist/federation/mod.d.cts +3 -3
  21. package/dist/federation/mod.d.ts +3 -3
  22. package/dist/federation/mod.js +1 -1
  23. package/dist/federation/outgoing-proof.test.mjs +4 -5
  24. package/dist/federation/portable-actor.test.mjs +3 -3
  25. package/dist/federation/portable-chain.test.mjs +3 -3
  26. package/dist/federation/portable-collection.test.mjs +4 -4
  27. package/dist/federation/portable-delivery.test.mjs +2 -2
  28. package/dist/federation/portable-gateway-keys.test.mjs +4 -4
  29. package/dist/federation/portable-inbox.test.mjs +4 -4
  30. package/dist/federation/portable-parse-uri.test.mjs +1 -1
  31. package/dist/federation/portable-route-activity.test.mjs +2 -2
  32. package/dist/federation/portable.test.mjs +3 -3
  33. package/dist/federation/send.test.mjs +3 -3
  34. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  35. package/dist/federation/tasks/tasks.test.mjs +2 -2
  36. package/dist/federation/temporal.test.mjs +1 -1
  37. package/dist/federation/webfinger.test.mjs +1 -1
  38. package/dist/{federation-BW53Wxj7.cjs → federation-lzy7M3hT.cjs} +48 -20
  39. package/dist/{http-D6JDnBO1.mjs → http-CFyizTHa.mjs} +4 -4
  40. package/dist/{http-Cg5Yj_yk.js → http-Cmz7x6Iw.js} +151 -19
  41. package/dist/{http-Btzv2JZU.cjs → http-D1RPHoq3.cjs} +161 -17
  42. package/dist/{key-DYxuyd-s.d.cts → key-DhsBxxZN.d.ts} +6 -2
  43. package/dist/{key-C1nv7_jD.d.ts → key-nYGY4QB9.d.cts} +6 -2
  44. package/dist/{kv-cache-CamfvHLY.js → kv-cache-C0-HuvwP.js} +1 -1
  45. package/dist/{kv-cache-0qHe-sN1.cjs → kv-cache-Jym5nP3J.cjs} +1 -1
  46. package/dist/{kv-cache-BoekCvYF.mjs → kv-cache-rOQX3I3c.mjs} +1 -1
  47. package/dist/{key-R5cUSA6S.mjs → ld-DJ--ZUpr.mjs} +760 -16
  48. package/dist/{metrics-DUdlIyrB.mjs → metrics-Dwgav7s_.mjs} +1 -1
  49. package/dist/{middleware-Hl0lTClT.mjs → middleware-BbBsa5iR.mjs} +13 -14
  50. package/dist/{middleware-DLB1TqQ1.mjs → middleware-CJWxuUy5.mjs} +1 -1
  51. package/dist/{middleware-BYOXwJvI.js → middleware-CqgRIsWM.js} +48 -20
  52. package/dist/{mod-Dw-nPxQh.d.cts → mod-B5-wdzmJ.d.cts} +1 -1
  53. package/dist/{mod-BojP2Bw3.d.cts → mod-BBPd4M_0.d.cts} +1 -1
  54. package/dist/{mod-CtpF2BU5.d.ts → mod-BRpER-B0.d.ts} +1 -1
  55. package/dist/{mod-Xj5P4s4d.d.ts → mod-CUYBGKof.d.ts} +1 -1
  56. package/dist/{mod-DEZXwV6J.d.ts → mod-DkhfZC1u.d.ts} +1 -1
  57. package/dist/{mod-CavhAgLw.d.cts → mod-xAfaLS4T.d.cts} +1 -1
  58. package/dist/mod.cjs +4 -4
  59. package/dist/mod.d.cts +5 -5
  60. package/dist/mod.d.ts +5 -5
  61. package/dist/mod.js +4 -4
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/{owner-CKHKMnp-.mjs → owner-Btd7SwMj.mjs} +3 -3
  64. package/dist/{portable-collection-CyTnj1m9.cjs → portable-collection-BvWxS1sL.cjs} +1 -1
  65. package/dist/{portable-collection-Dhg0By3t.js → portable-collection-DwQT28O2.js} +1 -1
  66. package/dist/{portable-collection-DxVKitQN.mjs → portable-collection-gb9V8XEO.mjs} +2 -2
  67. package/dist/{portable-key-BOBhrrKN.mjs → portable-key-Cwti99nP.mjs} +1 -1
  68. package/dist/{proof-BGyUYuOb.mjs → proof-Bwzv6mXZ.mjs} +44 -11
  69. package/dist/{send-DmlYxKmb.mjs → send-BrQYUSb4.mjs} +3 -3
  70. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  71. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  72. package/dist/sig/compound-proof-verification.test.mjs +168 -2
  73. package/dist/sig/compound-proof.test.mjs +2 -2
  74. package/dist/sig/http.test.mjs +2 -2
  75. package/dist/sig/key.test.mjs +208 -3
  76. package/dist/sig/ld.test.mjs +1 -2
  77. package/dist/sig/mitra-receive-interop.test.mjs +4 -4
  78. package/dist/sig/mitra-send-interop.test.mjs +3 -3
  79. package/dist/sig/mod.cjs +2 -2
  80. package/dist/sig/mod.d.cts +2 -2
  81. package/dist/sig/mod.d.ts +2 -2
  82. package/dist/sig/mod.js +2 -2
  83. package/dist/sig/owner.test.mjs +1 -1
  84. package/dist/sig/portable-collection.test.mjs +1 -1
  85. package/dist/sig/portable-interop.test.mjs +3 -3
  86. package/dist/sig/portable-key.test.mjs +5 -6
  87. package/dist/sig/proof.test.mjs +3 -3
  88. package/dist/sig/tootik-request-interop.test.mjs +4 -4
  89. package/dist/sig/tootik-send-interop.test.mjs +3 -3
  90. package/dist/sig/verification.test.mjs +3 -3
  91. package/dist/{temporal-Bvota1RR.mjs → temporal-BRaCTxVe.mjs} +1 -1
  92. package/dist/testing/kv.test.mjs +1 -1
  93. package/dist/testing/mod.d.mts +5 -1
  94. package/dist/utils/docloader.test.mjs +2 -2
  95. package/dist/utils/kv-cache.test.mjs +1 -1
  96. package/dist/utils/mod.cjs +1 -1
  97. package/dist/utils/mod.d.cts +1 -1
  98. package/dist/utils/mod.d.ts +1 -1
  99. package/dist/utils/mod.js +1 -1
  100. package/package.json +6 -6
  101. package/dist/ld-B6RQHcnq.mjs +0 -658
@@ -2,15 +2,77 @@ import { Temporal } from "temporal-polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { c as isPortableActorDocument, d as isPortableUri, l as isPortableId, m as parseKeyIdString, s as isCompatibleKeyId } from "./portable-key-id-Ca30-hOa.mjs";
5
- import { a as verificationObservation } from "./verification-Dpfcw8ml.mjs";
6
- import { n as version, t as name } from "./deno-Bp8q024B.mjs";
7
- import { _ as recordKeyLookup, n as getDurationMs, t as classifyFetchError } from "./metrics-DUdlIyrB.mjs";
5
+ import { a as verificationObservation, i as triedKey, n as observeCheck, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
6
+ import { n as version, t as name } from "./deno-Ci6tSK9-.mjs";
7
+ import { _ as recordKeyLookup, n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch, t as classifyFetchError } from "./metrics-Dwgav7s_.mjs";
8
8
  import { n as attachKeyOwnerEvidence, t as MAX_PORTABLE_KEY_TTL } from "./key-owner-evidence-APB6NpSk.mjs";
9
9
  import { getLogger } from "@logtape/logtape";
10
- import { CryptographicKey, Multikey, Object as Object$1, isActor } from "@fedify/vocab";
10
+ import { Activity, CryptographicKey, Multikey, Object as Object$1, getTypeId, isActor } from "@fedify/vocab";
11
11
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
12
- import { FetchError, getDocumentLoader, parseDidKeyVerificationMethod } from "@fedify/vocab-runtime";
12
+ import { FetchError, UrlError, getDocumentLoader, parseDidKeyVerificationMethod } from "@fedify/vocab-runtime";
13
+ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
14
+ import { encodeHex } from "byte-encodings/hex";
15
+ import jsonld from "@fedify/vocab-runtime/jsonld";
13
16
  //#region src/sig/key.ts
17
+ /** Classifies decoding failures without hiding unexpected loader errors. */
18
+ function classifyKeyJsonLdError(error, seen = /* @__PURE__ */ new Set()) {
19
+ if (!(error instanceof Error) || !error.name.startsWith("jsonld.")) return null;
20
+ if (seen.has(error)) throw error;
21
+ seen.add(error);
22
+ const details = error.details;
23
+ if (typeof details?.code !== "string") return null;
24
+ if (details.code !== "loading remote context failed" || !("cause" in details) && !("cause" in error)) return "invalid";
25
+ const cause = "cause" in details ? details.cause : error.cause;
26
+ const nestedFailure = classifyKeyJsonLdError(cause, seen);
27
+ if (nestedFailure != null) return nestedFailure;
28
+ if (cause instanceof SyntaxError) return "invalid";
29
+ if (cause instanceof FetchError || cause instanceof UrlError) return "fetch";
30
+ if (cause instanceof Error && [
31
+ "AbortError",
32
+ "TimeoutError",
33
+ "NetworkError"
34
+ ].includes(cause.name)) return "fetch";
35
+ if (cause instanceof TypeError) {
36
+ const urlCode = cause.code;
37
+ if (cause.name === "InvalidContextReferenceError") return "invalid";
38
+ if (urlCode === "ERR_INVALID_URL" || cause.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(cause.message) || / cannot be parsed as a URL\.?$/.test(cause.message)) return typeof details.url === "string" && /^[A-Za-z][A-Za-z0-9+.-]*:/.test(details.url) && !URL.canParse(details.url) ? "invalid" : "fetch";
39
+ const networkCause = cause.cause;
40
+ const code = cause.code ?? networkCause?.code;
41
+ if (typeof code === "string" && [
42
+ "ECONNREFUSED",
43
+ "ECONNRESET",
44
+ "ECONNABORTED",
45
+ "ETIMEDOUT",
46
+ "EHOSTUNREACH",
47
+ "ENETUNREACH",
48
+ "ENOTFOUND",
49
+ "EAI_AGAIN",
50
+ "UND_ERR_CONNECT_TIMEOUT",
51
+ "UND_ERR_HEADERS_TIMEOUT",
52
+ "UND_ERR_BODY_TIMEOUT",
53
+ "UND_ERR_SOCKET"
54
+ ].includes(code) || /^(fetch failed|Failed to fetch|error sending request|error reading a body from connection|Unable to connect|ConnectionRefused|Network connection lost|The socket connection was closed unexpectedly)/.test(cause.message)) return "fetch";
55
+ }
56
+ throw cause;
57
+ }
58
+ /** Carries a context transport failure through the key decoding boundary. */
59
+ var KeyContextFetchError = class extends Error {
60
+ error;
61
+ constructor(error) {
62
+ super("Failed to fetch a key's JSON-LD context.", { cause: error });
63
+ this.error = error;
64
+ }
65
+ };
66
+ function contextFetchError(error) {
67
+ const seen = /* @__PURE__ */ new Set();
68
+ while (error instanceof Error && !seen.has(error)) {
69
+ seen.add(error);
70
+ const details = error.details;
71
+ if (!error.name.startsWith("jsonld.") || details?.code !== "loading remote context failed") break;
72
+ error = "cause" in details ? details.cause : error.cause;
73
+ }
74
+ return new KeyContextFetchError(error);
75
+ }
14
76
  /**
15
77
  * Checks if the given key is valid and supported. No-op if the key is valid,
16
78
  * otherwise throws an error.
@@ -105,6 +167,9 @@ async function importJwk(jwk, type) {
105
167
  * @internal
106
168
  */
107
169
  async function fetchActorDocument(actorId, options = {}) {
170
+ return await fetchActorDocumentInternal(actorId, options, false);
171
+ }
172
+ async function fetchActorDocumentInternal(actorId, options, propagateContextFetchErrors) {
108
173
  const logger = getLogger([
109
174
  "fedify",
110
175
  "sig",
@@ -139,9 +204,12 @@ async function fetchActorDocument(actorId, options = {}) {
139
204
  baseUrl: documentUrl
140
205
  });
141
206
  } catch (error) {
142
- if (!(error instanceof TypeError)) throw error;
143
- logger.debug("The document served at {documentUrl} is not a valid object: {error}", {
207
+ const failure = classifyKeyJsonLdError(error);
208
+ if (failure === "fetch" && propagateContextFetchErrors) throw contextFetchError(error);
209
+ if (failure == null && !(error instanceof TypeError)) throw error;
210
+ logger.debug("Failed to decode the actor document at {documentUrl}: {error}", {
144
211
  documentUrl: documentUrl.href,
212
+ failure: failure ?? "invalid",
145
213
  error
146
214
  });
147
215
  return null;
@@ -187,6 +255,9 @@ async function fetchActorDocument(actorId, options = {}) {
187
255
  * @internal
188
256
  */
189
257
  async function verifyKeyOwnership(key, options = {}) {
258
+ return await verifyKeyOwnershipInternal(key, options, false);
259
+ }
260
+ async function verifyKeyOwnershipInternal(key, options, propagateContextFetchErrors) {
190
261
  const logger = getLogger([
191
262
  "fedify",
192
263
  "sig",
@@ -196,7 +267,7 @@ async function verifyKeyOwnership(key, options = {}) {
196
267
  if (keyId == null) return null;
197
268
  const claimedOwnerId = key instanceof CryptographicKey ? key.ownerId : key.controllerId;
198
269
  if (claimedOwnerId == null) return null;
199
- const owner = await fetchActorDocument(claimedOwnerId, options);
270
+ const owner = await fetchActorDocumentInternal(claimedOwnerId, options, propagateContextFetchErrors);
200
271
  if (owner == null) {
201
272
  logger.debug("The owner ({claimedOwnerId}) that key {keyId} claims could not be resolved.", {
202
273
  keyId: keyId.href,
@@ -522,6 +593,21 @@ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, {
522
593
  tracerProvider
523
594
  });
524
595
  } catch (e) {
596
+ const failure = classifyKeyJsonLdError(e);
597
+ if (failure === "fetch") throw contextFetchError(e);
598
+ if (failure != null) {
599
+ logger.debug("Failed to decode key {keyId}: {error}", {
600
+ keyId,
601
+ failure,
602
+ error: e
603
+ });
604
+ await keyCache?.set(cacheKey, null);
605
+ await clearFetchErrorMetadata(cacheKey, keyCache);
606
+ return {
607
+ key: null,
608
+ cached: false
609
+ };
610
+ }
525
611
  if (!(e instanceof TypeError)) throw e;
526
612
  try {
527
613
  object = await cls.fromJsonLd(document, {
@@ -530,8 +616,14 @@ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, {
530
616
  tracerProvider
531
617
  });
532
618
  } catch (e) {
533
- if (e instanceof TypeError) {
534
- logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
619
+ const failure = classifyKeyJsonLdError(e);
620
+ if (failure === "fetch") throw contextFetchError(e);
621
+ if (failure != null || e instanceof TypeError) {
622
+ logger.debug("Failed to decode key {keyId}: {error}", {
623
+ keyId,
624
+ failure: failure ?? "invalid",
625
+ error: e
626
+ });
535
627
  await keyCache?.set(cacheKey, null);
536
628
  await clearFetchErrorMetadata(cacheKey, keyCache);
537
629
  return {
@@ -670,16 +762,17 @@ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, {
670
762
  }
671
763
  if (ownerDocument != null && claimedOwnerId == null) key = key instanceof CryptographicKey ? key.clone({ owner: ownerDocument.id }) : key.clone({ controller: ownerDocument.id });
672
764
  else if (claimedOwnerId != null && claimedOwnerId.href !== ownerDocument?.id?.href) {
673
- if (await verifyKeyOwnership(key, {
765
+ if (await verifyKeyOwnershipInternal(key, {
674
766
  documentLoader,
675
767
  contextLoader,
676
768
  tracerProvider
677
- }) == null) {
769
+ }, true) == null) {
678
770
  logger.debug("Failed to verify; the owner {claimedOwnerId} that key {keyId} claims does not list the key as its own.", {
679
771
  keyId,
680
772
  claimedOwnerId: claimedOwnerId.href
681
773
  });
682
774
  await keyCache?.set(cacheKey, null);
775
+ await clearFetchErrorMetadata(cacheKey, keyCache);
683
776
  return {
684
777
  key: null,
685
778
  cached: false
@@ -756,9 +849,17 @@ async function fetchKeyWithResult(cacheKey, cls, options, onCachedUnavailable, o
756
849
  outcome = classified;
757
850
  return errored;
758
851
  }
759
- const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, options, logger);
760
- outcome = { result: resolved.key != null ? "fetched" : "invalid" };
761
- return resolved;
852
+ try {
853
+ const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, options, logger);
854
+ outcome = { result: resolved.key != null ? "fetched" : "invalid" };
855
+ return resolved;
856
+ } catch (error) {
857
+ if (!(error instanceof KeyContextFetchError)) throw error;
858
+ const classified = classifyFetchError(error.error);
859
+ const errored = await onFetchError(error.error, cacheKey, keyId, keyCache, logger);
860
+ outcome = classified;
861
+ return errored;
862
+ }
762
863
  } finally {
763
864
  recordKeyLookup(options.meterProvider, {
764
865
  durationMs: getDurationMs(start),
@@ -948,4 +1049,647 @@ async function fetchKeyInternal(keyId, cls, options = {}) {
948
1049
  });
949
1050
  }
950
1051
  //#endregion
951
- export { fetchKeyDetailed as a, validateCryptoKey as c, fetchKey as i, verifyKeyOwnership as l, exportJwk as n, generateCryptoKeyPair as o, fetchActorDocument as r, importJwk as s, bypassKeyCacheReads as t };
1052
+ //#region src/sig/ld.ts
1053
+ const logger = getLogger([
1054
+ "fedify",
1055
+ "sig",
1056
+ "ld"
1057
+ ]);
1058
+ const localContext = [
1059
+ "https://w3id.org/identity/v1",
1060
+ "https://www.w3.org/ns/activitystreams",
1061
+ "https://w3id.org/security/v1",
1062
+ "https://w3id.org/security/data-integrity/v1"
1063
+ ];
1064
+ const localContextUrls = new Set(localContext);
1065
+ const builtInContextLoader = getDocumentLoader();
1066
+ const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
1067
+ "@graph",
1068
+ "@included",
1069
+ "@reverse"
1070
+ ]);
1071
+ /** @internal */
1072
+ var UnsafeJsonLdError = class extends TypeError {
1073
+ keyword;
1074
+ constructor(keyword) {
1075
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
1076
+ this.keyword = keyword;
1077
+ this.name = "UnsafeJsonLdError";
1078
+ }
1079
+ };
1080
+ /** @internal */
1081
+ var InvalidContextReferenceError = class extends TypeError {
1082
+ reference;
1083
+ constructor(reference) {
1084
+ super(`Invalid JSON-LD context reference: ${reference}.`);
1085
+ this.reference = reference;
1086
+ this.name = "InvalidContextReferenceError";
1087
+ }
1088
+ };
1089
+ function createLoadingRemoteContextFailedError(reference, cause) {
1090
+ const message = cause instanceof Error ? cause.message : String(cause);
1091
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
1092
+ error.name = "jsonld.InvalidUrl";
1093
+ error.details = {
1094
+ code: "loading remote context failed",
1095
+ url: reference
1096
+ };
1097
+ error.cause = cause;
1098
+ return error;
1099
+ }
1100
+ /** @internal */
1101
+ function isClearlyMalformedContextReference(reference) {
1102
+ for (const char of reference) {
1103
+ const code = char.charCodeAt(0);
1104
+ if (code <= 32 || code === 127) return true;
1105
+ }
1106
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
1107
+ for (let i = 0; i < reference.length; i++) {
1108
+ if (reference[i] !== "%") continue;
1109
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
1110
+ i += 2;
1111
+ }
1112
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
1113
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
1114
+ }
1115
+ return false;
1116
+ }
1117
+ function cloneRemoteDocument(remoteDocument) {
1118
+ return structuredClone(remoteDocument);
1119
+ }
1120
+ function createMemoizedDocumentLoader(documentLoader) {
1121
+ const cache = /* @__PURE__ */ new Map();
1122
+ return async (url, options) => {
1123
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
1124
+ let remoteDocument = cache.get(cacheKey);
1125
+ if (remoteDocument == null) {
1126
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
1127
+ remoteDocument.catch(() => {
1128
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
1129
+ });
1130
+ cache.set(cacheKey, remoteDocument);
1131
+ }
1132
+ return cloneRemoteDocument(await remoteDocument);
1133
+ };
1134
+ }
1135
+ /** @internal */
1136
+ function wrapContextLoaderForJsonLd(contextLoader) {
1137
+ const loader = contextLoader ?? builtInContextLoader;
1138
+ return async (url, options) => {
1139
+ try {
1140
+ return await loader(url, options);
1141
+ } catch (error) {
1142
+ if (!isInvalidUrlTypeError(error)) throw error;
1143
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
1144
+ throw createLoadingRemoteContextFailedError(url, error);
1145
+ }
1146
+ };
1147
+ }
1148
+ /** @internal */
1149
+ function getNormalizationContextLoader(contextLoader) {
1150
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
1151
+ return createMemoizedDocumentLoader(async (url, options) => {
1152
+ if (URL.canParse(url)) {
1153
+ const normalizedUrl = new URL(url).href;
1154
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
1155
+ }
1156
+ return await loader(url, options);
1157
+ });
1158
+ }
1159
+ /** @internal */
1160
+ async function compactJsonLd(jsonLd, contextLoader) {
1161
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
1162
+ const signature = hasLds ? jsonLd.signature : void 0;
1163
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
1164
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
1165
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
1166
+ const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
1167
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
1168
+ assertSafeJsonLd(compacted);
1169
+ return compacted;
1170
+ }
1171
+ function createInvalidRemoteContextError(reference) {
1172
+ 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}".`);
1173
+ error.name = "jsonld.InvalidUrl";
1174
+ error.details = {
1175
+ code: "invalid remote context",
1176
+ url: reference
1177
+ };
1178
+ return error;
1179
+ }
1180
+ function getRemoteContext(remoteDocument, reference) {
1181
+ const { contextUrl, documentUrl } = remoteDocument;
1182
+ let { document } = remoteDocument;
1183
+ if (typeof document === "string") document = JSON.parse(document);
1184
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
1185
+ let context = "@context" in document ? document["@context"] : {};
1186
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
1187
+ return {
1188
+ context,
1189
+ baseUrl: documentUrl ?? reference
1190
+ };
1191
+ }
1192
+ function createGraphAliasContextState() {
1193
+ return {
1194
+ graphTerms: /* @__PURE__ */ new Set(),
1195
+ jsonTerms: /* @__PURE__ */ new Set(),
1196
+ propertyContexts: /* @__PURE__ */ new Map(),
1197
+ termTargets: /* @__PURE__ */ new Map()
1198
+ };
1199
+ }
1200
+ function cloneGraphAliasContextState(state) {
1201
+ return {
1202
+ graphTerms: new Set(state.graphTerms),
1203
+ jsonTerms: new Set(state.jsonTerms),
1204
+ propertyContexts: new Map(state.propertyContexts),
1205
+ termTargets: new Map(state.termTargets)
1206
+ };
1207
+ }
1208
+ function resolveContextTarget(target, state) {
1209
+ if (target === "@graph") return target;
1210
+ const mapped = state.termTargets.get(target);
1211
+ if (mapped == null) return target;
1212
+ return mapped;
1213
+ }
1214
+ function getDirectContextTarget(definition) {
1215
+ if (definition === null) return null;
1216
+ if (typeof definition === "string") return definition;
1217
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
1218
+ const id = definition["@id"];
1219
+ if (id === null) return null;
1220
+ if (typeof id === "string") return id;
1221
+ }
1222
+ }
1223
+ function isJsonTypedDefinition(definition) {
1224
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
1225
+ }
1226
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
1227
+ if (target === "@graph") return target;
1228
+ if (seen.has(target)) return target;
1229
+ seen.add(target);
1230
+ if (localTargets.has(target)) {
1231
+ const localTarget = localTargets.get(target);
1232
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
1233
+ }
1234
+ return resolveContextTarget(target, state);
1235
+ }
1236
+ function refreshGraphAliases(state) {
1237
+ state.graphTerms.clear();
1238
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
1239
+ }
1240
+ function normalizeContextReference(reference, baseUrl) {
1241
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
1242
+ return URL.canParse(reference) ? new URL(reference).href : reference;
1243
+ }
1244
+ /** @internal */
1245
+ function isInvalidUrlTypeError(error) {
1246
+ const code = error.code;
1247
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || error.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
1248
+ }
1249
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
1250
+ if (context === null) return createGraphAliasContextState();
1251
+ let nextState = cloneGraphAliasContextState(state);
1252
+ if (Array.isArray(context)) {
1253
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
1254
+ return nextState;
1255
+ }
1256
+ if (typeof context === "string") {
1257
+ const reference = normalizeContextReference(context, baseUrl);
1258
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
1259
+ if (processingContexts.has(cacheKey)) return nextState;
1260
+ processingContexts.add(cacheKey);
1261
+ try {
1262
+ let remoteContext = remoteContextCache.get(cacheKey);
1263
+ if (remoteContext == null) {
1264
+ remoteContext = (async () => {
1265
+ try {
1266
+ return getRemoteContext(await documentLoader(reference), reference);
1267
+ } catch (error) {
1268
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
1269
+ throw error;
1270
+ }
1271
+ })();
1272
+ remoteContextCache.set(cacheKey, remoteContext);
1273
+ }
1274
+ const loadedRemoteContext = await remoteContext;
1275
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
1276
+ } finally {
1277
+ processingContexts.delete(cacheKey);
1278
+ }
1279
+ }
1280
+ if (typeof context === "object" && context != null) {
1281
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
1282
+ const localTargets = /* @__PURE__ */ new Map();
1283
+ for (const [term, definition] of globalThis.Object.entries(context)) {
1284
+ if (term.startsWith("@")) continue;
1285
+ const target = getDirectContextTarget(definition);
1286
+ if (target == null) localTargets.set(term, null);
1287
+ else if (typeof target === "string") localTargets.set(term, target);
1288
+ else localTargets.delete(term);
1289
+ }
1290
+ for (const [term, definition] of globalThis.Object.entries(context)) {
1291
+ if (term.startsWith("@")) continue;
1292
+ if (localTargets.has(term)) {
1293
+ const directTarget = localTargets.get(term);
1294
+ if (directTarget == null) nextState.termTargets.set(term, null);
1295
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
1296
+ } else nextState.termTargets.delete(term);
1297
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
1298
+ context: definition["@context"],
1299
+ baseUrl
1300
+ });
1301
+ else nextState.propertyContexts.delete(term);
1302
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
1303
+ else nextState.jsonTerms.delete(term);
1304
+ }
1305
+ refreshGraphAliases(nextState);
1306
+ }
1307
+ return nextState;
1308
+ }
1309
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
1310
+ if (Array.isArray(jsonLd)) {
1311
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
1312
+ return;
1313
+ }
1314
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
1315
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
1316
+ let state = inheritedState;
1317
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
1318
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
1319
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
1320
+ if (key === "@context") continue;
1321
+ if (jsonLiteralWrapper && key === "@value") continue;
1322
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
1323
+ if (state.jsonTerms.has(key)) continue;
1324
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
1325
+ }
1326
+ }
1327
+ function isJsonLiteralWrapper(value) {
1328
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
1329
+ }
1330
+ /** @internal */
1331
+ function assertSafeJsonLd(jsonLd) {
1332
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
1333
+ else if (typeof jsonLd === "object" && jsonLd != null) {
1334
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
1335
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
1336
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
1337
+ if (jsonLiteralWrapper && key === "@value") continue;
1338
+ assertSafeJsonLd(value);
1339
+ }
1340
+ }
1341
+ }
1342
+ /**
1343
+ * Attaches a LD signature to the given JSON-LD document.
1344
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
1345
+ * modified.
1346
+ * @param signature The signature to attach.
1347
+ * @returns The JSON-LD document with the attached signature.
1348
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
1349
+ * @since 1.0.0
1350
+ */
1351
+ function attachSignature(jsonLd, signature) {
1352
+ if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
1353
+ return {
1354
+ ...jsonLd,
1355
+ signature
1356
+ };
1357
+ }
1358
+ /**
1359
+ * Creates a LD signature for the given JSON-LD document.
1360
+ * @param jsonLd The JSON-LD document to sign.
1361
+ * @param privateKey The private key to sign the document.
1362
+ * @param keyId The ID of the public key that corresponds to the private key.
1363
+ * @param options Additional options for creating the signature.
1364
+ * See also {@link CreateSignatureOptions}.
1365
+ * @return The created signature.
1366
+ * @throws {TypeError} If the private key is invalid or unsupported.
1367
+ * @since 1.0.0
1368
+ */
1369
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
1370
+ validateCryptoKey(privateKey, "private");
1371
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
1372
+ const options = {
1373
+ "@context": "https://w3id.org/identity/v1",
1374
+ creator: keyId.href,
1375
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
1376
+ };
1377
+ const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
1378
+ const messageBytes = new TextEncoder().encode(message);
1379
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
1380
+ return {
1381
+ ...options,
1382
+ type: "RsaSignature2017",
1383
+ signatureValue: encodeBase64(signature)
1384
+ };
1385
+ }
1386
+ /**
1387
+ * Signs the given JSON-LD document with the private key and returns the signed
1388
+ * JSON-LD document.
1389
+ * @param jsonLd The JSON-LD document to sign.
1390
+ * @param privateKey The private key to sign the document.
1391
+ * @param keyId The key ID to use in the signature. It will be used by the
1392
+ * verifier to fetch the corresponding public key.
1393
+ * @param options Additional options for signing the document.
1394
+ * See also {@link SignJsonLdOptions}.
1395
+ * @returns The signed JSON-LD document.
1396
+ * @throws {TypeError} If the private key is invalid or unsupported.
1397
+ * @since 1.0.0
1398
+ */
1399
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
1400
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
1401
+ try {
1402
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
1403
+ if (span.isRecording()) {
1404
+ span.setAttribute("ld_signatures.type", signature.type);
1405
+ span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
1406
+ }
1407
+ return attachSignature(jsonLd, signature);
1408
+ } catch (error) {
1409
+ span.setStatus({
1410
+ code: SpanStatusCode.ERROR,
1411
+ message: String(error)
1412
+ });
1413
+ throw error;
1414
+ } finally {
1415
+ span.end();
1416
+ }
1417
+ });
1418
+ }
1419
+ /**
1420
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
1421
+ * object, without restricting it to a single suite-specific shape.
1422
+ * @param jsonLd The JSON-LD document to check.
1423
+ * @returns `true` if the document has a signature-like object; `false`
1424
+ * otherwise.
1425
+ * @since 2.2.0
1426
+ */
1427
+ function hasSignatureLike(jsonLd) {
1428
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
1429
+ const signature = jsonLd.signature;
1430
+ const hasReference = (value) => {
1431
+ if (typeof value === "string") return true;
1432
+ if (Array.isArray(value)) return value.some(hasReference);
1433
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
1434
+ };
1435
+ const hasSignatureObject = (value) => {
1436
+ if (typeof value !== "object" || value == null) return false;
1437
+ const signatureRecord = value;
1438
+ 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");
1439
+ };
1440
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
1441
+ }
1442
+ /**
1443
+ * Checks if the given JSON-LD document has a Linked Data Signature.
1444
+ * @param jsonLd The JSON-LD document to check.
1445
+ * @returns `true` if the document has a signature; `false` otherwise.
1446
+ * @since 1.0.0
1447
+ */
1448
+ function hasSignature(jsonLd) {
1449
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
1450
+ if ("signature" in jsonLd) {
1451
+ const signature = jsonLd.signature;
1452
+ if (typeof signature !== "object" || signature == null) return false;
1453
+ 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";
1454
+ }
1455
+ return false;
1456
+ }
1457
+ /**
1458
+ * Detaches Linked Data Signatures from the given JSON-LD document.
1459
+ * @param jsonLd The JSON-LD document to modify.
1460
+ * @returns The modified JSON-LD document. If the input document does not
1461
+ * contain a signature, the original document is returned.
1462
+ * @since 1.0.0
1463
+ */
1464
+ function detachSignature(jsonLd) {
1465
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
1466
+ const doc = { ...jsonLd };
1467
+ delete doc.signature;
1468
+ return doc;
1469
+ }
1470
+ /**
1471
+ * Verifies Linked Data Signatures of the given JSON-LD document.
1472
+ *
1473
+ * This is a low-level utility that only checks the cryptographic signature
1474
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
1475
+ * attribution, and owner checks that a complete inbound LD verification
1476
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
1477
+ * the public verification entry point and the one that emits the
1478
+ * `activitypub.signature.verification.duration` metric for the LD path.
1479
+ * `verifySignature` itself only emits
1480
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
1481
+ * that the verification-duration metric is meant to cover happens in
1482
+ * `verifyJsonLd`.
1483
+ * @param jsonLd The JSON-LD document to verify.
1484
+ * @param options Options for verifying the signature.
1485
+ * @returns The public key that signed the document or `null` if the signature
1486
+ * is invalid or the key is not found.
1487
+ * @since 1.0.0
1488
+ */
1489
+ async function verifySignature(jsonLd, options = {}) {
1490
+ if (!hasSignature(jsonLd)) return null;
1491
+ if (options[verificationObservation]?.attempt != null && options[verificationObservation]?.check == null) {
1492
+ const declared = getLdSignatureObject(jsonLd)?.creator;
1493
+ return await observeCheck(options, { mechanism: "linkedData" }, typeof declared === "string" ? declared : null, (observation) => verifySignature(jsonLd, {
1494
+ ...options,
1495
+ [verificationObservation]: observation
1496
+ }));
1497
+ }
1498
+ const sig = jsonLd.signature;
1499
+ let signature;
1500
+ try {
1501
+ signature = decodeBase64(sig.signatureValue);
1502
+ } catch (error) {
1503
+ logger.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
1504
+ ...sig,
1505
+ error
1506
+ });
1507
+ return null;
1508
+ }
1509
+ const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
1510
+ if (key == null) return null;
1511
+ const sigOpts = {
1512
+ ...sig,
1513
+ "@context": "https://w3id.org/identity/v1"
1514
+ };
1515
+ delete sigOpts.type;
1516
+ delete sigOpts.id;
1517
+ delete sigOpts.signatureValue;
1518
+ let sigOptsHash;
1519
+ try {
1520
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
1521
+ } catch (error) {
1522
+ logger.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
1523
+ signatureOptions: sigOpts,
1524
+ error
1525
+ });
1526
+ return null;
1527
+ }
1528
+ const document = { ...jsonLd };
1529
+ delete document.signature;
1530
+ let docHash;
1531
+ try {
1532
+ docHash = await hashJsonLd(document, options.contextLoader);
1533
+ } catch (error) {
1534
+ logger.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
1535
+ document,
1536
+ error
1537
+ });
1538
+ return null;
1539
+ }
1540
+ const encoder = new TextEncoder();
1541
+ const message = sigOptsHash + docHash;
1542
+ const messageBytes = encoder.encode(message);
1543
+ triedKey(options, key);
1544
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
1545
+ if (cached) {
1546
+ logger.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
1547
+ keyId: sig.creator,
1548
+ ...sig
1549
+ });
1550
+ const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
1551
+ ...options,
1552
+ keyCache: bypassKeyCacheReads(options.keyCache)
1553
+ }));
1554
+ if (key == null) return null;
1555
+ triedKey(options, key);
1556
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
1557
+ }
1558
+ logger.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}", {
1559
+ keyId: sig.creator,
1560
+ ...sig,
1561
+ message
1562
+ });
1563
+ return null;
1564
+ }
1565
+ /**
1566
+ * Known Linked Data Signature `type` values, used to keep
1567
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
1568
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
1569
+ * only from external documents and are dropped from the metric attribute to
1570
+ * avoid attacker-controlled cardinality.
1571
+ */
1572
+ const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
1573
+ /**
1574
+ * Reports only whether a `signature` key is present on the document, with
1575
+ * no shape check on its value. This is intentionally looser than
1576
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
1577
+ * and {@link hasSignatureLike} (which structurally accepts several known
1578
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
1579
+ * unsupported signature payload (classified as `rejected`) apart from a
1580
+ * truly unsigned document (classified as `missing`), and only this
1581
+ * presence-only check captures both cases.
1582
+ */
1583
+ function hasLdSignatureProperty(jsonLd) {
1584
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
1585
+ }
1586
+ function getLdSignatureObject(jsonLd) {
1587
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
1588
+ const { signature } = jsonLd;
1589
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
1590
+ return signature;
1591
+ }
1592
+ /**
1593
+ * Verify the authenticity of the given JSON-LD document using Linked Data
1594
+ * Signatures. If the document is signed, this function verifies the signature
1595
+ * and checks if the document is attributed to the owner of the public key.
1596
+ * If the document is not signed, this function returns `false`.
1597
+ * @param jsonLd The JSON-LD document to verify.
1598
+ * @param options Options for verifying the document.
1599
+ * @returns `true` if the document is authentic; `false` otherwise.
1600
+ */
1601
+ async function verifyJsonLd(jsonLd, options = {}) {
1602
+ return await verifyJsonLdInternal(jsonLd, options, true);
1603
+ }
1604
+ /** @internal */
1605
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
1606
+ return await verifyJsonLdInternal(jsonLd, options, false);
1607
+ }
1608
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
1609
+ if (options[verificationObservation]?.attempt == null) return await observeAttempt({
1610
+ ...options,
1611
+ [verificationObservation]: options[verificationObservation] ?? { attempts: [] }
1612
+ }, "linkedData", (observation) => verifyJsonLdInternal(jsonLd, {
1613
+ ...options,
1614
+ [verificationObservation]: observation
1615
+ }, compact), (value) => value);
1616
+ const observation = options[verificationObservation];
1617
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
1618
+ const start = performance.now();
1619
+ let verified = false;
1620
+ let threw = false;
1621
+ let signatureType;
1622
+ try {
1623
+ const verificationOptions = hasSignature(jsonLd) ? {
1624
+ ...options,
1625
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
1626
+ } : options;
1627
+ const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
1628
+ const object = await Object$1.fromJsonLd(compacted, verificationOptions);
1629
+ observation?.parsedObject?.(object);
1630
+ if (observation?.subject != null) observation.subject.id = object.id == null ? null : new URL(object.id.href);
1631
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
1632
+ span.setAttribute("activitypub.object.type", getTypeId(object).href);
1633
+ const sig = getLdSignatureObject(jsonLd);
1634
+ if (sig != null) {
1635
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
1636
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
1637
+ if (typeof sig.type === "string") {
1638
+ span.setAttribute("ld_signatures.type", sig.type);
1639
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
1640
+ }
1641
+ }
1642
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
1643
+ if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
1644
+ const key = await verifySignature(compacted, verificationOptions);
1645
+ if (key == null) {
1646
+ if (observation?.attempt != null && !hasLdSignatureProperty(jsonLd)) observation.attempt.reason = { type: "noSignature" };
1647
+ return false;
1648
+ }
1649
+ if (key.ownerId == null) {
1650
+ if (observation?.attempt != null) observation.attempt.reason = { type: "missingOwner" };
1651
+ logger.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
1652
+ return false;
1653
+ }
1654
+ attributions.delete(key.ownerId.href);
1655
+ if (attributions.size > 0) {
1656
+ if (observation?.attempt != null) observation.attempt.reason = {
1657
+ type: "uncoveredAttribution",
1658
+ attributionIds: [...attributions].map((id) => new URL(id))
1659
+ };
1660
+ logger.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
1661
+ return false;
1662
+ }
1663
+ verified = true;
1664
+ return true;
1665
+ } catch (error) {
1666
+ threw = true;
1667
+ span.setStatus({
1668
+ code: SpanStatusCode.ERROR,
1669
+ message: String(error)
1670
+ });
1671
+ throw error;
1672
+ } finally {
1673
+ if (observation?.attempt?.reason != null) {
1674
+ span.setAttribute("activitypub.verification.failure_reason", observation.attempt.reason.type);
1675
+ span.setStatus({ code: SpanStatusCode.ERROR });
1676
+ }
1677
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
1678
+ getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, {
1679
+ ldType: signatureType,
1680
+ verificationFailureReason: verified || threw ? void 0 : observation?.attempt?.reason?.type ?? (hasLdSignatureProperty(jsonLd) ? "signatureVerificationFailed" : "noSignature")
1681
+ });
1682
+ span.end();
1683
+ }
1684
+ });
1685
+ }
1686
+ async function hashJsonLd(jsonLd, contextLoader) {
1687
+ const canon = await jsonld.canonize(jsonLd, {
1688
+ format: "application/n-quads",
1689
+ documentLoader: contextLoader ?? getDocumentLoader()
1690
+ });
1691
+ const encoder = new TextEncoder();
1692
+ return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
1693
+ }
1694
+ //#endregion
1695
+ export { generateCryptoKeyPair as C, verifyKeyOwnership as E, fetchKeyDetailed as S, validateCryptoKey as T, wrapContextLoaderForJsonLd as _, compactJsonLd as a, fetchActorDocument as b, getNormalizationContextLoader as c, isClearlyMalformedContextReference as d, isInvalidUrlTypeError as f, verifySignature as g, verifyJsonLd as h, attachSignature as i, hasSignature as l, verifyCompactJsonLd as m, UnsafeJsonLdError as n, createSignature as o, signJsonLd as p, assertSafeJsonLd as r, detachSignature as s, InvalidContextReferenceError as t, hasSignatureLike as u, bypassKeyCacheReads as v, importJwk as w, fetchKey as x, exportJwk as y };