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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/{builder-BGlpUocK.mjs → builder-Bno54o_-.mjs} +34 -3
  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-B6Aj2kGY.mjs → compound-proof-X3SxXVbc.mjs} +191 -13
  6. package/dist/{context-CZjZYXFC.d.cts → context-C43spTGI.d.cts} +5 -2
  7. package/dist/{context-BSywYspi.d.ts → context-MORIQJIh.d.ts} +5 -2
  8. package/dist/{deno-Dn-py9Zy.mjs → deno-dxdvl2XZ.mjs} +1 -1
  9. package/dist/{docloader-BUq5bYJr.mjs → docloader-eBxQDsk9.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/compound-fanout.test.mjs +3 -3
  12. package/dist/federation/handler-compound-proof.test.mjs +3 -3
  13. package/dist/federation/handler.test.mjs +5 -5
  14. package/dist/federation/hashlink-media.test.mjs +2 -2
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/metrics.test.mjs +1 -1
  17. package/dist/federation/middleware.test.mjs +7 -7
  18. package/dist/federation/mod.cjs +1 -1
  19. package/dist/federation/mod.d.cts +2 -2
  20. package/dist/federation/mod.d.ts +2 -2
  21. package/dist/federation/mod.js +1 -1
  22. package/dist/federation/outgoing-proof.test.mjs +254 -5
  23. package/dist/federation/portable-gateway-keys.test.mjs +72 -11
  24. package/dist/federation/portable-inbox.test.mjs +487 -10
  25. package/dist/federation/portable.test.mjs +182 -4
  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 +89 -1
  31. package/dist/{federation-BLGx8JUH.cjs → federation-C4Ef3JKa.cjs} +1487 -1070
  32. package/dist/{http-B5q1CHtL.cjs → http-C8cZTE3Y.cjs} +1224 -985
  33. package/dist/{http-4PCCvhsU.js → http-D-rbr_Sy.js} +1663 -1460
  34. package/dist/{http-B0VRNipE.mjs → http-DsgawTd8.mjs} +82 -7
  35. package/dist/{key-BJrp524f.mjs → key-DYfmjnmp.mjs} +39 -99
  36. package/dist/{kv-cache-1KUmAPH7.js → kv-cache-DIxwMeNi.js} +1 -1
  37. package/dist/{kv-cache-Dhhhrryv.cjs → kv-cache-Dvd-Q-E2.cjs} +1 -1
  38. package/dist/{kv-cache-C4C3LyYW.mjs → kv-cache-EvOgrFsS.mjs} +1 -1
  39. package/dist/{ld-BmFz5NLA.mjs → ld-B00wWHzc.mjs} +3 -3
  40. package/dist/{metrics-Beod6tzO.mjs → metrics-BP3vdBpb.mjs} +1 -1
  41. package/dist/{middleware-BKeQYPm0.mjs → middleware-Br1_d-Ga.mjs} +606 -389
  42. package/dist/{middleware-D_9pNYe9.js → middleware-CcXMe400.js} +1602 -1185
  43. package/dist/{middleware-B7CNsyqt.mjs → middleware-CeBVBa61.mjs} +1 -1
  44. package/dist/{mod-B2h2KY0q.d.ts → mod-BL5BQHCq.d.ts} +1 -1
  45. package/dist/{mod-HDSvS-ww.d.cts → mod-C8LieBzF.d.cts} +16 -3
  46. package/dist/{mod-C9WSpZWm.d.ts → mod-Coacostr.d.ts} +16 -3
  47. package/dist/{mod-JzkaEXsi.d.cts → mod-DMI4DbOo.d.cts} +1 -1
  48. package/dist/mod.cjs +5 -5
  49. package/dist/mod.d.cts +3 -3
  50. package/dist/mod.d.ts +3 -3
  51. package/dist/mod.js +5 -5
  52. package/dist/nodeinfo/handler.test.mjs +1 -1
  53. package/dist/{owner-CsKVgMzk.mjs → owner-BJPDRDRq.mjs} +5 -4
  54. package/dist/{owner-BQFZtFV4.cjs → owner-DSzH7wro.cjs} +2 -2
  55. package/dist/{owner-_pbbgLJK.js → owner-U12fDpQW.js} +2 -2
  56. package/dist/{portable-key-B4R-CiIV.mjs → portable-key-D0mWbV9G.mjs} +60 -41
  57. package/dist/portable-key-id-Bva5iT3W.mjs +136 -0
  58. package/dist/{proof-ozG4HfcQ.mjs → proof-ChjBwnep.mjs} +59 -18
  59. package/dist/{send-ClPt8nYu.mjs → send-yFX0E-ye.mjs} +3 -3
  60. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  61. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  62. package/dist/sig/compound-proof-verification.test.mjs +160 -3
  63. package/dist/sig/compound-proof.test.mjs +2 -2
  64. package/dist/sig/http.test.mjs +72 -2
  65. package/dist/sig/key.test.mjs +1 -1
  66. package/dist/sig/ld.test.mjs +2 -2
  67. package/dist/sig/mod.cjs +3 -3
  68. package/dist/sig/mod.d.cts +1 -1
  69. package/dist/sig/mod.d.ts +1 -1
  70. package/dist/sig/mod.js +3 -3
  71. package/dist/sig/owner.test.mjs +1 -1
  72. package/dist/sig/portable-collection.test.mjs +69 -5
  73. package/dist/sig/portable-key.test.mjs +176 -10
  74. package/dist/sig/proof.test.mjs +107 -4
  75. package/dist/{sig-k3C8sF7g.cjs → sig-B689Nj7y.cjs} +19 -3
  76. package/dist/{sig-DhdomAN0.js → sig-C85KqAcx.js} +19 -3
  77. package/dist/{temporal-Ba0EAZAI.mjs → temporal-Dl9x-Qw4.mjs} +1 -1
  78. package/dist/testing/kv.test.mjs +1 -1
  79. package/dist/testing/mod.d.mts +5 -2
  80. package/dist/utils/docloader.test.mjs +2 -2
  81. package/dist/utils/kv-cache.test.mjs +1 -1
  82. package/dist/utils/mod.cjs +1 -1
  83. package/dist/utils/mod.js +1 -1
  84. package/package.json +7 -7
@@ -3,17 +3,147 @@ import { URLPattern } from "urlpattern-polyfill";
3
3
  import { getLogger } from "@logtape/logtape";
4
4
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, PUBLIC_COLLECTION, getTypeId, isActor } from "@fedify/vocab";
5
5
  import { SpanKind, SpanStatusCode, metrics, trace } from "@opentelemetry/api";
6
+ import { FetchError, canonicalizePortableUri, encodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, isGatewayUrl, parseDidKeyVerificationMethod, parseIri, preloadedContexts, toCompatibleEf61Id } from "@fedify/vocab-runtime";
7
+ import { isCompatibleEf61Iri } from "@fedify/vocab-runtime/internal/portable-dereference";
6
8
  import { encodeHex } from "byte-encodings/hex";
7
- import { FetchError, canonicalizePortableUri, encodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, haveSameFe34Origin, isGatewayUrl, parseDidKeyVerificationMethod, parseIri, preloadedContexts, toCompatibleEf61Id } from "@fedify/vocab-runtime";
8
9
  import jsonld from "@fedify/vocab-runtime/jsonld";
9
10
  import { Item, decodeDict, encodeDict, encodeItem } from "structured-field-values";
11
+ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
10
12
  import { isPlainJsonTree, retainSignedRepresentation } from "@fedify/vocab-runtime/internal/signed-representation";
11
13
  import serialize from "json-canon";
12
- import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
13
14
  import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
14
15
  //#region deno.json
15
16
  var name = "@fedify/fedify";
