@fedify/fedify 2.4.0-dev.1964 → 2.4.0-dev.1995

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 (94) hide show
  1. package/dist/{builder-B4zpKIFU.mjs → builder-D0DxgOV5.mjs} +2 -2
  2. package/dist/{client-CtxvmazV.mjs → client-DpnpgjyX.mjs} +78 -4
  3. package/dist/compat/mod.d.cts +1 -1
  4. package/dist/compat/mod.d.ts +1 -1
  5. package/dist/compat/transformers.test.mjs +1 -1
  6. package/dist/compound-proof-CJnWc6c-.mjs +495 -0
  7. package/dist/{context-COLwHogJ.d.cts → context-BeDnDuF3.d.cts} +4 -3
  8. package/dist/{context-DiiCt4S7.d.ts → context-uyRUWoZQ.d.ts} +4 -3
  9. package/dist/{deno-CtG93ohj.mjs → deno-CABhzCb_.mjs} +1 -1
  10. package/dist/{docloader-dk_k3S8d.mjs → docloader-BbGSL0Xq.mjs} +2 -2
  11. package/dist/federation/builder.test.mjs +1 -1
  12. package/dist/federation/handler-compound-proof.test.d.mts +2 -0
  13. package/dist/federation/handler-compound-proof.test.mjs +152 -0
  14. package/dist/federation/handler.test.mjs +122 -4
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/keycache.test.mjs +52 -9
  17. package/dist/federation/metrics.test.mjs +1 -1
  18. package/dist/federation/middleware.test.mjs +111 -15
  19. package/dist/federation/mod.cjs +1 -1
  20. package/dist/federation/mod.d.cts +2 -2
  21. package/dist/federation/mod.d.ts +2 -2
  22. package/dist/federation/mod.js +1 -1
  23. package/dist/federation/send.test.mjs +139 -4
  24. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  25. package/dist/federation/tasks/tasks.test.mjs +2 -2
  26. package/dist/federation/temporal.test.mjs +1 -1
  27. package/dist/federation/webfinger.test.mjs +1 -1
  28. package/dist/{federation-Drjlrrax.cjs → federation-DCEHQk4G.cjs} +632 -57
  29. package/dist/{http-6TI0tI03.d.cts → http-65PYi9jY.d.ts} +34 -2
  30. package/dist/{http-Dj4s1UQ0.js → http-9WyuldYh.js} +170 -8
  31. package/dist/{http-CdrSn2ip.d.ts → http-CP-7OdSq.d.cts} +34 -2
  32. package/dist/{http-B3skRvGo.cjs → http-CRFns-UE.cjs} +181 -7
  33. package/dist/{http-D7LX-BL9.mjs → http-D9urSO2D.mjs} +3 -3
  34. package/dist/{key-BVjgbs_9.mjs → key-Ccs8cnd7.mjs} +169 -7
  35. package/dist/{keycache-ZLqIfrkL.mjs → keycache-BUDHB5rY.mjs} +12 -4
  36. package/dist/{kv-cache-DtsjH_bY.cjs → kv-cache-DXT9vmIg.cjs} +2 -2
  37. package/dist/{kv-cache-tGNbvDCF.js → kv-cache-DtmXhPXG.js} +2 -2
  38. package/dist/{kv-cache-xRcC_xxP.mjs → kv-cache-lKyFn_Dn.mjs} +1 -1
  39. package/dist/{ld-OuCeQFny.mjs → ld-qup__MAW.mjs} +3 -3
  40. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +204 -0
  41. package/dist/map-local-create-note-B0SeXJms.mjs +214 -0
  42. package/dist/{metrics-B9N27cCB.mjs → metrics-CISXCvB1.mjs} +1 -1
  43. package/dist/{middleware-TeLjzoxn.mjs → middleware-CzvJvPHK.mjs} +58 -15
  44. package/dist/{middleware-Cd_vPqDH.mjs → middleware-DkrU2WhY.mjs} +1 -1
  45. package/dist/{middleware-CPTDFMmJ.js → middleware-DsfWajaD.js} +593 -18
  46. package/dist/{mod-DypxPS9H.d.ts → mod-C0BYc0OU.d.ts} +1 -1
  47. package/dist/{mod-CnGLNoVw.d.cts → mod-CbKDOnCt.d.cts} +1 -1
  48. package/dist/{mod-CLHkCwLm.d.cts → mod-CyiSjRkk.d.cts} +1 -1
  49. package/dist/{mod-CSH1Ee-I.d.ts → mod-D882_Xsg.d.ts} +1 -1
  50. package/dist/{mod-DzRXACM5.d.ts → mod-UDwMjuHM.d.ts} +1 -1
  51. package/dist/{mod-BZldCEU0.d.cts → mod-x9W0d0Pk.d.cts} +1 -1
  52. package/dist/mod.cjs +20 -20
  53. package/dist/mod.d.cts +6 -6
  54. package/dist/mod.d.ts +6 -6
  55. package/dist/mod.js +5 -5
  56. package/dist/nodeinfo/client.test.mjs +28 -1
  57. package/dist/nodeinfo/handler.test.mjs +1 -1
  58. package/dist/nodeinfo/mod.cjs +1 -1
  59. package/dist/nodeinfo/mod.js +1 -1
  60. package/dist/{owner-DGSfntI-.d.ts → owner-BF0L9cMt.d.cts} +12 -1
  61. package/dist/{proof-BO_esQii.js → owner-BIPEZGiU.js} +1255 -1098
  62. package/dist/{owner-r_waTiQj.d.cts → owner-BSzr5-I8.d.ts} +12 -1
  63. package/dist/owner-CRoq8Spb.mjs +175 -0
  64. package/dist/{proof-Dua0d906.cjs → owner-CVA7L9MA.cjs} +1266 -1097
  65. package/dist/{proof-D5Ajk4DJ.mjs → proof-BDxNVZ3E.mjs} +186 -83
  66. package/dist/{send-DVXyUqhO.mjs → send-BzM5GLyn.mjs} +68 -11
  67. package/dist/sig/compound-proof-discovery.test.d.mts +2 -0
  68. package/dist/sig/compound-proof-discovery.test.mjs +331 -0
  69. package/dist/sig/compound-proof-verification.test.d.mts +2 -0
  70. package/dist/sig/compound-proof-verification.test.mjs +465 -0
  71. package/dist/sig/compound-proof.test.d.mts +2 -0
  72. package/dist/sig/compound-proof.test.mjs +324 -0
  73. package/dist/sig/http.test.mjs +2 -2
  74. package/dist/sig/key.test.mjs +169 -2
  75. package/dist/sig/ld.test.mjs +55 -2
  76. package/dist/sig/mod.cjs +17 -17
  77. package/dist/sig/mod.d.cts +3 -3
  78. package/dist/sig/mod.d.ts +3 -3
  79. package/dist/sig/mod.js +2 -2
  80. package/dist/sig/owner.test.mjs +103 -4
  81. package/dist/sig/proof.test.mjs +120 -1
  82. package/dist/{temporal-BoDw51A-.mjs → temporal-Dv6Qv-8k.mjs} +1 -1
  83. package/dist/testing/kv.test.mjs +1 -1
  84. package/dist/testing/mod.d.mts +2 -1
  85. package/dist/{types-RXm5YxpC.cjs → types-Be2zbyeG.cjs} +94 -2
  86. package/dist/{types-Dtyf8lVj.js → types-C_cNlNVK.js} +78 -4
  87. package/dist/utils/docloader.test.mjs +27 -3
  88. package/dist/utils/kv-cache.test.mjs +1 -1
  89. package/dist/utils/mod.cjs +1 -1
  90. package/dist/utils/mod.d.cts +1 -1
  91. package/dist/utils/mod.d.ts +1 -1
  92. package/dist/utils/mod.js +1 -1
  93. package/package.json +6 -6
  94. package/dist/owner-DTEqTzSr.mjs +0 -120
@@ -1,1117 +1,1006 @@
1
1
  const { URLPattern } = require("urlpattern-polyfill");
2
2
  const require_rolldown_runtime = require("./rolldown-runtime-Dmm3t92W.cjs");
3
- const require_http = require("./http-B3skRvGo.cjs");
3
+ const require_http = require("./http-CRFns-UE.cjs");
4
4
  let _logtape_logtape = require("@logtape/logtape");
5
5
  let _fedify_vocab = require("@fedify/vocab");
6
6
  let _opentelemetry_api = require("@opentelemetry/api");
7
7
  let byte_encodings_hex = require("byte-encodings/hex");
8
8
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
9
- let byte_encodings_base64 = require("byte-encodings/base64");
10
9
  let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
11
10
  _fedify_vocab_runtime_jsonld = require_rolldown_runtime.__toESM(_fedify_vocab_runtime_jsonld, 1);
12
11
  let json_canon = require("json-canon");
13
12
  json_canon = require_rolldown_runtime.__toESM(json_canon, 1);
14
- //#region src/sig/ld.ts
15
- const logger$3 = (0, _logtape_logtape.getLogger)([
13
+ let byte_encodings_base64 = require("byte-encodings/base64");
14
+ //#region src/compat/preloaded-context-loader.ts
15
+ /**
16
+ * A restricted JSON-LD document loader that resolves only contexts bundled
17
+ * with Fedify.
18
+ *
19
+ * This is intentionally narrower than `getDocumentLoader()`: normalization
20
+ * helpers are also reached from verification paths that operate on inbound,
21
+ * attacker-controlled JSON-LD, so the default fallback must never fetch
22
+ * attacker-supplied context URLs.
23
+ */
24
+ const preloadedOnlyDocumentLoader = (url) => {
25
+ if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
26
+ contextUrl: null,
27
+ documentUrl: url,
28
+ document: _fedify_vocab_runtime.preloadedContexts[url]
29
+ });
30
+ return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
31
+ };
32
+ //#endregion
33
+ //#region src/compat/public-audience.ts
34
+ const logger$4 = (0, _logtape_logtape.getLogger)([
16
35
  "fedify",
17
- "sig",
18
- "ld"
36
+ "compat",
37
+ "public-audience"
19
38
  ]);
20
- const localContext = [
21
- "https://w3id.org/identity/v1",
22
- "https://www.w3.org/ns/activitystreams",
23
- "https://w3id.org/security/v1",
24
- "https://w3id.org/security/data-integrity/v1"
25
- ];
26
- const localContextUrls = new Set(localContext);
27
- const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
28
- const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
29
- "@graph",
30
- "@included",
31
- "@reverse"
39
+ const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
40
+ "to",
41
+ "cc",
42
+ "bto",
43
+ "bcc",
44
+ "audience"
32
45
  ]);
