@fedify/fedify 2.3.16-dev.2841 → 2.3.16

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 (108) hide show
  1. package/dist/attachment-arrays-BlfpZlWF.mjs +16 -0
  2. package/dist/{builder-G4wSHQX-.mjs → builder-D4GE1Gmi.mjs} +3 -3
  3. package/dist/callback-kR_sx2zZ.d.mts +2661 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-jE7oGvRh.d.ts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-DpUNYKla.mjs → client-DFgYVbUA.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +255 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  12. package/dist/compat/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-CE_Tj_Oc.d.cts → context-CEE8vl-b.d.cts} +31 -14
  15. package/dist/{context-H_5tZXg-.d.ts → context-CTJwXHRu.d.ts} +31 -14
  16. package/dist/{deno-DmDVx5sE.mjs → deno-FtdqgHJA.mjs} +1 -1
  17. package/dist/{docloader-0fjyUmvI.mjs → docloader-B9iU4DP2.mjs} +2 -2
  18. package/dist/federation/attachment-responses.test.d.mts +2 -0
  19. package/dist/federation/attachment-responses.test.mjs +182 -0
  20. package/dist/federation/builder.test.mjs +1 -1
  21. package/dist/federation/circuit-breaker.test.mjs +2 -2
  22. package/dist/federation/collection.test.mjs +1 -1
  23. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  24. package/dist/federation/delivery-attachments.test.mjs +288 -0
  25. package/dist/federation/handler.test.mjs +208 -16
  26. package/dist/federation/idempotency.test.mjs +2 -2
  27. package/dist/federation/inbox.test.mjs +2 -2
  28. package/dist/federation/metrics.test.mjs +1 -1
  29. package/dist/federation/middleware.test.mjs +1191 -16
  30. package/dist/federation/mod.cjs +1 -1
  31. package/dist/federation/mod.d.cts +2 -2
  32. package/dist/federation/mod.d.ts +2 -2
  33. package/dist/federation/mod.js +1 -1
  34. package/dist/federation/negotiation.test.mjs +1 -1
  35. package/dist/federation/retry.test.mjs +1 -1
  36. package/dist/federation/send.test.mjs +293 -3
  37. package/dist/federation/temporal.test.mjs +25 -1
  38. package/dist/federation/webfinger.test.mjs +1 -1
  39. package/dist/{http-CKX94hfh.cjs → http-2RyDQ0tE.cjs} +6 -4
  40. package/dist/{http-DmP0sr2l.d.ts → http-Bs5mXWlH.d.ts} +3 -3
  41. package/dist/{http-CZPYFK3b.d.cts → http-D8DgRhHU.d.cts} +3 -3
  42. package/dist/{http-DCK-QQfE.mjs → http-D8tiOrZf.mjs} +7 -5
  43. package/dist/{http-DwIMsxu9.js → http-mLeLYFj-.js} +6 -4
  44. package/dist/{inbox-Bx6PCMeE.mjs → inbox-Dy8awbi8.mjs} +2 -2
  45. package/dist/{key-SkLDUmPM.mjs → key-o1SmN5s0.mjs} +4 -3
  46. package/dist/{kv-cache-BaJOO6O3.mjs → kv-cache-BwUrzCVO.mjs} +1 -1
  47. package/dist/{kv-cache-BnZ4KLMY.cjs → kv-cache-CI6Z0WiS.cjs} +1 -1
  48. package/dist/{kv-cache-xIexNacM.js → kv-cache-Dsq8C8D8.js} +1 -1
  49. package/dist/{ld-DUG6cq9q.mjs → ld-DCKrqj9y.mjs} +155 -22
  50. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  51. package/dist/{metrics-D3OnAgfj.mjs → metrics-CaoYRhNH.mjs} +1 -1
  52. package/dist/{middleware-CUwjLKp3.mjs → middleware-4p3opEMT.mjs} +1 -1
  53. package/dist/{middleware-C9RexCTx.cjs → middleware-CP-8P7kk.cjs} +492 -117
  54. package/dist/{middleware-DU2jy5eY.js → middleware-Cce0nLDw.js} +491 -117
  55. package/dist/{middleware-zEy-wJYI.mjs → middleware-D31fNcY4.mjs} +399 -109
  56. package/dist/{mod-C_gFmeNq.d.cts → mod-BD0-_vya.d.ts} +31 -13
  57. package/dist/{mod-HQXFvOHs.d.ts → mod-BMX6nsHP.d.cts} +31 -13
  58. package/dist/{mod-CDFFESfL.d.ts → mod-BTvP5Hva.d.ts} +1 -1
  59. package/dist/{mod-DMjhnFbg.d.ts → mod-DgMTlwUO.d.ts} +3 -3
  60. package/dist/{mod-DDVkmZ_h.d.cts → mod-Q1Fo3FJk.d.cts} +3 -3
  61. package/dist/{mod-DDjtbkZO.d.cts → mod-n51LED4J.d.cts} +1 -1
  62. package/dist/mod.cjs +5 -5
  63. package/dist/mod.d.cts +8 -8
  64. package/dist/mod.d.ts +8 -8
  65. package/dist/mod.js +5 -5
  66. package/dist/nodeinfo/client.test.mjs +432 -4
  67. package/dist/nodeinfo/handler.test.mjs +1 -1
  68. package/dist/nodeinfo/mod.cjs +1 -1
  69. package/dist/nodeinfo/mod.d.cts +1 -1
  70. package/dist/nodeinfo/mod.d.ts +1 -1
  71. package/dist/nodeinfo/mod.js +1 -1
  72. package/dist/nodeinfo/types.test.mjs +1 -1
  73. package/dist/{outgoing-jsonld-D4iTv7uM.mjs → outgoing-jsonld-BZEAVK_Q.mjs} +38 -8
  74. package/dist/{owner-Baf_LRb2.mjs → owner-Bdj0nHhf.mjs} +2 -2
  75. package/dist/{proof-CNGy7TJL.js → proof-B9XJiyz-.js} +1030 -858
  76. package/dist/{proof-BdAFbOFg.cjs → proof-CmcP8yqP.cjs} +1243 -1059
  77. package/dist/{proof-LTsbjXnQ.mjs → proof-DrbjYma9.mjs} +41 -16
  78. package/dist/{send-DOf5y1nB.mjs → send-VD_WG3dN.mjs} +100 -22
  79. package/dist/sig/http.test.mjs +2 -2
  80. package/dist/sig/key-types.test.d.mts +218 -0
  81. package/dist/sig/key-types.test.mjs +8 -0
  82. package/dist/sig/key.test.mjs +2 -2
  83. package/dist/sig/ld.test.mjs +573 -8
  84. package/dist/sig/mod.cjs +2 -2
  85. package/dist/sig/mod.d.cts +3 -3
  86. package/dist/sig/mod.d.ts +3 -3
  87. package/dist/sig/mod.js +2 -2
  88. package/dist/sig/owner.test.mjs +1 -1
  89. package/dist/sig/proof.test.mjs +96 -4
  90. package/dist/{temporal-fl4sM1Gs.mjs → temporal-CMvoB-vD.mjs} +3 -5
  91. package/dist/testing/mod.d.mts +2 -2476
  92. package/dist/{types-DOvyymM4.cjs → types-BWx7zw3Y.cjs} +85 -10
  93. package/dist/{types-B1_pRFE_.js → types-Dx_w2JSM.js} +86 -11
  94. package/dist/utils/docloader.test.mjs +2 -2
  95. package/dist/utils/kv-cache.test.mjs +1 -1
  96. package/dist/utils/mod.cjs +1 -1
  97. package/dist/utils/mod.d.cts +1 -1
  98. package/dist/utils/mod.d.ts +1 -1
  99. package/dist/utils/mod.js +1 -1
  100. package/package.json +7 -7
  101. /package/dist/{activity-listener-tztVvlNb.mjs → activity-listener-BeTGV3wc.mjs} +0 -0
  102. /package/dist/{circuit-breaker-D1fxthDI.mjs → circuit-breaker-B1fLHmg2.mjs} +0 -0
  103. /package/dist/{circuit-breaker-test-utils-CAdwjgMi.mjs → circuit-breaker-test-utils-BGHm_MsT.mjs} +0 -0
  104. /package/dist/{collection-Cc3DVAhE.mjs → collection-Dp5ky45w.mjs} +0 -0
  105. /package/dist/{negotiation-DDstyBvc.mjs → negotiation-DC8nG6J_.mjs} +0 -0
  106. /package/dist/{public-audience-Dp4ZScSr.mjs → public-audience-rnYUGj8a.mjs} +0 -0
  107. /package/dist/{retry-CXg_MBI-.mjs → retry-C4G_vIgv.mjs} +0 -0
  108. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -1,1172 +1,1320 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  const require_chunk = require("./chunk-DDcVe30Y.cjs");
4
- const require_http = require("./http-CKX94hfh.cjs");
4
+ const require_http = require("./http-2RyDQ0tE.cjs");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  let _fedify_vocab = require("@fedify/vocab");
7
7
  let _opentelemetry_api = require("@opentelemetry/api");
8
8
  let byte_encodings_hex = require("byte-encodings/hex");
9
9
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
10
- let byte_encodings_base64 = require("byte-encodings/base64");
11
10
  let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
12
11
  _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld, 1);
12
+ let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
13
+ let byte_encodings_base64 = require("byte-encodings/base64");
13
14
  let json_canon = require("json-canon");
14
15
  json_canon = require_chunk.__toESM(json_canon, 1);
15
- //#region src/sig/ld.ts
16
+ //#region src/compat/preloaded-context-loader.ts
17
+ /**
18
+ * A restricted JSON-LD document loader that resolves only contexts bundled
19
+ * with Fedify.
20
+ *
21
+ * This is intentionally narrower than `getDocumentLoader()`: normalization
22
+ * helpers are also reached from verification paths that operate on inbound,
23
+ * attacker-controlled JSON-LD, so the default fallback must never fetch
24
+ * attacker-supplied context URLs.
25
+ */
26
+ const preloadedOnlyDocumentLoader = (url) => {
27
+ if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
28
+ contextUrl: null,
29
+ documentUrl: url,
30
+ document: _fedify_vocab_runtime.preloadedContexts[url]
31
+ });
32
+ return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
33
+ };
34
+ //#endregion
35
+ //#region src/compat/public-audience.ts
16
36
  const logger$4 = (0, _logtape_logtape.getLogger)([
17
37
  "fedify",
18
- "sig",
19
- "ld"
38
+ "compat",
39
+ "public-audience"
20
40
  ]);
