@fedify/fedify 2.4.0-pr.936.41 → 2.5.0-dev.2271
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/README.md +50 -39
- package/dist/{assert-CJ1KXcvv.mjs → assert-D1Eafmd_.mjs} +1 -1
- package/dist/{assert_equals-BV7oLMxm.mjs → assert_equals-Z6IcEbWU.mjs} +2 -28
- package/dist/assert_exists-cffSpJ7X.mjs +28 -0
- package/dist/assert_false-CPdRnc3E.mjs +23 -0
- package/dist/assert_greater_or_equal-BlafOF4-.mjs +31 -0
- package/dist/{assert_instance_of-Q9KTBnrf.mjs → assert_instance_of-mrXWWNY-.mjs} +1 -1
- package/dist/{assert_not_equals-EPJPoxuf.mjs → assert_not_equals-CpPK2t89.mjs} +2 -1
- package/dist/assert_rejects-CTptdYck.mjs +39 -0
- package/dist/{assert_strict_equals-Ec20AUwa.mjs → assert_strict_equals-CYvBmkpC.mjs} +2 -1
- package/dist/{assert_throws-NiFfqbnH.mjs → assert_throws-BYITOvPO.mjs} +2 -1
- package/dist/assertion_error-B-cx0fFA.mjs +31 -0
- package/dist/audience-CHQ-FlLD.mjs +95 -0
- package/dist/{builder-DonuxRl_.mjs → builder-Bda6LK7A.mjs} +169 -14
- package/dist/{circuit-breaker-CBGyz5F7.mjs → circuit-breaker-XJ53md4S.mjs} +224 -17
- package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +14 -0
- package/dist/{client-CjF5IYQS.mjs → client-CEnNz8O7.mjs} +144 -8
- package/dist/{codec-BBga-FWI.mjs → codec-C6rTrpIp.mjs} +26 -3
- package/dist/{collection-BIhlldqK.mjs → collection-CnnP1UAv.mjs} +1 -1
- package/dist/compat/mod.cjs +1 -1
- package/dist/compat/mod.d.cts +1 -1
- package/dist/compat/mod.d.ts +1 -1
- package/dist/compat/mod.js +1 -1
- package/dist/compat/outgoing-jsonld.test.mjs +71 -3
- package/dist/compat/public-audience.test.mjs +14 -5
- package/dist/compat/secured-document.test.d.mts +2 -0
- package/dist/compat/secured-document.test.mjs +58 -0
- package/dist/compat/transformers.test.mjs +5 -5
- package/dist/compound-proof-B-9mXxFW.mjs +989 -0
- package/dist/{context-Zii1f5xS.d.ts → context-7NyiqIcg.d.ts} +1600 -25
- package/dist/{context-BJXxPElm.mjs → context-8Tu9kea0.mjs} +21 -63
- package/dist/{context-lxX6I7as.d.cts → context-tsYPJ2Ew.d.cts} +1600 -25
- package/dist/{deno-BHzKn9Ig.mjs → deno-oR5aJKpU.mjs} +1 -1
- package/dist/dist-DJQM4u7i.mjs +189 -0
- package/dist/docloader-DBoYbvYW.mjs +87 -0
- package/dist/{esm-yYQfPhIY.mjs → esm-BHXXx4Wx.mjs} +13 -6
- package/dist/federation/audience.test.d.mts +2 -0
- package/dist/federation/audience.test.mjs +130 -0
- package/dist/federation/builder.test.mjs +54 -5
- package/dist/federation/circuit-breaker.test.mjs +838 -7
- package/dist/federation/collection.test.mjs +3 -3
- package/dist/federation/compound-fanout.test.d.mts +2 -0
- package/dist/federation/compound-fanout.test.mjs +228 -0
- package/dist/federation/handler-compound-proof.test.d.mts +2 -0
- package/dist/federation/handler-compound-proof.test.mjs +384 -0
- package/dist/federation/handler.test.mjs +385 -15
- package/dist/federation/hashlink-media.test.d.mts +2 -0
- package/dist/federation/hashlink-media.test.mjs +422 -0
- package/dist/federation/idempotency.test.mjs +6 -6
- package/dist/federation/inbox-report.test.d.mts +2 -0
- package/dist/federation/inbox-report.test.mjs +475 -0
- package/dist/federation/inbox.test.mjs +3 -3
- package/dist/federation/keycache.test.mjs +215 -14
- package/dist/federation/kv.test.mjs +3 -3
- package/dist/federation/metrics.test.mjs +5 -5
- package/dist/federation/middleware.test.mjs +967 -35
- package/dist/federation/mod.cjs +18 -261
- package/dist/federation/mod.d.cts +5 -5
- package/dist/federation/mod.d.ts +5 -5
- package/dist/federation/mod.js +279 -1
- package/dist/federation/mq.test.mjs +123 -47
- package/dist/federation/negotiation.test.mjs +4 -4
- package/dist/federation/outgoing-proof.test.d.mts +2 -0
- package/dist/federation/outgoing-proof.test.mjs +931 -0
- package/dist/federation/portable-actor.test.d.mts +2 -0
- package/dist/federation/portable-actor.test.mjs +496 -0
- package/dist/federation/portable-chain.test.d.mts +2 -0
- package/dist/federation/portable-chain.test.mjs +370 -0
- package/dist/federation/portable-collection.test.d.mts +2 -0
- package/dist/federation/portable-collection.test.mjs +832 -0
- package/dist/federation/portable-delivery.test.d.mts +2 -0
- package/dist/federation/portable-delivery.test.mjs +746 -0
- package/dist/federation/portable-gateway-keys.test.d.mts +2 -0
- package/dist/federation/portable-gateway-keys.test.mjs +686 -0
- package/dist/federation/portable-inbox.test.d.mts +2 -0
- package/dist/federation/portable-inbox.test.mjs +1535 -0
- package/dist/federation/portable-parse-uri.test.d.mts +2 -0
- package/dist/federation/portable-parse-uri.test.mjs +348 -0
- package/dist/federation/portable-route-activity.test.d.mts +2 -0
- package/dist/federation/portable-route-activity.test.mjs +259 -0
- package/dist/federation/portable.test.d.mts +2 -0
- package/dist/federation/portable.test.mjs +1072 -0
- package/dist/federation/retry.test.mjs +4 -3
- package/dist/federation/router.test.mjs +9 -159
- package/dist/federation/send.test.mjs +245 -27
- package/dist/federation/tasks/codec.test.mjs +4 -4
- package/dist/federation/tasks/enqueue.test.mjs +42 -4
- package/dist/federation/tasks/tasks.test.mjs +7 -6
- package/dist/federation/temporal.test.mjs +4 -4
- package/dist/federation/webfinger.test.mjs +275 -12
- package/dist/{middleware-FrSMAYEx.cjs → federation-CkZiAcWY.cjs} +8640 -3722
- package/dist/http-B5JT115n.cjs +10630 -0
- package/dist/http-DydWCB7R.js +6527 -0
- package/dist/{http-CPVMUgsW.mjs → http-siciWkmx.mjs} +397 -168
- package/dist/key-BspPiXqn.mjs +951 -0
- package/dist/key-C1nv7_jD.d.ts +1125 -0
- package/dist/key-DYxuyd-s.d.cts +1125 -0
- package/dist/key-owner-evidence-APB6NpSk.mjs +108 -0
- package/dist/keycache-Da8A8mZa.mjs +200 -0
- package/dist/{kv-D6hNiMTK.d.ts → kv-B2mzK5tl.d.cts} +3 -2
- package/dist/{kv-gJ8LYbxX.d.cts → kv-B2mzK5tl.d.ts} +3 -2
- package/dist/kv-DBRWVx3Q.mjs +104 -0
- package/dist/{kv-cache-KyGqJqSp.mjs → kv-cache-BF1hnW65.mjs} +1 -1
- package/dist/{kv-cache-5bnX3-Jq.js → kv-cache-CTQr1tbn.js} +54 -16
- package/dist/{kv-cache-DQ29C4XL.cjs → kv-cache-DCac1nEU.cjs} +55 -19
- package/dist/{ld-Cj9F_5AP.mjs → ld-CzaP-hJl.mjs} +44 -12
- package/dist/map-local-context-conflict-DOYEEJ3u.mjs +204 -0
- package/dist/map-local-create-note-B0SeXJms.mjs +214 -0
- package/dist/{metrics-DMk-nTxI.mjs → metrics-CYg9yxBL.mjs} +3 -2
- package/dist/metrics-DVKYY6K1.d.cts +36 -0
- package/dist/metrics-DoRtI0qU.d.ts +36 -0
- package/dist/{middleware-Y-kpsp6S.js → middleware-CsDDXKuL.js} +5493 -1103
- package/dist/{middleware-CvwTUgnP.mjs → middleware-D7_LO-Vs.mjs} +3157 -272
- package/dist/{middleware-CEctxBN6.mjs → middleware-DWjrfpcz.mjs} +1 -1
- package/dist/{mod-gOlPDuT8.d.cts → mod-BojP2Bw3.d.cts} +1 -1
- package/dist/mod-CavhAgLw.d.cts +320 -0
- package/dist/mod-CtpF2BU5.d.ts +320 -0
- package/dist/{mod-BtEaIEcD.d.cts → mod-DEZXwV6J.d.ts} +10 -4
- package/dist/{mod-UMmveiO0.d.ts → mod-Dw-nPxQh.d.cts} +10 -4
- package/dist/{mod-DLc2Ot6f.d.ts → mod-Xj5P4s4d.d.ts} +1 -1
- package/dist/mod.cjs +40 -39
- package/dist/mod.d.cts +10 -11
- package/dist/mod.d.ts +10 -11
- package/dist/mod.js +9 -9
- package/dist/{mq-llHKivST.mjs → mq-Dm1Wmtm-.mjs} +6 -0
- package/dist/nodeinfo/client.test.mjs +139 -4
- package/dist/nodeinfo/handler.test.mjs +5 -5
- 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 +4 -4
- package/dist/otel/exporter.test.mjs +3 -3
- package/dist/otel/mod.cjs +0 -1
- package/dist/otel/mod.d.cts +1 -1
- package/dist/otel/mod.d.ts +1 -1
- package/dist/{outgoing-jsonld-URuqsICz.mjs → outgoing-jsonld-4IJqPYos.mjs} +12 -10
- package/dist/{owner-DEvZuyOE.d.cts → owner-BF0L9cMt.d.cts} +11 -0
- package/dist/{owner-CnngXDNJ.d.ts → owner-BSzr5-I8.d.ts} +11 -0
- package/dist/owner-DYgfTFHy.mjs +267 -0
- package/dist/portable-collection-BpsVsRov.js +670 -0
- package/dist/portable-collection-C74P1vtC.mjs +418 -0
- package/dist/portable-collection-DZd2bm7M.cjs +686 -0
- package/dist/portable-key-BIMLrAP4.mjs +549 -0
- package/dist/portable-key-id-Ca30-hOa.mjs +248 -0
- package/dist/proof-Dxy6ByqI.mjs +1299 -0
- package/dist/{public-audience-Cr5MsnMq.mjs → public-audience--klBIOk1.mjs} +15 -10
- package/dist/router-u5O5KCQr.mjs +156 -0
- package/dist/runtime/mod.cjs +1 -1
- package/dist/runtime/mod.js +1 -1
- package/dist/secured-document-CxzZZ9nL.mjs +35 -0
- package/dist/send-C4dDpAxm.mjs +495 -0
- package/dist/sig/accept.test.mjs +1 -1
- package/dist/sig/compound-proof-discovery.test.d.mts +2 -0
- package/dist/sig/compound-proof-discovery.test.mjs +331 -0
- package/dist/sig/compound-proof-producer.test.d.mts +2 -0
- package/dist/sig/compound-proof-producer.test.mjs +107 -0
- package/dist/sig/compound-proof-verification.test.d.mts +2 -0
- package/dist/sig/compound-proof-verification.test.mjs +833 -0
- package/dist/sig/compound-proof.test.d.mts +2 -0
- package/dist/sig/compound-proof.test.mjs +411 -0
- package/dist/sig/http.test.mjs +702 -31
- package/dist/sig/key-owner-evidence.test.d.mts +2 -0
- package/dist/sig/key-owner-evidence.test.mjs +100 -0
- package/dist/sig/key.test.mjs +220 -8
- package/dist/sig/ld.test.mjs +65 -7
- package/dist/sig/mitra-receive-interop.test.d.mts +2 -0
- package/dist/sig/mitra-receive-interop.test.mjs +260 -0
- package/dist/sig/mitra-send-interop.test.d.mts +2 -0
- package/dist/sig/mitra-send-interop.test.mjs +461 -0
- package/dist/sig/mod.cjs +18 -16
- package/dist/sig/mod.d.cts +4 -4
- package/dist/sig/mod.d.ts +4 -4
- package/dist/sig/mod.js +3 -3
- package/dist/sig/owner.test.mjs +108 -9
- package/dist/sig/portable-collection.test.d.mts +2 -0
- package/dist/sig/portable-collection.test.mjs +697 -0
- package/dist/sig/portable-interop.test.d.mts +2 -0
- package/dist/sig/portable-interop.test.mjs +156 -0
- package/dist/sig/portable-key-id.test.d.mts +2 -0
- package/dist/sig/portable-key-id.test.mjs +67 -0
- package/dist/sig/portable-key.test.d.mts +2 -0
- package/dist/sig/portable-key.test.mjs +1439 -0
- package/dist/sig/proof.test.mjs +1753 -16
- package/dist/sig/tootik-request-interop.test.d.mts +2 -0
- package/dist/sig/tootik-request-interop.test.mjs +190 -0
- package/dist/sig/tootik-send-interop.test.d.mts +2 -0
- package/dist/sig/tootik-send-interop.test.mjs +331 -0
- package/dist/sig/verification.test.d.mts +2 -0
- package/dist/sig/verification.test.mjs +310 -0
- package/dist/std__assert-DvMDRPes.mjs +8 -0
- package/dist/{testing-CO7ftO8A.mjs → tasks-IG3pHfvZ.mjs} +2 -2
- package/dist/{temporal-fsXO5IvD.mjs → temporal-D0KJI4NF.mjs} +3 -3
- package/dist/testing/context.test.d.mts +2 -0
- package/dist/testing/context.test.mjs +19 -0
- package/dist/testing/kv.test.d.mts +2 -0
- package/dist/testing/kv.test.mjs +101 -0
- package/dist/testing/mod.d.mts +1617 -48
- package/dist/testing/mod.mjs +6 -3
- package/dist/testing-t8xDeJZ5.mjs +8 -0
- package/dist/{transformers-DGwl-hD1.cjs → transformers-BalCrSsr.cjs} +0 -1
- package/dist/{types-DC1pNgJA.js → types-_S2_MeLF.js} +144 -8
- package/dist/{types-CPym83zc.cjs → types-poIao40f.cjs} +160 -7
- package/dist/utils/docloader.test.mjs +530 -8
- package/dist/utils/kv-cache.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/dist/verification-C3954hQh.mjs +5 -0
- package/dist/verification-Dpfcw8ml.mjs +105 -0
- package/dist/vocab/cjs.test.mjs +1 -1
- package/package.json +8 -8
- package/dist/assert_rejects-EgstcQy5.mjs +0 -82
- package/dist/docloader-e1khNUKy.mjs +0 -49
- package/dist/http-CsmQ-BQ4.js +0 -2483
- package/dist/http-VyDTd4G3.d.cts +0 -553
- package/dist/http-hlIjmewS.cjs +0 -2694
- package/dist/http-lf8Hsd91.d.ts +0 -553
- package/dist/key-DfPsX8hv.mjs +0 -453
- package/dist/keycache-_DHqz5z_.mjs +0 -97
- package/dist/metrics-CoUJLQhZ.d.cts +0 -276
- package/dist/metrics-Dc4jR-IC.d.ts +0 -276
- package/dist/mod-B0hW12_O.d.cts +0 -307
- package/dist/mod-COIAjwRS.d.ts +0 -307
- package/dist/owner-Br9YYzn_.mjs +0 -120
- package/dist/proof-B4ngoaNQ.mjs +0 -316
- package/dist/proof-B6E0XUXJ.js +0 -1415
- package/dist/proof-NN4xCQGL.cjs +0 -1562
- package/dist/send-CxHKUNzv.mjs +0 -239
- package/dist/std__assert-B2NnY9bq.mjs +0 -79
- package/dist/temporal-polyfill-BCdTHexd.cjs +0 -3565
- /package/dist/{accept-8PiolDP7.mjs → accept-CPVqki78.mjs} +0 -0
- /package/dist/{activity-listener-BtTSxZWA.mjs → activity-listener-C-BSbKI7.mjs} +0 -0
- /package/dist/{client-CAM_bQXx.d.cts → client-D-XP_Ccb.d.cts} +0 -0
- /package/dist/{client-CSddvgWN.d.ts → client-D-XP_Ccb.d.ts} +0 -0
- /package/dist/{keys-Dbyd7bhl.mjs → keys-DIJNHW-Y.mjs} +0 -0
- /package/dist/{kv-CXBAok3k.mjs → kv-DCHkaJ9-.mjs} +0 -0
- /package/dist/{negotiation-RuwrPFqi.mjs → negotiation-CCocWT_N.mjs} +0 -0
- /package/dist/{retry-DgFqeS5k.mjs → retry-zX5xw5e0.mjs} +0 -0
- /package/dist/{chunk-D5IdezsZ.js → rolldown-runtime-BC-Eo5Mj.js} +0 -0
- /package/dist/{chunk-Czpeue4M.cjs → rolldown-runtime-Dmm3t92W.cjs} +0 -0
- /package/dist/{transformers-DXze6FUB.js → transformers-DAtXl_Kc.js} +0 -0
- /package/dist/{types-CrtdVuDP.mjs → types-DE_LV1JB.mjs} +0 -0
package/dist/proof-B6E0XUXJ.js
DELETED
|
@@ -1,1415 +0,0 @@
|
|
|
1
|
-
import { Temporal } from "temporal-polyfill";
|
|
2
|
-
import { URLPattern } from "urlpattern-polyfill";
|
|
3
|
-
import { F as version, P as name, _ as measureSignatureKeyFetch, d as validateCryptoKey, f as getDurationMs, p as getFederationMetrics, s as fetchKey } from "./http-CsmQ-BQ4.js";
|
|
4
|
-
import { getLogger } from "@logtape/logtape";
|
|
5
|
-
import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, PUBLIC_COLLECTION, getTypeId, isActor } from "@fedify/vocab";
|
|
6
|
-
import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
7
|
-
import { encodeHex } from "byte-encodings/hex";
|
|
8
|
-
import { getDocumentLoader, haveSameFe34Origin, preloadedContexts } from "@fedify/vocab-runtime";
|
|
9
|
-
import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
|
|
10
|
-
import jsonld from "@fedify/vocab-runtime/jsonld";
|
|
11
|
-
import serialize from "json-canon";
|
|
12
|
-
//#region src/sig/ld.ts
|
|
13
|
-
const logger$3 = getLogger([
|
|
14
|
-
"fedify",
|
|
15
|
-
"sig",
|
|
16
|
-
"ld"
|
|
17
|
-
]);
|
|
18
|
-
const localContext = [
|
|
19
|
-
"https://w3id.org/identity/v1",
|
|
20
|
-
"https://www.w3.org/ns/activitystreams",
|
|
21
|
-
"https://w3id.org/security/v1",
|
|
22
|
-
"https://w3id.org/security/data-integrity/v1"
|
|
23
|
-
];
|
|
24
|
-
const localContextUrls = new Set(localContext);
|
|
25
|
-
const builtInContextLoader = getDocumentLoader();
|
|
26
|
-
const disallowedJsonLdKeywords = new Set([
|
|
27
|
-
"@graph",
|
|
28
|
-
"@included",
|
|
29
|
-
"@reverse"
|
|
30
|
-
]);
|
|
31
|
-
/** @internal */
|
|
32
|
-
var UnsafeJsonLdError = class extends TypeError {
|
|
33
|
-
keyword;
|
|
34
|
-
constructor(keyword) {
|
|
35
|
-
super(`Unsupported JSON-LD keyword: ${keyword}.`);
|
|
36
|
-
this.keyword = keyword;
|
|
37
|
-
this.name = "UnsafeJsonLdError";
|
|
38
|
-
}
|
|
39
|
-
};
|
|
40
|
-
/** @internal */
|
|
41
|
-
var InvalidContextReferenceError = class extends TypeError {
|
|
42
|
-
reference;
|
|
43
|
-
constructor(reference) {
|
|
44
|
-
super(`Invalid JSON-LD context reference: ${reference}.`);
|
|
45
|
-
this.reference = reference;
|
|
46
|
-
this.name = "InvalidContextReferenceError";
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
function createLoadingRemoteContextFailedError(reference, cause) {
|
|
50
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
51
|
-
const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
|
|
52
|
-
error.name = "jsonld.InvalidUrl";
|
|
53
|
-
error.details = {
|
|
54
|
-
code: "loading remote context failed",
|
|
55
|
-
url: reference
|
|
56
|
-
};
|
|
57
|
-
error.cause = cause;
|
|
58
|
-
return error;
|
|
59
|
-
}
|
|
60
|
-
/** @internal */
|
|
61
|
-
function isClearlyMalformedContextReference(reference) {
|
|
62
|
-
for (const char of reference) {
|
|
63
|
-
const code = char.charCodeAt(0);
|
|
64
|
-
if (code <= 32 || code === 127) return true;
|
|
65
|
-
}
|
|
66
|
-
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
|
|
67
|
-
for (let i = 0; i < reference.length; i++) {
|
|
68
|
-
if (reference[i] !== "%") continue;
|
|
69
|
-
if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
|
|
70
|
-
i += 2;
|
|
71
|
-
}
|
|
72
|
-
if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
|
|
73
|
-
for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
|
|
74
|
-
}
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
function cloneRemoteDocument(remoteDocument) {
|
|
78
|
-
return structuredClone(remoteDocument);
|
|
79
|
-
}
|
|
80
|
-
function createMemoizedDocumentLoader(documentLoader) {
|
|
81
|
-
const cache = /* @__PURE__ */ new Map();
|
|
82
|
-
return async (url, options) => {
|
|
83
|
-
const cacheKey = URL.canParse(url) ? new URL(url).href : url;
|
|
84
|
-
let remoteDocument = cache.get(cacheKey);
|
|
85
|
-
if (remoteDocument == null) {
|
|
86
|
-
remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
|
|
87
|
-
remoteDocument.catch(() => {
|
|
88
|
-
if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
|
|
89
|
-
});
|
|
90
|
-
cache.set(cacheKey, remoteDocument);
|
|
91
|
-
}
|
|
92
|
-
return cloneRemoteDocument(await remoteDocument);
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
/** @internal */
|
|
96
|
-
function wrapContextLoaderForJsonLd(contextLoader) {
|
|
97
|
-
const loader = contextLoader ?? builtInContextLoader;
|
|
98
|
-
return async (url, options) => {
|
|
99
|
-
try {
|
|
100
|
-
return await loader(url, options);
|
|
101
|
-
} catch (error) {
|
|
102
|
-
if (!isInvalidUrlTypeError(error)) throw error;
|
|
103
|
-
if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
|
|
104
|
-
throw createLoadingRemoteContextFailedError(url, error);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
/** @internal */
|
|
109
|
-
function getNormalizationContextLoader(contextLoader) {
|
|
110
|
-
const loader = wrapContextLoaderForJsonLd(contextLoader);
|
|
111
|
-
return createMemoizedDocumentLoader(async (url, options) => {
|
|
112
|
-
if (URL.canParse(url)) {
|
|
113
|
-
const normalizedUrl = new URL(url).href;
|
|
114
|
-
if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
|
|
115
|
-
}
|
|
116
|
-
return await loader(url, options);
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
/** @internal */
|
|
120
|
-
async function compactJsonLd(jsonLd, contextLoader) {
|
|
121
|
-
const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
|
|
122
|
-
const signature = hasLds ? jsonLd.signature : void 0;
|
|
123
|
-
const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
|
|
124
|
-
const document = hasLds ? detachSignature(jsonLd) : jsonLd;
|
|
125
|
-
await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
|
|
126
|
-
const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
|
|
127
|
-
if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
|
|
128
|
-
assertSafeJsonLd(compacted);
|
|
129
|
-
return compacted;
|
|
130
|
-
}
|
|
131
|
-
function createInvalidRemoteContextError(reference) {
|
|
132
|
-
const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${reference}".`);
|
|
133
|
-
error.name = "jsonld.InvalidUrl";
|
|
134
|
-
error.details = {
|
|
135
|
-
code: "invalid remote context",
|
|
136
|
-
url: reference
|
|
137
|
-
};
|
|
138
|
-
return error;
|
|
139
|
-
}
|
|
140
|
-
function getRemoteContext(remoteDocument, reference) {
|
|
141
|
-
const { contextUrl, documentUrl } = remoteDocument;
|
|
142
|
-
let { document } = remoteDocument;
|
|
143
|
-
if (typeof document === "string") document = JSON.parse(document);
|
|
144
|
-
if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
|
|
145
|
-
let context = "@context" in document ? document["@context"] : {};
|
|
146
|
-
if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
|
|
147
|
-
return {
|
|
148
|
-
context,
|
|
149
|
-
baseUrl: documentUrl ?? reference
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
function createGraphAliasContextState() {
|
|
153
|
-
return {
|
|
154
|
-
graphTerms: /* @__PURE__ */ new Set(),
|
|
155
|
-
jsonTerms: /* @__PURE__ */ new Set(),
|
|
156
|
-
propertyContexts: /* @__PURE__ */ new Map(),
|
|
157
|
-
termTargets: /* @__PURE__ */ new Map()
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
function cloneGraphAliasContextState(state) {
|
|
161
|
-
return {
|
|
162
|
-
graphTerms: new Set(state.graphTerms),
|
|
163
|
-
jsonTerms: new Set(state.jsonTerms),
|
|
164
|
-
propertyContexts: new Map(state.propertyContexts),
|
|
165
|
-
termTargets: new Map(state.termTargets)
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
function resolveContextTarget(target, state) {
|
|
169
|
-
if (target === "@graph") return target;
|
|
170
|
-
const mapped = state.termTargets.get(target);
|
|
171
|
-
if (mapped == null) return target;
|
|
172
|
-
return mapped;
|
|
173
|
-
}
|
|
174
|
-
function getDirectContextTarget(definition) {
|
|
175
|
-
if (definition === null) return null;
|
|
176
|
-
if (typeof definition === "string") return definition;
|
|
177
|
-
if (typeof definition === "object" && definition != null && "@id" in definition) {
|
|
178
|
-
const id = definition["@id"];
|
|
179
|
-
if (id === null) return null;
|
|
180
|
-
if (typeof id === "string") return id;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
function isJsonTypedDefinition(definition) {
|
|
184
|
-
return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
|
|
185
|
-
}
|
|
186
|
-
function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
|
|
187
|
-
if (target === "@graph") return target;
|
|
188
|
-
if (seen.has(target)) return target;
|
|
189
|
-
seen.add(target);
|
|
190
|
-
if (localTargets.has(target)) {
|
|
191
|
-
const localTarget = localTargets.get(target);
|
|
192
|
-
return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
|
|
193
|
-
}
|
|
194
|
-
return resolveContextTarget(target, state);
|
|
195
|
-
}
|
|
196
|
-
function refreshGraphAliases(state) {
|
|
197
|
-
state.graphTerms.clear();
|
|
198
|
-
for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
|
|
199
|
-
}
|
|
200
|
-
function normalizeContextReference(reference, baseUrl) {
|
|
201
|
-
if (baseUrl != null) return new URL(reference, baseUrl).href;
|
|
202
|
-
return URL.canParse(reference) ? new URL(reference).href : reference;
|
|
203
|
-
}
|
|
204
|
-
/** @internal */
|
|
205
|
-
function isInvalidUrlTypeError(error) {
|
|
206
|
-
const code = error.code;
|
|
207
|
-
return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
|
|
208
|
-
}
|
|
209
|
-
async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
|
|
210
|
-
if (context === null) return createGraphAliasContextState();
|
|
211
|
-
let nextState = cloneGraphAliasContextState(state);
|
|
212
|
-
if (Array.isArray(context)) {
|
|
213
|
-
for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
|
|
214
|
-
return nextState;
|
|
215
|
-
}
|
|
216
|
-
if (typeof context === "string") {
|
|
217
|
-
const reference = normalizeContextReference(context, baseUrl);
|
|
218
|
-
const cacheKey = `${baseUrl ?? ""}\n${reference}`;
|
|
219
|
-
if (processingContexts.has(cacheKey)) return nextState;
|
|
220
|
-
processingContexts.add(cacheKey);
|
|
221
|
-
try {
|
|
222
|
-
let remoteContext = remoteContextCache.get(cacheKey);
|
|
223
|
-
if (remoteContext == null) {
|
|
224
|
-
remoteContext = (async () => {
|
|
225
|
-
try {
|
|
226
|
-
return getRemoteContext(await documentLoader(reference), reference);
|
|
227
|
-
} catch (error) {
|
|
228
|
-
if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
|
|
229
|
-
throw error;
|
|
230
|
-
}
|
|
231
|
-
})();
|
|
232
|
-
remoteContextCache.set(cacheKey, remoteContext);
|
|
233
|
-
}
|
|
234
|
-
const loadedRemoteContext = await remoteContext;
|
|
235
|
-
return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
|
|
236
|
-
} finally {
|
|
237
|
-
processingContexts.delete(cacheKey);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
if (typeof context === "object" && context != null) {
|
|
241
|
-
if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
|
|
242
|
-
const localTargets = /* @__PURE__ */ new Map();
|
|
243
|
-
for (const [term, definition] of globalThis.Object.entries(context)) {
|
|
244
|
-
if (term.startsWith("@")) continue;
|
|
245
|
-
const target = getDirectContextTarget(definition);
|
|
246
|
-
if (target == null) localTargets.set(term, null);
|
|
247
|
-
else if (typeof target === "string") localTargets.set(term, target);
|
|
248
|
-
else localTargets.delete(term);
|
|
249
|
-
}
|
|
250
|
-
for (const [term, definition] of globalThis.Object.entries(context)) {
|
|
251
|
-
if (term.startsWith("@")) continue;
|
|
252
|
-
if (localTargets.has(term)) {
|
|
253
|
-
const directTarget = localTargets.get(term);
|
|
254
|
-
if (directTarget == null) nextState.termTargets.set(term, null);
|
|
255
|
-
else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
|
|
256
|
-
} else nextState.termTargets.delete(term);
|
|
257
|
-
if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
|
|
258
|
-
context: definition["@context"],
|
|
259
|
-
baseUrl
|
|
260
|
-
});
|
|
261
|
-
else nextState.propertyContexts.delete(term);
|
|
262
|
-
if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
|
|
263
|
-
else nextState.jsonTerms.delete(term);
|
|
264
|
-
}
|
|
265
|
-
refreshGraphAliases(nextState);
|
|
266
|
-
}
|
|
267
|
-
return nextState;
|
|
268
|
-
}
|
|
269
|
-
async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
|
|
270
|
-
if (Array.isArray(jsonLd)) {
|
|
271
|
-
for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
|
|
272
|
-
return;
|
|
273
|
-
}
|
|
274
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return;
|
|
275
|
-
const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
|
|
276
|
-
let state = inheritedState;
|
|
277
|
-
if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
|
|
278
|
-
if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
|
|
279
|
-
for (const [key, value] of globalThis.Object.entries(jsonLd)) {
|
|
280
|
-
if (key === "@context") continue;
|
|
281
|
-
if (jsonLiteralWrapper && key === "@value") continue;
|
|
282
|
-
if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
|
|
283
|
-
if (state.jsonTerms.has(key)) continue;
|
|
284
|
-
await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
function isJsonLiteralWrapper(value) {
|
|
288
|
-
return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
|
|
289
|
-
}
|
|
290
|
-
/** @internal */
|
|
291
|
-
function assertSafeJsonLd(jsonLd) {
|
|
292
|
-
if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
|
|
293
|
-
else if (typeof jsonLd === "object" && jsonLd != null) {
|
|
294
|
-
const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
|
|
295
|
-
for (const [key, value] of globalThis.Object.entries(jsonLd)) {
|
|
296
|
-
if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
|
|
297
|
-
if (jsonLiteralWrapper && key === "@value") continue;
|
|
298
|
-
assertSafeJsonLd(value);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* Attaches a LD signature to the given JSON-LD document.
|
|
304
|
-
* @param jsonLd The JSON-LD document to attach the signature to. It is not
|
|
305
|
-
* modified.
|
|
306
|
-
* @param signature The signature to attach.
|
|
307
|
-
* @returns The JSON-LD document with the attached signature.
|
|
308
|
-
* @throws {TypeError} If the input document is not a valid JSON-LD document.
|
|
309
|
-
* @since 1.0.0
|
|
310
|
-
*/
|
|
311
|
-
function attachSignature(jsonLd, signature) {
|
|
312
|
-
if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
|
|
313
|
-
return {
|
|
314
|
-
...jsonLd,
|
|
315
|
-
signature
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* Creates a LD signature for the given JSON-LD document.
|
|
320
|
-
* @param jsonLd The JSON-LD document to sign.
|
|
321
|
-
* @param privateKey The private key to sign the document.
|
|
322
|
-
* @param keyId The ID of the public key that corresponds to the private key.
|
|
323
|
-
* @param options Additional options for creating the signature.
|
|
324
|
-
* See also {@link CreateSignatureOptions}.
|
|
325
|
-
* @return The created signature.
|
|
326
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
327
|
-
* @since 1.0.0
|
|
328
|
-
*/
|
|
329
|
-
async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
|
|
330
|
-
validateCryptoKey(privateKey, "private");
|
|
331
|
-
if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
|
|
332
|
-
const options = {
|
|
333
|
-
"@context": "https://w3id.org/identity/v1",
|
|
334
|
-
creator: keyId.href,
|
|
335
|
-
created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
336
|
-
};
|
|
337
|
-
const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
|
|
338
|
-
const messageBytes = new TextEncoder().encode(message);
|
|
339
|
-
const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
|
|
340
|
-
return {
|
|
341
|
-
...options,
|
|
342
|
-
type: "RsaSignature2017",
|
|
343
|
-
signatureValue: encodeBase64(signature)
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* Signs the given JSON-LD document with the private key and returns the signed
|
|
348
|
-
* JSON-LD document.
|
|
349
|
-
* @param jsonLd The JSON-LD document to sign.
|
|
350
|
-
* @param privateKey The private key to sign the document.
|
|
351
|
-
* @param keyId The key ID to use in the signature. It will be used by the
|
|
352
|
-
* verifier to fetch the corresponding public key.
|
|
353
|
-
* @param options Additional options for signing the document.
|
|
354
|
-
* See also {@link SignJsonLdOptions}.
|
|
355
|
-
* @returns The signed JSON-LD document.
|
|
356
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
357
|
-
* @since 1.0.0
|
|
358
|
-
*/
|
|
359
|
-
async function signJsonLd(jsonLd, privateKey, keyId, options) {
|
|
360
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
|
|
361
|
-
try {
|
|
362
|
-
const signature = await createSignature(jsonLd, privateKey, keyId, options);
|
|
363
|
-
if (span.isRecording()) {
|
|
364
|
-
span.setAttribute("ld_signatures.type", signature.type);
|
|
365
|
-
span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
|
|
366
|
-
}
|
|
367
|
-
return attachSignature(jsonLd, signature);
|
|
368
|
-
} catch (error) {
|
|
369
|
-
span.setStatus({
|
|
370
|
-
code: SpanStatusCode.ERROR,
|
|
371
|
-
message: String(error)
|
|
372
|
-
});
|
|
373
|
-
throw error;
|
|
374
|
-
} finally {
|
|
375
|
-
span.end();
|
|
376
|
-
}
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Checks if the given JSON-LD document has a Linked Data Signature-like
|
|
381
|
-
* object, without restricting it to a single suite-specific shape.
|
|
382
|
-
* @param jsonLd The JSON-LD document to check.
|
|
383
|
-
* @returns `true` if the document has a signature-like object; `false`
|
|
384
|
-
* otherwise.
|
|
385
|
-
* @since 2.2.0
|
|
386
|
-
*/
|
|
387
|
-
function hasSignatureLike(jsonLd) {
|
|
388
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
389
|
-
const signature = jsonLd.signature;
|
|
390
|
-
const hasReference = (value) => {
|
|
391
|
-
if (typeof value === "string") return true;
|
|
392
|
-
if (Array.isArray(value)) return value.some(hasReference);
|
|
393
|
-
return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
|
|
394
|
-
};
|
|
395
|
-
const hasSignatureObject = (value) => {
|
|
396
|
-
if (typeof value !== "object" || value == null) return false;
|
|
397
|
-
const signatureRecord = value;
|
|
398
|
-
return (typeof signatureRecord.type === "string" || Array.isArray(signatureRecord.type) && signatureRecord.type.some((item) => typeof item === "string")) && (hasReference(signatureRecord.creator) || hasReference(signatureRecord.verificationMethod)) && (typeof signatureRecord.signatureValue === "string" || typeof signatureRecord.jws === "string");
|
|
399
|
-
};
|
|
400
|
-
return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
|
|
401
|
-
}
|
|
402
|
-
/**
|
|
403
|
-
* Checks if the given JSON-LD document has a Linked Data Signature.
|
|
404
|
-
* @param jsonLd The JSON-LD document to check.
|
|
405
|
-
* @returns `true` if the document has a signature; `false` otherwise.
|
|
406
|
-
* @since 1.0.0
|
|
407
|
-
*/
|
|
408
|
-
function hasSignature(jsonLd) {
|
|
409
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
410
|
-
if ("signature" in jsonLd) {
|
|
411
|
-
const signature = jsonLd.signature;
|
|
412
|
-
if (typeof signature !== "object" || signature == null) return false;
|
|
413
|
-
return "type" in signature && signature.type === "RsaSignature2017" && "creator" in signature && typeof signature.creator === "string" && "created" in signature && typeof signature.created === "string" && "signatureValue" in signature && typeof signature.signatureValue === "string";
|
|
414
|
-
}
|
|
415
|
-
return false;
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* Detaches Linked Data Signatures from the given JSON-LD document.
|
|
419
|
-
* @param jsonLd The JSON-LD document to modify.
|
|
420
|
-
* @returns The modified JSON-LD document. If the input document does not
|
|
421
|
-
* contain a signature, the original document is returned.
|
|
422
|
-
* @since 1.0.0
|
|
423
|
-
*/
|
|
424
|
-
function detachSignature(jsonLd) {
|
|
425
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
|
|
426
|
-
const doc = { ...jsonLd };
|
|
427
|
-
delete doc.signature;
|
|
428
|
-
return doc;
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* Verifies Linked Data Signatures of the given JSON-LD document.
|
|
432
|
-
*
|
|
433
|
-
* This is a low-level utility that only checks the cryptographic signature
|
|
434
|
-
* and (optionally) the cached key. It does not run the JSON-LD parsing,
|
|
435
|
-
* attribution, and owner checks that a complete inbound LD verification
|
|
436
|
-
* needs. For incoming activities, prefer {@link verifyJsonLd}, which is
|
|
437
|
-
* the public verification entry point and the one that emits the
|
|
438
|
-
* `activitypub.signature.verification.duration` metric for the LD path.
|
|
439
|
-
* `verifySignature` itself only emits
|
|
440
|
-
* `activitypub.signature.key_fetch.duration`, since the rest of the work
|
|
441
|
-
* that the verification-duration metric is meant to cover happens in
|
|
442
|
-
* `verifyJsonLd`.
|
|
443
|
-
* @param jsonLd The JSON-LD document to verify.
|
|
444
|
-
* @param options Options for verifying the signature.
|
|
445
|
-
* @returns The public key that signed the document or `null` if the signature
|
|
446
|
-
* is invalid or the key is not found.
|
|
447
|
-
* @since 1.0.0
|
|
448
|
-
*/
|
|
449
|
-
async function verifySignature(jsonLd, options = {}) {
|
|
450
|
-
if (!hasSignature(jsonLd)) return null;
|
|
451
|
-
const sig = jsonLd.signature;
|
|
452
|
-
let signature;
|
|
453
|
-
try {
|
|
454
|
-
signature = decodeBase64(sig.signatureValue);
|
|
455
|
-
} catch (error) {
|
|
456
|
-
logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
|
|
457
|
-
...sig,
|
|
458
|
-
error
|
|
459
|
-
});
|
|
460
|
-
return null;
|
|
461
|
-
}
|
|
462
|
-
const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
|
|
463
|
-
if (key == null) return null;
|
|
464
|
-
const sigOpts = {
|
|
465
|
-
...sig,
|
|
466
|
-
"@context": "https://w3id.org/identity/v1"
|
|
467
|
-
};
|
|
468
|
-
delete sigOpts.type;
|
|
469
|
-
delete sigOpts.id;
|
|
470
|
-
delete sigOpts.signatureValue;
|
|
471
|
-
let sigOptsHash;
|
|
472
|
-
try {
|
|
473
|
-
sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
|
|
474
|
-
} catch (error) {
|
|
475
|
-
logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
|
|
476
|
-
signatureOptions: sigOpts,
|
|
477
|
-
error
|
|
478
|
-
});
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
const document = { ...jsonLd };
|
|
482
|
-
delete document.signature;
|
|
483
|
-
let docHash;
|
|
484
|
-
try {
|
|
485
|
-
docHash = await hashJsonLd(document, options.contextLoader);
|
|
486
|
-
} catch (error) {
|
|
487
|
-
logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
|
|
488
|
-
document,
|
|
489
|
-
error
|
|
490
|
-
});
|
|
491
|
-
return null;
|
|
492
|
-
}
|
|
493
|
-
const encoder = new TextEncoder();
|
|
494
|
-
const message = sigOptsHash + docHash;
|
|
495
|
-
const messageBytes = encoder.encode(message);
|
|
496
|
-
if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
|
|
497
|
-
if (cached) {
|
|
498
|
-
logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
|
|
499
|
-
keyId: sig.creator,
|
|
500
|
-
...sig
|
|
501
|
-
});
|
|
502
|
-
const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
|
|
503
|
-
...options,
|
|
504
|
-
keyCache: {
|
|
505
|
-
get: () => Promise.resolve(void 0),
|
|
506
|
-
set: async (keyId, key) => await options.keyCache?.set(keyId, key)
|
|
507
|
-
}
|
|
508
|
-
}));
|
|
509
|
-
if (key == null) return null;
|
|
510
|
-
return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
|
|
511
|
-
}
|
|
512
|
-
logger$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
|
|
513
|
-
keyId: sig.creator,
|
|
514
|
-
...sig,
|
|
515
|
-
message
|
|
516
|
-
});
|
|
517
|
-
return null;
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Known Linked Data Signature `type` values, used to keep
|
|
521
|
-
* `ld_signatures.type` on a bounded set of spec-defined string values.
|
|
522
|
-
* Fedify only signs and verifies `RsaSignature2017`; other values come in
|
|
523
|
-
* only from external documents and are dropped from the metric attribute to
|
|
524
|
-
* avoid attacker-controlled cardinality.
|
|
525
|
-
*/
|
|
526
|
-
const LD_KNOWN_SIGNATURE_TYPES = new Set(["RsaSignature2017"]);
|
|
527
|
-
/**
|
|
528
|
-
* Reports only whether a `signature` key is present on the document, with
|
|
529
|
-
* no shape check on its value. This is intentionally looser than
|
|
530
|
-
* {@link hasSignature} (which validates a full `RsaSignature2017` shape)
|
|
531
|
-
* and {@link hasSignatureLike} (which structurally accepts several known
|
|
532
|
-
* suites): `verifyJsonLd` needs to tell a document with a malformed or
|
|
533
|
-
* unsupported signature payload (classified as `rejected`) apart from a
|
|
534
|
-
* truly unsigned document (classified as `missing`), and only this
|
|
535
|
-
* presence-only check captures both cases.
|
|
536
|
-
*/
|
|
537
|
-
function hasLdSignatureProperty(jsonLd) {
|
|
538
|
-
return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
|
|
539
|
-
}
|
|
540
|
-
function getLdSignatureObject(jsonLd) {
|
|
541
|
-
if (!hasLdSignatureProperty(jsonLd)) return void 0;
|
|
542
|
-
const { signature } = jsonLd;
|
|
543
|
-
if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
|
|
544
|
-
return signature;
|
|
545
|
-
}
|
|
546
|
-
/**
|
|
547
|
-
* Verify the authenticity of the given JSON-LD document using Linked Data
|
|
548
|
-
* Signatures. If the document is signed, this function verifies the signature
|
|
549
|
-
* and checks if the document is attributed to the owner of the public key.
|
|
550
|
-
* If the document is not signed, this function returns `false`.
|
|
551
|
-
* @param jsonLd The JSON-LD document to verify.
|
|
552
|
-
* @param options Options for verifying the document.
|
|
553
|
-
* @returns `true` if the document is authentic; `false` otherwise.
|
|
554
|
-
*/
|
|
555
|
-
async function verifyJsonLd(jsonLd, options = {}) {
|
|
556
|
-
return await verifyJsonLdInternal(jsonLd, options, true);
|
|
557
|
-
}
|
|
558
|
-
/** @internal */
|
|
559
|
-
async function verifyCompactJsonLd(jsonLd, options = {}) {
|
|
560
|
-
return await verifyJsonLdInternal(jsonLd, options, false);
|
|
561
|
-
}
|
|
562
|
-
async function verifyJsonLdInternal(jsonLd, options, compact) {
|
|
563
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
|
|
564
|
-
const start = performance.now();
|
|
565
|
-
let verified = false;
|
|
566
|
-
let threw = false;
|
|
567
|
-
let signatureType;
|
|
568
|
-
try {
|
|
569
|
-
const verificationOptions = hasSignature(jsonLd) ? {
|
|
570
|
-
...options,
|
|
571
|
-
contextLoader: getNormalizationContextLoader(options.contextLoader)
|
|
572
|
-
} : options;
|
|
573
|
-
const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
|
|
574
|
-
const object = await Object$1.fromJsonLd(compacted, verificationOptions);
|
|
575
|
-
if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
|
|
576
|
-
span.setAttribute("activitypub.object.type", getTypeId(object).href);
|
|
577
|
-
const sig = getLdSignatureObject(jsonLd);
|
|
578
|
-
if (sig != null) {
|
|
579
|
-
if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
|
|
580
|
-
if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
|
|
581
|
-
if (typeof sig.type === "string") {
|
|
582
|
-
span.setAttribute("ld_signatures.type", sig.type);
|
|
583
|
-
if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
const attributions = new Set(object.attributionIds.map((uri) => uri.href));
|
|
587
|
-
if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
|
|
588
|
-
const key = await verifySignature(compacted, verificationOptions);
|
|
589
|
-
if (key == null) return false;
|
|
590
|
-
if (key.ownerId == null) {
|
|
591
|
-
logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
|
|
592
|
-
return false;
|
|
593
|
-
}
|
|
594
|
-
attributions.delete(key.ownerId.href);
|
|
595
|
-
if (attributions.size > 0) {
|
|
596
|
-
logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
|
|
597
|
-
return false;
|
|
598
|
-
}
|
|
599
|
-
verified = true;
|
|
600
|
-
return true;
|
|
601
|
-
} catch (error) {
|
|
602
|
-
threw = true;
|
|
603
|
-
span.setStatus({
|
|
604
|
-
code: SpanStatusCode.ERROR,
|
|
605
|
-
message: String(error)
|
|
606
|
-
});
|
|
607
|
-
throw error;
|
|
608
|
-
} finally {
|
|
609
|
-
const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
|
|
610
|
-
getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, { ldType: signatureType });
|
|
611
|
-
span.end();
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
async function hashJsonLd(jsonLd, contextLoader) {
|
|
616
|
-
const canon = await jsonld.canonize(jsonLd, {
|
|
617
|
-
format: "application/n-quads",
|
|
618
|
-
documentLoader: contextLoader ?? getDocumentLoader()
|
|
619
|
-
});
|
|
620
|
-
const encoder = new TextEncoder();
|
|
621
|
-
return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
|
|
622
|
-
}
|
|
623
|
-
//#endregion
|
|
624
|
-
//#region src/sig/owner.ts
|
|
625
|
-
/**
|
|
626
|
-
* Checks if the actor of the given activity owns the specified key.
|
|
627
|
-
* @param activity The activity to check.
|
|
628
|
-
* @param key The public key to check.
|
|
629
|
-
* @param options Options for checking the key ownership.
|
|
630
|
-
* @returns Whether the actor is the owner of the key.
|
|
631
|
-
*/
|
|
632
|
-
async function doesActorOwnKey(activity, key, options) {
|
|
633
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.verify_key_ownership", {
|
|
634
|
-
kind: SpanKind.INTERNAL,
|
|
635
|
-
attributes: {
|
|
636
|
-
"activitypub.actor.id": activity.actorId?.href ?? "",
|
|
637
|
-
"activitypub.key.id": key.id?.href ?? ""
|
|
638
|
-
}
|
|
639
|
-
}, async (span) => {
|
|
640
|
-
try {
|
|
641
|
-
if (key.ownerId != null) {
|
|
642
|
-
const owns = key.ownerId.href === activity.actorId?.href;
|
|
643
|
-
span.setAttribute("activitypub.key_ownership.verified", owns);
|
|
644
|
-
span.setAttribute("activitypub.key_ownership.method", "owner_id");
|
|
645
|
-
return owns;
|
|
646
|
-
}
|
|
647
|
-
const actor = await activity.getActor(options);
|
|
648
|
-
if (actor == null || !isActor(actor)) {
|
|
649
|
-
span.setAttribute("activitypub.key_ownership.verified", false);
|
|
650
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
651
|
-
return false;
|
|
652
|
-
}
|
|
653
|
-
for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
|
|
654
|
-
span.setAttribute("activitypub.key_ownership.verified", true);
|
|
655
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
656
|
-
return true;
|
|
657
|
-
}
|
|
658
|
-
span.setAttribute("activitypub.key_ownership.verified", false);
|
|
659
|
-
span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
|
|
660
|
-
return false;
|
|
661
|
-
} catch (error) {
|
|
662
|
-
span.recordException(error);
|
|
663
|
-
span.setStatus({
|
|
664
|
-
code: SpanStatusCode.ERROR,
|
|
665
|
-
message: String(error)
|
|
666
|
-
});
|
|
667
|
-
throw error;
|
|
668
|
-
} finally {
|
|
669
|
-
span.end();
|
|
670
|
-
}
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
/**
|
|
674
|
-
* Gets the actor that owns the specified key. Returns `null` if the key has no
|
|
675
|
-
* known owner.
|
|
676
|
-
*
|
|
677
|
-
* @param keyId The ID of the key to check, or the key itself.
|
|
678
|
-
* @param options Options for getting the key owner.
|
|
679
|
-
* @returns The actor that owns the key, or `null` if the key has no known
|
|
680
|
-
* owner.
|
|
681
|
-
* @since 0.7.0
|
|
682
|
-
*/
|
|
683
|
-
async function getKeyOwner(keyId, options) {
|
|
684
|
-
const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
|
|
685
|
-
const documentLoader = options.documentLoader ?? getDocumentLoader();
|
|
686
|
-
const contextLoader = options.contextLoader ?? getDocumentLoader();
|
|
687
|
-
let object;
|
|
688
|
-
if (keyId instanceof CryptographicKey) {
|
|
689
|
-
object = keyId;
|
|
690
|
-
if (object.id == null) return null;
|
|
691
|
-
keyId = object.id;
|
|
692
|
-
} else {
|
|
693
|
-
let keyDoc;
|
|
694
|
-
try {
|
|
695
|
-
const { document } = await documentLoader(keyId.href);
|
|
696
|
-
keyDoc = document;
|
|
697
|
-
} catch (_) {
|
|
698
|
-
return null;
|
|
699
|
-
}
|
|
700
|
-
try {
|
|
701
|
-
object = await Object$1.fromJsonLd(keyDoc, {
|
|
702
|
-
documentLoader,
|
|
703
|
-
contextLoader,
|
|
704
|
-
tracerProvider
|
|
705
|
-
});
|
|
706
|
-
} catch (e) {
|
|
707
|
-
if (!(e instanceof TypeError)) throw e;
|
|
708
|
-
try {
|
|
709
|
-
object = await CryptographicKey.fromJsonLd(keyDoc, {
|
|
710
|
-
documentLoader,
|
|
711
|
-
contextLoader,
|
|
712
|
-
tracerProvider
|
|
713
|
-
});
|
|
714
|
-
} catch (e) {
|
|
715
|
-
if (e instanceof TypeError) return null;
|
|
716
|
-
throw e;
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
let owner = null;
|
|
721
|
-
if (object instanceof CryptographicKey) {
|
|
722
|
-
if (object.ownerId == null) return null;
|
|
723
|
-
owner = await object.getOwner({
|
|
724
|
-
documentLoader,
|
|
725
|
-
contextLoader,
|
|
726
|
-
tracerProvider
|
|
727
|
-
});
|
|
728
|
-
} else if (isActor(object)) owner = object;
|
|
729
|
-
else return null;
|
|
730
|
-
if (owner == null) return null;
|
|
731
|
-
for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
|
|
732
|
-
return null;
|
|
733
|
-
}
|
|
734
|
-
//#endregion
|
|
735
|
-
//#region src/compat/preloaded-context-loader.ts
|
|
736
|
-
/**
|
|
737
|
-
* A restricted JSON-LD document loader that resolves only contexts bundled
|
|
738
|
-
* with Fedify.
|
|
739
|
-
*
|
|
740
|
-
* This is intentionally narrower than `getDocumentLoader()`: normalization
|
|
741
|
-
* helpers are also reached from verification paths that operate on inbound,
|
|
742
|
-
* attacker-controlled JSON-LD, so the default fallback must never fetch
|
|
743
|
-
* attacker-supplied context URLs.
|
|
744
|
-
*/
|
|
745
|
-
const preloadedOnlyDocumentLoader = (url) => {
|
|
746
|
-
if (Object.hasOwn(preloadedContexts, url)) return Promise.resolve({
|
|
747
|
-
contextUrl: null,
|
|
748
|
-
documentUrl: url,
|
|
749
|
-
document: preloadedContexts[url]
|
|
750
|
-
});
|
|
751
|
-
return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
|
|
752
|
-
};
|
|
753
|
-
//#endregion
|
|
754
|
-
//#region src/compat/public-audience.ts
|
|
755
|
-
const logger$2 = getLogger([
|
|
756
|
-
"fedify",
|
|
757
|
-
"compat",
|
|
758
|
-
"public-audience"
|
|
759
|
-
]);
|
|
760
|
-
const PUBLIC_ADDRESSING_FIELDS = new Set([
|
|
761
|
-
"to",
|
|
762
|
-
"cc",
|
|
763
|
-
"bto",
|
|
764
|
-
"bcc",
|
|
765
|
-
"audience"
|
|
766
|
-
]);
|
|
767
|
-
const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
|
|
768
|
-
const MAX_TRAVERSAL_DEPTH$1 = 64;
|
|
769
|
-
const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(preloadedContexts));
|
|
770
|
-
function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
|
|
771
|
-
if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
|
|
772
|
-
if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
|
|
773
|
-
if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
|
|
774
|
-
if (typeof value !== "object" || value == null) return false;
|
|
775
|
-
const record = value;
|
|
776
|
-
for (const key of Object.keys(record)) {
|
|
777
|
-
if (key === "@context") continue;
|
|
778
|
-
if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
|
|
779
|
-
}
|
|
780
|
-
return false;
|
|
781
|
-
}
|
|
782
|
-
function rewritePublicAudience(value, parentKey, depth = 0) {
|
|
783
|
-
if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return PUBLIC_COLLECTION.href;
|
|
784
|
-
if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
|
|
785
|
-
if (Array.isArray(value)) {
|
|
786
|
-
let changed = false;
|
|
787
|
-
const mapped = value.map((item) => {
|
|
788
|
-
const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
|
|
789
|
-
if (rewritten !== item) changed = true;
|
|
790
|
-
return rewritten;
|
|
791
|
-
});
|
|
792
|
-
return changed ? mapped : value;
|
|
793
|
-
}
|
|
794
|
-
if (typeof value !== "object" || value == null) return value;
|
|
795
|
-
const record = value;
|
|
796
|
-
let changed = false;
|
|
797
|
-
const normalized = Object.create(null);
|
|
798
|
-
for (const key of Object.keys(record)) {
|
|
799
|
-
const rewritten = key === "@context" ? record[key] : rewritePublicAudience(record[key], key, depth + 1);
|
|
800
|
-
if (rewritten !== record[key]) changed = true;
|
|
801
|
-
normalized[key] = rewritten;
|
|
802
|
-
}
|
|
803
|
-
return changed ? normalized : value;
|
|
804
|
-
}
|
|
805
|
-
/**
|
|
806
|
-
* Reports whether `value` carries an `@context` property anywhere inside
|
|
807
|
-
* its subtree (not counting the value itself). A nested `@context` can
|
|
808
|
-
* introduce a local term-definition scope that redefines `as:` or `Public`
|
|
809
|
-
* even when the top-level `@context` is safe, so the fast path must defer
|
|
810
|
-
* to the URDNA2015 equivalence check whenever one is present.
|
|
811
|
-
*/
|
|
812
|
-
function hasNestedContext$1(value, depth = 0) {
|
|
813
|
-
if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
|
|
814
|
-
if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
|
|
815
|
-
if (typeof value !== "object" || value == null) return false;
|
|
816
|
-
const record = value;
|
|
817
|
-
for (const key of Object.keys(record)) {
|
|
818
|
-
if (key === "@context") return true;
|
|
819
|
-
if (hasNestedContext$1(record[key], depth + 1)) return true;
|
|
820
|
-
}
|
|
821
|
-
return false;
|
|
822
|
-
}
|
|
823
|
-
/**
|
|
824
|
-
* Checks whether the `@context` of a JSON-LD document is guaranteed not
|
|
825
|
-
* to redefine the `as:` prefix or the bare `Public` term. Only documents
|
|
826
|
-
* whose `@context` is a string, or an array of strings, drawn from Fedify's
|
|
827
|
-
* preloaded context set AND including the ActivityStreams URL qualify,
|
|
828
|
-
* AND no nested subtree carries its own `@context` that might redefine
|
|
829
|
-
* those terms within a local scope. When all of that holds the rewrite
|
|
830
|
-
* is provably semantics-preserving and the URDNA2015 equivalence check
|
|
831
|
-
* can be skipped. Any other shape (unknown external URLs, inline
|
|
832
|
-
* objects at the top level, nested `@context` blocks) is treated as
|
|
833
|
-
* potentially unsafe.
|
|
834
|
-
*/
|
|
835
|
-
function hasKnownSafeContext$1(jsonLd) {
|
|
836
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
837
|
-
const record = jsonLd;
|
|
838
|
-
if (!Object.hasOwn(record, "@context")) return false;
|
|
839
|
-
const ctx = record["@context"];
|
|
840
|
-
const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
|
|
841
|
-
if (entries == null || entries.length === 0) return false;
|
|
842
|
-
let hasAs = false;
|
|
843
|
-
for (const entry of entries) {
|
|
844
|
-
if (typeof entry !== "string") return false;
|
|
845
|
-
if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
|
|
846
|
-
if (entry === AS_CONTEXT_URL$1) hasAs = true;
|
|
847
|
-
}
|
|
848
|
-
if (!hasAs) return false;
|
|
849
|
-
for (const key of Object.keys(record)) {
|
|
850
|
-
if (key === "@context") continue;
|
|
851
|
-
if (hasNestedContext$1(record[key])) return false;
|
|
852
|
-
}
|
|
853
|
-
return true;
|
|
854
|
-
}
|
|
855
|
-
/**
|
|
856
|
-
* Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
|
|
857
|
-
* addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
|
|
858
|
-
* expanded `https://www.w3.org/ns/activitystreams#Public` URI.
|
|
859
|
-
*
|
|
860
|
-
* Several ActivityPub implementations, Lemmy among them, match these
|
|
861
|
-
* fields as plain URLs without running JSON-LD expansion, and silently
|
|
862
|
-
* drop activities whose public addressing appears in CURIE form. This
|
|
863
|
-
* helper works around that gap.
|
|
864
|
-
*
|
|
865
|
-
* For documents whose `@context` is drawn entirely from Fedify's
|
|
866
|
-
* preloaded context set and includes the ActivityStreams URL, the
|
|
867
|
-
* rewrite is applied directly: the content of every preloaded non-AS
|
|
868
|
-
* context is known not to redefine the `as:` prefix or the bare `Public`
|
|
869
|
-
* term, so the semantics are preserved by construction. Any other
|
|
870
|
-
* shape (an inline object, an unknown external URL, and so on) is
|
|
871
|
-
* treated as potentially unsafe and gated on a JSON-LD equivalence
|
|
872
|
-
* check; both forms are canonicalized with URDNA2015 and the resulting
|
|
873
|
-
* N-Quads are compared. When they differ, the original document is
|
|
874
|
-
* returned unchanged. Canonicalization failures also fall back to the
|
|
875
|
-
* original document.
|
|
876
|
-
*
|
|
877
|
-
* When no `contextLoader` is supplied the helper falls back to an
|
|
878
|
-
* internal loader that resolves only the URLs in Fedify's
|
|
879
|
-
* preloaded-contexts set and rejects every other URL without issuing a
|
|
880
|
-
* network request. That behaviour is deliberately narrower than
|
|
881
|
-
* `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
|
|
882
|
-
* `validatePublicUrl` check will happily fetch non-preloaded URLs: the
|
|
883
|
-
* helper is reached from verification paths (`verifyProof()` /
|
|
884
|
-
* `verifyObject()`) that operate on inbound, potentially adversarial
|
|
885
|
-
* JSON-LD, and a default loader that fetches attacker-supplied
|
|
886
|
-
* `@context` URLs on the caller's behalf would be an SSRF vector.
|
|
887
|
-
* Canonicalization failures against the restricted loader fall back to
|
|
888
|
-
* the original document, same as any other canonicalization error.
|
|
889
|
-
* Callers that genuinely need the remote-fetch loader (for example
|
|
890
|
-
* applications that sign local JSON-LD against a custom vocabulary)
|
|
891
|
-
* should pass a `contextLoader` explicitly.
|
|
892
|
-
*
|
|
893
|
-
* Must be called before any signing step that canonicalizes the
|
|
894
|
-
* compact form byte-for-byte (for example, Object Integrity Proofs
|
|
895
|
-
* using the `eddsa-jcs-2022` cryptosuite), so the signed payload
|
|
896
|
-
* matches what is sent on the wire.
|
|
897
|
-
*/
|
|
898
|
-
async function normalizePublicAudience(jsonLd, contextLoader) {
|
|
899
|
-
if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
|
|
900
|
-
const normalized = rewritePublicAudience(jsonLd);
|
|
901
|
-
if (hasKnownSafeContext$1(jsonLd)) return normalized;
|
|
902
|
-
const loader = contextLoader ?? preloadedOnlyDocumentLoader;
|
|
903
|
-
try {
|
|
904
|
-
const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
|
|
905
|
-
format: "application/n-quads",
|
|
906
|
-
documentLoader: loader
|
|
907
|
-
}), jsonld.canonize(normalized, {
|
|
908
|
-
format: "application/n-quads",
|
|
909
|
-
documentLoader: loader
|
|
910
|
-
})]);
|
|
911
|
-
if (before === after) return normalized;
|
|
912
|
-
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.");
|
|
913
|
-
} catch (error) {
|
|
914
|
-
logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
|
|
915
|
-
}
|
|
916
|
-
return jsonLd;
|
|
917
|
-
}
|
|
918
|
-
//#endregion
|
|
919
|
-
//#region src/compat/outgoing-jsonld.ts
|
|
920
|
-
const logger$1 = getLogger([
|
|
921
|
-
"fedify",
|
|
922
|
-
"compat",
|
|
923
|
-
"outgoing-jsonld"
|
|
924
|
-
]);
|
|
925
|
-
const ATTACHMENT_FIELDS = new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
|
|
926
|
-
const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
|
|
927
|
-
const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
|
|
928
|
-
const MAX_TRAVERSAL_DEPTH = 64;
|
|
929
|
-
function isJsonLdListObject(value) {
|
|
930
|
-
return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
|
|
931
|
-
}
|
|
932
|
-
function isJsonLdValueObject(value) {
|
|
933
|
-
return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
|
|
934
|
-
}
|
|
935
|
-
function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
936
|
-
if (Array.isArray(value)) {
|
|
937
|
-
if (seen.has(value)) return;
|
|
938
|
-
seen.add(value);
|
|
939
|
-
for (const item of value) yield* getContextObjects(item, seen);
|
|
940
|
-
return;
|
|
941
|
-
}
|
|
942
|
-
if (typeof value === "object" && value != null) {
|
|
943
|
-
if (seen.has(value)) return;
|
|
944
|
-
seen.add(value);
|
|
945
|
-
const record = value;
|
|
946
|
-
yield record;
|
|
947
|
-
for (const definition of Object.values(record)) {
|
|
948
|
-
if (typeof definition !== "object" || definition == null) continue;
|
|
949
|
-
const nestedContext = definition["@context"];
|
|
950
|
-
if (nestedContext == null) continue;
|
|
951
|
-
yield* getContextObjects(nestedContext, seen);
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
function isActivityStreamsAttachmentTerm(value) {
|
|
956
|
-
return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
|
|
957
|
-
}
|
|
958
|
-
/** @internal */
|
|
959
|
-
function isPreloadedContextAttachmentSafe(document) {
|
|
960
|
-
if (typeof document !== "object" || document == null) return true;
|
|
961
|
-
const context = document["@context"];
|
|
962
|
-
for (const contextObject of getContextObjects(context)) {
|
|
963
|
-
if (!Object.hasOwn(contextObject, "attachment")) continue;
|
|
964
|
-
if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
|
|
965
|
-
return false;
|
|
966
|
-
}
|
|
967
|
-
return true;
|
|
968
|
-
}
|
|
969
|
-
function getKnownSafeContextUrls() {
|
|
970
|
-
const urls = /* @__PURE__ */ new Set();
|
|
971
|
-
for (const [url, document] of Object.entries(preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
|
|
972
|
-
else logger$1.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
|
|
973
|
-
return urls;
|
|
974
|
-
}
|
|
975
|
-
/**
|
|
976
|
-
* Wraps scalar ActivityStreams attachment properties in arrays.
|
|
977
|
-
*/
|
|
978
|
-
function wrapScalarAttachments(jsonLd, depth = 0) {
|
|
979
|
-
if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
|
|
980
|
-
if (Array.isArray(jsonLd)) {
|
|
981
|
-
let normalized = null;
|
|
982
|
-
for (let i = 0; i < jsonLd.length; i++) {
|
|
983
|
-
const item = jsonLd[i];
|
|
984
|
-
const next = wrapScalarAttachments(item, depth + 1);
|
|
985
|
-
if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
|
|
986
|
-
if (normalized != null) normalized[i] = next;
|
|
987
|
-
}
|
|
988
|
-
return normalized ?? jsonLd;
|
|
989
|
-
}
|
|
990
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
|
|
991
|
-
const record = jsonLd;
|
|
992
|
-
const keys = Object.keys(record);
|
|
993
|
-
let normalized = null;
|
|
994
|
-
for (let i = 0; i < keys.length; i++) {
|
|
995
|
-
const key = keys[i];
|
|
996
|
-
const value = record[key];
|
|
997
|
-
const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
|
|
998
|
-
const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
|
|
999
|
-
if (normalized == null && output !== value) {
|
|
1000
|
-
const cloned = Object.create(null);
|
|
1001
|
-
for (let j = 0; j < i; j++) {
|
|
1002
|
-
const previousKey = keys[j];
|
|
1003
|
-
cloned[previousKey] = record[previousKey];
|
|
1004
|
-
}
|
|
1005
|
-
normalized = cloned;
|
|
1006
|
-
}
|
|
1007
|
-
if (normalized != null) normalized[key] = output;
|
|
1008
|
-
}
|
|
1009
|
-
return normalized ?? jsonLd;
|
|
1010
|
-
}
|
|
1011
|
-
function hasNestedContext(value, depth = 0) {
|
|
1012
|
-
if (depth >= MAX_TRAVERSAL_DEPTH) return true;
|
|
1013
|
-
if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
|
|
1014
|
-
if (typeof value !== "object" || value == null) return false;
|
|
1015
|
-
const record = value;
|
|
1016
|
-
for (const key of Object.keys(record)) {
|
|
1017
|
-
if (key === "@context") return true;
|
|
1018
|
-
if (key === "@value" && isJsonLdValueObject(value)) continue;
|
|
1019
|
-
if (hasNestedContext(record[key], depth + 1)) return true;
|
|
1020
|
-
}
|
|
1021
|
-
return false;
|
|
1022
|
-
}
|
|
1023
|
-
function exceedsTraversalDepth(value, depth = 0) {
|
|
1024
|
-
if (depth >= MAX_TRAVERSAL_DEPTH) return true;
|
|
1025
|
-
if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
|
|
1026
|
-
if (typeof value !== "object" || value == null) return false;
|
|
1027
|
-
const record = value;
|
|
1028
|
-
for (const key of Object.keys(record)) {
|
|
1029
|
-
if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
|
|
1030
|
-
if (exceedsTraversalDepth(record[key], depth + 1)) return true;
|
|
1031
|
-
}
|
|
1032
|
-
return false;
|
|
1033
|
-
}
|
|
1034
|
-
function hasKnownSafeContext(jsonLd) {
|
|
1035
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
1036
|
-
const record = jsonLd;
|
|
1037
|
-
if (!Object.hasOwn(record, "@context")) return false;
|
|
1038
|
-
const context = record["@context"];
|
|
1039
|
-
const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
|
|
1040
|
-
if (entries == null || entries.length < 1) return false;
|
|
1041
|
-
let hasActivityStreamsContext = false;
|
|
1042
|
-
for (const entry of entries) {
|
|
1043
|
-
if (typeof entry !== "string") return false;
|
|
1044
|
-
if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
|
|
1045
|
-
if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
|
|
1046
|
-
}
|
|
1047
|
-
if (!hasActivityStreamsContext) return false;
|
|
1048
|
-
for (const key of Object.keys(record)) {
|
|
1049
|
-
if (key === "@context") continue;
|
|
1050
|
-
if (hasNestedContext(record[key])) return false;
|
|
1051
|
-
}
|
|
1052
|
-
return true;
|
|
1053
|
-
}
|
|
1054
|
-
function getLogSafeJsonLdMetadata(jsonLd) {
|
|
1055
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return {};
|
|
1056
|
-
const record = jsonLd;
|
|
1057
|
-
const context = record["@context"];
|
|
1058
|
-
return {
|
|
1059
|
-
id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
|
|
1060
|
-
type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
|
|
1061
|
-
context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
|
|
1062
|
-
};
|
|
1063
|
-
}
|
|
1064
|
-
/**
|
|
1065
|
-
* Ensures ActivityStreams attachment properties are represented as arrays
|
|
1066
|
-
* when doing so preserves the JSON-LD semantics.
|
|
1067
|
-
*
|
|
1068
|
-
* JSON-LD compaction collapses single-item arrays into scalar values by
|
|
1069
|
-
* default. Some ActivityPub implementations, Pixelfed among them, parse
|
|
1070
|
-
* `attachment` as a plain JSON array rather than a JSON-LD property and reject
|
|
1071
|
-
* otherwise valid objects whose single attachment is emitted as a scalar.
|
|
1072
|
-
*
|
|
1073
|
-
* When no `contextLoader` is supplied, the helper falls back to a restricted
|
|
1074
|
-
* loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
|
|
1075
|
-
* every other URL without network access. Documents with custom, inline, or
|
|
1076
|
-
* otherwise uncached contexts should pass a real `contextLoader` if they need
|
|
1077
|
-
* the semantic-preservation check to succeed; otherwise canonicalization
|
|
1078
|
-
* failures leave the original document unchanged.
|
|
1079
|
-
*/
|
|
1080
|
-
async function normalizeAttachmentArrays(jsonLd, contextLoader) {
|
|
1081
|
-
const normalized = wrapScalarAttachments(jsonLd);
|
|
1082
|
-
if (normalized === jsonLd) return jsonLd;
|
|
1083
|
-
if (exceedsTraversalDepth(jsonLd)) {
|
|
1084
|
-
logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
|
|
1085
|
-
return jsonLd;
|
|
1086
|
-
}
|
|
1087
|
-
if (hasKnownSafeContext(jsonLd)) return normalized;
|
|
1088
|
-
const loader = contextLoader ?? preloadedOnlyDocumentLoader;
|
|
1089
|
-
try {
|
|
1090
|
-
const [before, after] = await Promise.all([jsonld.canonize(jsonLd, {
|
|
1091
|
-
format: "application/n-quads",
|
|
1092
|
-
documentLoader: loader
|
|
1093
|
-
}), jsonld.canonize(normalized, {
|
|
1094
|
-
format: "application/n-quads",
|
|
1095
|
-
documentLoader: loader
|
|
1096
|
-
})]);
|
|
1097
|
-
if (before === after) return normalized;
|
|
1098
|
-
logger$1.warn("Wrapping scalar attachment values in arrays would change the canonical form of the JSON-LD document; leaving it unchanged. This usually means the active JSON-LD context redefines the `attachment` term. Document: {id}; type: {type}; context: {context}.", getLogSafeJsonLdMetadata(jsonLd));
|
|
1099
|
-
} catch (error) {
|
|
1100
|
-
logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
|
|
1101
|
-
}
|
|
1102
|
-
return jsonLd;
|
|
1103
|
-
}
|
|
1104
|
-
/**
|
|
1105
|
-
* Applies Fedify's internal JSON-LD wire-format interoperability workarounds
|
|
1106
|
-
* to locally generated outgoing activities before they are signed, enqueued,
|
|
1107
|
-
* or sent.
|
|
1108
|
-
*/
|
|
1109
|
-
async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
|
|
1110
|
-
jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
|
|
1111
|
-
return await normalizeAttachmentArrays(jsonLd, contextLoader);
|
|
1112
|
-
}
|
|
1113
|
-
//#endregion
|
|
1114
|
-
//#region src/sig/proof.ts
|
|
1115
|
-
/**
|
|
1116
|
-
* Known Object Integrity Proof `cryptosuite` values, used to keep
|
|
1117
|
-
* `object_integrity_proofs.cryptosuite` on a bounded set of spec-defined
|
|
1118
|
-
* string values. Fedify currently signs and verifies only
|
|
1119
|
-
* `eddsa-jcs-2022`; other values come in only from external proofs and are
|
|
1120
|
-
* dropped from the metric attribute to avoid attacker-controlled
|
|
1121
|
-
* cardinality.
|
|
1122
|
-
*/
|
|
1123
|
-
const OIP_KNOWN_CRYPTOSUITES = new Set(["eddsa-jcs-2022"]);
|
|
1124
|
-
const logger = getLogger([
|
|
1125
|
-
"fedify",
|
|
1126
|
-
"sig",
|
|
1127
|
-
"proof"
|
|
1128
|
-
]);
|
|
1129
|
-
/**
|
|
1130
|
-
* Checks if the given JSON-LD document has a DataIntegrityProof-like object,
|
|
1131
|
-
* without fully deserializing it into vocabulary classes.
|
|
1132
|
-
* @param jsonLd The JSON-LD document to check.
|
|
1133
|
-
* @returns `true` if the document has a proof-like object; `false` otherwise.
|
|
1134
|
-
* @since 2.2.0
|
|
1135
|
-
*/
|
|
1136
|
-
function hasProofLike(jsonLd) {
|
|
1137
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
1138
|
-
const record = jsonLd;
|
|
1139
|
-
const proof = record.proof ?? record["https://w3id.org/security#proof"];
|
|
1140
|
-
const getField = (source, compact, expanded) => source[compact] ?? source[expanded];
|
|
1141
|
-
const isReference = (value) => {
|
|
1142
|
-
if (typeof value === "string") return true;
|
|
1143
|
-
if (Array.isArray(value)) return value.some(isReference);
|
|
1144
|
-
return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string" || "@value" in value && typeof value["@value"] === "string");
|
|
1145
|
-
};
|
|
1146
|
-
const hasType = (value) => {
|
|
1147
|
-
if (typeof value === "string") return value === "DataIntegrityProof" || value === "https://w3id.org/security#DataIntegrityProof";
|
|
1148
|
-
if (Array.isArray(value)) return value.some(hasType);
|
|
1149
|
-
return false;
|
|
1150
|
-
};
|
|
1151
|
-
const isProofLike = (value) => {
|
|
1152
|
-
if (typeof value !== "object" || value == null) return false;
|
|
1153
|
-
const proofRecord = value;
|
|
1154
|
-
return hasType(proofRecord.type ?? proofRecord["@type"]) && isReference(getField(proofRecord, "verificationMethod", "https://w3id.org/security#verificationMethod")) && isReference(getField(proofRecord, "proofPurpose", "https://w3id.org/security#proofPurpose")) && isReference(getField(proofRecord, "proofValue", "https://w3id.org/security#proofValue"));
|
|
1155
|
-
};
|
|
1156
|
-
return Array.isArray(proof) ? proof.some(isProofLike) : isProofLike(proof);
|
|
1157
|
-
}
|
|
1158
|
-
/**
|
|
1159
|
-
* Creates a proof for the given object.
|
|
1160
|
-
* @param object The object to create a proof for.
|
|
1161
|
-
* @param privateKey The private key to sign the proof with.
|
|
1162
|
-
* @param keyId The key ID to use in the proof. It will be used by the verifier.
|
|
1163
|
-
* @param options Additional options. See also {@link CreateProofOptions}.
|
|
1164
|
-
* @returns The created proof.
|
|
1165
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
1166
|
-
* @since 0.10.0
|
|
1167
|
-
*/
|
|
1168
|
-
async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
|
|
1169
|
-
validateCryptoKey(privateKey, "private");
|
|
1170
|
-
if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
|
|
1171
|
-
let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
|
|
1172
|
-
format: "compact",
|
|
1173
|
-
contextLoader,
|
|
1174
|
-
context
|
|
1175
|
-
});
|
|
1176
|
-
compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader);
|
|
1177
|
-
const msgCanon = serialize(compactMsg);
|
|
1178
|
-
const encoder = new TextEncoder();
|
|
1179
|
-
const msgBytes = encoder.encode(msgCanon);
|
|
1180
|
-
const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
|
|
1181
|
-
created ??= Temporal.Now.instant();
|
|
1182
|
-
const proofCanon = serialize({
|
|
1183
|
-
"@context": compactMsg["@context"],
|
|
1184
|
-
type: "DataIntegrityProof",
|
|
1185
|
-
cryptosuite: "eddsa-jcs-2022",
|
|
1186
|
-
verificationMethod: keyId.href,
|
|
1187
|
-
proofPurpose: "assertionMethod",
|
|
1188
|
-
created: created.toString()
|
|
1189
|
-
});
|
|
1190
|
-
const proofBytes = encoder.encode(proofCanon);
|
|
1191
|
-
const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
|
|
1192
|
-
const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
|
|
1193
|
-
digest.set(new Uint8Array(proofDigest), 0);
|
|
1194
|
-
digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
|
|
1195
|
-
const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
|
|
1196
|
-
return new DataIntegrityProof({
|
|
1197
|
-
cryptosuite: "eddsa-jcs-2022",
|
|
1198
|
-
verificationMethod: keyId,
|
|
1199
|
-
proofPurpose: "assertionMethod",
|
|
1200
|
-
created: created ?? Temporal.Now.instant(),
|
|
1201
|
-
proofValue: new Uint8Array(sig)
|
|
1202
|
-
});
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Signs the given object with the private key and returns the signed object.
|
|
1206
|
-
* @param object The object to create a proof for.
|
|
1207
|
-
* @param privateKey The private key to sign the proof with.
|
|
1208
|
-
* @param keyId The key ID to use in the proof. It will be used by the verifier.
|
|
1209
|
-
* @param options Additional options. See also {@link SignObjectOptions}.
|
|
1210
|
-
* @returns The signed object.
|
|
1211
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
1212
|
-
* @since 0.10.0
|
|
1213
|
-
*/
|
|
1214
|
-
async function signObject(object, privateKey, keyId, options = {}) {
|
|
1215
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
|
|
1216
|
-
try {
|
|
1217
|
-
if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
|
|
1218
|
-
const existingProofs = [];
|
|
1219
|
-
for await (const proof of object.getProofs(options)) existingProofs.push(proof);
|
|
1220
|
-
const proof = await createProof(object, privateKey, keyId, options);
|
|
1221
|
-
if (span.isRecording()) {
|
|
1222
|
-
if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
|
|
1223
|
-
if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
|
|
1224
|
-
if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
|
|
1225
|
-
}
|
|
1226
|
-
return object.clone({ proofs: [...existingProofs, proof] });
|
|
1227
|
-
} catch (error) {
|
|
1228
|
-
span.setStatus({
|
|
1229
|
-
code: SpanStatusCode.ERROR,
|
|
1230
|
-
message: String(error)
|
|
1231
|
-
});
|
|
1232
|
-
throw error;
|
|
1233
|
-
} finally {
|
|
1234
|
-
span.end();
|
|
1235
|
-
}
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
/**
|
|
1239
|
-
* Verifies the given proof for the object.
|
|
1240
|
-
* @param jsonLd The JSON-LD object to verify the proof for. If it contains
|
|
1241
|
-
* any proofs, they will be ignored.
|
|
1242
|
-
* @param proof The proof to verify.
|
|
1243
|
-
* @param options Additional options. See also {@link VerifyProofOptions}.
|
|
1244
|
-
* @returns The public key that was used to sign the proof, or `null` if the
|
|
1245
|
-
* proof is invalid.
|
|
1246
|
-
* @since 0.10.0
|
|
1247
|
-
*/
|
|
1248
|
-
async function verifyProof(jsonLd, proof, options = {}) {
|
|
1249
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
|
|
1250
|
-
const start = performance.now();
|
|
1251
|
-
let verified = false;
|
|
1252
|
-
let threw = false;
|
|
1253
|
-
const cryptosuite = proof.cryptosuite != null && OIP_KNOWN_CRYPTOSUITES.has(proof.cryptosuite) ? proof.cryptosuite : void 0;
|
|
1254
|
-
if (span.isRecording()) {
|
|
1255
|
-
if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
|
|
1256
|
-
if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
|
|
1257
|
-
if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
|
|
1258
|
-
}
|
|
1259
|
-
try {
|
|
1260
|
-
const key = await verifyProofInternal(jsonLd, proof, options);
|
|
1261
|
-
if (key == null) span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1262
|
-
else verified = true;
|
|
1263
|
-
return key;
|
|
1264
|
-
} catch (error) {
|
|
1265
|
-
threw = true;
|
|
1266
|
-
span.setStatus({
|
|
1267
|
-
code: SpanStatusCode.ERROR,
|
|
1268
|
-
message: String(error)
|
|
1269
|
-
});
|
|
1270
|
-
throw error;
|
|
1271
|
-
} finally {
|
|
1272
|
-
const classified = threw ? "error" : verified ? "verified" : "rejected";
|
|
1273
|
-
getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "object_integrity", classified, { cryptosuite });
|
|
1274
|
-
span.end();
|
|
1275
|
-
}
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
async function verifyProofInternal(jsonLd, proof, options) {
|
|
1279
|
-
if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
|
|
1280
|
-
const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, options));
|
|
1281
|
-
const proofConfig = {
|
|
1282
|
-
"@context": jsonLd["@context"],
|
|
1283
|
-
type: "DataIntegrityProof",
|
|
1284
|
-
cryptosuite: proof.cryptosuite,
|
|
1285
|
-
verificationMethod: proof.verificationMethodId.href,
|
|
1286
|
-
proofPurpose: proof.proofPurpose,
|
|
1287
|
-
created: proof.created.toString()
|
|
1288
|
-
};
|
|
1289
|
-
const encoder = new TextEncoder();
|
|
1290
|
-
const proofBytes = encoder.encode(serialize(proofConfig));
|
|
1291
|
-
const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
|
|
1292
|
-
const msg = { ...jsonLd };
|
|
1293
|
-
if ("proof" in msg) delete msg.proof;
|
|
1294
|
-
if ("https://w3id.org/security#proof" in msg) delete msg["https://w3id.org/security#proof"];
|
|
1295
|
-
let fetchedKey;
|
|
1296
|
-
try {
|
|
1297
|
-
fetchedKey = await publicKeyPromise;
|
|
1298
|
-
} catch (error) {
|
|
1299
|
-
logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
|
|
1300
|
-
proof,
|
|
1301
|
-
keyId: proof.verificationMethodId.href,
|
|
1302
|
-
error
|
|
1303
|
-
});
|
|
1304
|
-
return null;
|
|
1305
|
-
}
|
|
1306
|
-
const publicKey = fetchedKey.key;
|
|
1307
|
-
if (publicKey == null) {
|
|
1308
|
-
logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
|
|
1309
|
-
proof,
|
|
1310
|
-
keyId: proof.verificationMethodId.href
|
|
1311
|
-
});
|
|
1312
|
-
return null;
|
|
1313
|
-
}
|
|
1314
|
-
if (publicKey.publicKey.algorithm.name !== "Ed25519") {
|
|
1315
|
-
if (fetchedKey.cached) {
|
|
1316
|
-
logger.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
|
|
1317
|
-
proof,
|
|
1318
|
-
keyId: proof.verificationMethodId.href
|
|
1319
|
-
});
|
|
1320
|
-
return await verifyProofInternal(jsonLd, proof, {
|
|
1321
|
-
...options,
|
|
1322
|
-
keyCache: {
|
|
1323
|
-
get: () => Promise.resolve(void 0),
|
|
1324
|
-
set: async (keyId, key) => await options.keyCache?.set(keyId, key)
|
|
1325
|
-
}
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
logger.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
|
|
1329
|
-
proof,
|
|
1330
|
-
keyId: proof.verificationMethodId.href
|
|
1331
|
-
});
|
|
1332
|
-
return null;
|
|
1333
|
-
}
|
|
1334
|
-
const digest = new Uint8Array(proofDigest.byteLength + 32);
|
|
1335
|
-
digest.set(new Uint8Array(proofDigest), 0);
|
|
1336
|
-
const proofValue = proof.proofValue;
|
|
1337
|
-
const verifyCandidate = async (candidate) => {
|
|
1338
|
-
const msgBytes = encoder.encode(serialize(candidate));
|
|
1339
|
-
const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
|
|
1340
|
-
digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
|
|
1341
|
-
return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
|
|
1342
|
-
};
|
|
1343
|
-
if (await verifyCandidate(msg)) return publicKey;
|
|
1344
|
-
const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
|
|
1345
|
-
if (normalized !== msg && await verifyCandidate(normalized)) return publicKey;
|
|
1346
|
-
if (fetchedKey.cached) {
|
|
1347
|
-
logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
|
|
1348
|
-
keyId: proof.verificationMethodId.href,
|
|
1349
|
-
proof
|
|
1350
|
-
});
|
|
1351
|
-
return await verifyProofInternal(jsonLd, proof, {
|
|
1352
|
-
...options,
|
|
1353
|
-
keyCache: {
|
|
1354
|
-
get: () => Promise.resolve(void 0),
|
|
1355
|
-
set: async (keyId, key) => await options.keyCache?.set(keyId, key)
|
|
1356
|
-
}
|
|
1357
|
-
});
|
|
1358
|
-
}
|
|
1359
|
-
logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
|
|
1360
|
-
keyId: proof.verificationMethodId.href,
|
|
1361
|
-
proof
|
|
1362
|
-
});
|
|
1363
|
-
return null;
|
|
1364
|
-
}
|
|
1365
|
-
/**
|
|
1366
|
-
* Verifies the given object. It will verify all the proofs in the object,
|
|
1367
|
-
* and succeed only if all the proofs are valid and all attributions and
|
|
1368
|
-
* actors are authenticated by the proofs.
|
|
1369
|
-
* @template T The type of the object to verify.
|
|
1370
|
-
* @param cls The class of the object to verify. It must be a subclass of
|
|
1371
|
-
* the {@link Object}.
|
|
1372
|
-
* @param jsonLd The JSON-LD object to verify. It's assumed that the object
|
|
1373
|
-
* is a compacted JSON-LD representation of a `T` with `@context`.
|
|
1374
|
-
* @param options Additional options. See also {@link VerifyObjectOptions}.
|
|
1375
|
-
* @returns The object if it's verified, or `null` if it's not.
|
|
1376
|
-
* @throws {TypeError} If the object is invalid or unsupported.
|
|
1377
|
-
* @since 0.10.0
|
|
1378
|
-
*/
|
|
1379
|
-
async function verifyObject(cls, jsonLd, options = {}) {
|
|
1380
|
-
const logger = getLogger([
|
|
1381
|
-
"fedify",
|
|
1382
|
-
"sig",
|
|
1383
|
-
"proof"
|
|
1384
|
-
]);
|
|
1385
|
-
const object = await cls.fromJsonLd(jsonLd, options);
|
|
1386
|
-
const attributions = new Set(object.attributionIds.map((uri) => uri.href));
|
|
1387
|
-
if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
|
|
1388
|
-
for await (const proof of object.getProofs(options)) {
|
|
1389
|
-
const key = await verifyProof(jsonLd, proof, options);
|
|
1390
|
-
if (key === null) return null;
|
|
1391
|
-
if (proof.verificationMethodId == null) return null;
|
|
1392
|
-
if (key.controllerId == null) {
|
|
1393
|
-
logger.debug("Key {keyId} does not have a controller.", { keyId: key.id?.href });
|
|
1394
|
-
continue;
|
|
1395
|
-
}
|
|
1396
|
-
deleteAuthenticatedAttribution(attributions, key.controllerId, proof.verificationMethodId);
|
|
1397
|
-
}
|
|
1398
|
-
if (attributions.size > 0) {
|
|
1399
|
-
logger.debug("Some attributions are not authenticated by the proofs: {attributions}.", { attributions: [...attributions] });
|
|
1400
|
-
return null;
|
|
1401
|
-
}
|
|
1402
|
-
return object;
|
|
1403
|
-
}
|
|
1404
|
-
function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
|
|
1405
|
-
const controllerHasCryptographicOrigin = hasCryptographicOrigin(controllerId.href);
|
|
1406
|
-
const verificationMethodMatchesController = controllerHasCryptographicOrigin && hasCryptographicOrigin(verificationMethodId.href) && haveSameFe34Origin(controllerId, verificationMethodId);
|
|
1407
|
-
if (!controllerHasCryptographicOrigin || verificationMethodMatchesController) attributions.delete(controllerId.href);
|
|
1408
|
-
if (!verificationMethodMatchesController) return;
|
|
1409
|
-
for (const attribution of [...attributions]) if (hasCryptographicOrigin(attribution) && haveSameFe34Origin(controllerId, attribution)) attributions.delete(attribution);
|
|
1410
|
-
}
|
|
1411
|
-
function hasCryptographicOrigin(iri) {
|
|
1412
|
-
return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
|
|
1413
|
-
}
|
|
1414
|
-
//#endregion
|
|
1415
|
-
export { verifySignature as C, verifyJsonLd as S, hasSignatureLike as _, verifyProof as a, signJsonLd as b, getKeyOwner as c, attachSignature as d, compactJsonLd as f, hasSignature as g, getNormalizationContextLoader as h, verifyObject as i, InvalidContextReferenceError as l, detachSignature as m, hasProofLike as n, normalizeOutgoingActivityJsonLd as o, createSignature as p, signObject as r, doesActorOwnKey as s, createProof as t, assertSafeJsonLd as u, isClearlyMalformedContextReference as v, wrapContextLoaderForJsonLd as w, verifyCompactJsonLd as x, isInvalidUrlTypeError as y };
|