33
- /** @internal */
34
- var UnsafeJsonLdError = class extends TypeError {
35
- keyword;
36
- constructor(keyword) {
37
- super(`Unsupported JSON-LD keyword: ${keyword}.`);
38
- this.keyword = keyword;
39
- this.name = "UnsafeJsonLdError";
40
- }
41
- };
42
- /** @internal */
43
- var InvalidContextReferenceError = class extends TypeError {
44
- reference;
45
- constructor(reference) {
46
- super(`Invalid JSON-LD context reference: ${reference}.`);
47
- this.reference = reference;
48
- this.name = "InvalidContextReferenceError";
46
+ const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
47
+ const MAX_TRAVERSAL_DEPTH$1 = 64;
48
+ const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
49
+ function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
50
+ if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
51
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
52
+ if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
53
+ if (typeof value !== "object" || value == null) return false;
54
+ const record = value;
55
+ for (const key of Object.keys(record)) {
56
+ if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
57
+ if (key === "@context") continue;
58
+ if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
49
59
  }
50
- };
51
- function createLoadingRemoteContextFailedError(reference, cause) {
52
- const message = cause instanceof Error ? cause.message : String(cause);
53
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
54
- error.name = "jsonld.InvalidUrl";
55
- error.details = {
56
- code: "loading remote context failed",
57
- url: reference
58
- };
59
- error.cause = cause;
60
- return error;
60
+ return false;
61
61
  }
62
- /** @internal */
63
- function isClearlyMalformedContextReference(reference) {
64
- for (const char of reference) {
65
- const code = char.charCodeAt(0);
66
- if (code <= 32 || code === 127) return true;
62
+ function rewritePublicAudience(value, parentKey, depth = 0) {
63
+ if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
64
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
65
+ if (Array.isArray(value)) {
66
+ let changed = false;
67
+ const mapped = value.map((item) => {
68
+ const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
69
+ if (rewritten !== item) changed = true;
70
+ return rewritten;
71
+ });
72
+ return changed ? mapped : value;
67
73
  }
68
- if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
69
- for (let i = 0; i < reference.length; i++) {
70
- if (reference[i] !== "%") continue;
71
- if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
72
- i += 2;
74
+ if (typeof value !== "object" || value == null) return value;
75
+ const record = value;
76
+ let changed = false;
77
+ const normalized = Object.create(null);
78
+ for (const key of Object.keys(record)) {
79
+ 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);
80
+ if (rewritten !== record[key]) changed = true;
81
+ normalized[key] = rewritten;
73
82
  }
74
- if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
75
- for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
83
+ return changed ? normalized : value;
84
+ }
85
+ /**
86
+ * Reports whether `value` carries an `@context` property anywhere inside
87
+ * its subtree (not counting the value itself). A nested `@context` can
88
+ * introduce a local term-definition scope that redefines `as:` or `Public`
89
+ * even when the top-level `@context` is safe, so the fast path must defer
90
+ * to the URDNA2015 equivalence check whenever one is present.
91
+ */
92
+ function hasNestedContext$1(value, depth = 0) {
93
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
94
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
95
+ if (typeof value !== "object" || value == null) return false;
96
+ const record = value;
97
+ for (const key of Object.keys(record)) {
98
+ if (key === "@context") return true;
99
+ if (hasNestedContext$1(record[key], depth + 1)) return true;
76
100
  }
77
101
  return false;
78
102
  }
79
- function cloneRemoteDocument(remoteDocument) {
80
- return structuredClone(remoteDocument);
81
- }
82
- function createMemoizedDocumentLoader(documentLoader) {
83
- const cache = /* @__PURE__ */ new Map();
84
- return async (url, options) => {
85
- const cacheKey = URL.canParse(url) ? new URL(url).href : url;
86
- let remoteDocument = cache.get(cacheKey);
87
- if (remoteDocument == null) {
88
- remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
89
- remoteDocument.catch(() => {
90
- if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
91
- });
92
- cache.set(cacheKey, remoteDocument);
93
- }
94
- return cloneRemoteDocument(await remoteDocument);
95
- };
103
+ /**
104
+ * Checks whether the `@context` of a JSON-LD document is guaranteed not
105
+ * to redefine the `as:` prefix or the bare `Public` term. Only documents
106
+ * whose `@context` is a string, or an array of strings, drawn from Fedify's
107
+ * preloaded context set AND including the ActivityStreams URL qualify,
108
+ * AND no nested subtree carries its own `@context` that might redefine
109
+ * those terms within a local scope. When all of that holds the rewrite
110
+ * is provably semantics-preserving and the URDNA2015 equivalence check
111
+ * can be skipped. Any other shape (unknown external URLs, inline
112
+ * objects at the top level, nested `@context` blocks) is treated as
113
+ * potentially unsafe.
114
+ */
115
+ function hasKnownSafeContext$1(jsonLd) {
116
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
117
+ const record = jsonLd;
118
+ if (!Object.hasOwn(record, "@context")) return false;
119
+ const ctx = record["@context"];
120
+ const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
121
+ if (entries == null || entries.length === 0) return false;
122
+ let hasAs = false;
123
+ for (const entry of entries) {
124
+ if (typeof entry !== "string") return false;
125
+ if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
126
+ if (entry === AS_CONTEXT_URL$1) hasAs = true;
127
+ }
128
+ if (!hasAs) return false;
129
+ for (const key of Object.keys(record)) {
130
+ if (key === "@context") continue;
131
+ if (hasNestedContext$1(record[key])) return false;
132
+ }
133
+ return true;
96
134
  }
97
- /** @internal */
98
- function wrapContextLoaderForJsonLd(contextLoader) {
99
- const loader = contextLoader ?? builtInContextLoader;
100
- return async (url, options) => {
101
- try {
102
- return await loader(url, options);
103
- } catch (error) {
104
- if (!isInvalidUrlTypeError(error)) throw error;
105
- if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
106
- throw createLoadingRemoteContextFailedError(url, error);
107
- }
108
- };
135
+ /**
136
+ * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
137
+ * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
138
+ * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
139
+ *
140
+ * Several ActivityPub implementations, Lemmy among them, match these
141
+ * fields as plain URLs without running JSON-LD expansion, and silently
142
+ * drop activities whose public addressing appears in CURIE form. This
143
+ * helper works around that gap.
144
+ *
145
+ * For documents whose `@context` is drawn entirely from Fedify's
146
+ * preloaded context set and includes the ActivityStreams URL, the
147
+ * rewrite is applied directly: the content of every preloaded non-AS
148
+ * context is known not to redefine the `as:` prefix or the bare `Public`
149
+ * term, so the semantics are preserved by construction. Any other
150
+ * shape (an inline object, an unknown external URL, and so on) is
151
+ * treated as potentially unsafe and gated on a JSON-LD equivalence
152
+ * check; both forms are canonicalized with URDNA2015 and the resulting
153
+ * N-Quads are compared. When they differ, the original document is
154
+ * returned unchanged. Canonicalization failures also fall back to the
155
+ * original document.
156
+ *
157
+ * When no `contextLoader` is supplied the helper falls back to an
158
+ * internal loader that resolves only the URLs in Fedify's
159
+ * preloaded-contexts set and rejects every other URL without issuing a
160
+ * network request. That behaviour is deliberately narrower than
161
+ * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
162
+ * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
163
+ * helper is reached from verification paths (`verifyProof()` /
164
+ * `verifyObject()`) that operate on inbound, potentially adversarial
165
+ * JSON-LD, and a default loader that fetches attacker-supplied
166
+ * `@context` URLs on the caller's behalf would be an SSRF vector.
167
+ * Canonicalization failures against the restricted loader fall back to
168
+ * the original document, same as any other canonicalization error.
169
+ * Callers that genuinely need the remote-fetch loader (for example
170
+ * applications that sign local JSON-LD against a custom vocabulary)
171
+ * should pass a `contextLoader` explicitly.
172
+ *
173
+ * Must be called before any signing step that canonicalizes the
174
+ * compact form byte-for-byte (for example, Object Integrity Proofs
175
+ * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
176
+ * matches what is sent on the wire.
177
+ */
178
+ async function normalizePublicAudience(jsonLd, contextLoader) {
179
+ if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
180
+ const normalized = rewritePublicAudience(jsonLd);
181
+ if (hasKnownSafeContext$1(jsonLd)) return normalized;
182
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
183
+ try {
184
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
185
+ format: "application/n-quads",
186
+ documentLoader: loader
187
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
188
+ format: "application/n-quads",
189
+ documentLoader: loader
190
+ })]);
191
+ if (before === after) return normalized;
192
+ 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.");
193
+ } catch (error) {
194
+ logger$4.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
195
+ }
196
+ return jsonLd;
109
197
  }
110
- /** @internal */
111
- function getNormalizationContextLoader(contextLoader) {
112
- const loader = wrapContextLoaderForJsonLd(contextLoader);
113
- return createMemoizedDocumentLoader(async (url, options) => {
114
- if (URL.canParse(url)) {
115
- const normalizedUrl = new URL(url).href;
116
- if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
117
- }
118
- return await loader(url, options);
119
- });
120
- }
121
- /** @internal */
122
- async function compactJsonLd(jsonLd, contextLoader) {
123
- const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
124
- const signature = hasLds ? jsonLd.signature : void 0;
125
- const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
126
- const document = hasLds ? detachSignature(jsonLd) : jsonLd;
127
- await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
128
- const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
129
- if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
130
- assertSafeJsonLd(compacted);
131
- return compacted;
132
- }
133
- function createInvalidRemoteContextError(reference) {
134
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${reference}".`);
135
- error.name = "jsonld.InvalidUrl";
136
- error.details = {
137
- code: "invalid remote context",
138
- url: reference
139
- };
140
- return error;
141
- }
142
- function getRemoteContext(remoteDocument, reference) {
143
- const { contextUrl, documentUrl } = remoteDocument;
144
- let { document } = remoteDocument;
145
- if (typeof document === "string") document = JSON.parse(document);
146
- if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
147
- let context = "@context" in document ? document["@context"] : {};
148
- if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
149
- return {
150
- context,
151
- baseUrl: documentUrl ?? reference
152
- };
153
- }
154
- function createGraphAliasContextState() {
155
- return {
156
- graphTerms: /* @__PURE__ */ new Set(),
157
- jsonTerms: /* @__PURE__ */ new Set(),
158
- propertyContexts: /* @__PURE__ */ new Map(),
159
- termTargets: /* @__PURE__ */ new Map()
160
- };
161
- }
162
- function cloneGraphAliasContextState(state) {
163
- return {
164
- graphTerms: new Set(state.graphTerms),
165
- jsonTerms: new Set(state.jsonTerms),
166
- propertyContexts: new Map(state.propertyContexts),
167
- termTargets: new Map(state.termTargets)
168
- };
198
+ //#endregion
199
+ //#region src/compat/outgoing-jsonld.ts
200
+ const logger$3 = (0, _logtape_logtape.getLogger)([
201
+ "fedify",
202
+ "compat",
203
+ "outgoing-jsonld"
204
+ ]);
205
+ const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
206
+ const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
207
+ const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
208
+ const MAX_TRAVERSAL_DEPTH = 64;
209
+ function isJsonLdListObject(value) {
210
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
169
211
  }
170
- function resolveContextTarget(target, state) {
171
- if (target === "@graph") return target;
172
- const mapped = state.termTargets.get(target);
173
- if (mapped == null) return target;
174
- return mapped;
212
+ function isJsonLdValueObject(value) {
213
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
175
214
  }
176
- function getDirectContextTarget(definition) {
177
- if (definition === null) return null;
178
- if (typeof definition === "string") return definition;
179
- if (typeof definition === "object" && definition != null && "@id" in definition) {
180
- const id = definition["@id"];
181
- if (id === null) return null;
182
- if (typeof id === "string") return id;
215
+ function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
216
+ if (Array.isArray(value)) {
217
+ if (seen.has(value)) return;
218
+ seen.add(value);
219
+ for (const item of value) yield* getContextObjects(item, seen);
220
+ return;
183
221
  }
184
- }
185
- function isJsonTypedDefinition(definition) {
186
- return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
187
- }
188
- function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
189
- if (target === "@graph") return target;
190
- if (seen.has(target)) return target;
191
- seen.add(target);
192
- if (localTargets.has(target)) {
193
- const localTarget = localTargets.get(target);
194
- return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
222
+ if (typeof value === "object" && value != null) {
223
+ if (seen.has(value)) return;
224
+ seen.add(value);
225
+ const record = value;
226
+ yield record;
227
+ for (const definition of Object.values(record)) {
228
+ if (typeof definition !== "object" || definition == null) continue;
229
+ const nestedContext = definition["@context"];
230
+ if (nestedContext == null) continue;
231
+ yield* getContextObjects(nestedContext, seen);
232
+ }
195
233
  }
196
- return resolveContextTarget(target, state);
197
- }
198
- function refreshGraphAliases(state) {
199
- state.graphTerms.clear();
200
- for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
201
234
  }
202
- function normalizeContextReference(reference, baseUrl) {
203
- if (baseUrl != null) return new URL(reference, baseUrl).href;
204
- return URL.canParse(reference) ? new URL(reference).href : reference;
235
+ function isActivityStreamsAttachmentTerm(value) {
236
+ return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
205
237
  }
206
238
  /** @internal */
207
- function isInvalidUrlTypeError(error) {
208
- const code = error.code;
209
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
210
- }
211
- async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
212
- if (context === null) return createGraphAliasContextState();
213
- let nextState = cloneGraphAliasContextState(state);
214
- if (Array.isArray(context)) {
215
- for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
216
- return nextState;
239
+ function isPreloadedContextAttachmentSafe(document) {
240
+ if (typeof document !== "object" || document == null) return true;
241
+ const context = document["@context"];
242
+ for (const contextObject of getContextObjects(context)) {
243
+ if (!Object.hasOwn(contextObject, "attachment")) continue;
244
+ if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
245
+ return false;
217
246
  }
218
- if (typeof context === "string") {
219
- const reference = normalizeContextReference(context, baseUrl);
220
- const cacheKey = `${baseUrl ?? ""}\n${reference}`;
221
- if (processingContexts.has(cacheKey)) return nextState;
222
- processingContexts.add(cacheKey);
223
- try {
224
- let remoteContext = remoteContextCache.get(cacheKey);
225
- if (remoteContext == null) {
226
- remoteContext = (async () => {
227
- try {
228
- return getRemoteContext(await documentLoader(reference), reference);
229
- } catch (error) {
230
- if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
231
- throw error;
232
- }
233
- })();
234
- remoteContextCache.set(cacheKey, remoteContext);
235
- }
236
- const loadedRemoteContext = await remoteContext;
237
- return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
238
- } finally {
239
- processingContexts.delete(cacheKey);
247
+ return true;
248
+ }
249
+ function getKnownSafeContextUrls() {
250
+ const urls = /* @__PURE__ */ new Set();
251
+ for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
252
+ 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 });
253
+ return urls;
254
+ }
255
+ /**
256
+ * Wraps scalar ActivityStreams attachment properties in arrays.
257
+ */
258
+ function wrapScalarAttachments(jsonLd, depth = 0) {
259
+ if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
260
+ if (Array.isArray(jsonLd)) {
261
+ let normalized = null;
262
+ for (let i = 0; i < jsonLd.length; i++) {
263
+ const item = jsonLd[i];
264
+ const next = wrapScalarAttachments(item, depth + 1);
265
+ if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
266
+ if (normalized != null) normalized[i] = next;
240
267
  }
268
+ return normalized ?? jsonLd;
241
269
  }
242
- if (typeof context === "object" && context != null) {
243
- if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
244
- const localTargets = /* @__PURE__ */ new Map();
245
- for (const [term, definition] of globalThis.Object.entries(context)) {
246
- if (term.startsWith("@")) continue;
247
- const target = getDirectContextTarget(definition);
248
- if (target == null) localTargets.set(term, null);
249
- else if (typeof target === "string") localTargets.set(term, target);
250
- else localTargets.delete(term);
251
- }
252
- for (const [term, definition] of globalThis.Object.entries(context)) {
253
- if (term.startsWith("@")) continue;
254
- if (localTargets.has(term)) {
255
- const directTarget = localTargets.get(term);
256
- if (directTarget == null) nextState.termTargets.set(term, null);
257
- else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
258
- } else nextState.termTargets.delete(term);
259
- if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
260
- context: definition["@context"],
261
- baseUrl
262
- });
263
- else nextState.propertyContexts.delete(term);
264
- if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
265
- else nextState.jsonTerms.delete(term);
270
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
271
+ const record = jsonLd;
272
+ const keys = Object.keys(record);
273
+ let normalized = null;
274
+ for (let i = 0; i < keys.length; i++) {
275
+ const key = keys[i];
276
+ const value = record[key];
277
+ const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
278
+ const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
279
+ if (normalized == null && output !== value) {
280
+ const cloned = Object.create(null);
281
+ for (let j = 0; j < i; j++) {
282
+ const previousKey = keys[j];
283
+ cloned[previousKey] = record[previousKey];
284
+ }
285
+ normalized = cloned;
266
286
  }
267
- refreshGraphAliases(nextState);
287
+ if (normalized != null) normalized[key] = output;
268
288
  }
269
- return nextState;
289
+ return normalized ?? jsonLd;
270
290
  }
271
- async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
272
- if (Array.isArray(jsonLd)) {
273
- for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
274
- return;
275
- }
276
- if (typeof jsonLd !== "object" || jsonLd == null) return;
277
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
278
- let state = inheritedState;
279
- if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
280
- if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
281
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
282
- if (key === "@context") continue;
283
- if (jsonLiteralWrapper && key === "@value") continue;
284
- if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
285
- if (state.jsonTerms.has(key)) continue;
286
- await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
291
+ function hasNestedContext(value, depth = 0) {
292
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
293
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
294
+ if (typeof value !== "object" || value == null) return false;
295
+ const record = value;
296
+ for (const key of Object.keys(record)) {
297
+ if (key === "@context") return true;
298
+ if (key === "@value" && isJsonLdValueObject(value)) continue;
299
+ if (hasNestedContext(record[key], depth + 1)) return true;
287
300
  }
301
+ return false;
288
302
  }
289
- function isJsonLiteralWrapper(value) {
290
- return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
291
- }
292
- /** @internal */
293
- function assertSafeJsonLd(jsonLd) {
294
- if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
295
- else if (typeof jsonLd === "object" && jsonLd != null) {
296
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
297
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
298
- if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
299
- if (jsonLiteralWrapper && key === "@value") continue;
300
- assertSafeJsonLd(value);
301
- }
303
+ function exceedsTraversalDepth(value, depth = 0) {
304
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
305
+ if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
306
+ if (typeof value !== "object" || value == null) return false;
307
+ const record = value;
308
+ for (const key of Object.keys(record)) {
309
+ if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
310
+ if (exceedsTraversalDepth(record[key], depth + 1)) return true;
302
311
  }
312
+ return false;
303
313
  }
304
- /**
305
- * Attaches a LD signature to the given JSON-LD document.
306
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
307
- * modified.
308
- * @param signature The signature to attach.
309
- * @returns The JSON-LD document with the attached signature.
310
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
311
- * @since 1.0.0
312
- */
313
- function attachSignature(jsonLd, signature) {
314
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
315
- return {
316
- ...jsonLd,
317
- signature
318
- };
314
+ function hasKnownSafeContext(jsonLd) {
315
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
316
+ const record = jsonLd;
317
+ if (!Object.hasOwn(record, "@context")) return false;
318
+ const context = record["@context"];
319
+ const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
320
+ if (entries == null || entries.length < 1) return false;
321
+ let hasActivityStreamsContext = false;
322
+ for (const entry of entries) {
323
+ if (typeof entry !== "string") return false;
324
+ if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
325
+ if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
326
+ }
327
+ if (!hasActivityStreamsContext) return false;
328
+ for (const key of Object.keys(record)) {
329
+ if (key === "@context") continue;
330
+ if (hasNestedContext(record[key])) return false;
331
+ }
332
+ return true;
319
333
  }
320
- /**
321
- * Creates a LD signature for the given JSON-LD document.
322
- * @param jsonLd The JSON-LD document to sign.
323
- * @param privateKey The private key to sign the document.
324
- * @param keyId The ID of the public key that corresponds to the private key.
325
- * @param options Additional options for creating the signature.
326
- * See also {@link CreateSignatureOptions}.
327
- * @return The created signature.
328
- * @throws {TypeError} If the private key is invalid or unsupported.
329
- * @since 1.0.0
330
- */
331
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
332
- require_http.validateCryptoKey(privateKey, "private");
333
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
334
- const options = {
335
- "@context": "https://w3id.org/identity/v1",
336
- creator: keyId.href,
337
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
338
- };
339
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
340
- const messageBytes = new TextEncoder().encode(message);
341
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
334
+ function getLogSafeJsonLdMetadata(jsonLd) {
335
+ if (typeof jsonLd !== "object" || jsonLd == null) return {};
336
+ const record = jsonLd;
337
+ const context = record["@context"];
342
338
  return {
343
- ...options,
344
- type: "RsaSignature2017",
345
- signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
339
+ id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
340
+ type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
341
+ context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
346
342
  };
347
343
  }
348
344
  /**
349
- * Signs the given JSON-LD document with the private key and returns the signed
350
- * JSON-LD document.
351
- * @param jsonLd The JSON-LD document to sign.
352
- * @param privateKey The private key to sign the document.
353
- * @param keyId The key ID to use in the signature. It will be used by the
354
- * verifier to fetch the corresponding public key.
355
- * @param options Additional options for signing the document.
356
- * See also {@link SignJsonLdOptions}.
357
- * @returns The signed JSON-LD document.
358
- * @throws {TypeError} If the private key is invalid or unsupported.
359
- * @since 1.0.0
345
+ * Ensures ActivityStreams attachment properties are represented as arrays
346
+ * when doing so preserves the JSON-LD semantics.
347
+ *
348
+ * JSON-LD compaction collapses single-item arrays into scalar values by
349
+ * default. Some ActivityPub implementations, Pixelfed among them, parse
350
+ * `attachment` as a plain JSON array rather than a JSON-LD property and reject
351
+ * otherwise valid objects whose single attachment is emitted as a scalar.
352
+ *
353
+ * When no `contextLoader` is supplied, the helper falls back to a restricted
354
+ * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
355
+ * every other URL without network access. Documents with custom, inline, or
356
+ * otherwise uncached contexts should pass a real `contextLoader` if they need
357
+ * the semantic-preservation check to succeed; otherwise canonicalization
358
+ * failures leave the original document unchanged.
360
359
  */
361
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
362
- 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) => {
363
- try {
364
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
365
- if (span.isRecording()) {
366
- span.setAttribute("ld_signatures.type", signature.type);
367
- span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
368
- }
369
- return attachSignature(jsonLd, signature);
370
- } catch (error) {
371
- span.setStatus({
372
- code: _opentelemetry_api.SpanStatusCode.ERROR,
373
- message: String(error)
374
- });
375
- throw error;
376
- } finally {
377
- span.end();
378
- }
379
- });
360
+ async function normalizeAttachmentArrays(jsonLd, contextLoader) {
361
+ const normalized = wrapScalarAttachments(jsonLd);
362
+ if (normalized === jsonLd) return jsonLd;
363
+ if (exceedsTraversalDepth(jsonLd)) {
364
+ logger$3.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
365
+ return jsonLd;
366
+ }
367
+ if (hasKnownSafeContext(jsonLd)) return normalized;
368
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
369
+ try {
370
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
371
+ format: "application/n-quads",
372
+ documentLoader: loader
373
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
374
+ format: "application/n-quads",
375
+ documentLoader: loader
376
+ })]);
377
+ if (before === after) return normalized;
378
+ 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));
379
+ } catch (error) {
380
+ logger$3.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
381
+ }
382
+ return jsonLd;
380
383
  }
