@fedify/fedify 2.4.0-dev.1988 → 2.4.0-dev.2010

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 (62) hide show
  1. package/dist/{builder-Cts78G9N.mjs → builder-asm96yV1.mjs} +2 -2
  2. package/dist/compat/transformers.test.mjs +1 -1
  3. package/dist/compound-proof-7UIAueLV.mjs +495 -0
  4. package/dist/{deno-BgMEefEr.mjs → deno-Ckq9TwCv.mjs} +1 -1
  5. package/dist/{docloader-DEYs99FZ.mjs → docloader-DUKEPG-O.mjs} +2 -2
  6. package/dist/federation/builder.test.mjs +1 -1
  7. package/dist/federation/handler-compound-proof.test.d.mts +2 -0
  8. package/dist/federation/handler-compound-proof.test.mjs +152 -0
  9. package/dist/federation/handler.test.mjs +5 -5
  10. package/dist/federation/idempotency.test.mjs +2 -2
  11. package/dist/federation/metrics.test.mjs +1 -1
  12. package/dist/federation/middleware.test.mjs +7 -7
  13. package/dist/federation/mod.cjs +1 -1
  14. package/dist/federation/mod.js +1 -1
  15. package/dist/federation/send.test.mjs +3 -3
  16. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  17. package/dist/federation/tasks/tasks.test.mjs +2 -2
  18. package/dist/federation/temporal.test.mjs +1 -1
  19. package/dist/federation/webfinger.test.mjs +1 -1
  20. package/dist/{federation-DzPUG_AP.cjs → federation-CgbvMauV.cjs} +542 -43
  21. package/dist/{http-CgwqtxAy.js → http-DQA2JOEJ.js} +2 -2
  22. package/dist/{http-Z3anvCd-.cjs → http-DQBfmkrS.cjs} +2 -2
  23. package/dist/{http-CtidZS_t.mjs → http-DZaAutqg.mjs} +3 -3
  24. package/dist/{key-Cwbg5ggV.mjs → key-zxzx01Ec.mjs} +2 -2
  25. package/dist/{kv-cache-CykuL0ya.js → kv-cache-BBoePTOJ.js} +1 -1
  26. package/dist/{kv-cache-DHiR8yTf.mjs → kv-cache-CbrUX90H.mjs} +1 -1
  27. package/dist/{kv-cache-BM2-w-Wq.cjs → kv-cache-sy8OMNT8.cjs} +1 -1
  28. package/dist/{ld-CzhdWyTt.mjs → ld-CD_TN0e8.mjs} +3 -3
  29. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +204 -0
  30. package/dist/map-local-create-note-B0SeXJms.mjs +214 -0
  31. package/dist/{metrics-CrqsHP0l.mjs → metrics-B47Cm5gK.mjs} +1 -1
  32. package/dist/{middleware-CeCj5caM.js → middleware-U0OIuqwD.js} +511 -12
  33. package/dist/{middleware-CZpYxSKD.mjs → middleware-U_Gannqi.mjs} +1 -1
  34. package/dist/{middleware-DCpiAsZi.mjs → middleware-pHwDTAnq.mjs} +52 -20
  35. package/dist/mod.cjs +19 -19
  36. package/dist/mod.js +4 -4
  37. package/dist/nodeinfo/handler.test.mjs +1 -1
  38. package/dist/{proof-DHu5zI0Z.cjs → owner--mNatWct.cjs} +1252 -1140
  39. package/dist/{proof-CUghqhAf.js → owner-BNKC3s6G.js} +1239 -1139
  40. package/dist/{owner-BqVXJLW8.mjs → owner-u3IJRhVx.mjs} +2 -2
  41. package/dist/{proof-DL8Iid3a.mjs → proof-D3te0SP-.mjs} +176 -76
  42. package/dist/{send-6jS4xFsX.mjs → send-CDr0Zivk.mjs} +3 -3
  43. package/dist/sig/compound-proof-discovery.test.d.mts +2 -0
  44. package/dist/sig/compound-proof-discovery.test.mjs +331 -0
  45. package/dist/sig/compound-proof-verification.test.d.mts +2 -0
  46. package/dist/sig/compound-proof-verification.test.mjs +465 -0
  47. package/dist/sig/compound-proof.test.d.mts +2 -0
  48. package/dist/sig/compound-proof.test.mjs +324 -0
  49. package/dist/sig/http.test.mjs +2 -2
  50. package/dist/sig/key.test.mjs +1 -1
  51. package/dist/sig/ld.test.mjs +2 -2
  52. package/dist/sig/mod.cjs +17 -17
  53. package/dist/sig/mod.js +2 -2
  54. package/dist/sig/owner.test.mjs +1 -1
  55. package/dist/sig/proof.test.mjs +1 -1
  56. package/dist/{temporal-DcyzeytP.mjs → temporal-DKhVF_Uk.mjs} +1 -1
  57. package/dist/testing/kv.test.mjs +1 -1
  58. package/dist/utils/docloader.test.mjs +2 -2
  59. package/dist/utils/kv-cache.test.mjs +1 -1
  60. package/dist/utils/mod.cjs +1 -1
  61. package/dist/utils/mod.js +1 -1
  62. package/package.json +6 -6