16
- var version = "2.4.0-dev.2084+4b8bd325";
17
+ var version = "2.4.0-dev.2099+cd074fe2";
18
+ //#endregion
19
+ //#region src/sig/portable-key-id.ts
20
+ const COMPATIBLE_KEY_ID_PATH_PATTERN = /^\/\.well-known\/apgateway\/did(?::|%3A)/i;
21
+ /**
22
+ * Checks whether the URL is an `ap:` or `ap+ef61:` URI.
23
+ * @internal
24
+ */
25
+ function isPortableUri(url) {
26
+ return url.protocol === "ap:" || url.protocol === "ap+ef61:";
27
+ }
28
+ /**
29
+ * Checks whether an ID identifies an [FEP-ef61] portable object, i.e., it is
30
+ * an `ap:` or `ap+ef61:` URI, or looks like a compatible identifier.
31
+ * A malformed compatible identifier counts too, so that it is rejected as
32
+ * a portable object that no proof can match, rather than trusted by its web
33
+ * origin.
34
+ *
35
+ * [FEP-ef61]: https://w3id.org/fep/ef61
36
+ * @internal
37
+ */
38
+ function isPortableId(id) {
39
+ if (typeof id === "string") {
40
+ if (/^ap(?:\+ef61)?:\/\//i.test(id)) return true;
41
+ } else if (isPortableUri(id)) return true;
42
+ return isCompatibleEf61Iri(id);
43
+ }
44
+ /**
45
+ * Gets the DID, i.e., the FEP-fe34 cryptographic origin, of an `ap:` or
46
+ * `ap+ef61:` URI, a DID URL, or a compatible identifier.
47
+ * @returns The DID, or `null` if the ID is none of them, or is malformed.
48
+ * @internal
49
+ */
50
+ function getPortableDid(id) {
51
+ try {
52
+ const raw = typeof id === "string" ? id : id.href;
53
+ if (/^(?:did:|ap(?:\+ef61)?:\/\/)/i.test(raw)) return getFe34Origin(id);
54
+ const portable = fromCompatibleEf61Id(id);
55
+ return portable == null ? null : getFe34Origin(portable);
56
+ } catch (error) {
57
+ if (error instanceof TypeError) return null;
58
+ throw error;
59
+ }
60
+ }
61
+ /**
62
+ * Checks whether an activity is performed by an FEP-ef61 portable actor,
63
+ * i.e., any of its actors has an `ap:` or `ap+ef61:` ID, or a compatible
64
+ * identifier.
65
+ * @internal
66
+ */
67
+ function hasPortableActor(activity) {
68
+ return activity.actorIds.some((id) => isPortableId(id));
69
+ }
70
+ /**
71
+ * Checks whether a key ID looks like an [FEP-ef61] compatible identifier,
72
+ * i.e., an HTTP(S) URL under a gateway's `/.well-known/apgateway/did:` path.
73
+ * Such a key ID names a key that a gateway holds for a portable actor, so it
74
+ * is resolved only as a gateway key, and never cached in a key cache.
75
+ *
76
+ * [FEP-ef61]: https://w3id.org/fep/ef61
77
+ * @internal
78
+ */
79
+ function isCompatibleKeyId(keyId) {
80
+ return (keyId.protocol === "http:" || keyId.protocol === "https:") && COMPATIBLE_KEY_ID_PATH_PATTERN.test(keyId.pathname);
81
+ }
82
+ /**
83
+ * Gets the canonical portable ID of an actor ID that is either an `ap:` or
84
+ * `ap+ef61:` URI or a compatible identifier.
85
+ * @returns The canonical portable ID, or `null` if the ID is neither, or is
86
+ * malformed.
87
+ * @internal
88
+ */
89
+ function getCanonicalPortableId(id) {
90
+ try {
91
+ if (isPortableUri(id)) return canonicalizePortableUri(formatIri(id));
92
+ const portable = fromCompatibleEf61Id(id);
93
+ if (portable == null) return null;
94
+ return canonicalizePortableUri(formatIri(portable));
95
+ } catch (error) {
96
+ if (error instanceof TypeError) return null;
97
+ throw error;
98
+ }
99
+ }
100
+ /**
101
+ * Builds the base of the key IDs of a gateway's keys for a portable actor:
102
+ * the actor's compatible identifier on the gateway.
103
+ * @param actorId The portable actor's ID, either an `ap:` or `ap+ef61:` URI
104
+ * or a compatible identifier. It must not have a fragment.
105
+ * @param gateway The gateway's origin, e.g., `https://example.com`.
106
+ * @returns The compatible identifier without query and fragment.
107
+ * @throws {TypeError} If the actor ID is not a portable ID, or has
108
+ * a fragment.
109
+ * @internal
110
+ */
111
+ function getGatewayKeyBase(actorId, gateway) {
112
+ let portable;
113
+ if (isPortableUri(actorId)) portable = actorId;
114
+ else try {
115
+ portable = fromCompatibleEf61Id(actorId);
116
+ } catch (error) {
117
+ if (!(error instanceof TypeError)) throw error;
118
+ portable = null;
119
+ }
120
+ if (portable == null) throw new TypeError(`The portable actor ID ${actorId.href} must be an ap: or ap+ef61: URI, or an FEP-ef61 compatible identifier.`);
121
+ if (portable.hash !== "") throw new TypeError(`The portable actor ID ${actorId.href} must not have a fragment.`);
122
+ const base = toCompatibleEf61Id(portable, gateway);
123
+ base.search = "";
124
+ base.hash = "";
125
+ return base;
126
+ }
127
+ /**
128
+ * Tells whether a parsed document is a portable actor, i.e., an actor whose
129
+ * ID is an `ap:` or `ap+ef61:` URI or a compatible identifier. Such an actor
130
+ * is never authenticated by the web origin that served it; at a compatible
131
+ * key ID, it makes the key a gateway key that only
132
+ * {@link verifyPortableGatewayKeyDocument} can vouch for.
133
+ * @internal
134
+ */
135
+ function isPortableActorDocument(object) {
136
+ return isActor(object) && object.id != null && isPortableId(object.id);
137
+ }
138
+ /**
139
+ * Compares two public keys by their key material.
140
+ * @internal
141
+ */
142
+ async function isSamePublicKey(a, b) {
143
+ if (a.algorithm.name !== b.algorithm.name) return false;
144
+ const [x, y] = await Promise.all([crypto.subtle.exportKey("jwk", a), crypto.subtle.exportKey("jwk", b)]);
145
+ 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;
146
+ }
17
147
  //#endregion
18
148
  //#region src/sig/accept.ts
19
149
  /**
@@ -173,440 +303,44 @@ const preloadedOnlyDocumentLoader = (url) => {
173
303
  return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
174
304
  };
175
305
  //#endregion
176
- //#region src/compat/secured-document.ts
177
- function isJsonMap$1(value) {
178
- return typeof value === "object" && value != null && !Array.isArray(value);
179
- }
180
- function isNonEmptyString(value) {
181
- return typeof value === "string" && value.length > 0;
182
- }
183
- function hasDataIntegrityProofType(value) {
184
- return (Array.isArray(value) ? value : [value]).some((type) => type === "DataIntegrityProof" || type === "https://w3id.org/security#DataIntegrityProof");
185
- }
186
- /**
187
- * Checks whether a JSON value is a complete, self-contained secured document:
188
- * a map with its own `@context` and exactly one direct, map-valued `proof`
189
- * that carries every member `eddsa-jcs-2022` proof generation produces.
190
- *
191
- * This is deliberately stricter than {@link hasProofLike}, which exists to
192
- * decide whether a document is worth verifying. Here a false positive would
193
- * silently suppress a wire-compatibility fix on an ordinary document, so a
194
- * partial or malformed proof does not qualify.
195
- *
196
- * @internal
197
- */
198
- function isSelfContainedSecuredDocument(value) {
199
- if (!isJsonMap$1(value)) return false;
200
- if (!Object.hasOwn(value, "@context") || value["@context"] == null) return false;
201
- if (!Object.hasOwn(value, "proof")) return false;
202
- const proof = value.proof;
203
- if (!isJsonMap$1(proof)) return false;
204
- return hasDataIntegrityProofType(proof.type) && isNonEmptyString(proof.cryptosuite) && isNonEmptyString(proof.created) && isNonEmptyString(proof.verificationMethod) && isNonEmptyString(proof.proofPurpose) && isNonEmptyString(proof.proofValue);
205
- }
206
- //#endregion
207
- //#region src/compat/public-audience.ts
208
- const logger$4 = getLogger([
209
- "fedify",
210
- "compat",
211
- "public-audience"
212
- ]);
213
- const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
214
- "to",
215
- "cc",
216
- "bto",
217
- "bcc",
218
- "audience"
219
- ]);
220
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
221
- const MAX_TRAVERSAL_DEPTH$1 = 64;
222
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(preloadedContexts));
223
- function hasPublicCurieInAddressing(value, preserveSecured, parentKey, depth = 0) {
224
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
225
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
226
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, preserveSecured, parentKey, depth + 1));
227
- if (typeof value !== "object" || value == null) return false;
228
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return false;
229
- const record = value;
230
- for (const key of Object.keys(record)) {
231
- if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
232
- if (key === "@context") continue;
233
- if (hasPublicCurieInAddressing(record[key], preserveSecured, key, depth + 1)) return true;
234
- }
235
- return false;
236
- }
237
- function rewritePublicAudience(value, preserveSecured, parentKey, depth = 0) {
238
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return PUBLIC_COLLECTION.href;
239
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
240
- if (Array.isArray(value)) {
241
- let changed = false;
242
- const mapped = value.map((item) => {
243
- const rewritten = rewritePublicAudience(item, preserveSecured, parentKey, depth + 1);
244
- if (rewritten !== item) changed = true;
245
- return rewritten;
246
- });
247
- return changed ? mapped : value;
248
- }
249
- if (typeof value !== "object" || value == null) return value;
250
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return value;
251
- const record = value;
252
- let changed = false;
253
- const normalized = Object.create(null);
254
- for (const key of Object.keys(record)) {
255
- 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);
256
- if (rewritten !== record[key]) changed = true;
257
- normalized[key] = rewritten;
258
- }
259
- return changed ? normalized : value;
260
- }
261
- /**
262
- * Reports whether `value` carries an `@context` property anywhere inside
263
- * its subtree (not counting the value itself). A nested `@context` can
264
- * introduce a local term-definition scope that redefines `as:` or `Public`
265
- * even when the top-level `@context` is safe, so the fast path must defer
266
- * to the URDNA2015 equivalence check whenever one is present.
267
- */
268
- function hasNestedContext$1(value, depth = 0) {
269
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
270
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
271
- if (typeof value !== "object" || value == null) return false;
272
- const record = value;
273
- for (const key of Object.keys(record)) {
274
- if (key === "@context") return true;
275
- if (hasNestedContext$1(record[key], depth + 1)) return true;
276
- }
277
- return false;
278
- }
279
- /**
280
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
281
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
282
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
283
- * preloaded context set AND including the ActivityStreams URL qualify,
284
- * AND no nested subtree carries its own `@context` that might redefine
285
- * those terms within a local scope. When all of that holds the rewrite
286
- * is provably semantics-preserving and the URDNA2015 equivalence check
287
- * can be skipped. Any other shape (unknown external URLs, inline
288
- * objects at the top level, nested `@context` blocks) is treated as
289
- * potentially unsafe.
290
- */
291
- function hasKnownSafeContext$1(jsonLd) {
292
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
293
- const record = jsonLd;
294
- if (!Object.hasOwn(record, "@context")) return false;
295
- const ctx = record["@context"];
296
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
297
- if (entries == null || entries.length === 0) return false;
298
- let hasAs = false;
299
- for (const entry of entries) {
300
- if (typeof entry !== "string") return false;
301
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
302
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
303
- }
304
- if (!hasAs) return false;
305
- for (const key of Object.keys(record)) {
306
- if (key === "@context") continue;
307
- if (hasNestedContext$1(record[key])) return false;
308
- }
309
- return true;
310
- }
311
- /**
312
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
313
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
314
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
315
- *
316
- * Several ActivityPub implementations, Lemmy among them, match these
317
- * fields as plain URLs without running JSON-LD expansion, and silently
318
- * drop activities whose public addressing appears in CURIE form. This
319
- * helper works around that gap.
320
- *
321
- * For documents whose `@context` is drawn entirely from Fedify's
322
- * preloaded context set and includes the ActivityStreams URL, the
323
- * rewrite is applied directly: the content of every preloaded non-AS
324
- * context is known not to redefine the `as:` prefix or the bare `Public`
325
- * term, so the semantics are preserved by construction. Any other
326
- * shape (an inline object, an unknown external URL, and so on) is
327
- * treated as potentially unsafe and gated on a JSON-LD equivalence
328
- * check; both forms are canonicalized with URDNA2015 and the resulting
329
- * N-Quads are compared. When they differ, the original document is
330
- * returned unchanged. Canonicalization failures also fall back to the
331
- * original document.
332
- *
333
- * When no `contextLoader` is supplied the helper falls back to an
334
- * internal loader that resolves only the URLs in Fedify's
335
- * preloaded-contexts set and rejects every other URL without issuing a
336
- * network request. That behaviour is deliberately narrower than
337
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
338
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
339
- * helper is reached from verification paths (`verifyProof()` /
340
- * `verifyObject()`) that operate on inbound, potentially adversarial
341
- * JSON-LD, and a default loader that fetches attacker-supplied
342
- * `@context` URLs on the caller's behalf would be an SSRF vector.
343
- * Canonicalization failures against the restricted loader fall back to
344
- * the original document, same as any other canonicalization error.
345
- * Callers that genuinely need the remote-fetch loader (for example
346
- * applications that sign local JSON-LD against a custom vocabulary)
347
- * should pass a `contextLoader` explicitly.
348
- *
349
- * Must be called before any signing step that canonicalizes the
350
- * compact form byte-for-byte (for example, Object Integrity Proofs
351
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
352
- * matches what is sent on the wire.
353
- */
354
- async function normalizePublicAudience(jsonLd, contextLoader, options = {}) {
355
- const preserveSecured = options.preserveNestedSecuredDocuments ?? false;
356
- if (!hasPublicCurieInAddressing(jsonLd, preserveSecured)) return jsonLd;
357
- const normalized = rewritePublicAudience(jsonLd, preserveSecured);
358
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
359
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
360
- try {
361
- const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
362
- format: "application/n-quads",
363
- documentLoader: loader
364
- }), jsonld.canonize(normalized, {
365
- format: "application/n-quads",
366
- documentLoader: loader
367
- })]);
368
- if (before === after) return normalized;
369
- 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.");
370
- } catch (error) {
371
- logger$4.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
372
- }
373
- return jsonLd;
374
- }
375
- //#endregion
376
- //#region src/compat/outgoing-jsonld.ts
377
- const logger$3 = getLogger([
378
- "fedify",
379
- "compat",
380
- "outgoing-jsonld"
381
- ]);
382
- const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
383
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
384
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
385
- const MAX_TRAVERSAL_DEPTH = 64;
386
- function isJsonLdListObject(value) {
387
- return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
388
- }
389
- function isJsonLdValueObject(value) {
390
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
391
- }
392
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
393
- if (Array.isArray(value)) {
394
- if (seen.has(value)) return;
395
- seen.add(value);
396
- for (const item of value) yield* getContextObjects(item, seen);
397
- return;
398
- }
399
- if (typeof value === "object" && value != null) {
400
- if (seen.has(value)) return;
401
- seen.add(value);
402
- const record = value;
403
- yield record;
404
- for (const definition of Object.values(record)) {
405
- if (typeof definition !== "object" || definition == null) continue;
406
- const nestedContext = definition["@context"];
407
- if (nestedContext == null) continue;
408
- yield* getContextObjects(nestedContext, seen);
409
- }
410
- }
411
- }
412
- function isActivityStreamsAttachmentTerm(value) {
413
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
414
- }
415
- /** @internal */
416
- function isPreloadedContextAttachmentSafe(document) {
417
- if (typeof document !== "object" || document == null) return true;
418
- const context = document["@context"];
419
- for (const contextObject of getContextObjects(context)) {
420
- if (!Object.hasOwn(contextObject, "attachment")) continue;
421
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
422
- return false;
423
- }
424
- return true;
425
- }
426
- function getKnownSafeContextUrls() {
427
- const urls = /* @__PURE__ */ new Set();
428
- for (const [url, document] of Object.entries(preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
429
- 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 });
430
- return urls;
431
- }
432
- /**
433
- * Wraps scalar ActivityStreams attachment properties in arrays.
434
- */
435
- function wrapScalarAttachments(jsonLd, preserveSecured, depth = 0) {
436
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
437
- if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(jsonLd)) return jsonLd;
438
- if (Array.isArray(jsonLd)) {
439
- let normalized = null;
440
- for (let i = 0; i < jsonLd.length; i++) {
441
- const item = jsonLd[i];
442
- const next = wrapScalarAttachments(item, preserveSecured, depth + 1);
443
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
444
- if (normalized != null) normalized[i] = next;
445
- }
446
- return normalized ?? jsonLd;
447
- }
448
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
449
- const record = jsonLd;
450
- const keys = Object.keys(record);
451
- let normalized = null;
452
- for (let i = 0; i < keys.length; i++) {
453
- const key = keys[i];
454
- const value = record[key];
455
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, preserveSecured, depth + 1);
456
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
457
- if (normalized == null && output !== value) {
458
- const cloned = Object.create(null);
459
- for (let j = 0; j < i; j++) {
460
- const previousKey = keys[j];
461
- cloned[previousKey] = record[previousKey];
462
- }
463
- normalized = cloned;
464
- }
465
- if (normalized != null) normalized[key] = output;
466
- }
467
- return normalized ?? jsonLd;
468
- }
469
- function hasNestedContext(value, depth = 0) {
470
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
471
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
472
- if (typeof value !== "object" || value == null) return false;
473
- const record = value;
474
- for (const key of Object.keys(record)) {
475
- if (key === "@context") return true;
476
- if (key === "@value" && isJsonLdValueObject(value)) continue;
477
- if (hasNestedContext(record[key], depth + 1)) return true;
478
- }
479
- return false;
480
- }
481
- function exceedsTraversalDepth(value, depth = 0) {
482
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
483
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
484
- if (typeof value !== "object" || value == null) return false;
485
- const record = value;
486
- for (const key of Object.keys(record)) {
487
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
488
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
489
- }
490
- return false;
491
- }
492
- function hasKnownSafeContext(jsonLd) {
493
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
494
- const record = jsonLd;
495
- if (!Object.hasOwn(record, "@context")) return false;
496
- const context = record["@context"];
497
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
498
- if (entries == null || entries.length < 1) return false;
499
- let hasActivityStreamsContext = false;
500
- for (const entry of entries) {
501
- if (typeof entry !== "string") return false;
502
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
503
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
504
- }
505
- if (!hasActivityStreamsContext) return false;
506
- for (const key of Object.keys(record)) {
507
- if (key === "@context") continue;
508
- if (hasNestedContext(record[key])) return false;
509
- }
510
- return true;
511
- }
512
- function getLogSafeJsonLdMetadata(jsonLd) {
513
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
514
- const record = jsonLd;
515
- const context = record["@context"];
516
- return {
517
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
518
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
519
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
520
- };
521
- }
522
- /**
523
- * Ensures ActivityStreams attachment properties are represented as arrays
524
- * when doing so preserves the JSON-LD semantics.
525
- *
526
- * JSON-LD compaction collapses single-item arrays into scalar values by
527
- * default. Some ActivityPub implementations, Pixelfed among them, parse
528
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
529
- * otherwise valid objects whose single attachment is emitted as a scalar.
530
- *
531
- * When no `contextLoader` is supplied, the helper falls back to a restricted
532
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
533
- * every other URL without network access. Documents with custom, inline, or
534
- * otherwise uncached contexts should pass a real `contextLoader` if they need
535
- * the semantic-preservation check to succeed; otherwise canonicalization
536
- * failures leave the original document unchanged.
537
- */
538
- async function normalizeAttachmentArrays(jsonLd, contextLoader, options = {}) {
539
- const normalized = wrapScalarAttachments(jsonLd, options.preserveNestedSecuredDocuments ?? false);
540
- if (normalized === jsonLd) return jsonLd;
541
- if (exceedsTraversalDepth(jsonLd)) {
542
- logger$3.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
543
- return jsonLd;
544
- }
545
- if (hasKnownSafeContext(jsonLd)) return normalized;
546
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
547
- try {
548
- const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
549
- format: "application/n-quads",
550
- documentLoader: loader
551
- }), jsonld.canonize(normalized, {
552
- format: "application/n-quads",
553
- documentLoader: loader
554
- })]);
555
- if (before === after) return normalized;
556
- 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));
557
- } catch (error) {
558
- logger$3.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
559
- }
560
- return jsonLd;
561
- }
562
- /**
563
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
564
- * to locally generated outgoing activities before they are signed, enqueued,
565
- * or sent.
566
- */
567
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, options = {}) {
568
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader, options);
569
- return await normalizeAttachmentArrays(jsonLd, contextLoader, options);
570
- }
571
- //#endregion
572
- //#region src/federation/metrics.ts
573
- var FederationMetrics = class {
574
- deliverySent;
575
- deliveryPermanentFailure;
576
- signatureVerificationFailure;
577
- signatureVerificationDuration;
578
- signatureKeyFetchDuration;
579
- deliveryDuration;
580
- inboxProcessingDuration;
581
- httpServerRequestCount;
582
- httpServerRequestDuration;
583
- queueTaskEnqueued;
584
- queueTaskStarted;
585
- queueTaskCompleted;
586
- queueTaskFailed;
587
- queueTaskDuration;
588
- queueTaskInFlight;
589
- queueDepth;
590
- fanoutRecipients;
591
- inboxActivity;
592
- outboxActivity;
593
- circuitBreakerStateChange;
594
- keyLookup;
595
- keyLookupDuration;
596
- documentFetch;
597
- documentFetchDuration;
598
- documentCache;
599
- webFingerHandle;
600
- webFingerHandleDuration;
601
- collectionRequest;
602
- collectionDispatchDuration;
603
- collectionPageItems;
604
- collectionTotalItems;
605
- constructor(meterProvider) {
606
- const meter = meterProvider.getMeter(name, version);
607
- this.deliverySent = meter.createCounter("activitypub.delivery.sent", {
608
- description: "ActivityPub delivery attempts.",
609
- unit: "{attempt}"
306
+ //#region src/federation/metrics.ts
307
+ var FederationMetrics = class {
308
+ deliverySent;
309
+ deliveryPermanentFailure;
310
+ signatureVerificationFailure;
311
+ signatureVerificationDuration;
312
+ signatureKeyFetchDuration;
313
+ deliveryDuration;
314
+ inboxProcessingDuration;
315
+ httpServerRequestCount;
316
+ httpServerRequestDuration;
317
+ queueTaskEnqueued;
318
+ queueTaskStarted;
319
+ queueTaskCompleted;
320
+ queueTaskFailed;
321
+ queueTaskDuration;
322
+ queueTaskInFlight;
323
+ queueDepth;
324
+ fanoutRecipients;
325
+ inboxActivity;
326
+ outboxActivity;
327
+ circuitBreakerStateChange;
328
+ keyLookup;
329
+ keyLookupDuration;
330
+ documentFetch;
331
+ documentFetchDuration;
332
+ documentCache;
333
+ webFingerHandle;
334
+ webFingerHandleDuration;
335
+ collectionRequest;
336
+ collectionDispatchDuration;
337
+ collectionPageItems;
338
+ collectionTotalItems;
339
+ constructor(meterProvider) {
340
+ const meter = meterProvider.getMeter(name, version);
341
+ this.deliverySent = meter.createCounter("activitypub.delivery.sent", {
342
+ description: "ActivityPub delivery attempts.",
343
+ unit: "{attempt}"
610
344
  });
611
345
  this.deliveryPermanentFailure = meter.createCounter("activitypub.delivery.permanent_failure", {
612
346
  description: "ActivityPub deliveries abandoned as permanent failures.",
@@ -1379,99 +1113,6 @@ function getDurationMs(start) {
1379
1113
  return Math.max(0, performance.now() - start);
1380
1114
  }
1381
1115
  //#endregion
1382
- //#region src/sig/portable-key-id.ts
1383
- const COMPATIBLE_KEY_ID_PATH_PATTERN = /^\/\.well-known\/apgateway\/did(?::|%3A)/i;
1384
- /**
1385
- * Checks whether the URL is an `ap:` or `ap+ef61:` URI.
1386
- * @internal
1387
- */
1388
- function isPortableUri(url) {
1389
- return url.protocol === "ap:" || url.protocol === "ap+ef61:";
1390
- }
1391
- /**
1392
- * Checks whether an activity is performed by an FEP-ef61 portable actor,
1393
- * i.e., any of its actors has an `ap:` or `ap+ef61:` ID.
1394
- * @internal
1395
- */
1396
- function hasPortableActor(activity) {
1397
- return activity.actorIds.some(isPortableUri);
1398
- }
1399
- /**
1400
- * Checks whether a key ID looks like an [FEP-ef61] compatible identifier,
1401
- * i.e., an HTTP(S) URL under a gateway's `/.well-known/apgateway/did:` path.
1402
- * Such a key ID names a key that a gateway holds for a portable actor, so it
1403
- * is resolved only as a gateway key, and never cached in a key cache.
1404
- *
1405
- * [FEP-ef61]: https://w3id.org/fep/ef61
1406
- * @internal
1407
- */
1408
- function isCompatibleKeyId(keyId) {
1409
- return (keyId.protocol === "http:" || keyId.protocol === "https:") && COMPATIBLE_KEY_ID_PATH_PATTERN.test(keyId.pathname);
1410
- }
1411
- /**
1412
- * Gets the canonical portable ID of an actor ID that is either an `ap:` or
1413
- * `ap+ef61:` URI or a compatible identifier.
1414
- * @returns The canonical portable ID, or `null` if the ID is neither, or is
1415
- * malformed.
1416
- * @internal
1417
- */
1418
- function getCanonicalPortableId(id) {
1419
- try {
1420
- if (isPortableUri(id)) return canonicalizePortableUri(formatIri(id));
1421
- const portable = fromCompatibleEf61Id(id);
1422
- if (portable == null) return null;
1423
- return canonicalizePortableUri(formatIri(portable));
1424
- } catch (error) {
1425
- if (error instanceof TypeError) return null;
1426
- throw error;
1427
- }
1428
- }
1429
- /**
1430
- * Builds the base of the key IDs of a gateway's keys for a portable actor:
1431
- * the actor's compatible identifier on the gateway.
1432
- * @param actorId The portable actor's ID, either an `ap:` or `ap+ef61:` URI
1433
- * or a compatible identifier. It must not have a fragment.
1434
- * @param gateway The gateway's origin, e.g., `https://example.com`.
1435
- * @returns The compatible identifier without query and fragment.
1436
- * @throws {TypeError} If the actor ID is not a portable ID, or has
1437
- * a fragment.
1438
- * @internal
1439
- */
1440
- function getGatewayKeyBase(actorId, gateway) {
1441
- let portable;
1442
- if (isPortableUri(actorId)) portable = actorId;
1443
- else try {
1444
- portable = fromCompatibleEf61Id(actorId);
1445
- } catch (error) {
1446
- if (!(error instanceof TypeError)) throw error;
1447
- portable = null;
1448
- }
1449
- if (portable == null) throw new TypeError(`The portable actor ID ${actorId.href} must be an ap: or ap+ef61: URI, or an FEP-ef61 compatible identifier.`);
1450
- if (portable.hash !== "") throw new TypeError(`The portable actor ID ${actorId.href} must not have a fragment.`);
1451
- const base = toCompatibleEf61Id(portable, gateway);
1452
- base.search = "";
1453
- base.hash = "";
1454
- return base;
1455
- }
1456
- /**
1457
- * Tells whether a parsed document at a compatible key ID is a portable actor,
1458
- * which makes the key a gateway key that only
1459
- * {@link verifyPortableGatewayKeyDocument} can vouch for.
1460
- * @internal
1461
- */
1462
- function isPortableActorDocument(object) {
1463
- return isActor(object) && object.id != null && isPortableUri(object.id);
1464
- }
1465
- /**
1466
- * Compares two public keys by their key material.
1467
- * @internal
1468
- */
1469
- async function isSamePublicKey(a, b) {
1470
- if (a.algorithm.name !== b.algorithm.name) return false;
1471
- const [x, y] = await Promise.all([crypto.subtle.exportKey("jwk", a), crypto.subtle.exportKey("jwk", b)]);
1472
- 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;
1473
- }
1474
- //#endregion
1475
1116
  //#region src/sig/key.ts
1476
1117
  /**
1477
1118
  * Checks if the given key is valid and supported. No-op if the key is valid,
@@ -1572,6 +1213,10 @@ async function fetchActorDocument(actorId, options = {}) {
1572
1213
  "sig",
1573
1214
  "key"
1574
1215
  ]);
1216
+ if (isPortableId(actorId)) {
1217
+ logger.debug("The actor {actorId} is a portable actor, which is not authenticated by the web origin that serves it.", { actorId: actorId.href });
1218
+ return null;
1219
+ }
1575
1220
  const documentLoader = options.documentLoader ?? getDocumentLoader();
1576
1221
  const contextLoader = options.contextLoader ?? getDocumentLoader();
1577
1222
  const { tracerProvider } = options;
@@ -1605,6 +1250,13 @@ async function fetchActorDocument(actorId, options = {}) {
1605
1250
  return null;
1606
1251
  }
1607
1252
  if (!isActor(object)) return null;
1253
+ if (object.id != null && isPortableId(object.id)) {
1254
+ logger.debug("The document served at {documentUrl} claims to be the portable actor {actorId}, which is not authenticated by the web origin that serves it.", {
1255
+ documentUrl: documentUrl.href,
1256
+ actorId: object.id?.href
1257
+ });
1258
+ return null;
1259
+ }
1608
1260
  if (object.id == null || object.id.origin !== documentUrl.origin) {
1609
1261
  logger.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as that actor's document.", {
1610
1262
  documentUrl: documentUrl.href,
@@ -1748,992 +1400,1409 @@ async function fetchKeyDetailed(keyId, cls, options = {}) {
1748
1400
  logger.debug("Entry {keyId} found in cache with preserved fetch failure details.", { keyId });
1749
1401
  return {
1750
1402
  key: null,
1751
- cached: true,
1752
- fetchError
1403
+ cached: true,
1404
+ fetchError
1405
+ };
1406
+ }
1407
+ logger.debug("Entry {keyId} found in cache, but no fetch failure details are available.", { keyId });
1408
+ return {
1409
+ key: null,
1410
+ cached: true
1411
+ };
1412
+ }, async (error, cacheKey, keyId, keyCache, logger) => {
1413
+ logger.debug("Failed to fetch key {keyId}.", {
1414
+ keyId,
1415
+ error
1416
+ });
1417
+ await keyCache?.set(cacheKey, null);
1418
+ if (error instanceof FetchError && error.response != null) {
1419
+ const fetchError = {
1420
+ status: error.response.status,
1421
+ response: error.response.clone()
1422
+ };
1423
+ await keyCache?.setFetchError?.(cacheKey, fetchError);
1424
+ return {
1425
+ key: null,
1426
+ cached: false,
1427
+ fetchError
1428
+ };
1429
+ }
1430
+ const fetchError = { error: error instanceof Error ? error : new Error(String(error)) };
1431
+ await keyCache?.setFetchError?.(cacheKey, fetchError);
1432
+ return {
1433
+ key: null,
1434
+ cached: false,
1435
+ fetchError
1436
+ };
1437
+ });
1438
+ });
1439
+ }
1440
+ async function getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger) {
1441
+ if (keyCache == null) return null;
1442
+ const cachedKey = await keyCache.get(cacheKey);
1443
+ const hit = checkCachedKeyHit(cachedKey, keyId, cls, logger);
1444
+ if (hit != null) return hit;
1445
+ if (cachedKey === null) {
1446
+ logger.debug("Entry {keyId} found in cache, but it is unavailable.", { keyId });
1447
+ return {
1448
+ key: null,
1449
+ cached: true
1450
+ };
1451
+ }
1452
+ return null;
1453
+ }
1454
+ function checkCachedKeyHit(cachedKey, keyId, cls, logger) {
1455
+ if (cachedKey instanceof cls && cachedKey.publicKey != null) {
1456
+ logger.debug("Key {keyId} found in cache.", { keyId });
1457
+ return {
1458
+ key: cachedKey,
1459
+ cached: true
1460
+ };
1461
+ }
1462
+ return null;
1463
+ }
1464
+ async function clearFetchErrorMetadata(keyId, keyCache) {
1465
+ await keyCache?.setFetchError?.(keyId, null);
1466
+ }
1467
+ /**
1468
+ * Returns the identifier a fragment-bearing DID URL is a fragment of, or
1469
+ * `null` if the URL is not a DID URL. `did:web:example.com#key` is thereby
1470
+ * traced back to `did:web:example.com`, the DID that resolving the key went
1471
+ * through in the first place.
1472
+ */
1473
+ function stripFragment(keyId) {
1474
+ if (keyId.protocol !== "did:") return null;
1475
+ const did = new URL(keyId.href);
1476
+ did.hash = "";
1477
+ return did;
1478
+ }
1479
+ function isDidKeyUrl(keyId) {
1480
+ return keyId.protocol === "did:" && keyId.pathname.startsWith("key:");
1481
+ }
1482
+ async function doRawKeysMatch(left, right) {
1483
+ const [leftRaw, rightRaw] = await Promise.all([crypto.subtle.exportKey("raw", left), crypto.subtle.exportKey("raw", right)]);
1484
+ if (leftRaw.byteLength !== rightRaw.byteLength) return false;
1485
+ const leftBytes = new Uint8Array(leftRaw);
1486
+ const rightBytes = new Uint8Array(rightRaw);
1487
+ return leftBytes.every((byte, index) => byte === rightBytes[index]);
1488
+ }
1489
+ async function isCachedDidKeyValid(key, verificationMethod) {
1490
+ try {
1491
+ return key.id?.href === verificationMethod.id.href && key.controllerId?.href === verificationMethod.controller.href && await doRawKeysMatch(key.publicKey, verificationMethod.publicKey);
1492
+ } catch {
1493
+ return false;
1494
+ }
1495
+ }
1496
+ async function resolveDidKey(cacheKey, cls, keyCache, logger) {
1497
+ if (!isDidKeyUrl(cacheKey)) return null;
1498
+ const keyId = cacheKey.href;
1499
+ if (!(cls === Multikey)) {
1500
+ logger.debug("Failed to resolve did:key {keyId}; did:key verification methods are only supported as Multikey values.", { keyId });
1501
+ return {
1502
+ key: null,
1503
+ cached: false
1504
+ };
1505
+ }
1506
+ let verificationMethod;
1507
+ try {
1508
+ verificationMethod = await parseDidKeyVerificationMethod(cacheKey);
1509
+ } catch (error) {
1510
+ logger.debug("Failed to resolve did:key verification method {keyId}: {error}", {
1511
+ keyId,
1512
+ error
1513
+ });
1514
+ return {
1515
+ key: null,
1516
+ cached: false
1517
+ };
1518
+ }
1519
+ const hit = checkCachedKeyHit(await keyCache?.get(cacheKey), keyId, cls, logger);
1520
+ if (hit?.key instanceof Multikey && await isCachedDidKeyValid(hit.key, verificationMethod)) return hit;
1521
+ const key = new Multikey({
1522
+ id: verificationMethod.id,
1523
+ controller: verificationMethod.controller,
1524
+ publicKey: verificationMethod.publicKey
1525
+ });
1526
+ await keyCache?.set(cacheKey, key);
1527
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1528
+ logger.debug("Resolved did:key verification method {keyId}.", { keyId });
1529
+ return {
1530
+ key,
1531
+ cached: false
1532
+ };
1533
+ }
1534
+ async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, { documentLoader, contextLoader, keyCache, tracerProvider, keyIdBoundByCaller, portableGatewayKeyResolver }, logger) {
1535
+ let object;
1536
+ try {
1537
+ object = await Object$1.fromJsonLd(document, {
1538
+ documentLoader,
1539
+ contextLoader,
1540
+ tracerProvider
1541
+ });
1542
+ } catch (e) {
1543
+ if (!(e instanceof TypeError)) throw e;
1544
+ try {
1545
+ object = await cls.fromJsonLd(document, {
1546
+ documentLoader,
1547
+ contextLoader,
1548
+ tracerProvider
1549
+ });
1550
+ } catch (e) {
1551
+ if (e instanceof TypeError) {
1552
+ logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
1553
+ await keyCache?.set(cacheKey, null);
1554
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1555
+ return {
1556
+ key: null,
1557
+ cached: false
1753
1558
  };
1754
1559
  }
1755
- logger.debug("Entry {keyId} found in cache, but no fetch failure details are available.", { keyId });
1560
+ throw e;
1561
+ }
1562
+ }
1563
+ if (isCompatibleKeyId(cacheKey) && isPortableActorDocument(object)) {
1564
+ if (portableGatewayKeyResolver == null || cls !== CryptographicKey) {
1565
+ logger.debug("Failed to verify; key {keyId} is a gateway key of the portable actor {actorId}, which is only accepted for HTTP Signatures.", {
1566
+ keyId,
1567
+ actorId: object.id?.href
1568
+ });
1756
1569
  return {
1757
1570
  key: null,
1758
- cached: true
1571
+ cached: false
1759
1572
  };
1760
- }, async (error, cacheKey, keyId, keyCache, logger) => {
1761
- logger.debug("Failed to fetch key {keyId}.", {
1573
+ }
1574
+ const resolution = await portableGatewayKeyResolver(document, object, cacheKey);
1575
+ if (resolution.type !== "verified") {
1576
+ logger.debug("Failed to verify; the portable actor {actorId} does not vouch for its gateway key {keyId}.", {
1762
1577
  keyId,
1763
- error
1578
+ actorId: object.id?.href
1579
+ });
1580
+ return {
1581
+ key: null,
1582
+ cached: false
1583
+ };
1584
+ }
1585
+ return {
1586
+ key: resolution.key,
1587
+ cached: false
1588
+ };
1589
+ }
1590
+ let key = null;
1591
+ let ownerDocument = null;
1592
+ if (object instanceof cls && (object.id == null || object.id.href === keyId)) key = object.id == null ? object.clone({ id: cacheKey }) : object;
1593
+ else if (isActor(object)) {
1594
+ if (object.id == null || isPortableId(object.id) || object.id.origin !== documentUrl.origin) {
1595
+ logger.debug("Failed to verify; the document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin.", {
1596
+ keyId,
1597
+ documentUrl: documentUrl.href,
1598
+ actorId: object.id?.href
1764
1599
  });
1765
1600
  await keyCache?.set(cacheKey, null);
1766
- if (error instanceof FetchError && error.response != null) {
1767
- const fetchError = {
1768
- status: error.response.status,
1769
- response: error.response.clone()
1770
- };
1771
- await keyCache?.setFetchError?.(cacheKey, fetchError);
1772
- return {
1773
- key: null,
1774
- cached: false,
1775
- fetchError
1776
- };
1777
- }
1778
- const fetchError = { error: error instanceof Error ? error : new Error(String(error)) };
1779
- await keyCache?.setFetchError?.(cacheKey, fetchError);
1780
1601
  return {
1781
1602
  key: null,
1782
- cached: false,
1783
- fetchError
1603
+ cached: false
1784
1604
  };
1605
+ }
1606
+ ownerDocument = object;
1607
+ const keys = cls === CryptographicKey ? object.getPublicKeys({
1608
+ documentLoader,
1609
+ contextLoader,
1610
+ suppressError: true,
1611
+ tracerProvider
1612
+ }) : object.getAssertionMethods({
1613
+ documentLoader,
1614
+ contextLoader,
1615
+ suppressError: true,
1616
+ tracerProvider
1785
1617
  });
1786
- });
1787
- }
1788
- async function getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger) {
1789
- if (keyCache == null) return null;
1790
- const cachedKey = await keyCache.get(cacheKey);
1791
- const hit = checkCachedKeyHit(cachedKey, keyId, cls, logger);
1792
- if (hit != null) return hit;
1793
- if (cachedKey === null) {
1794
- logger.debug("Entry {keyId} found in cache, but it is unavailable.", { keyId });
1618
+ let length = 0;
1619
+ let lastKey = null;
1620
+ try {
1621
+ for await (const k of keys) {
1622
+ length++;
1623
+ lastKey = k;
1624
+ if (k.id?.href === keyId) {
1625
+ key = k;
1626
+ break;
1627
+ }
1628
+ }
1629
+ } catch (e) {
1630
+ if (!(e instanceof TypeError)) throw e;
1631
+ logger.debug("Failed to verify; a malformed key was encountered while iterating the keys of {keyId}; treating it as a missing key: {error}", {
1632
+ keyId,
1633
+ error: e
1634
+ });
1635
+ }
1636
+ const keyIdUrl = new URL(keyId);
1637
+ if (key == null && keyIdUrl.hash === "" && length === 1) key = lastKey;
1638
+ if (key == null) {
1639
+ logger.debug("Failed to verify; object {keyId} returned an {actorType}, but has no key matching {keyId}.", {
1640
+ keyId,
1641
+ actorType: object.constructor.name
1642
+ });
1643
+ await keyCache?.set(cacheKey, null);
1644
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1645
+ return {
1646
+ key: null,
1647
+ cached: false
1648
+ };
1649
+ }
1650
+ } else {
1651
+ logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
1652
+ await keyCache?.set(cacheKey, null);
1653
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1795
1654
  return {
1796
1655
  key: null,
1797
- cached: true
1656
+ cached: false
1798
1657
  };
1799
1658
  }
1800
- return null;
1801
- }
1802
- function checkCachedKeyHit(cachedKey, keyId, cls, logger) {
1803
- if (cachedKey instanceof cls && cachedKey.publicKey != null) {
1804
- logger.debug("Key {keyId} found in cache.", { keyId });
1659
+ if (key.publicKey == null) {
1660
+ logger.debug("Failed to verify; key {keyId} has no publicKeyPem field.", { keyId });
1661
+ await keyCache?.set(cacheKey, null);
1662
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1805
1663
  return {
1806
- key: cachedKey,
1807
- cached: true
1664
+ key: null,
1665
+ cached: false
1808
1666
  };
1809
1667
  }
1810
- return null;
1811
- }
1812
- async function clearFetchErrorMetadata(keyId, keyCache) {
1813
- await keyCache?.setFetchError?.(keyId, null);
1668
+ const claimedOwnerId = key instanceof CryptographicKey ? key.ownerId : key.controllerId;
1669
+ if (!(keyIdBoundByCaller && claimedOwnerId != null && claimedOwnerId.href === stripFragment(cacheKey)?.href)) {
1670
+ if (claimedOwnerId != null && isPortableId(claimedOwnerId)) {
1671
+ logger.debug("Failed to verify; key {keyId} claims the portable actor {claimedOwnerId} as its owner, but is not its gateway key.", {
1672
+ keyId,
1673
+ claimedOwnerId: claimedOwnerId.href
1674
+ });
1675
+ await keyCache?.set(cacheKey, null);
1676
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1677
+ return {
1678
+ key: null,
1679
+ cached: false
1680
+ };
1681
+ }
1682
+ if (ownerDocument != null && claimedOwnerId == null) key = key instanceof CryptographicKey ? key.clone({ owner: ownerDocument.id }) : key.clone({ controller: ownerDocument.id });
1683
+ else if (claimedOwnerId != null && claimedOwnerId.href !== ownerDocument?.id?.href) {
1684
+ if (await verifyKeyOwnership(key, {
1685
+ documentLoader,
1686
+ contextLoader,
1687
+ tracerProvider
1688
+ }) == null) {
1689
+ logger.debug("Failed to verify; the owner {claimedOwnerId} that key {keyId} claims does not list the key as its own.", {
1690
+ keyId,
1691
+ claimedOwnerId: claimedOwnerId.href
1692
+ });
1693
+ await keyCache?.set(cacheKey, null);
1694
+ return {
1695
+ key: null,
1696
+ cached: false
1697
+ };
1698
+ }
1699
+ }
1700
+ }
1701
+ if (keyCache != null) {
1702
+ await keyCache.set(cacheKey, key);
1703
+ logger.debug("Key {keyId} cached.", { keyId });
1704
+ }
1705
+ await clearFetchErrorMetadata(cacheKey, keyCache);
1706
+ return {
1707
+ key,
1708
+ cached: false
1709
+ };
1814
1710
  }
1815
1711
  /**
1816
- * Returns the identifier a fragment-bearing DID URL is a fragment of, or
1817
- * `null` if the URL is not a DID URL. `did:web:example.com#key` is thereby
1818
- * traced back to `did:web:example.com`, the DID that resolving the key went
1819
- * through in the first place.
1712
+ * Tells whether a key claims a portable actor as its owner. Such a key can
1713
+ * only be a gateway key, which is never cached, so a cached one was cached
1714
+ * by an older version that trusted web origins, and is fetched again.
1820
1715
  */
1821
- function stripFragment(keyId) {
1822
- if (keyId.protocol !== "did:") return null;
1823
- const did = new URL(keyId.href);
1824
- did.hash = "";
1825
- return did;
1826
- }
1827
- function isDidKeyUrl(keyId) {
1828
- return keyId.protocol === "did:" && keyId.pathname.startsWith("key:");
1829
- }
1830
- async function doRawKeysMatch(left, right) {
1831
- const [leftRaw, rightRaw] = await Promise.all([crypto.subtle.exportKey("raw", left), crypto.subtle.exportKey("raw", right)]);
1832
- if (leftRaw.byteLength !== rightRaw.byteLength) return false;
1833
- const leftBytes = new Uint8Array(leftRaw);
1834
- const rightBytes = new Uint8Array(rightRaw);
1835
- return leftBytes.every((byte, index) => byte === rightBytes[index]);
1716
+ function claimsPortableOwner(key) {
1717
+ const ownerId = key instanceof CryptographicKey ? key.ownerId : key?.controllerId;
1718
+ return ownerId != null && isPortableId(ownerId);
1836
1719
  }
1837
- async function isCachedDidKeyValid(key, verificationMethod) {
1720
+ async function fetchKeyWithResult(cacheKey, cls, options, onCachedUnavailable, onFetchError) {
1721
+ const start = performance.now();
1722
+ let outcome = { result: "error" };
1838
1723
  try {
1839
- return key.id?.href === verificationMethod.id.href && key.controllerId?.href === verificationMethod.controller.href && await doRawKeysMatch(key.publicKey, verificationMethod.publicKey);
1840
- } catch {
1841
- return false;
1842
- }
1843
- }
1844
- async function resolveDidKey(cacheKey, cls, keyCache, logger) {
1845
- if (!isDidKeyUrl(cacheKey)) return null;
1846
- const keyId = cacheKey.href;
1847
- if (!(cls === Multikey)) {
1848
- logger.debug("Failed to resolve did:key {keyId}; did:key verification methods are only supported as Multikey values.", { keyId });
1724
+ const logger = getLogger([
1725
+ "fedify",
1726
+ "sig",
1727
+ "key"
1728
+ ]);
1729
+ const keyId = cacheKey.href;
1730
+ if (isCompatibleKeyId(cacheKey)) options = {
1731
+ ...options,
1732
+ keyCache: void 0
1733
+ };
1734
+ const keyCache = options.keyCache;
1735
+ const didKey = await resolveDidKey(cacheKey, cls, keyCache, logger);
1736
+ if (didKey != null) {
1737
+ outcome = { result: didKey.key == null ? "invalid" : didKey.cached ? "hit" : "fetched" };
1738
+ return didKey;
1739
+ }
1740
+ const cached = await getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger);
1741
+ if (cached?.key === null && cached.cached) {
1742
+ const cachedUnavailable = await onCachedUnavailable(cacheKey, keyId, keyCache, logger);
1743
+ outcome = { result: "hit" };
1744
+ return cachedUnavailable;
1745
+ }
1746
+ if (cached != null && !claimsPortableOwner(cached.key)) {
1747
+ outcome = { result: "hit" };
1748
+ return cached;
1749
+ }
1750
+ logger.debug("Fetching key {keyId} to verify signature...", { keyId });
1751
+ let document;
1752
+ let documentUrl = cacheKey;
1753
+ try {
1754
+ const remoteDocument = await (options.documentLoader ?? getDocumentLoader())(keyId);
1755
+ document = remoteDocument.document;
1756
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", cacheKey);
1757
+ } catch (error) {
1758
+ const classified = classifyFetchError(error);
1759
+ const errored = await onFetchError(error, cacheKey, keyId, keyCache, logger);
1760
+ outcome = classified;
1761
+ return errored;
1762
+ }
1763
+ const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, options, logger);
1764
+ outcome = { result: resolved.key != null ? "fetched" : "invalid" };
1765
+ return resolved;
1766
+ } finally {
1767
+ recordKeyLookup(options.meterProvider, {
1768
+ durationMs: getDurationMs(start),
1769
+ result: outcome.result,
1770
+ remoteUrl: cacheKey,
1771
+ cacheEnabled: options.keyCache != null,
1772
+ statusCode: outcome.statusCode
1773
+ });
1774
+ }
1775
+ }
1776
+ async function fetchKeyInternal(keyId, cls, options = {}) {
1777
+ return await fetchKeyWithResult(typeof keyId === "string" ? new URL(keyId) : keyId, cls, options, (_cacheKey, _keyId, _keyCache, _logger) => {
1849
1778
  return {
1850
1779
  key: null,
1851
- cached: false
1780
+ cached: true
1852
1781
  };
1853
- }
1854
- let verificationMethod;
1855
- try {
1856
- verificationMethod = await parseDidKeyVerificationMethod(cacheKey);
1857
- } catch (error) {
1858
- logger.debug("Failed to resolve did:key verification method {keyId}: {error}", {
1782
+ }, async (error, cacheKey, keyId, keyCache, logger) => {
1783
+ logger.debug("Failed to fetch key {keyId}.", {
1859
1784
  keyId,
1860
1785
  error
1861
1786
  });
1787
+ await keyCache?.set(cacheKey, null);
1788
+ if (error instanceof FetchError && error.response != null) await keyCache?.setFetchError?.(cacheKey, {
1789
+ status: error.response.status,
1790
+ response: error.response.clone()
1791
+ });
1792
+ else await keyCache?.setFetchError?.(cacheKey, { error: error instanceof Error ? error : new Error(String(error)) });
1862
1793
  return {
1863
1794
  key: null,
1864
1795
  cached: false
1865
1796
  };
1797
+ });
1798
+ }
1799
+ //#endregion
1800
+ //#region src/sig/ld.ts
1801
+ const logger$4 = getLogger([
1802
+ "fedify",
1803
+ "sig",
1804
+ "ld"
1805
+ ]);
1806
+ const localContext = [
1807
+ "https://w3id.org/identity/v1",
1808
+ "https://www.w3.org/ns/activitystreams",
1809
+ "https://w3id.org/security/v1",
1810
+ "https://w3id.org/security/data-integrity/v1"
1811
+ ];
1812
+ const localContextUrls = new Set(localContext);
1813
+ const builtInContextLoader = getDocumentLoader();
1814
+ const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
1815
+ "@graph",
1816
+ "@included",
1817
+ "@reverse"
1818
+ ]);
1819
+ /** @internal */
1820
+ var UnsafeJsonLdError = class extends TypeError {
1821
+ keyword;
1822
+ constructor(keyword) {
1823
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
1824
+ this.keyword = keyword;
1825
+ this.name = "UnsafeJsonLdError";
1866
1826
  }
1867
- const hit = checkCachedKeyHit(await keyCache?.get(cacheKey), keyId, cls, logger);
1868
- if (hit?.key instanceof Multikey && await isCachedDidKeyValid(hit.key, verificationMethod)) return hit;
1869
- const key = new Multikey({
1870
- id: verificationMethod.id,
1871
- controller: verificationMethod.controller,
1872
- publicKey: verificationMethod.publicKey
1827
+ };
1828
+ /** @internal */
1829
+ var InvalidContextReferenceError = class extends TypeError {
1830
+ reference;
1831
+ constructor(reference) {
1832
+ super(`Invalid JSON-LD context reference: ${reference}.`);
1833
+ this.reference = reference;
1834
+ this.name = "InvalidContextReferenceError";
1835
+ }
1836
+ };
1837
+ function createLoadingRemoteContextFailedError(reference, cause) {
1838
+ const message = cause instanceof Error ? cause.message : String(cause);
1839
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
1840
+ error.name = "jsonld.InvalidUrl";
1841
+ error.details = {
1842
+ code: "loading remote context failed",
1843
+ url: reference
1844
+ };
1845
+ error.cause = cause;
1846
+ return error;
1847
+ }
1848
+ /** @internal */
1849
+ function isClearlyMalformedContextReference(reference) {
1850
+ for (const char of reference) {
1851
+ const code = char.charCodeAt(0);
1852
+ if (code <= 32 || code === 127) return true;
1853
+ }
1854
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
1855
+ for (let i = 0; i < reference.length; i++) {
1856
+ if (reference[i] !== "%") continue;
1857
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
1858
+ i += 2;
1859
+ }
1860
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
1861
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
1862
+ }
1863
+ return false;
1864
+ }
1865
+ function cloneRemoteDocument(remoteDocument) {
1866
+ return structuredClone(remoteDocument);
1867
+ }
1868
+ function createMemoizedDocumentLoader(documentLoader) {
1869
+ const cache = /* @__PURE__ */ new Map();
1870
+ return async (url, options) => {
1871
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
1872
+ let remoteDocument = cache.get(cacheKey);
1873
+ if (remoteDocument == null) {
1874
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
1875
+ remoteDocument.catch(() => {
1876
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
1877
+ });
1878
+ cache.set(cacheKey, remoteDocument);
1879
+ }
1880
+ return cloneRemoteDocument(await remoteDocument);
1881
+ };
1882
+ }
1883
+ /** @internal */
1884
+ function wrapContextLoaderForJsonLd(contextLoader) {
1885
+ const loader = contextLoader ?? builtInContextLoader;
1886
+ return async (url, options) => {
1887
+ try {
1888
+ return await loader(url, options);
1889
+ } catch (error) {
1890
+ if (!isInvalidUrlTypeError(error)) throw error;
1891
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
1892
+ throw createLoadingRemoteContextFailedError(url, error);
1893
+ }
1894
+ };
1895
+ }
1896
+ /** @internal */
1897
+ function getNormalizationContextLoader(contextLoader) {
1898
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
1899
+ return createMemoizedDocumentLoader(async (url, options) => {
1900
+ if (URL.canParse(url)) {
1901
+ const normalizedUrl = new URL(url).href;
1902
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
1903
+ }
1904
+ return await loader(url, options);
1873
1905
  });
1874
- await keyCache?.set(cacheKey, key);
1875
- await clearFetchErrorMetadata(cacheKey, keyCache);
1876
- logger.debug("Resolved did:key verification method {keyId}.", { keyId });
1906
+ }
1907
+ /** @internal */
1908
+ async function compactJsonLd(jsonLd, contextLoader) {
1909
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
1910
+ const signature = hasLds ? jsonLd.signature : void 0;
1911
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
1912
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
1913
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
1914
+ const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
1915
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
1916
+ assertSafeJsonLd(compacted);
1917
+ return compacted;
1918
+ }
1919
+ function createInvalidRemoteContextError(reference) {
1920
+ 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}".`);
1921
+ error.name = "jsonld.InvalidUrl";
1922
+ error.details = {
1923
+ code: "invalid remote context",
1924
+ url: reference
1925
+ };
1926
+ return error;
1927
+ }
1928
+ function getRemoteContext(remoteDocument, reference) {
1929
+ const { contextUrl, documentUrl } = remoteDocument;
1930
+ let { document } = remoteDocument;
1931
+ if (typeof document === "string") document = JSON.parse(document);
1932
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
1933
+ let context = "@context" in document ? document["@context"] : {};
1934
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
1877
1935
  return {
1878
- key,
1879
- cached: false
1936
+ context,
1937
+ baseUrl: documentUrl ?? reference
1880
1938
  };
1881
1939
  }
1882
- async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, { documentLoader, contextLoader, keyCache, tracerProvider, keyIdBoundByCaller, portableGatewayKeyResolver }, logger) {
1883
- let object;
1884
- try {
1885
- object = await Object$1.fromJsonLd(document, {
1886
- documentLoader,
1887
- contextLoader,
1888
- tracerProvider
1889
- });
1890
- } catch (e) {
1891
- if (!(e instanceof TypeError)) throw e;
1892
- try {
1893
- object = await cls.fromJsonLd(document, {
1894
- documentLoader,
1895
- contextLoader,
1896
- tracerProvider
1897
- });
1898
- } catch (e) {
1899
- if (e instanceof TypeError) {
1900
- logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
1901
- await keyCache?.set(cacheKey, null);
1902
- await clearFetchErrorMetadata(cacheKey, keyCache);
1903
- return {
1904
- key: null,
1905
- cached: false
1906
- };
1940
+ function createGraphAliasContextState() {
1941
+ return {
1942
+ graphTerms: /* @__PURE__ */ new Set(),
1943
+ jsonTerms: /* @__PURE__ */ new Set(),
1944
+ propertyContexts: /* @__PURE__ */ new Map(),
1945
+ termTargets: /* @__PURE__ */ new Map()
1946
+ };
1947
+ }
1948
+ function cloneGraphAliasContextState(state) {
1949
+ return {
1950
+ graphTerms: new Set(state.graphTerms),
1951
+ jsonTerms: new Set(state.jsonTerms),
1952
+ propertyContexts: new Map(state.propertyContexts),
1953
+ termTargets: new Map(state.termTargets)
1954
+ };
1955
+ }
1956
+ function resolveContextTarget(target, state) {
1957
+ if (target === "@graph") return target;
1958
+ const mapped = state.termTargets.get(target);
1959
+ if (mapped == null) return target;
1960
+ return mapped;
1961
+ }
1962
+ function getDirectContextTarget(definition) {
1963
+ if (definition === null) return null;
1964
+ if (typeof definition === "string") return definition;
1965
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
1966
+ const id = definition["@id"];
1967
+ if (id === null) return null;
1968
+ if (typeof id === "string") return id;
1969
+ }
1970
+ }
1971
+ function isJsonTypedDefinition(definition) {
1972
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
1973
+ }
1974
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
1975
+ if (target === "@graph") return target;
1976
+ if (seen.has(target)) return target;
1977
+ seen.add(target);
1978
+ if (localTargets.has(target)) {
1979
+ const localTarget = localTargets.get(target);
1980
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
1981
+ }
1982
+ return resolveContextTarget(target, state);
1983
+ }
1984
+ function refreshGraphAliases(state) {
1985
+ state.graphTerms.clear();
1986
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
1987
+ }
1988
+ function normalizeContextReference(reference, baseUrl) {
1989
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
1990
+ return URL.canParse(reference) ? new URL(reference).href : reference;
1991
+ }
1992
+ /** @internal */
1993
+ function isInvalidUrlTypeError(error) {
1994
+ const code = error.code;
1995
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
1996
+ }
1997
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
1998
+ if (context === null) return createGraphAliasContextState();
1999
+ let nextState = cloneGraphAliasContextState(state);
2000
+ if (Array.isArray(context)) {
2001
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
2002
+ return nextState;
2003
+ }
2004
+ if (typeof context === "string") {
2005
+ const reference = normalizeContextReference(context, baseUrl);
2006
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
2007
+ if (processingContexts.has(cacheKey)) return nextState;
2008
+ processingContexts.add(cacheKey);
2009
+ try {
2010
+ let remoteContext = remoteContextCache.get(cacheKey);
2011
+ if (remoteContext == null) {
2012
+ remoteContext = (async () => {
2013
+ try {
2014
+ return getRemoteContext(await documentLoader(reference), reference);
2015
+ } catch (error) {
2016
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
2017
+ throw error;
2018
+ }
2019
+ })();
2020
+ remoteContextCache.set(cacheKey, remoteContext);
1907
2021
  }
1908
- throw e;
2022
+ const loadedRemoteContext = await remoteContext;
2023
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
2024
+ } finally {
2025
+ processingContexts.delete(cacheKey);
1909
2026
  }
1910
2027
  }
1911
- if (isCompatibleKeyId(cacheKey) && isPortableActorDocument(object)) {
1912
- if (portableGatewayKeyResolver == null || cls !== CryptographicKey) {
1913
- logger.debug("Failed to verify; key {keyId} is a gateway key of the portable actor {actorId}, which is only accepted for HTTP Signatures.", {
1914
- keyId,
1915
- actorId: object.id?.href
1916
- });
1917
- return {
1918
- key: null,
1919
- cached: false
1920
- };
2028
+ if (typeof context === "object" && context != null) {
2029
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
2030
+ const localTargets = /* @__PURE__ */ new Map();
2031
+ for (const [term, definition] of globalThis.Object.entries(context)) {
2032
+ if (term.startsWith("@")) continue;
2033
+ const target = getDirectContextTarget(definition);
2034
+ if (target == null) localTargets.set(term, null);
2035
+ else if (typeof target === "string") localTargets.set(term, target);
2036
+ else localTargets.delete(term);
1921
2037
  }
1922
- const resolution = await portableGatewayKeyResolver(document, object, cacheKey);
1923
- if (resolution.type !== "verified") {
1924
- logger.debug("Failed to verify; the portable actor {actorId} does not vouch for its gateway key {keyId}.", {
1925
- keyId,
1926
- actorId: object.id?.href
2038
+ for (const [term, definition] of globalThis.Object.entries(context)) {
2039
+ if (term.startsWith("@")) continue;
2040
+ if (localTargets.has(term)) {
2041
+ const directTarget = localTargets.get(term);
2042
+ if (directTarget == null) nextState.termTargets.set(term, null);
2043
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
2044
+ } else nextState.termTargets.delete(term);
2045
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
2046
+ context: definition["@context"],
2047
+ baseUrl
1927
2048
  });
1928
- return {
1929
- key: null,
1930
- cached: false
1931
- };
2049
+ else nextState.propertyContexts.delete(term);
2050
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
2051
+ else nextState.jsonTerms.delete(term);
1932
2052
  }
1933
- return {
1934
- key: resolution.key,
1935
- cached: false
1936
- };
2053
+ refreshGraphAliases(nextState);
1937
2054
  }
1938
- let key = null;
1939
- let ownerDocument = null;
1940
- if (object instanceof cls && (object.id == null || object.id.href === keyId)) key = object.id == null ? object.clone({ id: cacheKey }) : object;
1941
- else if (isActor(object)) {
1942
- if (object.id == null || object.id.origin !== documentUrl.origin) {
1943
- logger.debug("Failed to verify; the document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin.", {
1944
- keyId,
1945
- documentUrl: documentUrl.href,
1946
- actorId: object.id?.href
1947
- });
1948
- await keyCache?.set(cacheKey, null);
1949
- return {
1950
- key: null,
1951
- cached: false
1952
- };
1953
- }
1954
- ownerDocument = object;
1955
- const keys = cls === CryptographicKey ? object.getPublicKeys({
1956
- documentLoader,
1957
- contextLoader,
1958
- suppressError: true,
1959
- tracerProvider
1960
- }) : object.getAssertionMethods({
1961
- documentLoader,
1962
- contextLoader,
1963
- suppressError: true,
1964
- tracerProvider
1965
- });
1966
- let length = 0;
1967
- let lastKey = null;
1968
- try {
1969
- for await (const k of keys) {
1970
- length++;
1971
- lastKey = k;
1972
- if (k.id?.href === keyId) {
1973
- key = k;
1974
- break;
1975
- }
1976
- }
1977
- } catch (e) {
1978
- if (!(e instanceof TypeError)) throw e;
1979
- logger.debug("Failed to verify; a malformed key was encountered while iterating the keys of {keyId}; treating it as a missing key: {error}", {
1980
- keyId,
1981
- error: e
1982
- });
1983
- }
1984
- const keyIdUrl = new URL(keyId);
1985
- if (key == null && keyIdUrl.hash === "" && length === 1) key = lastKey;
1986
- if (key == null) {
1987
- logger.debug("Failed to verify; object {keyId} returned an {actorType}, but has no key matching {keyId}.", {
1988
- keyId,
1989
- actorType: object.constructor.name
1990
- });
1991
- await keyCache?.set(cacheKey, null);
1992
- await clearFetchErrorMetadata(cacheKey, keyCache);
1993
- return {
1994
- key: null,
1995
- cached: false
1996
- };
1997
- }
1998
- } else {
1999
- logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
2000
- await keyCache?.set(cacheKey, null);
2001
- await clearFetchErrorMetadata(cacheKey, keyCache);
2002
- return {
2003
- key: null,
2004
- cached: false
2005
- };
2055
+ return nextState;
2056
+ }
2057
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
2058
+ if (Array.isArray(jsonLd)) {
2059
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
2060
+ return;
2006
2061
  }
2007
- if (key.publicKey == null) {
2008
- logger.debug("Failed to verify; key {keyId} has no publicKeyPem field.", { keyId });
2009
- await keyCache?.set(cacheKey, null);
2010
- await clearFetchErrorMetadata(cacheKey, keyCache);
2011
- return {
2012
- key: null,
2013
- cached: false
2014
- };
2062
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
2063
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
2064
+ let state = inheritedState;
2065
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
2066
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
2067
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
2068
+ if (key === "@context") continue;
2069
+ if (jsonLiteralWrapper && key === "@value") continue;
2070
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
2071
+ if (state.jsonTerms.has(key)) continue;
2072
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
2015
2073
  }
2016
- const claimedOwnerId = key instanceof CryptographicKey ? key.ownerId : key.controllerId;
2017
- if (!(keyIdBoundByCaller && claimedOwnerId != null && claimedOwnerId.href === stripFragment(cacheKey)?.href)) {
2018
- if (ownerDocument != null && claimedOwnerId == null) key = key instanceof CryptographicKey ? key.clone({ owner: ownerDocument.id }) : key.clone({ controller: ownerDocument.id });
2019
- else if (claimedOwnerId != null && claimedOwnerId.href !== ownerDocument?.id?.href) {
2020
- if (await verifyKeyOwnership(key, {
2021
- documentLoader,
2022
- contextLoader,
2023
- tracerProvider
2024
- }) == null) {
2025
- logger.debug("Failed to verify; the owner {claimedOwnerId} that key {keyId} claims does not list the key as its own.", {
2026
- keyId,
2027
- claimedOwnerId: claimedOwnerId.href
2028
- });
2029
- await keyCache?.set(cacheKey, null);
2030
- return {
2031
- key: null,
2032
- cached: false
2033
- };
2074
+ }
2075
+ function isJsonLiteralWrapper(value) {
2076
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
2077
+ }
2078
+ /** @internal */
2079
+ function assertSafeJsonLd(jsonLd) {
2080
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
2081
+ else if (typeof jsonLd === "object" && jsonLd != null) {
2082
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
2083
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
2084
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
2085
+ if (jsonLiteralWrapper && key === "@value") continue;
2086
+ assertSafeJsonLd(value);
2087
+ }
2088
+ }
2089
+ }
2090
+ /**
2091
+ * Attaches a LD signature to the given JSON-LD document.
2092
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
2093
+ * modified.
2094
+ * @param signature The signature to attach.
2095
+ * @returns The JSON-LD document with the attached signature.
2096
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
2097
+ * @since 1.0.0
2098
+ */
2099
+ function attachSignature(jsonLd, signature) {
2100
+ if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
2101
+ return {
2102
+ ...jsonLd,
2103
+ signature
2104
+ };
2105
+ }
2106
+ /**
2107
+ * Creates a LD signature for the given JSON-LD document.
2108
+ * @param jsonLd The JSON-LD document to sign.
2109
+ * @param privateKey The private key to sign the document.
2110
+ * @param keyId The ID of the public key that corresponds to the private key.
2111
+ * @param options Additional options for creating the signature.
2112
+ * See also {@link CreateSignatureOptions}.
2113
+ * @return The created signature.
2114
+ * @throws {TypeError} If the private key is invalid or unsupported.
2115
+ * @since 1.0.0
2116
+ */
2117
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
2118
+ validateCryptoKey(privateKey, "private");
2119
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2120
+ const options = {
2121
+ "@context": "https://w3id.org/identity/v1",
2122
+ creator: keyId.href,
2123
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
2124
+ };
2125
+ const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
2126
+ const messageBytes = new TextEncoder().encode(message);
2127
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
2128
+ return {
2129
+ ...options,
2130
+ type: "RsaSignature2017",
2131
+ signatureValue: encodeBase64(signature)
2132
+ };
2133
+ }
2134
+ /**
2135
+ * Signs the given JSON-LD document with the private key and returns the signed
2136
+ * JSON-LD document.
2137
+ * @param jsonLd The JSON-LD document to sign.
2138
+ * @param privateKey The private key to sign the document.
2139
+ * @param keyId The key ID to use in the signature. It will be used by the
2140
+ * verifier to fetch the corresponding public key.
2141
+ * @param options Additional options for signing the document.
2142
+ * See also {@link SignJsonLdOptions}.
2143
+ * @returns The signed JSON-LD document.
2144
+ * @throws {TypeError} If the private key is invalid or unsupported.
2145
+ * @since 1.0.0
2146
+ */
2147
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
2148
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
2149
+ try {
2150
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
2151
+ if (span.isRecording()) {
2152
+ span.setAttribute("ld_signatures.type", signature.type);
2153
+ span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
2034
2154
  }
2155
+ return attachSignature(jsonLd, signature);
2156
+ } catch (error) {
2157
+ span.setStatus({
2158
+ code: SpanStatusCode.ERROR,
2159
+ message: String(error)
2160
+ });
2161
+ throw error;
2162
+ } finally {
2163
+ span.end();
2035
2164
  }
2036
- }
2037
- if (keyCache != null) {
2038
- await keyCache.set(cacheKey, key);
2039
- logger.debug("Key {keyId} cached.", { keyId });
2040
- }
2041
- await clearFetchErrorMetadata(cacheKey, keyCache);
2042
- return {
2043
- key,
2044
- cached: false
2165
+ });
2166
+ }
2167
+ /**
2168
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
2169
+ * object, without restricting it to a single suite-specific shape.
2170
+ * @param jsonLd The JSON-LD document to check.
2171
+ * @returns `true` if the document has a signature-like object; `false`
2172
+ * otherwise.
2173
+ * @since 2.2.0
2174
+ */
2175
+ function hasSignatureLike(jsonLd) {
2176
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
2177
+ const signature = jsonLd.signature;
2178
+ const hasReference = (value) => {
2179
+ if (typeof value === "string") return true;
2180
+ if (Array.isArray(value)) return value.some(hasReference);
2181
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
2182
+ };
2183
+ const hasSignatureObject = (value) => {
2184
+ if (typeof value !== "object" || value == null) return false;
2185
+ const signatureRecord = value;
2186
+ 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");
2045
2187
  };
2188
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
2046
2189
  }
2047
- async function fetchKeyWithResult(cacheKey, cls, options, onCachedUnavailable, onFetchError) {
2048
- const start = performance.now();
2049
- let outcome = { result: "error" };
2050
- try {
2051
- const logger = getLogger([
2052
- "fedify",
2053
- "sig",
2054
- "key"
2055
- ]);
2056
- const keyId = cacheKey.href;
2057
- if (isCompatibleKeyId(cacheKey)) options = {
2058
- ...options,
2059
- keyCache: void 0
2060
- };
2061
- const keyCache = options.keyCache;
2062
- const didKey = await resolveDidKey(cacheKey, cls, keyCache, logger);
2063
- if (didKey != null) {
2064
- outcome = { result: didKey.key == null ? "invalid" : didKey.cached ? "hit" : "fetched" };
2065
- return didKey;
2066
- }
2067
- const cached = await getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger);
2068
- if (cached?.key === null && cached.cached) {
2069
- const cachedUnavailable = await onCachedUnavailable(cacheKey, keyId, keyCache, logger);
2070
- outcome = { result: "hit" };
2071
- return cachedUnavailable;
2072
- }
2073
- if (cached != null) {
2074
- outcome = { result: "hit" };
2075
- return cached;
2076
- }
2077
- logger.debug("Fetching key {keyId} to verify signature...", { keyId });
2078
- let document;
2079
- let documentUrl = cacheKey;
2080
- try {
2081
- const remoteDocument = await (options.documentLoader ?? getDocumentLoader())(keyId);
2082
- document = remoteDocument.document;
2083
- documentUrl = new URL(remoteDocument.documentUrl ?? "", cacheKey);
2084
- } catch (error) {
2085
- const classified = classifyFetchError(error);
2086
- const errored = await onFetchError(error, cacheKey, keyId, keyCache, logger);
2087
- outcome = classified;
2088
- return errored;
2089
- }
2090
- const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, options, logger);
2091
- outcome = { result: resolved.key != null ? "fetched" : "invalid" };
2092
- return resolved;
2093
- } finally {
2094
- recordKeyLookup(options.meterProvider, {
2095
- durationMs: getDurationMs(start),
2096
- result: outcome.result,
2097
- remoteUrl: cacheKey,
2098
- cacheEnabled: options.keyCache != null,
2099
- statusCode: outcome.statusCode
2100
- });
2190
+ /**
2191
+ * Checks if the given JSON-LD document has a Linked Data Signature.
2192
+ * @param jsonLd The JSON-LD document to check.
2193
+ * @returns `true` if the document has a signature; `false` otherwise.
2194
+ * @since 1.0.0
2195
+ */
2196
+ function hasSignature(jsonLd) {
2197
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
2198
+ if ("signature" in jsonLd) {
2199
+ const signature = jsonLd.signature;
2200
+ if (typeof signature !== "object" || signature == null) return false;
2201
+ 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";
2101
2202
  }
2203
+ return false;
2102
2204
  }
2103
- async function fetchKeyInternal(keyId, cls, options = {}) {
2104
- return await fetchKeyWithResult(typeof keyId === "string" ? new URL(keyId) : keyId, cls, options, (_cacheKey, _keyId, _keyCache, _logger) => {
2105
- return {
2106
- key: null,
2107
- cached: true
2108
- };
2109
- }, async (error, cacheKey, keyId, keyCache, logger) => {
2110
- logger.debug("Failed to fetch key {keyId}.", {
2111
- keyId,
2205
+ /**
2206
+ * Detaches Linked Data Signatures from the given JSON-LD document.
2207
+ * @param jsonLd The JSON-LD document to modify.
2208
+ * @returns The modified JSON-LD document. If the input document does not
2209
+ * contain a signature, the original document is returned.
2210
+ * @since 1.0.0
2211
+ */
2212
+ function detachSignature(jsonLd) {
2213
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
2214
+ const doc = { ...jsonLd };
2215
+ delete doc.signature;
2216
+ return doc;
2217
+ }
2218
+ /**
2219
+ * Verifies Linked Data Signatures of the given JSON-LD document.
2220
+ *
2221
+ * This is a low-level utility that only checks the cryptographic signature
2222
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
2223
+ * attribution, and owner checks that a complete inbound LD verification
2224
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
2225
+ * the public verification entry point and the one that emits the
2226
+ * `activitypub.signature.verification.duration` metric for the LD path.
2227
+ * `verifySignature` itself only emits
2228
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
2229
+ * that the verification-duration metric is meant to cover happens in
2230
+ * `verifyJsonLd`.
2231
+ * @param jsonLd The JSON-LD document to verify.
2232
+ * @param options Options for verifying the signature.
2233
+ * @returns The public key that signed the document or `null` if the signature
2234
+ * is invalid or the key is not found.
2235
+ * @since 1.0.0
2236
+ */
2237
+ async function verifySignature(jsonLd, options = {}) {
2238
+ if (!hasSignature(jsonLd)) return null;
2239
+ const sig = jsonLd.signature;
2240
+ let signature;
2241
+ try {
2242
+ signature = decodeBase64(sig.signatureValue);
2243
+ } catch (error) {
2244
+ logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
2245
+ ...sig,
2112
2246
  error
2113
2247
  });
2114
- await keyCache?.set(cacheKey, null);
2115
- if (error instanceof FetchError && error.response != null) await keyCache?.setFetchError?.(cacheKey, {
2116
- status: error.response.status,
2117
- response: error.response.clone()
2118
- });
2119
- else await keyCache?.setFetchError?.(cacheKey, { error: error instanceof Error ? error : new Error(String(error)) });
2120
- return {
2121
- key: null,
2122
- cached: false
2123
- };
2124
- });
2125
- }
2126
- //#endregion
2127
- //#region src/sig/ld.ts
2128
- const logger$2 = getLogger([
2129
- "fedify",
2130
- "sig",
2131
- "ld"
2132
- ]);
2133
- const localContext = [
2134
- "https://w3id.org/identity/v1",
2135
- "https://www.w3.org/ns/activitystreams",
2136
- "https://w3id.org/security/v1",
2137
- "https://w3id.org/security/data-integrity/v1"
2138
- ];
2139
- const localContextUrls = new Set(localContext);
2140
- const builtInContextLoader = getDocumentLoader();
2141
- const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
2142
- "@graph",
2143
- "@included",
2144
- "@reverse"
2145
- ]);
2146
- /** @internal */
2147
- var UnsafeJsonLdError = class extends TypeError {
2148
- keyword;
2149
- constructor(keyword) {
2150
- super(`Unsupported JSON-LD keyword: ${keyword}.`);
2151
- this.keyword = keyword;
2152
- this.name = "UnsafeJsonLdError";
2153
- }
2154
- };
2155
- /** @internal */
2156
- var InvalidContextReferenceError = class extends TypeError {
2157
- reference;
2158
- constructor(reference) {
2159
- super(`Invalid JSON-LD context reference: ${reference}.`);
2160
- this.reference = reference;
2161
- this.name = "InvalidContextReferenceError";
2248
+ return null;
2162
2249
  }
2163
- };
2164
- function createLoadingRemoteContextFailedError(reference, cause) {
2165
- const message = cause instanceof Error ? cause.message : String(cause);
2166
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
2167
- error.name = "jsonld.InvalidUrl";
2168
- error.details = {
2169
- code: "loading remote context failed",
2170
- url: reference
2250
+ const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
2251
+ if (key == null) return null;
2252
+ const sigOpts = {
2253
+ ...sig,
2254
+ "@context": "https://w3id.org/identity/v1"
2171
2255
  };
2172
- error.cause = cause;
2173
- return error;
2174
- }
2175
- /** @internal */
2176
- function isClearlyMalformedContextReference(reference) {
2177
- for (const char of reference) {
2178
- const code = char.charCodeAt(0);
2179
- if (code <= 32 || code === 127) return true;
2256
+ delete sigOpts.type;
2257
+ delete sigOpts.id;
2258
+ delete sigOpts.signatureValue;
2259
+ let sigOptsHash;
2260
+ try {
2261
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
2262
+ } catch (error) {
2263
+ logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
2264
+ signatureOptions: sigOpts,
2265
+ error
2266
+ });
2267
+ return null;
2180
2268
  }
2181
- if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
2182
- for (let i = 0; i < reference.length; i++) {
2183
- if (reference[i] !== "%") continue;
2184
- if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
2185
- i += 2;
2269
+ const document = { ...jsonLd };
2270
+ delete document.signature;
2271
+ let docHash;
2272
+ try {
2273
+ docHash = await hashJsonLd(document, options.contextLoader);
2274
+ } catch (error) {
2275
+ logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
2276
+ document,
2277
+ error
2278
+ });
2279
+ return null;
2186
2280
  }
2187
- if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
2188
- for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
2281
+ const encoder = new TextEncoder();
2282
+ const message = sigOptsHash + docHash;
2283
+ const messageBytes = encoder.encode(message);
2284
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
2285
+ if (cached) {
2286
+ logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
2287
+ keyId: sig.creator,
2288
+ ...sig
2289
+ });
2290
+ const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
2291
+ ...options,
2292
+ keyCache: {
2293
+ get: () => Promise.resolve(void 0),
2294
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
2295
+ }
2296
+ }));
2297
+ if (key == null) return null;
2298
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
2189
2299
  }
2190
- return false;
2300
+ logger$4.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}", {
2301
+ keyId: sig.creator,
2302
+ ...sig,
2303
+ message
2304
+ });
2305
+ return null;
2191
2306
  }