381
384
  /**
382
- * Checks if the given JSON-LD document has a Linked Data Signature-like
383
- * object, without restricting it to a single suite-specific shape.
384
- * @param jsonLd The JSON-LD document to check.
385
- * @returns `true` if the document has a signature-like object; `false`
386
- * otherwise.
387
- * @since 2.2.0
385
+ * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
386
+ * to locally generated outgoing activities before they are signed, enqueued,
387
+ * or sent.
388
388
  */
389
- function hasSignatureLike(jsonLd) {
390
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
391
- const signature = jsonLd.signature;
392
- const hasReference = (value) => {
393
- if (typeof value === "string") return true;
394
- if (Array.isArray(value)) return value.some(hasReference);
395
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
396
- };
397
- const hasSignatureObject = (value) => {
398
- if (typeof value !== "object" || value == null) return false;
399
- const signatureRecord = value;
400
- return (typeof signatureRecord.type === "string" || Array.isArray(signatureRecord.type) && signatureRecord.type.some((item) => typeof item === "string")) && (hasReference(signatureRecord.creator) || hasReference(signatureRecord.verificationMethod)) && (typeof signatureRecord.signatureValue === "string" || typeof signatureRecord.jws === "string");
389
+ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
390
+ jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
391
+ return await normalizeAttachmentArrays(jsonLd, contextLoader);
392
+ }
393
+ //#endregion
394
+ //#region src/sig/ld.ts
395
+ const logger$2 = (0, _logtape_logtape.getLogger)([
396
+ "fedify",
397
+ "sig",
398
+ "ld"
399
+ ]);
400
+ const localContext = [
401
+ "https://w3id.org/identity/v1",
402
+ "https://www.w3.org/ns/activitystreams",
403
+ "https://w3id.org/security/v1",
404
+ "https://w3id.org/security/data-integrity/v1"
405
+ ];
406
+ const localContextUrls = new Set(localContext);
407
+ const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
408
+ const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
409
+ "@graph",
410
+ "@included",
411
+ "@reverse"
412
+ ]);
413
+ /** @internal */
414
+ var UnsafeJsonLdError = class extends TypeError {
415
+ keyword;
416
+ constructor(keyword) {
417
+ super(`Unsupported JSON-LD keyword: ${keyword}.`);
418
+ this.keyword = keyword;
419
+ this.name = "UnsafeJsonLdError";
420
+ }
421
+ };
422
+ /** @internal */
423
+ var InvalidContextReferenceError = class extends TypeError {
424
+ reference;
425
+ constructor(reference) {
426
+ super(`Invalid JSON-LD context reference: ${reference}.`);
427
+ this.reference = reference;
428
+ this.name = "InvalidContextReferenceError";
429
+ }
430
+ };
431
+ function createLoadingRemoteContextFailedError(reference, cause) {
432
+ const message = cause instanceof Error ? cause.message : String(cause);
433
+ const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
434
+ error.name = "jsonld.InvalidUrl";
435
+ error.details = {
436
+ code: "loading remote context failed",
437
+ url: reference
401
438
  };
402
- return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
439
+ error.cause = cause;
440
+ return error;
403
441
  }
