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