@@ -1,1171 +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-Z3anvCd-.cjs");
3
+ const require_http = require("./http-DQBfmkrS.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
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
15
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$4.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$4.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$4.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$4.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$4.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
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$4.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$4.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
- });
488
+ };
616
489
  }
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)()
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);
497
+ }
498
+ return await loader(url, options);
621
499
  });
622
- const encoder = new TextEncoder();
623
- return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
624
500
  }
625
- //#endregion
626
- //#region src/sig/owner.ts
627
- const logger$3 = (0, _logtape_logtape.getLogger)([
628
- "fedify",
629
- "sig",
630
- "owner"
631
- ]);
632
- /**
633
- * Checks if the actor of the given activity owns the specified key.
634
- *
635
- * Ownership is never taken from what the activity or the key say about
636
- * themselves, as both are written by whoever sent the activity. It is
637
- * established from a document that the owner itself serves: either the key's
638
- * claimed owner links back to the key, or the actor the activity claims lists
639
- * the key as its own.
640
- *
641
- * @param activity The activity to check.
642
- * @param key The public key to check.
643
- * @param options Options for checking the key ownership.
644
- * @returns Whether the actor is the owner of the key.
645
- */
646
- async function doesActorOwnKey(activity, key, options) {
647
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
648
- kind: _opentelemetry_api.SpanKind.INTERNAL,
649
- attributes: {
650
- "activitypub.actor.id": activity.actorId?.href ?? "",
651
- "activitypub.key.id": key.id?.href ?? ""
652
- }
653
- }, async (span) => {
654
- try {
655
- const actorId = activity.actorId;
656
- if (actorId == null) {
657
- span.setAttribute("activitypub.key_ownership.verified", false);
658
- span.setAttribute("activitypub.key_ownership.method", "none");
659
- return false;
660
- }
661
- if (key.ownerId != null) {
662
- const owner = await require_http.verifyKeyOwnership(key, options);
663
- if (owner?.id != null && owner.id.href === actorId.href) {
664
- span.setAttribute("activitypub.key_ownership.verified", true);
665
- span.setAttribute("activitypub.key_ownership.method", "key_owner");
666
- return true;
667
- }
668
- }
669
- const actor = await require_http.fetchActorDocument(actorId, options);
670
- if (actor != null && await doesActorListKey(actor, key, options)) {
671
- span.setAttribute("activitypub.key_ownership.verified", true);
672
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
673
- return true;
674
- }
675
- logger$3.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
676
- actorId: actorId.href,
677
- keyId: key.id?.href
678
- });
679
- span.setAttribute("activitypub.key_ownership.verified", false);
680
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
681
- return false;
682
- } catch (error) {
683
- span.recordException(error);
684
- span.setStatus({
685
- code: _opentelemetry_api.SpanStatusCode.ERROR,
686
- message: String(error)
687
- });
688
- throw error;
689
- } finally {
690
- span.end();
691
- }
692
- });
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;
693
512
  }
694
- /**
695
- * Determines whether the given actor's own document lists the given key among
696
- * its public keys.
697
- *
698
- * Keys are matched by id, which is what an actor document links to. A key
699
- * document may leave its id implicit, though, and then there is no id for the
700
- * actor to link to; the key material itself is the only thing the two can
701
- * have in common, so that is what gets compared.
702
- */
703
- async function doesActorListKey(actor, key, options) {
704
- if (key.id != null) {
705
- for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
706
- return false;
707
- }
708
- if (key.publicKey == null) return false;
709
- const publicKeys = actor.getPublicKeys({
710
- ...options,
711
- suppressError: true
712
- });
713
- for await (const publicKey of publicKeys) {
714
- if (publicKey.publicKey == null) continue;
715
- if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
716
- }
717
- 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;
718
521
  }
719
- /**
720
- * Compares two public keys by their key material, ignoring the metadata that
721
- * surrounds it.
722
- */
723
- async function isSamePublicKey(a, b) {
724
- const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
725
- 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;
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
+ };
726
533
  }