404
- /**
405
- * Checks if the given JSON-LD document has a Linked Data Signature.
406
- * @param jsonLd The JSON-LD document to check.
407
- * @returns `true` if the document has a signature; `false` otherwise.
408
- * @since 1.0.0
409
- */
410
- function hasSignature(jsonLd) {
411
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
412
- if ("signature" in jsonLd) {
413
- const signature = jsonLd.signature;
414
- if (typeof signature !== "object" || signature == null) return false;
415
- return "type" in signature && signature.type === "RsaSignature2017" && "creator" in signature && typeof signature.creator === "string" && "created" in signature && typeof signature.created === "string" && "signatureValue" in signature && typeof signature.signatureValue === "string";
442
+ /** @internal */
443
+ function isClearlyMalformedContextReference(reference) {
444
+ for (const char of reference) {
445
+ const code = char.charCodeAt(0);
446
+ if (code <= 32 || code === 127) return true;
447
+ }
448
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
449
+ for (let i = 0; i < reference.length; i++) {
450
+ if (reference[i] !== "%") continue;
451
+ if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
452
+ i += 2;
453
+ }
454
+ if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
455
+ for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
416
456
  }
417
457
  return false;
418
458
  }
419
- /**
420
- * Detaches Linked Data Signatures from the given JSON-LD document.
421
- * @param jsonLd The JSON-LD document to modify.
422
- * @returns The modified JSON-LD document. If the input document does not
423
- * contain a signature, the original document is returned.
424
- * @since 1.0.0
425
- */
426
- function detachSignature(jsonLd) {
427
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
428
- const doc = { ...jsonLd };
429
- delete doc.signature;
430
- return doc;
459
+ function cloneRemoteDocument(remoteDocument) {
460
+ return structuredClone(remoteDocument);
431
461
  }
432
- /**
433
- * Verifies Linked Data Signatures of the given JSON-LD document.
434
- *
435
- * This is a low-level utility that only checks the cryptographic signature
436
- * and (optionally) the cached key. It does not run the JSON-LD parsing,
437
- * attribution, and owner checks that a complete inbound LD verification
438
- * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
439
- * the public verification entry point and the one that emits the
440
- * `activitypub.signature.verification.duration` metric for the LD path.
441
- * `verifySignature` itself only emits
442
- * `activitypub.signature.key_fetch.duration`, since the rest of the work
443
- * that the verification-duration metric is meant to cover happens in
444
- * `verifyJsonLd`.
445
- * @param jsonLd The JSON-LD document to verify.
446
- * @param options Options for verifying the signature.
447
- * @returns The public key that signed the document or `null` if the signature
448
- * is invalid or the key is not found.
449
- * @since 1.0.0
450
- */
451
- async function verifySignature(jsonLd, options = {}) {
452
- if (!hasSignature(jsonLd)) return null;
453
- const sig = jsonLd.signature;
454
- let signature;
455
- try {
456
- signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
457
- } catch (error) {
458
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
459
- ...sig,
460
- error
461
- });
462
- return null;
463
- }
464
- const { key, cached } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options));
465
- if (key == null) return null;
466
- const sigOpts = {
467
- ...sig,
468
- "@context": "https://w3id.org/identity/v1"
462
+ function createMemoizedDocumentLoader(documentLoader) {
463
+ const cache = /* @__PURE__ */ new Map();
464
+ return async (url, options) => {
465
+ const cacheKey = URL.canParse(url) ? new URL(url).href : url;
466
+ let remoteDocument = cache.get(cacheKey);
467
+ if (remoteDocument == null) {
468
+ remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
469
+ remoteDocument.catch(() => {
470
+ if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
471
+ });
472
+ cache.set(cacheKey, remoteDocument);
473
+ }
474
+ return cloneRemoteDocument(await remoteDocument);
469
475
  };
470
- delete sigOpts.type;
471
- delete sigOpts.id;
472
- delete sigOpts.signatureValue;
473
- let sigOptsHash;
474
- try {
475
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
476
- } catch (error) {
477
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
478
- signatureOptions: sigOpts,
479
- error
480
- });
481
- return null;
482
- }
483
- const document = { ...jsonLd };
484
- delete document.signature;
485
- let docHash;
486
- try {
487
- docHash = await hashJsonLd(document, options.contextLoader);
488
- } catch (error) {
489
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
490
- document,
491
- error
492
- });
493
- return null;
494
- }
495
- const encoder = new TextEncoder();
496
- const message = sigOptsHash + docHash;
497
- const messageBytes = encoder.encode(message);
498
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
499
- if (cached) {
500
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
501
- keyId: sig.creator,
502
- ...sig
503
- });
504
- const { key } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
505
- ...options,
506
- keyCache: {
507
- get: () => Promise.resolve(void 0),
508
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
509
- }
510
- }));
511
- if (key == null) return null;
512
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
513
- }
514
- logger$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
515
- keyId: sig.creator,
516
- ...sig,
517
- message
518
- });
519
- return null;
520
- }
521
- /**
522
- * Known Linked Data Signature `type` values, used to keep
523
- * `ld_signatures.type` on a bounded set of spec-defined string values.
524
- * Fedify only signs and verifies `RsaSignature2017`; other values come in
525
- * only from external documents and are dropped from the metric attribute to
526
- * avoid attacker-controlled cardinality.
527
- */
528
- const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
529
- /**
530
- * Reports only whether a `signature` key is present on the document, with
531
- * no shape check on its value. This is intentionally looser than
532
- * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
533
- * and {@link hasSignatureLike} (which structurally accepts several known
534
- * suites): `verifyJsonLd` needs to tell a document with a malformed or
535
- * unsupported signature payload (classified as `rejected`) apart from a
536
- * truly unsigned document (classified as `missing`), and only this
537
- * presence-only check captures both cases.
538
- */
539
- function hasLdSignatureProperty(jsonLd) {
540
- return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
541
- }
542
- function getLdSignatureObject(jsonLd) {
543
- if (!hasLdSignatureProperty(jsonLd)) return void 0;
544
- const { signature } = jsonLd;
545
- if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
546
- return signature;
547
- }
548
- /**
549
- * Verify the authenticity of the given JSON-LD document using Linked Data
550
- * Signatures. If the document is signed, this function verifies the signature
551
- * and checks if the document is attributed to the owner of the public key.
552
- * If the document is not signed, this function returns `false`.
553
- * @param jsonLd The JSON-LD document to verify.
554
- * @param options Options for verifying the document.
555
- * @returns `true` if the document is authentic; `false` otherwise.
556
- */
557
- async function verifyJsonLd(jsonLd, options = {}) {
558
- return await verifyJsonLdInternal(jsonLd, options, true);
559
476
  }
560
477
  /** @internal */
561
- async function verifyCompactJsonLd(jsonLd, options = {}) {
562
- return await verifyJsonLdInternal(jsonLd, options, false);
563
- }
564
- async function verifyJsonLdInternal(jsonLd, options, compact) {
565
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
566
- const start = performance.now();
567
- let verified = false;
568
- let threw = false;
569
- let signatureType;
478
+ function wrapContextLoaderForJsonLd(contextLoader) {
479
+ const loader = contextLoader ?? builtInContextLoader;
480
+ return async (url, options) => {
570
481
  try {
571
- const verificationOptions = hasSignature(jsonLd) ? {
572
- ...options,
573
- contextLoader: getNormalizationContextLoader(options.contextLoader)
574
- } : options;
575
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
576
- const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
577
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
578
- span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
579
- const sig = getLdSignatureObject(jsonLd);
580
- if (sig != null) {
581
- if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
582
- if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
583
- if (typeof sig.type === "string") {
584
- span.setAttribute("ld_signatures.type", sig.type);
585
- if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
586
- }
587
- }
588
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
589
- if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
590
- const key = await verifySignature(compacted, verificationOptions);
591
- if (key == null) return false;
592
- if (key.ownerId == null) {
593
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
594
- return false;
595
- }
596
- attributions.delete(key.ownerId.href);
597
- if (attributions.size > 0) {
598
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
599
- return false;
600
- }
601
- verified = true;
602
- return true;
482
+ return await loader(url, options);
603
483
  } catch (error) {
604
- threw = true;
605
- span.setStatus({
606
- code: _opentelemetry_api.SpanStatusCode.ERROR,
607
- message: String(error)
608
- });
609
- throw error;
610
- } finally {
611
- const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
612
- require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "linked_data", classified, { ldType: signatureType });
613
- span.end();
484
+ if (!isInvalidUrlTypeError(error)) throw error;
485
+ if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
486
+ throw createLoadingRemoteContextFailedError(url, error);
614
487
  }
615
- });
616
- }
617
- async function hashJsonLd(jsonLd, contextLoader) {
618
- const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
619
- format: "application/n-quads",
620
- documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
621
- });
622
- const encoder = new TextEncoder();
623
- return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
488
+ };
624
489
  }
625
- //#endregion
626
- //#region src/sig/owner.ts
627
- /**
628
- * Checks if the actor of the given activity owns the specified key.
629
- * @param activity The activity to check.
630
- * @param key The public key to check.
631
- * @param options Options for checking the key ownership.
632
- * @returns Whether the actor is the owner of the key.
633
- */
634
- async function doesActorOwnKey(activity, key, options) {
635
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
636
- kind: _opentelemetry_api.SpanKind.INTERNAL,
637
- attributes: {
638
- "activitypub.actor.id": activity.actorId?.href ?? "",
639
- "activitypub.key.id": key.id?.href ?? ""
640
- }
641
- }, async (span) => {
642
- try {
643
- if (key.ownerId != null) {
644
- const owns = key.ownerId.href === activity.actorId?.href;
645
- span.setAttribute("activitypub.key_ownership.verified", owns);
646
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
647
- return owns;
648
- }
649
- const actor = await activity.getActor(options);
650
- if (actor == null || !(0, _fedify_vocab.isActor)(actor)) {
651
- span.setAttribute("activitypub.key_ownership.verified", false);
652
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
653
- return false;
654
- }
655
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
656
- span.setAttribute("activitypub.key_ownership.verified", true);
657
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
658
- return true;
659
- }
660
- span.setAttribute("activitypub.key_ownership.verified", false);
661
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
662
- return false;
663
- } catch (error) {
664
- span.recordException(error);
665
- span.setStatus({
666
- code: _opentelemetry_api.SpanStatusCode.ERROR,
667
- message: String(error)
668
- });
669
- throw error;
670
- } finally {
671
- span.end();
490
+ /** @internal */
491
+ function getNormalizationContextLoader(contextLoader) {
492
+ const loader = wrapContextLoaderForJsonLd(contextLoader);
493
+ return createMemoizedDocumentLoader(async (url, options) => {
494
+ if (URL.canParse(url)) {
495
+ const normalizedUrl = new URL(url).href;
496
+ if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
672
497
  }
498
+ return await loader(url, options);
673
499
  });
674
500
  }
675
- /**
676
- * Gets the actor that owns the specified key. Returns `null` if the key has no
677
- * known owner.
678
- *
679
- * @param keyId The ID of the key to check, or the key itself.
680
- * @param options Options for getting the key owner.
681
- * @returns The actor that owns the key, or `null` if the key has no known
682
- * owner.
683
- * @since 0.7.0
684
- */
685
- async function getKeyOwner(keyId, options) {
686
- const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
687
- const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
688
- const contextLoader = options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
689
- let object;
690
- if (keyId instanceof _fedify_vocab.CryptographicKey) {
691
- object = keyId;
692
- if (object.id == null) return null;
693
- keyId = object.id;
694
- } else {
695
- let keyDoc;
696
- try {
697
- const { document } = await documentLoader(keyId.href);
698
- keyDoc = document;
699
- } catch (_) {
700
- return null;
701
- }
702
- try {
703
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
704
- documentLoader,
705
- contextLoader,
706
- tracerProvider
707
- });
708
- } catch (e) {
709
- if (!(e instanceof TypeError)) throw e;
710
- try {
711
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, {
712
- documentLoader,
713
- contextLoader,
714
- tracerProvider
715
- });
716
- } catch (e) {
717
- if (e instanceof TypeError) return null;
718
- throw e;
719
- }
720
- }
721
- }
722
- let owner = null;
723
- if (object instanceof _fedify_vocab.CryptographicKey) {
724
- if (object.ownerId == null) return null;
725
- owner = await object.getOwner({
726
- documentLoader,
727
- contextLoader,
728
- tracerProvider
729
- });
730
- } else if ((0, _fedify_vocab.isActor)(object)) owner = object;
731
- else return null;
732
- if (owner == null) return null;
733
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
734
- return null;
501
+ /** @internal */
502
+ async function compactJsonLd(jsonLd, contextLoader) {
503
+ const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
504
+ const signature = hasLds ? jsonLd.signature : void 0;
505
+ const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
506
+ const document = hasLds ? detachSignature(jsonLd) : jsonLd;
507
+ await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
508
+ const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
509
+ if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
510
+ assertSafeJsonLd(compacted);
511
+ return compacted;
735
512
  }
736
- //#endregion
737
- //#region src/compat/preloaded-context-loader.ts
738
- /**
739
- * A restricted JSON-LD document loader that resolves only contexts bundled
740
- * with Fedify.
741
- *
742
- * This is intentionally narrower than `getDocumentLoader()`: normalization
743
- * helpers are also reached from verification paths that operate on inbound,
744
- * attacker-controlled JSON-LD, so the default fallback must never fetch
745
- * attacker-supplied context URLs.
746
- */
747
- const preloadedOnlyDocumentLoader = (url) => {
748
- if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
749
- contextUrl: null,
750
- documentUrl: url,
751
- document: _fedify_vocab_runtime.preloadedContexts[url]
752
- });
753
- return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
754
- };
755
- //#endregion
756
- //#region src/compat/public-audience.ts
757
- const logger$2 = (0, _logtape_logtape.getLogger)([
758
- "fedify",
759
- "compat",
760
- "public-audience"
761
- ]);
762
- const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
763
- "to",
764
- "cc",
765
- "bto",
766
- "bcc",
767
- "audience"
768
- ]);
769
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
770
- const MAX_TRAVERSAL_DEPTH$1 = 64;
771
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
772
- function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
773
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
774
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
775
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
776
- if (typeof value !== "object" || value == null) return false;
777
- const record = value;
778
- for (const key of Object.keys(record)) {
779
- if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
780
- if (key === "@context") continue;
781
- if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
782
- }
783
- return false;
513
+ function createInvalidRemoteContextError(reference) {
514
+ 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}".`);
515
+ error.name = "jsonld.InvalidUrl";
516
+ error.details = {
517
+ code: "invalid remote context",
518
+ url: reference
519
+ };
520
+ return error;
784
521
  }
