@fedify/fedify 2.5.0-dev.2664 → 2.5.0-dev.2710
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/compat/mod.d.cts +1 -1
- package/dist/compat/mod.d.ts +1 -1
- package/dist/{context-xrqq4Hrq.d.ts → context-CuLvR1Os.d.ts} +2 -2
- package/dist/{context-C1NqcIct.d.cts → context-apq0IBg2.d.cts} +2 -2
- package/dist/federation/mod.cjs +1 -1
- package/dist/federation/mod.d.cts +3 -3
- package/dist/federation/mod.d.ts +3 -3
- package/dist/federation/mod.js +1 -1
- package/dist/{federation-FbwcnRHg.cjs → federation-JvzYDx0P.cjs} +5 -5
- package/dist/{http-DbvOPsFZ.cjs → http-BG5cDmTS.cjs} +1 -1
- package/dist/{http-CWn0K5jD.js → http-MUf125Jc.js} +1 -1
- package/dist/{key-dwwAg5bA.d.ts → key-BZw-YiK5.d.ts} +2 -2
- package/dist/{key-DlHT4R6k.d.cts → key-D5fbQkKM.d.cts} +2 -2
- package/dist/{kv-cache-B-fOrhb-.cjs → kv-cache-A2po7h0_.cjs} +1 -1
- package/dist/{kv-cache-BC837EqC.js → kv-cache-CbWc1BZA.js} +1 -1
- package/dist/{ld-CWVpo_NM.d.cts → ld-DEi9ERHf.d.cts} +1 -1
- package/dist/{ld-o4LnhCYY.d.ts → ld-DlC78ioJ.d.ts} +1 -1
- package/dist/{middleware-n2UrG62B.js → middleware-DzzdJ7Wz.js} +5 -5
- package/dist/{mod-D22ZsiKi.d.ts → mod-BJRtsw7l.d.ts} +1 -1
- package/dist/{mod-C1nT74IG.d.cts → mod-BamwZjJx.d.cts} +1 -1
- package/dist/{mod-DO0epJGH.d.ts → mod-BkTi19dI.d.ts} +1 -1
- package/dist/{mod-CQC9xlLZ.d.ts → mod-CMtF0VVy.d.ts} +1 -1
- package/dist/{mod-YvA4Rk8J.d.cts → mod-D2Z9MiCm.d.cts} +1 -1
- package/dist/{mod-TwiQgEf3.d.cts → mod-DB2NOzQF.d.cts} +1 -1
- package/dist/mod.cjs +4 -4
- package/dist/mod.d.cts +6 -6
- package/dist/mod.d.ts +6 -6
- package/dist/mod.js +4 -4
- package/dist/{portable-collection-DQhIkX5a.js → portable-collection-CAer9RWN.js} +1 -1
- package/dist/{portable-collection-DseoiPPj.cjs → portable-collection-d8w7TCn9.cjs} +1 -1
- 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/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 +22 -9
- package/skills/fedify/SKILL.md +10 -0
- package/dist/accept-CPVqki78.mjs +0 -145
- package/dist/activity-listener-CELFAodc.mjs +0 -44
- package/dist/assert-D1Eafmd_.mjs +0 -23
- package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
- package/dist/assert_exists-cffSpJ7X.mjs +0 -28
- package/dist/assert_false-CPdRnc3E.mjs +0 -23
- package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
- package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
- package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
- package/dist/assert_rejects-CTptdYck.mjs +0 -39
- package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
- package/dist/assert_throws-BYITOvPO.mjs +0 -74
- package/dist/assertion_error-B-cx0fFA.mjs +0 -31
- package/dist/audience-CHQ-FlLD.mjs +0 -95
- package/dist/builder-CGJ-NXcZ.mjs +0 -911
- package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
- package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
- package/dist/client-5SIFzW3q.mjs +0 -441
- package/dist/codec-C6rTrpIp.mjs +0 -147
- package/dist/collection-CnnP1UAv.mjs +0 -44
- package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
- package/dist/compat/outgoing-jsonld.test.mjs +0 -257
- package/dist/compat/public-audience.test.d.mts +0 -2
- package/dist/compat/public-audience.test.mjs +0 -187
- package/dist/compat/secured-document.test.d.mts +0 -2
- package/dist/compat/secured-document.test.mjs +0 -58
- package/dist/compat/transformers.test.d.mts +0 -2
- package/dist/compat/transformers.test.mjs +0 -62
- package/dist/compound-proof-CnzwOddk.mjs +0 -1019
- package/dist/context-LgGFFSz7.mjs +0 -146
- package/dist/deno-eoFpPk7W.mjs +0 -8
- package/dist/dist-_geWsuaI.mjs +0 -189
- package/dist/docloader-DwkipyL1.mjs +0 -136
- package/dist/esm-BHXXx4Wx.mjs +0 -1233
- package/dist/exporter-DVG68ozH.mjs +0 -263
- package/dist/federation/audience.test.d.mts +0 -2
- package/dist/federation/audience.test.mjs +0 -130
- package/dist/federation/builder.test.d.mts +0 -2
- package/dist/federation/builder.test.mjs +0 -396
- package/dist/federation/circuit-breaker.test.d.mts +0 -2
- package/dist/federation/circuit-breaker.test.mjs +0 -1277
- package/dist/federation/collection.test.d.mts +0 -2
- package/dist/federation/collection.test.mjs +0 -21
- package/dist/federation/compound-fanout.test.d.mts +0 -2
- package/dist/federation/compound-fanout.test.mjs +0 -231
- package/dist/federation/handler-compound-proof.test.d.mts +0 -2
- package/dist/federation/handler-compound-proof.test.mjs +0 -384
- package/dist/federation/handler.test.d.mts +0 -2
- package/dist/federation/handler.test.mjs +0 -5445
- package/dist/federation/hashlink-media.test.d.mts +0 -2
- package/dist/federation/hashlink-media.test.mjs +0 -422
- package/dist/federation/idempotency.test.d.mts +0 -2
- package/dist/federation/idempotency.test.mjs +0 -207
- package/dist/federation/inbox-actorless.test.d.mts +0 -2
- package/dist/federation/inbox-actorless.test.mjs +0 -522
- package/dist/federation/inbox-authentication.test.d.mts +0 -2
- package/dist/federation/inbox-authentication.test.mjs +0 -220
- package/dist/federation/inbox-report.test.d.mts +0 -2
- package/dist/federation/inbox-report.test.mjs +0 -719
- package/dist/federation/inbox-view.test.d.mts +0 -2
- package/dist/federation/inbox-view.test.mjs +0 -369
- package/dist/federation/inbox.test.d.mts +0 -2
- package/dist/federation/inbox.test.mjs +0 -139
- package/dist/federation/keycache.test.d.mts +0 -2
- package/dist/federation/keycache.test.mjs +0 -337
- package/dist/federation/kv.test.d.mts +0 -2
- package/dist/federation/kv.test.mjs +0 -88
- package/dist/federation/metrics.test.d.mts +0 -2
- package/dist/federation/metrics.test.mjs +0 -634
- package/dist/federation/middleware.test.d.mts +0 -2
- package/dist/federation/middleware.test.mjs +0 -9314
- package/dist/federation/mq.test.d.mts +0 -2
- package/dist/federation/mq.test.mjs +0 -591
- package/dist/federation/negotiation.test.d.mts +0 -2
- package/dist/federation/negotiation.test.mjs +0 -18
- package/dist/federation/outbound-body.test.d.mts +0 -2
- package/dist/federation/outbound-body.test.mjs +0 -149
- package/dist/federation/outbound-capture.test.d.mts +0 -2
- package/dist/federation/outbound-capture.test.mjs +0 -394
- package/dist/federation/outbound-dispatch.test.d.mts +0 -2
- package/dist/federation/outbound-dispatch.test.mjs +0 -368
- package/dist/federation/outbound-document.test.d.mts +0 -2
- package/dist/federation/outbound-document.test.mjs +0 -171
- package/dist/federation/outbound-provenance.test.d.mts +0 -2
- package/dist/federation/outbound-provenance.test.mjs +0 -543
- package/dist/federation/outbound-report.test.d.mts +0 -2
- package/dist/federation/outbound-report.test.mjs +0 -5475
- package/dist/federation/outbound-workers.test.d.mts +0 -2
- package/dist/federation/outbound-workers.test.mjs +0 -64
- package/dist/federation/outbound-workflow.test.d.mts +0 -2
- package/dist/federation/outbound-workflow.test.mjs +0 -154
- package/dist/federation/outgoing-proof.test.d.mts +0 -2
- package/dist/federation/outgoing-proof.test.mjs +0 -933
- package/dist/federation/portable-actor.test.d.mts +0 -2
- package/dist/federation/portable-actor.test.mjs +0 -496
- package/dist/federation/portable-chain.test.d.mts +0 -2
- package/dist/federation/portable-chain.test.mjs +0 -370
- package/dist/federation/portable-collection.test.d.mts +0 -2
- package/dist/federation/portable-collection.test.mjs +0 -832
- package/dist/federation/portable-delivery.test.d.mts +0 -2
- package/dist/federation/portable-delivery.test.mjs +0 -845
- package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
- package/dist/federation/portable-gateway-keys.test.mjs +0 -692
- package/dist/federation/portable-inbox.test.d.mts +0 -2
- package/dist/federation/portable-inbox.test.mjs +0 -1960
- package/dist/federation/portable-parse-uri.test.d.mts +0 -2
- package/dist/federation/portable-parse-uri.test.mjs +0 -348
- package/dist/federation/portable-route-activity.test.d.mts +0 -2
- package/dist/federation/portable-route-activity.test.mjs +0 -259
- package/dist/federation/portable.test.d.mts +0 -2
- package/dist/federation/portable.test.mjs +0 -1072
- package/dist/federation/retry.test.d.mts +0 -2
- package/dist/federation/retry.test.mjs +0 -42
- package/dist/federation/router.test.d.mts +0 -2
- package/dist/federation/router.test.mjs +0 -123
- package/dist/federation/send.test.d.mts +0 -2
- package/dist/federation/send.test.mjs +0 -1421
- package/dist/federation/tasks/codec.test.d.mts +0 -2
- package/dist/federation/tasks/codec.test.mjs +0 -302
- package/dist/federation/tasks/enqueue.test.d.mts +0 -2
- package/dist/federation/tasks/enqueue.test.mjs +0 -1095
- package/dist/federation/tasks/tasks.test.d.mts +0 -2
- package/dist/federation/tasks/tasks.test.mjs +0 -1229
- package/dist/federation/temporal.test.d.mts +0 -2
- package/dist/federation/temporal.test.mjs +0 -71
- package/dist/federation/webfinger.test.d.mts +0 -2
- package/dist/federation/webfinger.test.mjs +0 -944
- package/dist/http-l1zKGCll.mjs +0 -1449
- package/dist/inbox-CWX3EBTO.mjs +0 -399
- package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
- package/dist/inbox-view-DkPCF71K.mjs +0 -385
- package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
- package/dist/keycache-N2opu4-3.mjs +0 -221
- package/dist/keys-DIJNHW-Y.mjs +0 -120
- package/dist/kv-DBRWVx3Q.mjs +0 -104
- package/dist/kv-DCHkaJ9-.mjs +0 -92
- package/dist/kv-cache-8eJh4Xum.mjs +0 -121
- package/dist/ld-Cdt8qD-r.mjs +0 -1752
- package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
- package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
- package/dist/metrics-BnfvSPj9.mjs +0 -818
- package/dist/middleware-CwnXJze2.mjs +0 -5
- package/dist/middleware-D_W_LdJN.mjs +0 -9971
- package/dist/mq-eF96QxUT.mjs +0 -288
- package/dist/negotiation-BAKO9nih.mjs +0 -96
- package/dist/nodeinfo/client.test.d.mts +0 -2
- package/dist/nodeinfo/client.test.mjs +0 -1364
- package/dist/nodeinfo/handler.test.d.mts +0 -2
- package/dist/nodeinfo/handler.test.mjs +0 -94
- package/dist/nodeinfo/types.test.d.mts +0 -2
- package/dist/nodeinfo/types.test.mjs +0 -192
- package/dist/otel/exporter.test.d.mts +0 -2
- package/dist/otel/exporter.test.mjs +0 -887
- package/dist/outbound-body-CckPA5gc.mjs +0 -83
- package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
- package/dist/outbound-document-BMgwLXTY.mjs +0 -179
- package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
- package/dist/owner-DukEQnv3.mjs +0 -267
- package/dist/portable-collection-OHaqa11n.mjs +0 -418
- package/dist/portable-key-BkOLJxVz.mjs +0 -549
- package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
- package/dist/proof-Y7omSVvc.mjs +0 -1420
- package/dist/public-audience--klBIOk1.mjs +0 -197
- package/dist/retry-zX5xw5e0.mjs +0 -34
- package/dist/router-u5O5KCQr.mjs +0 -156
- package/dist/secured-document-CxzZZ9nL.mjs +0 -35
- package/dist/send-ccQynabr.mjs +0 -710
- package/dist/sig/accept.test.d.mts +0 -2
- package/dist/sig/accept.test.mjs +0 -416
- package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
- package/dist/sig/compound-proof-discovery.test.mjs +0 -331
- package/dist/sig/compound-proof-producer.test.d.mts +0 -2
- package/dist/sig/compound-proof-producer.test.mjs +0 -107
- package/dist/sig/compound-proof-verification.test.d.mts +0 -2
- package/dist/sig/compound-proof-verification.test.mjs +0 -1017
- package/dist/sig/compound-proof.test.d.mts +0 -2
- package/dist/sig/compound-proof.test.mjs +0 -411
- package/dist/sig/http.test.d.mts +0 -2
- package/dist/sig/http.test.mjs +0 -3328
- package/dist/sig/key-owner-evidence.test.d.mts +0 -2
- package/dist/sig/key-owner-evidence.test.mjs +0 -100
- package/dist/sig/key.test.d.mts +0 -2
- package/dist/sig/key.test.mjs +0 -1250
- package/dist/sig/ld.test.d.mts +0 -2
- package/dist/sig/ld.test.mjs +0 -1044
- package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
- package/dist/sig/mitra-receive-interop.test.mjs +0 -260
- package/dist/sig/mitra-send-interop.test.d.mts +0 -2
- package/dist/sig/mitra-send-interop.test.mjs +0 -461
- package/dist/sig/owner.test.d.mts +0 -2
- package/dist/sig/owner.test.mjs +0 -202
- package/dist/sig/portable-collection.test.d.mts +0 -2
- package/dist/sig/portable-collection.test.mjs +0 -697
- package/dist/sig/portable-interop.test.d.mts +0 -2
- package/dist/sig/portable-interop.test.mjs +0 -156
- package/dist/sig/portable-key-id.test.d.mts +0 -2
- package/dist/sig/portable-key-id.test.mjs +0 -67
- package/dist/sig/portable-key.test.d.mts +0 -2
- package/dist/sig/portable-key.test.mjs +0 -1438
- package/dist/sig/proof.test.d.mts +0 -2
- package/dist/sig/proof.test.mjs +0 -2638
- package/dist/sig/tootik-request-interop.test.d.mts +0 -2
- package/dist/sig/tootik-request-interop.test.mjs +0 -190
- package/dist/sig/tootik-send-interop.test.d.mts +0 -2
- package/dist/sig/tootik-send-interop.test.mjs +0 -331
- package/dist/sig/verification.test.d.mts +0 -2
- package/dist/sig/verification.test.mjs +0 -310
- package/dist/std__assert-DvMDRPes.mjs +0 -8
- package/dist/tasks-BCUmQbbz.mjs +0 -77
- package/dist/temporal-f_K4lAVR.mjs +0 -95
- package/dist/testing/context.test.d.mts +0 -2
- package/dist/testing/context.test.mjs +0 -19
- package/dist/testing/kv.test.d.mts +0 -2
- package/dist/testing/kv.test.mjs +0 -101
- package/dist/testing/mod.d.mts +0 -6099
- package/dist/testing/mod.mjs +0 -9
- package/dist/testing-vrnD5Uaa.mjs +0 -8
- package/dist/types-DE_LV1JB.mjs +0 -46
- package/dist/utils/docloader.test.d.mts +0 -2
- package/dist/utils/docloader.test.mjs +0 -1076
- package/dist/utils/kv-cache.test.d.mts +0 -2
- package/dist/utils/kv-cache.test.mjs +0 -261
- package/dist/verification-C3954hQh.mjs +0 -5
- package/dist/verification-Dpfcw8ml.mjs +0 -105
- package/dist/vocab/cjs.test.d.mts +0 -2
- package/dist/vocab/cjs.test.mjs +0 -27
package/dist/ld-Cdt8qD-r.mjs
DELETED
|
@@ -1,1752 +0,0 @@
|
|
|
1
|
-
import { Temporal } from "temporal-polyfill";
|
|
2
|
-
import "urlpattern-polyfill";
|
|
3
|
-
globalThis.addEventListener = () => {};
|
|
4
|
-
import { c as isPortableActorDocument, d as isPortableUri, l as isPortableId, m as parseKeyIdString, s as isCompatibleKeyId } from "./portable-key-id-Ca30-hOa.mjs";
|
|
5
|
-
import { a as verificationObservation, i as triedKey, n as observeCheck, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
|
|
6
|
-
import { n as version, t as name } from "./deno-eoFpPk7W.mjs";
|
|
7
|
-
import { _ as recordKeyLookup, n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch, t as classifyFetchError } from "./metrics-BnfvSPj9.mjs";
|
|
8
|
-
import { n as attachKeyOwnerEvidence, t as MAX_PORTABLE_KEY_TTL } from "./key-owner-evidence-APB6NpSk.mjs";
|
|
9
|
-
import { getLogger } from "@logtape/logtape";
|
|
10
|
-
import { Activity, CryptographicKey, Multikey, Object as Object$1, getTypeId, isActor } from "@fedify/vocab";
|
|
11
|
-
import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
12
|
-
import { FetchError, UrlError, getDocumentLoader, parseDidKeyVerificationMethod } from "@fedify/vocab-runtime";
|
|
13
|
-
import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
|
|
14
|
-
import { encodeHex } from "byte-encodings/hex";
|
|
15
|
-
import jsonld from "@fedify/vocab-runtime/jsonld";
|
|
16
|
-
//#region src/sig/key.ts
|
|
17
|
-
/** Classifies decoding failures without hiding unexpected loader errors. */
|
|
18
|
-
function classifyKeyJsonLdError(error, seen = /* @__PURE__ */ new Set()) {
|
|
19
|
-
if (!(error instanceof Error) || !error.name.startsWith("jsonld.")) return null;
|
|
20
|
-
if (seen.has(error)) throw error;
|
|
21
|
-
seen.add(error);
|
|
22
|
-
const details = error.details;
|
|
23
|
-
if (typeof details?.code !== "string") return null;
|
|
24
|
-
if (details.code !== "loading remote context failed" || !("cause" in details) && !("cause" in error)) return "invalid";
|
|
25
|
-
const cause = "cause" in details ? details.cause : error.cause;
|
|
26
|
-
const nestedFailure = classifyKeyJsonLdError(cause, seen);
|
|
27
|
-
if (nestedFailure != null) return nestedFailure;
|
|
28
|
-
if (cause instanceof SyntaxError) return "invalid";
|
|
29
|
-
if (cause instanceof FetchError || cause instanceof UrlError) return "fetch";
|
|
30
|
-
if (cause instanceof Error && [
|
|
31
|
-
"AbortError",
|
|
32
|
-
"TimeoutError",
|
|
33
|
-
"NetworkError"
|
|
34
|
-
].includes(cause.name)) return "fetch";
|
|
35
|
-
if (cause instanceof TypeError) {
|
|
36
|
-
const urlCode = cause.code;
|
|
37
|
-
if (cause.name === "InvalidContextReferenceError") return "invalid";
|
|
38
|
-
if (urlCode === "ERR_INVALID_URL" || cause.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(cause.message) || / cannot be parsed as a URL\.?$/.test(cause.message)) return typeof details.url === "string" && /^[A-Za-z][A-Za-z0-9+.-]*:/.test(details.url) && !URL.canParse(details.url) ? "invalid" : "fetch";
|
|
39
|
-
const networkCause = cause.cause;
|
|
40
|
-
const code = cause.code ?? networkCause?.code;
|
|
41
|
-
if (typeof code === "string" && [
|
|
42
|
-
"ECONNREFUSED",
|
|
43
|
-
"ECONNRESET",
|
|
44
|
-
"ECONNABORTED",
|
|
45
|
-
"ETIMEDOUT",
|
|
46
|
-
"EHOSTUNREACH",
|
|
47
|
-
"ENETUNREACH",
|
|
48
|
-
"ENOTFOUND",
|
|
49
|
-
"EAI_AGAIN",
|
|
50
|
-
"UND_ERR_CONNECT_TIMEOUT",
|
|
51
|
-
"UND_ERR_HEADERS_TIMEOUT",
|
|
52
|
-
"UND_ERR_BODY_TIMEOUT",
|
|
53
|
-
"UND_ERR_SOCKET"
|
|
54
|
-
].includes(code) || /^(fetch failed|Failed to fetch|error sending request|error reading a body from connection|Unable to connect|ConnectionRefused|Network connection lost|The socket connection was closed unexpectedly)/.test(cause.message)) return "fetch";
|
|
55
|
-
}
|
|
56
|
-
throw cause;
|
|
57
|
-
}
|
|
58
|
-
/** Carries a context transport failure through the key decoding boundary. */
|
|
59
|
-
var KeyContextFetchError = class extends Error {
|
|
60
|
-
error;
|
|
61
|
-
constructor(error) {
|
|
62
|
-
super("Failed to fetch a key's JSON-LD context.", { cause: error });
|
|
63
|
-
this.error = error;
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
function contextFetchError(error) {
|
|
67
|
-
const seen = /* @__PURE__ */ new Set();
|
|
68
|
-
while (error instanceof Error && !seen.has(error)) {
|
|
69
|
-
seen.add(error);
|
|
70
|
-
const details = error.details;
|
|
71
|
-
if (!error.name.startsWith("jsonld.") || details?.code !== "loading remote context failed") break;
|
|
72
|
-
error = "cause" in details ? details.cause : error.cause;
|
|
73
|
-
}
|
|
74
|
-
return new KeyContextFetchError(error);
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Checks if the given key is valid and supported. No-op if the key is valid,
|
|
78
|
-
* otherwise throws an error.
|
|
79
|
-
* @param key The key to check.
|
|
80
|
-
* @param type Which type of key to check. If not specified, the key can be
|
|
81
|
-
* either public or private.
|
|
82
|
-
* @throws {TypeError} If the key is invalid or unsupported.
|
|
83
|
-
*/
|
|
84
|
-
function validateCryptoKey(key, type) {
|
|
85
|
-
if (type != null && key.type !== type) throw new TypeError(`The key is not a ${type} key.`);
|
|
86
|
-
if (!key.extractable) throw new TypeError("The key is not extractable.");
|
|
87
|
-
if (key.algorithm.name !== "RSASSA-PKCS1-v1_5" && key.algorithm.name !== "Ed25519") throw new TypeError("Currently only RSASSA-PKCS1-v1_5 and Ed25519 keys are supported. More algorithms will be added in the future!");
|
|
88
|
-
if (key.algorithm.name === "RSASSA-PKCS1-v1_5") {
|
|
89
|
-
if (key.algorithm.hash.name !== "SHA-256") throw new TypeError("For compatibility with the existing Fediverse software (e.g., Mastodon), hash algorithm for RSASSA-PKCS1-v1_5 keys must be SHA-256.");
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Generates a key pair which is appropriate for Fedify.
|
|
94
|
-
* @param algorithm The algorithm to use. Currently only RSASSA-PKCS1-v1_5 and
|
|
95
|
-
* Ed25519 are supported.
|
|
96
|
-
* @returns The generated key pair.
|
|
97
|
-
* @throws {TypeError} If the algorithm is unsupported.
|
|
98
|
-
*/
|
|
99
|
-
function generateCryptoKeyPair(algorithm) {
|
|
100
|
-
if (algorithm == null) getLogger([
|
|
101
|
-
"fedify",
|
|
102
|
-
"sig",
|
|
103
|
-
"key"
|
|
104
|
-
]).warn("No algorithm specified. Using RSASSA-PKCS1-v1_5 by default, but it is recommended to specify the algorithm explicitly as the parameter will be required in the future.");
|
|
105
|
-
if (algorithm == null || algorithm === "RSASSA-PKCS1-v1_5") return crypto.subtle.generateKey({
|
|
106
|
-
name: "RSASSA-PKCS1-v1_5",
|
|
107
|
-
modulusLength: 4096,
|
|
108
|
-
publicExponent: new Uint8Array([
|
|
109
|
-
1,
|
|
110
|
-
0,
|
|
111
|
-
1
|
|
112
|
-
]),
|
|
113
|
-
hash: "SHA-256"
|
|
114
|
-
}, true, ["sign", "verify"]);
|
|
115
|
-
else if (algorithm === "Ed25519") return crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"]);
|
|
116
|
-
throw new TypeError("Unsupported algorithm: " + algorithm);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Exports a key in JWK format.
|
|
120
|
-
* @param key The key to export. Either public or private key.
|
|
121
|
-
* @returns The exported key in JWK format. The key is suitable for
|
|
122
|
-
* serialization and storage.
|
|
123
|
-
* @throws {TypeError} If the key is invalid or unsupported.
|
|
124
|
-
*/
|
|
125
|
-
async function exportJwk(key) {
|
|
126
|
-
validateCryptoKey(key);
|
|
127
|
-
const jwk = await crypto.subtle.exportKey("jwk", key);
|
|
128
|
-
if (jwk.crv === "Ed25519") jwk.alg = "Ed25519";
|
|
129
|
-
return jwk;
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Imports a key from JWK format.
|
|
133
|
-
* @param jwk The key in JWK format.
|
|
134
|
-
* @param type Which type of key to import, either `"public"` or `"private"`.
|
|
135
|
-
* @returns The imported key.
|
|
136
|
-
* @throws {TypeError} If the key is invalid or unsupported.
|
|
137
|
-
*/
|
|
138
|
-
async function importJwk(jwk, type) {
|
|
139
|
-
let key;
|
|
140
|
-
if (jwk.kty === "RSA" && jwk.alg === "RS256") key = await crypto.subtle.importKey("jwk", jwk, {
|
|
141
|
-
name: "RSASSA-PKCS1-v1_5",
|
|
142
|
-
hash: "SHA-256"
|
|
143
|
-
}, true, type === "public" ? ["verify"] : ["sign"]);
|
|
144
|
-
else if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
|
|
145
|
-
if (navigator?.userAgent === "Cloudflare-Workers") {
|
|
146
|
-
jwk = { ...jwk };
|
|
147
|
-
delete jwk.alg;
|
|
148
|
-
}
|
|
149
|
-
key = await crypto.subtle.importKey("jwk", jwk, "Ed25519", true, type === "public" ? ["verify"] : ["sign"]);
|
|
150
|
-
} else throw new TypeError("Unsupported JWK format.");
|
|
151
|
-
validateCryptoKey(key, type);
|
|
152
|
-
return key;
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
|
-
* Fetches the document that the given actor URI dereferences to, and returns
|
|
156
|
-
* the actor only if the host that served the document is authoritative for
|
|
157
|
-
* the id the document claims, and that id is the actor that was asked for.
|
|
158
|
-
*
|
|
159
|
-
* Only the origin that serves an actor id can speak for it. Without that
|
|
160
|
-
* rule any host could serve a document describing somebody else's actor—and
|
|
161
|
-
* listing its own keys as that actor's.
|
|
162
|
-
*
|
|
163
|
-
* The returned actor always has exactly the requested `actorId` as its `id`.
|
|
164
|
-
* A document loader follows redirects and alternate document links, so the
|
|
165
|
-
* document an actor id leads to may describe a different actor altogether,
|
|
166
|
-
* on the same origin or on another; accepting it would attribute that other
|
|
167
|
-
* actor's keys to the requested one. See GHSA-8863-8468-7hq7.
|
|
168
|
-
*
|
|
169
|
-
* @param actorId The URI of the actor to fetch.
|
|
170
|
-
* @param options Options for fetching the document.
|
|
171
|
-
* @returns The actor, or `null` if the document cannot be fetched, is not an
|
|
172
|
-
* actor, belongs to another origin, or describes an actor other
|
|
173
|
-
* than the requested one.
|
|
174
|
-
* @internal
|
|
175
|
-
*/
|
|
176
|
-
async function fetchActorDocument(actorId, options = {}) {
|
|
177
|
-
return await fetchActorDocumentInternal(actorId, options, false);
|
|
178
|
-
}
|
|
179
|
-
async function fetchActorDocumentInternal(actorId, options, propagateContextFetchErrors) {
|
|
180
|
-
const logger = getLogger([
|
|
181
|
-
"fedify",
|
|
182
|
-
"sig",
|
|
183
|
-
"key"
|
|
184
|
-
]);
|
|
185
|
-
if (isPortableId(actorId)) {
|
|
186
|
-
logger.debug("The actor {actorId} is a portable actor, which is not authenticated by the web origin that serves it.", { actorId: actorId.href });
|
|
187
|
-
return null;
|
|
188
|
-
}
|
|
189
|
-
const documentLoader = options.documentLoader ?? getDocumentLoader();
|
|
190
|
-
const contextLoader = options.contextLoader ?? getDocumentLoader();
|
|
191
|
-
const { tracerProvider } = options;
|
|
192
|
-
let document;
|
|
193
|
-
let documentUrl = actorId;
|
|
194
|
-
try {
|
|
195
|
-
const remoteDocument = await documentLoader(actorId.href);
|
|
196
|
-
document = remoteDocument.document;
|
|
197
|
-
documentUrl = new URL(remoteDocument.documentUrl ?? "", actorId);
|
|
198
|
-
} catch (error) {
|
|
199
|
-
logger.debug("Failed to fetch the actor {actorId}: {error}", {
|
|
200
|
-
actorId: actorId.href,
|
|
201
|
-
error
|
|
202
|
-
});
|
|
203
|
-
if (propagateContextFetchErrors) throw new KeyContextFetchError(error);
|
|
204
|
-
return null;
|
|
205
|
-
}
|
|
206
|
-
let object;
|
|
207
|
-
try {
|
|
208
|
-
object = await Object$1.fromJsonLd(document, {
|
|
209
|
-
documentLoader,
|
|
210
|
-
contextLoader,
|
|
211
|
-
tracerProvider,
|
|
212
|
-
baseUrl: documentUrl
|
|
213
|
-
});
|
|
214
|
-
} catch (error) {
|
|
215
|
-
const failure = classifyKeyJsonLdError(error);
|
|
216
|
-
if (failure === "fetch" && propagateContextFetchErrors) throw contextFetchError(error);
|
|
217
|
-
if (failure == null && !(error instanceof TypeError)) throw error;
|
|
218
|
-
logger.debug("Failed to decode the actor document at {documentUrl}: {error}", {
|
|
219
|
-
documentUrl: documentUrl.href,
|
|
220
|
-
failure: failure ?? "invalid",
|
|
221
|
-
error
|
|
222
|
-
});
|
|
223
|
-
return null;
|
|
224
|
-
}
|
|
225
|
-
if (!isActor(object)) return null;
|
|
226
|
-
if (object.id != null && isPortableId(object.id)) {
|
|
227
|
-
logger.debug("The document served at {documentUrl} claims to be the portable actor {actorId}, which is not authenticated by the web origin that serves it.", {
|
|
228
|
-
documentUrl: documentUrl.href,
|
|
229
|
-
actorId: object.id?.href
|
|
230
|
-
});
|
|
231
|
-
return null;
|
|
232
|
-
}
|
|
233
|
-
if (object.id == null || object.id.origin !== documentUrl.origin) {
|
|
234
|
-
logger.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as that actor's document.", {
|
|
235
|
-
documentUrl: documentUrl.href,
|
|
236
|
-
actorId: object.id?.href
|
|
237
|
-
});
|
|
238
|
-
return null;
|
|
239
|
-
}
|
|
240
|
-
if (object.id.href !== actorId.href) {
|
|
241
|
-
logger.debug("The document fetched for the actor {actorId} is the actor {documentActorId} instead; refusing to treat it as the requested actor's document.", {
|
|
242
|
-
actorId: actorId.href,
|
|
243
|
-
documentActorId: object.id.href
|
|
244
|
-
});
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
return object;
|
|
248
|
-
}
|
|
249
|
-
/**
|
|
250
|
-
* Resolves the owner that the given key claims, and returns it only if the
|
|
251
|
-
* claim holds.
|
|
252
|
-
*
|
|
253
|
-
* The `owner` of a {@link CryptographicKey}, like the `controller` of
|
|
254
|
-
* a {@link Multikey}, proves nothing on its own: the key document and the
|
|
255
|
-
* claim inside it are served by the same host, so anyone able to serve a key
|
|
256
|
-
* document can name any actor in the world as its owner. The claim becomes
|
|
257
|
-
* meaningful only once the named actor's own document is fetched and turns
|
|
258
|
-
* out to link back to the key. This function performs that mutual-link
|
|
259
|
-
* check, which is the only sound way to learn a fetched key's owner.
|
|
260
|
-
*
|
|
261
|
-
* The claimed owner is always dereferenced, never read out of the key
|
|
262
|
-
* document: an owner embedded there is written by whoever wrote the key.
|
|
263
|
-
*
|
|
264
|
-
* @param key The key whose ownership claim is to be verified. It must carry
|
|
265
|
-
* an `id`, as that is what the owner has to link back to.
|
|
266
|
-
* @param options Options for fetching the claimed owner.
|
|
267
|
-
* @returns The verified owner, or `null` if the key claims no owner, the
|
|
268
|
-
* owner cannot be fetched, or the owner does not link back to
|
|
269
|
-
* the key.
|
|
270
|
-
* @internal
|
|
271
|
-
*/
|
|
272
|
-
async function verifyKeyOwnership(key, options = {}) {
|
|
273
|
-
return await verifyKeyOwnershipInternal(key, options, false);
|
|
274
|
-
}
|
|
275
|
-
async function verifyKeyOwnershipInternal(key, options, propagateContextFetchErrors) {
|
|
276
|
-
const logger = getLogger([
|
|
277
|
-
"fedify",
|
|
278
|
-
"sig",
|
|
279
|
-
"key"
|
|
280
|
-
]);
|
|
281
|
-
const keyId = key.id;
|
|
282
|
-
if (keyId == null) return null;
|
|
283
|
-
const claimedOwnerId = key instanceof CryptographicKey ? key.ownerId : key.controllerId;
|
|
284
|
-
if (claimedOwnerId == null) return null;
|
|
285
|
-
const owner = await fetchActorDocumentInternal(claimedOwnerId, options, propagateContextFetchErrors);
|
|
286
|
-
if (owner == null) {
|
|
287
|
-
logger.debug("The owner ({claimedOwnerId}) that key {keyId} claims could not be resolved.", {
|
|
288
|
-
keyId: keyId.href,
|
|
289
|
-
claimedOwnerId: claimedOwnerId.href
|
|
290
|
-
});
|
|
291
|
-
return null;
|
|
292
|
-
}
|
|
293
|
-
const linkedKeyIds = key instanceof CryptographicKey ? owner.publicKeyIds : owner.assertionMethodIds;
|
|
294
|
-
for (const linkedKeyId of linkedKeyIds) if (linkedKeyId.href === keyId.href) return owner;
|
|
295
|
-
logger.debug("The owner ({claimedOwnerId}) that key {keyId} claims does not list the key as its own.", {
|
|
296
|
-
keyId: keyId.href,
|
|
297
|
-
claimedOwnerId: claimedOwnerId.href
|
|
298
|
-
});
|
|
299
|
-
return null;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Wraps a key cache so that lookups through the wrapper miss, while
|
|
303
|
-
* whatever they resolve is still written to the cache. It is used to retry
|
|
304
|
-
* a verification that failed with a cached key with a freshly fetched one.
|
|
305
|
-
* @param keyCache The key cache to wrap.
|
|
306
|
-
* @returns The wrapped key cache.
|
|
307
|
-
* @internal
|
|
308
|
-
*/
|
|
309
|
-
function bypassKeyCacheReads(keyCache) {
|
|
310
|
-
const cache = keyCache;
|
|
311
|
-
const bypassed = {
|
|
312
|
-
get: () => Promise.resolve(void 0),
|
|
313
|
-
set: async (keyId, key) => await cache?.set(keyId, key),
|
|
314
|
-
getFetchError: () => Promise.resolve(void 0),
|
|
315
|
-
setFetchError: async (keyId, error) => await cache?.setFetchError?.(keyId, error)
|
|
316
|
-
};
|
|
317
|
-
if (cache?.compatibleKeyScope != null) bypassed.compatibleKeyScope = (scope) => {
|
|
318
|
-
const scoped = cache.compatibleKeyScope(scope);
|
|
319
|
-
return {
|
|
320
|
-
get: () => Promise.resolve(void 0),
|
|
321
|
-
getEntry: () => Promise.resolve(void 0),
|
|
322
|
-
set: async (keyId, key, options) => await scoped.set(keyId, key, options),
|
|
323
|
-
delete: async (keyId) => await scoped.delete(keyId)
|
|
324
|
-
};
|
|
325
|
-
};
|
|
326
|
-
return bypassed;
|
|
327
|
-
}
|
|
328
|
-
/**
|
|
329
|
-
* Parses a key ID given as a string. Unlike `new URL()`, it accepts `ap:`
|
|
330
|
-
* and `ap+ef61:` URIs, and refuses a portable or compatible key ID whose
|
|
331
|
-
* identity URL parsing would change, e.g., by resolving dot segments.
|
|
332
|
-
* @throws {TypeError} If the key ID is invalid.
|
|
333
|
-
*/
|
|
334
|
-
function parseKeyIdOrThrow(keyId) {
|
|
335
|
-
const parsed = parseKeyIdString(keyId);
|
|
336
|
-
if (parsed == null) throw new TypeError(`Invalid key ID: ${keyId}`);
|
|
337
|
-
return parsed;
|
|
338
|
-
}
|
|
339
|
-
async function withFetchKeySpan(keyId, tracerProvider, fetcher) {
|
|
340
|
-
tracerProvider ??= trace.getTracerProvider();
|
|
341
|
-
return await tracerProvider.getTracer(name, version).startActiveSpan("activitypub.fetch_key", {
|
|
342
|
-
kind: SpanKind.CLIENT,
|
|
343
|
-
attributes: {
|
|
344
|
-
"http.method": "GET",
|
|
345
|
-
"url.full": keyId.href,
|
|
346
|
-
"url.scheme": keyId.protocol.replace(/:$/, ""),
|
|
347
|
-
"url.domain": keyId.hostname,
|
|
348
|
-
"url.path": keyId.pathname,
|
|
349
|
-
"url.query": keyId.search.replace(/^\?/, ""),
|
|
350
|
-
"url.fragment": keyId.hash.replace(/^#/, "")
|
|
351
|
-
}
|
|
352
|
-
}, async (span) => {
|
|
353
|
-
try {
|
|
354
|
-
const result = await fetcher();
|
|
355
|
-
span.setAttribute("activitypub.actor.key.cached", result.cached);
|
|
356
|
-
return result;
|
|
357
|
-
} catch (e) {
|
|
358
|
-
span.setStatus({
|
|
359
|
-
code: SpanStatusCode.ERROR,
|
|
360
|
-
message: String(e)
|
|
361
|
-
});
|
|
362
|
-
throw e;
|
|
363
|
-
} finally {
|
|
364
|
-
span.end();
|
|
365
|
-
}
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* Fetches a {@link CryptographicKey} or {@link Multikey} from the given URL.
|
|
370
|
-
* If the given URL contains an {@link Actor} object, it tries to find
|
|
371
|
-
* the corresponding key in the `publicKey` or `assertionMethod` property. *
|
|
372
|
-
* Gateway keys of [FEP-ef61] portable actors, i.e., keys whose IDs are
|
|
373
|
-
* compatible identifiers that dereference to portable actor documents, are
|
|
374
|
-
* not resolved by this function, as they only authenticate HTTP requests;
|
|
375
|
-
* use `verifyRequest()` or `getKeyOwner()` for them instead. Nor are keys
|
|
376
|
-
* of portable actors whose IDs are `ap:` or `ap+ef61:` URIs, for the same
|
|
377
|
-
* reason. Keys whose IDs are compatible identifiers or `ap:` or `ap+ef61:`
|
|
378
|
-
* URIs are never read from or written to the key cache under their IDs,
|
|
379
|
-
* except for failures to fetch them.
|
|
380
|
-
*
|
|
381
|
-
* [FEP-ef61]: https://w3id.org/fep/ef61
|
|
382
|
-
* @template T The type of the key to fetch. Either {@link CryptographicKey}
|
|
383
|
-
* or {@link Multikey}.
|
|
384
|
-
* @param keyId The URL of the key.
|
|
385
|
-
* @param cls The class of the key to fetch. Either {@link CryptographicKey}
|
|
386
|
-
* or {@link Multikey}.
|
|
387
|
-
* @param options Options for fetching the key. See {@link FetchKeyOptions}.
|
|
388
|
-
* @returns The fetched key or `null` if the key is not found.
|
|
389
|
-
* @since 1.3.0
|
|
390
|
-
*/
|
|
391
|
-
function fetchKey(keyId, cls, options = {}) {
|
|
392
|
-
keyId = typeof keyId === "string" ? parseKeyIdOrThrow(keyId) : keyId;
|
|
393
|
-
return withFetchKeySpan(keyId, options.tracerProvider, () => fetchKeyInternal(keyId, cls, options));
|
|
394
|
-
}
|
|
395
|
-
/**
|
|
396
|
-
* Fetches a {@link CryptographicKey} or {@link Multikey} from the given URL,
|
|
397
|
-
* preserving transport-level fetch failures for callers that need to inspect
|
|
398
|
-
* why the key could not be loaded. *
|
|
399
|
-
* Gateway keys of [FEP-ef61] portable actors, i.e., keys whose IDs are
|
|
400
|
-
* compatible identifiers that dereference to portable actor documents, are
|
|
401
|
-
* not resolved by this function, as they only authenticate HTTP requests;
|
|
402
|
-
* use `verifyRequest()` or `getKeyOwner()` for them instead. Nor are keys
|
|
403
|
-
* of portable actors whose IDs are `ap:` or `ap+ef61:` URIs, for the same
|
|
404
|
-
* reason. Keys whose IDs are compatible identifiers or `ap:` or `ap+ef61:`
|
|
405
|
-
* URIs are never read from or written to the key cache under their IDs,
|
|
406
|
-
* except for failures to fetch them.
|
|
407
|
-
*
|
|
408
|
-
* [FEP-ef61]: https://w3id.org/fep/ef61
|
|
409
|
-
*
|
|
410
|
-
* @template T The type of the key to fetch. Either {@link CryptographicKey}
|
|
411
|
-
* or {@link Multikey}.
|
|
412
|
-
* @param keyId The URL of the key.
|
|
413
|
-
* @param cls The class of the key to fetch. Either {@link CryptographicKey}
|
|
414
|
-
* or {@link Multikey}.
|
|
415
|
-
* @param options Options for fetching the key.
|
|
416
|
-
* @returns The fetched key, or detailed fetch failure information.
|
|
417
|
-
* @since 2.1.0
|
|
418
|
-
*/
|
|
419
|
-
async function fetchKeyDetailed(keyId, cls, options = {}) {
|
|
420
|
-
const cacheKey = typeof keyId === "string" ? parseKeyIdOrThrow(keyId) : keyId;
|
|
421
|
-
return await withFetchKeySpan(cacheKey, options.tracerProvider, async () => {
|
|
422
|
-
return await fetchKeyWithResult(cacheKey, cls, options, async (cacheKey, keyId, keyCache, logger) => {
|
|
423
|
-
const fetchError = await keyCache?.getFetchError?.(cacheKey);
|
|
424
|
-
if (fetchError != null) {
|
|
425
|
-
logger.debug("Entry {keyId} found in cache with preserved fetch failure details.", { keyId });
|
|
426
|
-
return {
|
|
427
|
-
key: null,
|
|
428
|
-
cached: true,
|
|
429
|
-
fetchError
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
logger.debug("Entry {keyId} found in cache, but no fetch failure details are available.", { keyId });
|
|
433
|
-
return {
|
|
434
|
-
key: null,
|
|
435
|
-
cached: true
|
|
436
|
-
};
|
|
437
|
-
}, async (error, cacheKey, keyId, keyCache, logger) => {
|
|
438
|
-
logger.debug("Failed to fetch key {keyId}.", {
|
|
439
|
-
keyId,
|
|
440
|
-
error
|
|
441
|
-
});
|
|
442
|
-
await keyCache?.set(cacheKey, null);
|
|
443
|
-
if (error instanceof FetchError && error.response != null) {
|
|
444
|
-
const fetchError = {
|
|
445
|
-
status: error.response.status,
|
|
446
|
-
response: error.response.clone()
|
|
447
|
-
};
|
|
448
|
-
await keyCache?.setFetchError?.(cacheKey, fetchError);
|
|
449
|
-
return {
|
|
450
|
-
key: null,
|
|
451
|
-
cached: false,
|
|
452
|
-
fetchError
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
const fetchError = { error: error instanceof Error ? error : new Error(String(error)) };
|
|
456
|
-
await keyCache?.setFetchError?.(cacheKey, fetchError);
|
|
457
|
-
return {
|
|
458
|
-
key: null,
|
|
459
|
-
cached: false,
|
|
460
|
-
fetchError
|
|
461
|
-
};
|
|
462
|
-
});
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
async function getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger) {
|
|
466
|
-
if (keyCache == null) return null;
|
|
467
|
-
const cachedKey = await keyCache.get(cacheKey);
|
|
468
|
-
const hit = checkCachedKeyHit(cachedKey, keyId, cls, logger);
|
|
469
|
-
if (hit != null) return hit;
|
|
470
|
-
if (cachedKey === null) {
|
|
471
|
-
logger.debug("Entry {keyId} found in cache, but it is unavailable.", { keyId });
|
|
472
|
-
return {
|
|
473
|
-
key: null,
|
|
474
|
-
cached: true
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
return null;
|
|
478
|
-
}
|
|
479
|
-
function checkCachedKeyHit(cachedKey, keyId, cls, logger) {
|
|
480
|
-
if (cachedKey instanceof cls && cachedKey.publicKey != null) {
|
|
481
|
-
logger.debug("Key {keyId} found in cache.", { keyId });
|
|
482
|
-
return {
|
|
483
|
-
key: cachedKey,
|
|
484
|
-
cached: true
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
return null;
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* Looks up a key at a compatible identifier, or at an `ap:` or `ap+ef61:`
|
|
491
|
-
* URI, in the cache namespace of a purpose, like {@link getCachedFetchKey}.
|
|
492
|
-
* A key that the verified document of its portable actor was cached with
|
|
493
|
-
* gets the actor's evidence attached from the same entry; see
|
|
494
|
-
* {@link attachKeyOwnerEvidence}.
|
|
495
|
-
*/
|
|
496
|
-
async function getCachedCompatibleKey(cacheKey, keyId, cls, scopedCache, logger) {
|
|
497
|
-
if (scopedCache?.getEntry == null) return await getCachedFetchKey(cacheKey, keyId, cls, scopedCache, logger);
|
|
498
|
-
const entry = await scopedCache.getEntry(cacheKey);
|
|
499
|
-
if (entry === void 0) return null;
|
|
500
|
-
if (entry === null) {
|
|
501
|
-
logger.debug("Entry {keyId} found in cache, but it is unavailable.", { keyId });
|
|
502
|
-
return {
|
|
503
|
-
key: null,
|
|
504
|
-
cached: true
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
const hit = checkCachedKeyHit(entry.key, keyId, cls, logger);
|
|
508
|
-
if (hit?.key instanceof CryptographicKey && entry.owner != null) attachKeyOwnerEvidence(hit.key, entry.owner, entry.expires);
|
|
509
|
-
return hit;
|
|
510
|
-
}
|
|
511
|
-
/**
|
|
512
|
-
* Attaches the evidence of the portable actor whose document has just
|
|
513
|
-
* vouched for a key to the key. The evidence expires with the cache entry
|
|
514
|
-
* of the key, so that it is never trusted longer than the key is cached.
|
|
515
|
-
* Without a cache, it expires with the proof of the document, but no later
|
|
516
|
-
* than {@link MAX_PORTABLE_KEY_TTL}, as a cache entry would.
|
|
517
|
-
* @param resolution The resolution of the key.
|
|
518
|
-
* @param scopedCache The cache namespace the key was stored in, if any.
|
|
519
|
-
* @param cached When the cache entry expires, if the cache stored one.
|
|
520
|
-
*/
|
|
521
|
-
function attachResolvedKeyOwnerEvidence(resolution, scopedCache, cached) {
|
|
522
|
-
let expires;
|
|
523
|
-
if (scopedCache != null) {
|
|
524
|
-
if (cached == null) return;
|
|
525
|
-
expires = cached;
|
|
526
|
-
} else {
|
|
527
|
-
expires = Temporal.Now.instant().add(MAX_PORTABLE_KEY_TTL);
|
|
528
|
-
if (resolution.expires != null && Temporal.Instant.compare(resolution.expires, expires) < 0) expires = resolution.expires;
|
|
529
|
-
}
|
|
530
|
-
attachKeyOwnerEvidence(resolution.key, resolution.document, expires);
|
|
531
|
-
}
|
|
532
|
-
async function clearFetchErrorMetadata(keyId, keyCache) {
|
|
533
|
-
await keyCache?.setFetchError?.(keyId, null);
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* Returns the identifier a fragment-bearing DID URL is a fragment of, or
|
|
537
|
-
* `null` if the URL is not a DID URL. `did:web:example.com#key` is thereby
|
|
538
|
-
* traced back to `did:web:example.com`, the DID that resolving the key went
|
|
539
|
-
* through in the first place.
|
|
540
|
-
*/
|
|
541
|
-
function stripFragment(keyId) {
|
|
542
|
-
if (keyId.protocol !== "did:") return null;
|
|
543
|
-
const did = new URL(keyId.href);
|
|
544
|
-
did.hash = "";
|
|
545
|
-
return did;
|
|
546
|
-
}
|
|
547
|
-
function isDidKeyUrl(keyId) {
|
|
548
|
-
return keyId.protocol === "did:" && keyId.pathname.startsWith("key:");
|
|
549
|
-
}
|
|
550
|
-
async function doRawKeysMatch(left, right) {
|
|
551
|
-
const [leftRaw, rightRaw] = await Promise.all([crypto.subtle.exportKey("raw", left), crypto.subtle.exportKey("raw", right)]);
|
|
552
|
-
if (leftRaw.byteLength !== rightRaw.byteLength) return false;
|
|
553
|
-
const leftBytes = new Uint8Array(leftRaw);
|
|
554
|
-
const rightBytes = new Uint8Array(rightRaw);
|
|
555
|
-
return leftBytes.every((byte, index) => byte === rightBytes[index]);
|
|
556
|
-
}
|
|
557
|
-
async function isCachedDidKeyValid(key, verificationMethod) {
|
|
558
|
-
try {
|
|
559
|
-
return key.id?.href === verificationMethod.id.href && key.controllerId?.href === verificationMethod.controller.href && await doRawKeysMatch(key.publicKey, verificationMethod.publicKey);
|
|
560
|
-
} catch {
|
|
561
|
-
return false;
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
async function resolveDidKey(cacheKey, cls, keyCache, logger) {
|
|
565
|
-
if (!isDidKeyUrl(cacheKey)) return null;
|
|
566
|
-
const keyId = cacheKey.href;
|
|
567
|
-
if (!(cls === Multikey)) {
|
|
568
|
-
logger.debug("Failed to resolve did:key {keyId}; did:key verification methods are only supported as Multikey values.", { keyId });
|
|
569
|
-
return {
|
|
570
|
-
key: null,
|
|
571
|
-
cached: false
|
|
572
|
-
};
|
|
573
|
-
}
|
|
574
|
-
let verificationMethod;
|
|
575
|
-
try {
|
|
576
|
-
verificationMethod = await parseDidKeyVerificationMethod(cacheKey);
|
|
577
|
-
} catch (error) {
|
|
578
|
-
logger.debug("Failed to resolve did:key verification method {keyId}: {error}", {
|
|
579
|
-
keyId,
|
|
580
|
-
error
|
|
581
|
-
});
|
|
582
|
-
return {
|
|
583
|
-
key: null,
|
|
584
|
-
cached: false
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
const hit = checkCachedKeyHit(await keyCache?.get(cacheKey), keyId, cls, logger);
|
|
588
|
-
if (hit?.key instanceof Multikey && await isCachedDidKeyValid(hit.key, verificationMethod)) return hit;
|
|
589
|
-
const key = new Multikey({
|
|
590
|
-
id: verificationMethod.id,
|
|
591
|
-
controller: verificationMethod.controller,
|
|
592
|
-
publicKey: verificationMethod.publicKey
|
|
593
|
-
});
|
|
594
|
-
await keyCache?.set(cacheKey, key);
|
|
595
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
596
|
-
logger.debug("Resolved did:key verification method {keyId}.", { keyId });
|
|
597
|
-
return {
|
|
598
|
-
key,
|
|
599
|
-
cached: false
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
async function resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, { documentLoader, contextLoader, keyCache, tracerProvider, keyIdBoundByCaller, portableKeyResolvers }, logger) {
|
|
603
|
-
let object;
|
|
604
|
-
try {
|
|
605
|
-
object = await Object$1.fromJsonLd(document, {
|
|
606
|
-
documentLoader,
|
|
607
|
-
contextLoader,
|
|
608
|
-
tracerProvider
|
|
609
|
-
});
|
|
610
|
-
} catch (e) {
|
|
611
|
-
const failure = classifyKeyJsonLdError(e);
|
|
612
|
-
if (failure === "fetch") throw contextFetchError(e);
|
|
613
|
-
if (failure != null) {
|
|
614
|
-
logger.debug("Failed to decode key {keyId}: {error}", {
|
|
615
|
-
keyId,
|
|
616
|
-
failure,
|
|
617
|
-
error: e
|
|
618
|
-
});
|
|
619
|
-
await keyCache?.set(cacheKey, null);
|
|
620
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
621
|
-
return {
|
|
622
|
-
key: null,
|
|
623
|
-
cached: false
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
if (!(e instanceof TypeError)) throw e;
|
|
627
|
-
try {
|
|
628
|
-
object = await cls.fromJsonLd(document, {
|
|
629
|
-
documentLoader,
|
|
630
|
-
contextLoader,
|
|
631
|
-
tracerProvider
|
|
632
|
-
});
|
|
633
|
-
} catch (e) {
|
|
634
|
-
const failure = classifyKeyJsonLdError(e);
|
|
635
|
-
if (failure === "fetch") throw contextFetchError(e);
|
|
636
|
-
if (failure != null || e instanceof TypeError) {
|
|
637
|
-
logger.debug("Failed to decode key {keyId}: {error}", {
|
|
638
|
-
keyId,
|
|
639
|
-
failure: failure ?? "invalid",
|
|
640
|
-
error: e
|
|
641
|
-
});
|
|
642
|
-
await keyCache?.set(cacheKey, null);
|
|
643
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
644
|
-
return {
|
|
645
|
-
key: null,
|
|
646
|
-
cached: false
|
|
647
|
-
};
|
|
648
|
-
}
|
|
649
|
-
throw e;
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
if (isCompatibleKeyId(cacheKey) && isPortableActorDocument(object)) {
|
|
653
|
-
const scopedCache = keyCache;
|
|
654
|
-
if (portableKeyResolvers == null || cls !== CryptographicKey) {
|
|
655
|
-
logger.debug("Failed to verify; key {keyId} is a gateway key of the portable actor {actorId}, which is only accepted for HTTP Signatures.", {
|
|
656
|
-
keyId,
|
|
657
|
-
actorId: object.id?.href
|
|
658
|
-
});
|
|
659
|
-
await scopedCache?.set(cacheKey, null);
|
|
660
|
-
return {
|
|
661
|
-
key: null,
|
|
662
|
-
cached: false
|
|
663
|
-
};
|
|
664
|
-
}
|
|
665
|
-
const resolution = await portableKeyResolvers.gatewayKey(document, object, cacheKey);
|
|
666
|
-
if (resolution.type !== "verified") {
|
|
667
|
-
logger.debug("Failed to verify; the portable actor {actorId} does not vouch for its gateway key {keyId}.", {
|
|
668
|
-
keyId,
|
|
669
|
-
actorId: object.id?.href
|
|
670
|
-
});
|
|
671
|
-
await scopedCache?.set(cacheKey, null);
|
|
672
|
-
return {
|
|
673
|
-
key: null,
|
|
674
|
-
cached: false
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
attachResolvedKeyOwnerEvidence(resolution, scopedCache, await scopedCache?.set(cacheKey, resolution.key, {
|
|
678
|
-
expires: resolution.expires,
|
|
679
|
-
owner: resolution.document
|
|
680
|
-
}));
|
|
681
|
-
return {
|
|
682
|
-
key: resolution.key,
|
|
683
|
-
cached: false
|
|
684
|
-
};
|
|
685
|
-
}
|
|
686
|
-
let key = null;
|
|
687
|
-
let ownerDocument = null;
|
|
688
|
-
if (object instanceof cls && (object.id == null || object.id.href === keyId)) key = object.id == null ? object.clone({ id: cacheKey }) : object;
|
|
689
|
-
else if (isActor(object)) {
|
|
690
|
-
if (object.id == null || isPortableId(object.id) || object.id.origin !== documentUrl.origin) {
|
|
691
|
-
logger.debug("Failed to verify; the document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin.", {
|
|
692
|
-
keyId,
|
|
693
|
-
documentUrl: documentUrl.href,
|
|
694
|
-
actorId: object.id?.href
|
|
695
|
-
});
|
|
696
|
-
await keyCache?.set(cacheKey, null);
|
|
697
|
-
return {
|
|
698
|
-
key: null,
|
|
699
|
-
cached: false
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
ownerDocument = object;
|
|
703
|
-
const keys = cls === CryptographicKey ? object.getPublicKeys({
|
|
704
|
-
documentLoader,
|
|
705
|
-
contextLoader,
|
|
706
|
-
suppressError: true,
|
|
707
|
-
tracerProvider
|
|
708
|
-
}) : object.getAssertionMethods({
|
|
709
|
-
documentLoader,
|
|
710
|
-
contextLoader,
|
|
711
|
-
suppressError: true,
|
|
712
|
-
tracerProvider
|
|
713
|
-
});
|
|
714
|
-
let length = 0;
|
|
715
|
-
let lastKey = null;
|
|
716
|
-
try {
|
|
717
|
-
for await (const k of keys) {
|
|
718
|
-
length++;
|
|
719
|
-
lastKey = k;
|
|
720
|
-
if (k.id?.href === keyId) {
|
|
721
|
-
key = k;
|
|
722
|
-
break;
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
} catch (e) {
|
|
726
|
-
if (!(e instanceof TypeError)) throw e;
|
|
727
|
-
logger.debug("Failed to verify; a malformed key was encountered while iterating the keys of {keyId}; treating it as a missing key: {error}", {
|
|
728
|
-
keyId,
|
|
729
|
-
error: e
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
const keyIdUrl = new URL(keyId);
|
|
733
|
-
if (key == null && keyIdUrl.hash === "" && length === 1) key = lastKey;
|
|
734
|
-
if (key == null) {
|
|
735
|
-
logger.debug("Failed to verify; object {keyId} returned an {actorType}, but has no key matching {keyId}.", {
|
|
736
|
-
keyId,
|
|
737
|
-
actorType: object.constructor.name
|
|
738
|
-
});
|
|
739
|
-
await keyCache?.set(cacheKey, null);
|
|
740
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
741
|
-
return {
|
|
742
|
-
key: null,
|
|
743
|
-
cached: false
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
} else {
|
|
747
|
-
logger.debug("Failed to verify; key {keyId} returned an invalid object.", { keyId });
|
|
748
|
-
await keyCache?.set(cacheKey, null);
|
|
749
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
750
|
-
return {
|
|
751
|
-
key: null,
|
|
752
|
-
cached: false
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
if (key.publicKey == null) {
|
|
756
|
-
logger.debug("Failed to verify; key {keyId} has no publicKeyPem field.", { keyId });
|
|
757
|
-
await keyCache?.set(cacheKey, null);
|
|
758
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
759
|
-
return {
|
|
760
|
-
key: null,
|
|
761
|
-
cached: false
|
|
762
|
-
};
|
|
763
|
-
}
|
|
764
|
-
const claimedOwnerId = key instanceof CryptographicKey ? key.ownerId : key.controllerId;
|
|
765
|
-
if (!(keyIdBoundByCaller && claimedOwnerId != null && claimedOwnerId.href === stripFragment(cacheKey)?.href)) {
|
|
766
|
-
if (claimedOwnerId != null && isPortableId(claimedOwnerId)) {
|
|
767
|
-
logger.debug("Failed to verify; key {keyId} claims the portable actor {claimedOwnerId} as its owner, but is not its gateway key.", {
|
|
768
|
-
keyId,
|
|
769
|
-
claimedOwnerId: claimedOwnerId.href
|
|
770
|
-
});
|
|
771
|
-
await keyCache?.set(cacheKey, null);
|
|
772
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
773
|
-
return {
|
|
774
|
-
key: null,
|
|
775
|
-
cached: false
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
if (ownerDocument != null && claimedOwnerId == null) key = key instanceof CryptographicKey ? key.clone({ owner: ownerDocument.id }) : key.clone({ controller: ownerDocument.id });
|
|
779
|
-
else if (claimedOwnerId != null && claimedOwnerId.href !== ownerDocument?.id?.href) {
|
|
780
|
-
if (await verifyKeyOwnershipInternal(key, {
|
|
781
|
-
documentLoader,
|
|
782
|
-
contextLoader,
|
|
783
|
-
tracerProvider
|
|
784
|
-
}, true) == null) {
|
|
785
|
-
logger.debug("Failed to verify; the owner {claimedOwnerId} that key {keyId} claims does not list the key as its own.", {
|
|
786
|
-
keyId,
|
|
787
|
-
claimedOwnerId: claimedOwnerId.href
|
|
788
|
-
});
|
|
789
|
-
await keyCache?.set(cacheKey, null);
|
|
790
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
791
|
-
return {
|
|
792
|
-
key: null,
|
|
793
|
-
cached: false
|
|
794
|
-
};
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
if (keyCache != null) {
|
|
799
|
-
await keyCache.set(cacheKey, key);
|
|
800
|
-
logger.debug("Key {keyId} cached.", { keyId });
|
|
801
|
-
}
|
|
802
|
-
await clearFetchErrorMetadata(cacheKey, keyCache);
|
|
803
|
-
return {
|
|
804
|
-
key,
|
|
805
|
-
cached: false
|
|
806
|
-
};
|
|
807
|
-
}
|
|
808
|
-
/**
|
|
809
|
-
* Tells whether a key claims a portable actor as its owner. Such a key can
|
|
810
|
-
* only be a gateway key, which is never cached under its ID, so a cached one
|
|
811
|
-
* was cached by an older version that trusted web origins, and is fetched
|
|
812
|
-
* again.
|
|
813
|
-
*/
|
|
814
|
-
function claimsPortableOwner(key) {
|
|
815
|
-
const ownerId = key instanceof CryptographicKey ? key.ownerId : key?.controllerId;
|
|
816
|
-
return ownerId != null && isPortableId(ownerId);
|
|
817
|
-
}
|
|
818
|
-
async function fetchKeyWithResult(cacheKey, cls, options, onCachedUnavailable, onFetchError) {
|
|
819
|
-
const start = performance.now();
|
|
820
|
-
let outcome = { result: "error" };
|
|
821
|
-
try {
|
|
822
|
-
const logger = getLogger([
|
|
823
|
-
"fedify",
|
|
824
|
-
"sig",
|
|
825
|
-
"key"
|
|
826
|
-
]);
|
|
827
|
-
const keyId = cacheKey.href;
|
|
828
|
-
const keyCache = options.keyCache;
|
|
829
|
-
if (isPortableUri(cacheKey)) {
|
|
830
|
-
const result = await fetchPortableActorKey(cacheKey, cls, options, onCachedUnavailable, onFetchError, logger);
|
|
831
|
-
outcome = result.outcome;
|
|
832
|
-
return result.result;
|
|
833
|
-
}
|
|
834
|
-
if (isCompatibleKeyId(cacheKey)) {
|
|
835
|
-
const result = await fetchCompatibleKey(cacheKey, cls, options, onCachedUnavailable, onFetchError, logger);
|
|
836
|
-
outcome = result.outcome;
|
|
837
|
-
return result.result;
|
|
838
|
-
}
|
|
839
|
-
const didKey = await resolveDidKey(cacheKey, cls, keyCache, logger);
|
|
840
|
-
if (didKey != null) {
|
|
841
|
-
outcome = { result: didKey.key == null ? "invalid" : didKey.cached ? "hit" : "fetched" };
|
|
842
|
-
return didKey;
|
|
843
|
-
}
|
|
844
|
-
const cached = await getCachedFetchKey(cacheKey, keyId, cls, keyCache, logger);
|
|
845
|
-
if (cached?.key === null && cached.cached) {
|
|
846
|
-
const cachedUnavailable = await onCachedUnavailable(cacheKey, keyId, keyCache, logger);
|
|
847
|
-
outcome = { result: "hit" };
|
|
848
|
-
return cachedUnavailable;
|
|
849
|
-
}
|
|
850
|
-
if (cached != null && !claimsPortableOwner(cached.key)) {
|
|
851
|
-
outcome = { result: "hit" };
|
|
852
|
-
return cached;
|
|
853
|
-
}
|
|
854
|
-
logger.debug("Fetching key {keyId} to verify signature...", { keyId });
|
|
855
|
-
let document;
|
|
856
|
-
let documentUrl = cacheKey;
|
|
857
|
-
try {
|
|
858
|
-
const remoteDocument = await (options.documentLoader ?? getDocumentLoader())(keyId);
|
|
859
|
-
document = remoteDocument.document;
|
|
860
|
-
documentUrl = new URL(remoteDocument.documentUrl ?? "", cacheKey);
|
|
861
|
-
} catch (error) {
|
|
862
|
-
const classified = classifyFetchError(error);
|
|
863
|
-
const errored = await onFetchError(error, cacheKey, keyId, keyCache, logger);
|
|
864
|
-
outcome = classified;
|
|
865
|
-
return errored;
|
|
866
|
-
}
|
|
867
|
-
try {
|
|
868
|
-
const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, options, logger);
|
|
869
|
-
outcome = { result: resolved.key != null ? "fetched" : "invalid" };
|
|
870
|
-
return resolved;
|
|
871
|
-
} catch (error) {
|
|
872
|
-
if (!(error instanceof KeyContextFetchError)) throw error;
|
|
873
|
-
const classified = classifyFetchError(error.error);
|
|
874
|
-
const errored = await onFetchError(error.error, cacheKey, keyId, keyCache, logger);
|
|
875
|
-
outcome = classified;
|
|
876
|
-
return errored;
|
|
877
|
-
}
|
|
878
|
-
} finally {
|
|
879
|
-
recordKeyLookup(options.meterProvider, {
|
|
880
|
-
durationMs: getDurationMs(start),
|
|
881
|
-
result: outcome.result,
|
|
882
|
-
remoteUrl: cacheKey,
|
|
883
|
-
cacheEnabled: options.keyCache != null,
|
|
884
|
-
statusCode: outcome.statusCode
|
|
885
|
-
});
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
/**
|
|
889
|
-
* Tells which purpose a lookup of a key at a compatible identifier serves.
|
|
890
|
-
*/
|
|
891
|
-
function getCompatibleKeyScope(cls, options) {
|
|
892
|
-
if (cls !== CryptographicKey) return "multikey";
|
|
893
|
-
return options.portableKeyResolvers == null ? "cryptographicKey" : "httpSignature";
|
|
894
|
-
}
|
|
895
|
-
/**
|
|
896
|
-
* Looks up a key at an [FEP-ef61] compatible identifier. Such a key may be
|
|
897
|
-
* a gateway key of a portable actor, which is accepted for some purposes but
|
|
898
|
-
* not for others, so everything resolved from the document at the key ID is
|
|
899
|
-
* cached in a namespace of the lookup's purpose, and one purpose never reuses
|
|
900
|
-
* what another resolved, nor what another rejected. A failure to fetch
|
|
901
|
-
* the document fails every purpose alike, so it is cached in the shared
|
|
902
|
-
* namespace, as for any other key.
|
|
903
|
-
*
|
|
904
|
-
* [FEP-ef61]: https://w3id.org/fep/ef61
|
|
905
|
-
*/
|
|
906
|
-
async function fetchCompatibleKey(cacheKey, cls, options, onCachedUnavailable, onFetchError, logger) {
|
|
907
|
-
const keyId = cacheKey.href;
|
|
908
|
-
const sharedCache = options.keyCache;
|
|
909
|
-
const scopedCache = sharedCache?.compatibleKeyScope?.(getCompatibleKeyScope(cls, options));
|
|
910
|
-
const cached = await getCachedCompatibleKey(cacheKey, keyId, cls, scopedCache, logger);
|
|
911
|
-
if (cached != null) return {
|
|
912
|
-
result: cached,
|
|
913
|
-
outcome: { result: "hit" }
|
|
914
|
-
};
|
|
915
|
-
if (await sharedCache?.get(cacheKey) === null) {
|
|
916
|
-
logger.debug("Entry {keyId} found in cache, but it could not be fetched.", { keyId });
|
|
917
|
-
return {
|
|
918
|
-
result: await onCachedUnavailable(cacheKey, keyId, sharedCache, logger),
|
|
919
|
-
outcome: { result: "hit" }
|
|
920
|
-
};
|
|
921
|
-
}
|
|
922
|
-
logger.debug("Fetching key {keyId} to verify signature...", { keyId });
|
|
923
|
-
let document;
|
|
924
|
-
let documentUrl;
|
|
925
|
-
try {
|
|
926
|
-
const remoteDocument = await (options.documentLoader ?? getDocumentLoader())(keyId);
|
|
927
|
-
document = remoteDocument.document;
|
|
928
|
-
documentUrl = new URL(remoteDocument.documentUrl ?? "", cacheKey);
|
|
929
|
-
} catch (error) {
|
|
930
|
-
const outcome = classifyFetchError(error);
|
|
931
|
-
const result = await onFetchError(error, cacheKey, keyId, sharedCache, logger);
|
|
932
|
-
await scopedCache?.delete(cacheKey);
|
|
933
|
-
return {
|
|
934
|
-
result,
|
|
935
|
-
outcome
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
const resolved = await resolveFetchedKey(document, cacheKey, documentUrl, keyId, cls, {
|
|
939
|
-
...options,
|
|
940
|
-
keyCache: scopedCache
|
|
941
|
-
}, logger);
|
|
942
|
-
return {
|
|
943
|
-
result: resolved,
|
|
944
|
-
outcome: { result: resolved.key != null ? "fetched" : "invalid" }
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
/**
|
|
948
|
-
* Looks up a key of an [FEP-ef61] portable actor at an `ap:` or `ap+ef61:`
|
|
949
|
-
* key ID. Such a key is accepted only for HTTP Signatures, and is rejected
|
|
950
|
-
* for any other purpose without being fetched. Like keys at compatible
|
|
951
|
-
* identifiers, what it resolves to is cached in the namespace of the lookup's
|
|
952
|
-
* purpose, and a failure to fetch the actor's document from every gateway is
|
|
953
|
-
* cached in the shared namespace. A failure that is neither, e.g., one
|
|
954
|
-
* gateway being unreachable while another served an invalid document, is not
|
|
955
|
-
* cached at all.
|
|
956
|
-
*
|
|
957
|
-
* [FEP-ef61]: https://w3id.org/fep/ef61
|
|
958
|
-
*/
|
|
959
|
-
async function fetchPortableActorKey(cacheKey, cls, options, onCachedUnavailable, onFetchError, logger) {
|
|
960
|
-
const keyId = cacheKey.href;
|
|
961
|
-
const resolvers = options.portableKeyResolvers;
|
|
962
|
-
if (resolvers == null || cls !== CryptographicKey) {
|
|
963
|
-
logger.debug("Failed to verify; key {keyId} is a key of a portable actor, which is only accepted for HTTP Signatures.", { keyId });
|
|
964
|
-
return {
|
|
965
|
-
result: {
|
|
966
|
-
key: null,
|
|
967
|
-
cached: false
|
|
968
|
-
},
|
|
969
|
-
outcome: { result: "invalid" }
|
|
970
|
-
};
|
|
971
|
-
}
|
|
972
|
-
const sharedCache = options.keyCache;
|
|
973
|
-
const scopedCache = sharedCache?.compatibleKeyScope?.("httpSignature");
|
|
974
|
-
const cached = await getCachedCompatibleKey(cacheKey, keyId, cls, scopedCache, logger);
|
|
975
|
-
if (cached != null) return {
|
|
976
|
-
result: cached,
|
|
977
|
-
outcome: { result: "hit" }
|
|
978
|
-
};
|
|
979
|
-
if (await sharedCache?.get(cacheKey) === null) {
|
|
980
|
-
logger.debug("Entry {keyId} found in cache, but it could not be fetched.", { keyId });
|
|
981
|
-
return {
|
|
982
|
-
result: await onCachedUnavailable(cacheKey, keyId, sharedCache, logger),
|
|
983
|
-
outcome: { result: "hit" }
|
|
984
|
-
};
|
|
985
|
-
}
|
|
986
|
-
logger.debug("Resolving key {keyId} to verify signature...", { keyId });
|
|
987
|
-
const resolution = await resolvers.actorKey(cacheKey);
|
|
988
|
-
if (resolution.type === "verified") {
|
|
989
|
-
attachResolvedKeyOwnerEvidence(resolution, scopedCache, await scopedCache?.set(cacheKey, resolution.key, {
|
|
990
|
-
expires: resolution.expires,
|
|
991
|
-
owner: resolution.document
|
|
992
|
-
}));
|
|
993
|
-
return {
|
|
994
|
-
result: {
|
|
995
|
-
key: resolution.key,
|
|
996
|
-
cached: false
|
|
997
|
-
},
|
|
998
|
-
outcome: { result: "fetched" }
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
if (resolution.type === "rejected") {
|
|
1002
|
-
await scopedCache?.set(cacheKey, null);
|
|
1003
|
-
return {
|
|
1004
|
-
result: {
|
|
1005
|
-
key: null,
|
|
1006
|
-
cached: false
|
|
1007
|
-
},
|
|
1008
|
-
outcome: { result: "invalid" }
|
|
1009
|
-
};
|
|
1010
|
-
}
|
|
1011
|
-
await scopedCache?.delete(cacheKey);
|
|
1012
|
-
return {
|
|
1013
|
-
result: await onFetchError(resolution.error, cacheKey, keyId, resolution.cacheable ? sharedCache : void 0, logger),
|
|
1014
|
-
outcome: resolution.cacheable ? classifyFetchError(resolution.error) : { result: "error" }
|
|
1015
|
-
};
|
|
1016
|
-
}
|
|
1017
|
-
async function fetchKeyInternal(keyId, cls, options = {}) {
|
|
1018
|
-
return await fetchKeyWithResult(typeof keyId === "string" ? parseKeyIdOrThrow(keyId) : keyId, cls, options, async (_cacheKey, _keyId, _keyCache, _logger) => {
|
|
1019
|
-
const check = options[verificationObservation]?.check;
|
|
1020
|
-
if (check != null) try {
|
|
1021
|
-
const result = await _keyCache?.getFetchError?.(_cacheKey);
|
|
1022
|
-
if (result != null) check.reason = {
|
|
1023
|
-
type: "keyFetchError",
|
|
1024
|
-
keyId: new URL(_cacheKey.href),
|
|
1025
|
-
result
|
|
1026
|
-
};
|
|
1027
|
-
} catch {}
|
|
1028
|
-
return {
|
|
1029
|
-
key: null,
|
|
1030
|
-
cached: true
|
|
1031
|
-
};
|
|
1032
|
-
}, async (error, cacheKey, keyId, keyCache, logger) => {
|
|
1033
|
-
const check = options[verificationObservation]?.check;
|
|
1034
|
-
if (check != null) {
|
|
1035
|
-
let result;
|
|
1036
|
-
try {
|
|
1037
|
-
result = error instanceof FetchError && error.response != null ? {
|
|
1038
|
-
status: error.response.status,
|
|
1039
|
-
response: error.response.clone()
|
|
1040
|
-
} : { error: error instanceof Error ? error : new Error(String(error)) };
|
|
1041
|
-
} catch {
|
|
1042
|
-
result = { error: error instanceof Error ? error : /* @__PURE__ */ new Error("Unknown verification error") };
|
|
1043
|
-
}
|
|
1044
|
-
check.reason = {
|
|
1045
|
-
type: "keyFetchError",
|
|
1046
|
-
keyId: new URL(cacheKey.href),
|
|
1047
|
-
result
|
|
1048
|
-
};
|
|
1049
|
-
}
|
|
1050
|
-
logger.debug("Failed to fetch key {keyId}.", {
|
|
1051
|
-
keyId,
|
|
1052
|
-
error
|
|
1053
|
-
});
|
|
1054
|
-
await keyCache?.set(cacheKey, null);
|
|
1055
|
-
if (error instanceof FetchError && error.response != null) await keyCache?.setFetchError?.(cacheKey, {
|
|
1056
|
-
status: error.response.status,
|
|
1057
|
-
response: error.response.clone()
|
|
1058
|
-
});
|
|
1059
|
-
else await keyCache?.setFetchError?.(cacheKey, { error: error instanceof Error ? error : new Error(String(error)) });
|
|
1060
|
-
return {
|
|
1061
|
-
key: null,
|
|
1062
|
-
cached: false
|
|
1063
|
-
};
|
|
1064
|
-
});
|
|
1065
|
-
}
|
|
1066
|
-
//#endregion
|
|
1067
|
-
//#region src/sig/ld.ts
|
|
1068
|
-
const logger = getLogger([
|
|
1069
|
-
"fedify",
|
|
1070
|
-
"sig",
|
|
1071
|
-
"ld"
|
|
1072
|
-
]);
|
|
1073
|
-
const localContext = [
|
|
1074
|
-
"https://w3id.org/identity/v1",
|
|
1075
|
-
"https://www.w3.org/ns/activitystreams",
|
|
1076
|
-
"https://w3id.org/security/v1",
|
|
1077
|
-
"https://w3id.org/security/data-integrity/v1"
|
|
1078
|
-
];
|
|
1079
|
-
const localContextUrls = new Set(localContext);
|
|
1080
|
-
const builtInContextLoader = getDocumentLoader();
|
|
1081
|
-
const disallowedJsonLdKeywords = /* @__PURE__ */ new Set([
|
|
1082
|
-
"@graph",
|
|
1083
|
-
"@included",
|
|
1084
|
-
"@reverse"
|
|
1085
|
-
]);
|
|
1086
|
-
/** @internal */
|
|
1087
|
-
var UnsafeJsonLdError = class extends TypeError {
|
|
1088
|
-
keyword;
|
|
1089
|
-
constructor(keyword) {
|
|
1090
|
-
super(`Unsupported JSON-LD keyword: ${keyword}.`);
|
|
1091
|
-
this.keyword = keyword;
|
|
1092
|
-
this.name = "UnsafeJsonLdError";
|
|
1093
|
-
}
|
|
1094
|
-
};
|
|
1095
|
-
/** @internal */
|
|
1096
|
-
var InvalidContextReferenceError = class extends TypeError {
|
|
1097
|
-
reference;
|
|
1098
|
-
constructor(reference) {
|
|
1099
|
-
super(`Invalid JSON-LD context reference: ${reference}.`);
|
|
1100
|
-
this.reference = reference;
|
|
1101
|
-
this.name = "InvalidContextReferenceError";
|
|
1102
|
-
}
|
|
1103
|
-
};
|
|
1104
|
-
function createLoadingRemoteContextFailedError(reference, cause) {
|
|
1105
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1106
|
-
const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
|
|
1107
|
-
error.name = "jsonld.InvalidUrl";
|
|
1108
|
-
error.details = {
|
|
1109
|
-
code: "loading remote context failed",
|
|
1110
|
-
url: reference
|
|
1111
|
-
};
|
|
1112
|
-
error.cause = cause;
|
|
1113
|
-
return error;
|
|
1114
|
-
}
|
|
1115
|
-
/** @internal */
|
|
1116
|
-
function isClearlyMalformedContextReference(reference) {
|
|
1117
|
-
for (const char of reference) {
|
|
1118
|
-
const code = char.charCodeAt(0);
|
|
1119
|
-
if (code <= 32 || code === 127) return true;
|
|
1120
|
-
}
|
|
1121
|
-
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
|
|
1122
|
-
for (let i = 0; i < reference.length; i++) {
|
|
1123
|
-
if (reference[i] !== "%") continue;
|
|
1124
|
-
if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
|
|
1125
|
-
i += 2;
|
|
1126
|
-
}
|
|
1127
|
-
if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
|
|
1128
|
-
for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
|
|
1129
|
-
}
|
|
1130
|
-
return false;
|
|
1131
|
-
}
|
|
1132
|
-
function cloneRemoteDocument(remoteDocument) {
|
|
1133
|
-
return structuredClone(remoteDocument);
|
|
1134
|
-
}
|
|
1135
|
-
function createMemoizedDocumentLoader(documentLoader) {
|
|
1136
|
-
const cache = /* @__PURE__ */ new Map();
|
|
1137
|
-
return async (url, options) => {
|
|
1138
|
-
const cacheKey = URL.canParse(url) ? new URL(url).href : url;
|
|
1139
|
-
let remoteDocument = cache.get(cacheKey);
|
|
1140
|
-
if (remoteDocument == null) {
|
|
1141
|
-
remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
|
|
1142
|
-
remoteDocument.catch(() => {
|
|
1143
|
-
if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
|
|
1144
|
-
});
|
|
1145
|
-
cache.set(cacheKey, remoteDocument);
|
|
1146
|
-
}
|
|
1147
|
-
return cloneRemoteDocument(await remoteDocument);
|
|
1148
|
-
};
|
|
1149
|
-
}
|
|
1150
|
-
const effectiveContextLoaderPolicies = /* @__PURE__ */ new WeakMap();
|
|
1151
|
-
/**
|
|
1152
|
-
* Marks a context loader as the *effective* loader of a policy, i.e., one
|
|
1153
|
-
* that already applies what {@link wrapContextLoaderForJsonLd} (`"standard"`)
|
|
1154
|
-
* or {@link getNormalizationContextLoader} (`"normalization"`) would add.
|
|
1155
|
-
* Those functions return a marked loader as is instead of wrapping it again,
|
|
1156
|
-
* so that a caller can observe every response a parse actually uses,
|
|
1157
|
-
* including Fedify's own baseline contexts.
|
|
1158
|
-
* @param loader The effective context loader.
|
|
1159
|
-
* @param policy The policy the loader already applies.
|
|
1160
|
-
* @returns The given loader.
|
|
1161
|
-
* @internal
|
|
1162
|
-
*/
|
|
1163
|
-
function markEffectiveContextLoader(loader, policy) {
|
|
1164
|
-
effectiveContextLoaderPolicies.set(loader, policy);
|
|
1165
|
-
return loader;
|
|
1166
|
-
}
|
|
1167
|
-
/** @internal */
|
|
1168
|
-
function wrapContextLoaderForJsonLd(contextLoader) {
|
|
1169
|
-
if (contextLoader != null && effectiveContextLoaderPolicies.has(contextLoader)) return contextLoader;
|
|
1170
|
-
const loader = contextLoader ?? builtInContextLoader;
|
|
1171
|
-
return async (url, options) => {
|
|
1172
|
-
try {
|
|
1173
|
-
return await loader(url, options);
|
|
1174
|
-
} catch (error) {
|
|
1175
|
-
if (!isInvalidUrlTypeError(error)) throw error;
|
|
1176
|
-
if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
|
|
1177
|
-
throw createLoadingRemoteContextFailedError(url, error);
|
|
1178
|
-
}
|
|
1179
|
-
};
|
|
1180
|
-
}
|
|
1181
|
-
/** @internal */
|
|
1182
|
-
function getNormalizationContextLoader(contextLoader) {
|
|
1183
|
-
if (contextLoader != null && effectiveContextLoaderPolicies.get(contextLoader) === "normalization") return contextLoader;
|
|
1184
|
-
const loader = wrapContextLoaderForJsonLd(contextLoader);
|
|
1185
|
-
return createMemoizedDocumentLoader(async (url, options) => {
|
|
1186
|
-
if (URL.canParse(url)) {
|
|
1187
|
-
const normalizedUrl = new URL(url).href;
|
|
1188
|
-
if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
|
|
1189
|
-
}
|
|
1190
|
-
return await loader(url, options);
|
|
1191
|
-
});
|
|
1192
|
-
}
|
|
1193
|
-
/** @internal */
|
|
1194
|
-
async function compactJsonLd(jsonLd, contextLoader) {
|
|
1195
|
-
const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
|
|
1196
|
-
const signature = hasLds ? jsonLd.signature : void 0;
|
|
1197
|
-
const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
|
|
1198
|
-
const document = hasLds ? detachSignature(jsonLd) : jsonLd;
|
|
1199
|
-
await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
|
|
1200
|
-
const compacted = await jsonld.compact(document, localContext, { documentLoader: normalizationContextLoader });
|
|
1201
|
-
if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
|
|
1202
|
-
assertSafeJsonLd(compacted);
|
|
1203
|
-
return compacted;
|
|
1204
|
-
}
|
|
1205
|
-
function createInvalidRemoteContextError(reference) {
|
|
1206
|
-
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}".`);
|
|
1207
|
-
error.name = "jsonld.InvalidUrl";
|
|
1208
|
-
error.details = {
|
|
1209
|
-
code: "invalid remote context",
|
|
1210
|
-
url: reference
|
|
1211
|
-
};
|
|
1212
|
-
return error;
|
|
1213
|
-
}
|
|
1214
|
-
function getRemoteContext(remoteDocument, reference) {
|
|
1215
|
-
const { contextUrl, documentUrl } = remoteDocument;
|
|
1216
|
-
let { document } = remoteDocument;
|
|
1217
|
-
if (typeof document === "string") document = JSON.parse(document);
|
|
1218
|
-
if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
|
|
1219
|
-
let context = "@context" in document ? document["@context"] : {};
|
|
1220
|
-
if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
|
|
1221
|
-
return {
|
|
1222
|
-
context,
|
|
1223
|
-
baseUrl: documentUrl ?? reference
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
function createGraphAliasContextState() {
|
|
1227
|
-
return {
|
|
1228
|
-
graphTerms: /* @__PURE__ */ new Set(),
|
|
1229
|
-
jsonTerms: /* @__PURE__ */ new Set(),
|
|
1230
|
-
propertyContexts: /* @__PURE__ */ new Map(),
|
|
1231
|
-
termTargets: /* @__PURE__ */ new Map()
|
|
1232
|
-
};
|
|
1233
|
-
}
|
|
1234
|
-
function cloneGraphAliasContextState(state) {
|
|
1235
|
-
return {
|
|
1236
|
-
graphTerms: new Set(state.graphTerms),
|
|
1237
|
-
jsonTerms: new Set(state.jsonTerms),
|
|
1238
|
-
propertyContexts: new Map(state.propertyContexts),
|
|
1239
|
-
termTargets: new Map(state.termTargets)
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
function resolveContextTarget(target, state) {
|
|
1243
|
-
if (target === "@graph") return target;
|
|
1244
|
-
const mapped = state.termTargets.get(target);
|
|
1245
|
-
if (mapped == null) return target;
|
|
1246
|
-
return mapped;
|
|
1247
|
-
}
|
|
1248
|
-
function getDirectContextTarget(definition) {
|
|
1249
|
-
if (definition === null) return null;
|
|
1250
|
-
if (typeof definition === "string") return definition;
|
|
1251
|
-
if (typeof definition === "object" && definition != null && "@id" in definition) {
|
|
1252
|
-
const id = definition["@id"];
|
|
1253
|
-
if (id === null) return null;
|
|
1254
|
-
if (typeof id === "string") return id;
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1257
|
-
function isJsonTypedDefinition(definition) {
|
|
1258
|
-
return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
|
|
1259
|
-
}
|
|
1260
|
-
function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
|
|
1261
|
-
if (target === "@graph") return target;
|
|
1262
|
-
if (seen.has(target)) return target;
|
|
1263
|
-
seen.add(target);
|
|
1264
|
-
if (localTargets.has(target)) {
|
|
1265
|
-
const localTarget = localTargets.get(target);
|
|
1266
|
-
return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
|
|
1267
|
-
}
|
|
1268
|
-
return resolveContextTarget(target, state);
|
|
1269
|
-
}
|
|
1270
|
-
function refreshGraphAliases(state) {
|
|
1271
|
-
state.graphTerms.clear();
|
|
1272
|
-
for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
|
|
1273
|
-
}
|
|
1274
|
-
function normalizeContextReference(reference, baseUrl) {
|
|
1275
|
-
if (baseUrl != null) return new URL(reference, baseUrl).href;
|
|
1276
|
-
return URL.canParse(reference) ? new URL(reference).href : reference;
|
|
1277
|
-
}
|
|
1278
|
-
/** @internal */
|
|
1279
|
-
function isInvalidUrlTypeError(error) {
|
|
1280
|
-
const code = error.code;
|
|
1281
|
-
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));
|
|
1282
|
-
}
|
|
1283
|
-
async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
|
|
1284
|
-
if (context === null) return createGraphAliasContextState();
|
|
1285
|
-
let nextState = cloneGraphAliasContextState(state);
|
|
1286
|
-
if (Array.isArray(context)) {
|
|
1287
|
-
for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
|
|
1288
|
-
return nextState;
|
|
1289
|
-
}
|
|
1290
|
-
if (typeof context === "string") {
|
|
1291
|
-
const reference = normalizeContextReference(context, baseUrl);
|
|
1292
|
-
const cacheKey = `${baseUrl ?? ""}\n${reference}`;
|
|
1293
|
-
if (processingContexts.has(cacheKey)) return nextState;
|
|
1294
|
-
processingContexts.add(cacheKey);
|
|
1295
|
-
try {
|
|
1296
|
-
let remoteContext = remoteContextCache.get(cacheKey);
|
|
1297
|
-
if (remoteContext == null) {
|
|
1298
|
-
remoteContext = (async () => {
|
|
1299
|
-
try {
|
|
1300
|
-
return getRemoteContext(await documentLoader(reference), reference);
|
|
1301
|
-
} catch (error) {
|
|
1302
|
-
if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
|
|
1303
|
-
throw error;
|
|
1304
|
-
}
|
|
1305
|
-
})();
|
|
1306
|
-
remoteContextCache.set(cacheKey, remoteContext);
|
|
1307
|
-
}
|
|
1308
|
-
const loadedRemoteContext = await remoteContext;
|
|
1309
|
-
return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
|
|
1310
|
-
} finally {
|
|
1311
|
-
processingContexts.delete(cacheKey);
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
if (typeof context === "object" && context != null) {
|
|
1315
|
-
if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
|
|
1316
|
-
const localTargets = /* @__PURE__ */ new Map();
|
|
1317
|
-
for (const [term, definition] of globalThis.Object.entries(context)) {
|
|
1318
|
-
if (term.startsWith("@")) continue;
|
|
1319
|
-
const target = getDirectContextTarget(definition);
|
|
1320
|
-
if (target == null) localTargets.set(term, null);
|
|
1321
|
-
else if (typeof target === "string") localTargets.set(term, target);
|
|
1322
|
-
else localTargets.delete(term);
|
|
1323
|
-
}
|
|
1324
|
-
for (const [term, definition] of globalThis.Object.entries(context)) {
|
|
1325
|
-
if (term.startsWith("@")) continue;
|
|
1326
|
-
if (localTargets.has(term)) {
|
|
1327
|
-
const directTarget = localTargets.get(term);
|
|
1328
|
-
if (directTarget == null) nextState.termTargets.set(term, null);
|
|
1329
|
-
else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
|
|
1330
|
-
} else nextState.termTargets.delete(term);
|
|
1331
|
-
if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
|
|
1332
|
-
context: definition["@context"],
|
|
1333
|
-
baseUrl
|
|
1334
|
-
});
|
|
1335
|
-
else nextState.propertyContexts.delete(term);
|
|
1336
|
-
if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
|
|
1337
|
-
else nextState.jsonTerms.delete(term);
|
|
1338
|
-
}
|
|
1339
|
-
refreshGraphAliases(nextState);
|
|
1340
|
-
}
|
|
1341
|
-
return nextState;
|
|
1342
|
-
}
|
|
1343
|
-
async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
|
|
1344
|
-
if (Array.isArray(jsonLd)) {
|
|
1345
|
-
for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
|
|
1346
|
-
return;
|
|
1347
|
-
}
|
|
1348
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return;
|
|
1349
|
-
const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
|
|
1350
|
-
let state = inheritedState;
|
|
1351
|
-
if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
|
|
1352
|
-
if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
|
|
1353
|
-
for (const [key, value] of globalThis.Object.entries(jsonLd)) {
|
|
1354
|
-
if (key === "@context") continue;
|
|
1355
|
-
if (jsonLiteralWrapper && key === "@value") continue;
|
|
1356
|
-
if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
|
|
1357
|
-
if (state.jsonTerms.has(key)) continue;
|
|
1358
|
-
await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
function isJsonLiteralWrapper(value) {
|
|
1362
|
-
return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
|
|
1363
|
-
}
|
|
1364
|
-
/** @internal */
|
|
1365
|
-
function assertSafeJsonLd(jsonLd) {
|
|
1366
|
-
if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
|
|
1367
|
-
else if (typeof jsonLd === "object" && jsonLd != null) {
|
|
1368
|
-
const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
|
|
1369
|
-
for (const [key, value] of globalThis.Object.entries(jsonLd)) {
|
|
1370
|
-
if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
|
|
1371
|
-
if (jsonLiteralWrapper && key === "@value") continue;
|
|
1372
|
-
assertSafeJsonLd(value);
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
/**
|
|
1377
|
-
* Attaches a LD signature to the given JSON-LD document.
|
|
1378
|
-
* @param jsonLd The JSON-LD document to attach the signature to. It is not
|
|
1379
|
-
* modified.
|
|
1380
|
-
* @param signature The signature to attach.
|
|
1381
|
-
* @returns The JSON-LD document with the attached signature.
|
|
1382
|
-
* @throws {TypeError} If the input document is not a valid JSON-LD document.
|
|
1383
|
-
* @since 1.0.0
|
|
1384
|
-
*/
|
|
1385
|
-
function attachSignature(jsonLd, signature) {
|
|
1386
|
-
if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
|
|
1387
|
-
return {
|
|
1388
|
-
...jsonLd,
|
|
1389
|
-
signature
|
|
1390
|
-
};
|
|
1391
|
-
}
|
|
1392
|
-
/**
|
|
1393
|
-
* Creates a LD signature for the given JSON-LD document.
|
|
1394
|
-
* @param jsonLd The JSON-LD document to sign.
|
|
1395
|
-
* @param privateKey The private key to sign the document.
|
|
1396
|
-
* @param keyId The ID of the public key that corresponds to the private key.
|
|
1397
|
-
* @param options Additional options for creating the signature.
|
|
1398
|
-
* See also {@link CreateSignatureOptions}.
|
|
1399
|
-
* @return The created signature.
|
|
1400
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
1401
|
-
* @since 1.0.0
|
|
1402
|
-
*/
|
|
1403
|
-
async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
|
|
1404
|
-
validateCryptoKey(privateKey, "private");
|
|
1405
|
-
if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
|
|
1406
|
-
const options = {
|
|
1407
|
-
"@context": "https://w3id.org/identity/v1",
|
|
1408
|
-
creator: keyId.href,
|
|
1409
|
-
created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1410
|
-
};
|
|
1411
|
-
const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
|
|
1412
|
-
const messageBytes = new TextEncoder().encode(message);
|
|
1413
|
-
const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
|
|
1414
|
-
return {
|
|
1415
|
-
...options,
|
|
1416
|
-
type: "RsaSignature2017",
|
|
1417
|
-
signatureValue: encodeBase64(signature)
|
|
1418
|
-
};
|
|
1419
|
-
}
|
|
1420
|
-
/**
|
|
1421
|
-
* Signs the given JSON-LD document with the private key and returns the signed
|
|
1422
|
-
* JSON-LD document.
|
|
1423
|
-
* @param jsonLd The JSON-LD document to sign.
|
|
1424
|
-
* @param privateKey The private key to sign the document.
|
|
1425
|
-
* @param keyId The key ID to use in the signature. It will be used by the
|
|
1426
|
-
* verifier to fetch the corresponding public key.
|
|
1427
|
-
* @param options Additional options for signing the document.
|
|
1428
|
-
* See also {@link SignJsonLdOptions}.
|
|
1429
|
-
* @returns The signed JSON-LD document.
|
|
1430
|
-
* @throws {TypeError} If the private key is invalid or unsupported.
|
|
1431
|
-
* @since 1.0.0
|
|
1432
|
-
*/
|
|
1433
|
-
async function signJsonLd(jsonLd, privateKey, keyId, options) {
|
|
1434
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
|
|
1435
|
-
try {
|
|
1436
|
-
const signature = await createSignature(jsonLd, privateKey, keyId, options);
|
|
1437
|
-
if (span.isRecording()) {
|
|
1438
|
-
span.setAttribute("ld_signatures.type", signature.type);
|
|
1439
|
-
span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
|
|
1440
|
-
}
|
|
1441
|
-
return attachSignature(jsonLd, signature);
|
|
1442
|
-
} catch (error) {
|
|
1443
|
-
span.setStatus({
|
|
1444
|
-
code: SpanStatusCode.ERROR,
|
|
1445
|
-
message: String(error)
|
|
1446
|
-
});
|
|
1447
|
-
throw error;
|
|
1448
|
-
} finally {
|
|
1449
|
-
span.end();
|
|
1450
|
-
}
|
|
1451
|
-
});
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Checks if the given JSON-LD document has a Linked Data Signature-like
|
|
1455
|
-
* object, without restricting it to a single suite-specific shape.
|
|
1456
|
-
* @param jsonLd The JSON-LD document to check.
|
|
1457
|
-
* @returns `true` if the document has a signature-like object; `false`
|
|
1458
|
-
* otherwise.
|
|
1459
|
-
* @since 2.2.0
|
|
1460
|
-
*/
|
|
1461
|
-
function hasSignatureLike(jsonLd) {
|
|
1462
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
1463
|
-
const signature = jsonLd.signature;
|
|
1464
|
-
const hasReference = (value) => {
|
|
1465
|
-
if (typeof value === "string") return true;
|
|
1466
|
-
if (Array.isArray(value)) return value.some(hasReference);
|
|
1467
|
-
return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
|
|
1468
|
-
};
|
|
1469
|
-
const hasSignatureObject = (value) => {
|
|
1470
|
-
if (typeof value !== "object" || value == null) return false;
|
|
1471
|
-
const signatureRecord = value;
|
|
1472
|
-
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");
|
|
1473
|
-
};
|
|
1474
|
-
return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
|
|
1475
|
-
}
|
|
1476
|
-
/**
|
|
1477
|
-
* Checks if the given JSON-LD document has a Linked Data Signature.
|
|
1478
|
-
* @param jsonLd The JSON-LD document to check.
|
|
1479
|
-
* @returns `true` if the document has a signature; `false` otherwise.
|
|
1480
|
-
* @since 1.0.0
|
|
1481
|
-
*/
|
|
1482
|
-
function hasSignature(jsonLd) {
|
|
1483
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return false;
|
|
1484
|
-
if ("signature" in jsonLd) {
|
|
1485
|
-
const signature = jsonLd.signature;
|
|
1486
|
-
if (typeof signature !== "object" || signature == null) return false;
|
|
1487
|
-
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";
|
|
1488
|
-
}
|
|
1489
|
-
return false;
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* Detaches Linked Data Signatures from the given JSON-LD document.
|
|
1493
|
-
* @param jsonLd The JSON-LD document to modify.
|
|
1494
|
-
* @returns The modified JSON-LD document. If the input document does not
|
|
1495
|
-
* contain a signature, the original document is returned.
|
|
1496
|
-
* @since 1.0.0
|
|
1497
|
-
*/
|
|
1498
|
-
function detachSignature(jsonLd) {
|
|
1499
|
-
if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
|
|
1500
|
-
const doc = { ...jsonLd };
|
|
1501
|
-
delete doc.signature;
|
|
1502
|
-
return doc;
|
|
1503
|
-
}
|
|
1504
|
-
/**
|
|
1505
|
-
* Verifies Linked Data Signatures of the given JSON-LD document.
|
|
1506
|
-
*
|
|
1507
|
-
* This is a low-level utility that only checks the cryptographic signature
|
|
1508
|
-
* and (optionally) the cached key. It does not run the JSON-LD parsing,
|
|
1509
|
-
* attribution, and owner checks that a complete inbound LD verification
|
|
1510
|
-
* needs. For incoming activities, prefer {@link verifyJsonLd}, which is
|
|
1511
|
-
* the public verification entry point and the one that emits the
|
|
1512
|
-
* `activitypub.signature.verification.duration` metric for the LD path.
|
|
1513
|
-
* `verifySignature` itself only emits
|
|
1514
|
-
* `activitypub.signature.key_fetch.duration`, since the rest of the work
|
|
1515
|
-
* that the verification-duration metric is meant to cover happens in
|
|
1516
|
-
* `verifyJsonLd`.
|
|
1517
|
-
* @param jsonLd The JSON-LD document to verify.
|
|
1518
|
-
* @param options Options for verifying the signature.
|
|
1519
|
-
* @returns The public key that signed the document or `null` if the signature
|
|
1520
|
-
* is invalid or the key is not found.
|
|
1521
|
-
* @since 1.0.0
|
|
1522
|
-
*/
|
|
1523
|
-
async function verifySignature(jsonLd, options = {}) {
|
|
1524
|
-
if (!hasSignature(jsonLd)) return null;
|
|
1525
|
-
if (options[verificationObservation]?.attempt != null && options[verificationObservation]?.check == null) {
|
|
1526
|
-
const declared = getLdSignatureObject(jsonLd)?.creator;
|
|
1527
|
-
return await observeCheck(options, { mechanism: "linkedData" }, typeof declared === "string" ? declared : null, (observation) => verifySignature(jsonLd, {
|
|
1528
|
-
...options,
|
|
1529
|
-
[verificationObservation]: observation
|
|
1530
|
-
}));
|
|
1531
|
-
}
|
|
1532
|
-
const sig = jsonLd.signature;
|
|
1533
|
-
let signature;
|
|
1534
|
-
try {
|
|
1535
|
-
signature = decodeBase64(sig.signatureValue);
|
|
1536
|
-
} catch (error) {
|
|
1537
|
-
logger.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
|
|
1538
|
-
...sig,
|
|
1539
|
-
error
|
|
1540
|
-
});
|
|
1541
|
-
return null;
|
|
1542
|
-
}
|
|
1543
|
-
const { key, cached } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, options));
|
|
1544
|
-
if (key == null) return null;
|
|
1545
|
-
const sigOpts = {
|
|
1546
|
-
...sig,
|
|
1547
|
-
"@context": "https://w3id.org/identity/v1"
|
|
1548
|
-
};
|
|
1549
|
-
delete sigOpts.type;
|
|
1550
|
-
delete sigOpts.id;
|
|
1551
|
-
delete sigOpts.signatureValue;
|
|
1552
|
-
let sigOptsHash;
|
|
1553
|
-
try {
|
|
1554
|
-
sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
|
|
1555
|
-
} catch (error) {
|
|
1556
|
-
logger.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
|
|
1557
|
-
signatureOptions: sigOpts,
|
|
1558
|
-
error
|
|
1559
|
-
});
|
|
1560
|
-
return null;
|
|
1561
|
-
}
|
|
1562
|
-
const document = { ...jsonLd };
|
|
1563
|
-
delete document.signature;
|
|
1564
|
-
let docHash;
|
|
1565
|
-
try {
|
|
1566
|
-
docHash = await hashJsonLd(document, options.contextLoader);
|
|
1567
|
-
} catch (error) {
|
|
1568
|
-
logger.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
|
|
1569
|
-
document,
|
|
1570
|
-
error
|
|
1571
|
-
});
|
|
1572
|
-
return null;
|
|
1573
|
-
}
|
|
1574
|
-
const encoder = new TextEncoder();
|
|
1575
|
-
const message = sigOptsHash + docHash;
|
|
1576
|
-
const messageBytes = encoder.encode(message);
|
|
1577
|
-
triedKey(options, key);
|
|
1578
|
-
if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
|
|
1579
|
-
if (cached) {
|
|
1580
|
-
logger.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
|
|
1581
|
-
keyId: sig.creator,
|
|
1582
|
-
...sig
|
|
1583
|
-
});
|
|
1584
|
-
const { key } = await measureSignatureKeyFetch(options.meterProvider, "linked_data", () => fetchKey(new URL(sig.creator), CryptographicKey, {
|
|
1585
|
-
...options,
|
|
1586
|
-
keyCache: bypassKeyCacheReads(options.keyCache)
|
|
1587
|
-
}));
|
|
1588
|
-
if (key == null) return null;
|
|
1589
|
-
triedKey(options, key);
|
|
1590
|
-
return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
|
|
1591
|
-
}
|
|
1592
|
-
logger.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}", {
|
|
1593
|
-
keyId: sig.creator,
|
|
1594
|
-
...sig,
|
|
1595
|
-
message
|
|
1596
|
-
});
|
|
1597
|
-
return null;
|
|
1598
|
-
}
|
|
1599
|
-
/**
|
|
1600
|
-
* Known Linked Data Signature `type` values, used to keep
|
|
1601
|
-
* `ld_signatures.type` on a bounded set of spec-defined string values.
|
|
1602
|
-
* Fedify only signs and verifies `RsaSignature2017`; other values come in
|
|
1603
|
-
* only from external documents and are dropped from the metric attribute to
|
|
1604
|
-
* avoid attacker-controlled cardinality.
|
|
1605
|
-
*/
|
|
1606
|
-
const LD_KNOWN_SIGNATURE_TYPES = /* @__PURE__ */ new Set(["RsaSignature2017"]);
|
|
1607
|
-
/**
|
|
1608
|
-
* Reports only whether a `signature` key is present on the document, with
|
|
1609
|
-
* no shape check on its value. This is intentionally looser than
|
|
1610
|
-
* {@link hasSignature} (which validates a full `RsaSignature2017` shape)
|
|
1611
|
-
* and {@link hasSignatureLike} (which structurally accepts several known
|
|
1612
|
-
* suites): `verifyJsonLd` needs to tell a document with a malformed or
|
|
1613
|
-
* unsupported signature payload (classified as `rejected`) apart from a
|
|
1614
|
-
* truly unsigned document (classified as `missing`), and only this
|
|
1615
|
-
* presence-only check captures both cases.
|
|
1616
|
-
*/
|
|
1617
|
-
function hasLdSignatureProperty(jsonLd) {
|
|
1618
|
-
return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
|
|
1619
|
-
}
|
|
1620
|
-
function getLdSignatureObject(jsonLd) {
|
|
1621
|
-
if (!hasLdSignatureProperty(jsonLd)) return void 0;
|
|
1622
|
-
const { signature } = jsonLd;
|
|
1623
|
-
if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
|
|
1624
|
-
return signature;
|
|
1625
|
-
}
|
|
1626
|
-
/**
|
|
1627
|
-
* Verify the authenticity of the given JSON-LD document using Linked Data
|
|
1628
|
-
* Signatures. If the document is signed, this function verifies the signature
|
|
1629
|
-
* and checks if the document is attributed to the owner of the public key.
|
|
1630
|
-
* If the document is not signed, this function returns `false`.
|
|
1631
|
-
* @param jsonLd The JSON-LD document to verify.
|
|
1632
|
-
* @param options Options for verifying the document.
|
|
1633
|
-
* @returns `true` if the document is authentic; `false` otherwise.
|
|
1634
|
-
*/
|
|
1635
|
-
async function verifyJsonLd(jsonLd, options = {}) {
|
|
1636
|
-
return (await verifyJsonLdInternal(jsonLd, options, true)).verified;
|
|
1637
|
-
}
|
|
1638
|
-
/** @internal */
|
|
1639
|
-
async function verifyCompactJsonLd(jsonLd, options = {}) {
|
|
1640
|
-
return (await verifyJsonLdInternal(jsonLd, options, false)).verified;
|
|
1641
|
-
}
|
|
1642
|
-
/**
|
|
1643
|
-
* Same as {@link verifyCompactJsonLd}, but also returns the key that verified
|
|
1644
|
-
* the signature, whose `owner` {@link fetchKey} has confirmed.
|
|
1645
|
-
* @param jsonLd The compacted JSON-LD document to verify.
|
|
1646
|
-
* @param options Options for verifying the JSON-LD document.
|
|
1647
|
-
* @returns The result.
|
|
1648
|
-
* @internal
|
|
1649
|
-
*/
|
|
1650
|
-
async function verifyCompactJsonLdDetailed(jsonLd, options = {}) {
|
|
1651
|
-
return await verifyJsonLdInternal(jsonLd, options, false);
|
|
1652
|
-
}
|
|
1653
|
-
async function verifyJsonLdInternal(jsonLd, options, compact) {
|
|
1654
|
-
if (options[verificationObservation]?.attempt == null) return await observeAttempt({
|
|
1655
|
-
...options,
|
|
1656
|
-
[verificationObservation]: options[verificationObservation] ?? { attempts: [] }
|
|
1657
|
-
}, "linkedData", (observation) => verifyJsonLdInternal(jsonLd, {
|
|
1658
|
-
...options,
|
|
1659
|
-
[verificationObservation]: observation
|
|
1660
|
-
}, compact), (value) => value.verified);
|
|
1661
|
-
const observation = options[verificationObservation];
|
|
1662
|
-
return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
|
|
1663
|
-
const start = performance.now();
|
|
1664
|
-
let verified = false;
|
|
1665
|
-
let threw = false;
|
|
1666
|
-
let signatureType;
|
|
1667
|
-
try {
|
|
1668
|
-
const verificationOptions = hasSignature(jsonLd) ? {
|
|
1669
|
-
...options,
|
|
1670
|
-
contextLoader: getNormalizationContextLoader(options.contextLoader)
|
|
1671
|
-
} : options;
|
|
1672
|
-
const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
|
|
1673
|
-
const object = await Object$1.fromJsonLd(compacted, verificationOptions);
|
|
1674
|
-
observation?.parsedObject?.(object);
|
|
1675
|
-
if (observation?.subject != null) observation.subject.id = object.id == null ? null : new URL(object.id.href);
|
|
1676
|
-
if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
|
|
1677
|
-
span.setAttribute("activitypub.object.type", getTypeId(object).href);
|
|
1678
|
-
const sig = getLdSignatureObject(jsonLd);
|
|
1679
|
-
if (sig != null) {
|
|
1680
|
-
if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
|
|
1681
|
-
if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
|
|
1682
|
-
if (typeof sig.type === "string") {
|
|
1683
|
-
span.setAttribute("ld_signatures.type", sig.type);
|
|
1684
|
-
if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
const attributions = new Set(object.attributionIds.map((uri) => uri.href));
|
|
1688
|
-
if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
|
|
1689
|
-
const key = await verifySignature(compacted, verificationOptions);
|
|
1690
|
-
if (key == null) {
|
|
1691
|
-
if (observation?.attempt != null && !hasLdSignatureProperty(jsonLd)) observation.attempt.reason = { type: "noSignature" };
|
|
1692
|
-
return {
|
|
1693
|
-
verified: false,
|
|
1694
|
-
key: null
|
|
1695
|
-
};
|
|
1696
|
-
}
|
|
1697
|
-
if (key.ownerId == null) {
|
|
1698
|
-
if (observation?.attempt != null) observation.attempt.reason = { type: "missingOwner" };
|
|
1699
|
-
logger.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
|
|
1700
|
-
return {
|
|
1701
|
-
verified: false,
|
|
1702
|
-
key: null
|
|
1703
|
-
};
|
|
1704
|
-
}
|
|
1705
|
-
attributions.delete(key.ownerId.href);
|
|
1706
|
-
if (attributions.size > 0) {
|
|
1707
|
-
if (observation?.attempt != null) observation.attempt.reason = {
|
|
1708
|
-
type: "uncoveredAttribution",
|
|
1709
|
-
attributionIds: [...attributions].map((id) => new URL(id))
|
|
1710
|
-
};
|
|
1711
|
-
logger.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
|
|
1712
|
-
return {
|
|
1713
|
-
verified: false,
|
|
1714
|
-
key: null
|
|
1715
|
-
};
|
|
1716
|
-
}
|
|
1717
|
-
verified = true;
|
|
1718
|
-
return {
|
|
1719
|
-
verified: true,
|
|
1720
|
-
key
|
|
1721
|
-
};
|
|
1722
|
-
} catch (error) {
|
|
1723
|
-
threw = true;
|
|
1724
|
-
span.setStatus({
|
|
1725
|
-
code: SpanStatusCode.ERROR,
|
|
1726
|
-
message: String(error)
|
|
1727
|
-
});
|
|
1728
|
-
throw error;
|
|
1729
|
-
} finally {
|
|
1730
|
-
if (observation?.attempt?.reason != null) {
|
|
1731
|
-
span.setAttribute("activitypub.verification.failure_reason", observation.attempt.reason.type);
|
|
1732
|
-
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1733
|
-
}
|
|
1734
|
-
const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
|
|
1735
|
-
getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "linked_data", classified, {
|
|
1736
|
-
ldType: signatureType,
|
|
1737
|
-
verificationFailureReason: verified || threw ? void 0 : observation?.attempt?.reason?.type ?? (hasLdSignatureProperty(jsonLd) ? "signatureVerificationFailed" : "noSignature")
|
|
1738
|
-
});
|
|
1739
|
-
span.end();
|
|
1740
|
-
}
|
|
1741
|
-
});
|
|
1742
|
-
}
|
|
1743
|
-
async function hashJsonLd(jsonLd, contextLoader) {
|
|
1744
|
-
const canon = await jsonld.canonize(jsonLd, {
|
|
1745
|
-
format: "application/n-quads",
|
|
1746
|
-
documentLoader: contextLoader ?? getDocumentLoader()
|
|
1747
|
-
});
|
|
1748
|
-
const encoder = new TextEncoder();
|
|
1749
|
-
return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
|
|
1750
|
-
}
|
|
1751
|
-
//#endregion
|
|
1752
|
-
export { fetchKey as C, validateCryptoKey as D, importJwk as E, verifyKeyOwnership as O, fetchActorDocument as S, generateCryptoKeyPair as T, verifyJsonLd as _, compactJsonLd as a, bypassKeyCacheReads as b, getNormalizationContextLoader as c, isClearlyMalformedContextReference as d, isInvalidUrlTypeError as f, verifyCompactJsonLdDetailed as g, verifyCompactJsonLd as h, attachSignature as i, hasSignature as l, signJsonLd as m, UnsafeJsonLdError as n, createSignature as o, markEffectiveContextLoader as p, assertSafeJsonLd as r, detachSignature as s, InvalidContextReferenceError as t, hasSignatureLike as u, verifySignature as v, fetchKeyDetailed as w, exportJwk as x, wrapContextLoaderForJsonLd as y };
|