727
- /**
728
- * Gets the actor that owns the specified key. Returns `null` if the key has no
729
- * known owner.
730
- *
731
- * The owner is only returned when the key and the owner link to each other:
732
- * a document that merely claims to own a key is not enough, as the claim and
733
- * the key can come from the same host.
734
- *
735
- * @param keyId The ID of the key to check, or the key itself.
736
- * @param options Options for getting the key owner.
737
- * @returns The actor that owns the key, or `null` if the key has no known
738
- * owner.
739
- * @since 0.7.0
740
- */
741
- async function getKeyOwner(keyId, options) {
742
- const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
743
- const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
744
- const fetchOptions = {
745
- documentLoader,
746
- contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
747
- tracerProvider
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()
748
540
  };
749
- if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
750
- let keyDoc;
751
- let documentUrl = keyId;
752
- try {
753
- const remoteDocument = await documentLoader(keyId.href);
754
- keyDoc = remoteDocument.document;
755
- documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
756
- } catch (_) {
757
- return null;
758
- }
759
- let object;
760
- try {
761
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
762
- ...fetchOptions,
763
- baseUrl: documentUrl
764
- });
765
- } catch (e) {
766
- if (!(e instanceof TypeError)) throw e;
767
- try {
768
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
769
- } catch (e) {
770
- if (e instanceof TypeError) return null;
771
- throw e;
772
- }
773
- }
774
- if (object instanceof _fedify_vocab.CryptographicKey) {
775
- if (object.id != null && object.id.href !== keyId.href) return null;
776
- return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
777
- }
778
- if (!(0, _fedify_vocab.isActor)(object)) return null;
779
- if (object.id == null || object.id.origin !== documentUrl.origin) {
780
- logger$3.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
781
- documentUrl: documentUrl.href,
782
- actorId: object.id?.href,
783
- keyId: keyId.href
784
- });
785
- return null;
786
- }
787
- for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
788
- return null;
789
541
  }
790
- //#endregion
791
- //#region src/compat/preloaded-context-loader.ts
792
- /**
793
- * A restricted JSON-LD document loader that resolves only contexts bundled
794
- * with Fedify.
795
- *
796
- * This is intentionally narrower than `getDocumentLoader()`: normalization
797
- * helpers are also reached from verification paths that operate on inbound,
798
- * attacker-controlled JSON-LD, so the default fallback must never fetch
799
- * attacker-supplied context URLs.
800
- */
801
- const preloadedOnlyDocumentLoader = (url) => {
802
- if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
803
- contextUrl: null,
804
- documentUrl: url,
805
- document: _fedify_vocab_runtime.preloadedContexts[url]
806
- });
807
- return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
808
- };
809
- //#endregion
810
- //#region src/compat/public-audience.ts
811
- const logger$2 = (0, _logtape_logtape.getLogger)([
812
- "fedify",
813
- "compat",
814
- "public-audience"
815
- ]);
816
- const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
817
- "to",
818
- "cc",
819
- "bto",
820
- "bcc",
821
- "audience"
822
- ]);
823
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
824
- const MAX_TRAVERSAL_DEPTH$1 = 64;
825
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
826
- function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
827
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
828
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
829
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
830
- if (typeof value !== "object" || value == null) return false;
831
- const record = value;
832
- for (const key of Object.keys(record)) {
833
- if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
834
- if (key === "@context") continue;
835
- if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
836
- }
837
- 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
+ };
838
549
  }
839
- function rewritePublicAudience(value, parentKey, depth = 0) {
840
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
841
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
842
- if (Array.isArray(value)) {
843
- let changed = false;
844
- const mapped = value.map((item) => {
845
- const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
846
- if (rewritten !== item) changed = true;
847
- return rewritten;
848
- });
849
- return changed ? mapped : value;
850
- }
851
- if (typeof value !== "object" || value == null) return value;
852
- const record = value;
853
- let changed = false;
854
- const normalized = Object.create(null);
855
- for (const key of Object.keys(record)) {
856
- 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);
857
- if (rewritten !== record[key]) changed = true;
858
- normalized[key] = rewritten;
859
- }
860
- return changed ? normalized : value;
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;
861
555
  }
862
- /**
863
- * Reports whether `value` carries an `@context` property anywhere inside
864
- * its subtree (not counting the value itself). A nested `@context` can
865
- * introduce a local term-definition scope that redefines `as:` or `Public`
866
- * even when the top-level `@context` is safe, so the fast path must defer
867
- * to the URDNA2015 equivalence check whenever one is present.
868
- */
869
- function hasNestedContext$1(value, depth = 0) {
870
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
871
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
872
- if (typeof value !== "object" || value == null) return false;
873
- const record = value;
874
- for (const key of Object.keys(record)) {
875
- if (key === "@context") return true;
876
- if (hasNestedContext$1(record[key], depth + 1)) return true;
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;
877
563
  }
878
- return false;
879
564
  }