2192
- function cloneRemoteDocument(remoteDocument) {
2193
- return structuredClone(remoteDocument);
2307
+ /**
2308
+ * Known Linked Data Signature `type` values, used to keep
2309
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
2310
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
2311
+ * only from external documents and are dropped from the metric attribute to
2312
+ * avoid attacker-controlled cardinality.
2313
+ */
2314
+ const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
2315
+ /**
2316
+ * Reports only whether a `signature` key is present on the document, with
2317
+ * no shape check on its value. This is intentionally looser than
2318
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
2319
+ * and {@link hasSignatureLike} (which structurally accepts several known
2320
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
2321
+ * unsupported signature payload (classified as `rejected`) apart from a
2322
+ * truly unsigned document (classified as `missing`), and only this
2323
+ * presence-only check captures both cases.
2324
+ */
2325
+ function hasLdSignatureProperty(jsonLd) {
2326
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
2194
2327
  }
2195
- function createMemoizedDocumentLoader(documentLoader) {
2196
- const cache = /* @__PURE__ */ new Map();
2197
- return async (url, options) => {
2198
- const cacheKey = URL.canParse(url) ? new URL(url).href : url;
2199
- let remoteDocument = cache.get(cacheKey);
2200
- if (remoteDocument == null) {
2201
- remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
2202
- remoteDocument.catch(() => {
2203
- if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
2204
- });
2205
- cache.set(cacheKey, remoteDocument);
2206
- }
2207
- return cloneRemoteDocument(await remoteDocument);
2208
- };
2328
+ function getLdSignatureObject(jsonLd) {
2329
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
2330
+ const { signature } = jsonLd;
2331
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
2332
+ return signature;
2333
+ }
2334
+ /**
2335
+ * Verify the authenticity of the given JSON-LD document using Linked Data
2336
+ * Signatures. If the document is signed, this function verifies the signature
2337
+ * and checks if the document is attributed to the owner of the public key.
2338
+ * If the document is not signed, this function returns `false`.
2339
+ * @param jsonLd The JSON-LD document to verify.
2340
+ * @param options Options for verifying the document.
2341
+ * @returns `true` if the document is authentic; `false` otherwise.
2342
+ */
2343
+ async function verifyJsonLd(jsonLd, options = {}) {
2344
+ return await verifyJsonLdInternal(jsonLd, options, true);
2209
2345
  }
2210
2346
  /** @internal */
2211
- function wrapContextLoaderForJsonLd(contextLoader) {
2212
- const loader = contextLoader ?? builtInContextLoader;
2213
- return async (url, options) => {
2347
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
2348
+ return await verifyJsonLdInternal(jsonLd, options, false);
2349
+ }
2350
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
2351
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
2352
+ const start = performance.now();
2353
+ let verified = false;
2354
+ let threw = false;
2355
+ let signatureType;
2214
2356
  try {
2215
- return await loader(url, options);
2357
+ const verificationOptions = hasSignature(jsonLd) ? {
2358
+ ...options,
2359
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
2360
+ } : options;
2361
+ const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
2362
+ const object = await Object$1.fromJsonLd(compacted, verificationOptions);
2363
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
2364
+ span.setAttribute("activitypub.object.type", getTypeId(object).href);
2365
+ const sig = getLdSignatureObject(jsonLd);
2366
+ if (sig != null) {
2367
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
2368
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
2369
+ if (typeof sig.type === "string") {
2370
+ span.setAttribute("ld_signatures.type", sig.type);
2371
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
2372
+ }
2373
+ }
2374
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
2375
+ if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
2376
+ const key = await verifySignature(compacted, verificationOptions);
2377
+ if (key == null) return false;
2378
+ if (key.ownerId == null) {
2379
+ logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
2380
+ return false;
2381
+ }
2382
+ attributions.delete(key.ownerId.href);
2383
+ if (attributions.size > 0) {
2384
+ logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
2385
+ return false;
2386
+ }
2387
+ verified = true;
2388
+ return true;
2216
2389
  } catch (error) {
2217
- if (!isInvalidUrlTypeError(error)) throw error;
2218
- if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
2219
- throw createLoadingRemoteContextFailedError(url, error);
2220
- }
2221
- };
2222
- }
2223
- /** @internal */
2224
- function getNormalizationContextLoader(contextLoader) {
2225
- const loader = wrapContextLoaderForJsonLd(contextLoader);
2226
- return createMemoizedDocumentLoader(async (url, options) => {
2227
- if (URL.canParse(url)) {
2228
- const normalizedUrl = new URL(url).href;
2229
- if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
2390
+ threw = true;
2391
+ span.setStatus({
2392
+ code: SpanStatusCode.ERROR,
2393
+ message: String(error)
2394
+ });
2395
+ throw error;
2396
+ } finally {
2397
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
2398
+ getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
2399
+ span.end();
2230
2400
  }
2231
- return await loader(url, options);
2232
2401
  });
2233
2402
  }
2234
- /** @internal */
2235
- async function compactJsonLd(jsonLd, contextLoader) {
2236
- const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
2237
- const signature = hasLds ? jsonLd.signature : void 0;
2238
- const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
2239
- const document = hasLds ? detachSignature(jsonLd) : jsonLd;
2240
- await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
2241
- const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
2242
- if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
2243
- assertSafeJsonLd(compacted);
2244
- return compacted;
2245
- }
2246
- function createInvalidRemoteContextError(reference) {
2247
- 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}".`);
2248
- error.name = "jsonld.InvalidUrl";
2249
- error.details = {
2250
- code: "invalid remote context",
2251
- url: reference
2252
- };
2253
- return error;
2403
+ async function hashJsonLd(jsonLd, contextLoader) {
2404
+ const canon = await jsonld.canonize(jsonLd, {
2405
+ format: "application/n-quads",
2406
+ documentLoader: contextLoader ?? getDocumentLoader()
2407
+ });
2408
+ const encoder = new TextEncoder();
2409
+ return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
2254
2410
  }
2255
- function getRemoteContext(remoteDocument, reference) {
2256
- const { contextUrl, documentUrl } = remoteDocument;
2257
- let { document } = remoteDocument;
2258
- if (typeof document === "string") document = JSON.parse(document);
2259
- if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
2260
- let context = "@context" in document ? document["@context"] : {};
2261
- if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
2262
- return {
2263
- context,
2264
- baseUrl: documentUrl ?? reference
2265
- };
2411
+ //#endregion
2412
+ //#region src/compat/secured-document.ts
2413
+ function isJsonMap$1(value) {
2414
+ return typeof value === "object" && value != null && !Array.isArray(value);
2266
2415
  }
2267
- function createGraphAliasContextState() {
2268
- return {
2269
- graphTerms: /* @__PURE__ */ new Set(),
2270
- jsonTerms: /* @__PURE__ */ new Set(),
2271
- propertyContexts: /* @__PURE__ */ new Map(),
2272
- termTargets: /* @__PURE__ */ new Map()
2273
- };
2416
+ function isNonEmptyString(value) {
2417
+ return typeof value === "string" && value.length > 0;
2274
2418
  }
2275
- function cloneGraphAliasContextState(state) {
2276
- return {
2277
- graphTerms: new Set(state.graphTerms),
2278
- jsonTerms: new Set(state.jsonTerms),
2279
- propertyContexts: new Map(state.propertyContexts),
2280
- termTargets: new Map(state.termTargets)
2281
- };
2419
+ function hasDataIntegrityProofType(value) {
2420
+ return (Array.isArray(value) ? value : [value]).some((type) => type === "DataIntegrityProof" || type === "https://w3id.org/security#DataIntegrityProof");
2282
2421
  }
2283
- function resolveContextTarget(target, state) {
2284
- if (target === "@graph") return target;
2285
- const mapped = state.termTargets.get(target);
2286
- if (mapped == null) return target;
2287
- return mapped;
2422
+ /**
2423
+ * Checks whether a JSON value is a complete, self-contained secured document:
2424
+ * a map with its own `@context` and exactly one direct, map-valued `proof`
2425
+ * that carries every member `eddsa-jcs-2022` proof generation produces.
2426
+ *
2427
+ * This is deliberately stricter than {@link hasProofLike}, which exists to
2428
+ * decide whether a document is worth verifying. Here a false positive would
2429
+ * silently suppress a wire-compatibility fix on an ordinary document, so a
2430
+ * partial or malformed proof does not qualify.
2431
+ *
2432
+ * @internal
2433
+ */
2434
+ function isSelfContainedSecuredDocument(value) {
2435
+ if (!isJsonMap$1(value)) return false;
2436
+ if (!Object.hasOwn(value, "@context") || value["@context"] == null) return false;
2437
+ if (!Object.hasOwn(value, "proof")) return false;
2438
+ const proof = value.proof;
2439
+ if (!isJsonMap$1(proof)) return false;
2440
+ return hasDataIntegrityProofType(proof.type) && isNonEmptyString(proof.cryptosuite) && isNonEmptyString(proof.created) && isNonEmptyString(proof.verificationMethod) && isNonEmptyString(proof.proofPurpose) && isNonEmptyString(proof.proofValue);
2288
2441
  }
2289
- function getDirectContextTarget(definition) {
2290
- if (definition === null) return null;
2291
- if (typeof definition === "string") return definition;
2292
- if (typeof definition === "object" && definition != null && "@id" in definition) {
2293
- const id = definition["@id"];
2294
- if (id === null) return null;
2295
- if (typeof id === "string") return id;
2442
+ //#endregion
2443
+ //#region src/compat/public-audience.ts
2444
+ const logger$3 = getLogger([
2445
+ "fedify",
2446
+ "compat",
2447
+ "public-audience"
2448
+ ]);
2449
+ const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
2450
+ "to",
2451
+ "cc",
2452
+ "bto",
2453
+ "bcc",
2454
+ "audience"
2455
+ ]);
2456
+ const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
2457
+ const MAX_TRAVERSAL_DEPTH$1 = 64;
2458
+ const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(preloadedContexts));
2459
+ function hasPublicCurieInAddressing(value, preserveSecured, parentKey, depth = 0) {
2460
+ if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
2461
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
2462
+ if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, preserveSecured, parentKey, depth + 1));
2463
+ if (typeof value !== "object" || value == null) return false;
2464
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return false;
2465
+ const record = value;
2466
+ for (const key of Object.keys(record)) {
2467
+ if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
2468
+ if (key === "@context") continue;
2469
+ if (hasPublicCurieInAddressing(record[key], preserveSecured, key, depth + 1)) return true;
2296
2470
  }
2471
+ return false;
2297
2472
  }
2298
- function isJsonTypedDefinition(definition) {
2299
- return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
2300
- }
2301
- function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
2302
- if (target === "@graph") return target;
2303
- if (seen.has(target)) return target;
2304
- seen.add(target);
2305
- if (localTargets.has(target)) {
2306
- const localTarget = localTargets.get(target);
2307
- return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
2473
+ function rewritePublicAudience(value, preserveSecured, parentKey, depth = 0) {
2474
+ if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return PUBLIC_COLLECTION.href;
2475
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
2476
+ if (Array.isArray(value)) {
2477
+ let changed = false;
2478
+ const mapped = value.map((item) => {
2479
+ const rewritten = rewritePublicAudience(item, preserveSecured, parentKey, depth + 1);
2480
+ if (rewritten !== item) changed = true;
2481
+ return rewritten;
2482
+ });
2483
+ return changed ? mapped : value;
2308
2484
  }
2309
- return resolveContextTarget(target, state);
2310
- }
2311
- function refreshGraphAliases(state) {
2312
- state.graphTerms.clear();
2313
- for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
2314
- }
2315
- function normalizeContextReference(reference, baseUrl) {
2316
- if (baseUrl != null) return new URL(reference, baseUrl).href;
2317
- return URL.canParse(reference) ? new URL(reference).href : reference;
2485
+ if (typeof value !== "object" || value == null) return value;
2486
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(value)) return value;
2487
+ const record = value;
2488
+ let changed = false;
2489
+ const normalized = Object.create(null);
2490
+ for (const key of Object.keys(record)) {
2491
+ 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);
2492
+ if (rewritten !== record[key]) changed = true;
2493
+ normalized[key] = rewritten;
2494
+ }
2495
+ return changed ? normalized : value;
2318
2496
  }
2319
- /** @internal */
2320
- function isInvalidUrlTypeError(error) {
2321
- const code = error.code;
2322
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
2497
+ /**
2498
+ * Reports whether `value` carries an `@context` property anywhere inside
2499
+ * its subtree (not counting the value itself). A nested `@context` can
2500
+ * introduce a local term-definition scope that redefines `as:` or `Public`
2501
+ * even when the top-level `@context` is safe, so the fast path must defer
2502
+ * to the URDNA2015 equivalence check whenever one is present.
2503
+ */
2504
+ function hasNestedContext$1(value, depth = 0) {
2505
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
2506
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
2507
+ if (typeof value !== "object" || value == null) return false;
2508
+ const record = value;
2509
+ for (const key of Object.keys(record)) {
2510
+ if (key === "@context") return true;
2511
+ if (hasNestedContext$1(record[key], depth + 1)) return true;
2512
+ }
2513
+ return false;
2323
2514
  }
2324
- async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
2325
- if (context === null) return createGraphAliasContextState();
2326
- let nextState = cloneGraphAliasContextState(state);
2327
- if (Array.isArray(context)) {
2328
- for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
2329
- return nextState;
2515
+ /**
2516
+ * Checks whether the `@context` of a JSON-LD document is guaranteed not
2517
+ * to redefine the `as:` prefix or the bare `Public` term. Only documents
2518
+ * whose `@context` is a string, or an array of strings, drawn from Fedify's
2519
+ * preloaded context set AND including the ActivityStreams URL qualify,
2520
+ * AND no nested subtree carries its own `@context` that might redefine
2521
+ * those terms within a local scope. When all of that holds the rewrite
2522
+ * is provably semantics-preserving and the URDNA2015 equivalence check
2523
+ * can be skipped. Any other shape (unknown external URLs, inline
2524
+ * objects at the top level, nested `@context` blocks) is treated as
2525
+ * potentially unsafe.
2526
+ */
2527
+ function hasKnownSafeContext$1(jsonLd) {
2528
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
2529
+ const record = jsonLd;
2530
+ if (!Object.hasOwn(record, "@context")) return false;
2531
+ const ctx = record["@context"];
2532
+ const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
2533
+ if (entries == null || entries.length === 0) return false;
2534
+ let hasAs = false;
2535
+ for (const entry of entries) {
2536
+ if (typeof entry !== "string") return false;
2537
+ if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
2538
+ if (entry === AS_CONTEXT_URL$1) hasAs = true;
2330
2539
  }
2331
- if (typeof context === "string") {
2332
- const reference = normalizeContextReference(context, baseUrl);
2333
- const cacheKey = `${baseUrl ?? ""}\n${reference}`;
2334
- if (processingContexts.has(cacheKey)) return nextState;
2335
- processingContexts.add(cacheKey);
2336
- try {
2337
- let remoteContext = remoteContextCache.get(cacheKey);
2338
- if (remoteContext == null) {
2339
- remoteContext = (async () => {
2340
- try {
2341
- return getRemoteContext(await documentLoader(reference), reference);
2342
- } catch (error) {
2343
- if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
2344
- throw error;
2345
- }
2346
- })();
2347
- remoteContextCache.set(cacheKey, remoteContext);
2348
- }
2349
- const loadedRemoteContext = await remoteContext;
2350
- return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
2351
- } finally {
2352
- processingContexts.delete(cacheKey);
2353
- }
2540
+ if (!hasAs) return false;
2541
+ for (const key of Object.keys(record)) {
2542
+ if (key === "@context") continue;
2543
+ if (hasNestedContext$1(record[key])) return false;
2354
2544
  }
2355
- if (typeof context === "object" && context != null) {
2356
- if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
2357
- const localTargets = /* @__PURE__ */ new Map();
2358
- for (const [term, definition] of globalThis.Object.entries(context)) {
2359
- if (term.startsWith("@")) continue;
2360
- const target = getDirectContextTarget(definition);
2361
- if (target == null) localTargets.set(term, null);
2362
- else if (typeof target === "string") localTargets.set(term, target);
2363
- else localTargets.delete(term);
2364
- }
2365
- for (const [term, definition] of globalThis.Object.entries(context)) {
2366
- if (term.startsWith("@")) continue;
2367
- if (localTargets.has(term)) {
2368
- const directTarget = localTargets.get(term);
2369
- if (directTarget == null) nextState.termTargets.set(term, null);
2370
- else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
2371
- } else nextState.termTargets.delete(term);
2372
- if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
2373
- context: definition["@context"],
2374
- baseUrl
2375
- });
2376
- else nextState.propertyContexts.delete(term);
2377
- if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
2378
- else nextState.jsonTerms.delete(term);
2379
- }
2380
- refreshGraphAliases(nextState);
2545
+ return true;
2546
+ }
2547
+ /**
2548
+ * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
2549
+ * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
2550
+ * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
2551
+ *
2552
+ * Several ActivityPub implementations, Lemmy among them, match these
2553
+ * fields as plain URLs without running JSON-LD expansion, and silently
2554
+ * drop activities whose public addressing appears in CURIE form. This
2555
+ * helper works around that gap.
2556
+ *
2557
+ * For documents whose `@context` is drawn entirely from Fedify's
2558
+ * preloaded context set and includes the ActivityStreams URL, the
2559
+ * rewrite is applied directly: the content of every preloaded non-AS
2560
+ * context is known not to redefine the `as:` prefix or the bare `Public`
2561
+ * term, so the semantics are preserved by construction. Any other
2562
+ * shape (an inline object, an unknown external URL, and so on) is
2563
+ * treated as potentially unsafe and gated on a JSON-LD equivalence
2564
+ * check; both forms are canonicalized with URDNA2015 and the resulting
2565
+ * N-Quads are compared. When they differ, the original document is
2566
+ * returned unchanged. Canonicalization failures also fall back to the
2567
+ * original document.
2568
+ *
2569
+ * When no `contextLoader` is supplied the helper falls back to an
2570
+ * internal loader that resolves only the URLs in Fedify's
2571
+ * preloaded-contexts set and rejects every other URL without issuing a
2572
+ * network request. That behaviour is deliberately narrower than
2573
+ * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
2574
+ * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
2575
+ * helper is reached from verification paths (`verifyProof()` /
2576
+ * `verifyObject()`) that operate on inbound, potentially adversarial
2577
+ * JSON-LD, and a default loader that fetches attacker-supplied
2578
+ * `@context` URLs on the caller's behalf would be an SSRF vector.
2579
+ * Canonicalization failures against the restricted loader fall back to
2580
+ * the original document, same as any other canonicalization error.
2581
+ * Callers that genuinely need the remote-fetch loader (for example
2582
+ * applications that sign local JSON-LD against a custom vocabulary)
2583
+ * should pass a `contextLoader` explicitly.
2584
+ *
2585
+ * Must be called before any signing step that canonicalizes the
2586
+ * compact form byte-for-byte (for example, Object Integrity Proofs
2587
+ * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
2588
+ * matches what is sent on the wire.
2589
+ */
2590
+ async function normalizePublicAudience(jsonLd, contextLoader, options = {}) {
2591
+ const preserveSecured = options.preserveNestedSecuredDocuments ?? false;
2592
+ if (!hasPublicCurieInAddressing(jsonLd, preserveSecured)) return jsonLd;
2593
+ const normalized = rewritePublicAudience(jsonLd, preserveSecured);
2594
+ if (hasKnownSafeContext$1(jsonLd)) return normalized;
2595
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
2596
+ try {
2597
+ const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
2598
+ format: "application/n-quads",
2599
+ documentLoader: loader
2600
+ }), jsonld.canonize(normalized, {
2601
+ format: "application/n-quads",
2602
+ documentLoader: loader
2603
+ })]);
2604
+ if (before === after) return normalized;
2605
+ logger$3.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.");
2606
+ } catch (error) {
2607
+ logger$3.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
2381
2608
  }
