@fedify/fedify 2.1.12 → 2.1.14

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.
Files changed (96) hide show
  1. package/dist/{builder-D9hlyCx5.mjs → builder-BBifZZ5G.mjs} +3 -3
  2. package/dist/{chunk-nlSIicah.js → chunk-CRNNMoPX.js} +2 -2
  3. package/dist/{client-z-8dc-e1.d.cts → client-CAM_bQXx.d.cts} +1 -0
  4. package/dist/{client-AtlibPOU.d.ts → client-CSddvgWN.d.ts} +1 -2
  5. package/dist/compat/mod.d.cts +2 -1
  6. package/dist/compat/mod.d.ts +2 -3
  7. package/dist/compat/mod.js +3 -3
  8. package/dist/compat/transformers.test.mjs +1 -1
  9. package/dist/{context-C0fssarc.d.ts → context-_l9t359k.d.ts} +53 -12
  10. package/dist/{context-LmrZPwti.d.cts → context-o22vjzS2.d.cts} +53 -10
  11. package/dist/{deno-Ddb3P7G7.mjs → deno-bqnW1QlD.mjs} +1 -1
  12. package/dist/{docloader-CK8tewt1.mjs → docloader-D-Fu0kBF.mjs} +2 -2
  13. package/dist/federation/builder.test.mjs +1 -1
  14. package/dist/federation/handler.test.mjs +1361 -41
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/inbox.test.mjs +1 -1
  17. package/dist/federation/middleware.test.mjs +1588 -84
  18. package/dist/federation/mod.cjs +1 -1
  19. package/dist/federation/mod.d.cts +4 -3
  20. package/dist/federation/mod.d.ts +4 -5
  21. package/dist/federation/mod.js +2 -2
  22. package/dist/federation/retry.test.mjs +1 -1
  23. package/dist/federation/send.test.mjs +3 -3
  24. package/dist/federation/temporal.test.d.mts +2 -0
  25. package/dist/federation/temporal.test.mjs +71 -0
  26. package/dist/federation/webfinger.test.mjs +1 -1
  27. package/dist/{http-CrGuipxe.d.cts → http-BDZeS5om.d.ts} +2 -1
  28. package/dist/{http-aQzN9Ayi.d.ts → http-C87EWkO0.d.cts} +2 -3
  29. package/dist/{http-CmDErAnD.cjs → http-CEXtUHix.cjs} +57 -9
  30. package/dist/{http-qKyJKSnF.js → http-Cw1EorUA.js} +58 -10
  31. package/dist/{http-DRDpStn2.mjs → http-DvhFwy2E.mjs} +58 -10
  32. package/dist/{inbox-DTuPJEma.mjs → inbox-7b3VYnec.mjs} +7 -4
  33. package/dist/{key-WSedbAA-.mjs → key-B3OBz6A_.mjs} +1 -1
  34. package/dist/{kv-CbLNp3zQ.d.cts → kv-D6hNiMTK.d.ts} +1 -0
  35. package/dist/{kv-cache-9cdQDeT0.cjs → kv-cache-BIapFiSV.cjs} +2 -2
  36. package/dist/{kv-cache-DNNRFY8u.js → kv-cache-C6nynGhh.js} +2 -2
  37. package/dist/{kv-cache-B01V7s3h.mjs → kv-cache-FsT1ljhs.mjs} +1 -1
  38. package/dist/{kv-GFYnFoOl.d.ts → kv-gJ8LYbxX.d.cts} +1 -3
  39. package/dist/ld-DTxYKZTT.mjs +550 -0
  40. package/dist/{middleware-UThUK30x.js → middleware-0vceVN10.js} +407 -82
  41. package/dist/{middleware-DFcgN1cH.cjs → middleware-BcbU5lKS.cjs} +406 -80
  42. package/dist/{middleware-8P6Z15Wq.cjs → middleware-DUT--Qen.cjs} +1 -1
  43. package/dist/{middleware-DDsnRvFC.mjs → middleware-DmT9t0BJ.mjs} +317 -84
  44. package/dist/{middleware-C2c1rlmE.mjs → middleware-Li_g_vqz.mjs} +1 -1
  45. package/dist/{mod-CnwZoDzx.d.ts → mod-0dF0OeGw.d.cts} +2 -3
  46. package/dist/{mod-B505FZBC.d.cts → mod-BTWFtZwa.d.ts} +4 -3
  47. package/dist/{mod-Cgpc49fA.d.cts → mod-Bv1elC-b.d.ts} +2 -1
  48. package/dist/{mod-DoJBjjnO.d.cts → mod-CjiK2zrW.d.ts} +3 -2
  49. package/dist/{mod-DvxszxXC.d.ts → mod-D5YlzzP3.d.cts} +3 -4
  50. package/dist/{mod-D7PAuO6k.d.ts → mod-dxOnKp2Y.d.cts} +4 -5
  51. package/dist/mod.cjs +4 -4
  52. package/dist/mod.d.cts +9 -8
  53. package/dist/mod.d.ts +9 -10
  54. package/dist/mod.js +9 -9
  55. package/dist/nodeinfo/handler.test.mjs +1 -1
  56. package/dist/nodeinfo/mod.d.cts +2 -1
  57. package/dist/nodeinfo/mod.d.ts +2 -3
  58. package/dist/nodeinfo/mod.js +3 -3
  59. package/dist/otel/mod.d.cts +2 -1
  60. package/dist/otel/mod.d.ts +2 -3
  61. package/dist/otel/mod.js +2 -2
  62. package/dist/{owner-CptqhsOy.d.cts → owner-CnngXDNJ.d.ts} +2 -1
  63. package/dist/{owner-74ARJ5TL.d.ts → owner-DEvZuyOE.d.cts} +2 -3
  64. package/dist/{owner-BceqCVOs.mjs → owner-DzcnuWYo.mjs} +2 -2
  65. package/dist/{proof-4NUQlbQV.js → proof-CtTT8A7y.js} +299 -5
  66. package/dist/{proof-BojC8L94.mjs → proof-DmVGi7mI.mjs} +2 -2
  67. package/dist/{proof-kuTIVfyZ.cjs → proof-JEoW3ODq.cjs} +345 -3
  68. package/dist/runtime/mod.d.cts +1 -0
  69. package/dist/runtime/mod.d.ts +1 -2
  70. package/dist/runtime/mod.js +3 -3
  71. package/dist/{send-Buz5Gy8x.mjs → send-5ulOKVCW.mjs} +2 -2
  72. package/dist/sig/http.test.mjs +120 -2
  73. package/dist/sig/key.test.mjs +1 -1
  74. package/dist/sig/ld.test.mjs +558 -2
  75. package/dist/sig/mod.cjs +2 -2
  76. package/dist/sig/mod.d.cts +4 -3
  77. package/dist/sig/mod.d.ts +4 -5
  78. package/dist/sig/mod.js +4 -4
  79. package/dist/sig/owner.test.mjs +1 -1
  80. package/dist/sig/proof.test.mjs +1 -1
  81. package/dist/temporal-CmJkd-25.mjs +95 -0
  82. package/dist/testing/mod.d.mts +48 -6
  83. package/dist/{transformers-ve6e2xcg.js → transformers-BGMIq1cs.js} +2 -2
  84. package/dist/{types-hvL8ElAs.js → types-CAY3OdLq.js} +2 -2
  85. package/dist/utils/docloader.test.mjs +2 -2
  86. package/dist/utils/kv-cache.test.mjs +1 -1
  87. package/dist/utils/mod.cjs +1 -1
  88. package/dist/utils/mod.d.cts +2 -1
  89. package/dist/utils/mod.d.ts +2 -3
  90. package/dist/utils/mod.js +3 -3
  91. package/dist/vocab/mod.d.cts +1 -0
  92. package/dist/vocab/mod.d.ts +1 -2
  93. package/dist/vocab/mod.js +2 -2
  94. package/package.json +7 -7
  95. package/dist/ld-OBpaLfHR.mjs +0 -256
  96. /package/dist/{retry-B_E3V_Dx.mjs → retry-CJL0poaU.mjs} +0 -0