21
- const localContext = [
22
- "https://w3id.org/identity/v1",
23
- "https://www.w3.org/ns/activitystreams",
24
- "https://w3id.org/security/v1",
25
- "https://w3id.org/security/data-integrity/v1"
26
- ];
27
- const localContextUrls = new Set(localContext);
28
- const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
29
- const disallowedJsonLdKeywords = new Set([
30
- "@graph",
31
- "@included",
32
- "@reverse"
41
+ const PUBLIC_ADDRESSING_FIELDS = new Set([
42
+ "to",
43
+ "cc",
44
+ "bto",
45
+ "bcc",
46
+ "audience"
33
47
  ]);
34
- /** @internal */
35
- var UnsafeJsonLdError = class extends TypeError {
36
- keyword;
37
- constructor(keyword) {
38
- super(`Unsupported JSON-LD keyword: ${keyword}.`);
39
- this.keyword = keyword;
40
- this.name = "UnsafeJsonLdError";
41
- }
42
- };
43
- /** @internal */
44
- var InvalidContextReferenceError = class extends TypeError {
45
- reference;
46
- constructor(reference) {
47
- super(`Invalid JSON-LD context reference: ${reference}.`);
48
- this.reference = reference;
49
- this.name = "InvalidContextReferenceError";
48
+ const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
49
+ const MAX_TRAVERSAL_DEPTH$1 = 64;
50
+ const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
51
+ function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
52
+ if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
53
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
54
+ if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
55
+ if (typeof value !== "object" || value == null) return false;
56
+ const record = value;
57
+ for (const key of Object.keys(record)) {
58
+ if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
59
+ if (key === "@context") continue;
60
+ if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
50
61
  }
51
- };
52
- function createLoadingRemoteContextFailedError(reference, cause) {
53
- const message = cause instanceof Error ? cause.message : String(cause);
54
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
55
- error.name = "jsonld.InvalidUrl";
56
- error.details = {
57
- code: "loading remote context failed",
58
- url: reference
59
- };
60
- error.cause = cause;
61
- return error;
62
+ return false;
62
63
  }
63
- /** @internal */
64
- function isClearlyMalformedContextReference(reference) {
65
- for (const char of reference) {
66
- const code = char.charCodeAt(0);
67
- if (code <= 32 || code === 127) return true;
64
+ function rewritePublicAudience(value, parentKey, depth = 0) {
65
+ if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
66
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
67
+ if (Array.isArray(value)) {
68
+ let changed = false;
69
+ const mapped = value.map((item) => {
70
+ const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
71
+ if (rewritten !== item) changed = true;
72
+ return rewritten;
73
+ });
74
+ return changed ? mapped : value;
68
75
  }
69
- if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
70
- for (let i = 0; i < reference.length; i++) {
71
- if (reference[i] !== "%") continue;
72
- if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
73
- i += 2;
76
+ if (typeof value !== "object" || value == null) return value;
77
+ const record = value;
78
+ let changed = false;
79
+ const normalized = Object.create(null);
80
+ for (const key of Object.keys(record)) {
81
+ const rewritten = key === "@context" ? record[key] : record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public") ? _fedify_vocab.PUBLIC_COLLECTION.href : rewritePublicAudience(record[key], key, depth + 1);
82
+ if (rewritten !== record[key]) changed = true;
83
+ normalized[key] = rewritten;
74
84
  }
75
- if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
76
- for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
85
+ return changed ? normalized : value;
86
+ }
87
+ /**
88
+ * Reports whether `value` carries an `@context` property anywhere inside
89
+ * its subtree (not counting the value itself). A nested `@context` can
90
+ * introduce a local term-definition scope that redefines `as:` or `Public`
91
+ * even when the top-level `@context` is safe, so the fast path must defer
92
+ * to the URDNA2015 equivalence check whenever one is present.
93
+ */
94
+ function hasNestedContext$1(value, depth = 0) {
95
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
96
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
97
+ if (typeof value !== "object" || value == null) return false;
98
+ const record = value;
99
+ for (const key of Object.keys(record)) {
100
+ if (key === "@context") return true;
101
+ if (hasNestedContext$1(record[key], depth + 1)) return true;
77
102
  }
78
103
  return false;
79
104
  }
80
- function cloneRemoteDocument(remoteDocument) {
81
- return structuredClone(remoteDocument);
82
- }
83
- function createMemoizedDocumentLoader(documentLoader) {
84
- const cache = /* @__PURE__ */ new Map();
85
- return async (url, options) => {
86
- const cacheKey = URL.canParse(url) ? new URL(url).href : url;
87
- let remoteDocument = cache.get(cacheKey);
88
- if (remoteDocument == null) {
89
- remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
90
- remoteDocument.catch(() => {
91
- if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
92
- });
93
- cache.set(cacheKey, remoteDocument);
94
- }
95
- return cloneRemoteDocument(await remoteDocument);
96
- };
105
+ /**
106
+ * Checks whether the `@context` of a JSON-LD document is guaranteed not
107
+ * to redefine the `as:` prefix or the bare `Public` term. Only documents
108
+ * whose `@context` is a string, or an array of strings, drawn from Fedify's
109
+ * preloaded context set AND including the ActivityStreams URL qualify,
110
+ * AND no nested subtree carries its own `@context` that might redefine
111
+ * those terms within a local scope. When all of that holds the rewrite
112
+ * is provably semantics-preserving and the URDNA2015 equivalence check
113
+ * can be skipped. Any other shape (unknown external URLs, inline
114
+ * objects at the top level, nested `@context` blocks) is treated as
115
+ * potentially unsafe.
116
+ */
117
+ function hasKnownSafeContext$1(jsonLd) {
118
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
119
+ const record = jsonLd;
120
+ if (!Object.hasOwn(record, "@context")) return false;
121
+ const ctx = record["@context"];
122
+ const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
123
+ if (entries == null || entries.length === 0) return false;
124
+ let hasAs = false;
125
+ for (const entry of entries) {
126
+ if (typeof entry !== "string") return false;
127
+ if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
128
+ if (entry === AS_CONTEXT_URL$1) hasAs = true;
129
+ }
130
+ if (!hasAs) return false;
131
+ for (const key of Object.keys(record)) {
132
+ if (key === "@context") continue;
133
+ if (hasNestedContext$1(record[key])) return false;
134
+ }
135
+ return true;
97
136
  }
98
- /** @internal */
99
- function wrapContextLoaderForJsonLd(contextLoader) {
100
- const loader = contextLoader ?? builtInContextLoader;
101
- return async (url, options) => {
102
- try {
103
- return await loader(url, options);
104
- } catch (error) {
105
- if (!isInvalidUrlTypeError(error)) throw error;
106
- if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
107
- throw createLoadingRemoteContextFailedError(url, error);
108
- }
109
- };
137
+ /**
138
+ * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
139
+ * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
140
+ * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
141
+ *
142
+ * Several ActivityPub implementations, Lemmy among them, match these
143
+ * fields as plain URLs without running JSON-LD expansion, and silently
144
+ * drop activities whose public addressing appears in CURIE form. This
145
+ * helper works around that gap.
146
+ *
147
+ * For documents whose `@context` is drawn entirely from Fedify's
148
+ * preloaded context set and includes the ActivityStreams URL, the
149
+ * rewrite is applied directly: the content of every preloaded non-AS
150
+ * context is known not to redefine the `as:` prefix or the bare `Public`
151
+ * term, so the semantics are preserved by construction. Any other
152
+ * shape (an inline object, an unknown external URL, and so on) is
153
+ * treated as potentially unsafe and gated on a JSON-LD equivalence
154
+ * check; both forms are canonicalized with URDNA2015 and the resulting
155
+ * N-Quads are compared. When they differ, the original document is
156
+ * returned unchanged. Canonicalization failures also fall back to the
157
+ * original document.
158
+ *
159
+ * When no `contextLoader` is supplied the helper falls back to an
160
+ * internal loader that resolves only the URLs in Fedify's
161
+ * preloaded-contexts set and rejects every other URL without issuing a
162
+ * network request. That behaviour is deliberately narrower than
163
+ * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
164
+ * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
165
+ * helper is reached from verification paths (`verifyProof()` /
166
+ * `verifyObject()`) that operate on inbound, potentially adversarial
167
+ * JSON-LD, and a default loader that fetches attacker-supplied
168
+ * `@context` URLs on the caller's behalf would be an SSRF vector.
169
+ * Canonicalization failures against the restricted loader fall back to
170
+ * the original document, same as any other canonicalization error.
171
+ * Callers that genuinely need the remote-fetch loader (for example
172
+ * applications that sign local JSON-LD against a custom vocabulary)
173
+ * should pass a `contextLoader` explicitly.
174
+ *
175
+ * Must be called before any signing step that canonicalizes the
176
+ * compact form byte-for-byte (for example, Object Integrity Proofs
177
+ * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
178
+ * matches what is sent on the wire.
179
+ */
180
+ async function normalizePublicAudience(jsonLd, contextLoader) {
181
+ if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
182
+ const normalized = rewritePublicAudience(jsonLd);
183
+ if (hasKnownSafeContext$1(jsonLd)) return normalized;
184
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
185
+ try {
186
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
187
+ format: "application/n-quads",
188
+ documentLoader: loader
189
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
190
+ format: "application/n-quads",
191
+ documentLoader: loader
192
+ })]);
193
+ if (before === after) return normalized;
194
+ 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.");
195
+ } catch (error) {
196
+ logger$4.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
197
+ }
198
+ return jsonLd;
110
199
  }
111
- /** @internal */
112
- function getNormalizationContextLoader(contextLoader) {
113
- const loader = wrapContextLoaderForJsonLd(contextLoader);
114
- return createMemoizedDocumentLoader(async (url, options) => {
115
- if (URL.canParse(url)) {
116
- const normalizedUrl = new URL(url).href;
117
- if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
118
- }
119
- return await loader(url, options);
120
- });
121
- }
122
- /** @internal */
123
- async function compactJsonLd(jsonLd, contextLoader) {
124
- const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
125
- const signature = hasLds ? jsonLd.signature : void 0;
126
- const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
127
- const document = hasLds ? detachSignature(jsonLd) : jsonLd;
128
- await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
129
- const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
130
- if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
131
- assertSafeJsonLd(compacted);
132
- return compacted;
133
- }
134
- function createInvalidRemoteContextError(reference) {
135
- 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}".`);
136
- error.name = "jsonld.InvalidUrl";
137
- error.details = {
138
- code: "invalid remote context",
139
- url: reference
140
- };
141
- return error;
142
- }
143
- function getRemoteContext(remoteDocument, reference) {
144
- const { contextUrl, documentUrl } = remoteDocument;
145
- let { document } = remoteDocument;
146
- if (typeof document === "string") document = JSON.parse(document);
147
- if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
148
- let context = "@context" in document ? document["@context"] : {};
149
- if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
150
- return {
151
- context,
152
- baseUrl: documentUrl ?? reference
153
- };
154
- }
155
- function createGraphAliasContextState() {
156
- return {
157
- graphTerms: /* @__PURE__ */ new Set(),
158
- jsonTerms: /* @__PURE__ */ new Set(),
159
- propertyContexts: /* @__PURE__ */ new Map(),
160
- termTargets: /* @__PURE__ */ new Map()
161
- };
162
- }
163
- function cloneGraphAliasContextState(state) {
164
- return {
165
- graphTerms: new Set(state.graphTerms),
166
- jsonTerms: new Set(state.jsonTerms),
167
- propertyContexts: new Map(state.propertyContexts),
168
- termTargets: new Map(state.termTargets)
169
- };
200
+ //#endregion
201
+ //#region src/compat/outgoing-jsonld.ts
202
+ const logger$3 = (0, _logtape_logtape.getLogger)([
203
+ "fedify",
204
+ "compat",
205
+ "outgoing-jsonld"
206
+ ]);
207
+ const ATTACHMENT_FIELDS = new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
208
+ const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
209
+ const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
210
+ const MAX_TRAVERSAL_DEPTH = 64;
211
+ function isJsonLdListObject(value) {
212
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
170
213
  }
171
- function resolveContextTarget(target, state) {
172
- if (target === "@graph") return target;
173
- const mapped = state.termTargets.get(target);
174
- if (mapped == null) return target;
175
- return mapped;
214
+ function isJsonLdValueObject(value) {
215
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
176
216
  }
177
- function getDirectContextTarget(definition) {
178
- if (definition === null) return null;
179
- if (typeof definition === "string") return definition;
180
- if (typeof definition === "object" && definition != null && "@id" in definition) {
181
- const id = definition["@id"];
182
- if (id === null) return null;
183
- if (typeof id === "string") return id;
217
+ function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
218
+ if (Array.isArray(value)) {
219
+ if (seen.has(value)) return;
220
+ seen.add(value);
221
+ for (const item of value) yield* getContextObjects(item, seen);
222
+ return;
184
223
  }
185
- }
186
- function isJsonTypedDefinition(definition) {
187
- return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
188
- }
189
- function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
190
- if (target === "@graph") return target;
191
- if (seen.has(target)) return target;
192
- seen.add(target);
193
- if (localTargets.has(target)) {
194
- const localTarget = localTargets.get(target);
195
- return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
224
+ if (typeof value === "object" && value != null) {
225
+ if (seen.has(value)) return;
226
+ seen.add(value);
227
+ const record = value;
228
+ yield record;
229
+ for (const definition of Object.values(record)) {
230
+ if (typeof definition !== "object" || definition == null) continue;
231
+ const nestedContext = definition["@context"];
232
+ if (nestedContext == null) continue;
233
+ yield* getContextObjects(nestedContext, seen);
234
+ }
196
235
  }
197
- return resolveContextTarget(target, state);
198
- }
199
- function refreshGraphAliases(state) {
200
- state.graphTerms.clear();
201
- for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
202
236
  }
203
- function normalizeContextReference(reference, baseUrl) {
204
- if (baseUrl != null) return new URL(reference, baseUrl).href;
205
- return URL.canParse(reference) ? new URL(reference).href : reference;
237
+ function isActivityStreamsAttachmentTerm(value) {
238
+ return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
206
239
  }
207
240
  /** @internal */
208
- function isInvalidUrlTypeError(error) {
209
- const code = error.code;
210
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || error.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
211
- }
212
- async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
213
- if (context === null) return createGraphAliasContextState();
214
- let nextState = cloneGraphAliasContextState(state);
215
- if (Array.isArray(context)) {
216
- for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
217
- return nextState;
241
+ function isPreloadedContextAttachmentSafe(document) {
242
+ if (typeof document !== "object" || document == null) return true;
243
+ const context = document["@context"];
244
+ for (const contextObject of getContextObjects(context)) {
245
+ if (!Object.hasOwn(contextObject, "attachment")) continue;
246
+ if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
247
+ return false;
218
248
  }
219
- if (typeof context === "string") {
220
- const reference = normalizeContextReference(context, baseUrl);
221
- const cacheKey = `${baseUrl ?? ""}\n${reference}`;
222
- if (processingContexts.has(cacheKey)) return nextState;
223
- processingContexts.add(cacheKey);
224
- try {
225
- let remoteContext = remoteContextCache.get(cacheKey);
226
- if (remoteContext == null) {
227
- remoteContext = (async () => {
228
- try {
229
- return getRemoteContext(await documentLoader(reference), reference);
230
- } catch (error) {
231
- if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
232
- throw error;
233
- }
234
- })();
235
- remoteContextCache.set(cacheKey, remoteContext);
236
- }
237
- const loadedRemoteContext = await remoteContext;
238
- return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
239
- } finally {
240
- processingContexts.delete(cacheKey);
249
+ return true;
250
+ }
251
+ function getKnownSafeContextUrls() {
252
+ const urls = /* @__PURE__ */ new Set();
253
+ for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
254
+ 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 });
255
+ return urls;
256
+ }
257
+ /**
258
+ * Wraps scalar ActivityStreams attachment properties in arrays.
259
+ */
260
+ function wrapScalarAttachments(jsonLd, depth = 0) {
261
+ if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
262
+ if (Array.isArray(jsonLd)) {
263
+ let normalized = null;
264
+ for (let i = 0; i < jsonLd.length; i++) {
265
+ const item = jsonLd[i];
266
+ const next = wrapScalarAttachments(item, depth + 1);
267
+ if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
268
+ if (normalized != null) normalized[i] = next;
241
269
  }
270
+ return normalized ?? jsonLd;
242
271
  }
243
- if (typeof context === "object" && context != null) {
244
- if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
245
- const localTargets = /* @__PURE__ */ new Map();
246
- for (const [term, definition] of globalThis.Object.entries(context)) {
247
- if (term.startsWith("@")) continue;
248
- const target = getDirectContextTarget(definition);
249
- if (target == null) localTargets.set(term, null);
250
- else if (typeof target === "string") localTargets.set(term, target);
251
- else localTargets.delete(term);
252
- }
253
- for (const [term, definition] of globalThis.Object.entries(context)) {
254
- if (term.startsWith("@")) continue;
255
- if (localTargets.has(term)) {
256
- const directTarget = localTargets.get(term);
257
- if (directTarget == null) nextState.termTargets.set(term, null);
258
- else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
259
- } else nextState.termTargets.delete(term);
260
- if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
261
- context: definition["@context"],
262
- baseUrl
263
- });
264
- else nextState.propertyContexts.delete(term);
265
- if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
266
- else nextState.jsonTerms.delete(term);
272
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
273
+ const record = jsonLd;
274
+ const keys = Object.keys(record);
275
+ let normalized = null;
276
+ for (let i = 0; i < keys.length; i++) {
277
+ const key = keys[i];
278
+ const value = record[key];
279
+ const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
280
+ const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
281
+ if (normalized == null && output !== value) {
282
+ const cloned = Object.create(null);
283
+ for (let j = 0; j < i; j++) {
284
+ const previousKey = keys[j];
285
+ cloned[previousKey] = record[previousKey];
286
+ }
287
+ normalized = cloned;
267
288
  }
268
- refreshGraphAliases(nextState);
289
+ if (normalized != null) normalized[key] = output;
269
290
  }
270
- return nextState;
291
+ return normalized ?? jsonLd;
271
292
  }
272
- async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
273
- if (Array.isArray(jsonLd)) {
274
- for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
275
- return;
276
- }
277
- if (typeof jsonLd !== "object" || jsonLd == null) return;
278
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
279
- let state = inheritedState;
280
- if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
281
- if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
282
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
283
- if (key === "@context") continue;
284
- if (jsonLiteralWrapper && key === "@value") continue;
285
- if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
286
- if (state.jsonTerms.has(key)) continue;
287
- await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
293
+ function hasNestedContext(value, depth = 0) {
294
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
295
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
296
+ if (typeof value !== "object" || value == null) return false;
297
+ const record = value;
298
+ for (const key of Object.keys(record)) {
299
+ if (key === "@context") return true;
300
+ if (key === "@value" && isJsonLdValueObject(value)) continue;
301
+ if (hasNestedContext(record[key], depth + 1)) return true;
288
302
  }
303
+ return false;
289
304
  }
290
- function isJsonLiteralWrapper(value) {
291
- return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
292
- }
293
- /** @internal */
294
- function assertSafeJsonLd(jsonLd) {
295
- if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
296
- else if (typeof jsonLd === "object" && jsonLd != null) {
297
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
298
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
299
- if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
300
- if (jsonLiteralWrapper && key === "@value") continue;
301
- assertSafeJsonLd(value);
302
- }
305
+ function exceedsTraversalDepth(value, depth = 0) {
306
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
307
+ if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
308
+ if (typeof value !== "object" || value == null) return false;
309
+ const record = value;
310
+ for (const key of Object.keys(record)) {
311
+ if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
312
+ if (exceedsTraversalDepth(record[key], depth + 1)) return true;
303
313
  }
314
+ return false;
304
315
  }
305
- /**
306
- * Attaches a LD signature to the given JSON-LD document.
307
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
308
- * modified.
309
- * @param signature The signature to attach.
310
- * @returns The JSON-LD document with the attached signature.
311
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
312
- * @since 1.0.0
313
- */
314
- function attachSignature(jsonLd, signature) {
315
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
316
- return {
317
- ...jsonLd,
318
- signature
319
- };
316
+ function hasKnownSafeContext(jsonLd) {
317
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
318
+ const record = jsonLd;
319
+ if (!Object.hasOwn(record, "@context")) return false;
320
+ const context = record["@context"];
321
+ const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
322
+ if (entries == null || entries.length < 1) return false;
323
+ let hasActivityStreamsContext = false;
324
+ for (const entry of entries) {
325
+ if (typeof entry !== "string") return false;
326
+ if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
327
+ if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
328
+ }
329
+ if (!hasActivityStreamsContext) return false;
330
+ for (const key of Object.keys(record)) {
331
+ if (key === "@context") continue;
332
+ if (hasNestedContext(record[key])) return false;
333
+ }
334
+ return true;
320
335
  }
321
- /**
322
- * Creates a LD signature for the given JSON-LD document.
323
- * @param jsonLd The JSON-LD document to sign.
324
- * @param privateKey The private key to sign the document.
325
- * @param keyId The ID of the public key that corresponds to the private key.
326
- * @param options Additional options for creating the signature.
327
- * See also {@link CreateSignatureOptions}.
328
- * @return The created signature.
329
- * @throws {TypeError} If the private key is invalid or unsupported.
330
- * @since 1.0.0
331
- */
332
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
333
- require_http.validateCryptoKey(privateKey, "private");
334
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
335
- const options = {
336
- "@context": "https://w3id.org/identity/v1",
337
- creator: keyId.href,
338
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
339
- };
340
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
341
- const messageBytes = new TextEncoder().encode(message);
342
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
336
+ function getLogSafeJsonLdMetadata(jsonLd) {
337
+ if (typeof jsonLd !== "object" || jsonLd == null) return {};
338
+ const record = jsonLd;
339
+ const context = record["@context"];
343
340
  return {
344
- ...options,
345
- type: "RsaSignature2017",
346
- signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
341
+ id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
342
+ type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
343
+ context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
347
344
  };
348
345
  }
349
346
  /**
350
- * Signs the given JSON-LD document with the private key and returns the signed
351
- * JSON-LD document.
352
- * @param jsonLd The JSON-LD document to sign.
353
- * @param privateKey The private key to sign the document.
354
- * @param keyId The key ID to use in the signature. It will be used by the
355
- * verifier to fetch the corresponding public key.
356
- * @param options Additional options for signing the document.
357
- * See also {@link SignJsonLdOptions}.
358
- * @returns The signed JSON-LD document.
359
- * @throws {TypeError} If the private key is invalid or unsupported.
360
- * @since 1.0.0
347
+ * Ensures ActivityStreams attachment properties are represented as arrays
348
+ * when doing so preserves the JSON-LD semantics.
349
+ *
350
+ * JSON-LD compaction collapses single-item arrays into scalar values by
351
+ * default. Some ActivityPub implementations, Pixelfed among them, parse
352
+ * `attachment` as a plain JSON array rather than a JSON-LD property and reject
353
+ * otherwise valid objects whose single attachment is emitted as a scalar.
354
+ *
355
+ * When no `contextLoader` is supplied, the helper falls back to a restricted
356
+ * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
357
+ * every other URL without network access. Documents with custom, inline, or
358
+ * otherwise uncached contexts should pass a real `contextLoader` if they need
359
+ * the semantic-preservation check to succeed; otherwise canonicalization
360
+ * failures leave the original document unchanged.
361
361
  */
362
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
363
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
364
- try {
365
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
366
- if (span.isRecording()) {
367
- span.setAttribute("ld_signatures.type", signature.type);
368
- span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
369
- }
370
- return attachSignature(jsonLd, signature);
371
- } catch (error) {
372
- span.setStatus({
373
- code: _opentelemetry_api.SpanStatusCode.ERROR,
374
- message: String(error)
375
- });
376
- throw error;
377
- } finally {
378
- span.end();
362
+ async function normalizeAttachmentArrays(jsonLd, contextLoader, preserveSecured = false) {
363
+ const normalized = wrapScalarAttachments(jsonLd);
364
+ if (normalized === jsonLd) return jsonLd;
365
+ if (exceedsTraversalDepth(jsonLd)) {
366
+ logger$3.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
367
+ return jsonLd;
368
+ }
369
+ const sourceLoader = contextLoader ?? preloadedOnlyDocumentLoader;
370
+ const pending = /* @__PURE__ */ new Map();
371
+ const loader = (url, options) => {
372
+ let result = pending.get(url);
373
+ if (result == null) {
374
+ result = sourceLoader(url, options);
375
+ pending.set(url, result);
379
376
  }
380
- });
381
- }
382
- /**
383
- * Checks if the given JSON-LD document has a Linked Data Signature-like
384
- * object, without restricting it to a single suite-specific shape.
385
- * @param jsonLd The JSON-LD document to check.
386
- * @returns `true` if the document has a signature-like object; `false`
387
- * otherwise.
388
- * @since 2.2.0
389
- */
390
- function hasSignatureLike(jsonLd) {
391
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
392
- const signature = jsonLd.signature;
393
- const hasReference = (value) => {
394
- if (typeof value === "string") return true;
395
- if (Array.isArray(value)) return value.some(hasReference);
396
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
397
- };
398
- const hasSignatureObject = (value) => {
399
- if (typeof value !== "object" || value == null) return false;
400
- const signatureRecord = value;
401
- 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");
377
+ return result;
402
378
  };
403
- return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
379
+ try {
380
+ if (preserveSecured) {
381
+ if (hasSecurityPredicate(await _fedify_vocab_runtime_jsonld.default.expand(jsonLd, { documentLoader: loader }))) return jsonLd;
382
+ }
383
+ if (!preserveSecured && hasKnownSafeContext(jsonLd)) return normalized;
384
+ const [before, after] = await Promise.allSettled([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
385
+ format: "application/n-quads",
386
+ documentLoader: loader
387
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
388
+ format: "application/n-quads",
389
+ documentLoader: loader
390
+ })]);
391
+ if (before.status === "rejected") throw before.reason;
392
+ if (after.status === "rejected") throw after.reason;
393
+ if (before.value === after.value) return normalized;
394
+ 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));
395
+ } catch (error) {
396
+ logger$3.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
397
+ }
398
+ return jsonLd;
404
399
  }
405
- /**
406
- * Checks if the given JSON-LD document has a Linked Data Signature.
407
- * @param jsonLd The JSON-LD document to check.
408
- * @returns `true` if the document has a signature; `false` otherwise.
409
- * @since 1.0.0
410
- */
411
- function hasSignature(jsonLd) {
412
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
413
- if ("signature" in jsonLd) {
414
- const signature = jsonLd.signature;
415
- if (typeof signature !== "object" || signature == null) return false;
416
- 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";
400
+ function hasSecurityPredicate(value) {
401
+ if (Array.isArray(value)) return value.some(hasSecurityPredicate);
402
+ if (typeof value !== "object" || value == null) return false;
403
+ const record = value;
404
+ if (Object.hasOwn(record, "@value")) return false;
405
+ for (const [key, child] of Object.entries(record)) {
406
+ if (key === "https://w3id.org/security#proof" || key === "https://w3id.org/security#signature") return true;
407
+ if (hasSecurityPredicate(child)) return true;
417
408
  }
418
409
  return false;
419
410
  }
420
411
  /**
421
- * Detaches Linked Data Signatures from the given JSON-LD document.
422
- * @param jsonLd The JSON-LD document to modify.
423
- * @returns The modified JSON-LD document. If the input document does not
424
- * contain a signature, the original document is returned.
425
- * @since 1.0.0
426
- */
427
- function detachSignature(jsonLd) {
428
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
429
- const doc = { ...jsonLd };
430
- delete doc.signature;
431
- return doc;
432
- }
433
- /**
434
- * Verifies Linked Data Signatures of the given JSON-LD document.
435
- *
436
- * This is a low-level utility that only checks the cryptographic signature
437
- * and (optionally) the cached key. It does not run the JSON-LD parsing,
438
- * attribution, and owner checks that a complete inbound LD verification
439
- * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
440
- * the public verification entry point and the one that emits the
441
- * `activitypub.signature.verification.duration` metric for the LD path.
442
- * `verifySignature` itself only emits
443
- * `activitypub.signature.key_fetch.duration`, since the rest of the work
444
- * that the verification-duration metric is meant to cover happens in
445
- * `verifyJsonLd`.
446
- * @param jsonLd The JSON-LD document to verify.
447
- * @param options Options for verifying the signature.
448
- * @returns The public key that signed the document or `null` if the signature
449
- * is invalid or the key is not found.
450
- * @since 1.0.0
412
+ * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
413
+ * to locally generated outgoing activities before they are signed, enqueued,
414
+ * or sent.
451
415
  */
452
- async function verifySignature(jsonLd, options = {}) {
453
- if (!hasSignature(jsonLd)) return null;
454
- const sig = jsonLd.signature;
455
- let signature;
456
- try {
457
- signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
458
- } catch (error) {
459
- logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
460
- ...sig,
461
- error
462
- });
463
- return null;
416
+ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, preserveSecured = false) {
417
+ if (preserveSecured) try {
418
+ if (hasSecurityPredicate(await _fedify_vocab_runtime_jsonld.default.expand(jsonLd, { documentLoader: contextLoader ?? preloadedOnlyDocumentLoader }))) return jsonLd;
419
+ } catch {
420
+ return jsonLd;
464
421
  }
465
- const { key, cached } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options));
466
- if (key == null) return null;
467
- const sigOpts = {
468
- ...sig,
469
- "@context": "https://w3id.org/identity/v1"
470
- };
471
- delete sigOpts.type;
472
- delete sigOpts.id;
473
- delete sigOpts.signatureValue;
474
- let sigOptsHash;
475
- try {
476
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
477
- } catch (error) {
478
- logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
479
- signatureOptions: sigOpts,
480
- error
481
- });
482
- return null;
422
+ jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
423
+ return await normalizeAttachmentArrays(jsonLd, contextLoader, preserveSecured);
424
+ }
425
+ //#endregion
426
+ //#region src/sig/ld.ts
427
+ const logger$2 = (0, _logtape_logtape.getLogger)([
428
+ "fedify",
429
+ "sig",
430
+ "ld"
431
+ ]);
432
+ const localContext = [
433
+ "https://w3id.org/identity/v1",
434
+ "https://www.w3.org/ns/activitystreams",
435
+ "https://w3id.org/security/v1",
436
+ "https://w3id.org/security/data-integrity/v1"
437
+ ];
438
+ const localContextUrls = new Set(localContext);
439
+ const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
440
+ const disallowedJsonLdKeywords = new Set([
441
+ "@graph",
442
+ "@included",
443
+ "@reverse"
444
+ ]);
445
+ /** @internal */
446
+ var UnsafeJsonLdError = class extends TypeError {
447
+ keyword;
448
+ constructor(keyword) {
449
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
450
+ this.keyword = keyword;
451
+ this.name = "UnsafeJsonLdError";
483
452
  }
484
- const document = { ...jsonLd };
485
- delete document.signature;
486
- let docHash;
487
- try {
488
- docHash = await hashJsonLd(document, options.contextLoader);
489
- } catch (error) {
490
- logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
491
- document,
492
- error
493
- });
494
- return null;
495
- }
496
- const encoder = new TextEncoder();
497
- const message = sigOptsHash + docHash;
498
- const messageBytes = encoder.encode(message);
499
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
500
- if (cached) {
501
- logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
502
- keyId: sig.creator,
503
- ...sig
504
- });
505
- const { key } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
506
- ...options,
507
- keyCache: {
508
- get: () => Promise.resolve(void 0),
509
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
510
- }
511
- }));
512
- if (key == null) return null;
513
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
453
+ };
454
+ /** @internal */
455
+ var InvalidContextReferenceError = class extends TypeError {
456
+ reference;
457
+ constructor(reference) {
458
+ super(`Invalid JSON-LD context reference: ${reference}.`);
459
+ this.reference = reference;
460
+ this.name = "InvalidContextReferenceError";
514
461
  }
515
- 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}", {
516
- keyId: sig.creator,
517
- ...sig,
518
- message
519
- });
520
- return null;
462
+ };
463
+ function createLoadingRemoteContextFailedError(reference, cause) {
464
+ const message = cause instanceof Error ? cause.message : String(cause);
465
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
466
+ error.name = "jsonld.InvalidUrl";
467
+ error.details = {
468
+ code: "loading remote context failed",
469
+ url: reference
470
+ };
471
+ error.cause = cause;
472
+ return error;
521
473
  }