880
- /**
881
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
882
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
883
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
884
- * preloaded context set AND including the ActivityStreams URL qualify,
885
- * AND no nested subtree carries its own `@context` that might redefine
886
- * those terms within a local scope. When all of that holds the rewrite
887
- * is provably semantics-preserving and the URDNA2015 equivalence check
888
- * can be skipped. Any other shape (unknown external URLs, inline
889
- * objects at the top level, nested `@context` blocks) is treated as
890
- * potentially unsafe.
891
- */
892
- function hasKnownSafeContext$1(jsonLd) {
893
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
894
- const record = jsonLd;
895
- if (!Object.hasOwn(record, "@context")) return false;
896
- const ctx = record["@context"];
897
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
898
- if (entries == null || entries.length === 0) return false;
899
- let hasAs = false;
900
- for (const entry of entries) {
901
- if (typeof entry !== "string") return false;
902
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
903
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
904
- }
905
- if (!hasAs) return false;
906
- for (const key of Object.keys(record)) {
907
- if (key === "@context") continue;
908
- if (hasNestedContext$1(record[key])) return false;
909
- }
910
- return true;
565
+ function isJsonTypedDefinition(definition) {
566
+ return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
911
567
  }
912
- /**
913
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
914
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
915
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
916
- *
917
- * Several ActivityPub implementations, Lemmy among them, match these
918
- * fields as plain URLs without running JSON-LD expansion, and silently
919
- * drop activities whose public addressing appears in CURIE form. This
920
- * helper works around that gap.
921
- *
922
- * For documents whose `@context` is drawn entirely from Fedify's
923
- * preloaded context set and includes the ActivityStreams URL, the
924
- * rewrite is applied directly: the content of every preloaded non-AS
925
- * context is known not to redefine the `as:` prefix or the bare `Public`
926
- * term, so the semantics are preserved by construction. Any other
927
- * shape (an inline object, an unknown external URL, and so on) is
928
- * treated as potentially unsafe and gated on a JSON-LD equivalence
929
- * check; both forms are canonicalized with URDNA2015 and the resulting
930
- * N-Quads are compared. When they differ, the original document is
931
- * returned unchanged. Canonicalization failures also fall back to the
932
- * original document.
933
- *
934
- * When no `contextLoader` is supplied the helper falls back to an
935
- * internal loader that resolves only the URLs in Fedify's
936
- * preloaded-contexts set and rejects every other URL without issuing a
937
- * network request. That behaviour is deliberately narrower than
938
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
939
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
940
- * helper is reached from verification paths (`verifyProof()` /
941
- * `verifyObject()`) that operate on inbound, potentially adversarial
942
- * JSON-LD, and a default loader that fetches attacker-supplied
943
- * `@context` URLs on the caller's behalf would be an SSRF vector.
944
- * Canonicalization failures against the restricted loader fall back to
945
- * the original document, same as any other canonicalization error.
946
- * Callers that genuinely need the remote-fetch loader (for example
947
- * applications that sign local JSON-LD against a custom vocabulary)
948
- * should pass a `contextLoader` explicitly.
949
- *
950
- * Must be called before any signing step that canonicalizes the
951
- * compact form byte-for-byte (for example, Object Integrity Proofs
952
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
953
- * matches what is sent on the wire.
954
- */
955
- async function normalizePublicAudience(jsonLd, contextLoader) {
956
- if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
957
- const normalized = rewritePublicAudience(jsonLd);
958
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
959
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
960
- try {
961
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
962
- format: "application/n-quads",
963
- documentLoader: loader
964
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
965
- format: "application/n-quads",
966
- documentLoader: loader
967
- })]);
968
- if (before === after) return normalized;
969
- 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.");
970
- } catch (error) {
971
- logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
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);
972
575
  }
973
- return jsonLd;
576
+ return resolveContextTarget(target, state);
974
577
  }
975
- //#endregion
976
- //#region src/compat/outgoing-jsonld.ts
977
- const logger$1 = (0, _logtape_logtape.getLogger)([
978
- "fedify",
979
- "compat",
980
- "outgoing-jsonld"
981
- ]);
982
- const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
983
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
984
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
985
- const MAX_TRAVERSAL_DEPTH = 64;
986
- function isJsonLdListObject(value) {
987
- 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);
988
581
  }
989
- function isJsonLdValueObject(value) {
990
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
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;
991
585
  }