785
- function rewritePublicAudience(value, parentKey, depth = 0) {
786
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
787
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
788
- if (Array.isArray(value)) {
789
- let changed = false;
790
- const mapped = value.map((item) => {
791
- const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
792
- if (rewritten !== item) changed = true;
793
- return rewritten;
794
- });
795
- return changed ? mapped : value;
796
- }
797
- if (typeof value !== "object" || value == null) return value;
798
- const record = value;
799
- let changed = false;
800
- const normalized = Object.create(null);
801
- for (const key of Object.keys(record)) {
802
- 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);
803
- if (rewritten !== record[key]) changed = true;
804
- normalized[key] = rewritten;
805
- }
806
- return changed ? normalized : value;
522
+ function getRemoteContext(remoteDocument, reference) {
523
+ const { contextUrl, documentUrl } = remoteDocument;
524
+ let { document } = remoteDocument;
525
+ if (typeof document === "string") document = JSON.parse(document);
526
+ if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
527
+ let context = "@context" in document ? document["@context"] : {};
528
+ if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
529
+ return {
530
+ context,
531
+ baseUrl: documentUrl ?? reference
532
+ };
807
533
  }
808
- /**
809
- * Reports whether `value` carries an `@context` property anywhere inside
810
- * its subtree (not counting the value itself). A nested `@context` can
811
- * introduce a local term-definition scope that redefines `as:` or `Public`
812
- * even when the top-level `@context` is safe, so the fast path must defer
813
- * to the URDNA2015 equivalence check whenever one is present.
814
- */
815
- function hasNestedContext$1(value, depth = 0) {
816
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
817
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
818
- if (typeof value !== "object" || value == null) return false;
819
- const record = value;
820
- for (const key of Object.keys(record)) {
821
- if (key === "@context") return true;
822
- if (hasNestedContext$1(record[key], depth + 1)) return true;
823
- }
824
- return false;
534
+ function createGraphAliasContextState() {
535
+ return {
536
+ graphTerms: /* @__PURE__ */ new Set(),
537
+ jsonTerms: /* @__PURE__ */ new Set(),
538
+ propertyContexts: /* @__PURE__ */ new Map(),
539
+ termTargets: /* @__PURE__ */ new Map()
540
+ };
825
541
  }
826
- /**
827
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
828
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
829
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
830
- * preloaded context set AND including the ActivityStreams URL qualify,
831
- * AND no nested subtree carries its own `@context` that might redefine
832
- * those terms within a local scope. When all of that holds the rewrite
833
- * is provably semantics-preserving and the URDNA2015 equivalence check
834
- * can be skipped. Any other shape (unknown external URLs, inline
835
- * objects at the top level, nested `@context` blocks) is treated as
836
- * potentially unsafe.
837
- */
838
- function hasKnownSafeContext$1(jsonLd) {
839
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
840
- const record = jsonLd;
841
- if (!Object.hasOwn(record, "@context")) return false;
842
- const ctx = record["@context"];
843
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
844
- if (entries == null || entries.length === 0) return false;
845
- let hasAs = false;
846
- for (const entry of entries) {
847
- if (typeof entry !== "string") return false;
848
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
849
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
850
- }
851
- if (!hasAs) return false;
852
- for (const key of Object.keys(record)) {
853
- if (key === "@context") continue;
854
- if (hasNestedContext$1(record[key])) return false;
542
+ function cloneGraphAliasContextState(state) {
543
+ return {
544
+ graphTerms: new Set(state.graphTerms),
545
+ jsonTerms: new Set(state.jsonTerms),
546
+ propertyContexts: new Map(state.propertyContexts),
547
+ termTargets: new Map(state.termTargets)
548
+ };
549
+ }
550
+ function resolveContextTarget(target, state) {
551
+ if (target === "@graph") return target;
552
+ const mapped = state.termTargets.get(target);
553
+ if (mapped == null) return target;
554
+ return mapped;
555
+ }
556
+ function getDirectContextTarget(definition) {
557
+ if (definition === null) return null;
558
+ if (typeof definition === "string") return definition;
559
+ if (typeof definition === "object" && definition != null && "@id" in definition) {
560
+ const id = definition["@id"];
561
+ if (id === null) return null;
562
+ if (typeof id === "string") return id;
855
563
  }
856
- return true;
857
564
  }
858
- /**
859
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
860
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
861
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
862
- *
863
- * Several ActivityPub implementations, Lemmy among them, match these
864
- * fields as plain URLs without running JSON-LD expansion, and silently
865
- * drop activities whose public addressing appears in CURIE form. This
866
- * helper works around that gap.
867
- *
868
- * For documents whose `@context` is drawn entirely from Fedify's
869
- * preloaded context set and includes the ActivityStreams URL, the
870
- * rewrite is applied directly: the content of every preloaded non-AS
871
- * context is known not to redefine the `as:` prefix or the bare `Public`
872
- * term, so the semantics are preserved by construction. Any other
873
- * shape (an inline object, an unknown external URL, and so on) is
874
- * treated as potentially unsafe and gated on a JSON-LD equivalence
875
- * check; both forms are canonicalized with URDNA2015 and the resulting
876
- * N-Quads are compared. When they differ, the original document is
877
- * returned unchanged. Canonicalization failures also fall back to the
878
- * original document.
879
- *
880
- * When no `contextLoader` is supplied the helper falls back to an
881
- * internal loader that resolves only the URLs in Fedify's
882
- * preloaded-contexts set and rejects every other URL without issuing a
883
- * network request. That behaviour is deliberately narrower than
884
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
885
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
886
- * helper is reached from verification paths (`verifyProof()` /
887
- * `verifyObject()`) that operate on inbound, potentially adversarial
888
- * JSON-LD, and a default loader that fetches attacker-supplied
889
- * `@context` URLs on the caller's behalf would be an SSRF vector.
890
- * Canonicalization failures against the restricted loader fall back to
891
- * the original document, same as any other canonicalization error.
892
- * Callers that genuinely need the remote-fetch loader (for example
893
- * applications that sign local JSON-LD against a custom vocabulary)
894
- * should pass a `contextLoader` explicitly.
895
- *
896
- * Must be called before any signing step that canonicalizes the
897
- * compact form byte-for-byte (for example, Object Integrity Proofs
898
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
899
- * matches what is sent on the wire.
900
- */
901
- async function normalizePublicAudience(jsonLd, contextLoader) {
902
- if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
903
- const normalized = rewritePublicAudience(jsonLd);
904
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
905
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
906
- try {
907
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
908
- format: "application/n-quads",
909
- documentLoader: loader
910
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
911
- format: "application/n-quads",
912
- documentLoader: loader
913
- })]);
914
- if (before === after) return normalized;
915
- 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.");
916
- } catch (error) {
917
- logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
565
+ function isJsonTypedDefinition(definition) {
566
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
567
+ }
568
+ function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
569
+ if (target === "@graph") return target;
570
+ if (seen.has(target)) return target;
571
+ seen.add(target);
572
+ if (localTargets.has(target)) {
573
+ const localTarget = localTargets.get(target);
574
+ return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
918
575
  }
919
- return jsonLd;
576
+ return resolveContextTarget(target, state);
920
577
  }