522
- /**
523
- * Known Linked Data Signature `type` values, used to keep
524
- * `ld_signatures.type` on a bounded set of spec-defined string values.
525
- * Fedify only signs and verifies `RsaSignature2017`; other values come in
526
- * only from external documents and are dropped from the metric attribute to
527
- * avoid attacker-controlled cardinality.
528
- */
529
- const LD_KNOWN_SIGNATURE_TYPES = new Set(["RsaSignature2017"]);
530
- /**
531
- * Reports only whether a `signature` key is present on the document, with
532
- * no shape check on its value. This is intentionally looser than
533
- * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
534
- * and {@link hasSignatureLike} (which structurally accepts several known
535
- * suites): `verifyJsonLd` needs to tell a document with a malformed or
536
- * unsupported signature payload (classified as `rejected`) apart from a
537
- * truly unsigned document (classified as `missing`), and only this
538
- * presence-only check captures both cases.
539
- */
540
- function hasLdSignatureProperty(jsonLd) {
541
- return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
474
+ /** @internal */
475
+ function isClearlyMalformedContextReference(reference) {
476
+ for (const char of reference) {
477
+ const code = char.charCodeAt(0);
478
+ if (code <= 32 || code === 127) return true;
479
+ }
480
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
481
+ for (let i = 0; i < reference.length; i++) {
482
+ if (reference[i] !== "%") continue;
483
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
484
+ i += 2;
485
+ }
486
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
487
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
488
+ }
489
+ return false;
542
490
  }
