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