921
- //#endregion
922
- //#region src/compat/outgoing-jsonld.ts
923
- const logger$1 = (0, _logtape_logtape.getLogger)([
924
- "fedify",
925
- "compat",
926
- "outgoing-jsonld"
927
- ]);
928
- const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
929
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
930
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
931
- const MAX_TRAVERSAL_DEPTH = 64;
932
- function isJsonLdListObject(value) {
933
- return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
578
+ function refreshGraphAliases(state) {
579
+ state.graphTerms.clear();
580
+ for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
581
+ }
582
+ function normalizeContextReference(reference, baseUrl) {
583
+ if (baseUrl != null) return new URL(reference, baseUrl).href;
584
+ return URL.canParse(reference) ? new URL(reference).href : reference;
934
585
  }
935
- function isJsonLdValueObject(value) {
936
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
586
+ /** @internal */
587
+ function isInvalidUrlTypeError(error) {
588
+ const code = error.code;
589
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
937
590
  }
938
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
939
- if (Array.isArray(value)) {
940
- if (seen.has(value)) return;
941
- seen.add(value);
942
- for (const item of value) yield* getContextObjects(item, seen);
943
- return;
591
+ async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
592
+ if (context === null) return createGraphAliasContextState();
593
+ let nextState = cloneGraphAliasContextState(state);
594
+ if (Array.isArray(context)) {
595
+ for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
596
+ return nextState;
944
597
  }
945
- if (typeof value === "object" && value != null) {
946
- if (seen.has(value)) return;
947
- seen.add(value);
948
- const record = value;
949
- yield record;
950
- for (const definition of Object.values(record)) {
951
- if (typeof definition !== "object" || definition == null) continue;
952
- const nestedContext = definition["@context"];
953
- if (nestedContext == null) continue;
954
- yield* getContextObjects(nestedContext, seen);
598
+ if (typeof context === "string") {
599
+ const reference = normalizeContextReference(context, baseUrl);
600
+ const cacheKey = `${baseUrl ?? ""}\n${reference}`;
601
+ if (processingContexts.has(cacheKey)) return nextState;
602
+ processingContexts.add(cacheKey);
603
+ try {
604
+ let remoteContext = remoteContextCache.get(cacheKey);
605
+ if (remoteContext == null) {
606
+ remoteContext = (async () => {
607
+ try {
608
+ return getRemoteContext(await documentLoader(reference), reference);
609
+ } catch (error) {
610
+ if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
611
+ throw error;
612
+ }
613
+ })();
614
+ remoteContextCache.set(cacheKey, remoteContext);
615
+ }
616
+ const loadedRemoteContext = await remoteContext;
617
+ return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
618
+ } finally {
619
+ processingContexts.delete(cacheKey);
620
+ }
621
+ }
622
+ if (typeof context === "object" && context != null) {
623
+ if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
624
+ const localTargets = /* @__PURE__ */ new Map();
625
+ for (const [term, definition] of globalThis.Object.entries(context)) {
626
+ if (term.startsWith("@")) continue;
627
+ const target = getDirectContextTarget(definition);
628
+ if (target == null) localTargets.set(term, null);
629
+ else if (typeof target === "string") localTargets.set(term, target);
630
+ else localTargets.delete(term);
631
+ }
632
+ for (const [term, definition] of globalThis.Object.entries(context)) {
633
+ if (term.startsWith("@")) continue;
634
+ if (localTargets.has(term)) {
635
+ const directTarget = localTargets.get(term);
636
+ if (directTarget == null) nextState.termTargets.set(term, null);
637
+ else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
638
+ } else nextState.termTargets.delete(term);
639
+ if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
640
+ context: definition["@context"],
641
+ baseUrl
642
+ });
643
+ else nextState.propertyContexts.delete(term);
644
+ if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
645
+ else nextState.jsonTerms.delete(term);
955
646
  }
647
+ refreshGraphAliases(nextState);
956
648
  }
649
+ return nextState;
957
650
  }
958
- function isActivityStreamsAttachmentTerm(value) {
959
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
651
+ async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
652
+ if (Array.isArray(jsonLd)) {
653
+ for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
654
+ return;
655
+ }
656
+ if (typeof jsonLd !== "object" || jsonLd == null) return;
657
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
658
+ let state = inheritedState;
659
+ if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
660
+ if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
661
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
662
+ if (key === "@context") continue;
663
+ if (jsonLiteralWrapper && key === "@value") continue;
664
+ if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
665
+ if (state.jsonTerms.has(key)) continue;
666
+ await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
667
+ }
668
+ }
669
+ function isJsonLiteralWrapper(value) {
670
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
960
671
  }
961
672
  /** @internal */
962
- function isPreloadedContextAttachmentSafe(document) {
963
- if (typeof document !== "object" || document == null) return true;
964
- const context = document["@context"];
965
- for (const contextObject of getContextObjects(context)) {
966
- if (!Object.hasOwn(contextObject, "attachment")) continue;
967
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
968
- return false;
673
+ function assertSafeJsonLd(jsonLd) {
674
+ if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
675
+ else if (typeof jsonLd === "object" && jsonLd != null) {
676
+ const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
677
+ for (const [key, value] of globalThis.Object.entries(jsonLd)) {
678
+ if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
679
+ if (jsonLiteralWrapper && key === "@value") continue;
680
+ assertSafeJsonLd(value);
681
+ }
969
682
  }
970
- return true;
971
683
  }
972
- function getKnownSafeContextUrls() {
973
- const urls = /* @__PURE__ */ new Set();
974
- for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
975
- 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 });
976
- return urls;
684
+ /**
685
+ * Attaches a LD signature to the given JSON-LD document.
686
+ * @param jsonLd The JSON-LD document to attach the signature to. It is not
687
+ * modified.
688
+ * @param signature The signature to attach.
689
+ * @returns The JSON-LD document with the attached signature.
690
+ * @throws {TypeError} If the input document is not a valid JSON-LD document.
691
+ * @since 1.0.0
692
+ */
693
+ function attachSignature(jsonLd, signature) {
694
+ if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
695
+ return {
696
+ ...jsonLd,
697
+ signature
698
+ };
977
699
  }
978
700
  /**
979
- * Wraps scalar ActivityStreams attachment properties in arrays.
701
+ * Creates a LD signature for the given JSON-LD document.
702
+ * @param jsonLd The JSON-LD document to sign.
703
+ * @param privateKey The private key to sign the document.
704
+ * @param keyId The ID of the public key that corresponds to the private key.
705
+ * @param options Additional options for creating the signature.
706
+ * See also {@link CreateSignatureOptions}.
707
+ * @return The created signature.
708
+ * @throws {TypeError} If the private key is invalid or unsupported.
709
+ * @since 1.0.0
980
710
  */
981
- function wrapScalarAttachments(jsonLd, depth = 0) {
982
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
983
- if (Array.isArray(jsonLd)) {
984
- let normalized = null;
985
- for (let i = 0; i < jsonLd.length; i++) {
986
- const item = jsonLd[i];
987
- const next = wrapScalarAttachments(item, depth + 1);
988
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
989
- if (normalized != null) normalized[i] = next;
990
- }
991
- return normalized ?? jsonLd;
992
- }
993
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
994
- const record = jsonLd;
995
- const keys = Object.keys(record);
996
- let normalized = null;
997
- for (let i = 0; i < keys.length; i++) {
998
- const key = keys[i];
999
- const value = record[key];
1000
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
1001
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
1002
- if (normalized == null && output !== value) {
1003
- const cloned = Object.create(null);
1004
- for (let j = 0; j < i; j++) {
1005
- const previousKey = keys[j];
1006
- cloned[previousKey] = record[previousKey];
711
+ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
712
+ require_http.validateCryptoKey(privateKey, "private");
713
+ if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
714
+ const options = {
715
+ "@context": "https://w3id.org/identity/v1",
716
+ creator: keyId.href,
717
+ created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
718
+ };
719
+ const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
720
+ const messageBytes = new TextEncoder().encode(message);
721
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
722
+ return {
723
+ ...options,
724
+ type: "RsaSignature2017",
725
+ signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
726
+ };
727
+ }
728
+ /**
729
+ * Signs the given JSON-LD document with the private key and returns the signed
730
+ * JSON-LD document.
731
+ * @param jsonLd The JSON-LD document to sign.
732
+ * @param privateKey The private key to sign the document.
733
+ * @param keyId The key ID to use in the signature. It will be used by the
734
+ * verifier to fetch the corresponding public key.
735
+ * @param options Additional options for signing the document.
736
+ * See also {@link SignJsonLdOptions}.
737
+ * @returns The signed JSON-LD document.
738
+ * @throws {TypeError} If the private key is invalid or unsupported.
739
+ * @since 1.0.0
740
+ */
741
+ async function signJsonLd(jsonLd, privateKey, keyId, options) {
742
+ 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) => {
743
+ try {
744
+ const signature = await createSignature(jsonLd, privateKey, keyId, options);
745
+ if (span.isRecording()) {
746
+ span.setAttribute("ld_signatures.type", signature.type);
747
+ span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
1007
748
  }
1008
- normalized = cloned;
749
+ return attachSignature(jsonLd, signature);
750
+ } catch (error) {
751
+ span.setStatus({
752
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
753
+ message: String(error)
754
+ });
755
+ throw error;
756
+ } finally {
757
+ span.end();
1009
758
  }
1010
- if (normalized != null) normalized[key] = output;
1011
- }
1012
- return normalized ?? jsonLd;
1013
- }
1014
- function hasNestedContext(value, depth = 0) {
1015
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1016
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
1017
- if (typeof value !== "object" || value == null) return false;
1018
- const record = value;
1019
- for (const key of Object.keys(record)) {
1020
- if (key === "@context") return true;
1021
- if (key === "@value" && isJsonLdValueObject(value)) continue;
1022
- if (hasNestedContext(record[key], depth + 1)) return true;
1023
- }
1024
- return false;
759
+ });
1025
760
  }
1026
- function exceedsTraversalDepth(value, depth = 0) {
1027
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1028
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
1029
- if (typeof value !== "object" || value == null) return false;
1030
- const record = value;
1031
- for (const key of Object.keys(record)) {
1032
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
1033
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
1034
- }
1035
- return false;
761
+ /**
762
+ * Checks if the given JSON-LD document has a Linked Data Signature-like
763
+ * object, without restricting it to a single suite-specific shape.
764
+ * @param jsonLd The JSON-LD document to check.
765
+ * @returns `true` if the document has a signature-like object; `false`
766
+ * otherwise.
767
+ * @since 2.2.0
768
+ */
769
+ function hasSignatureLike(jsonLd) {
770
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
771
+ const signature = jsonLd.signature;
772
+ const hasReference = (value) => {
773
+ if (typeof value === "string") return true;
774
+ if (Array.isArray(value)) return value.some(hasReference);
775
+ return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
776
+ };
777
+ const hasSignatureObject = (value) => {
778
+ if (typeof value !== "object" || value == null) return false;
779
+ const signatureRecord = value;
780
+ 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");
781
+ };
782
+ return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
1036
783
  }
1037
- function hasKnownSafeContext(jsonLd) {
784
+ /**
785
+ * Checks if the given JSON-LD document has a Linked Data Signature.
786
+ * @param jsonLd The JSON-LD document to check.
787
+ * @returns `true` if the document has a signature; `false` otherwise.
788
+ * @since 1.0.0
789
+ */
790
+ function hasSignature(jsonLd) {
1038
791
  if (typeof jsonLd !== "object" || jsonLd == null) return false;
1039
- const record = jsonLd;
1040
- if (!Object.hasOwn(record, "@context")) return false;
1041
- const context = record["@context"];
1042
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
1043
- if (entries == null || entries.length < 1) return false;
1044
- let hasActivityStreamsContext = false;
1045
- for (const entry of entries) {
1046
- if (typeof entry !== "string") return false;
1047
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
1048
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
1049
- }
1050
- if (!hasActivityStreamsContext) return false;
1051
- for (const key of Object.keys(record)) {
1052
- if (key === "@context") continue;
1053
- if (hasNestedContext(record[key])) return false;
792
+ if ("signature" in jsonLd) {
793
+ const signature = jsonLd.signature;
794
+ if (typeof signature !== "object" || signature == null) return false;
795
+ 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";
1054
796
  }
1055
- return true;
797
+ return false;
1056
798
  }
1057
- function getLogSafeJsonLdMetadata(jsonLd) {
1058
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
1059
- const record = jsonLd;
1060
- const context = record["@context"];
1061
- return {
1062
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
1063
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
1064
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
1065
- };
799
+ /**
800
+ * Detaches Linked Data Signatures from the given JSON-LD document.
801
+ * @param jsonLd The JSON-LD document to modify.
802
+ * @returns The modified JSON-LD document. If the input document does not
803
+ * contain a signature, the original document is returned.
804
+ * @since 1.0.0
805
+ */
806
+ function detachSignature(jsonLd) {
807
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
808
+ const doc = { ...jsonLd };
809
+ delete doc.signature;
810
+ return doc;
1066
811
  }
1067
812
  /**
1068
- * Ensures ActivityStreams attachment properties are represented as arrays
1069
- * when doing so preserves the JSON-LD semantics.
1070
- *
1071
- * JSON-LD compaction collapses single-item arrays into scalar values by
1072
- * default. Some ActivityPub implementations, Pixelfed among them, parse
1073
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
1074
- * otherwise valid objects whose single attachment is emitted as a scalar.
813
+ * Verifies Linked Data Signatures of the given JSON-LD document.
1075
814
  *
1076
- * When no `contextLoader` is supplied, the helper falls back to a restricted
1077
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
1078
- * every other URL without network access. Documents with custom, inline, or
1079
- * otherwise uncached contexts should pass a real `contextLoader` if they need
1080
- * the semantic-preservation check to succeed; otherwise canonicalization
1081
- * failures leave the original document unchanged.
815
+ * This is a low-level utility that only checks the cryptographic signature
816
+ * and (optionally) the cached key. It does not run the JSON-LD parsing,
817
+ * attribution, and owner checks that a complete inbound LD verification
818
+ * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
819
+ * the public verification entry point and the one that emits the
820
+ * `activitypub.signature.verification.duration` metric for the LD path.
821
+ * `verifySignature` itself only emits
822
+ * `activitypub.signature.key_fetch.duration`, since the rest of the work
823
+ * that the verification-duration metric is meant to cover happens in
824
+ * `verifyJsonLd`.
825
+ * @param jsonLd The JSON-LD document to verify.
826
+ * @param options Options for verifying the signature.
827
+ * @returns The public key that signed the document or `null` if the signature
828
+ * is invalid or the key is not found.
829
+ * @since 1.0.0
1082
830
  */
1083
- async function normalizeAttachmentArrays(jsonLd, contextLoader) {
1084
- const normalized = wrapScalarAttachments(jsonLd);
1085
- if (normalized === jsonLd) return jsonLd;
1086
- if (exceedsTraversalDepth(jsonLd)) {
1087
- logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
1088
- return jsonLd;
831
+ async function verifySignature(jsonLd, options = {}) {
832
+ if (!hasSignature(jsonLd)) return null;
833
+ const sig = jsonLd.signature;
834
+ let signature;
835
+ try {
836
+ signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
837
+ } catch (error) {
838
+ logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
839
+ ...sig,
840
+ error
841
+ });
842
+ return null;
1089
843
  }
1090
- if (hasKnownSafeContext(jsonLd)) return normalized;
1091
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
844
+ const { key, cached } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options));
845
+ if (key == null) return null;
846
+ const sigOpts = {
847
+ ...sig,
848
+ "@context": "https://w3id.org/identity/v1"
849
+ };
850
+ delete sigOpts.type;
851
+ delete sigOpts.id;
852
+ delete sigOpts.signatureValue;
853
+ let sigOptsHash;
1092
854
  try {
1093
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
1094
- format: "application/n-quads",
1095
- documentLoader: loader
1096
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
1097
- format: "application/n-quads",
1098
- documentLoader: loader
1099
- })]);
1100
- if (before === after) return normalized;
1101
- 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));
855
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
856
+ } catch (error) {
857
+ logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
858
+ signatureOptions: sigOpts,
859
+ error
860
+ });
861
+ return null;
862
+ }
863
+ const document = { ...jsonLd };
864
+ delete document.signature;
865
+ let docHash;
866
+ try {
867
+ docHash = await hashJsonLd(document, options.contextLoader);
1102
868
  } catch (error) {
1103
- logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
869
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
870
+ document,
871
+ error
872
+ });
873
+ return null;
1104
874
  }
1105
- return jsonLd;
875
+ const encoder = new TextEncoder();
876
+ const message = sigOptsHash + docHash;
877
+ const messageBytes = encoder.encode(message);
878
+ if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
879
+ if (cached) {
880
+ logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
881
+ keyId: sig.creator,
882
+ ...sig
883
+ });
884
+ const { key } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
885
+ ...options,
886
+ keyCache: {
887
+ get: () => Promise.resolve(void 0),
888
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
889
+ }
890
+ }));
891
+ if (key == null) return null;
892
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
893
+ }
894
+ 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}", {
895
+ keyId: sig.creator,
896
+ ...sig,
897
+ message
898
+ });
899
+ return null;
900
+ }
901
+ /**
902
+ * Known Linked Data Signature `type` values, used to keep
903
+ * `ld_signatures.type` on a bounded set of spec-defined string values.
904
+ * Fedify only signs and verifies `RsaSignature2017`; other values come in
905
+ * only from external documents and are dropped from the metric attribute to
906
+ * avoid attacker-controlled cardinality.
907
+ */
908
+ const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
909
+ /**
910
+ * Reports only whether a `signature` key is present on the document, with
911
+ * no shape check on its value. This is intentionally looser than
912
+ * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
913
+ * and {@link hasSignatureLike} (which structurally accepts several known
914
+ * suites): `verifyJsonLd` needs to tell a document with a malformed or
915
+ * unsupported signature payload (classified as `rejected`) apart from a
916
+ * truly unsigned document (classified as `missing`), and only this
917
+ * presence-only check captures both cases.
918
+ */
919
+ function hasLdSignatureProperty(jsonLd) {
920
+ return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
921
+ }
922
+ function getLdSignatureObject(jsonLd) {
923
+ if (!hasLdSignatureProperty(jsonLd)) return void 0;
924
+ const { signature } = jsonLd;
925
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
926
+ return signature;
927
+ }
928
+ /**
929
+ * Verify the authenticity of the given JSON-LD document using Linked Data
930
+ * Signatures. If the document is signed, this function verifies the signature
931
+ * and checks if the document is attributed to the owner of the public key.
932
+ * If the document is not signed, this function returns `false`.
933
+ * @param jsonLd The JSON-LD document to verify.
934
+ * @param options Options for verifying the document.
935
+ * @returns `true` if the document is authentic; `false` otherwise.
936
+ */
937
+ async function verifyJsonLd(jsonLd, options = {}) {
938
+ return await verifyJsonLdInternal(jsonLd, options, true);
939
+ }
940
+ /** @internal */
941
+ async function verifyCompactJsonLd(jsonLd, options = {}) {
942
+ return await verifyJsonLdInternal(jsonLd, options, false);
943
+ }
944
+ async function verifyJsonLdInternal(jsonLd, options, compact) {
945
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
946
+ const start = performance.now();
947
+ let verified = false;
948
+ let threw = false;
949
+ let signatureType;
950
+ try {
951
+ const verificationOptions = hasSignature(jsonLd) ? {
952
+ ...options,
953
+ contextLoader: getNormalizationContextLoader(options.contextLoader)
954
+ } : options;
955
+ const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
956
+ const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
957
+ if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
958
+ span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
959
+ const sig = getLdSignatureObject(jsonLd);
960
+ if (sig != null) {
961
+ if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
962
+ if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
963
+ if (typeof sig.type === "string") {
964
+ span.setAttribute("ld_signatures.type", sig.type);
965
+ if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
966
+ }
967
+ }
968
+ const attributions = new Set(object.attributionIds.map((uri) => uri.href));
969
+ if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
970
+ const key = await verifySignature(compacted, verificationOptions);
971
+ if (key == null) return false;
972
+ if (key.ownerId == null) {
973
+ logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
974
+ return false;
975
+ }
976
+ attributions.delete(key.ownerId.href);
977
+ if (attributions.size > 0) {
978
+ logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
979
+ return false;
980
+ }
981
+ verified = true;
982
+ return true;
983
+ } catch (error) {
984
+ threw = true;
985
+ span.setStatus({
986
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
987
+ message: String(error)
988
+ });
989
+ throw error;
990
+ } finally {
991
+ const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
992
+ require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "linked_data", classified, { ldType: signatureType });
993
+ span.end();
994
+ }
995
+ });
1106
996
  }