2382
- return nextState;
2609
+ return jsonLd;
2383
2610
  }
2384
- async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
2385
- if (Array.isArray(jsonLd)) {
2386
- for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
2611
+ //#endregion
2612
+ //#region src/compat/outgoing-jsonld.ts
2613
+ const logger$2 = getLogger([
2614
+ "fedify",
2615
+ "compat",
2616
+ "outgoing-jsonld"
2617
+ ]);
2618
+ const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
2619
+ const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
2620
+ const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
2621
+ const MAX_TRAVERSAL_DEPTH = 64;
2622
+ function isJsonLdListObject(value) {
2623
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
2624
+ }
2625
+ function isJsonLdValueObject(value) {
2626
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
2627
+ }
2628
+ function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
2629
+ if (Array.isArray(value)) {
2630
+ if (seen.has(value)) return;
2631
+ seen.add(value);
2632
+ for (const item of value) yield* getContextObjects(item, seen);
2387
2633
  return;
2388
2634
  }
2389
- if (typeof jsonLd !== "object" || jsonLd == null) return;
2390
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
2391
- let state = inheritedState;
2392
- if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
2393
- if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
2394
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
2395
- if (key === "@context") continue;
2396
- if (jsonLiteralWrapper && key === "@value") continue;
2397
- if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
2398
- if (state.jsonTerms.has(key)) continue;
2399
- await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
2635
+ if (typeof value === "object" && value != null) {
2636
+ if (seen.has(value)) return;
2637
+ seen.add(value);
2638
+ const record = value;
2639
+ yield record;
2640
+ for (const definition of Object.values(record)) {
2641
+ if (typeof definition !== "object" || definition == null) continue;
2642
+ const nestedContext = definition["@context"];
2643
+ if (nestedContext == null) continue;
2644
+ yield* getContextObjects(nestedContext, seen);
2645
+ }
2400
2646
  }
2401
2647
  }
