@fedify/fedify 2.4.0-dev.1964 → 2.4.0-dev.1995
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{builder-B4zpKIFU.mjs → builder-D0DxgOV5.mjs} +2 -2
- package/dist/{client-CtxvmazV.mjs → client-DpnpgjyX.mjs} +78 -4
- package/dist/compat/mod.d.cts +1 -1
- package/dist/compat/mod.d.ts +1 -1
- package/dist/compat/transformers.test.mjs +1 -1
- package/dist/compound-proof-CJnWc6c-.mjs +495 -0
- package/dist/{context-COLwHogJ.d.cts → context-BeDnDuF3.d.cts} +4 -3
- package/dist/{context-DiiCt4S7.d.ts → context-uyRUWoZQ.d.ts} +4 -3
- package/dist/{deno-CtG93ohj.mjs → deno-CABhzCb_.mjs} +1 -1
- package/dist/{docloader-dk_k3S8d.mjs → docloader-BbGSL0Xq.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 +122 -4
- package/dist/federation/idempotency.test.mjs +2 -2
- package/dist/federation/keycache.test.mjs +52 -9
- package/dist/federation/metrics.test.mjs +1 -1
- package/dist/federation/middleware.test.mjs +111 -15
- package/dist/federation/mod.cjs +1 -1
- package/dist/federation/mod.d.cts +2 -2
- package/dist/federation/mod.d.ts +2 -2
- package/dist/federation/mod.js +1 -1
- package/dist/federation/send.test.mjs +139 -4
- 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-Drjlrrax.cjs → federation-DCEHQk4G.cjs} +632 -57
- package/dist/{http-6TI0tI03.d.cts → http-65PYi9jY.d.ts} +34 -2
- package/dist/{http-Dj4s1UQ0.js → http-9WyuldYh.js} +170 -8
- package/dist/{http-CdrSn2ip.d.ts → http-CP-7OdSq.d.cts} +34 -2
- package/dist/{http-B3skRvGo.cjs → http-CRFns-UE.cjs} +181 -7
- package/dist/{http-D7LX-BL9.mjs → http-D9urSO2D.mjs} +3 -3
- package/dist/{key-BVjgbs_9.mjs → key-Ccs8cnd7.mjs} +169 -7
- package/dist/{keycache-ZLqIfrkL.mjs → keycache-BUDHB5rY.mjs} +12 -4
- package/dist/{kv-cache-DtsjH_bY.cjs → kv-cache-DXT9vmIg.cjs} +2 -2
- package/dist/{kv-cache-tGNbvDCF.js → kv-cache-DtmXhPXG.js} +2 -2
- package/dist/{kv-cache-xRcC_xxP.mjs → kv-cache-lKyFn_Dn.mjs} +1 -1
- package/dist/{ld-OuCeQFny.mjs → ld-qup__MAW.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-B9N27cCB.mjs → metrics-CISXCvB1.mjs} +1 -1
- package/dist/{middleware-TeLjzoxn.mjs → middleware-CzvJvPHK.mjs} +58 -15
- package/dist/{middleware-Cd_vPqDH.mjs → middleware-DkrU2WhY.mjs} +1 -1
- package/dist/{middleware-CPTDFMmJ.js → middleware-DsfWajaD.js} +593 -18
- package/dist/{mod-DypxPS9H.d.ts → mod-C0BYc0OU.d.ts} +1 -1
- package/dist/{mod-CnGLNoVw.d.cts → mod-CbKDOnCt.d.cts} +1 -1
- package/dist/{mod-CLHkCwLm.d.cts → mod-CyiSjRkk.d.cts} +1 -1
- package/dist/{mod-CSH1Ee-I.d.ts → mod-D882_Xsg.d.ts} +1 -1
- package/dist/{mod-DzRXACM5.d.ts → mod-UDwMjuHM.d.ts} +1 -1
- package/dist/{mod-BZldCEU0.d.cts → mod-x9W0d0Pk.d.cts} +1 -1
- package/dist/mod.cjs +20 -20
- package/dist/mod.d.cts +6 -6
- package/dist/mod.d.ts +6 -6
- package/dist/mod.js +5 -5
- package/dist/nodeinfo/client.test.mjs +28 -1
- package/dist/nodeinfo/handler.test.mjs +1 -1
- package/dist/nodeinfo/mod.cjs +1 -1
- package/dist/nodeinfo/mod.js +1 -1
- package/dist/{owner-DGSfntI-.d.ts → owner-BF0L9cMt.d.cts} +12 -1
- package/dist/{proof-BO_esQii.js → owner-BIPEZGiU.js} +1255 -1098
- package/dist/{owner-r_waTiQj.d.cts → owner-BSzr5-I8.d.ts} +12 -1
- package/dist/owner-CRoq8Spb.mjs +175 -0
- package/dist/{proof-Dua0d906.cjs → owner-CVA7L9MA.cjs} +1266 -1097
- package/dist/{proof-D5Ajk4DJ.mjs → proof-BDxNVZ3E.mjs} +186 -83
- package/dist/{send-DVXyUqhO.mjs → send-BzM5GLyn.mjs} +68 -11
- 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 +169 -2
- package/dist/sig/ld.test.mjs +55 -2
- package/dist/sig/mod.cjs +17 -17
- package/dist/sig/mod.d.cts +3 -3
- package/dist/sig/mod.d.ts +3 -3
- package/dist/sig/mod.js +2 -2
- package/dist/sig/owner.test.mjs +103 -4
- package/dist/sig/proof.test.mjs +120 -1
- package/dist/{temporal-BoDw51A-.mjs → temporal-Dv6Qv-8k.mjs} +1 -1
- package/dist/testing/kv.test.mjs +1 -1
- package/dist/testing/mod.d.mts +2 -1
- package/dist/{types-RXm5YxpC.cjs → types-Be2zbyeG.cjs} +94 -2
- package/dist/{types-Dtyf8lVj.js → types-C_cNlNVK.js} +78 -4
- package/dist/utils/docloader.test.mjs +27 -3
- package/dist/utils/kv-cache.test.mjs +1 -1
- package/dist/utils/mod.cjs +1 -1
- package/dist/utils/mod.d.cts +1 -1
- package/dist/utils/mod.d.ts +1 -1
- package/dist/utils/mod.js +1 -1
- package/package.json +6 -6
- package/dist/owner-DTEqTzSr.mjs +0 -120
|
@@ -1,1115 +1,1004 @@
|
|
|
1
1
|
import { Temporal } from "temporal-polyfill";
|
|
2
2
|
import { URLPattern } from "urlpattern-polyfill";
|
|
3
|
-
import {
|
|
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-9WyuldYh.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
|
-
|
|
13
|
-
|
|
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
|
|
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$3.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$3.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$3.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$3.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$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
|
|
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$3.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$3.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
|
-
}
|
|
614
|
-
}
|
|
615
|
-
async function hashJsonLd(jsonLd, contextLoader) {
|
|
616
|
-
const canon = await jsonld.canonize(jsonLd, {
|
|
617
|
-
format: "application/n-quads",
|
|
618
|
-
documentLoader: contextLoader ?? getDocumentLoader()
|
|
619
|
-
});
|
|
620
|
-
const encoder = new TextEncoder();
|
|
621
|
-
return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
|
|
486
|
+
};
|
|
622
487
|
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
* @returns Whether the actor is the owner of the key.
|
|
631
|
-
*/
|
|
632
|
-
async function doesActorOwnKey(activity, key, options) {
|
|
633
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.verify_key_ownership", {
|
|
634
|
-
kind: SpanKind.INTERNAL,
|
|
635
|
-
attributes: {
|
|
636
|
-
"activitypub.actor.id": activity.actorId?.href ?? "",
|
|
637
|
-
"activitypub.key.id": key.id?.href ?? ""
|
|
638
|
-
}
|
|
639
|
-
}, async (span) => {
|
|
640
|
-
try {
|
|
641
|
-
if (key.ownerId != null) {
|
|
642
|
-
const owns = key.ownerId.href === activity.actorId?.href;
|
|
643
|
-
span.setAttribute("activitypub.key_ownership.verified", owns);
|
|
644
|
-
span.setAttribute("activitypub.key_ownership.method", "owner_id");
|
|
645
|
-
return owns;
|
|
646
|
-
}
|
|
647
|
-
const actor = await activity.getActor(options);
|
|
648
|
-
if (actor == null || !isActor(actor)) {
|
|
649
|
-
span.setAttribute("activitypub.key_ownership.verified", false);
|
|
650
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
651
|
-
return false;
|
|
652
|
-
}
|
|
653
|
-
for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
|
|
654
|
-
span.setAttribute("activitypub.key_ownership.verified", true);
|
|
655
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
656
|
-
return true;
|
|
657
|
-
}
|
|
658
|
-
span.setAttribute("activitypub.key_ownership.verified", false);
|
|
659
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
660
|
-
return false;
|
|
661
|
-
} catch (error) {
|
|
662
|
-
span.recordException(error);
|
|
663
|
-
span.setStatus({
|
|
664
|
-
code: SpanStatusCode.ERROR,
|
|
665
|
-
message: String(error)
|
|
666
|
-
});
|
|
667
|
-
throw error;
|
|
668
|
-
} finally {
|
|
669
|
-
span.end();
|
|
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);
|
|
670
495
|
}
|
|
496
|
+
return await loader(url, options);
|
|
671
497
|
});
|
|
672
498
|
}
|
|
673
|
-
/**
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
|
|
685
|
-
const documentLoader = options.documentLoader ?? getDocumentLoader();
|
|
686
|
-
const contextLoader = options.contextLoader ?? getDocumentLoader();
|
|
687
|
-
let object;
|
|
688
|
-
if (keyId instanceof CryptographicKey) {
|
|
689
|
-
object = keyId;
|
|
690
|
-
if (object.id == null) return null;
|
|
691
|
-
keyId = object.id;
|
|
692
|
-
} else {
|
|
693
|
-
let keyDoc;
|
|
694
|
-
try {
|
|
695
|
-
const { document } = await documentLoader(keyId.href);
|
|
696
|
-
keyDoc = document;
|
|
697
|
-
} catch (_) {
|
|
698
|
-
return null;
|
|
699
|
-
}
|
|
700
|
-
try {
|
|
701
|
-
object = await Object$1.fromJsonLd(keyDoc, {
|
|
702
|
-
documentLoader,
|
|
703
|
-
contextLoader,
|
|
704
|
-
tracerProvider
|
|
705
|
-
});
|
|
706
|
-
} catch (e) {
|
|
707
|
-
if (!(e instanceof TypeError)) throw e;
|
|
708
|
-
try {
|
|
709
|
-
object = await CryptographicKey.fromJsonLd(keyDoc, {
|
|
710
|
-
documentLoader,
|
|
711
|
-
contextLoader,
|
|
712
|
-
tracerProvider
|
|
713
|
-
});
|
|
714
|
-
} catch (e) {
|
|
715
|
-
if (e instanceof TypeError) return null;
|
|
716
|
-
throw e;
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
let owner = null;
|
|
721
|
-
if (object instanceof CryptographicKey) {
|
|
722
|
-
if (object.ownerId == null) return null;
|
|
723
|
-
owner = await object.getOwner({
|
|
724
|
-
documentLoader,
|
|
725
|
-
contextLoader,
|
|
726
|
-
tracerProvider
|
|
727
|
-
});
|
|
728
|
-
} else if (isActor(object)) owner = object;
|
|
729
|
-
else return null;
|
|
730
|
-
if (owner == null) return null;
|
|
731
|
-
for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
|
|
732
|
-
return null;
|
|
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;
|
|
733
510
|
}
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
* attacker-controlled JSON-LD, so the default fallback must never fetch
|
|
743
|
-
* attacker-supplied context URLs.
|
|
744
|
-
*/
|
|
745
|
-
const preloadedOnlyDocumentLoader = (url) => {
|
|
746
|
-
if (Object.hasOwn(preloadedContexts, url)) return Promise.resolve({
|
|
747
|
-
contextUrl: null,
|
|
748
|
-
documentUrl: url,
|
|
749
|
-
document: preloadedContexts[url]
|
|
750
|
-
});
|
|
751
|
-
return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
|
|
752
|
-
};
|
|
753
|
-
//#endregion
|
|
754
|
-
//#region src/compat/public-audience.ts
|
|
755
|
-
const logger$2 = getLogger([
|
|
756
|
-
"fedify",
|
|
757
|
-
"compat",
|
|
758
|
-
"public-audience"
|
|
759
|
-
]);
|
|
760
|
-
const PUBLIC_ADDRESSING_FIELDS = /* @__PURE__ */ new Set([
|
|
761
|
-
"to",
|
|
762
|
-
"cc",
|
|
763
|
-
"bto",
|
|
764
|
-
"bcc",
|
|
765
|
-
"audience"
|
|
766
|
-
]);
|
|
767
|
-
const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
|
|
768
|
-
const MAX_TRAVERSAL_DEPTH$1 = 64;
|
|
769
|
-
const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(preloadedContexts));
|
|
770
|
-
function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
|
|
771
|
-
if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
|
|
772
|
-
if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
|
|
773
|
-
if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
|
|
774
|
-
if (typeof value !== "object" || value == null) return false;
|
|
775
|
-
const record = value;
|
|
776
|
-
for (const key of Object.keys(record)) {
|
|
777
|
-
if (record.type === "Follow" && key === "object" && (record[key] === "as:Public" || record[key] === "Public")) return true;
|
|
778
|
-
if (key === "@context") continue;
|
|
779
|
-
if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
|
|
780
|
-
}
|
|
781
|
-
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;
|
|
782
519
|
}
|
|
783
|
-
function
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
if (
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
}
|
|
795
|
-
if (typeof value !== "object" || value == null) return value;
|
|
796
|
-
const record = value;
|
|
797
|
-
let changed = false;
|
|
798
|
-
const normalized = Object.create(null);
|
|
799
|
-
for (const key of Object.keys(record)) {
|
|
800
|
-
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);
|
|
801
|
-
if (rewritten !== record[key]) changed = true;
|
|
802
|
-
normalized[key] = rewritten;
|
|
803
|
-
}
|
|
804
|
-
return changed ? normalized : value;
|
|
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
|
+
};
|
|
805
531
|
}
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
function hasNestedContext$1(value, depth = 0) {
|
|
814
|
-
if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
|
|
815
|
-
if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
|
|
816
|
-
if (typeof value !== "object" || value == null) return false;
|
|
817
|
-
const record = value;
|
|
818
|
-
for (const key of Object.keys(record)) {
|
|
819
|
-
if (key === "@context") return true;
|
|
820
|
-
if (hasNestedContext$1(record[key], depth + 1)) return true;
|
|
821
|
-
}
|
|
822
|
-
return false;
|
|
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()
|
|
538
|
+
};
|
|
823
539
|
}
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
if (
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
if (typeof entry !== "string") return false;
|
|
846
|
-
if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
|
|
847
|
-
if (entry === AS_CONTEXT_URL$1) hasAs = true;
|
|
848
|
-
}
|
|
849
|
-
if (!hasAs) return false;
|
|
850
|
-
for (const key of Object.keys(record)) {
|
|
851
|
-
if (key === "@context") continue;
|
|
852
|
-
if (hasNestedContext$1(record[key])) 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
|
+
};
|
|
547
|
+
}
|
|
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;
|
|
553
|
+
}
|
|
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;
|
|
853
561
|
}
|
|
854
|
-
return true;
|
|
855
562
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
* For documents whose `@context` is drawn entirely from Fedify's
|
|
867
|
-
* preloaded context set and includes the ActivityStreams URL, the
|
|
868
|
-
* rewrite is applied directly: the content of every preloaded non-AS
|
|
869
|
-
* context is known not to redefine the `as:` prefix or the bare `Public`
|
|
870
|
-
* term, so the semantics are preserved by construction. Any other
|
|
871
|
-
* shape (an inline object, an unknown external URL, and so on) is
|
|
872
|
-
* treated as potentially unsafe and gated on a JSON-LD equivalence
|
|
873
|
-
* check; both forms are canonicalized with URDNA2015 and the resulting
|
|
874
|
-
* N-Quads are compared. When they differ, the original document is
|
|
875
|
-
* returned unchanged. Canonicalization failures also fall back to the
|
|
876
|
-
* original document.
|
|
877
|
-
*
|
|
878
|
-
* When no `contextLoader` is supplied the helper falls back to an
|
|
879
|
-
* internal loader that resolves only the URLs in Fedify's
|
|
880
|
-
* preloaded-contexts set and rejects every other URL without issuing a
|
|
881
|
-
* network request. That behaviour is deliberately narrower than
|
|
882
|
-
* `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
|
|
883
|
-
* `validatePublicUrl` check will happily fetch non-preloaded URLs: the
|
|
884
|
-
* helper is reached from verification paths (`verifyProof()` /
|
|
885
|
-
* `verifyObject()`) that operate on inbound, potentially adversarial
|
|
886
|
-
* JSON-LD, and a default loader that fetches attacker-supplied
|
|
887
|
-
* `@context` URLs on the caller's behalf would be an SSRF vector.
|
|
888
|
-
* Canonicalization failures against the restricted loader fall back to
|
|
889
|
-
* the original document, same as any other canonicalization error.
|
|
890
|
-
* Callers that genuinely need the remote-fetch loader (for example
|
|
891
|
-
* applications that sign local JSON-LD against a custom vocabulary)
|
|
892
|
-
* should pass a `contextLoader` explicitly.
|
|
893
|
-
*
|
|
894
|
-
* Must be called before any signing step that canonicalizes the
|
|
895
|
-
* compact form byte-for-byte (for example, Object Integrity Proofs
|
|
896
|
-
* using the `eddsa-jcs-2022` cryptosuite), so the signed payload
|
|
897
|
-
* matches what is sent on the wire.
|
|
898
|
-
*/
|
|
899
|
-
async function normalizePublicAudience(jsonLd, contextLoader) {
|
|
900
|
-
if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
|
|
901
|
-
const normalized = rewritePublicAudience(jsonLd);
|
|
902
|
-
if (hasKnownSafeContext$1(jsonLd)) return normalized;
|
|
903
|
-
const loader = contextLoader ?? preloadedOnlyDocumentLoader;
|
|
904
|
-
try {
|
|
905
|
-
const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
|
|
906
|
-
format: "application/n-quads",
|
|
907
|
-
documentLoader: loader
|
|
908
|
-
}), jsonld.canonize(normalized, {
|
|
909
|
-
format: "application/n-quads",
|
|
910
|
-
documentLoader: loader
|
|
911
|
-
})]);
|
|
912
|
-
if (before === after) return normalized;
|
|
913
|
-
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.");
|
|
914
|
-
} catch (error) {
|
|
915
|
-
logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
|
|
563
|
+
function isJsonTypedDefinition(definition) {
|
|
564
|
+
return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
|
|
565
|
+
}
|
|
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);
|
|
916
573
|
}
|
|
917
|
-
return
|
|
574
|
+
return resolveContextTarget(target, state);
|
|
918
575
|
}
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
const
|
|
922
|
-
"fedify",
|
|
923
|
-
"compat",
|
|
924
|
-
"outgoing-jsonld"
|
|
925
|
-
]);
|
|
926
|
-
const ATTACHMENT_FIELDS = /* @__PURE__ */ new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
|
|
927
|
-
const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
|
|
928
|
-
const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
|
|
929
|
-
const MAX_TRAVERSAL_DEPTH = 64;
|
|
930
|
-
function isJsonLdListObject(value) {
|
|
931
|
-
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);
|
|
932
579
|
}
|
|
933
|
-
function
|
|
934
|
-
|
|
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;
|
|
935
583
|
}
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
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;
|
|
942
595
|
}
|
|
943
|
-
if (typeof
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
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);
|
|
953
644
|
}
|
|
645
|
+
refreshGraphAliases(nextState);
|
|
954
646
|
}
|
|
647
|
+
return nextState;
|
|
955
648
|
}
|
|
956
|
-
function
|
|
957
|
-
|
|
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);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
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);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function isJsonLiteralWrapper(value) {
|
|
668
|
+
return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
|
|
958
669
|
}
|
|
959
670
|
/** @internal */
|
|
960
|
-
function
|
|
961
|
-
if (
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
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
|
+
}
|
|
967
680
|
}
|
|
968
|
-
return true;
|
|
969
681
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
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
|
+
};
|
|
975
697
|
}
|
|
976
698
|
/**
|
|
977
|
-
*
|
|
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
|
|
978
708
|
*/
|
|
979
|
-
function
|
|
980
|
-
|
|
981
|
-
if (
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
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)));
|
|
1005
746
|
}
|
|
1006
|
-
|
|
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();
|
|
1007
756
|
}
|
|
1008
|
-
|
|
1009
|
-
}
|
|
1010
|
-
return normalized ?? jsonLd;
|
|
1011
|
-
}
|
|
1012
|
-
function hasNestedContext(value, depth = 0) {
|
|
1013
|
-
if (depth >= MAX_TRAVERSAL_DEPTH) return true;
|
|
1014
|
-
if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
|
|
1015
|
-
if (typeof value !== "object" || value == null) return false;
|
|
1016
|
-
const record = value;
|
|
1017
|
-
for (const key of Object.keys(record)) {
|
|
1018
|
-
if (key === "@context") return true;
|
|
1019
|
-
if (key === "@value" && isJsonLdValueObject(value)) continue;
|
|
1020
|
-
if (hasNestedContext(record[key], depth + 1)) return true;
|
|
1021
|
-
}
|
|
1022
|
-
return false;
|
|
757
|
+
});
|
|
1023
758
|
}
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
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);
|
|
1034
781
|
}
|
|
1035
|
-
|
|
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) {
|
|
1036
789
|
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
if (entries == null || entries.length < 1) return false;
|
|
1042
|
-
let hasActivityStreamsContext = false;
|
|
1043
|
-
for (const entry of entries) {
|
|
1044
|
-
if (typeof entry !== "string") return false;
|
|
1045
|
-
if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
|
|
1046
|
-
if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
|
|
1047
|
-
}
|
|
1048
|
-
if (!hasActivityStreamsContext) return false;
|
|
1049
|
-
for (const key of Object.keys(record)) {
|
|
1050
|
-
if (key === "@context") continue;
|
|
1051
|
-
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";
|
|
1052
794
|
}
|
|
1053
|
-
return
|
|
795
|
+
return false;
|
|
1054
796
|
}
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
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;
|
|
1064
809
|
}
|
|
1065
810
|
/**
|
|
1066
|
-
*
|
|
1067
|
-
* when doing so preserves the JSON-LD semantics.
|
|
1068
|
-
*
|
|
1069
|
-
* JSON-LD compaction collapses single-item arrays into scalar values by
|
|
1070
|
-
* default. Some ActivityPub implementations, Pixelfed among them, parse
|
|
1071
|
-
* `attachment` as a plain JSON array rather than a JSON-LD property and reject
|
|
1072
|
-
* otherwise valid objects whose single attachment is emitted as a scalar.
|
|
811
|
+
* Verifies Linked Data Signatures of the given JSON-LD document.
|
|
1073
812
|
*
|
|
1074
|
-
*
|
|
1075
|
-
*
|
|
1076
|
-
*
|
|
1077
|
-
*
|
|
1078
|
-
* the
|
|
1079
|
-
*
|
|
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
|
|
1080
828
|
*/
|
|
1081
|
-
async function
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
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;
|
|
1087
841
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
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;
|
|
1090
852
|
try {
|
|
1091
|
-
|
|
1092
|
-
format: "application/n-quads",
|
|
1093
|
-
documentLoader: loader
|
|
1094
|
-
}), jsonld.canonize(normalized, {
|
|
1095
|
-
format: "application/n-quads",
|
|
1096
|
-
documentLoader: loader
|
|
1097
|
-
})]);
|
|
1098
|
-
if (before === after) return normalized;
|
|
1099
|
-
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);
|
|
1100
854
|
} catch (error) {
|
|
1101
|
-
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;
|
|
1102
860
|
}
|
|
1103
|
-
|
|
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;
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
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.
|
|
905
|
+
*/
|
|
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
|
+
});
|
|
1104
994
|
}
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
return await normalizeAttachmentArrays(jsonLd, contextLoader);
|
|
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)));
|
|
1113
1002
|
}
|
|
1114
1003
|
//#endregion
|
|
1115
1004
|
//#region src/sig/proof.ts
|
|
@@ -1122,7 +1011,7 @@ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
|
|
|
1122
1011
|
* cardinality.
|
|
1123
1012
|
*/
|
|
1124
1013
|
const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
|
|
1125
|
-
const logger = getLogger([
|
|
1014
|
+
const logger$1 = getLogger([
|
|
1126
1015
|
"fedify",
|
|
1127
1016
|
"sig",
|
|
1128
1017
|
"proof"
|
|
@@ -1262,7 +1151,31 @@ async function signObject(object, privateKey, keyId, options = {}) {
|
|
|
1262
1151
|
async function verifyProof(jsonLd, proof, options = {}) {
|
|
1263
1152
|
return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
|
|
1264
1153
|
}
|
|
1265
|
-
|
|
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
|
+
}
|
|
1178
|
+
async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
|
|
1266
1179
|
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
|
|
1267
1180
|
const start = performance.now();
|
|
1268
1181
|
let verified = false;
|
|
@@ -1274,7 +1187,7 @@ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, message
|
|
|
1274
1187
|
if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
|
|
1275
1188
|
}
|
|
1276
1189
|
try {
|
|
1277
|
-
const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate);
|
|
1190
|
+
const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
|
|
1278
1191
|
if (key == null) span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1279
1192
|
else verified = true;
|
|
1280
1193
|
return key;
|
|
@@ -1332,10 +1245,11 @@ async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoa
|
|
|
1332
1245
|
async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
|
|
1333
1246
|
return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
|
|
1334
1247
|
}
|
|
1335
|
-
async function createProofMessageDigests(jsonLd, proofContextLoader, context) {
|
|
1248
|
+
async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
|
|
1336
1249
|
const msg = { ...jsonLd };
|
|
1337
|
-
|
|
1338
|
-
|
|
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);
|
|
1339
1253
|
const encoder = new TextEncoder();
|
|
1340
1254
|
const digest = async (value) => {
|
|
1341
1255
|
const bytes = encoder.encode(serialize(value));
|
|
@@ -1591,19 +1505,22 @@ async function hasValidProofOptions(proofConfig, options, documentLoader) {
|
|
|
1591
1505
|
if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return false;
|
|
1592
1506
|
return true;
|
|
1593
1507
|
}
|
|
1594
|
-
async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate) {
|
|
1508
|
+
async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
|
|
1595
1509
|
if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
|
|
1596
1510
|
const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
|
|
1597
1511
|
const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
|
|
1598
1512
|
if (proofConfiguration == null || !await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader)) return null;
|
|
1599
|
-
const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey,
|
|
1513
|
+
const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, {
|
|
1514
|
+
...options,
|
|
1515
|
+
keyIdBoundByCaller
|
|
1516
|
+
}));
|
|
1600
1517
|
const proofBytes = new TextEncoder().encode(serialize(proofConfiguration.value));
|
|
1601
1518
|
const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
|
|
1602
1519
|
let fetchedKey;
|
|
1603
1520
|
try {
|
|
1604
1521
|
fetchedKey = await publicKeyPromise;
|
|
1605
1522
|
} catch (error) {
|
|
1606
|
-
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}", {
|
|
1607
1524
|
proof,
|
|
1608
1525
|
keyId: proof.verificationMethodId.href,
|
|
1609
1526
|
error
|
|
@@ -1612,7 +1529,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
|
|
|
1612
1529
|
}
|
|
1613
1530
|
const publicKey = fetchedKey.key;
|
|
1614
1531
|
if (publicKey == null) {
|
|
1615
|
-
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}", {
|
|
1616
1533
|
proof,
|
|
1617
1534
|
keyId: proof.verificationMethodId.href
|
|
1618
1535
|
});
|
|
@@ -1620,7 +1537,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
|
|
|
1620
1537
|
}
|
|
1621
1538
|
if (publicKey.publicKey.algorithm.name !== "Ed25519") {
|
|
1622
1539
|
if (fetchedKey.cached) {
|
|
1623
|
-
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...", {
|
|
1624
1541
|
proof,
|
|
1625
1542
|
keyId: proof.verificationMethodId.href
|
|
1626
1543
|
});
|
|
@@ -1630,9 +1547,9 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
|
|
|
1630
1547
|
get: () => Promise.resolve(void 0),
|
|
1631
1548
|
set: async (keyId, key) => await options.keyCache?.set(keyId, key)
|
|
1632
1549
|
}
|
|
1633
|
-
}, messageDigestCache, rawProofCandidate);
|
|
1550
|
+
}, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
|
|
1634
1551
|
}
|
|
1635
|
-
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}", {
|
|
1636
1553
|
proof,
|
|
1637
1554
|
keyId: proof.verificationMethodId.href
|
|
1638
1555
|
});
|
|
@@ -1649,15 +1566,17 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
|
|
|
1649
1566
|
const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
|
|
1650
1567
|
let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
|
|
1651
1568
|
if (messageDigestsPromise == null) {
|
|
1652
|
-
messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context);
|
|
1569
|
+
messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
|
|
1653
1570
|
messageDigestValues.set(messageDigestKey, messageDigestsPromise);
|
|
1654
1571
|
}
|
|
1655
1572
|
const messageDigests = await messageDigestsPromise;
|
|
1656
1573
|
if (await verifyCandidate(messageDigests.onWire)) return publicKey;
|
|
1657
|
-
|
|
1658
|
-
|
|
1574
|
+
if (messageDigestCache.proofPropertyMode !== "literal") {
|
|
1575
|
+
const normalizedDigest = await messageDigests.normalized();
|
|
1576
|
+
if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
|
|
1577
|
+
}
|
|
1659
1578
|
if (fetchedKey.cached) {
|
|
1660
|
-
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...", {
|
|
1661
1580
|
keyId: proof.verificationMethodId.href,
|
|
1662
1581
|
proof
|
|
1663
1582
|
});
|
|
@@ -1667,9 +1586,9 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
|
|
|
1667
1586
|
get: () => Promise.resolve(void 0),
|
|
1668
1587
|
set: async (keyId, key) => await options.keyCache?.set(keyId, key)
|
|
1669
1588
|
}
|
|
1670
|
-
}, messageDigestCache, rawProofCandidate);
|
|
1589
|
+
}, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
|
|
1671
1590
|
}
|
|
1672
|
-
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}", {
|
|
1673
1592
|
keyId: proof.verificationMethodId.href,
|
|
1674
1593
|
proof
|
|
1675
1594
|
});
|
|
@@ -1747,59 +1666,55 @@ async function expandPortableObjectRoot(jsonLd, contextLoader) {
|
|
|
1747
1666
|
}
|
|
1748
1667
|
};
|
|
1749
1668
|
}
|
|
1750
|
-
|
|
1751
|
-
* Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
|
|
1752
|
-
*
|
|
1753
|
-
* This applies the FEP-2277 core-type classification to the top-level JSON-LD
|
|
1754
|
-
* node. Portable actors, activities, and objects require proofs. A portable
|
|
1755
|
-
* collection without a proof is reported separately so a caller can apply a
|
|
1756
|
-
* gateway trust policy. Embedded portable objects are not traversed.
|
|
1757
|
-
*
|
|
1758
|
-
* Every proof must use a DID URL whose DID matches the portable object's
|
|
1759
|
-
* authority, and every proof must pass {@link verifyProof}.
|
|
1760
|
-
*
|
|
1761
|
-
* @param jsonLd The JSON-LD document to verify.
|
|
1762
|
-
* @param options Additional options. See also
|
|
1763
|
-
* {@link VerifyPortableObjectProofOptions}.
|
|
1764
|
-
* @returns The detailed portable proof-policy result.
|
|
1765
|
-
* @throws {TypeError} If the input is not a single JSON-LD object or has a
|
|
1766
|
-
* malformed portable ID.
|
|
1767
|
-
* @since 2.4.0
|
|
1768
|
-
*/
|
|
1769
|
-
async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
1669
|
+
async function preparePortableObjectProof(jsonLd, options) {
|
|
1770
1670
|
if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !PORTABLE_OBJECT_ID_PATTERN.test(jsonLd["@id"])) return {
|
|
1771
|
-
|
|
1772
|
-
|
|
1671
|
+
prepared: false,
|
|
1672
|
+
result: {
|
|
1673
|
+
verified: false,
|
|
1674
|
+
reason: { type: "notPortableObject" }
|
|
1675
|
+
}
|
|
1773
1676
|
};
|
|
1774
1677
|
const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
|
|
1775
1678
|
const id = root["@id"];
|
|
1776
1679
|
if (typeof id !== "string" || !PORTABLE_OBJECT_ID_PATTERN.test(id)) return {
|
|
1777
|
-
|
|
1778
|
-
|
|
1680
|
+
prepared: false,
|
|
1681
|
+
result: {
|
|
1682
|
+
verified: false,
|
|
1683
|
+
reason: { type: "notPortableObject" }
|
|
1684
|
+
}
|
|
1779
1685
|
};
|
|
1780
1686
|
const objectId = parseIri(id);
|
|
1781
1687
|
getFe34Origin(objectId);
|
|
1782
1688
|
const objectType = classifyFep2277CoreType(root);
|
|
1783
1689
|
if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1690
|
+
prepared: false,
|
|
1691
|
+
result: {
|
|
1692
|
+
verified: false,
|
|
1693
|
+
reason: {
|
|
1694
|
+
type: "unsupportedObjectType",
|
|
1695
|
+
objectType
|
|
1696
|
+
}
|
|
1788
1697
|
}
|
|
1789
1698
|
};
|
|
1790
1699
|
const proofValues = root[SECURITY_PROOF];
|
|
1791
|
-
if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
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
|
+
}
|
|
1797
1709
|
};
|
|
1798
1710
|
if (!Array.isArray(proofValues)) return {
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1711
|
+
prepared: false,
|
|
1712
|
+
result: {
|
|
1713
|
+
verified: false,
|
|
1714
|
+
reason: {
|
|
1715
|
+
type: "invalidProof",
|
|
1716
|
+
proofIndex: 0
|
|
1717
|
+
}
|
|
1803
1718
|
}
|
|
1804
1719
|
};
|
|
1805
1720
|
const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
|
|
@@ -1807,10 +1722,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
|
1807
1722
|
for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
|
|
1808
1723
|
const proofValue = proofValues[proofIndex];
|
|
1809
1724
|
if (!hasValidPortableProofShape(proofValue)) return {
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1725
|
+
prepared: false,
|
|
1726
|
+
result: {
|
|
1727
|
+
verified: false,
|
|
1728
|
+
reason: {
|
|
1729
|
+
type: "invalidProof",
|
|
1730
|
+
proofIndex
|
|
1731
|
+
}
|
|
1814
1732
|
}
|
|
1815
1733
|
};
|
|
1816
1734
|
let proof;
|
|
@@ -1818,10 +1736,13 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
|
1818
1736
|
proof = await DataIntegrityProof.fromJsonLd(proofValue, options);
|
|
1819
1737
|
} catch {
|
|
1820
1738
|
return {
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1739
|
+
prepared: false,
|
|
1740
|
+
result: {
|
|
1741
|
+
verified: false,
|
|
1742
|
+
reason: {
|
|
1743
|
+
type: "invalidProof",
|
|
1744
|
+
proofIndex
|
|
1745
|
+
}
|
|
1825
1746
|
}
|
|
1826
1747
|
};
|
|
1827
1748
|
}
|
|
@@ -1830,18 +1751,24 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
|
1830
1751
|
for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
|
|
1831
1752
|
const verificationMethod = proofs[proofIndex].verificationMethodId;
|
|
1832
1753
|
if (verificationMethod == null) return {
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1754
|
+
prepared: false,
|
|
1755
|
+
result: {
|
|
1756
|
+
verified: false,
|
|
1757
|
+
reason: {
|
|
1758
|
+
type: "invalidProof",
|
|
1759
|
+
proofIndex
|
|
1760
|
+
}
|
|
1837
1761
|
}
|
|
1838
1762
|
};
|
|
1839
1763
|
if (verificationMethod.protocol !== "did:") return {
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1764
|
+
prepared: false,
|
|
1765
|
+
result: {
|
|
1766
|
+
verified: false,
|
|
1767
|
+
reason: {
|
|
1768
|
+
type: "unsupportedVerificationMethod",
|
|
1769
|
+
proofIndex,
|
|
1770
|
+
verificationMethod
|
|
1771
|
+
}
|
|
1845
1772
|
}
|
|
1846
1773
|
};
|
|
1847
1774
|
try {
|
|
@@ -1849,24 +1776,89 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
|
1849
1776
|
} catch (error) {
|
|
1850
1777
|
if (!(error instanceof TypeError)) throw error;
|
|
1851
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: {
|
|
1852
1793
|
verified: false,
|
|
1853
1794
|
reason: {
|
|
1854
|
-
type: "
|
|
1795
|
+
type: "verificationMethodMismatch",
|
|
1855
1796
|
proofIndex,
|
|
1797
|
+
objectId,
|
|
1856
1798
|
verificationMethod
|
|
1857
1799
|
}
|
|
1858
|
-
};
|
|
1859
|
-
}
|
|
1860
|
-
if (!haveSameFe34Origin(objectId, verificationMethod)) return {
|
|
1861
|
-
verified: false,
|
|
1862
|
-
reason: {
|
|
1863
|
-
type: "verificationMethodMismatch",
|
|
1864
|
-
proofIndex,
|
|
1865
|
-
objectId,
|
|
1866
|
-
verificationMethod
|
|
1867
1800
|
}
|
|
1868
1801
|
};
|
|
1869
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;
|
|
1870
1862
|
const keys = [];
|
|
1871
1863
|
const rawProofCandidatePool = {
|
|
1872
1864
|
candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
|
|
@@ -1882,7 +1874,7 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
|
|
|
1882
1874
|
proofIndex
|
|
1883
1875
|
}
|
|
1884
1876
|
};
|
|
1885
|
-
const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate);
|
|
1877
|
+
const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
|
|
1886
1878
|
if (key == null) return {
|
|
1887
1879
|
verified: false,
|
|
1888
1880
|
reason: {
|
|
@@ -1985,4 +1977,169 @@ function hasCryptographicOrigin(iri) {
|
|
|
1985
1977
|
return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
|
|
1986
1978
|
}
|
|
1987
1979
|
//#endregion
|
|
1988
|
-
|
|
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 };
|