@@ -0,0 +1,95 @@
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import "urlpattern-polyfill";
3
+ globalThis.addEventListener = () => {};
4
+ import { c as getNormalizationContextLoader } from "./ld-DTxYKZTT.mjs";
5
+ import jsonld from "@fedify/vocab-runtime/jsonld";
6
+ //#region src/federation/temporal.ts
7
+ function isPlainObject(value) {
8
+ return typeof value === "object" && value != null && !Array.isArray(value);
9
+ }
10
+ function normalizeDateTimeLiteral(value) {
11
+ return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
12
+ }
13
+ function isMalformedDateTimeLiteral(value) {
14
+ if (typeof value !== "string") return false;
15
+ try {
16
+ Temporal.Instant.from(normalizeDateTimeLiteral(value));
17
+ return false;
18
+ } catch {
19
+ return true;
20
+ }
21
+ }
22
+ function isMalformedDurationLiteral(value) {
23
+ if (typeof value !== "string") return false;
24
+ try {
25
+ Temporal.Duration.from(value);
26
+ return false;
27
+ } catch {
28
+ return true;
29
+ }
30
+ }
31
+ const TEMPORAL_DATE_TIME_IRIS = new Set([
32
+ "https://www.w3.org/ns/activitystreams#deleted",
33
+ "https://www.w3.org/ns/activitystreams#endTime",
34
+ "https://www.w3.org/ns/activitystreams#published",
35
+ "https://www.w3.org/ns/activitystreams#startTime",
36
+ "https://www.w3.org/ns/activitystreams#updated",
37
+ "http://purl.org/dc/terms/created",
38
+ "https://w3id.org/security#created"
39
+ ]);
40
+ const TEMPORAL_DURATION_IRIS = new Set(["https://www.w3.org/ns/activitystreams#duration"]);
41
+ const QUESTION_CLOSED_IRI = "https://www.w3.org/ns/activitystreams#closed";
42
+ const XSD_DATE_TIME_IRI = "http://www.w3.org/2001/XMLSchema#dateTime";
43
+ function hasMalformedExpandedDateTimeLiteral(value) {
44
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedDateTimeLiteral);
45
+ return isPlainObject(value) && "@value" in value && isMalformedDateTimeLiteral(value["@value"]);
46
+ }
47
+ function hasMalformedExpandedQuestionClosedLiteral(value) {
48
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedQuestionClosedLiteral);
49
+ if (!isPlainObject(value) || !("@value" in value)) return false;
50
+ const literal = value["@value"];
51
+ if (typeof literal === "boolean") return false;
52
+ if (typeof literal !== "string") return false;
53
+ if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
54
+ if (new Date(literal).toString() === "Invalid Date") return false;
55
+ return isMalformedDateTimeLiteral(literal);
56
+ }
57
+ function hasMalformedExpandedDurationLiteral(value) {
58
+ if (Array.isArray(value)) return value.some(hasMalformedExpandedDurationLiteral);
59
+ return isPlainObject(value) && "@value" in value && isMalformedDurationLiteral(value["@value"]);
60
+ }
61
+ function hasMalformedKnownTemporalLiteralInternal(value, visited) {
62
+ if (Array.isArray(value)) return value.some((item) => hasMalformedKnownTemporalLiteralInternal(item, visited));
63
+ if (!isPlainObject(value)) return false;
64
+ if (visited.has(value)) return false;
65
+ visited.add(value);
66
+ if ("@value" in value) return false;
67
+ for (const [key, child] of Object.entries(value)) {
68
+ if (TEMPORAL_DATE_TIME_IRIS.has(key)) {
69
+ if (hasMalformedExpandedDateTimeLiteral(child)) return true;
70
+ continue;
71
+ }
72
+ if (key === QUESTION_CLOSED_IRI) {
73
+ if (hasMalformedExpandedQuestionClosedLiteral(child)) return true;
74
+ continue;
75
+ }
76
+ if (TEMPORAL_DURATION_IRIS.has(key)) {
77
+ if (hasMalformedExpandedDurationLiteral(child)) return true;
78
+ continue;
79
+ }
80
+ if (hasMalformedKnownTemporalLiteralInternal(child, visited)) return true;
81
+ }
82
+ return false;
83
+ }
84
+ async function hasMalformedKnownTemporalLiteral(value, contextLoader) {
85
+ try {
86
+ return hasMalformedKnownTemporalLiteralInternal(await jsonld.expand(value, {
87
+ documentLoader: getNormalizationContextLoader(contextLoader),
88
+ keepFreeFloatingNodes: true
89
+ }), /* @__PURE__ */ new Set());
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+ //#endregion
95
+ export { hasMalformedKnownTemporalLiteral as t };
@@ -589,6 +589,42 @@ interface InboxMessage {
589
589
  readonly id: ReturnType<typeof crypto.randomUUID>;
590
590
  readonly baseUrl: string;
591
591
  readonly activity: unknown;
592
+ /**
593
+ * The normalized JSON-LD representation of a signed inbox activity that
594
+ * Fedify already compacted successfully while accepting the request. Queue
595
+ * workers can reuse this producer-side parse cache under stricter loader or
596
+ * network constraints without changing the raw payload preserved for
597
+ * forwarding.
598
+ *
599
+ * This may exist even when {@link ldSignatureVerified} is `false`, because
600
+ * fallback-authenticated traffic and already-queued backlog items can still
601
+ * depend on the cached normalized form to avoid re-fetching remote custom
602
+ * contexts during worker processing.
603
+ *
604
+ * This is optional for backward compatibility with messages that were
605
+ * queued by older Fedify versions or that were already in a queue before
606
+ * upgrading.
607
+ *
608
+ * Fedify keeps this on the queued message itself instead of an external
609
+ * sidecar because generic queue backends do not provide reliable lifecycle
610
+ * guarantees for auxiliary storage across retries and redeliveries.
611
+ *
612
+ * @internal
613
+ */
614
+ readonly normalizedActivity?: unknown;
615
+ /**
616
+ * Whether the producer actually verified the Linked Data Signature before
617
+ * queueing this message. This lets workers distinguish verified LDS replay
618
+ * from other authenticated inbox traffic that merely happened to include a
619
+ * signature block. This provenance marker is separate from the optional
620
+ * normalizedActivity parse cache.
621
+ *
622
+ * `undefined` preserves backward compatibility with older queued messages
623
+ * that predate this marker.
624
+ *
625
+ * @internal
626
+ */
627
+ readonly ldSignatureVerified?: boolean;
592
628
  readonly started: string;
593
629
  readonly attempt: number;
594
630
  readonly identifier: string | null;
@@ -1852,9 +1888,12 @@ interface InboxContext<TContextData> extends Context<TContextData> {
1852
1888
  * Forwards a received activity to the recipients' inboxes. The forwarded
1853
1889
  * activity will be signed in HTTP Signatures by the forwarder, but its
1854
1890
  * payload will not be modified, i.e., Linked Data Signatures and Object
1855
- * Integrity Proofs will not be added. Therefore, if the activity is not
1856
- * signed (i.e., it has neither Linked Data Signatures nor Object Integrity
1857
- * Proofs), the recipient probably will not trust the activity.
1891
+ * Integrity Proofs will not be added. Even when Fedify internally
1892
+ * normalizes a Linked Data Signature activity for parsing, this method still
1893
+ * forwards the original received payload so the sender's signatures/proofs
1894
+ * are preserved as-is. Therefore, if the activity is not signed (i.e., it
1895
+ * has neither Linked Data Signatures nor Object Integrity Proofs), the
1896
+ * recipient probably will not trust the activity.
1858
1897
  * @param forwarder The forwarder's identifier or the forwarder's username
1859
1898
  * or the forwarder's key pair(s).
1860
1899
  * @param recipients The recipients of the activity.
@@ -1870,9 +1909,12 @@ interface InboxContext<TContextData> extends Context<TContextData> {
1870
1909
  * Forwards a received activity to the recipients' inboxes. The forwarded
1871
1910
  * activity will be signed in HTTP Signatures by the forwarder, but its
1872
1911
  * payload will not be modified, i.e., Linked Data Signatures and Object
1873
- * Integrity Proofs will not be added. Therefore, if the activity is not
1874
- * signed (i.e., it has neither Linked Data Signatures nor Object Integrity
1875
- * Proofs), the recipient probably will not trust the activity.
1912
+ * Integrity Proofs will not be added. Even when Fedify internally
1913
+ * normalizes a Linked Data Signature activity for parsing, this method still
1914
+ * forwards the original received payload so the sender's signatures/proofs
1915
+ * are preserved as-is. Therefore, if the activity is not signed (i.e., it
1916
+ * has neither Linked Data Signatures nor Object Integrity Proofs), the
1917
+ * recipient probably will not trust the activity.
1876
1918
  * @param forwarder The forwarder's identifier or the forwarder's username.
1877
1919
  * @param recipients In this case, it must be `"followers"`.
1878
1920
  * @param options Options for forwarding the activity.
@@ -1,5 +1,5 @@
1
- import "@js-temporal/polyfill";
2
- import "urlpattern-polyfill";
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
3
  import { getLogger } from "@logtape/logtape";
4
4
  //#region src/compat/transformers.ts
5
5
  const logger = getLogger([
@@ -1,5 +1,5 @@
1
- import "@js-temporal/polyfill";
2
- import "urlpattern-polyfill";
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
3
  import { getLogger } from "@logtape/logtape";
4
4
  import { getUserAgent } from "@fedify/vocab-runtime";
5
5
  //#region src/nodeinfo/client.ts
@@ -5,9 +5,9 @@ import { t as esm_default } from "../esm-DVILvP5e.mjs";
5
5
  import { t as assertEquals } from "../assert_equals-Ew3jOFa3.mjs";
6
6
  import "../std__assert-Duiq_YC9.mjs";
7
7
  import { t as assertRejects } from "../assert_rejects-B-qJtC9Z.mjs";
8
- import { l as verifyRequest } from "../http-DRDpStn2.mjs";
8
+ import { l as verifyRequest } from "../http-DvhFwy2E.mjs";
9
9
  import { i as rsaPrivateKey2 } from "../keys-BAK-tUlf.mjs";
10
- import { t as getAuthenticatedDocumentLoader } from "../docloader-CK8tewt1.mjs";
10
+ import { t as getAuthenticatedDocumentLoader } from "../docloader-D-Fu0kBF.mjs";
11
11
  import { mockDocumentLoader, test } from "@fedify/fixture";
12
12
  import { UrlError } from "@fedify/vocab-runtime";
13
13
  //#region src/utils/docloader.test.ts
@@ -1,7 +1,7 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as kvCache, t as MockKvStore } from "../kv-cache-B01V7s3h.mjs";
4
+ import { n as kvCache, t as MockKvStore } from "../kv-cache-FsT1ljhs.mjs";
5
5
  import { mockDocumentLoader, test } from "@fedify/fixture";
6
6
  import { deepStrictEqual, throws } from "node:assert";
7
7
  import { preloadedContexts } from "@fedify/vocab-runtime";
@@ -1,6 +1,6 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
- const require_kv_cache = require("../kv-cache-9cdQDeT0.cjs");
4
+ const require_kv_cache = require("../kv-cache-BIapFiSV.cjs");
5
5
  exports.getAuthenticatedDocumentLoader = require_kv_cache.getAuthenticatedDocumentLoader;
6
6
  exports.kvCache = require_kv_cache.kvCache;
@@ -1,2 +1,3 @@
1
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../mod-B505FZBC.cjs";
1
+ /// <reference lib="esnext.temporal" />
2
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../mod-dxOnKp2Y.cjs";
2
3
  export { getAuthenticatedDocumentLoader, kvCache };
@@ -1,4 +1,3 @@
1
- import { Temporal } from "@js-temporal/polyfill";
2
- import { URLPattern } from "urlpattern-polyfill";
3
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../mod-D7PAuO6k.js";
1
+ /// <reference lib="esnext.temporal" />
2
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../mod-BTWFtZwa.js";
4
3
  export { getAuthenticatedDocumentLoader, kvCache };
package/dist/utils/mod.js CHANGED
@@ -1,4 +1,4 @@
1
- import "@js-temporal/polyfill";
2
- import "urlpattern-polyfill";
3
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../kv-cache-DNNRFY8u.js";
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "../kv-cache-C6nynGhh.js";
4
4
  export { getAuthenticatedDocumentLoader, kvCache };
@@ -1 +1,2 @@
1
+ /// <reference lib="esnext.temporal" />
1
2
  export * from "@fedify/vocab";
@@ -1,3 +1,2 @@
1
- import { Temporal } from "@js-temporal/polyfill";
2
- import { URLPattern } from "urlpattern-polyfill";
1
+ /// <reference lib="esnext.temporal" />
3
2
  export * from "@fedify/vocab";
package/dist/vocab/mod.js CHANGED
@@ -1,3 +1,3 @@
1
- import "@js-temporal/polyfill";
2
- import "urlpattern-polyfill";
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
3
  export * from "@fedify/vocab";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/fedify",
3
- "version": "2.1.12",
3
+ "version": "2.1.14",
4
4
  "description": "An ActivityPub server framework",
5
5
  "keywords": [
6
6
  "ActivityPub",
@@ -144,9 +144,9 @@
144
144
  "uri-template-router": "^1.0.0",
145
145
  "url-template": "^3.1.1",
146
146
  "urlpattern-polyfill": "^10.1.0",
147
- "@fedify/vocab-runtime": "2.1.12",
148
- "@fedify/webfinger": "2.1.12",
149
- "@fedify/vocab": "2.1.12"
147
+ "@fedify/webfinger": "2.1.14",
148
+ "@fedify/vocab-runtime": "2.1.14",
149
+ "@fedify/vocab": "2.1.14"
150
150
  },
151
151
  "devDependencies": {
152
152
  "@std/assert": "npm:@jsr/std__assert@^0.226.0",
@@ -156,10 +156,10 @@
156
156
  "miniflare": "^4.20250523.0",
157
157
  "tsdown": "^0.21.6",
158
158
  "tsx": "^4.19.4",
159
- "typescript": "^5.9.2",
159
+ "typescript": "^6.0.0",
160
160
  "wrangler": "^4.17.0",
161
- "@fedify/fixture": "2.0.0",
162
- "@fedify/vocab-tools": "^2.1.12"
161
+ "@fedify/vocab-tools": "^2.1.14",
162
+ "@fedify/fixture": "2.0.0"
163
163
  },
164
164
  "scripts": {
165
165
  "build:self": "tsdown",
@@ -1,256 +0,0 @@
1
- import "@js-temporal/polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-Ddb3P7G7.mjs";
5
- import { n as fetchKey, o as validateCryptoKey } from "./key-WSedbAA-.mjs";
6
- import { Activity, CryptographicKey, Object as Object$1, getTypeId } from "@fedify/vocab";
7
- import { SpanStatusCode, trace } from "@opentelemetry/api";
8
- import { getDocumentLoader } from "@fedify/vocab-runtime";
9
- import { getLogger } from "@logtape/logtape";
10
- import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
11
- import { encodeHex } from "byte-encodings/hex";
12
- import jsonld from "@fedify/vocab-runtime/jsonld";
13
- //#region src/sig/ld.ts
14
- const logger = getLogger([
15
- "fedify",
16
- "sig",
17
- "ld"
18
- ]);
19
- /**
20
- * Attaches a LD signature to the given JSON-LD document.
21
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
22
- * modified.
23
- * @param signature The signature to attach.
24
- * @returns The JSON-LD document with the attached signature.
25
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
26
- * @since 1.0.0
27
- */
28
- function attachSignature(jsonLd, signature) {
29
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
30
- return {
31
- ...jsonLd,
32
- signature
33
- };
34
- }
35
- /**
36
- * Creates a LD signature for the given JSON-LD document.
37
- * @param jsonLd The JSON-LD document to sign.
38
- * @param privateKey The private key to sign the document.
39
- * @param keyId The ID of the public key that corresponds to the private key.
40
- * @param options Additional options for creating the signature.
41
- * See also {@link CreateSignatureOptions}.
42
- * @return The created signature.
43
- * @throws {TypeError} If the private key is invalid or unsupported.
44
- * @since 1.0.0
45
- */
46
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
47
- validateCryptoKey(privateKey, "private");
48
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
49
- const options = {
50
- "@context": "https://w3id.org/identity/v1",
51
- creator: keyId.href,
52
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
53
- };
54
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
55
- const messageBytes = new TextEncoder().encode(message);
56
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
57
- return {
58
- ...options,
59
- type: "RsaSignature2017",
60
- signatureValue: encodeBase64(signature)
61
- };
62
- }
63
- /**
64
- * Signs the given JSON-LD document with the private key and returns the signed
65
- * JSON-LD document.
66
- * @param jsonLd The JSON-LD document to sign.
67
- * @param privateKey The private key to sign the document.
68
- * @param keyId The key ID to use in the signature. It will be used by the
69
- * verifier to fetch the corresponding public key.
70
- * @param options Additional options for signing the document.
71
- * See also {@link SignJsonLdOptions}.
72
- * @returns The signed JSON-LD document.
73
- * @throws {TypeError} If the private key is invalid or unsupported.
74
- * @since 1.0.0
75
- */
76
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
77
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
78
- try {
79
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
80
- if (span.isRecording()) {
81
- span.setAttribute("ld_signatures.type", signature.type);
82
- span.setAttribute("ld_signatures.signature", encodeHex(decodeBase64(signature.signatureValue)));
83
- }
84
- return attachSignature(jsonLd, signature);
85
- } catch (error) {
86
- span.setStatus({
87
- code: SpanStatusCode.ERROR,
88
- message: String(error)
89
- });
90
- throw error;
91
- } finally {
92
- span.end();
93
- }
94
- });
95
- }
96
- /**
97
- * Checks if the given JSON-LD document has a Linked Data Signature.
98
- * @param jsonLd The JSON-LD document to check.
99
- * @returns `true` if the document has a signature; `false` otherwise.
100
- * @since 1.0.0
101
- */
102
- function hasSignature(jsonLd) {
103
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
104
- if ("signature" in jsonLd) {
105
- const signature = jsonLd.signature;
106
- if (typeof signature !== "object" || signature == null) return false;
107
- 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";
108
- }
109
- return false;
110
- }
111
- /**
112
- * Detaches Linked Data Signatures from the given JSON-LD document.
113
- * @param jsonLd The JSON-LD document to modify.
114
- * @returns The modified JSON-LD document. If the input document does not
115
- * contain a signature, the original document is returned.
116
- * @since 1.0.0
117
- */
118
- function detachSignature(jsonLd) {
119
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
120
- const doc = { ...jsonLd };
121
- delete doc.signature;
122
- return doc;
123
- }
124
- /**
125
- * Verifies Linked Data Signatures of the given JSON-LD document.
126
- * @param jsonLd The JSON-LD document to verify.
127
- * @param options Options for verifying the signature.
128
- * @returns The public key that signed the document or `null` if the signature
129
- * is invalid or the key is not found.
130
- * @since 1.0.0
131
- */
132
- async function verifySignature(jsonLd, options = {}) {
133
- if (!hasSignature(jsonLd)) return null;
134
- const sig = jsonLd.signature;
135
- let signature;
136
- try {
137
- signature = decodeBase64(sig.signatureValue);
138
- } catch (error) {
139
- logger.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
140
- ...sig,
141
- error
142
- });
143
- return null;
144
- }
145
- const { key, cached } = await fetchKey(new URL(sig.creator), CryptographicKey, options);
146
- if (key == null) return null;
147
- const sigOpts = {
148
- ...sig,
149
- "@context": "https://w3id.org/identity/v1"
150
- };
151
- delete sigOpts.type;
152
- delete sigOpts.id;
153
- delete sigOpts.signatureValue;
154
- let sigOptsHash;
155
- try {
156
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
157
- } catch (error) {
158
- logger.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
159
- signatureOptions: sigOpts,
160
- error
161
- });
162
- return null;
163
- }
164
- const document = { ...jsonLd };
165
- delete document.signature;
166
- let docHash;
167
- try {
168
- docHash = await hashJsonLd(document, options.contextLoader);
169
- } catch (error) {
170
- logger.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
171
- document,
172
- error
173
- });
174
- return null;
175
- }
176
- const encoder = new TextEncoder();
177
- const message = sigOptsHash + docHash;
178
- const messageBytes = encoder.encode(message);
179
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
180
- if (cached) {
181
- logger.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
182
- keyId: sig.creator,
183
- ...sig
184
- });
185
- const { key } = await fetchKey(new URL(sig.creator), CryptographicKey, {
186
- ...options,
187
- keyCache: {
188
- get: () => Promise.resolve(void 0),
189
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
190
- }
191
- });
192
- if (key == null) return null;
193
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
194
- }
195
- 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}", {
196
- keyId: sig.creator,
197
- ...sig,
198
- message
199
- });
200
- return null;
201
- }
202
- /**
203
- * Verify the authenticity of the given JSON-LD document using Linked Data
204
- * Signatures. If the document is signed, this function verifies the signature
205
- * and checks if the document is attributed to the owner of the public key.
206
- * If the document is not signed, this function returns `false`.
207
- * @param jsonLd The JSON-LD document to verify.
208
- * @param options Options for verifying the document.
209
- * @returns `true` if the document is authentic; `false` otherwise.
210
- */
211
- async function verifyJsonLd(jsonLd, options = {}) {
212
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
213
- try {
214
- const object = await Object$1.fromJsonLd(jsonLd, options);
215
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
216
- span.setAttribute("activitypub.object.type", getTypeId(object).href);
217
- if (typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd && typeof jsonLd.signature === "object" && jsonLd.signature != null) {
218
- if ("creator" in jsonLd.signature && typeof jsonLd.signature.creator === "string") span.setAttribute("ld_signatures.key_id", jsonLd.signature.creator);
219
- if ("signatureValue" in jsonLd.signature && typeof jsonLd.signature.signatureValue === "string") span.setAttribute("ld_signatures.signature", jsonLd.signature.signatureValue);
220
- if ("type" in jsonLd.signature && typeof jsonLd.signature.type === "string") span.setAttribute("ld_signatures.type", jsonLd.signature.type);
221
- }
222
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
223
- if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
224
- const key = await verifySignature(jsonLd, options);
225
- if (key == null) return false;
226
- if (key.ownerId == null) {
227
- logger.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
228
- return false;
229
- }
230
- attributions.delete(key.ownerId.href);
231
- if (attributions.size > 0) {
232
- logger.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
233
- return false;
234
- }
235
- return true;
236
- } catch (error) {
237
- span.setStatus({
238
- code: SpanStatusCode.ERROR,
239
- message: String(error)
240
- });
241
- throw error;
242
- } finally {
243
- span.end();
244
- }
245
- });
246
- }
247
- async function hashJsonLd(jsonLd, contextLoader) {
248
- const canon = await jsonld.canonize(jsonLd, {
249
- format: "application/n-quads",
250
- documentLoader: contextLoader ?? getDocumentLoader()
251
- });
252
- const encoder = new TextEncoder();
253
- return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
254
- }
255
- //#endregion
256
- export { signJsonLd as a, hasSignature as i, createSignature as n, verifyJsonLd as o, detachSignature as r, verifySignature as s, attachSignature as t };
File without changes