2402
- function isJsonLiteralWrapper(value) {
2403
- return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
2648
+ function isActivityStreamsAttachmentTerm(value) {
2649
+ return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
2404
2650
  }
2405
2651
  /** @internal */
2406
- function assertSafeJsonLd(jsonLd) {
2407
- if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
2408
- else if (typeof jsonLd === "object" && jsonLd != null) {
2409
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
2410
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
2411
- if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
2412
- if (jsonLiteralWrapper && key === "@value") continue;
2413
- assertSafeJsonLd(value);
2414
- }
2652
+ function isPreloadedContextAttachmentSafe(document) {
2653
+ if (typeof document !== "object" || document == null) return true;
2654
+ const context = document["@context"];
2655
+ for (const contextObject of getContextObjects(context)) {
2656
+ if (!Object.hasOwn(contextObject, "attachment")) continue;
2657
+ if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
2658
+ return false;
2415
2659
  }
2660
+ return true;
2416
2661
  }
2417
- /**
2418
- * Attaches a LD signature to the given JSON-LD document.
2419
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
2420
- * modified.
2421
- * @param signature The signature to attach.
2422
- * @returns The JSON-LD document with the attached signature.
2423
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
2424
- * @since 1.0.0
2425
- */
2426
- function attachSignature(jsonLd, signature) {
2427
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
2428
- return {
2429
- ...jsonLd,
2430
- signature
2431
- };
2432
- }
2433
- /**
2434
- * Creates a LD signature for the given JSON-LD document.
2435
- * @param jsonLd The JSON-LD document to sign.
2436
- * @param privateKey The private key to sign the document.
2437
- * @param keyId The ID of the public key that corresponds to the private key.
2438
- * @param options Additional options for creating the signature.
2439
- * See also {@link CreateSignatureOptions}.
2440
- * @return The created signature.
2441
- * @throws {TypeError} If the private key is invalid or unsupported.
2442
- * @since 1.0.0
2443
- */
2444
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
2445
- validateCryptoKey(privateKey, "private");
2446
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2447
- const options = {
2448
- "@context": "https://w3id.org/identity/v1",
2449
- creator: keyId.href,
2450
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
2451
- };
2452
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
2453
- const messageBytes = new TextEncoder().encode(message);
2454
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
2455
- return {
2456
- ...options,
2457
- type: "RsaSignature2017",
2458
- signatureValue: encodeBase64(signature)
2459
- };
2662
+ function getKnownSafeContextUrls() {
2663
+ const urls = /* @__PURE__ */ new Set();
2664
+ for (const [url, document] of Object.entries(preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
2665
+ else logger$2.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
2666
+ return urls;
2460
2667
  }
2461
2668
  /**
2462
- * Signs the given JSON-LD document with the private key and returns the signed
2463
- * JSON-LD document.
2464
- * @param jsonLd The JSON-LD document to sign.
2465
- * @param privateKey The private key to sign the document.
2466
- * @param keyId The key ID to use in the signature. It will be used by the
2467
- * verifier to fetch the corresponding public key.
2468
- * @param options Additional options for signing the document.
2469
- * See also {@link SignJsonLdOptions}.
2470
- * @returns The signed JSON-LD document.
2471
- * @throws {TypeError} If the private key is invalid or unsupported.
2472
- * @since 1.0.0
2669
+ * Wraps scalar ActivityStreams attachment properties in arrays.
2473
2670
  */
2474
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
2475
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
2476
- try {
2477
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
2478
- if (span.isRecording()) {
2479
- span.setAttribute("ld_signatures.type", signature.type);
2480
- span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
2671
+ function wrapScalarAttachments(jsonLd, preserveSecured, depth = 0) {
2672
+ if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
2673
+ if (preserveSecured && depth > 0 && isSelfContainedSecuredDocument(jsonLd)) return jsonLd;
2674
+ if (Array.isArray(jsonLd)) {
2675
+ let normalized = null;
2676
+ for (let i = 0; i < jsonLd.length; i++) {
2677
+ const item = jsonLd[i];
2678
+ const next = wrapScalarAttachments(item, preserveSecured, depth + 1);
2679
+ if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
2680
+ if (normalized != null) normalized[i] = next;
2681
+ }
2682
+ return normalized ?? jsonLd;
2683
+ }
2684
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
2685
+ const record = jsonLd;
2686
+ const keys = Object.keys(record);
2687
+ let normalized = null;
2688
+ for (let i = 0; i < keys.length; i++) {
2689
+ const key = keys[i];
2690
+ const value = record[key];
2691
+ const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, preserveSecured, depth + 1);
2692
+ const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
2693
+ if (normalized == null && output !== value) {
2694
+ const cloned = Object.create(null);
2695
+ for (let j = 0; j < i; j++) {
2696
+ const previousKey = keys[j];
2697
+ cloned[previousKey] = record[previousKey];
2481
2698
  }
2482
- return attachSignature(jsonLd, signature);
2483
- } catch (error) {
2484
- span.setStatus({
2485
- code: SpanStatusCode.ERROR,
2486
- message: String(error)
2487
- });
2488
- throw error;
2489
- } finally {
2490
- span.end();
2699
+ normalized = cloned;
2491
2700
  }
2492
- });
2493
- }
2494
- /**
2495
- * Checks if the given JSON-LD document has a Linked Data Signature-like
2496
- * object, without restricting it to a single suite-specific shape.
2497
- * @param jsonLd The JSON-LD document to check.
2498
- * @returns `true` if the document has a signature-like object; `false`
2499
- * otherwise.
2500
- * @since 2.2.0
2501
- */
2502
- function hasSignatureLike(jsonLd) {
2503
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
2504
- const signature = jsonLd.signature;
2505
- const hasReference = (value) => {
2506
- if (typeof value === "string") return true;
2507
- if (Array.isArray(value)) return value.some(hasReference);
2508
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
2509
- };
2510
- const hasSignatureObject = (value) => {
2511
- if (typeof value !== "object" || value == null) return false;
2512
- const signatureRecord = value;
2513
- 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");
2514
- };
2515
- return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
2701
+ if (normalized != null) normalized[key] = output;
2702
+ }
2703
+ return normalized ?? jsonLd;
2516
2704
  }
2517
- /**
2518
- * Checks if the given JSON-LD document has a Linked Data Signature.
2519
- * @param jsonLd The JSON-LD document to check.
2520
- * @returns `true` if the document has a signature; `false` otherwise.
2521
- * @since 1.0.0
2522
- */
2523
- function hasSignature(jsonLd) {
2524
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
2525
- if ("signature" in jsonLd) {
2526
- const signature = jsonLd.signature;
2527
- if (typeof signature !== "object" || signature == null) return false;
2528
- 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";
2705
+ function hasNestedContext(value, depth = 0) {
2706
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
2707
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
2708
+ if (typeof value !== "object" || value == null) return false;
2709
+ const record = value;
2710
+ for (const key of Object.keys(record)) {
2711
+ if (key === "@context") return true;
2712
+ if (key === "@value" && isJsonLdValueObject(value)) continue;
2713
+ if (hasNestedContext(record[key], depth + 1)) return true;
2529
2714
  }
2530
2715
  return false;
2531
2716
  }
2532
- /**
2533
- * Detaches Linked Data Signatures from the given JSON-LD document.
2534
- * @param jsonLd The JSON-LD document to modify.
2535
- * @returns The modified JSON-LD document. If the input document does not
2536
- * contain a signature, the original document is returned.
2537
- * @since 1.0.0
2538
- */
2539
- function detachSignature(jsonLd) {
2540
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
2541
- const doc = { ...jsonLd };
2542
- delete doc.signature;
2543
- return doc;
2544
- }
2545
- /**
2546
- * Verifies Linked Data Signatures of the given JSON-LD document.
2547
- *
2548
- * This is a low-level utility that only checks the cryptographic signature
2549
- * and (optionally) the cached key. It does not run the JSON-LD parsing,
2550
- * attribution, and owner checks that a complete inbound LD verification
2551
- * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
2552
- * the public verification entry point and the one that emits the
2553
- * `activitypub.signature.verification.duration` metric for the LD path.
2554
- * `verifySignature` itself only emits
2555
- * `activitypub.signature.key_fetch.duration`, since the rest of the work
2556
- * that the verification-duration metric is meant to cover happens in
2557
- * `verifyJsonLd`.
2558
- * @param jsonLd The JSON-LD document to verify.
2559
- * @param options Options for verifying the signature.
2560
- * @returns The public key that signed the document or `null` if the signature
2561
- * is invalid or the key is not found.
2562
- * @since 1.0.0
2563
- */
2564
- async function verifySignature(jsonLd, options = {}) {
2565
- if (!hasSignature(jsonLd)) return null;
2566
- const sig = jsonLd.signature;
2567
- let signature;
2568
- try {
2569
- signature = decodeBase64(sig.signatureValue);
2570
- } catch (error) {
2571
- logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
2572
- ...sig,
2573
- error
2574
- });
2575
- return null;
2576
- }
2577
- const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
2578
- if (key == null) return null;
2579
- const sigOpts = {
2580
- ...sig,
2581
- "@context": "https://w3id.org/identity/v1"
2582
- };
2583
- delete sigOpts.type;
2584
- delete sigOpts.id;
2585
- delete sigOpts.signatureValue;
2586
- let sigOptsHash;
2587
- try {
2588
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
2589
- } catch (error) {
2590
- logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
2591
- signatureOptions: sigOpts,
2592
- error
2593
- });
2594
- return null;
2595
- }
2596
- const document = { ...jsonLd };
2597
- delete document.signature;
2598
- let docHash;
2599
- try {
2600
- docHash = await hashJsonLd(document, options.contextLoader);
2601
- } catch (error) {
2602
- logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
2603
- document,
2604
- error
2605
- });
2606
- return null;
2717
+ function exceedsTraversalDepth(value, depth = 0) {
2718
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
2719
+ if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
2720
+ if (typeof value !== "object" || value == null) return false;
2721
+ const record = value;
2722
+ for (const key of Object.keys(record)) {
2723
+ if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
2724
+ if (exceedsTraversalDepth(record[key], depth + 1)) return true;
2607
2725
  }
2608
- const encoder = new TextEncoder();
2609
- const message = sigOptsHash + docHash;
2610
- const messageBytes = encoder.encode(message);
2611
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
2612
- if (cached) {
2613
- logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
2614
- keyId: sig.creator,
2615
- ...sig
2616
- });
2617
- const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
2618
- ...options,
2619
- keyCache: {
2620
- get: () => Promise.resolve(void 0),
2621
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
2622
- }
2623
- }));
2624
- if (key == null) return null;
2625
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
2726
+ return false;
2727
+ }
2728
+ function hasKnownSafeContext(jsonLd) {
2729
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
2730
+ const record = jsonLd;
2731
+ if (!Object.hasOwn(record, "@context")) return false;
2732
+ const context = record["@context"];
2733
+ const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
2734
+ if (entries == null || entries.length < 1) return false;
2735
+ let hasActivityStreamsContext = false;
2736
+ for (const entry of entries) {
2737
+ if (typeof entry !== "string") return false;
2738
+ if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
2739
+ if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
2626
2740
  }
2627
- 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}", {
2628
- keyId: sig.creator,
2629
- ...sig,
2630
- message
2631
- });
2632
- return null;
2741
+ if (!hasActivityStreamsContext) return false;
2742
+ for (const key of Object.keys(record)) {
2743
+ if (key === "@context") continue;
2744
+ if (hasNestedContext(record[key])) return false;
2745
+ }
2746
+ return true;
2747
+ }
2748
+ function getLogSafeJsonLdMetadata(jsonLd) {
2749
+ if (typeof jsonLd !== "object" || jsonLd == null) return {};
2750
+ const record = jsonLd;
2751
+ const context = record["@context"];
2752
+ return {
2753
+ id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
2754
+ type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
2755
+ context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
2756
+ };
2633
2757
  }
