@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,2276 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import { URLPattern } from "urlpattern-polyfill";
3
- import { I as name, L as version, c as fetchKey, f as validateCryptoKey, h as getFederationMetrics, m as getDurationMs, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, y as measureSignatureKeyFetch } from "./http-z5n7chWw.js";
4
- import { getLogger } from "@logtape/logtape";
5
- import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, PUBLIC_COLLECTION, getTypeId, isActor } from "@fedify/vocab";
6
- import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
- import { encodeHex } from "byte-encodings/hex";
8
- import { encodeMultibase, formatIri, getDocumentLoader, getFe34Origin, haveSameFe34Origin, parseIri, preloadedContexts } from "@fedify/vocab-runtime";
9
- import jsonld from "@fedify/vocab-runtime/jsonld";
10
- import { isPlainJsonTree, retainSignedRepresentation } from "@fedify/vocab-runtime/internal/signed-representation";
11
- import serialize from "json-canon";
12
- import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
13
- //#region src/compat/preloaded-context-loader.ts
14
- /**
15
- * A restricted JSON-LD document loader that resolves only contexts bundled
16
- * with Fedify.
17
- *
18
- * This is intentionally narrower than `getDocumentLoader()`: normalization
19
- * helpers are also reached from verification paths that operate on inbound,
20
- * attacker-controlled JSON-LD, so the default fallback must never fetch
21
- * attacker-supplied context URLs.
22
- */
23
- const preloadedOnlyDocumentLoader = (url) => {
24
- if (Object.hasOwn(preloadedContexts, url)) return Promise.resolve({
25
- contextUrl: null,
26
- documentUrl: url,
27
- document: preloadedContexts[url]
28
- });
29
- return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
30
- };
31
- //#endregion
32
- //#region src/compat/secured-document.ts
33
- function isJsonMap$1(value) {
34
- return typeof value === "object" && value != null && !Array.isArray(value);
35
- }
36
- function isNonEmptyString(value) {
37
- return typeof value === "string" && value.length > 0;
38
- }
39
- function hasDataIntegrityProofType(value) {
40
- return (Array.isArray(value) ? value : [value]).some((type) => type === "DataIntegrityProof" || type === "https://w3id.org/security#DataIntegrityProof");
41
- }
42
- /**
43
- * Checks whether a JSON value is a complete, self-contained secured document:
44
- * a map with its own `@context` and exactly one direct, map-valued `proof`
45
- * that carries every member `eddsa-jcs-2022` proof generation produces.
46
- *
47
- * This is deliberately stricter than {@link hasProofLike}, which exists to
48
- * decide whether a document is worth verifying. Here a false positive would
49
- * silently suppress a wire-compatibility fix on an ordinary document, so a
50
- * partial or malformed proof does not qualify.
51
- *
52
- * @internal
53
- */
54
- function isSelfContainedSecuredDocument(value) {
55
- if (!isJsonMap$1(value)) return false;
56
- if (!Object.hasOwn(value, "@context") || value["@context"] == null) return false;
57
- if (!Object.hasOwn(value, "proof")) return false;
58
- const proof = value.proof;
59
- if (!isJsonMap$1(proof)) return false;
60
- return hasDataIntegrityProofType(proof.type) && isNonEmptyString(proof.cryptosuite) && isNonEmptyString(proof.created) && isNonEmptyString(proof.verificationMethod) && isNonEmptyString(proof.proofPurpose) && isNonEmptyString(proof.proofValue);
61
- }
62
- //#endregion
63
- //#region src/compat/public-audience.ts
64
- const logger$4 = getLogger([
65
- "fedify",
66
- "compat",
67
- "public-audience"
68
- ]);
69
- const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
70
- "to",
71
- "cc",
72
- "bto",
73
- "bcc",
74
- "audience"
75
- ]);
76
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
77
- const MAX_TRAVERSAL_DEPTH$1 = 64;
78
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(preloadedContexts));
79
- function hasPublicCurieInAddressing(value, preserveSecured, parentKey, depth = 0) {
80
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
81
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
82
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, preserveSecured, parentKey, depth + 1));
83
- if (typeof value !== "object" || value == null) return false;
84
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return false;
85
- const record = value;
86
- for (const key of Object.keys(record)) {
87
- if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
88
- if (key === "@context") continue;
89
- if (hasPublicCurieInAddressing(record[key], preserveSecured, key, depth + 1)) return true;
90
- }
91
- return false;
92
- }
93
- function rewritePublicAudience(value, preserveSecured, parentKey, depth = 0) {
94
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return PUBLIC_COLLECTION.href;
95
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
96
- if (Array.isArray(value)) {
97
- let changed = false;
98
- const mapped = value.map((item) => {
99
- const rewritten = rewritePublicAudience(item, preserveSecured, parentKey, depth + 1);
100
- if (rewritten !== item) changed = true;
101
- return rewritten;
102
- });
103
- return changed ? mapped : value;
104
- }
105
- if (typeof value !== "object" || value == null) return value;
106
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return value;
107
- const record = value;
108
- let changed = false;
109
- const normalized = Object.create(null);
110
- for (const key of Object.keys(record)) {
111
- const rewritten = key === "@context" ? record[key] : record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public") ? PUBLIC_COLLECTION.href : rewritePublicAudience(record[key], preserveSecured, key, depth + 1);
112
- if (rewritten !== record[key]) changed = true;
113
- normalized[key] = rewritten;
114
- }
115
- return changed ? normalized : value;
116
- }
117
- /**
118
- * Reports whether `value` carries an `@context` property anywhere inside
119
- * its subtree (not counting the value itself). A nested `@context` can
120
- * introduce a local term-definition scope that redefines `as:` or `Public`
121
- * even when the top-level `@context` is safe, so the fast path must defer
122
- * to the URDNA2015 equivalence check whenever one is present.
123
- */
124
- function hasNestedContext$1(value, depth = 0) {
125
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
126
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
127
- if (typeof value !== "object" || value == null) return false;
128
- const record = value;
129
- for (const key of Object.keys(record)) {
130
- if (key === "@context") return true;
131
- if (hasNestedContext$1(record[key], depth + 1)) return true;
132
- }
133
- return false;
134
- }
135
- /**
136
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
137
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
138
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
139
- * preloaded context set AND including the ActivityStreams URL qualify,
140
- * AND no nested subtree carries its own `@context` that might redefine
141
- * those terms within a local scope. When all of that holds the rewrite
142
- * is provably semantics-preserving and the URDNA2015 equivalence check
143
- * can be skipped. Any other shape (unknown external URLs, inline
144
- * objects at the top level, nested `@context` blocks) is treated as
145
- * potentially unsafe.
146
- */
147
- function hasKnownSafeContext$1(jsonLd) {
148
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
149
- const record = jsonLd;
150
- if (!Object.hasOwn(record, "@context")) return false;
151
- const ctx = record["@context"];
152
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
153
- if (entries == null || entries.length === 0) return false;
154
- let hasAs = false;
155
- for (const entry of entries) {
156
- if (typeof entry !== "string") return false;
157
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
158
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
159
- }
160
- if (!hasAs) return false;
161
- for (const key of Object.keys(record)) {
162
- if (key === "@context") continue;
163
- if (hasNestedContext$1(record[key])) return false;
164
- }
165
- return true;
166
- }
167
- /**
168
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
169
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
170
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
171
- *
172
- * Several ActivityPub implementations, Lemmy among them, match these
173
- * fields as plain URLs without running JSON-LD expansion, and silently
174
- * drop activities whose public addressing appears in CURIE form. This
175
- * helper works around that gap.
176
- *
177
- * For documents whose `@context` is drawn entirely from Fedify's
178
- * preloaded context set and includes the ActivityStreams URL, the
179
- * rewrite is applied directly: the content of every preloaded non-AS
180
- * context is known not to redefine the `as:` prefix or the bare `Public`
181
- * term, so the semantics are preserved by construction. Any other
182
- * shape (an inline object, an unknown external URL, and so on) is
183
- * treated as potentially unsafe and gated on a JSON-LD equivalence
184
- * check; both forms are canonicalized with URDNA2015 and the resulting
185
- * N-Quads are compared. When they differ, the original document is
186
- * returned unchanged. Canonicalization failures also fall back to the
187
- * original document.
188
- *
189
- * When no `contextLoader` is supplied the helper falls back to an
190
- * internal loader that resolves only the URLs in Fedify's
191
- * preloaded-contexts set and rejects every other URL without issuing a
192
- * network request. That behaviour is deliberately narrower than
193
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
194
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
195
- * helper is reached from verification paths (`verifyProof()` /
196
- * `verifyObject()`) that operate on inbound, potentially adversarial
197
- * JSON-LD, and a default loader that fetches attacker-supplied
198
- * `@context` URLs on the caller's behalf would be an SSRF vector.
199
- * Canonicalization failures against the restricted loader fall back to
200
- * the original document, same as any other canonicalization error.
201
- * Callers that genuinely need the remote-fetch loader (for example
202
- * applications that sign local JSON-LD against a custom vocabulary)
203
- * should pass a `contextLoader` explicitly.
204
- *
205
- * Must be called before any signing step that canonicalizes the
206
- * compact form byte-for-byte (for example, Object Integrity Proofs
207
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
208
- * matches what is sent on the wire.
209
- */
210
- async function normalizePublicAudience(jsonLd, contextLoader, options = {}) {
211
- const preserveSecured = options.preserveNestedSecuredDocuments ?? false;
212
- if (!hasPublicCurieInAddressing(jsonLd, preserveSecured)) return jsonLd;
213
- const normalized = rewritePublicAudience(jsonLd, preserveSecured);
214
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
215
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
216
- try {
217
- const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
218
- format: "application/n-quads",
219
- documentLoader: loader
220
- }), jsonld.canonize(normalized, {
221
- format: "application/n-quads",
222
- documentLoader: loader
223
- })]);
224
- if (before === after) return normalized;
225
- 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.");
226
- } catch (error) {
227
- logger$4.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
228
- }
229
- return jsonLd;
230
- }
231
- //#endregion
232
- //#region src/compat/outgoing-jsonld.ts
233
- const logger$3 = getLogger([
234
- "fedify",
235
- "compat",
236
- "outgoing-jsonld"
237
- ]);
238
- const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
239
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
240
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
241
- const MAX_TRAVERSAL_DEPTH = 64;
242
- function isJsonLdListObject(value) {
243
- return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
244
- }
245
- function isJsonLdValueObject(value) {
246
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
247
- }
248
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
249
- if (Array.isArray(value)) {
250
- if (seen.has(value)) return;
251
- seen.add(value);
252
- for (const item of value) yield* getContextObjects(item, seen);
253
- return;
254
- }
255
- if (typeof value === "object" && value != null) {
256
- if (seen.has(value)) return;
257
- seen.add(value);
258
- const record = value;
259
- yield record;
260
- for (const definition of Object.values(record)) {
261
- if (typeof definition !== "object" || definition == null) continue;
262
- const nestedContext = definition["@context"];
263
- if (nestedContext == null) continue;
264
- yield* getContextObjects(nestedContext, seen);
265
- }
266
- }
267
- }
268
- function isActivityStreamsAttachmentTerm(value) {
269
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
270
- }
271
- /** @internal */
272
- function isPreloadedContextAttachmentSafe(document) {
273
- if (typeof document !== "object" || document == null) return true;
274
- const context = document["@context"];
275
- for (const contextObject of getContextObjects(context)) {
276
- if (!Object.hasOwn(contextObject, "attachment")) continue;
277
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
278
- return false;
279
- }
280
- return true;
281
- }
282
- function getKnownSafeContextUrls() {
283
- const urls = /* @__PURE__ */ new Set();
284
- for (const [url, document] of Object.entries(preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
285
- 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 });
286
- return urls;
287
- }
288
- /**
289
- * Wraps scalar ActivityStreams attachment properties in arrays.
290
- */
291
- function wrapScalarAttachments(jsonLd, preserveSecured, depth = 0) {
292
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
293
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(jsonLd)) return jsonLd;
294
- if (Array.isArray(jsonLd)) {
295
- let normalized = null;
296
- for (let i = 0; i < jsonLd.length; i++) {
297
- const item = jsonLd[i];
298
- const next = wrapScalarAttachments(item, preserveSecured, depth + 1);
299
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
300
- if (normalized != null) normalized[i] = next;
301
- }
302
- return normalized ?? jsonLd;
303
- }
304
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
305
- const record = jsonLd;
306
- const keys = Object.keys(record);
307
- let normalized = null;
308
- for (let i = 0; i < keys.length; i++) {
309
- const key = keys[i];
310
- const value = record[key];
311
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, preserveSecured, depth + 1);
312
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
313
- if (normalized == null && output !== value) {
314
- const cloned = Object.create(null);
315
- for (let j = 0; j < i; j++) {
316
- const previousKey = keys[j];
317
- cloned[previousKey] = record[previousKey];
318
- }
319
- normalized = cloned;
320
- }
321
- if (normalized != null) normalized[key] = output;
322
- }
323
- return normalized ?? jsonLd;
324
- }
325
- function hasNestedContext(value, depth = 0) {
326
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
327
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
328
- if (typeof value !== "object" || value == null) return false;
329
- const record = value;
330
- for (const key of Object.keys(record)) {
331
- if (key === "@context") return true;
332
- if (key === "@value" && isJsonLdValueObject(value)) continue;
333
- if (hasNestedContext(record[key], depth + 1)) return true;
334
- }
335
- return false;
336
- }
337
- function exceedsTraversalDepth(value, depth = 0) {
338
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
339
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
340
- if (typeof value !== "object" || value == null) return false;
341
- const record = value;
342
- for (const key of Object.keys(record)) {
343
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
344
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
345
- }
346
- return false;
347
- }
348
- function hasKnownSafeContext(jsonLd) {
349
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
350
- const record = jsonLd;
351
- if (!Object.hasOwn(record, "@context")) return false;
352
- const context = record["@context"];
353
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
354
- if (entries == null || entries.length < 1) return false;
355
- let hasActivityStreamsContext = false;
356
- for (const entry of entries) {
357
- if (typeof entry !== "string") return false;
358
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
359
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
360
- }
361
- if (!hasActivityStreamsContext) return false;
362
- for (const key of Object.keys(record)) {
363
- if (key === "@context") continue;
364
- if (hasNestedContext(record[key])) return false;
365
- }
366
- return true;
367
- }
368
- function getLogSafeJsonLdMetadata(jsonLd) {
369
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
370
- const record = jsonLd;
371
- const context = record["@context"];
372
- return {
373
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
374
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
375
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
376
- };
377
- }
378
- /**
379
- * Ensures ActivityStreams attachment properties are represented as arrays
380
- * when doing so preserves the JSON-LD semantics.
381
- *
382
- * JSON-LD compaction collapses single-item arrays into scalar values by
383
- * default. Some ActivityPub implementations, Pixelfed among them, parse
384
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
385
- * otherwise valid objects whose single attachment is emitted as a scalar.
386
- *
387
- * When no `contextLoader` is supplied, the helper falls back to a restricted
388
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
389
- * every other URL without network access. Documents with custom, inline, or
390
- * otherwise uncached contexts should pass a real `contextLoader` if they need
391
- * the semantic-preservation check to succeed; otherwise canonicalization
392
- * failures leave the original document unchanged.
393
- */
394
- async function normalizeAttachmentArrays(jsonLd, contextLoader, options = {}) {
395
- const normalized = wrapScalarAttachments(jsonLd, options.preserveNestedSecuredDocuments ?? false);
396
- if (normalized === jsonLd) return jsonLd;
397
- if (exceedsTraversalDepth(jsonLd)) {
398
- logger$3.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
399
- return jsonLd;
400
- }
401
- if (hasKnownSafeContext(jsonLd)) return normalized;
402
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
403
- try {
404
- const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
405
- format: "application/n-quads",
406
- documentLoader: loader
407
- }), jsonld.canonize(normalized, {
408
- format: "application/n-quads",
409
- documentLoader: loader
410
- })]);
411
- if (before === after) return normalized;
412
- 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));
413
- } catch (error) {
414
- logger$3.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
415
- }
416
- return jsonLd;
417
- }
418
- /**
419
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
420
- * to locally generated outgoing activities before they are signed, enqueued,
421
- * or sent.
422
- */
423
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, options = {}) {
424
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader, options);
425
- return await normalizeAttachmentArrays(jsonLd, contextLoader, options);
426
- }
427
- //#endregion
428
- //#region src/sig/ld.ts
429
- const logger$2 = getLogger([
430
- "fedify",
431
- "sig",
432
- "ld"
433
- ]);
434
- const localContext = [
435
- "https://w3id.org/identity/v1",
436
- "https://www.w3.org/ns/activitystreams",
437
- "https://w3id.org/security/v1",
438
- "https://w3id.org/security/data-integrity/v1"
439
- ];
440
- const localContextUrls = new Set(localContext);
441
- const builtInContextLoader = getDocumentLoader();
442
- const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
443
- "@graph",
444
- "@included",
445
- "@reverse"
446
- ]);
447
- /** @internal */
448
- var UnsafeJsonLdError = class extends TypeError {
449
- keyword;
450
- constructor(keyword) {
451
- super(`Unsupported JSON-LD keyword: ${keyword}.`);
452
- this.keyword = keyword;
453
- this.name = "UnsafeJsonLdError";
454
- }
455
- };
456
- /** @internal */
457
- var InvalidContextReferenceError = class extends TypeError {
458
- reference;
459
- constructor(reference) {
460
- super(`Invalid JSON-LD context reference: ${reference}.`);
461
- this.reference = reference;
462
- this.name = "InvalidContextReferenceError";
463
- }
464
- };
465
- function createLoadingRemoteContextFailedError(reference, cause) {
466
- const message = cause instanceof Error ? cause.message : String(cause);
467
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
468
- error.name = "jsonld.InvalidUrl";
469
- error.details = {
470
- code: "loading remote context failed",
471
- url: reference
472
- };
473
- error.cause = cause;
474
- return error;
475
- }
476
- /** @internal */
477
- function isClearlyMalformedContextReference(reference) {
478
- for (const char of reference) {
479
- const code = char.charCodeAt(0);
480
- if (code <= 32 || code === 127) return true;
481
- }
482
- if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
483
- for (let i = 0; i < reference.length; i++) {
484
- if (reference[i] !== "%") continue;
485
- if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
486
- i += 2;
487
- }
488
- if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
489
- for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
490
- }
491
- return false;
492
- }
493
- function cloneRemoteDocument(remoteDocument) {
494
- return structuredClone(remoteDocument);
495
- }
496
- function createMemoizedDocumentLoader(documentLoader) {
497
- const cache = /* @__PURE__ */ new Map();
498
- return async (url, options) => {
499
- const cacheKey = URL.canParse(url) ? new URL(url).href : url;
500
- let remoteDocument = cache.get(cacheKey);
501
- if (remoteDocument == null) {
502
- remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
503
- remoteDocument.catch(() => {
504
- if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
505
- });
506
- cache.set(cacheKey, remoteDocument);
507
- }
508
- return cloneRemoteDocument(await remoteDocument);
509
- };
510
- }
511
- /** @internal */
512
- function wrapContextLoaderForJsonLd(contextLoader) {
513
- const loader = contextLoader ?? builtInContextLoader;
514
- return async (url, options) => {
515
- try {
516
- return await loader(url, options);
517
- } catch (error) {
518
- if (!isInvalidUrlTypeError(error)) throw error;
519
- if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
520
- throw createLoadingRemoteContextFailedError(url, error);
521
- }
522
- };
523
- }
524
- /** @internal */
525
- function getNormalizationContextLoader(contextLoader) {
526
- const loader = wrapContextLoaderForJsonLd(contextLoader);
527
- return createMemoizedDocumentLoader(async (url, options) => {
528
- if (URL.canParse(url)) {
529
- const normalizedUrl = new URL(url).href;
530
- if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
531
- }
532
- return await loader(url, options);
533
- });
534
- }
535
- /** @internal */
536
- async function compactJsonLd(jsonLd, contextLoader) {
537
- const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
538
- const signature = hasLds ? jsonLd.signature : void 0;
539
- const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
540
- const document = hasLds ? detachSignature(jsonLd) : jsonLd;
541
- await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
542
- const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
543
- if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
544
- assertSafeJsonLd(compacted);
545
- return compacted;
546
- }
547
- function createInvalidRemoteContextError(reference) {
548
- 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}".`);
549
- error.name = "jsonld.InvalidUrl";
550
- error.details = {
551
- code: "invalid remote context",
552
- url: reference
553
- };
554
- return error;
555
- }
556
- function getRemoteContext(remoteDocument, reference) {
557
- const { contextUrl, documentUrl } = remoteDocument;
558
- let { document } = remoteDocument;
559
- if (typeof document === "string") document = JSON.parse(document);
560
- if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
561
- let context = "@context" in document ? document["@context"] : {};
562
- if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
563
- return {
564
- context,
565
- baseUrl: documentUrl ?? reference
566
- };
567
- }
568
- function createGraphAliasContextState() {
569
- return {
570
- graphTerms: /* @__PURE__ */ new Set(),
571
- jsonTerms: /* @__PURE__ */ new Set(),
572
- propertyContexts: /* @__PURE__ */ new Map(),
573
- termTargets: /* @__PURE__ */ new Map()
574
- };
575
- }
576
- function cloneGraphAliasContextState(state) {
577
- return {
578
- graphTerms: new Set(state.graphTerms),
579
- jsonTerms: new Set(state.jsonTerms),
580
- propertyContexts: new Map(state.propertyContexts),
581
- termTargets: new Map(state.termTargets)
582
- };
583
- }
584
- function resolveContextTarget(target, state) {
585
- if (target === "@graph") return target;
586
- const mapped = state.termTargets.get(target);
587
- if (mapped == null) return target;
588
- return mapped;
589
- }
590
- function getDirectContextTarget(definition) {
591
- if (definition === null) return null;
592
- if (typeof definition === "string") return definition;
593
- if (typeof definition === "object" && definition != null && "@id" in definition) {
594
- const id = definition["@id"];
595
- if (id === null) return null;
596
- if (typeof id === "string") return id;
597
- }
598
- }
599
- function isJsonTypedDefinition(definition) {
600
- return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
601
- }
602
- function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
603
- if (target === "@graph") return target;
604
- if (seen.has(target)) return target;
605
- seen.add(target);
606
- if (localTargets.has(target)) {
607
- const localTarget = localTargets.get(target);
608
- return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
609
- }
610
- return resolveContextTarget(target, state);
611
- }
612
- function refreshGraphAliases(state) {
613
- state.graphTerms.clear();
614
- for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
615
- }
616
- function normalizeContextReference(reference, baseUrl) {
617
- if (baseUrl != null) return new URL(reference, baseUrl).href;
618
- return URL.canParse(reference) ? new URL(reference).href : reference;
619
- }
620
- /** @internal */
621
- function isInvalidUrlTypeError(error) {
622
- const code = error.code;
623
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
624
- }
625
- async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
626
- if (context === null) return createGraphAliasContextState();
627
- let nextState = cloneGraphAliasContextState(state);
628
- if (Array.isArray(context)) {
629
- for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
630
- return nextState;
631
- }
632
- if (typeof context === "string") {
633
- const reference = normalizeContextReference(context, baseUrl);
634
- const cacheKey = `${baseUrl ?? ""}\n${reference}`;
635
- if (processingContexts.has(cacheKey)) return nextState;
636
- processingContexts.add(cacheKey);
637
- try {
638
- let remoteContext = remoteContextCache.get(cacheKey);
639
- if (remoteContext == null) {
640
- remoteContext = (async () => {
641
- try {
642
- return getRemoteContext(await documentLoader(reference), reference);
643
- } catch (error) {
644
- if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
645
- throw error;
646
- }
647
- })();
648
- remoteContextCache.set(cacheKey, remoteContext);
649
- }
650
- const loadedRemoteContext = await remoteContext;
651
- return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
652
- } finally {
653
- processingContexts.delete(cacheKey);
654
- }
655
- }
656
- if (typeof context === "object" && context != null) {
657
- if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
658
- const localTargets = /* @__PURE__ */ new Map();
659
- for (const [term, definition] of globalThis.Object.entries(context)) {
660
- if (term.startsWith("@")) continue;
661
- const target = getDirectContextTarget(definition);
662
- if (target == null) localTargets.set(term, null);
663
- else if (typeof target === "string") localTargets.set(term, target);
664
- else localTargets.delete(term);
665
- }
666
- for (const [term, definition] of globalThis.Object.entries(context)) {
667
- if (term.startsWith("@")) continue;
668
- if (localTargets.has(term)) {
669
- const directTarget = localTargets.get(term);
670
- if (directTarget == null) nextState.termTargets.set(term, null);
671
- else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
672
- } else nextState.termTargets.delete(term);
673
- if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
674
- context: definition["@context"],
675
- baseUrl
676
- });
677
- else nextState.propertyContexts.delete(term);
678
- if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
679
- else nextState.jsonTerms.delete(term);
680
- }
681
- refreshGraphAliases(nextState);
682
- }
683
- return nextState;
684
- }
685
- async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
686
- if (Array.isArray(jsonLd)) {
687
- for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
688
- return;
689
- }
690
- if (typeof jsonLd !== "object" || jsonLd == null) return;
691
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
692
- let state = inheritedState;
693
- if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
694
- if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
695
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
696
- if (key === "@context") continue;
697
- if (jsonLiteralWrapper && key === "@value") continue;
698
- if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
699
- if (state.jsonTerms.has(key)) continue;
700
- await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
701
- }
702
- }
703
- function isJsonLiteralWrapper(value) {
704
- return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
705
- }
706
- /** @internal */
707
- function assertSafeJsonLd(jsonLd) {
708
- if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
709
- else if (typeof jsonLd === "object" && jsonLd != null) {
710
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
711
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
712
- if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
713
- if (jsonLiteralWrapper && key === "@value") continue;
714
- assertSafeJsonLd(value);
715
- }
716
- }
717
- }
718
- /**
719
- * Attaches a LD signature to the given JSON-LD document.
720
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
721
- * modified.
722
- * @param signature The signature to attach.
723
- * @returns The JSON-LD document with the attached signature.
724
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
725
- * @since 1.0.0
726
- */
727
- function attachSignature(jsonLd, signature) {
728
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
729
- return {
730
- ...jsonLd,
731
- signature
732
- };
733
- }
734
- /**
735
- * Creates a LD signature for the given JSON-LD document.
736
- * @param jsonLd The JSON-LD document to sign.
737
- * @param privateKey The private key to sign the document.
738
- * @param keyId The ID of the public key that corresponds to the private key.
739
- * @param options Additional options for creating the signature.
740
- * See also {@link CreateSignatureOptions}.
741
- * @return The created signature.
742
- * @throws {TypeError} If the private key is invalid or unsupported.
743
- * @since 1.0.0
744
- */
745
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
746
- validateCryptoKey(privateKey, "private");
747
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
748
- const options = {
749
- "@context": "https://w3id.org/identity/v1",
750
- creator: keyId.href,
751
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
752
- };
753
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
754
- const messageBytes = new TextEncoder().encode(message);
755
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
756
- return {
757
- ...options,
758
- type: "RsaSignature2017",
759
- signatureValue: encodeBase64(signature)
760
- };
761
- }
762
- /**
763
- * Signs the given JSON-LD document with the private key and returns the signed
764
- * JSON-LD document.
765
- * @param jsonLd The JSON-LD document to sign.
766
- * @param privateKey The private key to sign the document.
767
- * @param keyId The key ID to use in the signature. It will be used by the
768
- * verifier to fetch the corresponding public key.
769
- * @param options Additional options for signing the document.
770
- * See also {@link SignJsonLdOptions}.
771
- * @returns The signed JSON-LD document.
772
- * @throws {TypeError} If the private key is invalid or unsupported.
773
- * @since 1.0.0
774
- */
775
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
776
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
777
- try {
778
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
779
- if (span.isRecording()) {
780
- span.setAttribute("ld_signatures.type", signature.type);
781
- span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
782
- }
783
- return attachSignature(jsonLd, signature);
784
- } catch (error) {
785
- span.setStatus({
786
- code: SpanStatusCode.ERROR,
787
- message: String(error)
788
- });
789
- throw error;
790
- } finally {
791
- span.end();
792
- }
793
- });
794
- }
795
- /**
796
- * Checks if the given JSON-LD document has a Linked Data Signature-like
797
- * object, without restricting it to a single suite-specific shape.
798
- * @param jsonLd The JSON-LD document to check.
799
- * @returns `true` if the document has a signature-like object; `false`
800
- * otherwise.
801
- * @since 2.2.0
802
- */
803
- function hasSignatureLike(jsonLd) {
804
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
805
- const signature = jsonLd.signature;
806
- const hasReference = (value) => {
807
- if (typeof value === "string") return true;
808
- if (Array.isArray(value)) return value.some(hasReference);
809
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
810
- };
811
- const hasSignatureObject = (value) => {
812
- if (typeof value !== "object" || value == null) return false;
813
- const signatureRecord = value;
814
- 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");
815
- };
816
- return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
817
- }
818
- /**
819
- * Checks if the given JSON-LD document has a Linked Data Signature.
820
- * @param jsonLd The JSON-LD document to check.
821
- * @returns `true` if the document has a signature; `false` otherwise.
822
- * @since 1.0.0
823
- */
824
- function hasSignature(jsonLd) {
825
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
826
- if ("signature" in jsonLd) {
827
- const signature = jsonLd.signature;
828
- if (typeof signature !== "object" || signature == null) return false;
829
- 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";
830
- }
831
- return false;
832
- }
833
- /**
834
- * Detaches Linked Data Signatures from the given JSON-LD document.
835
- * @param jsonLd The JSON-LD document to modify.
836
- * @returns The modified JSON-LD document. If the input document does not
837
- * contain a signature, the original document is returned.
838
- * @since 1.0.0
839
- */
840
- function detachSignature(jsonLd) {
841
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
842
- const doc = { ...jsonLd };
843
- delete doc.signature;
844
- return doc;
845
- }
846
- /**
847
- * Verifies Linked Data Signatures of the given JSON-LD document.
848
- *
849
- * This is a low-level utility that only checks the cryptographic signature
850
- * and (optionally) the cached key. It does not run the JSON-LD parsing,
851
- * attribution, and owner checks that a complete inbound LD verification
852
- * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
853
- * the public verification entry point and the one that emits the
854
- * `activitypub.signature.verification.duration` metric for the LD path.
855
- * `verifySignature` itself only emits
856
- * `activitypub.signature.key_fetch.duration`, since the rest of the work
857
- * that the verification-duration metric is meant to cover happens in
858
- * `verifyJsonLd`.
859
- * @param jsonLd The JSON-LD document to verify.
860
- * @param options Options for verifying the signature.
861
- * @returns The public key that signed the document or `null` if the signature
862
- * is invalid or the key is not found.
863
- * @since 1.0.0
864
- */
865
- async function verifySignature(jsonLd, options = {}) {
866
- if (!hasSignature(jsonLd)) return null;
867
- const sig = jsonLd.signature;
868
- let signature;
869
- try {
870
- signature = decodeBase64(sig.signatureValue);
871
- } catch (error) {
872
- logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
873
- ...sig,
874
- error
875
- });
876
- return null;
877
- }
878
- const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
879
- if (key == null) return null;
880
- const sigOpts = {
881
- ...sig,
882
- "@context": "https://w3id.org/identity/v1"
883
- };
884
- delete sigOpts.type;
885
- delete sigOpts.id;
886
- delete sigOpts.signatureValue;
887
- let sigOptsHash;
888
- try {
889
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
890
- } catch (error) {
891
- logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
892
- signatureOptions: sigOpts,
893
- error
894
- });
895
- return null;
896
- }
897
- const document = { ...jsonLd };
898
- delete document.signature;
899
- let docHash;
900
- try {
901
- docHash = await hashJsonLd(document, options.contextLoader);
902
- } catch (error) {
903
- logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
904
- document,
905
- error
906
- });
907
- return null;
908
- }
909
- const encoder = new TextEncoder();
910
- const message = sigOptsHash + docHash;
911
- const messageBytes = encoder.encode(message);
912
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
913
- if (cached) {
914
- logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
915
- keyId: sig.creator,
916
- ...sig
917
- });
918
- const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
919
- ...options,
920
- keyCache: {
921
- get: () => Promise.resolve(void 0),
922
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
923
- }
924
- }));
925
- if (key == null) return null;
926
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
927
- }
928
- 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}", {
929
- keyId: sig.creator,
930
- ...sig,
931
- message
932
- });
933
- return null;
934
- }
935
- /**
936
- * Known Linked Data Signature `type` values, used to keep
937
- * `ld_signatures.type` on a bounded set of spec-defined string values.
938
- * Fedify only signs and verifies `RsaSignature2017`; other values come in
939
- * only from external documents and are dropped from the metric attribute to
940
- * avoid attacker-controlled cardinality.
941
- */
942
- const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
943
- /**
944
- * Reports only whether a `signature` key is present on the document, with
945
- * no shape check on its value. This is intentionally looser than
946
- * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
947
- * and {@link hasSignatureLike} (which structurally accepts several known
948
- * suites): `verifyJsonLd` needs to tell a document with a malformed or
949
- * unsupported signature payload (classified as `rejected`) apart from a
950
- * truly unsigned document (classified as `missing`), and only this
951
- * presence-only check captures both cases.
952
- */
953
- function hasLdSignatureProperty(jsonLd) {
954
- return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
955
- }
956
- function getLdSignatureObject(jsonLd) {
957
- if (!hasLdSignatureProperty(jsonLd)) return void 0;
958
- const { signature } = jsonLd;
959
- if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
960
- return signature;
961
- }
962
- /**
963
- * Verify the authenticity of the given JSON-LD document using Linked Data
964
- * Signatures. If the document is signed, this function verifies the signature
965
- * and checks if the document is attributed to the owner of the public key.
966
- * If the document is not signed, this function returns `false`.
967
- * @param jsonLd The JSON-LD document to verify.
968
- * @param options Options for verifying the document.
969
- * @returns `true` if the document is authentic; `false` otherwise.
970
- */
971
- async function verifyJsonLd(jsonLd, options = {}) {
972
- return await verifyJsonLdInternal(jsonLd, options, true);
973
- }
974
- /** @internal */
975
- async function verifyCompactJsonLd(jsonLd, options = {}) {
976
- return await verifyJsonLdInternal(jsonLd, options, false);
977
- }
978
- async function verifyJsonLdInternal(jsonLd, options, compact) {
979
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
980
- const start = performance.now();
981
- let verified = false;
982
- let threw = false;
983
- let signatureType;
984
- try {
985
- const verificationOptions = hasSignature(jsonLd) ? {
986
- ...options,
987
- contextLoader: getNormalizationContextLoader(options.contextLoader)
988
- } : options;
989
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
990
- const object = await Object$1.fromJsonLd(compacted, verificationOptions);
991
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
992
- span.setAttribute("activitypub.object.type", getTypeId(object).href);
993
- const sig = getLdSignatureObject(jsonLd);
994
- if (sig != null) {
995
- if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
996
- if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
997
- if (typeof sig.type === "string") {
998
- span.setAttribute("ld_signatures.type", sig.type);
999
- if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
1000
- }
1001
- }
1002
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
1003
- if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
1004
- const key = await verifySignature(compacted, verificationOptions);
1005
- if (key == null) return false;
1006
- if (key.ownerId == null) {
1007
- logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
1008
- return false;
1009
- }
1010
- attributions.delete(key.ownerId.href);
1011
- if (attributions.size > 0) {
1012
- logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
1013
- return false;
1014
- }
1015
- verified = true;
1016
- return true;
1017
- } catch (error) {
1018
- threw = true;
1019
- span.setStatus({
1020
- code: SpanStatusCode.ERROR,
1021
- message: String(error)
1022
- });
1023
- throw error;
1024
- } finally {
1025
- const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
1026
- getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
1027
- span.end();
1028
- }
1029
- });
1030
- }
1031
- async function hashJsonLd(jsonLd, contextLoader) {
1032
- const canon = await jsonld.canonize(jsonLd, {
1033
- format: "application/n-quads",
1034
- documentLoader: contextLoader ?? getDocumentLoader()
1035
- });
1036
- const encoder = new TextEncoder();
1037
- return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
1038
- }
1039
- //#endregion
1040
- //#region src/sig/proof.ts
1041
- /**
1042
- * Known Object Integrity Proof `cryptosuite` values, used to keep
1043
- * `object_integrity_proofs.cryptosuite` on a bounded set of spec-defined
1044
- * string values. Fedify currently signs and verifies only
1045
- * `eddsa-jcs-2022`; other values come in only from external proofs and are
1046
- * dropped from the metric attribute to avoid attacker-controlled
1047
- * cardinality.
1048
- */
1049
- const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
1050
- const logger$1 = getLogger([
1051
- "fedify",
1052
- "sig",
1053
- "proof"
1054
- ]);
1055
- const SECURITY_NAMESPACE = "https://w3id.org/security#";
1056
- const SECURITY_PROOF = `${SECURITY_NAMESPACE}proof`;
1057
- const SECURITY_PROOF_VALUE = `${SECURITY_NAMESPACE}proofValue`;
1058
- const DATA_INTEGRITY_PROOF = `${SECURITY_NAMESPACE}DataIntegrityProof`;
1059
- const SECURITY_VERIFICATION_METHOD = `${SECURITY_NAMESPACE}verificationMethod`;
1060
- const SECURITY_EXPIRATION = `${SECURITY_NAMESPACE}expiration`;
1061
- const SECURITY_DOMAIN = `${SECURITY_NAMESPACE}domain`;
1062
- const SECURITY_CHALLENGE = `${SECURITY_NAMESPACE}challenge`;
1063
- const SECURITY_NONCE = `${SECURITY_NAMESPACE}nonce`;
1064
- const SECURITY_PREVIOUS_PROOF = `${SECURITY_NAMESPACE}previousProof`;
1065
- /**
1066
- * Checks if the given JSON-LD document has a DataIntegrityProof-like object,
1067
- * without fully deserializing it into vocabulary classes.
1068
- * @param jsonLd The JSON-LD document to check.
1069
- * @returns `true` if the document has a proof-like object; `false` otherwise.
1070
- * @since 2.2.0
1071
- */
1072
- function hasProofLike(jsonLd) {
1073
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
1074
- const record = jsonLd;
1075
- const proof = record.proof ?? record["https://w3id.org/security#proof"];
1076
- const getField = (source, compact, expanded) => source[compact] ?? source[expanded];
1077
- const isReference = (value) => {
1078
- if (typeof value === "string") return true;
1079
- if (Array.isArray(value)) return value.some(isReference);
1080
- 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");
1081
- };
1082
- const hasType = (value) => {
1083
- if (typeof value === "string") return value === "DataIntegrityProof" || value === "https://w3id.org/security#DataIntegrityProof";
1084
- if (Array.isArray(value)) return value.some(hasType);
1085
- return false;
1086
- };
1087
- const isProofLike = (value) => {
1088
- if (typeof value !== "object" || value == null) return false;
1089
- const proofRecord = value;
1090
- 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"));
1091
- };
1092
- return Array.isArray(proof) ? proof.some(isProofLike) : isProofLike(proof);
1093
- }
1094
- function isJsonMap(value) {
1095
- return typeof value === "object" && value != null && !Array.isArray(value);
1096
- }
1097
- /**
1098
- * Assembles the secured JSON document from the bytes that were just signed.
1099
- *
1100
- * The document is not re-derived from the vocabulary object: it is
1101
- * `compactMsg`, the value whose JCS form was hashed, with the serialized
1102
- * proof added. Every part of it is then checked against the digests and the
1103
- * signature that {@link createProofInternal} produced, so a document that is
1104
- * returned verifies under the map-local compound-proof profile by
1105
- * construction. Anything that does not check out yields `null`, and the
1106
- * caller simply does not retain a representation.
1107
- */
1108
- async function captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, proofValue, contextLoader) {
1109
- if (!isJsonMap(compactMsg)) return null;
1110
- const documentContext = compactMsg["@context"];
1111
- if (documentContext == null) return null;
1112
- if (globalThis.Object.hasOwn(compactMsg, "proof")) return null;
1113
- try {
1114
- const proofJson = await proof.toJsonLd({
1115
- format: "compact",
1116
- contextLoader,
1117
- context: documentContext
1118
- });
1119
- if (!isJsonMap(proofJson)) return null;
1120
- const { proofValue: serializedProofValue, ...proofConfiguration } = proofJson;
1121
- if (serializedProofValue !== proofValue) return null;
1122
- if (serialize(proofConfiguration) !== proofCanon) return null;
1123
- const securedDocument = {
1124
- ...structuredClone(compactMsg),
1125
- proof: structuredClone(proofJson)
1126
- };
1127
- const { proof: _embeddedProof, ...unsecuredDocument } = securedDocument;
1128
- if (serialize(unsecuredDocument) !== msgCanon) return null;
1129
- if (!isPlainJsonTree(securedDocument)) return null;
1130
- return securedDocument;
1131
- } catch (error) {
1132
- 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 });
1133
- return null;
1134
- }
1135
- }
1136
- async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}, capture = false) {
1137
- validateCryptoKey(privateKey, "private");
1138
- if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
1139
- let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
1140
- format: "compact",
1141
- contextLoader,
1142
- context
1143
- });
1144
- compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader, { preserveNestedSecuredDocuments: true });
1145
- const msgCanon = serialize(compactMsg);
1146
- const encoder = new TextEncoder();
1147
- const msgBytes = encoder.encode(msgCanon);
1148
- const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
1149
- created ??= Temporal.Now.instant();
1150
- const proofCanon = serialize({
1151
- "@context": compactMsg["@context"],
1152
- type: "DataIntegrityProof",
1153
- cryptosuite: "eddsa-jcs-2022",
1154
- verificationMethod: keyId.href,
1155
- proofPurpose: "assertionMethod",
1156
- created: created.toString()
1157
- });
1158
- const proofBytes = encoder.encode(proofCanon);
1159
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1160
- const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
1161
- digest.set(new Uint8Array(proofDigest), 0);
1162
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
1163
- const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", privateKey, digest));
1164
- const proof = new DataIntegrityProof({
1165
- cryptosuite: "eddsa-jcs-2022",
1166
- verificationMethod: keyId,
1167
- proofPurpose: "assertionMethod",
1168
- created,
1169
- proofValue: sig
1170
- });
1171
- return {
1172
- proof,
1173
- securedDocument: capture ? await captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, new TextDecoder().decode(encodeMultibase("base58btc", sig)), contextLoader) : null
1174
- };
1175
- }
1176
- /**
1177
- * Creates a proof for the given object.
1178
- * @param object The object to create a proof for.
1179
- * @param privateKey The private key to sign the proof with.
1180
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
1181
- * @param options Additional options. See also {@link CreateProofOptions}.
1182
- * @returns The created proof.
1183
- * @throws {TypeError} If the private key is invalid or unsupported.
1184
- * @since 0.10.0
1185
- */
1186
- async function createProof(object, privateKey, keyId, options = {}) {
1187
- const { proof } = await createProofInternal(object, privateKey, keyId, options);
1188
- return proof;
1189
- }
1190
- /**
1191
- * Signs the given object with the private key and returns the signed object.
1192
- * @param object The object to create a proof for.
1193
- * @param privateKey The private key to sign the proof with.
1194
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
1195
- * @param options Additional options. See also {@link SignObjectOptions}.
1196
- * @returns The signed object.
1197
- * @throws {TypeError} If the private key is invalid or unsupported.
1198
- * @since 0.10.0
1199
- */
1200
- async function signObject(object, privateKey, keyId, options = {}) {
1201
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
1202
- try {
1203
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
1204
- const existingProofs = [];
1205
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
1206
- const { proof, securedDocument } = await createProofInternal(object, privateKey, keyId, options, existingProofs.length < 1);
1207
- if (span.isRecording()) {
1208
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
1209
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
1210
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
1211
- }
1212
- const signed = object.clone({ proofs: [...existingProofs, proof] });
1213
- if (securedDocument != null) retainSignedRepresentation(signed, securedDocument);
1214
- 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.", {
1215
- objectId: object.id?.href,
1216
- proofCount: existingProofs.length
1217
- });
1218
- return signed;
1219
- } catch (error) {
1220
- span.setStatus({
1221
- code: SpanStatusCode.ERROR,
1222
- message: String(error)
1223
- });
1224
- throw error;
1225
- } finally {
1226
- span.end();
1227
- }
1228
- });
1229
- }
1230
- /**
1231
- * Verifies the given proof for the object.
1232
- * @param jsonLd The JSON-LD object to verify the proof for. Its proof
1233
- * properties are excluded from the message, but matching proof
1234
- * occurrences are used to authenticate the received proof
1235
- * configuration.
1236
- * @param proof The proof to verify.
1237
- * @param options Additional options. See also {@link VerifyProofOptions}.
1238
- * @returns The public key that was used to sign the proof, or `null` if the
1239
- * proof is invalid.
1240
- * @since 0.10.0
1241
- * @since 2.4.0 Matching proof configurations are authenticated.
1242
- */
1243
- async function verifyProof(jsonLd, proof, options = {}) {
1244
- return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
1245
- }
1246
- /**
1247
- * Verifies the one direct literal proof on a map-local secured document.
1248
- *
1249
- * Unlike {@link verifyProof}, this removes only the literal `proof` member
1250
- * from the message digest. JSON-LD aliases remain part of the signed input,
1251
- * and the document's received `@context` is not replaced by the proof
1252
- * configuration context.
1253
- *
1254
- * @internal
1255
- */
1256
- async function verifyMapLocalProof(jsonLd, options = {}) {
1257
- if (!isJsonLdNode(jsonLd) || !globalThis.Object.hasOwn(jsonLd, "proof") || !isJsonLdNode(jsonLd.proof)) return null;
1258
- const proofContextLoader = getNormalizationContextLoader(preloadedOnlyDocumentLoader);
1259
- try {
1260
- const [candidate] = await parseRawProofCandidates(jsonLd, [jsonLd.proof], options, proofContextLoader);
1261
- if (candidate.proof == null) return null;
1262
- return await verifyProofWithMessageDigestCache(jsonLd, candidate.proof, options, {
1263
- proofContextLoader,
1264
- proofPropertyMode: "literal"
1265
- }, candidate);
1266
- } catch {
1267
- return null;
1268
- }
1269
- }
1270
- async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
1271
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
1272
- const start = performance.now();
1273
- let verified = false;
1274
- let threw = false;
1275
- const cryptosuite = proof.cryptosuite != null && OIP_KNOWN_CRYPTOSUITES.has(proof.cryptosuite) ? proof.cryptosuite : void 0;
1276
- if (span.isRecording()) {
1277
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
1278
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
1279
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
1280
- }
1281
- try {
1282
- const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1283
- if (key == null) span.setStatus({ code: SpanStatusCode.ERROR });
1284
- else verified = true;
1285
- return key;
1286
- } catch (error) {
1287
- threw = true;
1288
- span.setStatus({
1289
- code: SpanStatusCode.ERROR,
1290
- message: String(error)
1291
- });
1292
- throw error;
1293
- } finally {
1294
- const classified = threw ? "error" : verified ? "verified" : "rejected";
1295
- getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "object_integrity", classified, { cryptosuite });
1296
- span.end();
1297
- }
1298
- });
1299
- }
1300
- function expandContextPropertyIri(activeContext, key) {
1301
- const termId = jsonld.getContextValue(activeContext, key, "@id");
1302
- if (termId != null) return termId;
1303
- const colon = key.indexOf(":");
1304
- if (colon < 1) return key;
1305
- const prefix = key.substring(0, colon);
1306
- const suffix = key.substring(colon + 1);
1307
- if (prefix === "_" || suffix.startsWith("//")) return key;
1308
- const mapping = jsonld.getContextValue(activeContext, prefix);
1309
- if (typeof mapping === "object" && mapping != null && mapping._prefix === true && typeof mapping["@id"] === "string") return mapping["@id"] + suffix;
1310
- return key;
1311
- }
1312
- async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoader = preloadedOnlyDocumentLoader, inheritedContext, rejectOnContextError = false) {
1313
- const names = new Set(defaults);
1314
- const context = jsonLd["@context"] ?? inheritedContext;
1315
- if (context == null) return names;
1316
- try {
1317
- const options = { documentLoader };
1318
- let activeContext = await jsonld.processContext(null, null, options);
1319
- activeContext = await jsonld.processContext(activeContext, context, options);
1320
- const typeScopedContext = activeContext;
1321
- for (const key of globalThis.Object.keys(jsonLd).sort()) {
1322
- if (key !== "@type" && expandContextPropertyIri(activeContext, key) !== "@type") continue;
1323
- const value = jsonLd[key];
1324
- const types = Array.isArray(value) ? value.slice().sort() : [value];
1325
- for (const type of types) {
1326
- if (typeof type !== "string") continue;
1327
- const scopedContext = jsonld.getContextValue(typeScopedContext, type, "@context");
1328
- if (scopedContext != null) activeContext = await jsonld.processContext(activeContext, scopedContext, options);
1329
- }
1330
- }
1331
- for (const key of globalThis.Object.keys(jsonLd)) if (expandContextPropertyIri(activeContext, key) === propertyIri) names.add(key);
1332
- } catch {
1333
- if (rejectOnContextError) return null;
1334
- }
1335
- return names;
1336
- }
1337
- async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
1338
- return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
1339
- }
1340
- async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
1341
- const msg = { ...jsonLd };
1342
- if (proofPropertyMode === "literal") delete msg.proof;
1343
- else for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
1344
- if (proofPropertyMode === "jsonLd" && context != null) msg["@context"] = structuredClone(context);
1345
- const encoder = new TextEncoder();
1346
- const digest = async (value) => {
1347
- const bytes = encoder.encode(serialize(value));
1348
- return await crypto.subtle.digest("SHA-256", bytes);
1349
- };
1350
- const onWire = await digest(msg);
1351
- let normalizedPromise;
1352
- return {
1353
- onWire,
1354
- normalized() {
1355
- normalizedPromise ??= (async () => {
1356
- const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
1357
- return normalized === msg ? null : await digest(normalized);
1358
- })();
1359
- return normalizedPromise;
1360
- }
1361
- };
1362
- }
1363
- function contextValues(context) {
1364
- return Array.isArray(context) ? context : [context];
1365
- }
1366
- function equalJsonValues(left, right) {
1367
- try {
1368
- return serialize(left) === serialize(right);
1369
- } catch {
1370
- return false;
1371
- }
1372
- }
1373
- function contextStartsWith(documentContext, proofContext) {
1374
- if (documentContext == null) return false;
1375
- const documentValues = contextValues(documentContext);
1376
- const proofValues = contextValues(proofContext);
1377
- return proofValues.length <= documentValues.length && proofValues.every((value, index) => equalJsonValues(value, documentValues[index]));
1378
- }
1379
- function appendProofValues(values, value) {
1380
- if (Array.isArray(value)) for (const item of value) appendProofValues(values, item);
1381
- else if (isJsonLdNode(value) && Array.isArray(value["@graph"])) for (const item of value["@graph"]) appendProofValues(values, item);
1382
- else values.push(value);
1383
- }
1384
- async function getRawProofValues(jsonLd, documentLoader) {
1385
- const propertyNames = await getProofPropertyNames(jsonLd, documentLoader);
1386
- const values = [];
1387
- for (const [property, value] of globalThis.Object.entries(jsonLd)) if (propertyNames.has(property)) appendProofValues(values, value);
1388
- return values;
1389
- }
1390
- function sameBytes(left, right) {
1391
- if (left == null || right == null) return left === right;
1392
- return left.length === right.length && left.every((value, index) => value === right[index]);
1393
- }
1394
- function sameProof(left, right) {
1395
- 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();
1396
- }
1397
- function normalizeDocumentUrl(url) {
1398
- try {
1399
- return formatIri(parseIri(url));
1400
- } catch {
1401
- return URL.canParse(url) ? new URL(url).href : url;
1402
- }
1403
- }
1404
- function getRawProofReference(value) {
1405
- const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
1406
- if (typeof node === "string") return normalizeDocumentUrl(node);
1407
- if (!isJsonLdNode(node)) return void 0;
1408
- const id = node["@id"] ?? node.id;
1409
- return typeof id === "string" ? normalizeDocumentUrl(id) : void 0;
1410
- }
1411
- async function parseRawProofCandidates(jsonLd, values, options, documentLoader) {
1412
- const candidates = [];
1413
- for (const value of values) {
1414
- let parsed = null;
1415
- if (isJsonLdNode(value)) {
1416
- const proofJsonLd = value["@context"] == null && jsonLd["@context"] != null ? {
1417
- "@context": jsonLd["@context"],
1418
- ...value
1419
- } : value;
1420
- try {
1421
- parsed = await DataIntegrityProof.fromJsonLd(proofJsonLd, {
1422
- ...options,
1423
- contextLoader: documentLoader
1424
- });
1425
- } catch {}
1426
- }
1427
- candidates.push({
1428
- value,
1429
- proof: parsed,
1430
- reference: getRawProofReference(value) ?? parsed?.id?.href
1431
- });
1432
- }
1433
- return candidates;
1434
- }
1435
- async function findRawProofCandidate(jsonLd, proof, options, documentLoader) {
1436
- const candidates = await parseRawProofCandidates(jsonLd, await getRawProofValues(jsonLd, documentLoader), options, documentLoader);
1437
- const matches = [];
1438
- for (const candidate of candidates) if (candidate.proof != null && sameProof(candidate.proof, proof)) matches.push(candidate);
1439
- if (matches.length < 1) return void 0;
1440
- const first = matches[0];
1441
- const configurations = await Promise.all(matches.map((candidate) => normalizeProofConfiguration(candidate.value, jsonLd["@context"], documentLoader)));
1442
- const firstConfiguration = configurations[0];
1443
- return firstConfiguration != null && configurations.every((configuration) => configuration != null && equalJsonValues(configuration.value, firstConfiguration.value)) ? first : null;
1444
- }
1445
- function takeRawProofCandidate(pool, proof) {
1446
- for (let index = 0; index < pool.candidates.length; index++) {
1447
- if (pool.used.has(index)) continue;
1448
- const candidate = pool.candidates[index];
1449
- if (candidate.proof != null && sameProof(candidate.proof, proof)) {
1450
- pool.used.add(index);
1451
- return candidate;
1452
- }
1453
- }
1454
- }
1455
- const STANDARD_COMPACT_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
1456
- "@context",
1457
- "type",
1458
- "cryptosuite",
1459
- "verificationMethod",
1460
- "proofPurpose",
1461
- "proofValue",
1462
- "created"
1463
- ]);
1464
- const STANDARD_EXPANDED_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
1465
- "@context",
1466
- "@type",
1467
- `${SECURITY_NAMESPACE}cryptosuite`,
1468
- SECURITY_VERIFICATION_METHOD,
1469
- `${SECURITY_NAMESPACE}proofPurpose`,
1470
- `${SECURITY_NAMESPACE}proofValue`,
1471
- "http://purl.org/dc/terms/created"
1472
- ]);
1473
- function hasAdditionalProofOptions(value) {
1474
- const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
1475
- return isJsonLdNode(node) && globalThis.Object.keys(node).some((property) => !STANDARD_COMPACT_PROOF_PROPERTIES.has(property) && !STANDARD_EXPANDED_PROOF_PROPERTIES.has(property));
1476
- }
1477
- function isExpandedJsonLdNode(value) {
1478
- const properties = globalThis.Object.keys(value).filter((key) => !key.startsWith("@"));
1479
- return properties.length > 0 && properties.every((property) => URL.canParse(property));
1480
- }
1481
- async function normalizeProofConfiguration(rawProof, documentContext, documentLoader) {
1482
- let node = Array.isArray(rawProof) && rawProof.length === 1 ? rawProof[0] : rawProof;
1483
- if (!isJsonLdNode(node)) return null;
1484
- if (isExpandedJsonLdNode(node)) {
1485
- if (documentContext == null) return null;
1486
- node = await jsonld.compact(node, documentContext, { documentLoader });
1487
- if (!isJsonLdNode(node)) return null;
1488
- } else node = structuredClone(node);
1489
- const receivedContext = node["@context"];
1490
- if (receivedContext != null && !contextStartsWith(documentContext, receivedContext)) return null;
1491
- const context = receivedContext ?? documentContext;
1492
- if (context != null) node["@context"] = structuredClone(context);
1493
- const proofValueProperties = await getJsonLdPropertyNames(node, SECURITY_PROOF_VALUE, ["proofValue", SECURITY_PROOF_VALUE], documentLoader, context) ?? /* @__PURE__ */ new Set(["proofValue", SECURITY_PROOF_VALUE]);
1494
- for (const property of proofValueProperties) delete node[property];
1495
- return {
1496
- value: node,
1497
- context
1498
- };
1499
- }
1500
- async function createProofConfiguration(jsonLd, proof, options, documentLoader, rawProofCandidate) {
1501
- let rawProof;
1502
- if (rawProofCandidate == null) {
1503
- const match = await findRawProofCandidate(jsonLd, proof, options, documentLoader);
1504
- if (match === null) return null;
1505
- rawProof = match?.value;
1506
- } else rawProof = rawProofCandidate.value;
1507
- if (rawProof == null) {
1508
- const serializedProof = await proof.toJsonLd();
1509
- if (hasAdditionalProofOptions(serializedProof)) rawProof = serializedProof;
1510
- }
1511
- if (rawProof != null) return await normalizeProofConfiguration(rawProof, jsonLd["@context"], documentLoader);
1512
- const context = jsonLd["@context"];
1513
- return {
1514
- value: {
1515
- ...context == null ? {} : { "@context": context },
1516
- type: "DataIntegrityProof",
1517
- cryptosuite: proof.cryptosuite,
1518
- verificationMethod: proof.verificationMethodId.href,
1519
- proofPurpose: proof.proofPurpose,
1520
- created: proof.created.toString()
1521
- },
1522
- context
1523
- };
1524
- }
1525
- const KNOWN_PROOF_CONFIGURATION_PROPERTIES = /* @__PURE__ */ new Set([
1526
- "@context",
1527
- "@id",
1528
- "@type",
1529
- "id",
1530
- "type",
1531
- "cryptosuite",
1532
- `${SECURITY_NAMESPACE}cryptosuite`,
1533
- "verificationMethod",
1534
- SECURITY_VERIFICATION_METHOD,
1535
- "proofPurpose",
1536
- `${SECURITY_NAMESPACE}proofPurpose`,
1537
- "created",
1538
- "http://purl.org/dc/terms/created",
1539
- "expires",
1540
- SECURITY_EXPIRATION,
1541
- "domain",
1542
- SECURITY_DOMAIN,
1543
- "challenge",
1544
- SECURITY_CHALLENGE,
1545
- "nonce",
1546
- SECURITY_NONCE,
1547
- "previousProof",
1548
- SECURITY_PREVIOUS_PROOF
1549
- ]);
1550
- async function getProofOption(proofConfig, propertyIri, defaults, documentLoader) {
1551
- let names = await getJsonLdPropertyNames(proofConfig, propertyIri, defaults, documentLoader, proofConfig["@context"], true);
1552
- if (names == null) {
1553
- if (globalThis.Object.keys(proofConfig).some((property) => !KNOWN_PROOF_CONFIGURATION_PROPERTIES.has(property))) return null;
1554
- names = new Set(defaults);
1555
- }
1556
- const present = globalThis.Object.keys(proofConfig).filter((property) => names.has(property));
1557
- if (present.length > 1) return null;
1558
- return present.length < 1 ? { present: false } : {
1559
- present: true,
1560
- value: proofConfig[present[0]]
1561
- };
1562
- }
1563
- function parseStringSet(value) {
1564
- if (typeof value === "string") return /* @__PURE__ */ new Set([value]);
1565
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) return null;
1566
- return new Set(value);
1567
- }
1568
- function equalStringSets(left, right) {
1569
- return left.size === right.size && [...left].every((value) => right.has(value));
1570
- }
1571
- async function hasValidProofOptions(proofConfig, options, documentLoader) {
1572
- const expires = await getProofOption(proofConfig, SECURITY_EXPIRATION, ["expires", SECURITY_EXPIRATION], documentLoader);
1573
- if (expires == null) return false;
1574
- if (expires.present) {
1575
- if (typeof expires.value !== "string") return false;
1576
- let expiration;
1577
- try {
1578
- expiration = Temporal.Instant.from(expires.value);
1579
- } catch {
1580
- return false;
1581
- }
1582
- if (Temporal.Instant.compare(Temporal.Now.instant(), expiration) >= 0) return false;
1583
- }
1584
- const domain = await getProofOption(proofConfig, SECURITY_DOMAIN, ["domain", SECURITY_DOMAIN], documentLoader);
1585
- if (domain == null) return false;
1586
- const proofDomains = domain.present ? parseStringSet(domain.value) : null;
1587
- if (domain.present && proofDomains == null) return false;
1588
- if (options.domain != null) {
1589
- const expectedDomains = parseStringSet(options.domain);
1590
- if (expectedDomains == null || proofDomains == null || !equalStringSets(proofDomains, expectedDomains)) return false;
1591
- }
1592
- const challenge = await getProofOption(proofConfig, SECURITY_CHALLENGE, ["challenge", SECURITY_CHALLENGE], documentLoader);
1593
- if (challenge == null || challenge.present && typeof challenge.value !== "string" || options.challenge != null && (!challenge.present || challenge.value !== options.challenge)) return false;
1594
- const nonce = await getProofOption(proofConfig, SECURITY_NONCE, ["nonce", SECURITY_NONCE], documentLoader);
1595
- if (nonce == null || nonce.present && typeof nonce.value !== "string") return false;
1596
- const previousProof = await getProofOption(proofConfig, SECURITY_PREVIOUS_PROOF, ["previousProof", SECURITY_PREVIOUS_PROOF], documentLoader);
1597
- if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return false;
1598
- return true;
1599
- }
1600
- async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
1601
- if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
1602
- const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
1603
- const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
1604
- if (proofConfiguration == null || !await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader)) return null;
1605
- const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, {
1606
- ...options,
1607
- keyIdBoundByCaller
1608
- }));
1609
- const proofBytes = new TextEncoder().encode(serialize(proofConfiguration.value));
1610
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1611
- let fetchedKey;
1612
- try {
1613
- fetchedKey = await publicKeyPromise;
1614
- } catch (error) {
1615
- logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1616
- proof,
1617
- keyId: proof.verificationMethodId.href,
1618
- error
1619
- });
1620
- return null;
1621
- }
1622
- const publicKey = fetchedKey.key;
1623
- if (publicKey == null) {
1624
- logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1625
- proof,
1626
- keyId: proof.verificationMethodId.href
1627
- });
1628
- return null;
1629
- }
1630
- if (publicKey.publicKey.algorithm.name !== "Ed25519") {
1631
- if (fetchedKey.cached) {
1632
- logger$1.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
1633
- proof,
1634
- keyId: proof.verificationMethodId.href
1635
- });
1636
- return await verifyProofInternal(jsonLd, proof, {
1637
- ...options,
1638
- keyCache: {
1639
- get: () => Promise.resolve(void 0),
1640
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1641
- }
1642
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1643
- }
1644
- logger$1.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
1645
- proof,
1646
- keyId: proof.verificationMethodId.href
1647
- });
1648
- return null;
1649
- }
1650
- const digest = new Uint8Array(proofDigest.byteLength + 32);
1651
- digest.set(new Uint8Array(proofDigest), 0);
1652
- const proofValue = proof.proofValue;
1653
- const verifyCandidate = async (msgDigest) => {
1654
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
1655
- return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
1656
- };
1657
- const messageDigestKey = serialize(proofConfiguration.context ?? null);
1658
- const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
1659
- let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
1660
- if (messageDigestsPromise == null) {
1661
- messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
1662
- messageDigestValues.set(messageDigestKey, messageDigestsPromise);
1663
- }
1664
- const messageDigests = await messageDigestsPromise;
1665
- if (await verifyCandidate(messageDigests.onWire)) return publicKey;
1666
- if (messageDigestCache.proofPropertyMode !== "literal") {
1667
- const normalizedDigest = await messageDigests.normalized();
1668
- if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
1669
- }
1670
- if (fetchedKey.cached) {
1671
- logger$1.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
1672
- keyId: proof.verificationMethodId.href,
1673
- proof
1674
- });
1675
- return await verifyProofInternal(jsonLd, proof, {
1676
- ...options,
1677
- keyCache: {
1678
- get: () => Promise.resolve(void 0),
1679
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1680
- }
1681
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1682
- }
1683
- logger$1.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1684
- keyId: proof.verificationMethodId.href,
1685
- proof
1686
- });
1687
- return null;
1688
- }
1689
- const AS_NAMESPACE = "https://www.w3.org/ns/activitystreams#";
1690
- const FEP_2277_ACTOR_PROPERTIES = ["http://www.w3.org/ns/ldp#inbox", `${AS_NAMESPACE}outbox`];
1691
- const FEP_2277_COLLECTION_PROPERTIES = [
1692
- "items",
1693
- "orderedItems",
1694
- "totalItems",
1695
- "partOf",
1696
- "first",
1697
- "last",
1698
- "next",
1699
- "prev",
1700
- "current"
1701
- ].map((property) => AS_NAMESPACE + property);
1702
- const PORTABLE_OBJECT_ID_PATTERN = /^ap(?:\+ef61)?:\/\//i;
1703
- const FUNCTIONAL_PROOF_PROPERTIES = [
1704
- `${SECURITY_NAMESPACE}cryptosuite`,
1705
- SECURITY_VERIFICATION_METHOD,
1706
- `${SECURITY_NAMESPACE}proofPurpose`,
1707
- `${SECURITY_NAMESPACE}proofValue`,
1708
- "http://purl.org/dc/terms/created"
1709
- ];
1710
- function isJsonLdNode(value) {
1711
- return typeof value === "object" && value != null && !Array.isArray(value);
1712
- }
1713
- function hasValidPortableProofShape(proofValue) {
1714
- if (!isJsonLdNode(proofValue)) return false;
1715
- let proofNode = proofValue;
1716
- if ("@graph" in proofNode) {
1717
- const graph = proofNode["@graph"];
1718
- if (!Array.isArray(graph) || graph.length !== 1 || !isJsonLdNode(graph[0])) return false;
1719
- proofNode = graph[0];
1720
- }
1721
- const types = proofNode["@type"];
1722
- return Array.isArray(types) && types.length === 1 && types[0] === DATA_INTEGRITY_PROOF && FUNCTIONAL_PROOF_PROPERTIES.every((property) => {
1723
- const values = proofNode[property];
1724
- return Array.isArray(values) && values.length === 1 && !(isJsonLdNode(values[0]) && "@list" in values[0]);
1725
- });
1726
- }
1727
- function classifyFep2277CoreType(node) {
1728
- if (FEP_2277_ACTOR_PROPERTIES.every((property) => property in node)) return "actor";
1729
- if (`${SECURITY_NAMESPACE}publicKeyMultibase` in node) return "verificationMethod";
1730
- if (`${SECURITY_NAMESPACE}publicKeyPem` in node) return "publicKey";
1731
- if (`${AS_NAMESPACE}href` in node) return "link";
1732
- if (`${AS_NAMESPACE}actor` in node) return "activity";
1733
- if (FEP_2277_COLLECTION_PROPERTIES.some((property) => property in node)) return "collection";
1734
- return "object";
1735
- }
1736
- async function expandPortableObjectRoot(jsonLd, contextLoader) {
1737
- if (!isJsonLdNode(jsonLd)) throw new TypeError("Expected a single JSON-LD object.");
1738
- const loadedContexts = /* @__PURE__ */ new Map();
1739
- const loader = getNormalizationContextLoader(contextLoader);
1740
- const recordingLoader = async (url, options) => {
1741
- const remoteDocument = await loader(url, options);
1742
- const key = URL.canParse(url) ? new URL(url).href : url;
1743
- loadedContexts.set(key, structuredClone(remoteDocument));
1744
- return remoteDocument;
1745
- };
1746
- const expanded = await jsonld.expand(jsonLd, {
1747
- documentLoader: recordingLoader,
1748
- keepFreeFloatingNodes: true
1749
- });
1750
- if (expanded.length !== 1 || !isJsonLdNode(expanded[0])) throw new TypeError("Expected a single JSON-LD object.");
1751
- return {
1752
- root: expanded[0],
1753
- proofContextLoader: async (url, options) => {
1754
- const key = URL.canParse(url) ? new URL(url).href : url;
1755
- const remoteDocument = loadedContexts.get(key);
1756
- if (remoteDocument != null) return structuredClone(remoteDocument);
1757
- return await preloadedOnlyDocumentLoader(url, options);
1758
- }
1759
- };
1760
- }
1761
- async function preparePortableObjectProof(jsonLd, options) {
1762
- if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
1763
- prepared: false,
1764
- result: {
1765
- verified: false,
1766
- reason: { type: "notPortableObject" }
1767
- }
1768
- };
1769
- const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
1770
- const id = root["@id"];
1771
- if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
1772
- prepared: false,
1773
- result: {
1774
- verified: false,
1775
- reason: { type: "notPortableObject" }
1776
- }
1777
- };
1778
- const objectId = parseIri(id);
1779
- getFe34Origin(objectId);
1780
- const objectType = classifyFep2277CoreType(root);
1781
- if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
1782
- prepared: false,
1783
- result: {
1784
- verified: false,
1785
- reason: {
1786
- type: "unsupportedObjectType",
1787
- objectType
1788
- }
1789
- }
1790
- };
1791
- const proofValues = root[SECURITY_PROOF];
1792
- if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return {
1793
- prepared: false,
1794
- root,
1795
- objectType,
1796
- result: objectType === "collection" ? {
1797
- verified: false,
1798
- reason: { type: "unsecuredCollection" }
1799
- } : {
1800
- verified: false,
1801
- reason: { type: "missingProof" }
1802
- }
1803
- };
1804
- if (!Array.isArray(proofValues)) return {
1805
- prepared: false,
1806
- result: {
1807
- verified: false,
1808
- reason: {
1809
- type: "invalidProof",
1810
- proofIndex: 0
1811
- }
1812
- }
1813
- };
1814
- const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
1815
- const proofs = [];
1816
- for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
1817
- const proofValue = proofValues[proofIndex];
1818
- if (!hasValidPortableProofShape(proofValue)) return {
1819
- prepared: false,
1820
- result: {
1821
- verified: false,
1822
- reason: {
1823
- type: "invalidProof",
1824
- proofIndex
1825
- }
1826
- }
1827
- };
1828
- let proof;
1829
- try {
1830
- proof = await DataIntegrityProof.fromJsonLd(proofValue, options);
1831
- } catch {
1832
- return {
1833
- prepared: false,
1834
- result: {
1835
- verified: false,
1836
- reason: {
1837
- type: "invalidProof",
1838
- proofIndex
1839
- }
1840
- }
1841
- };
1842
- }
1843
- proofs.push(proof);
1844
- }
1845
- for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
1846
- const verificationMethod = proofs[proofIndex].verificationMethodId;
1847
- if (verificationMethod == null) return {
1848
- prepared: false,
1849
- result: {
1850
- verified: false,
1851
- reason: {
1852
- type: "invalidProof",
1853
- proofIndex
1854
- }
1855
- }
1856
- };
1857
- if (verificationMethod.protocol !== "did:") return {
1858
- prepared: false,
1859
- result: {
1860
- verified: false,
1861
- reason: {
1862
- type: "unsupportedVerificationMethod",
1863
- proofIndex,
1864
- verificationMethod
1865
- }
1866
- }
1867
- };
1868
- try {
1869
- getFe34Origin(verificationMethod);
1870
- } catch (error) {
1871
- if (!(error instanceof TypeError)) throw error;
1872
- return {
1873
- prepared: false,
1874
- result: {
1875
- verified: false,
1876
- reason: {
1877
- type: "unsupportedVerificationMethod",
1878
- proofIndex,
1879
- verificationMethod
1880
- }
1881
- }
1882
- };
1883
- }
1884
- if (!haveSameFe34Origin(objectId, verificationMethod)) return {
1885
- prepared: false,
1886
- result: {
1887
- verified: false,
1888
- reason: {
1889
- type: "verificationMethodMismatch",
1890
- proofIndex,
1891
- objectId,
1892
- verificationMethod
1893
- }
1894
- }
1895
- };
1896
- }
1897
- return {
1898
- prepared: true,
1899
- root,
1900
- objectType,
1901
- objectId,
1902
- proofs,
1903
- rawProofValues,
1904
- proofContextLoader
1905
- };
1906
- }
1907
- /**
1908
- * Applies portable-object proof policy to one map-local cryptographic result.
1909
- *
1910
- * @internal
1911
- */
1912
- async function verifyPortableObjectProofPolicy(jsonLd, key, options = {}) {
1913
- const policyOptions = {
1914
- ...options,
1915
- contextLoader: preloadedOnlyDocumentLoader
1916
- };
1917
- const prepared = await preparePortableObjectProof(jsonLd, policyOptions);
1918
- if (!prepared.prepared) return prepared.result;
1919
- const policyProof = prepared.proofs[0];
1920
- const literalProof = isJsonLdNode(jsonLd) && isJsonLdNode(jsonLd.proof) ? (await parseRawProofCandidates(jsonLd, [jsonLd.proof], policyOptions, prepared.proofContextLoader))[0]?.proof : null;
1921
- const verificationMethod = policyProof?.verificationMethodId;
1922
- if (prepared.proofs.length !== 1 || key == null || policyProof == null || literalProof == null || !sameProof(policyProof, literalProof) || verificationMethod == null || key.id?.href !== verificationMethod.href) return {
1923
- verified: false,
1924
- reason: {
1925
- type: "invalidProof",
1926
- proofIndex: prepared.proofs.length > 1 ? 1 : 0
1927
- }
1928
- };
1929
- return {
1930
- verified: true,
1931
- keys: [key],
1932
- objectId: formatIri(prepared.objectId)
1933
- };
1934
- }
1935
- /**
1936
- * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
1937
- *
1938
- * This applies the FEP-2277 core-type classification to the top-level JSON-LD
1939
- * node. Portable actors, activities, and objects require proofs. A portable
1940
- * collection without a proof is reported separately so a caller can apply a
1941
- * gateway trust policy. Embedded portable objects are not traversed.
1942
- *
1943
- * Every proof must use a DID URL whose DID matches the portable object's
1944
- * authority, and every proof must pass {@link verifyProof}.
1945
- *
1946
- * @param jsonLd The JSON-LD document to verify.
1947
- * @param options Additional options. See also
1948
- * {@link VerifyPortableObjectProofOptions}.
1949
- * @returns The detailed portable proof-policy result.
1950
- * @throws {TypeError} If the input is not a single JSON-LD object or has a
1951
- * malformed portable ID.
1952
- * @since 2.4.0
1953
- */
1954
- async function verifyPortableObjectProof(jsonLd, options = {}) {
1955
- return (await verifyPortableObjectProofWithRoot(jsonLd, options)).result;
1956
- }
1957
- /**
1958
- * Same as {@link verifyPortableObjectProof}, but also returns the expanded
1959
- * root node and its FEP-2277 core type, so that a caller can apply further
1960
- * policy, such as the gateway trust policy for unsecured collections, to the
1961
- * same interpretation of the document.
1962
- * @internal
1963
- */
1964
- async function verifyPortableObjectProofWithRoot(jsonLd, options = {}) {
1965
- const prepared = await preparePortableObjectProof(jsonLd, options);
1966
- if (!prepared.prepared) return {
1967
- result: prepared.result,
1968
- ...prepared.root == null ? {} : { root: prepared.root },
1969
- ...prepared.objectType == null ? {} : { objectType: prepared.objectType }
1970
- };
1971
- const { root, objectType } = prepared;
1972
- return {
1973
- result: await verifyPreparedPortableObjectProof(jsonLd, prepared, options),
1974
- root,
1975
- objectType
1976
- };
1977
- }
1978
- async function verifyPreparedPortableObjectProof(jsonLd, prepared, options) {
1979
- const { proofs, rawProofValues, proofContextLoader } = prepared;
1980
- const keys = [];
1981
- const rawProofCandidatePool = {
1982
- candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
1983
- used: /* @__PURE__ */ new Set()
1984
- };
1985
- const messageDigestCache = { proofContextLoader };
1986
- for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
1987
- const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proofs[proofIndex]);
1988
- if (rawProofCandidate == null) return {
1989
- verified: false,
1990
- reason: {
1991
- type: "invalidProof",
1992
- proofIndex
1993
- }
1994
- };
1995
- const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
1996
- if (key == null) return {
1997
- verified: false,
1998
- reason: {
1999
- type: "invalidProof",
2000
- proofIndex
2001
- }
2002
- };
2003
- keys.push(key);
2004
- }
2005
- return {
2006
- verified: true,
2007
- keys
2008
- };
2009
- }
2010
- /**
2011
- * Verifies the given object. It will verify all the proofs in the object,
2012
- * and succeed only if all the proofs are valid and all attributions and
2013
- * actors are authenticated by the proofs.
2014
- * @template T The type of the object to verify.
2015
- * @param cls The class of the object to verify. It must be a subclass of
2016
- * the {@link Object}.
2017
- * @param jsonLd The JSON-LD object to verify. It's assumed that the object
2018
- * is a compacted JSON-LD representation of a `T` with `@context`.
2019
- * @param options Additional options. See also {@link VerifyObjectOptions}.
2020
- * @returns The object if it's verified, or `null` if it's not.
2021
- * @throws {TypeError} If the object is invalid or unsupported.
2022
- * @since 0.10.0
2023
- */
2024
- async function verifyObject(cls, jsonLd, options = {}) {
2025
- const logger = getLogger([
2026
- "fedify",
2027
- "sig",
2028
- "proof"
2029
- ]);
2030
- const object = await cls.fromJsonLd(jsonLd, options);
2031
- const defaultDocumentLoader = getDocumentLoader();
2032
- const proofContextLoader = options.contextLoader ?? defaultDocumentLoader;
2033
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
2034
- if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
2035
- const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
2036
- const rawProofCandidates = isJsonLdNode(jsonLd) ? await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader) : [];
2037
- const rawProofCandidatePool = {
2038
- candidates: rawProofCandidates,
2039
- used: /* @__PURE__ */ new Set()
2040
- };
2041
- const baseDocumentLoader = options.documentLoader ?? defaultDocumentLoader;
2042
- const hydratedCandidates = /* @__PURE__ */ new Set();
2043
- let loadedPortableProofs = 0;
2044
- let acceptedPortableProofs = 0;
2045
- const acceptPortableProofDocument = async () => {
2046
- acceptedPortableProofs++;
2047
- return { verified: true };
2048
- };
2049
- const proofDocumentLoader = async (url, loaderOptions) => {
2050
- const remoteDocument = await baseDocumentLoader(url, loaderOptions);
2051
- if (PORTABLE_OBJECT_ID_PATTERN.test(url)) loadedPortableProofs++;
2052
- const reference = normalizeDocumentUrl(url);
2053
- const candidateIndex = rawProofCandidates.findIndex((candidate, index) => !hydratedCandidates.has(index) && !rawProofCandidatePool.used.has(index) && candidate.reference === reference);
2054
- if (candidateIndex >= 0) {
2055
- hydratedCandidates.add(candidateIndex);
2056
- let parsed = null;
2057
- try {
2058
- parsed = await DataIntegrityProof.fromJsonLd(remoteDocument.document, {
2059
- documentLoader: baseDocumentLoader,
2060
- contextLoader: proofContextLoader,
2061
- tracerProvider: options.tracerProvider,
2062
- baseUrl: parseIri(remoteDocument.documentUrl)
2063
- });
2064
- } catch {}
2065
- rawProofCandidates[candidateIndex] = {
2066
- value: structuredClone(remoteDocument.document),
2067
- proof: parsed,
2068
- reference
2069
- };
2070
- }
2071
- return remoteDocument;
2072
- };
2073
- for await (const proof of object.getProofs({
2074
- ...options,
2075
- documentLoader: proofDocumentLoader,
2076
- gateways: [],
2077
- verifyPortableObject: acceptPortableProofDocument
2078
- })) {
2079
- const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proof);
2080
- if (rawProofCandidate == null) return null;
2081
- const key = await verifyProofWithMessageDigestCache(jsonLd, proof, options, { proofContextLoader }, rawProofCandidate);
2082
- if (key === null) return null;
2083
- if (proof.verificationMethodId == null) return null;
2084
- if (key.controllerId == null) {
2085
- logger.debug("Key {keyId} does not have a controller.", { keyId: key.id?.href });
2086
- continue;
2087
- }
2088
- deleteAuthenticatedAttribution(attributions, key.controllerId, proof.verificationMethodId);
2089
- }
2090
- if (acceptedPortableProofs < loadedPortableProofs) {
2091
- logger.debug("Some portable proof references could not be dereferenced.");
2092
- return null;
2093
- }
2094
- if (attributions.size > 0) {
2095
- logger.debug("Some attributions are not authenticated by the proofs: {attributions}.", { attributions: [...attributions] });
2096
- return null;
2097
- }
2098
- return object;
2099
- }
2100
- function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
2101
- const controllerHasCryptographicOrigin = hasCryptographicOrigin(controllerId.href);
2102
- const verificationMethodMatchesController = controllerHasCryptographicOrigin && hasCryptographicOrigin(verificationMethodId.href) && haveSameFe34Origin(controllerId, verificationMethodId);
2103
- if (!controllerHasCryptographicOrigin || verificationMethodMatchesController) attributions.delete(controllerId.href);
2104
- if (!verificationMethodMatchesController) return;
2105
- for (const attribution of [...attributions]) if (hasCryptographicOrigin(attribution) && haveSameFe34Origin(controllerId, attribution)) attributions.delete(attribution);
2106
- }
2107
- function hasCryptographicOrigin(iri) {
2108
- return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
2109
- }
2110
- //#endregion
2111
- //#region src/sig/owner.ts
2112
- const logger = getLogger([
2113
- "fedify",
2114
- "sig",
2115
- "owner"
2116
- ]);
2117
- /**
2118
- * Checks if the actor of the given activity owns the specified key.
2119
- *
2120
- * Ownership is never taken from what the activity or the key say about
2121
- * themselves, as both are written by whoever sent the activity. It is
2122
- * established from a document that the owner itself serves: either the key's
2123
- * claimed owner links back to the key, or the actor the activity claims lists
2124
- * the key as its own.
2125
- *
2126
- * @param activity The activity to check.
2127
- * @param key The public key to check.
2128
- * @param options Options for checking the key ownership.
2129
- * @returns Whether the actor is the owner of the key.
2130
- */
2131
- async function doesActorOwnKey(activity, key, options) {
2132
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.verify_key_ownership", {
2133
- kind: SpanKind.INTERNAL,
2134
- attributes: {
2135
- "activitypub.actor.id": activity.actorId?.href ?? "",
2136
- "activitypub.key.id": key.id?.href ?? ""
2137
- }
2138
- }, async (span) => {
2139
- try {
2140
- const actorId = activity.actorId;
2141
- if (actorId == null) {
2142
- span.setAttribute("activitypub.key_ownership.verified", false);
2143
- span.setAttribute("activitypub.key_ownership.method", "none");
2144
- return false;
2145
- }
2146
- if (key.ownerId != null) {
2147
- const owner = await verifyKeyOwnership(key, options);
2148
- if (owner?.id != null && owner.id.href === actorId.href) {
2149
- span.setAttribute("activitypub.key_ownership.verified", true);
2150
- span.setAttribute("activitypub.key_ownership.method", "key_owner");
2151
- return true;
2152
- }
2153
- }
2154
- const actor = await fetchActorDocument(actorId, options);
2155
- if (actor != null && await doesActorListKey(actor, key, options)) {
2156
- span.setAttribute("activitypub.key_ownership.verified", true);
2157
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
2158
- return true;
2159
- }
2160
- logger.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
2161
- actorId: actorId.href,
2162
- keyId: key.id?.href
2163
- });
2164
- span.setAttribute("activitypub.key_ownership.verified", false);
2165
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
2166
- return false;
2167
- } catch (error) {
2168
- span.recordException(error);
2169
- span.setStatus({
2170
- code: SpanStatusCode.ERROR,
2171
- message: String(error)
2172
- });
2173
- throw error;
2174
- } finally {
2175
- span.end();
2176
- }
2177
- });
2178
- }
2179
- /**
2180
- * Determines whether the given actor's own document lists the given key among
2181
- * its public keys.
2182
- *
2183
- * Keys are matched by id, which is what an actor document links to. A key
2184
- * document may leave its id implicit, though, and then there is no id for the
2185
- * actor to link to; the key material itself is the only thing the two can
2186
- * have in common, so that is what gets compared.
2187
- */
2188
- async function doesActorListKey(actor, key, options) {
2189
- if (key.id != null) {
2190
- for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
2191
- return false;
2192
- }
2193
- if (key.publicKey == null) return false;
2194
- const publicKeys = actor.getPublicKeys({
2195
- ...options,
2196
- suppressError: true
2197
- });
2198
- for await (const publicKey of publicKeys) {
2199
- if (publicKey.publicKey == null) continue;
2200
- if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
2201
- }
2202
- return false;
2203
- }
2204
- /**
2205
- * Compares two public keys by their key material, ignoring the metadata that
2206
- * surrounds it.
2207
- */
2208
- async function isSamePublicKey(a, b) {
2209
- const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
2210
- 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;
2211
- }
2212
- /**
2213
- * Gets the actor that owns the specified key. Returns `null` if the key has no
2214
- * known owner.
2215
- *
2216
- * The owner is only returned when the key and the owner link to each other:
2217
- * a document that merely claims to own a key is not enough, as the claim and
2218
- * the key can come from the same host.
2219
- *
2220
- * @param keyId The ID of the key to check, or the key itself.
2221
- * @param options Options for getting the key owner.
2222
- * @returns The actor that owns the key, or `null` if the key has no known
2223
- * owner.
2224
- * @since 0.7.0
2225
- */
2226
- async function getKeyOwner(keyId, options) {
2227
- const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
2228
- const documentLoader = options.documentLoader ?? getDocumentLoader();
2229
- const fetchOptions = {
2230
- documentLoader,
2231
- contextLoader: options.contextLoader ?? getDocumentLoader(),
2232
- tracerProvider
2233
- };
2234
- if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
2235
- let keyDoc;
2236
- let documentUrl = keyId;
2237
- try {
2238
- const remoteDocument = await documentLoader(keyId.href);
2239
- keyDoc = remoteDocument.document;
2240
- documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
2241
- } catch (_) {
2242
- return null;
2243
- }
2244
- let object;
2245
- try {
2246
- object = await Object$1.fromJsonLd(keyDoc, {
2247
- ...fetchOptions,
2248
- baseUrl: documentUrl
2249
- });
2250
- } catch (e) {
2251
- if (!(e instanceof TypeError)) throw e;
2252
- try {
2253
- object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
2254
- } catch (e) {
2255
- if (e instanceof TypeError) return null;
2256
- throw e;
2257
- }
2258
- }
2259
- if (object instanceof CryptographicKey) {
2260
- if (object.id != null && object.id.href !== keyId.href) return null;
2261
- return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
2262
- }
2263
- if (!isActor(object)) return null;
2264
- if (object.id == null || object.id.origin !== documentUrl.origin) {
2265
- logger.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
2266
- documentUrl: documentUrl.href,
2267
- actorId: object.id?.href,
2268
- keyId: keyId.href
2269
- });
2270
- return null;
2271
- }
2272
- for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
2273
- return null;
2274
- }
2275
- //#endregion
2276
- export { signJsonLd as C, wrapContextLoaderForJsonLd as D, verifySignature as E, normalizeOutgoingActivityJsonLd as O, isInvalidUrlTypeError as S, verifyJsonLd as T, detachSignature as _, signObject as a, hasSignatureLike as b, verifyPortableObjectProof as c, verifyProof as d, InvalidContextReferenceError as f, createSignature as g, compactJsonLd as h, hasProofLike as i, verifyPortableObjectProofPolicy as l, attachSignature as m, getKeyOwner as n, verifyMapLocalProof as o, assertSafeJsonLd as p, createProof as r, verifyObject as s, doesActorOwnKey as t, verifyPortableObjectProofWithRoot as u, getNormalizationContextLoader as v, verifyCompactJsonLd as w, isClearlyMalformedContextReference as x, hasSignature as y };