543
- function getLdSignatureObject(jsonLd) {
544
- if (!hasLdSignatureProperty(jsonLd)) return void 0;
545
- const { signature } = jsonLd;
546
- if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
547
- return signature;
491
+ function cloneRemoteDocument(remoteDocument) {
492
+ return structuredClone(remoteDocument);
548
493
  }
549
- /**
550
- * Verify the authenticity of the given JSON-LD document using Linked Data
551
- * Signatures. If the document is signed, this function verifies the signature
552
- * and checks if the document is attributed to the owner of the public key.
553
- * If the document is not signed, this function returns `false`.
554
- * @param jsonLd The JSON-LD document to verify.
555
- * @param options Options for verifying the document.
556
- * @returns `true` if the document is authentic; `false` otherwise.
557
- */
558
- async function verifyJsonLd(jsonLd, options = {}) {
559
- return await verifyJsonLdInternal(jsonLd, options, true);
494
+ function createMemoizedDocumentLoader(documentLoader) {
495
+ const cache = /* @__PURE__ */ new Map();
496
+ return async (url, options) => {
497
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
498
+ let remoteDocument = cache.get(cacheKey);
499
+ if (remoteDocument == null) {
500
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
501
+ remoteDocument.catch(() => {
502
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
503
+ });
504
+ cache.set(cacheKey, remoteDocument);
505
+ }
506
+ return cloneRemoteDocument(await remoteDocument);
507
+ };
560
508
  }
561
509
  /** @internal */
562
- async function verifyCompactJsonLd(jsonLd, options = {}) {
563
- return await verifyJsonLdInternal(jsonLd, options, false);
564
- }
565
- async function verifyJsonLdInternal(jsonLd, options, compact) {
566
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
567
- const start = performance.now();
568
- let verified = false;
569
- let threw = false;
570
- let signatureType;
510
+ function wrapContextLoaderForJsonLd(contextLoader) {
511
+ const loader = contextLoader ?? builtInContextLoader;
512
+ return async (url, options) => {
571
513
  try {
572
- const verificationOptions = hasSignature(jsonLd) ? {
573
- ...options,
574
- contextLoader: getNormalizationContextLoader(options.contextLoader)
575
- } : options;
576
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
577
- const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
578
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
579
- span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
580
- const sig = getLdSignatureObject(jsonLd);
581
- if (sig != null) {
582
- if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
583
- if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
584
- if (typeof sig.type === "string") {
585
- span.setAttribute("ld_signatures.type", sig.type);
586
- if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
587
- }
588
- }
589
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
590
- if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
591
- const key = await verifySignature(compacted, verificationOptions);
592
- if (key == null) return false;
593
- if (key.ownerId == null) {
594
- logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
595
- return false;
596
- }
597
- attributions.delete(key.ownerId.href);
598
- if (attributions.size > 0) {
599
- logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
600
- return false;
601
- }
602
- verified = true;
603
- return true;
514
+ return await loader(url, options);
604
515
  } catch (error) {
605
- threw = true;
606
- span.setStatus({
607
- code: _opentelemetry_api.SpanStatusCode.ERROR,
608
- message: String(error)
609
- });
610
- throw error;
611
- } finally {
612
- const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
613
- require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "linked_data", classified, { ldType: signatureType });
614
- span.end();
516
+ if (!isInvalidUrlTypeError(error)) throw error;
517
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
518
+ throw createLoadingRemoteContextFailedError(url, error);
615
519
  }
616
- });
617
- }
618
- async function hashJsonLd(jsonLd, contextLoader) {
619
- const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
620
- format: "application/n-quads",
621
- documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
622
- });
623
- const encoder = new TextEncoder();
624
- return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
520
+ };
625
521
  }