2634
2758
  /**
2635
- * Known Linked Data Signature `type` values, used to keep
2636
- * `ld_signatures.type` on a bounded set of spec-defined string values.
2637
- * Fedify only signs and verifies `RsaSignature2017`; other values come in
2638
- * only from external documents and are dropped from the metric attribute to
2639
- * avoid attacker-controlled cardinality.
2640
- */
2641
- const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
2642
- /**
2643
- * Reports only whether a `signature` key is present on the document, with
2644
- * no shape check on its value. This is intentionally looser than
2645
- * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
2646
- * and {@link hasSignatureLike} (which structurally accepts several known
2647
- * suites): `verifyJsonLd` needs to tell a document with a malformed or
2648
- * unsupported signature payload (classified as `rejected`) apart from a
2649
- * truly unsigned document (classified as `missing`), and only this
2650
- * presence-only check captures both cases.
2759
+ * Ensures ActivityStreams attachment properties are represented as arrays
2760
+ * when doing so preserves the JSON-LD semantics.
2761
+ *
2762
+ * JSON-LD compaction collapses single-item arrays into scalar values by
2763
+ * default. Some ActivityPub implementations, Pixelfed among them, parse
2764
+ * `attachment` as a plain JSON array rather than a JSON-LD property and reject
2765
+ * otherwise valid objects whose single attachment is emitted as a scalar.
2766
+ *
2767
+ * When no `contextLoader` is supplied, the helper falls back to a restricted
2768
+ * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
2769
+ * every other URL without network access. Documents with custom, inline, or
2770
+ * otherwise uncached contexts should pass a real `contextLoader` if they need
2771
+ * the semantic-preservation check to succeed; otherwise canonicalization
2772
+ * failures leave the original document unchanged.
2651
2773
  */
