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