626
- //#endregion
627
- //#region src/sig/owner.ts
628
- const logger$3 = (0, _logtape_logtape.getLogger)([
629
- "fedify",
630
- "sig",
631
- "owner"
632
- ]);
633
- /**
634
- * Checks if the actor of the given activity owns the specified key.
635
- *
636
- * Ownership is never taken from what the activity or the key say about
637
- * themselves, as both are written by whoever sent the activity. It is
638
- * established from a document that the owner itself serves: either the key's
639
- * claimed owner links back to the key, or the actor the activity claims lists
640
- * the key as its own.
641
- *
642
- * @param activity The activity to check.
643
- * @param key The public key to check.
644
- * @param options Options for checking the key ownership.
645
- * @returns Whether the actor is the owner of the key.
646
- */
647
- async function doesActorOwnKey(activity, key, options) {
648
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
649
- kind: _opentelemetry_api.SpanKind.INTERNAL,
650
- attributes: {
651
- "activitypub.actor.id": activity.actorId?.href ?? "",
652
- "activitypub.key.id": key.id?.href ?? ""
653
- }
654
- }, async (span) => {
655
- try {
656
- const actorId = activity.actorId;
657
- if (actorId == null) {
658
- span.setAttribute("activitypub.key_ownership.verified", false);
659
- span.setAttribute("activitypub.key_ownership.method", "none");
660
- return false;
661
- }
662
- if (key.ownerId != null) {
663
- const owner = await require_http.verifyKeyOwnership(key, options);
664
- if (owner?.id != null && owner.id.href === actorId.href) {
665
- span.setAttribute("activitypub.key_ownership.verified", true);
666
- span.setAttribute("activitypub.key_ownership.method", "key_owner");
667
- return true;
668
- }
669
- }
670
- const actor = await require_http.fetchActorDocument(actorId, options);
671
- if (actor != null && await doesActorListKey(actor, key, options)) {
672
- span.setAttribute("activitypub.key_ownership.verified", true);
673
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
674
- return true;
675
- }
676
- logger$3.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
677
- actorId: actorId.href,
678
- keyId: key.id?.href
679
- });
680
- span.setAttribute("activitypub.key_ownership.verified", false);
681
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
682
- return false;
683
- } catch (error) {
684
- span.recordException(error);
685
- span.setStatus({
686
- code: _opentelemetry_api.SpanStatusCode.ERROR,
687
- message: String(error)
688
- });
689
- throw error;
690
- } finally {
691
- span.end();
522
+ /** @internal */
523
+ function getNormalizationContextLoader(contextLoader) {
524
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
525
+ return createMemoizedDocumentLoader(async (url, options) => {
526
+ if (URL.canParse(url)) {
527
+ const normalizedUrl = new URL(url).href;
528
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
692
529
  }
530
+ return await loader(url, options);
693
531
  });
694
532
  }
695
- /**
696
- * Determines whether the given actor's own document lists the given key among
697
- * its public keys.
698
- *
699
- * Keys are matched by id, which is what an actor document links to. A key
700
- * document may leave its id implicit, though, and then there is no id for the
701
- * actor to link to; the key material itself is the only thing the two can
702
- * have in common, so that is what gets compared.
703
- */
704
- async function doesActorListKey(actor, key, options) {
705
- if (key.id != null) {
706
- for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
707
- return false;
533
+ /** @internal */
534
+ async function compactJsonLd(jsonLd, contextLoader) {
535
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
536
+ const signature = hasLds ? jsonLd.signature : void 0;
537
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
538
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
539
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
540
+ const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
541
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
542
+ assertSafeJsonLd(compacted);
543
+ return compacted;
544
+ }
545
+ function createInvalidRemoteContextError(reference) {
546
+ 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}".`);
547
+ error.name = "jsonld.InvalidUrl";
548
+ error.details = {
549
+ code: "invalid remote context",
550
+ url: reference
551
+ };
552
+ return error;
553
+ }
554
+ function getRemoteContext(remoteDocument, reference) {
555
+ const { contextUrl, documentUrl } = remoteDocument;
556
+ let { document } = remoteDocument;
557
+ if (typeof document === "string") document = JSON.parse(document);
558
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
559
+ let context = "@context" in document ? document["@context"] : {};
560
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
561
+ return {
562
+ context,
563
+ baseUrl: documentUrl ?? reference
564
+ };
565
+ }
566
+ function createGraphAliasContextState() {
567
+ return {
568
+ graphTerms: /* @__PURE__ */ new Set(),
569
+ jsonTerms: /* @__PURE__ */ new Set(),
570
+ propertyContexts: /* @__PURE__ */ new Map(),
571
+ termTargets: /* @__PURE__ */ new Map()
572
+ };
573
+ }
574
+ function cloneGraphAliasContextState(state) {
575
+ return {
576
+ graphTerms: new Set(state.graphTerms),
577
+ jsonTerms: new Set(state.jsonTerms),
578
+ propertyContexts: new Map(state.propertyContexts),
579
+ termTargets: new Map(state.termTargets)
580
+ };
581
+ }
582
+ function resolveContextTarget(target, state) {
583
+ if (target === "@graph") return target;
584
+ const mapped = state.termTargets.get(target);
585
+ if (mapped == null) return target;
586
+ return mapped;
587
+ }
588
+ function getDirectContextTarget(definition) {
589
+ if (definition === null) return null;
590
+ if (typeof definition === "string") return definition;
591
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
592
+ const id = definition["@id"];
593
+ if (id === null) return null;
594
+ if (typeof id === "string") return id;
708
595
  }
709
- if (key.publicKey == null) return false;
710
- const publicKeys = actor.getPublicKeys({
711
- ...options,
712
- suppressError: true
713
- });
714
- for await (const publicKey of publicKeys) {
715
- if (publicKey.publicKey == null) continue;
716
- if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
596
+ }
597
+ function isJsonTypedDefinition(definition) {
598
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
599
+ }
600
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
601
+ if (target === "@graph") return target;
602
+ if (seen.has(target)) return target;
603
+ seen.add(target);
604
+ if (localTargets.has(target)) {
605
+ const localTarget = localTargets.get(target);
606
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
717
607
  }
718
- return false;
608
+ return resolveContextTarget(target, state);
719
609
  }
720
- /**
721
- * Compares two public keys by their key material, ignoring the metadata that
722
- * surrounds it.
723
- */
724
- async function isSamePublicKey(a, b) {
725
- const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
726
- 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;
610
+ function refreshGraphAliases(state) {
611
+ state.graphTerms.clear();
612
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
727
613
  }
728
- /**
729
- * Gets the actor that owns the specified key. Returns `null` if the key has no
730
- * known owner.
731
- *
732
- * The owner is only returned when the key and the owner link to each other:
733
- * a document that merely claims to own a key is not enough, as the claim and
734
- * the key can come from the same host.
735
- *
736
- * @param keyId The ID of the key to check, or the key itself.
737
- * @param options Options for getting the key owner.
738
- * @returns The actor that owns the key, or `null` if the key has no known
739
- * owner.
740
- * @since 0.7.0
741
- */
742
- async function getKeyOwner(keyId, options) {
743
- const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
744
- const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
745
- const fetchOptions = {
746
- documentLoader,
747
- contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
748
- tracerProvider
749
- };
750
- if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
751
- let keyDoc;
752
- let documentUrl = keyId;
753
- try {
754
- const remoteDocument = await documentLoader(keyId.href);
755
- keyDoc = remoteDocument.document;
756
- documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
757
- } catch (_) {
758
- return null;
614
+ function normalizeContextReference(reference, baseUrl) {
615
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
616
+ return URL.canParse(reference) ? new URL(reference).href : reference;
617
+ }
618
+ /** @internal */
619
+ function isInvalidUrlTypeError(error) {
620
+ const code = error.code;
621
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || error.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
622
+ }
623
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
624
+ if (context === null) return createGraphAliasContextState();
625
+ let nextState = cloneGraphAliasContextState(state);
626
+ if (Array.isArray(context)) {
627
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
628
+ return nextState;
759
629
  }
760
- let object;
761
- try {
762
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
763
- ...fetchOptions,
764
- baseUrl: documentUrl
765
- });
766
- } catch (e) {
767
- if (!(e instanceof TypeError)) throw e;
630
+ if (typeof context === "string") {
631
+ const reference = normalizeContextReference(context, baseUrl);
632
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
633
+ if (processingContexts.has(cacheKey)) return nextState;
634
+ processingContexts.add(cacheKey);
768
635
  try {
769
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
770
- } catch (e) {
771
- if (e instanceof TypeError) return null;
772
- throw e;
636
+ let remoteContext = remoteContextCache.get(cacheKey);
637
+ if (remoteContext == null) {
638
+ remoteContext = (async () => {
639
+ try {
640
+ return getRemoteContext(await documentLoader(reference), reference);
641
+ } catch (error) {
642
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
643
+ throw error;
644
+ }
645
+ })();
646
+ remoteContextCache.set(cacheKey, remoteContext);
647
+ }
648
+ const loadedRemoteContext = await remoteContext;
649
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
650
+ } finally {
651
+ processingContexts.delete(cacheKey);
773
652
  }
774
653
  }
775
- if (object instanceof _fedify_vocab.CryptographicKey) {
776
- if (object.id != null && object.id.href !== keyId.href) return null;
777
- return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
778
- }
779
- if (!(0, _fedify_vocab.isActor)(object)) return null;
780
- if (object.id == null || object.id.origin !== documentUrl.origin) {
781
- logger$3.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
782
- documentUrl: documentUrl.href,
783
- actorId: object.id?.href,
784
- keyId: keyId.href
785
- });
786
- return null;
654
+ if (typeof context === "object" && context != null) {
655
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
656
+ const localTargets = /* @__PURE__ */ new Map();
657
+ for (const [term, definition] of globalThis.Object.entries(context)) {
658
+ if (term.startsWith("@")) continue;
659
+ const target = getDirectContextTarget(definition);
660
+ if (target == null) localTargets.set(term, null);
661
+ else if (typeof target === "string") localTargets.set(term, target);
662
+ else localTargets.delete(term);
663
+ }
664
+ for (const [term, definition] of globalThis.Object.entries(context)) {
665
+ if (term.startsWith("@")) continue;
666
+ if (localTargets.has(term)) {
667
+ const directTarget = localTargets.get(term);
668
+ if (directTarget == null) nextState.termTargets.set(term, null);
669
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
670
+ } else nextState.termTargets.delete(term);
671
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
672
+ context: definition["@context"],
673
+ baseUrl
674
+ });
675
+ else nextState.propertyContexts.delete(term);
676
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
677
+ else nextState.jsonTerms.delete(term);
678
+ }
679
+ refreshGraphAliases(nextState);
787
680
  }
788
- for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
789
- return null;
681
+ return nextState;
790
682
  }
791
- //#endregion
792
- //#region src/compat/preloaded-context-loader.ts
793
- /**
794
- * A restricted JSON-LD document loader that resolves only contexts bundled
795
- * with Fedify.
796
- *
797
- * This is intentionally narrower than `getDocumentLoader()`: normalization
798
- * helpers are also reached from verification paths that operate on inbound,
799
- * attacker-controlled JSON-LD, so the default fallback must never fetch
800
- * attacker-supplied context URLs.
801
- */
802
- const preloadedOnlyDocumentLoader = (url) => {
803
- if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
804
- contextUrl: null,
805
- documentUrl: url,
806
- document: _fedify_vocab_runtime.preloadedContexts[url]
807
- });
808
- return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
809
- };
810
- //#endregion
811
- //#region src/compat/public-audience.ts
812
- const logger$2 = (0, _logtape_logtape.getLogger)([
813
- "fedify",
814
- "compat",
815
- "public-audience"
816
- ]);
817
- const PUBLIC_ADDRESSING_FIELDS = new Set([
818
- "to",
819
- "cc",
820
- "bto",
821
- "bcc",
822
- "audience"
823
- ]);
824
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
825
- const MAX_TRAVERSAL_DEPTH$1 = 64;
826
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
827
- function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
828
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
829
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
830
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
831
- if (typeof value !== "object" || value == null) return false;
832
- const record = value;
833
- for (const key of Object.keys(record)) {
834
- if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
683
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
684
+ if (Array.isArray(jsonLd)) {
685
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
686
+ return;
687
+ }
688
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
689
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
690
+ let state = inheritedState;
691
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
692
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
693
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
835
694
  if (key === "@context") continue;
836
- if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
695
+ if (jsonLiteralWrapper && key === "@value") continue;
696
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
697
+ if (state.jsonTerms.has(key)) continue;
698
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
837
699
  }
838
- return false;
839
700
  }
