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