992
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
993
- if (Array.isArray(value)) {
994
- if (seen.has(value)) return;
995
- seen.add(value);
996
- for (const item of value) yield* getContextObjects(item, seen);
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));
590
+ }
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;
597
+ }
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);
646
+ }
647
+ refreshGraphAliases(nextState);
648
+ }
649
+ return nextState;
650
+ }
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);
997
654
  return;
998
655
  }
999
- if (typeof value === "object" && value != null) {
1000
- if (seen.has(value)) return;
1001
- seen.add(value);
1002
- const record = value;
1003
- yield record;
1004
- for (const definition of Object.values(record)) {
1005
- if (typeof definition !== "object" || definition == null) continue;
1006
- const nestedContext = definition["@context"];
1007
- if (nestedContext == null) continue;
1008
- yield* getContextObjects(nestedContext, seen);
1009
- }
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);
1010
667
  }
1011
668
  }
1012
- function isActivityStreamsAttachmentTerm(value) {
1013
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
669
+ function isJsonLiteralWrapper(value) {
670
+ return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
1014
671
  }
1015
672
  /** @internal */
1016
- function isPreloadedContextAttachmentSafe(document) {
1017
- if (typeof document !== "object" || document == null) return true;
1018
- const context = document["@context"];
1019
- for (const contextObject of getContextObjects(context)) {
1020
- if (!Object.hasOwn(contextObject, "attachment")) continue;
1021
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
1022
- 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
+ }
1023
682
  }
1024
- return true;
1025
683
  }
1026
- function getKnownSafeContextUrls() {
1027
- const urls = /* @__PURE__ */ new Set();
1028
- for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
1029
- 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 });
1030
- 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
+ };
1031
699
  }
1032
700
  /**
1033
- * 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
1034
710
  */
1035
- function wrapScalarAttachments(jsonLd, depth = 0) {
1036
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
1037
- if (Array.isArray(jsonLd)) {
1038
- let normalized = null;
1039
- for (let i = 0; i < jsonLd.length; i++) {
1040
- const item = jsonLd[i];
1041
- const next = wrapScalarAttachments(item, depth + 1);
1042
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
1043
- if (normalized != null) normalized[i] = next;
1044
- }
1045
- return normalized ?? jsonLd;
1046
- }
1047
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
1048
- const record = jsonLd;
1049
- const keys = Object.keys(record);
1050
- let normalized = null;
1051
- for (let i = 0; i < keys.length; i++) {
1052
- const key = keys[i];
1053
- const value = record[key];
1054
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
1055
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
1056
- if (normalized == null && output !== value) {
1057
- const cloned = Object.create(null);
1058
- for (let j = 0; j < i; j++) {
1059
- const previousKey = keys[j];
1060
- 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)));
1061
748
  }
1062
- 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();
1063
758
  }
1064
- if (normalized != null) normalized[key] = output;
1065
- }
1066
- return normalized ?? jsonLd;
1067
- }
1068
- function hasNestedContext(value, depth = 0) {
1069
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1070
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
1071
- if (typeof value !== "object" || value == null) return false;
1072
- const record = value;
1073
- for (const key of Object.keys(record)) {
1074
- if (key === "@context") return true;
1075
- if (key === "@value" && isJsonLdValueObject(value)) continue;
1076
- if (hasNestedContext(record[key], depth + 1)) return true;
1077
- }
1078
- return false;
759
+ });
1079
760
  }
1080
- function exceedsTraversalDepth(value, depth = 0) {
1081
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1082
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
1083
- if (typeof value !== "object" || value == null) return false;
1084
- const record = value;
1085
- for (const key of Object.keys(record)) {
1086
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
1087
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
1088
- }
1089
- 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);
1090
783
  }
1091
- 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) {
1092
791
  if (typeof jsonLd !== "object" || jsonLd == null) return false;
1093
- const record = jsonLd;
1094
- if (!Object.hasOwn(record, "@context")) return false;
1095
- const context = record["@context"];
1096
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
1097
- if (entries == null || entries.length < 1) return false;
1098
- let hasActivityStreamsContext = false;
1099
- for (const entry of entries) {
1100
- if (typeof entry !== "string") return false;
1101
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
1102
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
1103
- }
1104
- if (!hasActivityStreamsContext) return false;
1105
- for (const key of Object.keys(record)) {
1106
- if (key === "@context") continue;
1107
- 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";
1108
796
  }
1109
- return true;
797
+ return false;
1110
798
  }
1111
- function getLogSafeJsonLdMetadata(jsonLd) {
1112
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
1113
- const record = jsonLd;
1114
- const context = record["@context"];
1115
- return {
1116
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
1117
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
1118
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
1119
- };
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;
1120
811
  }