1107
- /**
1108
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
1109
- * to locally generated outgoing activities before they are signed, enqueued,
1110
- * or sent.
1111
- */
1112
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
1113
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
1114
- return await normalizeAttachmentArrays(jsonLd, contextLoader);
997
+ async function hashJsonLd(jsonLd, contextLoader) {
998
+ const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
999
+ format: "application/n-quads",
1000
+ documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
1001
+ });
1002
+ const encoder = new TextEncoder();
1003
+ return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
1115
1004
  }
1116
1005
  //#endregion
1117
1006
  //#region src/sig/proof.ts
@@ -1125,7 +1014,7 @@ const Temporal = require_http.Temporal;
1125
1014
  * cardinality.
1126
1015
  */
1127
1016
  const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
1128
- const logger = (0, _logtape_logtape.getLogger)([
1017
+ const logger$1 = (0, _logtape_logtape.getLogger)([
1129
1018
  "fedify",
1130
1019
  "sig",
1131
1020
  "proof"
@@ -1265,7 +1154,31 @@ async function signObject(object, privateKey, keyId, options = {}) {
1265
1154
  async function verifyProof(jsonLd, proof, options = {}) {
1266
1155
  return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
1267
1156
  }
1268
- async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate) {
1157
+ /**
1158
+ * Verifies the one direct literal proof on a map-local secured document.
1159
+ *
1160
+ * Unlike {@link verifyProof}, this removes only the literal `proof` member
1161
+ * from the message digest. JSON-LD aliases remain part of the signed input,
1162
+ * and the document's received `@context` is not replaced by the proof
1163
+ * configuration context.
1164
+ *
1165
+ * @internal
1166
+ */
1167
+ async function verifyMapLocalProof(jsonLd, options = {}) {
1168
+ if (!isJsonLdNode(jsonLd) || !globalThis.Object.hasOwn(jsonLd, "proof") || !isJsonLdNode(jsonLd.proof)) return null;
1169
+ const proofContextLoader = getNormalizationContextLoader(preloadedOnlyDocumentLoader);
1170
+ try {
1171
+ const [candidate] = await parseRawProofCandidates(jsonLd, [jsonLd.proof], options, proofContextLoader);
1172
+ if (candidate.proof == null) return null;
1173
+ return await verifyProofWithMessageDigestCache(jsonLd, candidate.proof, options, {
1174
+ proofContextLoader,
1175
+ proofPropertyMode: "literal"
1176
+ }, candidate);
1177
+ } catch {
1178
+ return null;
1179
+ }
1180
+ }
1181
+ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
1269
1182
  return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
1270
1183
  const start = performance.now();
1271
1184
  let verified = false;
@@ -1277,7 +1190,7 @@ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, message
1277
1190
  if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
1278
1191
  }
1279
1192
  try {
1280
- const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate);
1193
+ const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1281
1194
  if (key == null) span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
1282
1195
  else verified = true;
1283
1196
  return key;
@@ -1335,10 +1248,11 @@ async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoa
1335
1248
  async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
1336
1249
  return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
1337
1250
  }
1338
- async function createProofMessageDigests(jsonLd, proofContextLoader, context) {
1251
+ async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
1339
1252
  const msg = { ...jsonLd };
1340
- for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
1341
- if (context != null) msg["@context"] = structuredClone(context);
1253
+ if (proofPropertyMode === "literal") delete msg.proof;
1254
+ else for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
1255
+ if (proofPropertyMode === "jsonLd" && context != null) msg["@context"] = structuredClone(context);
1342
1256
  const encoder = new TextEncoder();
1343
1257
  const digest = async (value) => {
1344
1258
  const bytes = encoder.encode((0, json_canon.default)(value));
@@ -1594,19 +1508,22 @@ async function hasValidProofOptions(proofConfig, options, documentLoader) {
1594
1508
  if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return false;
1595
1509
  return true;
1596
1510
  }
1597
- async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate) {
1511
+ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
1598
1512
  if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
1599
1513
  const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
1600
1514
  const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
1601
1515
  if (proofConfiguration == null || !await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader)) return null;
1602
- const publicKeyPromise = require_http.measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => require_http.fetchKey(proof.verificationMethodId, _fedify_vocab.Multikey, options));
1516
+ const publicKeyPromise = require_http.measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => require_http.fetchKey(proof.verificationMethodId, _fedify_vocab.Multikey, {
1517
+ ...options,
1518
+ keyIdBoundByCaller
1519
+ }));
1603
1520
  const proofBytes = new TextEncoder().encode((0, json_canon.default)(proofConfiguration.value));
1604
1521
  const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1605
1522
  let fetchedKey;
1606
1523
  try {
1607
1524
  fetchedKey = await publicKeyPromise;
1608
1525
  } catch (error) {
1609
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1526
+ logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1610
1527
  proof,
1611
1528
  keyId: proof.verificationMethodId.href,
1612
1529
  error
@@ -1615,7 +1532,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1615
1532
  }
1616
1533
  const publicKey = fetchedKey.key;
1617
1534
  if (publicKey == null) {
1618
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1535
+ logger$1.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1619
1536
  proof,
1620
1537
  keyId: proof.verificationMethodId.href
1621
1538
  });
@@ -1623,7 +1540,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1623
1540
  }
1624
1541
  if (publicKey.publicKey.algorithm.name !== "Ed25519") {
1625
1542
  if (fetchedKey.cached) {
1626
- logger.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
1543
+ logger$1.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
1627
1544
  proof,
1628
1545
  keyId: proof.verificationMethodId.href
1629
1546
  });
@@ -1633,9 +1550,9 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1633
1550
  get: () => Promise.resolve(void 0),
1634
1551
  set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1635
1552
  }
1636
- }, messageDigestCache, rawProofCandidate);
1553
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1637
1554
  }
1638
- logger.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
1555
+ logger$1.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
1639
1556
  proof,
1640
1557
  keyId: proof.verificationMethodId.href
1641
1558
  });
@@ -1652,15 +1569,17 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1652
1569
  const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
1653
1570
  let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
1654
1571
  if (messageDigestsPromise == null) {
1655
- messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context);
1572
+ messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
1656
1573
  messageDigestValues.set(messageDigestKey, messageDigestsPromise);
1657
1574
  }
1658
1575
  const messageDigests = await messageDigestsPromise;
1659
1576
  if (await verifyCandidate(messageDigests.onWire)) return publicKey;
1660
- const normalizedDigest = await messageDigests.normalized();
1661
- if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
1577
+ if (messageDigestCache.proofPropertyMode !== "literal") {
1578
+ const normalizedDigest = await messageDigests.normalized();
1579
+ if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
1580
+ }
1662
1581
  if (fetchedKey.cached) {
1663
- logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
1582
+ logger$1.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
1664
1583
  keyId: proof.verificationMethodId.href,
1665
1584
  proof
1666
1585
  });
@@ -1670,9 +1589,9 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1670
1589
  get: () => Promise.resolve(void 0),
1671
1590
  set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1672
1591
  }
1673
- }, messageDigestCache, rawProofCandidate);
1592
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1674
1593
  }
1675
- logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1594
+ logger$1.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1676
1595
  keyId: proof.verificationMethodId.href,
1677
1596
  proof
1678
1597
  });
@@ -1750,59 +1669,55 @@ async function expandPortableObjectRoot(jsonLd, contextLoader) {
1750
1669
  }
1751
1670
  };
1752
1671
  }
1753
- /**
1754
- * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
1755
- *
1756
- * This applies the FEP-2277 core-type classification to the top-level JSON-LD
1757
- * node. Portable actors, activities, and objects require proofs. A portable
1758
- * collection without a proof is reported separately so a caller can apply a
1759
- * gateway trust policy. Embedded portable objects are not traversed.
1760
- *
1761
- * Every proof must use a DID URL whose DID matches the portable object's
1762
- * authority, and every proof must pass {@link verifyProof}.
1763
- *
1764
- * @param jsonLd The JSON-LD document to verify.
1765
- * @param options Additional options. See also
1766
- * {@link VerifyPortableObjectProofOptions}.
1767
- * @returns The detailed portable proof-policy result.
1768
- * @throws {TypeError} If the input is not a single JSON-LD object or has a
1769
- * malformed portable ID.
1770
- * @since 2.4.0
1771
- */
1772
- async function verifyPortableObjectProof(jsonLd, options = {}) {
1672
+ async function preparePortableObjectProof(jsonLd, options) {
1773
1673
  if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
1774
- verified: false,
1775
- reason: { type: "notPortableObject" }
1674
+ prepared: false,
1675
+ result: {
1676
+ verified: false,
1677
+ reason: { type: "notPortableObject" }
1678
+ }
1776
1679
  };
1777
1680
  const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
1778
1681
  const id = root["@id"];
1779
1682
  if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
1780
- verified: false,
1781
- reason: { type: "notPortableObject" }
1683
+ prepared: false,
1684
+ result: {
1685
+ verified: false,
1686
+ reason: { type: "notPortableObject" }
1687
+ }
1782
1688
  };
1783
1689
  const objectId = (0, _fedify_vocab_runtime.parseIri)(id);
1784
1690
  (0, _fedify_vocab_runtime.getFe34Origin)(objectId);
1785
1691
  const objectType = classifyFep2277CoreType(root);
1786
1692
  if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
1787
- verified: false,
1788
- reason: {
1789
- type: "unsupportedObjectType",
1790
- objectType
1693
+ prepared: false,
1694
+ result: {
1695
+ verified: false,
1696
+ reason: {
1697
+ type: "unsupportedObjectType",
1698
+ objectType
1699
+ }
1791
1700
  }
1792
1701
  };
1793
1702
  const proofValues = root[SECURITY_PROOF];
