@fedify/fedify 2.3.0-dev.994 → 2.3.0-pr.809.36

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 (138) hide show
  1. package/README.md +16 -7
  2. package/dist/{assert-DikXweDx.mjs → assert-OguE97r2.mjs} +1 -1
  3. package/dist/{assert_instance_of-C4Ri6VuN.mjs → assert_instance_of-DBC5X09g.mjs} +1 -1
  4. package/dist/{assert_not_equals--wG9hV7u.mjs → assert_not_equals-DkVK8oqV.mjs} +1 -1
  5. package/dist/{assert_rejects-B-qJtC9Z.mjs → assert_rejects-DN60FHPX.mjs} +28 -3
  6. package/dist/{assert_strict_equals-Dmjbg-bA.mjs → assert_strict_equals-XEgZAlrj.mjs} +1 -1
  7. package/dist/{assert_throws-4NwKEy2q.mjs → assert_throws-BOkhLGYc.mjs} +1 -1
  8. package/dist/{builder-yAlpiIqP.mjs → builder-DSZ7FZmg.mjs} +96 -42
  9. package/dist/{chunk-nlSIicah.js → chunk-CRNNMoPX.js} +2 -2
  10. package/dist/circuit-breaker-CSWsyoef.mjs +337 -0
  11. package/dist/{client-z-8dc-e1.d.cts → client-CAM_bQXx.d.cts} +1 -0
  12. package/dist/{client-AtlibPOU.d.ts → client-CSddvgWN.d.ts} +1 -2
  13. package/dist/compat/mod.d.cts +2 -1
  14. package/dist/compat/mod.d.ts +2 -3
  15. package/dist/compat/mod.js +3 -3
  16. package/dist/compat/outgoing-jsonld.test.mjs +4 -4
  17. package/dist/compat/public-audience.test.mjs +4 -4
  18. package/dist/compat/transformers.test.mjs +5 -5
  19. package/dist/{context-BzH2-ajs.d.ts → context-BBVLF7lx.d.cts} +342 -269
  20. package/dist/{context-DJGagtNd.d.cts → context-BU6jSQdo.d.ts} +344 -266
  21. package/dist/{context-Dk_tacqz.mjs → context-DVoTs_wM.mjs} +64 -5
  22. package/dist/{deno-XBVlKnOX.mjs → deno-DCdM7d93.mjs} +1 -1
  23. package/dist/{docloader-DPp-X6gk.mjs → docloader-B7mVwA5_.mjs} +4 -4
  24. package/dist/{esm-DVILvP5e.mjs → esm-vrlUxr60.mjs} +4 -7
  25. package/dist/federation/builder.test.mjs +163 -11
  26. package/dist/federation/circuit-breaker.test.d.mts +2 -0
  27. package/dist/federation/circuit-breaker.test.mjs +446 -0
  28. package/dist/federation/collection.test.mjs +3 -3
  29. package/dist/federation/handler.test.mjs +1770 -29
  30. package/dist/federation/idempotency.test.mjs +5 -5
  31. package/dist/federation/inbox.test.mjs +4 -4
  32. package/dist/federation/keycache.test.mjs +5 -5
  33. package/dist/federation/kv.test.mjs +2 -2
  34. package/dist/federation/metrics.test.d.mts +2 -0
  35. package/dist/federation/metrics.test.mjs +634 -0
  36. package/dist/federation/middleware.test.mjs +4036 -146
  37. package/dist/federation/mod.cjs +195 -14
  38. package/dist/federation/mod.d.cts +6 -4
  39. package/dist/federation/mod.d.ts +6 -6
  40. package/dist/federation/mod.js +192 -14
  41. package/dist/federation/mq.test.mjs +176 -15
  42. package/dist/federation/negotiation.test.mjs +4 -4
  43. package/dist/federation/retry.test.mjs +3 -3
  44. package/dist/federation/router.test.mjs +190 -9
  45. package/dist/federation/send.test.mjs +153 -15
  46. package/dist/federation/temporal.test.d.mts +2 -0
  47. package/dist/federation/temporal.test.mjs +71 -0
  48. package/dist/federation/webfinger.test.mjs +150 -5
  49. package/dist/{http-CSlLA54v.mjs → http-BufbkLuW.mjs} +146 -47
  50. package/dist/{http-B4rrzxtg.js → http-Dh18nwJg.js} +994 -64
  51. package/dist/{http-aQzN9Ayi.d.ts → http-VyDTd4G3.d.cts} +15 -3
  52. package/dist/{http-BrGqJDXL.cjs → http-gOiudB3g.cjs} +1099 -61
  53. package/dist/{http-CrGuipxe.d.cts → http-lf8Hsd91.d.ts} +15 -1
  54. package/dist/{key-Bzx--sHD.mjs → key-DZdKLJXT.mjs} +43 -18
  55. package/dist/{kv-CbLNp3zQ.d.cts → kv-D6hNiMTK.d.ts} +1 -0
  56. package/dist/{kv-cache-DI-Sk7-I.cjs → kv-cache-BuK_nlpY.cjs} +20 -3
  57. package/dist/{kv-cache-U__xU4qR.mjs → kv-cache-C7SQnkGI.mjs} +21 -3
  58. package/dist/{kv-cache-EMIqoIuB.js → kv-cache-DNDSb6Po.js} +20 -3
  59. package/dist/{kv-GFYnFoOl.d.ts → kv-gJ8LYbxX.d.cts} +1 -3
  60. package/dist/ld-0Lsznacf.mjs +626 -0
  61. package/dist/metrics-BHeWd24f.mjs +815 -0
  62. package/dist/{middleware-zjZ6AFCW.mjs → middleware-BNANvDh2.mjs} +1 -1
  63. package/dist/{middleware-nidH7VZH.js → middleware-BgzRkDcm.js} +2260 -556
  64. package/dist/{middleware-An4DjES4.cjs → middleware-D-iES1nQ.cjs} +2318 -623
  65. package/dist/{middleware-K1g6bEkV.mjs → middleware-EV6J_eAc.mjs} +1639 -373
  66. package/dist/{mod-CR8soWa9.d.ts → mod-B0hW12_O.d.cts} +26 -4
  67. package/dist/mod-C0F6kvgS.d.cts +182 -0
  68. package/dist/{mod-Cr3f-ACa.d.cts → mod-COIAjwRS.d.ts} +26 -2
  69. package/dist/{mod-CMEbIaNh.d.cts → mod-DFvNJcNb.d.ts} +56 -4
  70. package/dist/mod-vPYVoa5n.d.ts +182 -0
  71. package/dist/{mod-CLgIXe9w.d.ts → mod-yvIXFAEi.d.cts} +56 -6
  72. package/dist/mod.cjs +9 -6
  73. package/dist/mod.d.cts +12 -10
  74. package/dist/mod.d.ts +12 -12
  75. package/dist/mod.js +11 -11
  76. package/dist/mq-D-nlpY04.d.ts +208 -0
  77. package/dist/mq-D8uSFzxe.d.cts +208 -0
  78. package/dist/{negotiation-SQvQgUqe.mjs → negotiation-DDstyBvc.mjs} +29 -0
  79. package/dist/nodeinfo/client.test.mjs +4 -4
  80. package/dist/nodeinfo/handler.test.mjs +4 -4
  81. package/dist/nodeinfo/mod.d.cts +2 -1
  82. package/dist/nodeinfo/mod.d.ts +2 -3
  83. package/dist/nodeinfo/mod.js +3 -3
  84. package/dist/nodeinfo/types.test.mjs +3 -3
  85. package/dist/otel/exporter.test.mjs +28 -25
  86. package/dist/otel/mod.cjs +6 -5
  87. package/dist/otel/mod.d.cts +5 -3
  88. package/dist/otel/mod.d.ts +5 -5
  89. package/dist/otel/mod.js +8 -7
  90. package/dist/{outgoing-jsonld-CNmZLixq.mjs → outgoing-jsonld-L_DbOaFe.mjs} +2 -2
  91. package/dist/{owner-C-tqfvxn.mjs → owner-Cl-1cAR8.mjs} +2 -2
  92. package/dist/{owner-CptqhsOy.d.cts → owner-CnngXDNJ.d.ts} +2 -1
  93. package/dist/{owner-74ARJ5TL.d.ts → owner-DEvZuyOE.d.cts} +2 -3
  94. package/dist/{proof-Bbbwf8_x.js → proof-CyXndf6-.js} +378 -15
  95. package/dist/{proof-BlmRPzrK.mjs → proof-Dnz8jtiQ.mjs} +26 -8
  96. package/dist/{proof-BW89QMVB.cjs → proof-tz35unOj.cjs} +432 -15
  97. package/dist/runtime/mod.d.cts +1 -0
  98. package/dist/runtime/mod.d.ts +1 -2
  99. package/dist/runtime/mod.js +3 -3
  100. package/dist/{send-05pJLcb6.mjs → send-DIbBYN5P.mjs} +72 -26
  101. package/dist/sig/http.test.mjs +356 -33
  102. package/dist/sig/key.test.mjs +103 -6
  103. package/dist/sig/ld.test.mjs +696 -7
  104. package/dist/sig/mod.cjs +2 -2
  105. package/dist/sig/mod.d.cts +4 -3
  106. package/dist/sig/mod.d.ts +4 -5
  107. package/dist/sig/mod.js +4 -4
  108. package/dist/sig/owner.test.mjs +6 -6
  109. package/dist/sig/proof.test.mjs +169 -8
  110. package/dist/{std__assert-CRDpx_HF.mjs → std__assert-BBjXFNOb.mjs} +5 -30
  111. package/dist/temporal-BEwob1Vg.mjs +95 -0
  112. package/dist/testing/mod.d.mts +110 -10
  113. package/dist/testing/mod.mjs +1 -2
  114. package/dist/{transformers-ve6e2xcg.js → transformers-BGMIq1cs.js} +2 -2
  115. package/dist/{types-hvL8ElAs.js → types-CAY3OdLq.js} +2 -2
  116. package/dist/utils/docloader.test.mjs +6 -6
  117. package/dist/utils/kv-cache.test.mjs +67 -2
  118. package/dist/utils/mod.cjs +1 -1
  119. package/dist/utils/mod.d.cts +2 -1
  120. package/dist/utils/mod.d.ts +2 -3
  121. package/dist/utils/mod.js +3 -3
  122. package/dist/vocab/cjs.test.mjs +1 -1
  123. package/dist/vocab/mod.d.cts +1 -0
  124. package/dist/vocab/mod.d.ts +1 -2
  125. package/dist/vocab/mod.js +2 -2
  126. package/package.json +16 -16
  127. package/dist/ld-DR78beiv.mjs +0 -279
  128. package/dist/middleware-BFBaR0mF.cjs +0 -4
  129. package/dist/mod-2d12ffz3.d.ts +0 -64
  130. package/dist/mod-D35TRn09.d.cts +0 -62
  131. package/dist/router-CrMLXoOr.mjs +0 -114
  132. package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-tztVvlNb.mjs} +0 -0
  133. package/dist/{assert_equals-Ew3jOFa3.mjs → assert_equals-C-ZRDbaf.mjs} +0 -0
  134. package/dist/{client-D_1QpnWt.mjs → client-ByXmQhYD.mjs} +1 -1
  135. package/dist/{collection-D-HqUuA2.mjs → collection-Cc3DVAhE.mjs} +0 -0
  136. package/dist/{keycache-EGATflN-.mjs → keycache-BeU0LCII.mjs} +0 -0
  137. package/dist/{public-audience-DYFHzm_c.mjs → public-audience-Cvbr2Gzt.mjs} +1 -1
  138. /package/dist/{retry-bMXBL97A.mjs → retry-CXg_MBI-.mjs} +0 -0