1121
812
  /**
1122
- * Ensures ActivityStreams attachment properties are represented as arrays
1123
- * when doing so preserves the JSON-LD semantics.
1124
- *
1125
- * JSON-LD compaction collapses single-item arrays into scalar values by
1126
- * default. Some ActivityPub implementations, Pixelfed among them, parse
1127
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
1128
- * otherwise valid objects whose single attachment is emitted as a scalar.
813
+ * Verifies Linked Data Signatures of the given JSON-LD document.
1129
814
  *
1130
- * When no `contextLoader` is supplied, the helper falls back to a restricted
1131
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
1132
- * every other URL without network access. Documents with custom, inline, or
1133
- * otherwise uncached contexts should pass a real `contextLoader` if they need
1134
- * the semantic-preservation check to succeed; otherwise canonicalization
1135
- * 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
1136
830
  */
1137
- async function normalizeAttachmentArrays(jsonLd, contextLoader) {
1138
- const normalized = wrapScalarAttachments(jsonLd);
1139
- if (normalized === jsonLd) return jsonLd;
1140
- if (exceedsTraversalDepth(jsonLd)) {
1141
- logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
1142
- 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;
1143
843
  }
1144
- if (hasKnownSafeContext(jsonLd)) return normalized;
1145
- 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;
1146
854
  try {
1147
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
1148
- format: "application/n-quads",
1149
- documentLoader: loader
1150
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
1151
- format: "application/n-quads",
1152
- documentLoader: loader
1153
- })]);
1154
- if (before === after) return normalized;
1155
- 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);
1156
856
  } catch (error) {
1157
- logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { 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;
1158
862
  }
1159
- return jsonLd;
863
+ const document = { ...jsonLd };
864
+ delete document.signature;
865
+ let docHash;
866
+ try {
867
+ docHash = await hashJsonLd(document, options.contextLoader);
868
+ } catch (error) {
869
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
870
+ document,
871
+ error
872
+ });
873
+ return null;
874
+ }
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;
1160
900
  }
1161
901
  /**
1162
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
1163
- * to locally generated outgoing activities before they are signed, enqueued,
1164
- * or sent.
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.
1165
907
  */
1166
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
1167
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
1168
- return await normalizeAttachmentArrays(jsonLd, contextLoader);
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
+ });
996
+ }
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)));
1169
1004
  }
1170
1005
  //#endregion
1171
1006
  //#region src/sig/proof.ts
@@ -1179,7 +1014,7 @@ const Temporal = require_http.Temporal;
1179
1014
  * cardinality.
1180
1015
  */
1181
1016
  const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
1182
- const logger = (0, _logtape_logtape.getLogger)([
1017
+ const logger$1 = (0, _logtape_logtape.getLogger)([
1183
1018
  "fedify",
1184
1019
  "sig",
1185
1020
  "proof"
@@ -1319,6 +1154,30 @@ async function signObject(object, privateKey, keyId, options = {}) {
1319
1154
  async function verifyProof(jsonLd, proof, options = {}) {
1320
1155
  return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
1321
1156
  }
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
+ }
1322
1181
  async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
1323
1182
  return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
1324
1183
  const start = performance.now();
@@ -1389,10 +1248,11 @@ async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoa
1389
1248
  async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
1390
1249
  return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
1391
1250
  }
1392
- async function createProofMessageDigests(jsonLd, proofContextLoader, context) {
1251
+ async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
1393
1252
  const msg = { ...jsonLd };
1394
- for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
1395
- 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);
1396
1256
  const encoder = new TextEncoder();
1397
1257
  const digest = async (value) => {
1398
1258
  const bytes = encoder.encode((0, json_canon.default)(value));
@@ -1663,7 +1523,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1663
1523
  try {
1664
1524
  fetchedKey = await publicKeyPromise;
1665
1525
  } catch (error) {
1666
- 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}", {
1667
1527
  proof,
1668
1528
  keyId: proof.verificationMethodId.href,
1669
1529
  error
@@ -1672,7 +1532,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1672
1532
  }
1673
1533
  const publicKey = fetchedKey.key;
1674
1534
  if (publicKey == null) {
1675
- 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}", {
1676
1536
  proof,
1677
1537
  keyId: proof.verificationMethodId.href
1678
1538
  });
@@ -1680,7 +1540,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1680
1540
  }
1681
1541
  if (publicKey.publicKey.algorithm.name !== "Ed25519") {
1682
1542
  if (fetchedKey.cached) {
1683
- 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...", {
1684
1544
  proof,
1685
1545
  keyId: proof.verificationMethodId.href
1686
1546
  });