1794
- if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return objectType === "collection" ? {
1795
- verified: false,
1796
- reason: { type: "unsecuredCollection" }
1797
- } : {
1798
- verified: false,
1799
- reason: { type: "missingProof" }
1703
+ if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return {
1704
+ prepared: false,
1705
+ result: objectType === "collection" ? {
1706
+ verified: false,
1707
+ reason: { type: "unsecuredCollection" }
1708
+ } : {
1709
+ verified: false,
1710
+ reason: { type: "missingProof" }
1711
+ }
1800
1712
  };
1801
1713
  if (!Array.isArray(proofValues)) return {
1802
- verified: false,
1803
- reason: {
1804
- type: "invalidProof",
1805
- proofIndex: 0
1714
+ prepared: false,
1715
+ result: {
1716
+ verified: false,
1717
+ reason: {
1718
+ type: "invalidProof",
1719
+ proofIndex: 0
1720
+ }
1806
1721
  }
1807
1722
  };
1808
1723
  const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
@@ -1810,10 +1725,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1810
1725
  for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
1811
1726
  const proofValue = proofValues[proofIndex];
1812
1727
  if (!hasValidPortableProofShape(proofValue)) return {
1813
- verified: false,
1814
- reason: {
1815
- type: "invalidProof",
1816
- proofIndex
1728
+ prepared: false,
1729
+ result: {
1730
+ verified: false,
1731
+ reason: {
1732
+ type: "invalidProof",
1733
+ proofIndex
1734
+ }
1817
1735
  }
1818
1736
  };
1819
1737
  let proof;
@@ -1821,10 +1739,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1821
1739
  proof = await _fedify_vocab.DataIntegrityProof.fromJsonLd(proofValue, options);
1822
1740
  } catch {
1823
1741
  return {
1824
- verified: false,
1825
- reason: {
1826
- type: "invalidProof",
1827
- proofIndex
1742
+ prepared: false,
1743
+ result: {
1744
+ verified: false,
1745
+ reason: {
1746
+ type: "invalidProof",
1747
+ proofIndex
1748
+ }
1828
1749
  }
1829
1750
  };
1830
1751
  }
@@ -1833,18 +1754,24 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1833
1754
  for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
1834
1755
  const verificationMethod = proofs[proofIndex].verificationMethodId;
1835
1756
  if (verificationMethod == null) return {
1836
- verified: false,
1837
- reason: {
1838
- type: "invalidProof",
1839
- proofIndex
1757
+ prepared: false,
1758
+ result: {
1759
+ verified: false,
1760
+ reason: {
1761
+ type: "invalidProof",
1762
+ proofIndex
1763
+ }
1840
1764
  }
1841
1765
  };
1842
1766
  if (verificationMethod.protocol !== "did:") return {
1843
- verified: false,
1844
- reason: {
1845
- type: "unsupportedVerificationMethod",
1846
- proofIndex,
1847
- verificationMethod
1767
+ prepared: false,
1768
+ result: {
1769
+ verified: false,
1770
+ reason: {
1771
+ type: "unsupportedVerificationMethod",
1772
+ proofIndex,
1773
+ verificationMethod
1774
+ }
1848
1775
  }
1849
1776
  };
1850
1777
  try {
@@ -1852,24 +1779,89 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1852
1779
  } catch (error) {
1853
1780
  if (!(error instanceof TypeError)) throw error;
1854
1781
  return {
1782
+ prepared: false,
1783
+ result: {
1784
+ verified: false,
1785
+ reason: {
1786
+ type: "unsupportedVerificationMethod",
1787
+ proofIndex,
1788
+ verificationMethod
1789
+ }
1790
+ }
1791
+ };
1792
+ }
1793
+ if (!(0, _fedify_vocab_runtime.haveSameFe34Origin)(objectId, verificationMethod)) return {
1794
+ prepared: false,
1795
+ result: {
1855
1796
  verified: false,
1856
1797
  reason: {
1857
- type: "unsupportedVerificationMethod",
1798
+ type: "verificationMethodMismatch",
1858
1799
  proofIndex,
1800
+ objectId,
1859
1801
  verificationMethod
1860
1802
  }
1861
- };
1862
- }
1863
- if (!(0, _fedify_vocab_runtime.haveSameFe34Origin)(objectId, verificationMethod)) return {
1864
- verified: false,
1865
- reason: {
1866
- type: "verificationMethodMismatch",
1867
- proofIndex,
1868
- objectId,
1869
- verificationMethod
1870
1803
  }
1871
1804
  };
1872
1805
  }
1806
+ return {
1807
+ prepared: true,
1808
+ objectId,
1809
+ proofs,
1810
+ rawProofValues,
1811
+ proofContextLoader
1812
+ };
1813
+ }
1814
+ /**
1815
+ * Applies portable-object proof policy to one map-local cryptographic result.
1816
+ *
1817
+ * @internal
1818
+ */
1819
+ async function verifyPortableObjectProofPolicy(jsonLd, key, options = {}) {
1820
+ const policyOptions = {
1821
+ ...options,
1822
+ contextLoader: preloadedOnlyDocumentLoader
1823
+ };
1824
+ const prepared = await preparePortableObjectProof(jsonLd, policyOptions);
1825
+ if (!prepared.prepared) return prepared.result;
1826
+ const policyProof = prepared.proofs[0];
1827
+ const literalProof = isJsonLdNode(jsonLd) && isJsonLdNode(jsonLd.proof) ? (await parseRawProofCandidates(jsonLd, [jsonLd.proof], policyOptions, prepared.proofContextLoader))[0]?.proof : null;
1828
+ const verificationMethod = policyProof?.verificationMethodId;
1829
+ if (prepared.proofs.length !== 1 || key == null || policyProof == null || literalProof == null || !sameProof(policyProof, literalProof) || verificationMethod == null || key.id?.href !== verificationMethod.href) return {
1830
+ verified: false,
1831
+ reason: {
1832
+ type: "invalidProof",
1833
+ proofIndex: prepared.proofs.length > 1 ? 1 : 0
1834
+ }
1835
+ };
1836
+ return {
1837
+ verified: true,
1838
+ keys: [key],
1839
+ objectId: (0, _fedify_vocab_runtime.formatIri)(prepared.objectId)
1840
+ };
1841
+ }
1842
+ /**
1843
+ * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
1844
+ *
1845
+ * This applies the FEP-2277 core-type classification to the top-level JSON-LD
1846
+ * node. Portable actors, activities, and objects require proofs. A portable
1847
+ * collection without a proof is reported separately so a caller can apply a
1848
+ * gateway trust policy. Embedded portable objects are not traversed.
1849
+ *
1850
+ * Every proof must use a DID URL whose DID matches the portable object's
1851
+ * authority, and every proof must pass {@link verifyProof}.
1852
+ *
1853
+ * @param jsonLd The JSON-LD document to verify.
1854
+ * @param options Additional options. See also
1855
+ * {@link VerifyPortableObjectProofOptions}.
1856
+ * @returns The detailed portable proof-policy result.
1857
+ * @throws {TypeError} If the input is not a single JSON-LD object or has a
1858
+ * malformed portable ID.
1859
+ * @since 2.4.0
1860
+ */
1861
+ async function verifyPortableObjectProof(jsonLd, options = {}) {
1862
+ const prepared = await preparePortableObjectProof(jsonLd, options);
1863
+ if (!prepared.prepared) return prepared.result;
1864
+ const { proofs, rawProofValues, proofContextLoader } = prepared;
1873
1865
  const keys = [];
1874
1866
  const rawProofCandidatePool = {
1875
1867
  candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
@@ -1885,7 +1877,7 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1885
1877
  proofIndex
1886
1878
  }
1887
1879
  };
1888
- const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate);
1880
+ const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
1889
1881
  if (key == null) return {
1890
1882
  verified: false,
1891
1883
  reason: {
@@ -1988,6 +1980,171 @@ function hasCryptographicOrigin(iri) {
1988
1980
  return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
1989
1981
  }
1990
1982
  //#endregion
1983
+ //#region src/sig/owner.ts
1984
+ const logger = (0, _logtape_logtape.getLogger)([
1985
+ "fedify",
1986
+ "sig",
1987
+ "owner"
1988
+ ]);
1989
+ /**
1990
+ * Checks if the actor of the given activity owns the specified key.
1991
+ *
1992
+ * Ownership is never taken from what the activity or the key say about
1993
+ * themselves, as both are written by whoever sent the activity. It is
1994
+ * established from a document that the owner itself serves: either the key's
1995
+ * claimed owner links back to the key, or the actor the activity claims lists
1996
+ * the key as its own.
1997
+ *
1998
+ * @param activity The activity to check.
1999
+ * @param key The public key to check.
2000
+ * @param options Options for checking the key ownership.
2001
+ * @returns Whether the actor is the owner of the key.
2002
+ */
2003
+ async function doesActorOwnKey(activity, key, options) {
2004
+ return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
2005
+ kind: _opentelemetry_api.SpanKind.INTERNAL,
2006
+ attributes: {
2007
+ "activitypub.actor.id": activity.actorId?.href ?? "",
2008
+ "activitypub.key.id": key.id?.href ?? ""
2009
+ }
2010
+ }, async (span) => {
2011
+ try {
2012
+ const actorId = activity.actorId;
2013
+ if (actorId == null) {
2014
+ span.setAttribute("activitypub.key_ownership.verified", false);
2015
+ span.setAttribute("activitypub.key_ownership.method", "none");
2016
+ return false;
2017
+ }
2018
+ if (key.ownerId != null) {
2019
+ const owner = await require_http.verifyKeyOwnership(key, options);
2020
+ if (owner?.id != null && owner.id.href === actorId.href) {
2021
+ span.setAttribute("activitypub.key_ownership.verified", true);
2022
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
2023
+ return true;
2024
+ }
2025
+ }
2026
+ const actor = await require_http.fetchActorDocument(actorId, options);
2027
+ if (actor != null && await doesActorListKey(actor, key, options)) {
2028
+ span.setAttribute("activitypub.key_ownership.verified", true);
2029
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
2030
+ return true;
2031
+ }
2032
+ logger.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
2033
+ actorId: actorId.href,
2034
+ keyId: key.id?.href
2035
+ });
2036
+ span.setAttribute("activitypub.key_ownership.verified", false);
2037
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
2038
+ return false;
2039
+ } catch (error) {
2040
+ span.recordException(error);
2041
+ span.setStatus({
2042
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
2043
+ message: String(error)
2044
+ });
2045
+ throw error;
2046
+ } finally {
2047
+ span.end();
2048
+ }
2049
+ });
2050
+ }
2051
+ /**
2052
+ * Determines whether the given actor's own document lists the given key among
2053
+ * its public keys.
2054
+ *
2055
+ * Keys are matched by id, which is what an actor document links to. A key
2056
+ * document may leave its id implicit, though, and then there is no id for the
2057
+ * actor to link to; the key material itself is the only thing the two can
2058
+ * have in common, so that is what gets compared.
2059
+ */
2060
+ async function doesActorListKey(actor, key, options) {
2061
+ if (key.id != null) {
2062
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
2063
+ return false;
2064
+ }
2065
+ if (key.publicKey == null) return false;
2066
+ const publicKeys = actor.getPublicKeys({
2067
+ ...options,
2068
+ suppressError: true
2069
+ });
2070
+ for await (const publicKey of publicKeys) {
2071
+ if (publicKey.publicKey == null) continue;
2072
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
2073
+ }
2074
+ return false;
2075
+ }
2076
+ /**
2077
+ * Compares two public keys by their key material, ignoring the metadata that
2078
+ * surrounds it.
2079
+ */
2080
+ async function isSamePublicKey(a, b) {
2081
+ const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
2082
+ 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;
2083
+ }
2084
+ /**
2085
+ * Gets the actor that owns the specified key. Returns `null` if the key has no
2086
+ * known owner.
2087
+ *
2088
+ * The owner is only returned when the key and the owner link to each other:
2089
+ * a document that merely claims to own a key is not enough, as the claim and
2090
+ * the key can come from the same host.
2091
+ *
2092
+ * @param keyId The ID of the key to check, or the key itself.
2093
+ * @param options Options for getting the key owner.
2094
+ * @returns The actor that owns the key, or `null` if the key has no known
2095
+ * owner.
2096
+ * @since 0.7.0
2097
+ */
2098
+ async function getKeyOwner(keyId, options) {
2099
+ const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
2100
+ const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
2101
+ const fetchOptions = {
2102
+ documentLoader,
2103
+ contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
2104
+ tracerProvider
2105
+ };
2106
+ if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
2107
+ let keyDoc;
2108
+ let documentUrl = keyId;
2109
+ try {
2110
+ const remoteDocument = await documentLoader(keyId.href);
2111
+ keyDoc = remoteDocument.document;
2112
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
2113
+ } catch (_) {
2114
+ return null;
2115
+ }
2116
+ let object;
2117
+ try {
2118
+ object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
2119
+ ...fetchOptions,
2120
+ baseUrl: documentUrl
2121
+ });
2122
+ } catch (e) {
2123
+ if (!(e instanceof TypeError)) throw e;
2124
+ try {
2125
+ object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
2126
+ } catch (e) {
2127
+ if (e instanceof TypeError) return null;
2128
+ throw e;
2129
+ }
2130
+ }
2131
+ if (object instanceof _fedify_vocab.CryptographicKey) {
2132
+ if (object.id != null && object.id.href !== keyId.href) return null;
2133
+ return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
2134
+ }
2135
+ if (!(0, _fedify_vocab.isActor)(object)) return null;
2136
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
2137
+ logger.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
2138
+ documentUrl: documentUrl.href,
2139
+ actorId: object.id?.href,
2140
+ keyId: keyId.href
2141
+ });
2142
+ return null;
2143
+ }
2144
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
2145
+ return null;
2146
+ }
2147
+ //#endregion
1991
2148
  Object.defineProperty(exports, "InvalidContextReferenceError", {
1992
2149
  enumerable: true,
1993
2150
  get: function() {
@@ -2108,6 +2265,12 @@ Object.defineProperty(exports, "verifyJsonLd", {
2108
2265
  return verifyJsonLd;
2109
2266
  }
2110
2267
  });
2268
+ Object.defineProperty(exports, "verifyMapLocalProof", {
2269
+ enumerable: true,
2270
+ get: function() {
2271
+ return verifyMapLocalProof;
2272
+ }
2273
+ });
2111
2274
  Object.defineProperty(exports, "verifyObject", {
2112
2275
  enumerable: true,
2113
2276
  get: function() {
@@ -2120,6 +2283,12 @@ Object.defineProperty(exports, "verifyPortableObjectProof", {
2120
2283
  return verifyPortableObjectProof;
2121
2284
  }
2122
2285
  });
2286
+ Object.defineProperty(exports, "verifyPortableObjectProofPolicy", {
2287
+ enumerable: true,
2288
+ get: function() {
2289
+ return verifyPortableObjectProofPolicy;
2290
+ }
2291
+ });
2123
2292
  Object.defineProperty(exports, "verifyProof", {
2124
2293
  enumerable: true,
2125
2294
  get: function() {