840
- function rewritePublicAudience(value, parentKey, depth = 0) {
841
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
842
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
843
- if (Array.isArray(value)) {
844
- let changed = false;
845
- const mapped = value.map((item) => {
846
- const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
847
- if (rewritten !== item) changed = true;
848
- return rewritten;
849
- });
850
- return changed ? mapped : value;
701
+ function isJsonLiteralWrapper(value) {
702
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
703
+ }
704
+ /** @internal */
705
+ function assertSafeJsonLd(jsonLd) {
706
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
707
+ else if (typeof jsonLd === "object" && jsonLd != null) {
708
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
709
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
710
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
711
+ if (jsonLiteralWrapper && key === "@value") continue;
712
+ assertSafeJsonLd(value);
713
+ }
851
714
  }
852
- if (typeof value !== "object" || value == null) return value;
853
- const record = value;
854
- let changed = false;
855
- const normalized = Object.create(null);
856
- for (const key of Object.keys(record)) {
857
- const rewritten = key === "@context" ? record[key] : record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public") ? _fedify_vocab.PUBLIC_COLLECTION.href : rewritePublicAudience(record[key], key, depth + 1);
858
- if (rewritten !== record[key]) changed = true;
859
- normalized[key] = rewritten;
715
+ }
716
+ const signatureTermDefinition = { "signature": "https://w3id.org/security#signature" };
717
+ const signatureDefiningContexts = new Set(["https://w3id.org/identity/v1", "https://w3id.org/security/v1"]);
718
+ const signatureFreeContexts = getSignatureFreeContexts();
719
+ function getSignatureFreeContexts() {
720
+ const urls = /* @__PURE__ */ new Set();
721
+ for (const [url, document] of globalThis.Object.entries(_fedify_vocab_runtime.preloadedContexts)) {
722
+ if (typeof document !== "object" || document == null) continue;
723
+ const context = document["@context"];
724
+ if (typeof context !== "object" || context == null || Array.isArray(context)) continue;
725
+ const record = context;
726
+ if (!globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) urls.add(url);
860
727
  }
861
- return changed ? normalized : value;
728
+ return urls;
729
+ }
730
+ function getContextEntryEffect(entry) {
731
+ if (entry == null) return "resets";
732
+ if (typeof entry === "string") {
733
+ if (signatureDefiningContexts.has(entry)) return "defines";
734
+ if (signatureFreeContexts.has(entry)) return "absent";
735
+ return "unknown";
736
+ }
737
+ if (typeof entry !== "object") return "absent";
738
+ const record = entry;
739
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) {
740
+ const definition = record["signature"];
741
+ const contextProtected = record["@protected"] === true;
742
+ const imported = globalThis.Object.prototype.hasOwnProperty.call(record, "@import");
743
+ if (definition == null) {
744
+ if (contextProtected) return "defines";
745
+ return imported ? "unknown" : "resets";
746
+ }
747
+ if (typeof definition === "object" && !Array.isArray(definition)) {
748
+ const term = definition;
749
+ const protectedTerm = contextProtected || term["@protected"] === true;
750
+ if (globalThis.Object.prototype.hasOwnProperty.call(term, "@id") && term["@id"] == null) {
751
+ if (protectedTerm) return "defines";
752
+ return imported ? "unknown" : "resets";
753
+ }
754
+ }
755
+ return "defines";
756
+ }
757
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "@import")) return "unknown";
758
+ return "absent";
759
+ }
760
+ function getSignatureTermState(context) {
761
+ if (context == null) return "absent";
762
+ if (!Array.isArray(context)) {
763
+ const effect = getContextEntryEffect(context);
764
+ return effect === "defines" ? "defined" : effect === "unknown" ? "unknown" : "absent";
765
+ }
766
+ let state = "absent";
767
+ for (const entry of context) {
768
+ const effect = getContextEntryEffect(entry);
769
+ if (effect === "defines") state = "defined";
770
+ else if (effect === "resets") state = "absent";
771
+ else if (effect === "unknown" && state !== "defined") state = "unknown";
772
+ }
773
+ return state;
774
+ }
775
+ function prepareSignatureDocument(jsonLd) {
776
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) return jsonLd;
777
+ const document = jsonLd;
778
+ if (document["proof"] != null) return { ...document };
779
+ const context = document["@context"];
780
+ if (getSignatureTermState(context) !== "absent") return { ...document };
781
+ const definition = { ...signatureTermDefinition };
782
+ return {
783
+ ...document,
784
+ "@context": context == null ? [definition] : Array.isArray(context) ? [...context, definition] : [context, definition]
785
+ };
862
786
  }
863
787
  /**
864
- * Reports whether `value` carries an `@context` property anywhere inside
865
- * its subtree (not counting the value itself). A nested `@context` can
866
- * introduce a local term-definition scope that redefines `as:` or `Public`
867
- * even when the top-level `@context` is safe, so the fast path must defer
868
- * to the URDNA2015 equivalence check whenever one is present.
788
+ * Attaches a LD signature to the given JSON-LD document.
789
+ *
790
+ * When the document's context does not already define the `signature`
791
+ * property, the returned document adds a minimal inline context for it.
792
+ * Without that definition, expanding the attached signature would produce a
793
+ * blank node predicate, which is not valid RDF. Documents that already carry
794
+ * a `proof` are left unchanged, since a new context definition would invalidate
795
+ * the proof. Documents whose context includes an unrecognized remote context
796
+ * are also left unchanged, since that context may already define `signature`.
797
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
798
+ * modified.
799
+ * @param signature The signature to attach.
800
+ * @returns The JSON-LD document with the attached signature.
801
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
802
+ * Top-level arrays are rejected, since a Linked Data
803
+ * Signature is attached to a single node.
804
+ * @since 1.0.0
869
805
  */
870
- function hasNestedContext$1(value, depth = 0) {
871
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
872
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
873
- if (typeof value !== "object" || value == null) return false;
874
- const record = value;
875
- for (const key of Object.keys(record)) {
876
- if (key === "@context") return true;
877
- if (hasNestedContext$1(record[key], depth + 1)) return true;
878
- }
879
- return false;
806
+ function attachSignature(jsonLd, signature) {
807
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
808
+ const output = prepareSignatureDocument(jsonLd);
809
+ output.signature = signature;
810
+ return output;
880
811
  }
881
812
  /**
882
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
883
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
884
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
885
- * preloaded context set AND including the ActivityStreams URL qualify,
886
- * AND no nested subtree carries its own `@context` that might redefine
887
- * those terms within a local scope. When all of that holds the rewrite
888
- * is provably semantics-preserving and the URDNA2015 equivalence check
889
- * can be skipped. Any other shape (unknown external URLs, inline
890
- * objects at the top level, nested `@context` blocks) is treated as
891
- * potentially unsafe.
813
+ * Creates a LD signature for the given JSON-LD document.
814
+ *
815
+ * If the document's context does not define the `signature` property, the
816
+ * signature is computed over the document with a minimal inline definition
817
+ * added. Use {@link attachSignature} to attach the signature to that exact
818
+ * document. Documents that already carry a `proof`, or whose context includes
819
+ * an unrecognized remote context, are hashed unchanged.
820
+ * @param jsonLd The JSON-LD document to sign.
821
+ * @param privateKey The private key to sign the document.
822
+ * @param keyId The ID of the public key that corresponds to the private key.
823
+ * @param options Additional options for creating the signature.
824
+ * See also {@link CreateSignatureOptions}.
825
+ * @return The created signature.
826
+ * @throws {TypeError} If the private key is invalid or unsupported.
827
+ * @since 1.0.0
892
828
  */
893
- function hasKnownSafeContext$1(jsonLd) {
829
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
830
+ require_http.validateCryptoKey(privateKey, "private");
831
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
832
+ const options = {
833
+ creator: keyId.href,
834
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
835
+ };
836
+ const message = await hashJsonLd({
837
+ "@context": "https://w3id.org/identity/v1",
838
+ ...options
839
+ }, contextLoader) + await hashJsonLd(prepareSignatureDocument(jsonLd), contextLoader);
840
+ const messageBytes = new TextEncoder().encode(message);
841
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), messageBytes);
842
+ return {
843
+ "@context": "https://w3id.org/security/v1",
844
+ ...options,
845
+ type: "RsaSignature2017",
846
+ signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
847
+ };
848
+ }
849
+ /**
850
+ * Signs the given JSON-LD document with the private key and returns the signed
851
+ * JSON-LD document.
852
+ * @param jsonLd The JSON-LD document to sign.
853
+ * @param privateKey The private key to sign the document.
854
+ * @param keyId The key ID to use in the signature. It will be used by the
855
+ * verifier to fetch the corresponding public key.
856
+ * @param options Additional options for signing the document.
857
+ * See also {@link SignJsonLdOptions}.
858
+ * @returns The signed JSON-LD document.
859
+ * @throws {TypeError} If the private key is invalid or unsupported.
860
+ * @since 1.0.0
861
+ */
862
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
863
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
864
+ try {
865
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
866
+ if (span.isRecording()) {
867
+ span.setAttribute("ld_signatures.type", signature.type);
868
+ span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
869
+ }
870
+ return attachSignature(jsonLd, signature);
871
+ } catch (error) {
872
+ span.setStatus({
873
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
874
+ message: String(error)
875
+ });
876
+ throw error;
877
+ } finally {
878
+ span.end();
879
+ }
880
+ });
881
+ }
882
+ /** @internal */
883
+ function hasVerifiableSignature(jsonLd) {
884
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || !("signature" in jsonLd)) return false;
885
+ const signature = jsonLd.signature;
886
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return false;
887
+ 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";
888
+ }
889
+ /** @internal */
890
+ function describeSignatureShape(jsonLd) {
891
+ if (typeof jsonLd !== "object" || jsonLd == null || !("signature" in jsonLd)) return null;
892
+ const signature = jsonLd.signature;
893
+ const properties = typeof signature === "object" && signature != null ? globalThis.Object.keys(signature) : [];
894
+ return {
895
+ signatureKind: signature == null ? String(signature) : Array.isArray(signature) ? "array" : typeof signature,
896
+ signatureProperties: properties.sort().slice(0, 20).map((p) => p.slice(0, 80)),
897
+ signaturePropertyCount: properties.length
898
+ };
899
+ }
900
+ /**
901
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
902
+ * object, without restricting it to a single suite-specific shape.
903
+ * @param jsonLd The JSON-LD document to check.
904
+ * @returns `true` if the document has a signature-like object; `false`
905
+ * otherwise.
906
+ * @since 2.2.0
907
+ */
908
+ function hasSignatureLike(jsonLd) {
894
909
  if (typeof jsonLd !== "object" || jsonLd == null) return false;
895
- const record = jsonLd;
896
- if (!Object.hasOwn(record, "@context")) return false;
897
- const ctx = record["@context"];
898
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
899
- if (entries == null || entries.length === 0) return false;
900
- let hasAs = false;
901
- for (const entry of entries) {
902
- if (typeof entry !== "string") return false;
903
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
904
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
905
- }
906
- if (!hasAs) return false;
907
- for (const key of Object.keys(record)) {
908
- if (key === "@context") continue;
909
- if (hasNestedContext$1(record[key])) return false;
910
- }
911
- return true;
910
+ const signature = jsonLd.signature;
911
+ const hasReference = (value) => {
912
+ if (typeof value === "string") return true;
913
+ if (Array.isArray(value)) return value.some(hasReference);
914
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
915
+ };
916
+ const hasSignatureObject = (value) => {
917
+ if (typeof value !== "object" || value == null) return false;
918
+ const signatureRecord = value;
919
+ 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");
920
+ };
921
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
912
922
  }
913
923
  /**
914
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
915
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
916
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
917
- *
918
- * Several ActivityPub implementations, Lemmy among them, match these
919
- * fields as plain URLs without running JSON-LD expansion, and silently
920
- * drop activities whose public addressing appears in CURIE form. This
921
- * helper works around that gap.
922
- *
923
- * For documents whose `@context` is drawn entirely from Fedify's
924
- * preloaded context set and includes the ActivityStreams URL, the
925
- * rewrite is applied directly: the content of every preloaded non-AS
926
- * context is known not to redefine the `as:` prefix or the bare `Public`
927
- * term, so the semantics are preserved by construction. Any other
928
- * shape (an inline object, an unknown external URL, and so on) is
929
- * treated as potentially unsafe and gated on a JSON-LD equivalence
930
- * check; both forms are canonicalized with URDNA2015 and the resulting
931
- * N-Quads are compared. When they differ, the original document is
932
- * returned unchanged. Canonicalization failures also fall back to the
933
- * original document.
924
+ * Detaches Linked Data Signatures from the given JSON-LD document.
925
+ * @param jsonLd The JSON-LD document to modify.
926
+ * @returns The modified JSON-LD document. If the input document does not
927
+ * contain a signature, the original document is returned.
928
+ * @since 1.0.0
929
+ */
930
+ function detachSignature(jsonLd) {
931
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
932
+ const doc = { ...jsonLd };
933
+ delete doc.signature;
934
+ return doc;
935
+ }
936
+ /**
937
+ * Verifies Linked Data Signatures of the given JSON-LD document.
934
938
  *
935
- * When no `contextLoader` is supplied the helper falls back to an
936
- * internal loader that resolves only the URLs in Fedify's
937
- * preloaded-contexts set and rejects every other URL without issuing a
938
- * network request. That behaviour is deliberately narrower than
939
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
940
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
941
- * helper is reached from verification paths (`verifyProof()` /
942
- * `verifyObject()`) that operate on inbound, potentially adversarial
943
- * JSON-LD, and a default loader that fetches attacker-supplied
944
- * `@context` URLs on the caller's behalf would be an SSRF vector.
945
- * Canonicalization failures against the restricted loader fall back to
946
- * the original document, same as any other canonicalization error.
947
- * Callers that genuinely need the remote-fetch loader (for example
948
- * applications that sign local JSON-LD against a custom vocabulary)
949
- * should pass a `contextLoader` explicitly.
939
+ * This is a low-level utility that only checks the cryptographic signature
940
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
941
+ * attribution, and owner checks that a complete inbound LD verification
942
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
943
+ * the public verification entry point and the one that emits the
944
+ * `activitypub.signature.verification.duration` metric for the LD path.
945
+ * `verifySignature` itself only emits
946
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
947
+ * that the verification-duration metric is meant to cover happens in
948
+ * `verifyJsonLd`.
950
949
  *
951
- * Must be called before any signing step that canonicalizes the
952
- * compact form byte-for-byte (for example, Object Integrity Proofs
953
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
954
- * matches what is sent on the wire.
950
+ * Unmapped properties discarded during JSON-LD processing are tolerated, but
951
+ * their values are not authenticated by the signature. Other unsafe
952
+ * canonicalization warnings, including relative IRIs, remain rejected.
953
+ * @param jsonLd The JSON-LD document to verify.
954
+ * @param options Options for verifying the signature.
955
+ * @returns The public key that signed the document or `null` if the signature
956
+ * is invalid or the key is not found.
957
+ * @since 1.0.0
955
958
  */