2652
- function hasLdSignatureProperty(jsonLd) {
2653
- return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
2654
- }
2655
- function getLdSignatureObject(jsonLd) {
2656
- if (!hasLdSignatureProperty(jsonLd)) return void 0;
2657
- const { signature } = jsonLd;
2658
- if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
2659
- return signature;
2774
+ async function normalizeAttachmentArrays(jsonLd, contextLoader, options = {}) {
2775
+ const normalized = wrapScalarAttachments(jsonLd, options.preserveNestedSecuredDocuments ?? false);
2776
+ if (normalized === jsonLd) return jsonLd;
2777
+ if (exceedsTraversalDepth(jsonLd)) {
2778
+ logger$2.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
2779
+ return jsonLd;
2780
+ }
2781
+ if (hasKnownSafeContext(jsonLd)) return normalized;
2782
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
2783
+ try {
2784
+ const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
2785
+ format: "application/n-quads",
2786
+ documentLoader: loader
2787
+ }), jsonld.canonize(normalized, {
2788
+ format: "application/n-quads",
2789
+ documentLoader: loader
2790
+ })]);
2791
+ if (before === after) return normalized;
2792
+ logger$2.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));
2793
+ } catch (error) {
2794
+ logger$2.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
2795
+ }
2796
+ return jsonLd;
2660
2797
  }
2661
2798
  /**
2662
- * Verify the authenticity of the given JSON-LD document using Linked Data
2663
- * Signatures. If the document is signed, this function verifies the signature
2664
- * and checks if the document is attributed to the owner of the public key.
2665
- * If the document is not signed, this function returns `false`.
2666
- * @param jsonLd The JSON-LD document to verify.
2667
- * @param options Options for verifying the document.
2668
- * @returns `true` if the document is authentic; `false` otherwise.
2799
+ * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
2800
+ * to locally generated outgoing activities before they are signed, enqueued,
2801
+ * or sent.
2669
2802
  */
2670
- async function verifyJsonLd(jsonLd, options = {}) {
2671
- return await verifyJsonLdInternal(jsonLd, options, true);
2672
- }
2673
- /** @internal */
2674
- async function verifyCompactJsonLd(jsonLd, options = {}) {
2675
- return await verifyJsonLdInternal(jsonLd, options, false);
2676
- }
2677
- async function verifyJsonLdInternal(jsonLd, options, compact) {
2678
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
2679
- const start = performance.now();
2680
- let verified = false;
2681
- let threw = false;
2682
- let signatureType;
2683
- try {
2684
- const verificationOptions = hasSignature(jsonLd) ? {
2685
- ...options,
2686
- contextLoader: getNormalizationContextLoader(options.contextLoader)
2687
- } : options;
2688
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
2689
- const object = await Object$1.fromJsonLd(compacted, verificationOptions);
2690
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
2691
- span.setAttribute("activitypub.object.type", getTypeId(object).href);
2692
- const sig = getLdSignatureObject(jsonLd);
2693
- if (sig != null) {
2694
- if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
2695
- if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
2696
- if (typeof sig.type === "string") {
2697
- span.setAttribute("ld_signatures.type", sig.type);
2698
- if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
2699
- }
2700
- }
2701
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
2702
- if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
2703
- const key = await verifySignature(compacted, verificationOptions);
2704
- if (key == null) return false;
2705
- if (key.ownerId == null) {
2706
- logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
2707
- return false;
2708
- }
2709
- attributions.delete(key.ownerId.href);
2710
- if (attributions.size > 0) {
2711
- logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
2712
- return false;
2713
- }
2714
- verified = true;
2715
- return true;
2716
- } catch (error) {
2717
- threw = true;
2718
- span.setStatus({
2719
- code: SpanStatusCode.ERROR,
2720
- message: String(error)
2721
- });
2722
- throw error;
2723
- } finally {
2724
- const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
2725
- getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
2726
- span.end();
2727
- }
2728
- });
2729
- }
2730
- async function hashJsonLd(jsonLd, contextLoader) {
2731
- const canon = await jsonld.canonize(jsonLd, {
2732
- format: "application/n-quads",
2733
- documentLoader: contextLoader ?? getDocumentLoader()
2734
- });
2735
- const encoder = new TextEncoder();
2736
- return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
2803
+ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, options = {}) {
2804
+ jsonLd = await normalizePublicAudience(jsonLd, contextLoader, options);
2805
+ return await normalizeAttachmentArrays(jsonLd, contextLoader, options);
2737
2806
  }
2738
2807
  //#endregion
2739
2808
  //#region src/sig/proof.ts
@@ -3457,8 +3526,37 @@ async function expandPortableObjectRoot(jsonLd, contextLoader) {
3457
3526
  }
3458
3527
  };
3459
3528
  }
3529
+ /**
3530
+ * Gets the DID of a portable object ID, which is either an `ap:` or
3531
+ * `ap+ef61:` URI or an FEP-ef61 compatible identifier.
3532
+ * @throws {TypeError} If the ID is malformed.
3533
+ */
3534
+ function getObjectDid(id) {
3535
+ try {
3536
+ parseIri(id);
3537
+ if (PORTABLE_OBJECT_ID_PATTERN.test(id)) return getFe34Origin(id);
3538
+ const portableId = fromCompatibleEf61Id(id);
3539
+ if (portableId != null) return getFe34Origin(portableId);
3540
+ } catch (error) {
3541
+ if (!(error instanceof TypeError)) throw error;
3542
+ throw new InvalidPortableObjectIdError(id, { cause: error });
3543
+ }
3544
+ throw new InvalidPortableObjectIdError(id);
3545
+ }
3546
+ /**
3547
+ * The error thrown when a document's ID looks portable, i.e., it is an `ap:`
3548
+ * or `ap+ef61:` URI or looks like an FEP-ef61 compatible identifier, but is
3549
+ * malformed.
3550
+ * @internal
3551
+ */
3552
+ var InvalidPortableObjectIdError = class extends TypeError {
3553
+ constructor(id, options) {
3554
+ super(`Invalid portable object ID: ${id}`, options);
3555
+ this.name = "InvalidPortableObjectIdError";
3556
+ }
3557
+ };
3460
3558
  async function preparePortableObjectProof(jsonLd, options) {
3461
- if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
3559
+ if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !isPortableId(jsonLd["@id"])) return {
3462
3560
  prepared: false,
3463
3561
  result: {
3464
3562
  verified: false,
@@ -3467,15 +3565,15 @@ async function preparePortableObjectProof(jsonLd, options) {
3467
3565
  };
3468
3566
  const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
3469
3567
  const id = root["@id"];
3470
- if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
3568
+ if (typeof id !== "string" || !isPortableId(id)) return {
3471
3569
  prepared: false,
3472
3570
  result: {
3473
3571
  verified: false,
3474
3572
  reason: { type: "notPortableObject" }
3475
3573
  }
3476
3574
  };
3575
+ const objectDid = getObjectDid(id);
3477
3576
  const objectId = parseIri(id);
3478
- getFe34Origin(objectId);
3479
3577
  const objectType = classifyFep2277CoreType(root);
3480
3578
  if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
3481
3579
  prepared: false,
@@ -3580,7 +3678,7 @@ async function preparePortableObjectProof(jsonLd, options) {
3580
3678
  }
3581
3679
  };
3582
3680
  }