@@ -1692,7 +1552,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1692
1552
  }
1693
1553
  }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1694
1554
  }
1695
- 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}", {
1696
1556
  proof,
1697
1557
  keyId: proof.verificationMethodId.href
1698
1558
  });
@@ -1709,15 +1569,17 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1709
1569
  const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
1710
1570
  let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
1711
1571
  if (messageDigestsPromise == null) {
1712
- messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context);
1572
+ messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
1713
1573
  messageDigestValues.set(messageDigestKey, messageDigestsPromise);
1714
1574
  }
1715
1575
  const messageDigests = await messageDigestsPromise;
1716
1576
  if (await verifyCandidate(messageDigests.onWire)) return publicKey;
1717
- const normalizedDigest = await messageDigests.normalized();
1718
- 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
+ }
1719
1581
  if (fetchedKey.cached) {
1720
- 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...", {
1721
1583
  keyId: proof.verificationMethodId.href,
1722
1584
  proof
1723
1585
  });
@@ -1729,7 +1591,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1729
1591
  }
1730
1592
  }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1731
1593
  }
1732
- 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}", {
1733
1595
  keyId: proof.verificationMethodId.href,
1734
1596
  proof
1735
1597
  });
@@ -1807,59 +1669,55 @@ async function expandPortableObjectRoot(jsonLd, contextLoader) {
1807
1669
  }
1808
1670
  };
1809
1671
  }
1810
- /**
1811
- * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
1812
- *
1813
- * This applies the FEP-2277 core-type classification to the top-level JSON-LD
1814
- * node. Portable actors, activities, and objects require proofs. A portable
1815
- * collection without a proof is reported separately so a caller can apply a
1816
- * gateway trust policy. Embedded portable objects are not traversed.
1817
- *
1818
- * Every proof must use a DID URL whose DID matches the portable object's
1819
- * authority, and every proof must pass {@link verifyProof}.
1820
- *
1821
- * @param jsonLd The JSON-LD document to verify.
1822
- * @param options Additional options. See also
1823
- * {@link VerifyPortableObjectProofOptions}.
1824
- * @returns The detailed portable proof-policy result.
1825
- * @throws {TypeError} If the input is not a single JSON-LD object or has a
1826
- * malformed portable ID.
1827
- * @since 2.4.0
1828
- */
1829
- async function verifyPortableObjectProof(jsonLd, options = {}) {
1672
+ async function preparePortableObjectProof(jsonLd, options) {
1830
1673
  if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
1831
- verified: false,
1832
- reason: { type: "notPortableObject" }
1674
+ prepared: false,
1675
+ result: {
1676
+ verified: false,
1677
+ reason: { type: "notPortableObject" }
1678
+ }
1833
1679
  };
1834
1680
  const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
1835
1681
  const id = root["@id"];
1836
1682
  if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
1837
- verified: false,
1838
- reason: { type: "notPortableObject" }
1683
+ prepared: false,
1684
+ result: {
1685
+ verified: false,
1686
+ reason: { type: "notPortableObject" }
1687
+ }
1839
1688
  };
1840
1689
  const objectId = (0, _fedify_vocab_runtime.parseIri)(id);
1841
1690
  (0, _fedify_vocab_runtime.getFe34Origin)(objectId);
1842
1691
  const objectType = classifyFep2277CoreType(root);
1843
1692
  if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
1844
- verified: false,
1845
- reason: {
1846
- type: "unsupportedObjectType",
1847
- objectType
1693
+ prepared: false,
1694
+ result: {
1695
+ verified: false,
1696
+ reason: {
1697
+ type: "unsupportedObjectType",
1698
+ objectType
1699
+ }
1848
1700
  }
1849
1701
  };
1850
1702
  const proofValues = root[SECURITY_PROOF];
1851
- if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return objectType === "collection" ? {
1852
- verified: false,
1853
- reason: { type: "unsecuredCollection" }
1854
- } : {
1855
- verified: false,
1856
- reason: { type: "missingProof" }
1857
- };
1858
- if (!Array.isArray(proofValues)) return {
1859
- verified: false,
1860
- reason: {
1861
- type: "invalidProof",
1862
- proofIndex: 0
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
+ }
1712
+ };
1713
+ if (!Array.isArray(proofValues)) return {
1714
+ prepared: false,
1715
+ result: {
1716
+ verified: false,
1717
+ reason: {
1718
+ type: "invalidProof",
1719
+ proofIndex: 0
1720
+ }
1863
1721
  }
1864
1722
  };
1865
1723
  const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