956
- async function normalizePublicAudience(jsonLd, contextLoader) {
957
- if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
958
- const normalized = rewritePublicAudience(jsonLd);
959
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
960
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
959
+ async function verifySignature(jsonLd, options = {}) {
960
+ if (!hasVerifiableSignature(jsonLd)) {
961
+ const shape = describeSignatureShape(jsonLd);
962
+ if (shape != null) logger$2.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
963
+ return null;
964
+ }
965
+ const sig = jsonLd.signature;
966
+ let signature;
961
967
  try {
962
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
963
- format: "application/n-quads",
964
- documentLoader: loader
965
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
966
- format: "application/n-quads",
967
- documentLoader: loader
968
- })]);
969
- if (before === after) return normalized;
970
- logger$2.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.");
968
+ signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
971
969
  } catch (error) {
972
- logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
970
+ logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
971
+ ...sig,
972
+ error
973
+ });
974
+ return null;
973
975
  }
974
- return jsonLd;
975
- }
976
- //#endregion
977
- //#region src/compat/outgoing-jsonld.ts
978
- const logger$1 = (0, _logtape_logtape.getLogger)([
979
- "fedify",
980
- "compat",
981
- "outgoing-jsonld"
982
- ]);
983
- const ATTACHMENT_FIELDS = new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
984
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
985
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
986
- const MAX_TRAVERSAL_DEPTH = 64;
987
- function isJsonLdListObject(value) {
988
- return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
989
- }
990
- function isJsonLdValueObject(value) {
991
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
992
- }
993
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
994
- if (Array.isArray(value)) {
995
- if (seen.has(value)) return;
996
- seen.add(value);
997
- for (const item of value) yield* getContextObjects(item, seen);
998
- return;
976
+ let creator;
977
+ try {
978
+ creator = new URL(sig.creator);
979
+ } catch {
980
+ logger$2.debug("Failed to verify; signature creator is not a valid URL.");
981
+ return null;
999
982
  }
1000
- if (typeof value === "object" && value != null) {
1001
- if (seen.has(value)) return;
1002
- seen.add(value);
1003
- const record = value;
1004
- yield record;
1005
- for (const definition of Object.values(record)) {
1006
- if (typeof definition !== "object" || definition == null) continue;
1007
- const nestedContext = definition["@context"];
1008
- if (nestedContext == null) continue;
1009
- yield* getContextObjects(nestedContext, seen);
1010
- }
983
+ const { key, cached } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(creator, _fedify_vocab.CryptographicKey, options));
984
+ if (key == null) return null;
985
+ const sigOpts = {
986
+ ...sig,
987
+ "@context": "https://w3id.org/identity/v1"
988
+ };
989
+ delete sigOpts.type;
990
+ delete sigOpts.id;
991
+ delete sigOpts.signatureValue;
992
+ let sigOptsHash;
993
+ try {
994
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader, "verify");
995
+ } catch (error) {
996
+ logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
997
+ signatureOptions: sigOpts,
998
+ error
999
+ });
1000
+ return null;
1001
+ }
1002
+ const document = { ...jsonLd };
1003
+ delete document.signature;
1004
+ let docHash;
1005
+ try {
1006
+ docHash = await hashJsonLd(document, options.contextLoader, "verify");
1007
+ } catch (error) {
1008
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
1009
+ document,
1010
+ error
1011
+ });
1012
+ return null;
1013
+ }
1014
+ const encoder = new TextEncoder();
1015
+ const message = sigOptsHash + docHash;
1016
+ const messageBytes = encoder.encode(message);
1017
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
1018
+ if (cached) {
1019
+ logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
1020
+ keyId: sig.creator,
1021
+ ...sig
1022
+ });
1023
+ const { key } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(creator, _fedify_vocab.CryptographicKey, {
1024
+ ...options,
1025
+ keyCache: {
1026
+ get: () => Promise.resolve(void 0),
1027
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1028
+ }
1029
+ }));
1030
+ if (key == null) return null;
1031
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
1011
1032
  }
1033
+ 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}", {
1034
+ keyId: sig.creator,
1035
+ ...sig,
1036
+ message
1037
+ });
1038
+ return null;
1012
1039
  }
1013
- function isActivityStreamsAttachmentTerm(value) {
1014
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
1040
+ /**
1041
+ * Known Linked Data Signature `type` values, used to keep
1042
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
1043
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
1044
+ * only from external documents and are dropped from the metric attribute to
1045
+ * avoid attacker-controlled cardinality.
1046
+ */
1047
+ const LD_KNOWN_SIGNATURE_TYPES = new Set(["RsaSignature2017"]);
1048
+ /**
1049
+ * Reports only whether a `signature` key is present on the document, with
1050
+ * no shape check on its value. This is intentionally looser than
1051
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
1052
+ * and {@link hasSignatureLike} (which structurally accepts several known
1053
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
1054
+ * unsupported signature payload (classified as `rejected`) apart from a
1055
+ * truly unsigned document (classified as `missing`), and only this
1056
+ * presence-only check captures both cases.
1057
+ */
1058
+ function hasLdSignatureProperty(jsonLd) {
1059
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
1060
+ }
1061
+ function getLdSignatureObject(jsonLd) {
1062
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
1063
+ const { signature } = jsonLd;
1064
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
1065
+ return signature;
1066
+ }
1067
+ /**
1068
+ * Verify the authenticity of the given JSON-LD document using Linked Data
1069
+ * Signatures. If the document is signed, this function verifies the signature
1070
+ * and checks if the document is attributed to the owner of the public key.
1071
+ * If the document is not signed, this function returns `false`.
1072
+ * Unmapped properties discarded during JSON-LD processing are not
1073
+ * authenticated, even when verification succeeds.
1074
+ * @param jsonLd The JSON-LD document to verify.
1075
+ * @param options Options for verifying the document.
1076
+ * @returns `true` if the document is authentic; `false` otherwise.
1077
+ */
1078
+ async function verifyJsonLd(jsonLd, options = {}) {
1079
+ return await verifyJsonLdInternal(jsonLd, options, true);
1015
1080
  }
1016
1081
  /** @internal */
1017
- function isPreloadedContextAttachmentSafe(document) {
1018
- if (typeof document !== "object" || document == null) return true;
1019
- const context = document["@context"];
1020
- for (const contextObject of getContextObjects(context)) {
1021
- if (!Object.hasOwn(contextObject, "attachment")) continue;
1022
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
1023
- return false;
1024
- }
1025
- return true;
1082
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
1083
+ return await verifyJsonLdInternal(jsonLd, options, false);
1026
1084
  }
1027
- function getKnownSafeContextUrls() {
1028
- const urls = /* @__PURE__ */ new Set();
1029
- for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
1030
- else logger$1.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
1031
- return urls;
1085
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
1086
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
1087
+ const start = performance.now();
1088
+ let verified = false;
1089
+ let threw = false;
1090
+ let signatureType;
1091
+ try {
1092
+ const hasLdSignature = hasVerifiableSignature(jsonLd);
1093
+ const verificationOptions = hasLdSignature ? {
1094
+ ...options,
1095
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
1096
+ } : options;
1097
+ const compacted = compact ? hasLdSignature ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
1098
+ const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
1099
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
1100
+ span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
1101
+ const sig = getLdSignatureObject(jsonLd);
1102
+ if (sig != null) {
1103
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
1104
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
1105
+ if (typeof sig.type === "string") {
1106
+ span.setAttribute("ld_signatures.type", sig.type);
1107
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
1108
+ }
1109
+ }
1110
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
1111
+ if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
1112
+ const key = await verifySignature(compacted, verificationOptions);
1113
+ if (key == null) return false;
1114
+ if (key.ownerId == null) {
1115
+ logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
1116
+ return false;
1117
+ }
1118
+ attributions.delete(key.ownerId.href);
1119
+ if (attributions.size > 0) {
1120
+ logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
1121
+ return false;
1122
+ }
1123
+ verified = true;
1124
+ return true;
1125
+ } catch (error) {
1126
+ threw = true;
1127
+ span.setStatus({
1128
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
1129
+ message: String(error)
1130
+ });
1131
+ throw error;
1132
+ } finally {
1133
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
1134
+ require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "linked_data", classified, { ldType: signatureType });
1135
+ span.end();
1136
+ }
1137
+ });
1032
1138
  }
1139
+ const tolerableVerificationWarnings = new Set(["blank node predicate", "invalid property"]);
1140
+ function handleVerificationEvent({ event, next }) {
1141
+ if (event.level === "warning" && !tolerableVerificationWarnings.has(event.code)) throw new TypeError(`Unsafe JSON-LD canonicalization warning: ${event.code}`);
1142
+ next();
1143
+ }
1144
+ async function hashJsonLd(jsonLd, contextLoader, mode = "sign") {
1145
+ const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
1146
+ format: "application/n-quads",
1147
+ documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
1148
+ safe: mode === "sign",
1149
+ eventHandler: mode === "verify" ? handleVerificationEvent : void 0
1150
+ });
1151
+ const encoder = new TextEncoder();
1152
+ return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
1153
+ }
1154
+ //#endregion
1155
+ //#region src/sig/owner.ts
1156
+ const logger$1 = (0, _logtape_logtape.getLogger)([
1157
+ "fedify",
1158
+ "sig",
1159
+ "owner"
1160
+ ]);
1033
1161
  /**
1034
- * Wraps scalar ActivityStreams attachment properties in arrays.
1035
- */
1036
- function wrapScalarAttachments(jsonLd, depth = 0) {
1037
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
1038
- if (Array.isArray(jsonLd)) {
1039
- let normalized = null;
1040
- for (let i = 0; i < jsonLd.length; i++) {
1041
- const item = jsonLd[i];
1042
- const next = wrapScalarAttachments(item, depth + 1);
1043
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
1044
- if (normalized != null) normalized[i] = next;
1162
+ * Checks if the actor of the given activity owns the specified key.
1163
+ *
1164
+ * Ownership is never taken from what the activity or the key say about
1165
+ * themselves, as both are written by whoever sent the activity. It is
1166
+ * established from a document that the owner itself serves: either the key's
1167
+ * claimed owner links back to the key, or the actor the activity claims lists
1168
+ * the key as its own.
1169
+ *
1170
+ * @param activity The activity to check.
1171
+ * @param key The public key to check.
1172
+ * @param options Options for checking the key ownership.
1173
+ * @returns Whether the actor is the owner of the key.
1174
+ */
1175
+ async function doesActorOwnKey(activity, key, options) {
1176
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
1177
+ kind: _opentelemetry_api.SpanKind.INTERNAL,
1178
+ attributes: {
1179
+ "activitypub.actor.id": activity.actorId?.href ?? "",
1180
+ "activitypub.key.id": key.id?.href ?? ""
1045
1181
  }
1046
- return normalized ?? jsonLd;
1047
- }
1048
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
1049
- const record = jsonLd;
1050
- const keys = Object.keys(record);
1051
- let normalized = null;
1052
- for (let i = 0; i < keys.length; i++) {
1053
- const key = keys[i];
1054
- const value = record[key];
1055
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
1056
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
1057
- if (normalized == null && output !== value) {
1058
- const cloned = Object.create(null);
1059
- for (let j = 0; j < i; j++) {
1060
- const previousKey = keys[j];
1061
- cloned[previousKey] = record[previousKey];
1182
+ }, async (span) => {
1183
+ try {
1184
+ const actorId = activity.actorId;
1185
+ if (actorId == null) {
1186
+ span.setAttribute("activitypub.key_ownership.verified", false);
1187
+ span.setAttribute("activitypub.key_ownership.method", "none");
1188
+ return false;
1062
1189
  }
1063
- normalized = cloned;
1190
+ if (key.ownerId != null) {
1191
+ const owner = await require_http.verifyKeyOwnership(key, options);
1192
+ if (owner?.id != null && owner.id.href === actorId.href) {
1193
+ span.setAttribute("activitypub.key_ownership.verified", true);
1194
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
1195
+ return true;
1196
+ }
1197
+ }
1198
+ const actor = await require_http.fetchActorDocument(actorId, options);
1199
+ if (actor != null && await doesActorListKey(actor, key, options)) {
1200
+ span.setAttribute("activitypub.key_ownership.verified", true);
1201
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
1202
+ return true;
1203
+ }
1204
+ logger$1.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
1205
+ actorId: actorId.href,
1206
+ keyId: key.id?.href
1207
+ });
1208
+ span.setAttribute("activitypub.key_ownership.verified", false);
1209
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
1210
+ return false;
1211
+ } catch (error) {
1212
+ span.recordException(error);
1213
+ span.setStatus({
1214
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
1215
+ message: String(error)
1216
+ });
1217
+ throw error;
1218
+ } finally {
1219
+ span.end();
1064
1220
  }
1065
- if (normalized != null) normalized[key] = output;
1066
- }
1067
- return normalized ?? jsonLd;
1221
+ });
1068
1222
  }