3583
- if (!haveSameFe34Origin(objectId, verificationMethod)) return {
3681
+ if (getFe34Origin(verificationMethod) !== objectDid) return {
3584
3682
  prepared: false,
3585
3683
  result: {
3586
3684
  verified: false,
@@ -3639,15 +3737,24 @@ async function verifyPortableObjectProofPolicy(jsonLd, key, options = {}) {
3639
3737
  * collection without a proof is reported separately so a caller can apply a
3640
3738
  * gateway trust policy. Embedded portable objects are not traversed.
3641
3739
  *
3740
+ * A portable object is a document whose ID is an `ap:` or `ap+ef61:` URI, or
3741
+ * an [FEP-ef61] compatible identifier such as
3742
+ * `https://gw.example/.well-known/apgateway/did:key:z6Mk…/actor`, which
3743
+ * stands for the portable ID `ap+ef61://did:key:z6Mk…/actor`.
3744
+ *
3642
3745
  * Every proof must use a DID URL whose DID matches the portable object's
3643
- * authority, and every proof must pass {@link verifyProof}.
3746
+ * authority, i.e., the DID of its canonical portable ID, and every proof must
3747
+ * pass {@link verifyProof}. The proofs are verified over the document as
3748
+ * given; a compatible identifier is never rewritten into a portable ID.
3749
+ *
3750
+ * [FEP-ef61]: https://w3id.org/fep/ef61
3644
3751
  *
3645
3752
  * @param jsonLd The JSON-LD document to verify.
3646
3753
  * @param options Additional options. See also
3647
3754
  * {@link VerifyPortableObjectProofOptions}.
3648
3755
  * @returns The detailed portable proof-policy result.
3649
3756
  * @throws {TypeError} If the input is not a single JSON-LD object or has a
3650
- * malformed portable ID.
3757
+ * malformed portable ID or compatible identifier.
3651
3758
  * @since 2.4.0
3652
3759
  */
3653
3760
  async function verifyPortableObjectProof(jsonLd, options = {}) {
@@ -3747,7 +3854,7 @@ async function verifyObject(cls, jsonLd, options = {}) {
3747
3854
  };
3748
3855
  const proofDocumentLoader = async (url, loaderOptions) => {
3749
3856
  const remoteDocument = await baseDocumentLoader(url, loaderOptions);
3750
- if (PORTABLE_OBJECT_ID_PATTERN.test(url)) loadedPortableProofs++;
3857
+ if (isPortableId(url)) loadedPortableProofs++;
3751
3858
  const reference = normalizeDocumentUrl(url);
3752
3859
  const candidateIndex = rawProofCandidates.findIndex((candidate, index) => !hydratedCandidates.has(index) && !rawProofCandidatePool.used.has(index) && candidate.reference === reference);
3753
3860
  if (candidateIndex >= 0) {
@@ -3797,11 +3904,13 @@ async function verifyObject(cls, jsonLd, options = {}) {
3797
3904
  return object;
3798
3905
  }
3799
3906
  function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
3800
- const controllerHasCryptographicOrigin = hasCryptographicOrigin(controllerId.href);
3801
- const verificationMethodMatchesController = controllerHasCryptographicOrigin && hasCryptographicOrigin(verificationMethodId.href) && haveSameFe34Origin(controllerId, verificationMethodId);
3802
- if (!controllerHasCryptographicOrigin || verificationMethodMatchesController) attributions.delete(controllerId.href);
3803
- if (!verificationMethodMatchesController) return;
3804
- for (const attribution of [...attributions]) if (hasCryptographicOrigin(attribution) && haveSameFe34Origin(controllerId, attribution)) attributions.delete(attribution);
3907
+ if (!hasCryptographicOrigin(controllerId.href) && !isPortableId(controllerId)) {
3908
+ attributions.delete(controllerId.href);
3909
+ return;
3910
+ }
3911
+ const did = getPortableDid(controllerId);
3912
+ if (did == null || !hasCryptographicOrigin(verificationMethodId.href) || getPortableDid(verificationMethodId) !== did) return;
3913
+ for (const attribution of [...attributions]) if ((hasCryptographicOrigin(attribution) || isPortableId(attribution)) && getPortableDid(attribution) === did) attributions.delete(attribution);
3805
3914
  }
3806
3915
  function hasCryptographicOrigin(iri) {
3807
3916
  return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
@@ -3820,13 +3929,19 @@ const SEC = "https://w3id.org/security#";
3820
3929
  *
3821
3930
  * A gateway key is accepted only if:
3822
3931
  *
3823
- * - the document is an actor whose portable ID is the one the key ID is
3824
- * the compatible identifier of;
3932
+ * - the document is an actor whose portable ID, i.e., its `ap:` ID or
3933
+ * the canonical portable ID of its compatible identifier, is the one
3934
+ * the key ID is the compatible identifier of;
3825
3935
  * - the document has a valid [FEP-8b32] Object Integrity Proof made by
3826
3936
  * the DID of its ID, i.e., it satisfies the [FEP-ef61] proof policy;
3827
3937
  * - the document embeds a `Multikey` with that ID in its `assertionMethod`,
3828
- * whose `controller` is the actor, as [FEP-521a] requires; a key
3829
- * embedded in its `publicKey` with the same ID must agree with it; and
3938
+ * whose `controller` is the actor, as [FEP-521a] requires, and a key
3939
+ * embedded in its `publicKey` with the same ID agrees with it; or, if
3940
+ * no `assertionMethod` entry has that ID, the document embeds
3941
+ * a `CryptographicKey` with that ID in its `publicKey`, whose `owner` is
3942
+ * the actor, as some publishers, e.g., tootik, list their RSA keys only
3943
+ * there;
3944
+ * - no more than one entry of either property has that ID; and
3830
3945
  * - the key ID's origin is one of the actor's `gateways`.
3831
3946
  *
3832
3947
  * [FEP-8b32]: https://w3id.org/fep/8b32
@@ -3875,6 +3990,21 @@ async function verifyPortableGatewayKeyDocument(document, actor, keyId, options
3875
3990
  if (!result.verified) return reject("The actor document does not satisfy the FEP-ef61 proof policy: " + result.reason.type);
3876
3991
  if (root == null) return reject("The actor document could not be expanded.");
3877
3992
  const refuse = (url) => Promise.reject(/* @__PURE__ */ new Error(`Refusing to fetch ${url}.`));
3993
+ const parseEmbeddedPublicKey = async (node) => {
3994
+ if (isReference(node)) return null;
3995
+ let key;
3996
+ try {
3997
+ key = await CryptographicKey.fromJsonLd(node, {
3998
+ documentLoader: refuse,
3999
+ contextLoader: options.contextLoader,
4000
+ tracerProvider: options.tracerProvider
4001
+ });
4002
+ } catch (error) {
4003
+ if (!(error instanceof TypeError)) throw error;
4004
+ return null;
4005
+ }
4006
+ return key.publicKey == null ? null : key;
4007
+ };
3878
4008
  let verifiedActor;
3879
4009
  try {
3880
4010
  verifiedActor = await Object$1.fromJsonLd(root, {
@@ -3888,41 +4018,42 @@ async function verifyPortableGatewayKeyDocument(document, actor, keyId, options
3888
4018
  }
3889
4019
  if (!isPortableActorDocument(verifiedActor) || getCanonicalPortableId(verifiedActor.id) !== claimedActorId) return reject("The key ID is not a compatible identifier of the actor whose document is signed.");
3890
4020
  actor = verifiedActor;
3891
- const multikeyNode = findEmbeddedNode(root[`${SEC}assertionMethod`], keyId);
3892
- if (multikeyNode == null) return reject("The actor document does not embed the key in its assertionMethod.");
3893
- let multikey;
3894
- try {
3895
- multikey = await Multikey.fromJsonLd(multikeyNode, {
3896
- documentLoader: refuse,
3897
- contextLoader: options.contextLoader,
3898
- tracerProvider: options.tracerProvider
3899
- });
3900
- } catch (error) {
3901
- if (!(error instanceof TypeError)) throw error;
3902
- return reject("The key in the assertionMethod is malformed.");
3903
- }
3904
- if (multikey.publicKey == null) return reject("The key in the assertionMethod has no public key.");
3905
- if (multikey.controllerId == null || getCanonicalPortableId(multikey.controllerId) !== actorId) return reject("The controller of the key is not the actor.");
3906
- const publicKeyNode = findEmbeddedNode(root[`${SEC}publicKey`], keyId);
3907
- if (publicKeyNode != null) {
3908
- let publicKey;
4021
+ const assertionNodes = findNodes(root[`${SEC}assertionMethod`], keyId);
4022
+ const publicKeyNodes = findNodes(root[`${SEC}publicKey`], keyId);
4023
+ if (assertionNodes.length > 1 || publicKeyNodes.length > 1) return reject("The actor document has more than one key with the ID.");
4024
+ let publicKey;
4025
+ if (assertionNodes.length > 0) {
4026
+ if (isReference(assertionNodes[0])) return reject("The actor document does not embed the key in its assertionMethod.");
4027
+ let multikey;
3909
4028
  try {
3910
- publicKey = await CryptographicKey.fromJsonLd(publicKeyNode, {
4029
+ multikey = await Multikey.fromJsonLd(assertionNodes[0], {
3911
4030
  documentLoader: refuse,
3912
4031
  contextLoader: options.contextLoader,
3913
4032
  tracerProvider: options.tracerProvider
3914
4033
  });
3915
4034
  } catch (error) {
3916
4035
  if (!(error instanceof TypeError)) throw error;
3917
- return reject("The key in the publicKey is malformed.");
4036
+ return reject("The key in the assertionMethod is malformed.");
3918
4037
  }
3919
- if (publicKey.publicKey == null || !await isSamePublicKey(publicKey.publicKey, multikey.publicKey) || publicKey.ownerId != null && getCanonicalPortableId(publicKey.ownerId) !== actorId) return reject("The key in the publicKey does not agree with the one in the assertionMethod.");
4038
+ if (multikey.publicKey == null) return reject("The key in the assertionMethod has no public key.");
4039
+ if (multikey.controllerId == null || getCanonicalPortableId(multikey.controllerId) !== actorId) return reject("The controller of the key is not the actor.");
4040
+ publicKey = multikey.publicKey;
4041
+ if (publicKeyNodes.length > 0 && !isReference(publicKeyNodes[0])) {
4042
+ const embedded = await parseEmbeddedPublicKey(publicKeyNodes[0]);
4043
+ if (embedded == null || !await isSamePublicKey(embedded.publicKey, publicKey) || embedded.ownerId != null && getCanonicalPortableId(embedded.ownerId) !== actorId) return reject("The key in the publicKey does not agree with the one in the assertionMethod.");
4044
+ }
4045
+ } else {
4046
+ if (publicKeyNodes.length < 1) return reject("The actor document embeds the key in neither its assertionMethod nor its publicKey.");
4047
+ const embedded = await parseEmbeddedPublicKey(publicKeyNodes[0]);
4048
+ if (embedded == null) return reject("The key in the publicKey is not embedded or malformed.");
4049
+ if (embedded.ownerId == null || getCanonicalPortableId(embedded.ownerId) !== actorId) return reject("The owner of the key is not the actor.");
4050
+ publicKey = embedded.publicKey;
3920
4051
  }
3921
4052
  if (!actor.gateways.some((gateway) => isGatewayUrl(gateway) && gateway.origin === keyId.origin)) return reject(`The gateway ${keyId.origin} is not listed in the actor's gateways.`);
3922
4053
  const key = new CryptographicKey({
3923
4054
  id: keyId,
3924
4055
  owner: actor.id,
3925
- publicKey: multikey.publicKey
4056
+ publicKey
3926
4057
  });
3927
4058
  return {
3928
4059
  type: "verified",
@@ -3972,24 +4103,21 @@ async function fetchPortableGatewayKey(keyId, options = {}) {
3972
4103
  contextLoader
3973
4104
  });
3974
4105
  }
3975
- function findEmbeddedNode(values, id) {
3976
- if (!Array.isArray(values)) return null;
4106
+ function findNodes(values, id) {
4107
+ if (!Array.isArray(values)) return [];
4108
+ const nodes = [];
3977
4109
  for (const value of values) {
3978
4110
  if (value == null || typeof value !== "object" || Array.isArray(value)) continue;
3979
4111
  const node = value;
3980
4112
  const nodeId = node["@id"];
3981
- if (typeof nodeId !== "string") continue;
3982
- let parsed;
3983
- try {
3984
- parsed = new URL(nodeId);
3985
- } catch {
3986
- continue;
3987
- }
3988
- if (parsed.href !== id.href) continue;
3989
- if (Object.keys(node).every((key) => key === "@id")) continue;
3990
- return node;
4113
+ if (typeof nodeId !== "string" || !URL.canParse(nodeId)) continue;
4114
+ if (new URL(nodeId).href === id.href) nodes.push(node);
3991
4115
  }
3992
- return null;
4116
+ return nodes;
4117
+ }
4118
+ /** A node with nothing but an `@id` is a reference, not an embedded key. */
4119
+ function isReference(node) {
4120
+ return Object.keys(node).every((key) => key === "@id");
3993
4121
  }
3994
4122
  //#endregion
3995
4123
  //#region src/sig/http.ts
@@ -4180,6 +4308,81 @@ function parseRfc9421Signature(signature) {
4180
4308
  for (const [key, value] of Object.entries(dict)) if (value.value instanceof Uint8Array) result[key] = value.value;
4181
4309
  return result;
4182
4310
  }
4311
+ /**
4312
+ * Parses the `Signature` header of draft-cavage HTTP Signatures into its
4313
+ * fields, e.g., `keyId` and `headers`.
4314
+ */
4315
+ function parseDraftSignature(signature) {
4316
+ return Object.fromEntries(signature.split(",").map((pair) => pair.match(/^\s*([A-Za-z]+)=(?:"([^"]*)"|(\d+))\s*$/)).filter((m) => m != null).map((m) => [m[1], m[2] ?? m[3]]));
4317
+ }
4318
+ /**
4319
+ * Lists the HTTP Signatures that a request claims to carry, without verifying
4320
+ * any of them. Signatures whose key IDs are not URLs are left out.
4321
+ * @param request The request.
4322
+ * @returns The signatures; RFC 9421 ones if the request has
4323
+ * a `Signature-Input` header, or a draft-cavage one otherwise.
4324
+ * @internal
4325
+ */
4326
+ function listRequestSignatures(request) {
4327
+ const signatureInput = request.headers.get("Signature-Input");
4328
+ if (signatureInput != null) {
4329
+ const signatures = [];
4330
+ const inputs = parseRfc9421SignatureInput(signatureInput);
4331
+ for (const [label, input] of Object.entries(inputs)) {
4332
+ const keyId = parseKeyId(input.keyId);
4333
+ if (keyId == null) continue;
4334
+ signatures.push({
4335
+ keyId,
4336
+ label,
4337
+ components: input.components
4338
+ });
4339
+ }
4340
+ return signatures;
4341
+ }
4342
+ const signature = request.headers.get("Signature");
4343
+ if (signature == null) return [];
4344
+ const values = parseDraftSignature(signature);
4345
+ const keyId = parseKeyId(values.keyId);
4346
+ if (keyId == null) return [];
4347
+ return [{
4348
+ keyId,
4349
+ label: null,
4350
+ components: (values.headers ?? "").split(/\s+/g).filter((name) => name !== "").map((name) => ({
4351
+ value: name,
4352
+ params: {}
4353
+ }))
4354
+ }];
4355
+ }
4356
+ /**
4357
+ * Makes a copy of a request that carries only one of its RFC 9421 signatures,
4358
+ * so that verifying the copy verifies that signature and no other.
4359
+ * A draft-cavage signature is the only one in its request, so the request is
4360
+ * just copied.
4361
+ * @param request The request, whose body must not be consumed.
4362
+ * @param signature One of the signatures that {@link listRequestSignatures}
4363
+ * lists for the request.
4364
+ * @returns The copy of the request.
4365
+ * @internal
4366
+ */
4367
+ function selectRequestSignature(request, signature) {
4368
+ const copy = request.clone();
4369
+ if (signature.label == null) return copy;
4370
+ const { label } = signature;
4371
+ const pick = (header) => {
4372
+ if (header == null) return "";
4373
+ let dict;
4374
+ try {
4375
+ dict = decodeDict(header);
4376
+ } catch {
4377
+ return "";
4378
+ }
4379
+ return Object.hasOwn(dict, label) ? encodeDict({ [label]: dict[label] }) : "";
4380
+ };
4381
+ const headers = new Headers(copy.headers);
4382
+ headers.set("Signature-Input", pick(headers.get("Signature-Input")));
4383
+ headers.set("Signature", pick(headers.get("Signature")));
4384
+ return new Request(copy, { headers });
4385
+ }
4183
4386
  async function signRequestRfc9421(request, privateKey, keyId, span, currentTime, bodyBuffer, rfc9421Options) {
4184
4387
  if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
4185
4388
  const url = new URL(request.url);
@@ -4411,7 +4614,7 @@ async function verifyRequestDraft(request, span, metricsContext, { documentLoade
4411
4614
  logger.debug("Failed to verify; no Signature header found.", { headers: Object.fromEntries(request.headers.entries()) });
4412
4615
  return noSignatureResult();
4413
4616
  }
4414
- const sigValues = Object.fromEntries(sigHeader.split(",").map((pair) => pair.match(/^\s*([A-Za-z]+)=(?:"([^"]*)"|(\d+))\s*$/)).filter((m) => m != null).map((m) => [m[1], m[2] ?? m[3]]));
4617
+ const sigValues = parseDraftSignature(sigHeader);
4415
4618
  const parsedKeyId = parseKeyId(sigValues.keyId);
4416
4619
  const dateHeader = request.headers.get("Date");
4417
4620
  if (dateHeader == null) {
@@ -5084,4 +5287,4 @@ function timingSafeEqual(a, b) {
5084
5287
  return result === 0;
5085
5288
  }
5086
5289
  //#endregion
5087
- export { recordCollectionPageItems as $, verifySignature as A, getCanonicalPortableId as B, hasSignature as C, signJsonLd as D, isInvalidUrlTypeError as E, fetchKeyDetailed as F, isSamePublicKey as G, hasPortableActor as H, generateCryptoKeyPair as I, getRemoteHost as J, getDurationMs as K, importJwk as L, exportJwk as M, fetchActorDocument as N, verifyCompactJsonLd as O, fetchKey as P, recordCollectionDispatchDuration as Q, validateCryptoKey as R, getNormalizationContextLoader as S, isClearlyMalformedContextReference as T, isCompatibleKeyId as U, getGatewayKeyBase as V, isPortableUri as W, isAbortError$1 as X, instrumentDocumentLoader as Y, recordCircuitBreakerStateChange as Z, assertSafeJsonLd as _, verifyRequestDetailed as a, recordOutboxActivity as at, createSignature as b, hasProofLike as c, registerQueueDepthGauge as ct, verifyObject as d, fulfillAcceptSignature as dt, recordCollectionRequest as et, verifyPortableObjectProof as f, parseAcceptSignature as ft, InvalidContextReferenceError as g, verifyProof as h, version as ht, verifyRequest as i, recordInboxActivity as it, wrapContextLoaderForJsonLd as j, verifyJsonLd as k, signObject as l, normalizeOutgoingActivityJsonLd as lt, verifyPortableObjectProofWithRoot as m, name as mt, parseRfc9421SignatureInput as n, recordDocumentCache as nt, fetchPortableGatewayKey as o, recordOutboxEnqueue as ot, verifyPortableObjectProofPolicy as p, validateAcceptSignature as pt, getFederationMetrics as q, signRequest as r, recordFanoutRecipients as rt, createProof as s, recordWebFingerHandle as st, doubleKnock as t, recordCollectionTotalItems as tt, verifyMapLocalProof as u, formatAcceptSignature as ut, attachSignature as v, hasSignatureLike as w, detachSignature as x, compactJsonLd as y, verifyKeyOwnership as z };
5290
+ export { recordCollectionTotalItems as $, isInvalidUrlTypeError as A, generateCryptoKeyPair as B, compactJsonLd as C, hasSignature as D, getNormalizationContextLoader as E, wrapContextLoaderForJsonLd as F, getFederationMetrics as G, validateCryptoKey as H, exportJwk as I, isAbortError$1 as J, getRemoteHost as K, fetchActorDocument as L, verifyCompactJsonLd as M, verifyJsonLd as N, hasSignatureLike as O, verifySignature as P, recordCollectionRequest as Q, fetchKey as R, attachSignature as S, detachSignature as T, verifyKeyOwnership as U, importJwk as V, getDurationMs as W, recordCollectionDispatchDuration as X, recordCircuitBreakerStateChange as Y, recordCollectionPageItems as Z, verifyPortableObjectProofWithRoot as _, isPortableId as _t, signRequest as a, recordWebFingerHandle as at, InvalidContextReferenceError as b, name as bt, fetchPortableGatewayKey as c, formatAcceptSignature as ct, hasProofLike as d, validateAcceptSignature as dt, recordDocumentCache as et, signObject as f, getCanonicalPortableId as ft, verifyPortableObjectProofPolicy as g, isCompatibleKeyId as gt, verifyPortableObjectProof as h, hasPortableActor as ht, selectRequestSignature as i, recordOutboxEnqueue as it, signJsonLd as j, isClearlyMalformedContextReference as k, InvalidPortableObjectIdError as l, fulfillAcceptSignature as lt, verifyObject as m, getPortableDid as mt, listRequestSignatures as n, recordInboxActivity as nt, verifyRequest as o, registerQueueDepthGauge as ot, verifyMapLocalProof as p, getGatewayKeyBase as pt, instrumentDocumentLoader as q, parseRfc9421SignatureInput as r, recordOutboxActivity as rt, verifyRequestDetailed as s, preloadedOnlyDocumentLoader as st, doubleKnock as t, recordFanoutRecipients as tt, createProof as u, parseAcceptSignature as ut, verifyProof as v, isPortableUri as vt, createSignature as w, assertSafeJsonLd as x, version as xt, normalizeOutgoingActivityJsonLd as y, isSamePublicKey as yt, fetchKeyDetailed as z };