@@ -1867,10 +1725,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1867
1725
  for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
1868
1726
  const proofValue = proofValues[proofIndex];
1869
1727
  if (!hasValidPortableProofShape(proofValue)) return {
1870
- verified: false,
1871
- reason: {
1872
- type: "invalidProof",
1873
- proofIndex
1728
+ prepared: false,
1729
+ result: {
1730
+ verified: false,
1731
+ reason: {
1732
+ type: "invalidProof",
1733
+ proofIndex
1734
+ }
1874
1735
  }
1875
1736
  };
1876
1737
  let proof;
@@ -1878,10 +1739,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1878
1739
  proof = await _fedify_vocab.DataIntegrityProof.fromJsonLd(proofValue, options);
1879
1740
  } catch {
1880
1741
  return {
1881
- verified: false,
1882
- reason: {
1883
- type: "invalidProof",
1884
- proofIndex
1742
+ prepared: false,
1743
+ result: {
1744
+ verified: false,
1745
+ reason: {
1746
+ type: "invalidProof",
1747
+ proofIndex
1748
+ }
1885
1749
  }
1886
1750
  };
1887
1751
  }
@@ -1890,18 +1754,24 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1890
1754
  for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
1891
1755
  const verificationMethod = proofs[proofIndex].verificationMethodId;
1892
1756
  if (verificationMethod == null) return {
1893
- verified: false,
1894
- reason: {
1895
- type: "invalidProof",
1896
- proofIndex
1757
+ prepared: false,
1758
+ result: {
1759
+ verified: false,
1760
+ reason: {
1761
+ type: "invalidProof",
1762
+ proofIndex
1763
+ }
1897
1764
  }
1898
1765
  };
1899
1766
  if (verificationMethod.protocol !== "did:") return {
1900
- verified: false,
1901
- reason: {
1902
- type: "unsupportedVerificationMethod",
1903
- proofIndex,
1904
- verificationMethod
1767
+ prepared: false,
1768
+ result: {
1769
+ verified: false,
1770
+ reason: {
1771
+ type: "unsupportedVerificationMethod",
1772
+ proofIndex,
1773
+ verificationMethod
1774
+ }
1905
1775
  }
1906
1776
  };
1907
1777
  try {
@@ -1909,24 +1779,89 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1909
1779
  } catch (error) {
1910
1780
  if (!(error instanceof TypeError)) throw error;
1911
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: {
1912
1796
  verified: false,
1913
1797
  reason: {
1914
- type: "unsupportedVerificationMethod",
1798
+ type: "verificationMethodMismatch",
1915
1799
  proofIndex,
1800
+ objectId,
1916
1801
  verificationMethod
1917
1802
  }
1918
- };
1919
- }
1920
- if (!(0, _fedify_vocab_runtime.haveSameFe34Origin)(objectId, verificationMethod)) return {
1921
- verified: false,
1922
- reason: {
1923
- type: "verificationMethodMismatch",
1924
- proofIndex,
1925
- objectId,
1926
- verificationMethod
1927
1803
  }
1928
1804
  };
1929
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;
1930
1865
  const keys = [];
1931
1866
  const rawProofCandidatePool = {
1932
1867
  candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
@@ -2045,6 +1980,171 @@ function hasCryptographicOrigin(iri) {
2045
1980
  return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
2046
1981
  }
2047
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
2048
2148
  Object.defineProperty(exports, "InvalidContextReferenceError", {
2049
2149
  enumerable: true,
2050
2150
  get: function() {
@@ -2165,6 +2265,12 @@ Object.defineProperty(exports, "verifyJsonLd", {
2165
2265
  return verifyJsonLd;
2166
2266
  }
2167
2267
  });
2268
+ Object.defineProperty(exports, "verifyMapLocalProof", {
2269
+ enumerable: true,
2270
+ get: function() {
2271
+ return verifyMapLocalProof;
2272
+ }
2273
+ });
2168
2274
  Object.defineProperty(exports, "verifyObject", {
2169
2275
  enumerable: true,
2170
2276
  get: function() {
@@ -2177,6 +2283,12 @@ Object.defineProperty(exports, "verifyPortableObjectProof", {
2177
2283
  return verifyPortableObjectProof;
2178
2284
  }
2179
2285
  });
2286
+ Object.defineProperty(exports, "verifyPortableObjectProofPolicy", {
2287
+ enumerable: true,
2288
+ get: function() {
2289
+ return verifyPortableObjectProofPolicy;
2290
+ }
2291
+ });
2180
2292
  Object.defineProperty(exports, "verifyProof", {
2181
2293
  enumerable: true,
2182
2294
  get: function() {