1069
- function hasNestedContext(value, depth = 0) {
1070
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1071
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
1072
- if (typeof value !== "object" || value == null) return false;
1073
- const record = value;
1074
- for (const key of Object.keys(record)) {
1075
- if (key === "@context") return true;
1076
- if (key === "@value" && isJsonLdValueObject(value)) continue;
1077
- if (hasNestedContext(record[key], depth + 1)) return true;
1223
+ /**
1224
+ * Determines whether the given actor's own document lists the given key among
1225
+ * its public keys.
1226
+ *
1227
+ * Keys are matched by id, which is what an actor document links to. A key
1228
+ * document may leave its id implicit, though, and then there is no id for the
1229
+ * actor to link to; the key material itself is the only thing the two can
1230
+ * have in common, so that is what gets compared.
1231
+ */
1232
+ async function doesActorListKey(actor, key, options) {
1233
+ if (key.id != null) {
1234
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
1235
+ return false;
1078
1236
  }
1079
- return false;
1080
- }
1081
- function exceedsTraversalDepth(value, depth = 0) {
1082
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1083
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
1084
- if (typeof value !== "object" || value == null) return false;
1085
- const record = value;
1086
- for (const key of Object.keys(record)) {
1087
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
1088
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
1237
+ if (key.publicKey == null) return false;
1238
+ const publicKeys = actor.getPublicKeys({
1239
+ ...options,
1240
+ suppressError: true
1241
+ });
1242
+ for await (const publicKey of publicKeys) {
1243
+ if (publicKey.publicKey == null) continue;
1244
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
1089
1245
  }
1090
1246
  return false;
1091
1247
  }
1092
- function hasKnownSafeContext(jsonLd) {
1093
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
1094
- const record = jsonLd;
1095
- if (!Object.hasOwn(record, "@context")) return false;
1096
- const context = record["@context"];
1097
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
1098
- if (entries == null || entries.length < 1) return false;
1099
- let hasActivityStreamsContext = false;
1100
- for (const entry of entries) {
1101
- if (typeof entry !== "string") return false;
1102
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
1103
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
1104
- }
1105
- if (!hasActivityStreamsContext) return false;
1106
- for (const key of Object.keys(record)) {
1107
- if (key === "@context") continue;
1108
- if (hasNestedContext(record[key])) return false;
1109
- }
1110
- return true;
1111
- }
1112
- function getLogSafeJsonLdMetadata(jsonLd) {
1113
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
1114
- const record = jsonLd;
1115
- const context = record["@context"];
1116
- return {
1117
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
1118
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
1119
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
1120
- };
1248
+ /**
1249
+ * Compares two public keys by their key material, ignoring the metadata that
1250
+ * surrounds it.
1251
+ */
1252
+ async function isSamePublicKey(a, b) {
1253
+ const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
1254
+ 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;
1121
1255
  }
1122
1256
  /**
1123
- * Ensures ActivityStreams attachment properties are represented as arrays
1124
- * when doing so preserves the JSON-LD semantics.
1257
+ * Gets the actor that owns the specified key. Returns `null` if the key has no
1258
+ * known owner.
1125
1259
  *
1126
- * JSON-LD compaction collapses single-item arrays into scalar values by
1127
- * default. Some ActivityPub implementations, Pixelfed among them, parse
1128
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
1129
- * otherwise valid objects whose single attachment is emitted as a scalar.
1260
+ * The owner is only returned when the key and the owner link to each other:
1261
+ * a document that merely claims to own a key is not enough, as the claim and
1262
+ * the key can come from the same host.
1130
1263
  *
1131
- * When no `contextLoader` is supplied, the helper falls back to a restricted
1132
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
1133
- * every other URL without network access. Documents with custom, inline, or
1134
- * otherwise uncached contexts should pass a real `contextLoader` if they need
1135
- * the semantic-preservation check to succeed; otherwise canonicalization
1136
- * failures leave the original document unchanged.
1264
+ * @param keyId The ID of the key to check, or the key itself.
1265
+ * @param options Options for getting the key owner.
1266
+ * @returns The actor that owns the key, or `null` if the key has no known
1267
+ * owner.
1268
+ * @since 0.7.0
1137
1269
  */
1138
- async function normalizeAttachmentArrays(jsonLd, contextLoader) {
1139
- const normalized = wrapScalarAttachments(jsonLd);
1140
- if (normalized === jsonLd) return jsonLd;
1141
- if (exceedsTraversalDepth(jsonLd)) {
1142
- logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
1143
- return jsonLd;
1270
+ async function getKeyOwner(keyId, options) {
1271
+ const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
1272
+ const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
1273
+ const fetchOptions = {
1274
+ documentLoader,
1275
+ contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
1276
+ tracerProvider
1277
+ };
1278
+ if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
1279
+ let keyDoc;
1280
+ let documentUrl = keyId;
1281
+ try {
1282
+ const remoteDocument = await documentLoader(keyId.href);
1283
+ keyDoc = remoteDocument.document;
1284
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
1285
+ } catch (_) {
1286
+ return null;
1144
1287
  }
1145
- if (hasKnownSafeContext(jsonLd)) return normalized;
1146
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
1288
+ let object;
1147
1289
  try {
1148
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
1149
- format: "application/n-quads",
1150
- documentLoader: loader
1151
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
1152
- format: "application/n-quads",
1153
- documentLoader: loader
1154
- })]);
1155
- if (before === after) return normalized;
1156
- logger$1.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));
1157
- } catch (error) {
1158
- logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
1290
+ object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
1291
+ ...fetchOptions,
1292
+ baseUrl: documentUrl
1293
+ });
1294
+ } catch (e) {
1295
+ if (!(e instanceof TypeError)) throw e;
1296
+ try {
1297
+ object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
1298
+ } catch (e) {
1299
+ if (e instanceof TypeError) return null;
1300
+ throw e;
1301
+ }
1159
1302
  }
1160
- return jsonLd;
1161
- }
1162
- /**
1163
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
1164
- * to locally generated outgoing activities before they are signed, enqueued,
1165
- * or sent.
1166
- */
1167
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
1168
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
1169
- return await normalizeAttachmentArrays(jsonLd, contextLoader);
1303
+ if (object instanceof _fedify_vocab.CryptographicKey) {
1304
+ if (object.id != null && object.id.href !== keyId.href) return null;
1305
+ return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
1306
+ }
1307
+ if (!(0, _fedify_vocab.isActor)(object)) return null;
1308
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
1309
+ logger$1.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
1310
+ documentUrl: documentUrl.href,
1311
+ actorId: object.id?.href,
1312
+ keyId: keyId.href
1313
+ });
1314
+ return null;
1315
+ }
1316
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
1317
+ return null;
1170
1318
  }
1171
1319
  //#endregion
1172
1320
  //#region src/sig/proof.ts
@@ -1223,7 +1371,10 @@ function hasProofLike(jsonLd) {
1223
1371
  * @throws {TypeError} If the private key is invalid or unsupported.
1224
1372
  * @since 0.10.0
1225
1373
  */
1226
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
1374
+ async function createProof(object, privateKey, keyId, options = {}) {
1375
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
1376
+ }
1377
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
1227
1378
  require_http.validateCryptoKey(privateKey, "private");
1228
1379
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
1229
1380
  let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -1250,14 +1401,26 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
1250
1401
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
1251
1402
  digest.set(new Uint8Array(proofDigest), 0);
1252
1403
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
1253
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
1254
- return new _fedify_vocab.DataIntegrityProof({
1255
- cryptosuite: "eddsa-jcs-2022",
1256
- verificationMethod: keyId,
1257
- proofPurpose: "assertionMethod",
1258
- created: created ?? Temporal.Now.instant(),
1259
- proofValue: new Uint8Array(sig)
1260
- });
1404
+ const sig = await crypto.subtle.sign("Ed25519", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), digest);
1405
+ return {
1406
+ proof: new _fedify_vocab.DataIntegrityProof({
1407
+ cryptosuite: "eddsa-jcs-2022",
1408
+ verificationMethod: keyId,
1409
+ proofPurpose: "assertionMethod",
1410
+ created: created ?? Temporal.Now.instant(),
1411
+ proofValue: new Uint8Array(sig)
1412
+ }),
1413
+ jsonLd: compactMsg
1414
+ };
1415
+ }
1416
+ function getJsonLdContextKey(value) {
1417
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
1418
+ return JSON.stringify(sortJsonKeys(context));
1419
+ }
1420
+ function sortJsonKeys(value) {
1421
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
1422
+ if (typeof value !== "object" || value == null) return value;
1423
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
1261
1424
  }
1262
1425
  /**
1263
1426
  * Signs the given object with the private key and returns the signed object.
@@ -1273,9 +1436,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
1273
1436
  return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(object).href } }, async (span) => {
1274
1437
  try {
1275
1438
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
1439
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
1276
1440
  const existingProofs = [];
1277
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
1278
- const proof = await createProof(object, privateKey, keyId, options);
1441
+ let hasProofs = object.proofIds.length > 0;
1442
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
1443
+ hasProofs = true;
1444
+ break;
1445
+ }
1446
+ if (hasProofs) {
1447
+ let sameContext = true;
1448
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
1449
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
1450
+ }
1279
1451
  if (span.isRecording()) {
1280
1452
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
1281
1453
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -1495,6 +1667,12 @@ Object.defineProperty(exports, "createSignature", {
1495
1667
  return createSignature;
1496
1668
  }
1497
1669
  });
1670
+ Object.defineProperty(exports, "describeSignatureShape", {
1671
+ enumerable: true,
1672
+ get: function() {
1673
+ return describeSignatureShape;
1674
+ }
1675
+ });
1498
1676
  Object.defineProperty(exports, "detachSignature", {
1499
1677
  enumerable: true,
1500
1678
  get: function() {
@@ -1525,16 +1703,16 @@ Object.defineProperty(exports, "hasProofLike", {
1525
1703
  return hasProofLike;
1526
1704
  }
1527
1705
  });
1528
- Object.defineProperty(exports, "hasSignature", {
1706
+ Object.defineProperty(exports, "hasSignatureLike", {
1529
1707
  enumerable: true,
1530
1708
  get: function() {
1531
- return hasSignature;
1709
+ return hasSignatureLike;
1532
1710
  }
1533
1711
  });
1534
- Object.defineProperty(exports, "hasSignatureLike", {
1712
+ Object.defineProperty(exports, "hasVerifiableSignature", {
1535
1713
  enumerable: true,
1536
1714
  get: function() {
1537
- return hasSignatureLike;
1715
+ return hasVerifiableSignature;
1538
1716
  }
1539
1717
  });
1540
1718
  Object.defineProperty(exports, "isClearlyMalformedContextReference", {
@@ -1549,6 +1727,12 @@ Object.defineProperty(exports, "isInvalidUrlTypeError", {
1549
1727
  return isInvalidUrlTypeError;
1550
1728
  }
1551
1729
  });
1730
+ Object.defineProperty(exports, "normalizeAttachmentArrays", {
1731
+ enumerable: true,
1732
+ get: function() {
1733
+ return normalizeAttachmentArrays;
1734
+ }
1735
+ });
1552
1736
  Object.defineProperty(exports, "normalizeOutgoingActivityJsonLd", {
1553
1737
  enumerable: true,
1554
1738
  get: function() {