@@ -0,0 +1,626 @@
1
+ import "@js-temporal/polyfill";
2
+ import "urlpattern-polyfill";
3
+ globalThis.addEventListener = () => {};
4
+ import { n as version, t as name } from "./deno-DCdM7d93.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-BHeWd24f.mjs";
6
+ import { n as fetchKey, o as validateCryptoKey } from "./key-DZdKLJXT.mjs";
7
+ import { getLogger } from "@logtape/logtape";
8
+ import { Activity, CryptographicKey, Object as Object$1, getTypeId } from "@fedify/vocab";
9
+ import { SpanStatusCode, trace } from "@opentelemetry/api";
10
+ import { getDocumentLoader } from "@fedify/vocab-runtime";
11
+ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
12
+ import { encodeHex } from "byte-encodings/hex";
13
+ import jsonld from "@fedify/vocab-runtime/jsonld";
14
+ //#region src/sig/ld.ts
15
+ const logger = getLogger([
16
+ "fedify",
17
+ "sig",
18
+ "ld"
19
+ ]);
20
+ const localContext = [
21
+ "https://w3id.org/identity/v1",
22
+ "https://www.w3.org/ns/activitystreams",
23
+ "https://w3id.org/security/v1",
24
+ "https://w3id.org/security/data-integrity/v1"
25
+ ];
26
+ const localContextUrls = new Set(localContext);
27
+ const builtInContextLoader = getDocumentLoader();
28
+ const disallowedJsonLdKeywords = new Set([
29
+ "@graph",
30
+ "@included",
31
+ "@reverse"
32
+ ]);
33
+ /** @internal */
34
+ var UnsafeJsonLdError = class extends TypeError {
35
+ keyword;
36
+ constructor(keyword) {
37
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
38
+ this.keyword = keyword;
39
+ this.name = "UnsafeJsonLdError";
40
+ }
41
+ };
42
+ /** @internal */
43
+ var InvalidContextReferenceError = class extends TypeError {
44
+ reference;
45
+ constructor(reference) {
46
+ super(`Invalid JSON-LD context reference: ${reference}.`);
47
+ this.reference = reference;
48
+ this.name = "InvalidContextReferenceError";
49
+ }
50
+ };
51
+ function createLoadingRemoteContextFailedError(reference, cause) {
52
+ const message = cause instanceof Error ? cause.message : String(cause);
53
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
54
+ error.name = "jsonld.InvalidUrl";
55
+ error.details = {
56
+ code: "loading remote context failed",
57
+ url: reference
58
+ };
59
+ error.cause = cause;
60
+ return error;
61
+ }
62
+ /** @internal */
63
+ function isClearlyMalformedContextReference(reference) {
64
+ for (const char of reference) {
65
+ const code = char.charCodeAt(0);
66
+ if (code <= 32 || code === 127) return true;
67
+ }
68
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
69
+ for (let i = 0; i < reference.length; i++) {
70
+ if (reference[i] !== "%") continue;
71
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
72
+ i += 2;
73
+ }
74
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
75
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
76
+ }
77
+ return false;
78
+ }
79
+ function cloneRemoteDocument(remoteDocument) {
80
+ return structuredClone(remoteDocument);
81
+ }
82
+ function createMemoizedDocumentLoader(documentLoader) {
83
+ const cache = /* @__PURE__ */ new Map();
84
+ return async (url, options) => {
85
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
86
+ let remoteDocument = cache.get(cacheKey);
87
+ if (remoteDocument == null) {
88
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
89
+ remoteDocument.catch(() => {
90
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
91
+ });
92
+ cache.set(cacheKey, remoteDocument);
93
+ }
94
+ return cloneRemoteDocument(await remoteDocument);
95
+ };
96
+ }
97
+ /** @internal */
98
+ function wrapContextLoaderForJsonLd(contextLoader) {
99
+ const loader = contextLoader ?? builtInContextLoader;
100
+ return async (url, options) => {
101
+ try {
102
+ return await loader(url, options);
103
+ } catch (error) {
104
+ if (!isInvalidUrlTypeError(error)) throw error;
105
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
106
+ throw createLoadingRemoteContextFailedError(url, error);
107
+ }
108
+ };
109
+ }
110
+ /** @internal */
111
+ function getNormalizationContextLoader(contextLoader) {
112
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
113
+ return createMemoizedDocumentLoader(async (url, options) => {
114
+ if (URL.canParse(url)) {
115
+ const normalizedUrl = new URL(url).href;
116
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
117
+ }
118
+ return await loader(url, options);
119
+ });
120
+ }
121
+ /** @internal */
122
+ async function compactJsonLd(jsonLd, contextLoader) {
123
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
124
+ const signature = hasLds ? jsonLd.signature : void 0;
125
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
126
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
127
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
128
+ const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
129
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
130
+ assertSafeJsonLd(compacted);
131
+ return compacted;
132
+ }
133
+ function createInvalidRemoteContextError(reference) {
134
+ 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}".`);
135
+ error.name = "jsonld.InvalidUrl";
136
+ error.details = {
137
+ code: "invalid remote context",
138
+ url: reference
139
+ };
140
+ return error;
141
+ }
142
+ function getRemoteContext(remoteDocument, reference) {
143
+ const { contextUrl, documentUrl } = remoteDocument;
144
+ let { document } = remoteDocument;
145
+ if (typeof document === "string") document = JSON.parse(document);
146
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
147
+ let context = "@context" in document ? document["@context"] : {};
148
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
149
+ return {
150
+ context,
151
+ baseUrl: documentUrl ?? reference
152
+ };
153
+ }
154
+ function createGraphAliasContextState() {
155
+ return {
156
+ graphTerms: /* @__PURE__ */ new Set(),
157
+ jsonTerms: /* @__PURE__ */ new Set(),
158
+ propertyContexts: /* @__PURE__ */ new Map(),
159
+ termTargets: /* @__PURE__ */ new Map()
160
+ };
161
+ }
162
+ function cloneGraphAliasContextState(state) {
163
+ return {
164
+ graphTerms: new Set(state.graphTerms),
165
+ jsonTerms: new Set(state.jsonTerms),
166
+ propertyContexts: new Map(state.propertyContexts),
167
+ termTargets: new Map(state.termTargets)
168
+ };
169
+ }
170
+ function resolveContextTarget(target, state) {
171
+ if (target === "@graph") return target;
172
+ const mapped = state.termTargets.get(target);
173
+ if (mapped == null) return target;
174
+ return mapped;
175
+ }
176
+ function getDirectContextTarget(definition) {
177
+ if (definition === null) return null;
178
+ if (typeof definition === "string") return definition;
179
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
180
+ const id = definition["@id"];
181
+ if (id === null) return null;
182
+ if (typeof id === "string") return id;
183
+ }
184
+ }
185
+ function isJsonTypedDefinition(definition) {
186
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
187
+ }
188
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
189
+ if (target === "@graph") return target;
190
+ if (seen.has(target)) return target;
191
+ seen.add(target);
192
+ if (localTargets.has(target)) {
193
+ const localTarget = localTargets.get(target);
194
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
195
+ }
196
+ return resolveContextTarget(target, state);
197
+ }
198
+ function refreshGraphAliases(state) {
199
+ state.graphTerms.clear();
200
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
201
+ }
202
+ function normalizeContextReference(reference, baseUrl) {
203
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
204
+ return URL.canParse(reference) ? new URL(reference).href : reference;
205
+ }
206
+ /** @internal */
207
+ function isInvalidUrlTypeError(error) {
208
+ const code = error.code;
209
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
210
+ }
211
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
212
+ if (context === null) return createGraphAliasContextState();
213
+ let nextState = cloneGraphAliasContextState(state);
214
+ if (Array.isArray(context)) {
215
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
216
+ return nextState;
217
+ }
218
+ if (typeof context === "string") {
219
+ const reference = normalizeContextReference(context, baseUrl);
220
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
221
+ if (processingContexts.has(cacheKey)) return nextState;
222
+ processingContexts.add(cacheKey);
223
+ try {
224
+ let remoteContext = remoteContextCache.get(cacheKey);
225
+ if (remoteContext == null) {
226
+ remoteContext = (async () => {
227
+ try {
228
+ return getRemoteContext(await documentLoader(reference), reference);
229
+ } catch (error) {
230
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
231
+ throw error;
232
+ }
233
+ })();
234
+ remoteContextCache.set(cacheKey, remoteContext);
235
+ }
236
+ const loadedRemoteContext = await remoteContext;
237
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
238
+ } finally {
239
+ processingContexts.delete(cacheKey);
240
+ }
241
+ }
242
+ if (typeof context === "object" && context != null) {
243
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
244
+ const localTargets = /* @__PURE__ */ new Map();
245
+ for (const [term, definition] of globalThis.Object.entries(context)) {
246
+ if (term.startsWith("@")) continue;
247
+ const target = getDirectContextTarget(definition);
248
+ if (target == null) localTargets.set(term, null);
249
+ else if (typeof target === "string") localTargets.set(term, target);
250
+ else localTargets.delete(term);
251
+ }
252
+ for (const [term, definition] of globalThis.Object.entries(context)) {
253
+ if (term.startsWith("@")) continue;
254
+ if (localTargets.has(term)) {
255
+ const directTarget = localTargets.get(term);
256
+ if (directTarget == null) nextState.termTargets.set(term, null);
257
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
258
+ } else nextState.termTargets.delete(term);
259
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
260
+ context: definition["@context"],
261
+ baseUrl
262
+ });
263
+ else nextState.propertyContexts.delete(term);
264
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
265
+ else nextState.jsonTerms.delete(term);
266
+ }
267
+ refreshGraphAliases(nextState);
268
+ }
269
+ return nextState;
270
+ }
271
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
272
+ if (Array.isArray(jsonLd)) {
273
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
274
+ return;
275
+ }
276
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
277
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
278
+ let state = inheritedState;
279
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
280
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
281
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
282
+ if (key === "@context") continue;
283
+ if (jsonLiteralWrapper && key === "@value") continue;
284
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
285
+ if (state.jsonTerms.has(key)) continue;
286
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
287
+ }
288
+ }
289
+ function isJsonLiteralWrapper(value) {
290
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
291
+ }
292
+ /** @internal */
293
+ function assertSafeJsonLd(jsonLd) {
294
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
295
+ else if (typeof jsonLd === "object" && jsonLd != null) {
296
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
297
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
298
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
299
+ if (jsonLiteralWrapper && key === "@value") continue;
300
+ assertSafeJsonLd(value);
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Attaches a LD signature to the given JSON-LD document.
306
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
307
+ * modified.
308
+ * @param signature The signature to attach.
309
+ * @returns The JSON-LD document with the attached signature.
310
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
311
+ * @since 1.0.0
312
+ */
313
+ function attachSignature(jsonLd, signature) {
314
+ if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
315
+ return {
316
+ ...jsonLd,
317
+ signature
318
+ };
319
+ }
320
+ /**
321
+ * Creates a LD signature for the given JSON-LD document.
322
+ * @param jsonLd The JSON-LD document to sign.
323
+ * @param privateKey The private key to sign the document.
324
+ * @param keyId The ID of the public key that corresponds to the private key.
325
+ * @param options Additional options for creating the signature.
326
+ * See also {@link CreateSignatureOptions}.
327
+ * @return The created signature.
328
+ * @throws {TypeError} If the private key is invalid or unsupported.
329
+ * @since 1.0.0
330
+ */
331
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
332
+ validateCryptoKey(privateKey, "private");
333
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
334
+ const options = {
335
+ "@context": "https://w3id.org/identity/v1",
336
+ creator: keyId.href,
337
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
338
+ };
339
+ const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
340
+ const messageBytes = new TextEncoder().encode(message);
341
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
342
+ return {
343
+ ...options,
344
+ type: "RsaSignature2017",
345
+ signatureValue: encodeBase64(signature)
346
+ };
347
+ }
348
+ /**
349
+ * Signs the given JSON-LD document with the private key and returns the signed
350
+ * JSON-LD document.
351
+ * @param jsonLd The JSON-LD document to sign.
352
+ * @param privateKey The private key to sign the document.
353
+ * @param keyId The key ID to use in the signature. It will be used by the
354
+ * verifier to fetch the corresponding public key.
355
+ * @param options Additional options for signing the document.
356
+ * See also {@link SignJsonLdOptions}.
357
+ * @returns The signed JSON-LD document.
358
+ * @throws {TypeError} If the private key is invalid or unsupported.
359
+ * @since 1.0.0
360
+ */
361
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
362
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
363
+ try {
364
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
365
+ if (span.isRecording()) {
366
+ span.setAttribute("ld_signatures.type", signature.type);
367
+ span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
368
+ }
369
+ return attachSignature(jsonLd, signature);
370
+ } catch (error) {
371
+ span.setStatus({
372
+ code: SpanStatusCode.ERROR,
373
+ message: String(error)
374
+ });
375
+ throw error;
376
+ } finally {
377
+ span.end();
378
+ }
379
+ });
380
+ }
381
+ /**
382
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
383
+ * object, without restricting it to a single suite-specific shape.
384
+ * @param jsonLd The JSON-LD document to check.
385
+ * @returns `true` if the document has a signature-like object; `false`
386
+ * otherwise.
387
+ * @since 2.2.0
388
+ */
389
+ function hasSignatureLike(jsonLd) {
390
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
391
+ const signature = jsonLd.signature;
392
+ const hasReference = (value) => {
393
+ if (typeof value === "string") return true;
394
+ if (Array.isArray(value)) return value.some(hasReference);
395
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
396
+ };
397
+ const hasSignatureObject = (value) => {
398
+ if (typeof value !== "object" || value == null) return false;
399
+ const signatureRecord = value;
400
+ 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");
401
+ };
402
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
403
+ }
404
+ /**
405
+ * Checks if the given JSON-LD document has a Linked Data Signature.
406
+ * @param jsonLd The JSON-LD document to check.
407
+ * @returns `true` if the document has a signature; `false` otherwise.
408
+ * @since 1.0.0
409
+ */
410
+ function hasSignature(jsonLd) {
411
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
412
+ if ("signature" in jsonLd) {
413
+ const signature = jsonLd.signature;
414
+ if (typeof signature !== "object" || signature == null) return false;
415
+ 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";
416
+ }
417
+ return false;
418
+ }
419
+ /**
420
+ * Detaches Linked Data Signatures from the given JSON-LD document.
421
+ * @param jsonLd The JSON-LD document to modify.
422
+ * @returns The modified JSON-LD document. If the input document does not
423
+ * contain a signature, the original document is returned.
424
+ * @since 1.0.0
425
+ */
426
+ function detachSignature(jsonLd) {
427
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
428
+ const doc = { ...jsonLd };
429
+ delete doc.signature;
430
+ return doc;
431
+ }
432
+ /**
433
+ * Verifies Linked Data Signatures of the given JSON-LD document.
434
+ *
435
+ * This is a low-level utility that only checks the cryptographic signature
436
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
437
+ * attribution, and owner checks that a complete inbound LD verification
438
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
439
+ * the public verification entry point and the one that emits the
440
+ * `activitypub.signature.verification.duration` metric for the LD path.
441
+ * `verifySignature` itself only emits
442
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
443
+ * that the verification-duration metric is meant to cover happens in
444
+ * `verifyJsonLd`.
445
+ * @param jsonLd The JSON-LD document to verify.
446
+ * @param options Options for verifying the signature.
447
+ * @returns The public key that signed the document or `null` if the signature
448
+ * is invalid or the key is not found.
449
+ * @since 1.0.0
450
+ */
451
+ async function verifySignature(jsonLd, options = {}) {
452
+ if (!hasSignature(jsonLd)) return null;
453
+ const sig = jsonLd.signature;
454
+ let signature;
455
+ try {
456
+ signature = decodeBase64(sig.signatureValue);
457
+ } catch (error) {
458
+ logger.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
459
+ ...sig,
460
+ error
461
+ });
462
+ return null;
463
+ }
464
+ const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
465
+ if (key == null) return null;
466
+ const sigOpts = {
467
+ ...sig,
468
+ "@context": "https://w3id.org/identity/v1"
469
+ };
470
+ delete sigOpts.type;
471
+ delete sigOpts.id;
472
+ delete sigOpts.signatureValue;
473
+ let sigOptsHash;
474
+ try {
475
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
476
+ } catch (error) {
477
+ logger.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
478
+ signatureOptions: sigOpts,
479
+ error
480
+ });
481
+ return null;
482
+ }
483
+ const document = { ...jsonLd };
484
+ delete document.signature;
485
+ let docHash;
486
+ try {
487
+ docHash = await hashJsonLd(document, options.contextLoader);
488
+ } catch (error) {
489
+ logger.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
490
+ document,
491
+ error
492
+ });
493
+ return null;
494
+ }
495
+ const encoder = new TextEncoder();
496
+ const message = sigOptsHash + docHash;
497
+ const messageBytes = encoder.encode(message);
498
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
499
+ if (cached) {
500
+ logger.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
501
+ keyId: sig.creator,
502
+ ...sig
503
+ });
504
+ const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
505
+ ...options,
506
+ keyCache: {
507
+ get: () => Promise.resolve(void 0),
508
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
509
+ }
510
+ }));
511
+ if (key == null) return null;
512
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
513
+ }
514
+ 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}", {
515
+ keyId: sig.creator,
516
+ ...sig,
517
+ message
518
+ });
519
+ return null;
520
+ }
521
+ /**
522
+ * Known Linked Data Signature `type` values, used to keep
523
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
524
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
525
+ * only from external documents and are dropped from the metric attribute to
526
+ * avoid attacker-controlled cardinality.
527
+ */
528
+ const LD_KNOWN_SIGNATURE_TYPES = new Set(["RsaSignature2017"]);
529
+ /**
530
+ * Reports only whether a `signature` key is present on the document, with
531
+ * no shape check on its value. This is intentionally looser than
532
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
533
+ * and {@link hasSignatureLike} (which structurally accepts several known
534
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
535
+ * unsupported signature payload (classified as `rejected`) apart from a
536
+ * truly unsigned document (classified as `missing`), and only this
537
+ * presence-only check captures both cases.
538
+ */
539
+ function hasLdSignatureProperty(jsonLd) {
540
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
541
+ }
542
+ function getLdSignatureObject(jsonLd) {
543
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
544
+ const { signature } = jsonLd;
545
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
546
+ return signature;
547
+ }
548
+ /**
549
+ * Verify the authenticity of the given JSON-LD document using Linked Data
550
+ * Signatures. If the document is signed, this function verifies the signature
551
+ * and checks if the document is attributed to the owner of the public key.
552
+ * If the document is not signed, this function returns `false`.
553
+ * @param jsonLd The JSON-LD document to verify.
554
+ * @param options Options for verifying the document.
555
+ * @returns `true` if the document is authentic; `false` otherwise.
556
+ */
557
+ async function verifyJsonLd(jsonLd, options = {}) {
558
+ return await verifyJsonLdInternal(jsonLd, options, true);
559
+ }
560
+ /** @internal */
561
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
562
+ return await verifyJsonLdInternal(jsonLd, options, false);
563
+ }
564
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
565
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
566
+ const start = performance.now();
567
+ let verified = false;
568
+ let threw = false;
569
+ let signatureType;
570
+ try {
571
+ const verificationOptions = hasSignature(jsonLd) ? {
572
+ ...options,
573
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
574
+ } : options;
575
+ const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
576
+ const object = await Object$1.fromJsonLd(compacted, verificationOptions);
577
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
578
+ span.setAttribute("activitypub.object.type", getTypeId(object).href);
579
+ const sig = getLdSignatureObject(jsonLd);
580
+ if (sig != null) {
581
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
582
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
583
+ if (typeof sig.type === "string") {
584
+ span.setAttribute("ld_signatures.type", sig.type);
585
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
586
+ }
587
+ }
588
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
589
+ if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
590
+ const key = await verifySignature(compacted, verificationOptions);
591
+ if (key == null) return false;
592
+ if (key.ownerId == null) {
593
+ logger.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
594
+ return false;
595
+ }
596
+ attributions.delete(key.ownerId.href);
597
+ if (attributions.size > 0) {
598
+ logger.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
599
+ return false;
600
+ }
601
+ verified = true;
602
+ return true;
603
+ } catch (error) {
604
+ threw = true;
605
+ span.setStatus({
606
+ code: SpanStatusCode.ERROR,
607
+ message: String(error)
608
+ });
609
+ throw error;
610
+ } finally {
611
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
612
+ getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
613
+ span.end();
614
+ }
615
+ });
616
+ }
617
+ async function hashJsonLd(jsonLd, contextLoader) {
618
+ const canon = await jsonld.canonize(jsonLd, {
619
+ format: "application/n-quads",
620
+ documentLoader: contextLoader ?? getDocumentLoader()
621
+ });
622
+ const encoder = new TextEncoder();
623
+ return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
624
+ }
625
+ //#endregion
626
+ export { wrapContextLoaderForJsonLd as _, compactJsonLd as a, 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 };