@fedify/fedify 2.2.0-pr.715.28 → 2.2.0-pr.731.34

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 (87) hide show
  1. package/dist/assert_strict_equals-Dmjbg-bA.mjs +41 -0
  2. package/dist/{builder-BfmqkrIE.mjs → builder-OFkoAQ85.mjs} +3 -3
  3. package/dist/compat/mod.d.cts +1 -1
  4. package/dist/compat/mod.d.ts +1 -1
  5. package/dist/compat/outgoing-jsonld.test.d.mts +2 -0
  6. package/dist/compat/outgoing-jsonld.test.mjs +189 -0
  7. package/dist/compat/public-audience.test.d.mts +2 -0
  8. package/dist/compat/public-audience.test.mjs +178 -0
  9. package/dist/compat/transformers.test.mjs +3 -3
  10. package/dist/{context-BGrYMSTk.d.ts → context-BzH2-ajs.d.ts} +22 -0
  11. package/dist/{context-CMUd4wy0.d.cts → context-DJGagtNd.d.cts} +22 -0
  12. package/dist/{deno-CjZGHpS5.mjs → deno-BYRjHaeb.mjs} +1 -1
  13. package/dist/{docloader-Du9_2PyA.mjs → docloader-CuVh02a1.mjs} +2 -2
  14. package/dist/federation/builder.test.mjs +3 -3
  15. package/dist/federation/collection.test.mjs +2 -2
  16. package/dist/federation/handler.test.mjs +8 -8
  17. package/dist/federation/idempotency.test.mjs +5 -5
  18. package/dist/federation/inbox.test.mjs +1 -1
  19. package/dist/federation/keycache.test.mjs +3 -3
  20. package/dist/federation/kv.test.mjs +2 -2
  21. package/dist/federation/middleware.test.mjs +160 -10
  22. package/dist/federation/mod.cjs +1 -1
  23. package/dist/federation/mod.d.cts +2 -2
  24. package/dist/federation/mod.d.ts +2 -2
  25. package/dist/federation/mod.js +1 -1
  26. package/dist/federation/mq.test.mjs +17 -10
  27. package/dist/federation/negotiation.test.mjs +3 -3
  28. package/dist/federation/retry.test.mjs +1 -1
  29. package/dist/federation/router.test.mjs +2 -2
  30. package/dist/federation/send.test.mjs +6 -6
  31. package/dist/federation/webfinger.test.mjs +3 -3
  32. package/dist/{http-9zjtsC0n.mjs → http-BrVfkREl.mjs} +3 -3
  33. package/dist/{http-Wm7tvhRa.cjs → http-H-4FzBb3.cjs} +1 -1
  34. package/dist/{http-C8puyZ4Z.js → http-pZce7PcA.js} +1 -1
  35. package/dist/{key-CMhIdO1-.mjs → key-cK-YTNKa.mjs} +1 -1
  36. package/dist/{kv-cache-BTq6qqgJ.js → kv-cache-CjweM0Am.js} +1 -1
  37. package/dist/{kv-cache-DyRjARFV.cjs → kv-cache-NgzTkTjv.cjs} +1 -1
  38. package/dist/{ld-BH-6muxq.mjs → ld-SXDkzuUo.mjs} +2 -2
  39. package/dist/{middleware-CO5RpqOP.mjs → middleware-AqjYcDmu.mjs} +1 -1
  40. package/dist/{middleware-DBgitte6.mjs → middleware-BMePykoo.mjs} +34 -22
  41. package/dist/{middleware-D3S_Ctwx.cjs → middleware-CXhCkBG4.cjs} +1 -1
  42. package/dist/{middleware-C_CRggCg.cjs → middleware-TZHT1gKk.cjs} +20 -9
  43. package/dist/{middleware-Da-j6H9U.js → middleware-YcQIUUHs.js} +19 -8
  44. package/dist/{mod-CJXfyw7v.d.ts → mod-2d12ffz3.d.ts} +1 -1
  45. package/dist/{mod-BcJHeuv1.d.cts → mod-D35TRn09.d.cts} +1 -1
  46. package/dist/mod.cjs +4 -4
  47. package/dist/mod.d.cts +2 -2
  48. package/dist/mod.d.ts +2 -2
  49. package/dist/mod.js +4 -4
  50. package/dist/nodeinfo/client.test.mjs +2 -2
  51. package/dist/nodeinfo/handler.test.mjs +3 -3
  52. package/dist/nodeinfo/types.test.mjs +2 -2
  53. package/dist/otel/exporter.test.mjs +2 -2
  54. package/dist/outgoing-jsonld-CNmZLixq.mjs +203 -0
  55. package/dist/{owner-CE5FwvNR.mjs → owner-Cudh-ej0.mjs} +2 -2
  56. package/dist/{proof-jHDv7IKD.js → proof-BJrEACyu.js} +425 -41
  57. package/dist/{proof-D-HuDCQe.cjs → proof-CFERN43j.cjs} +428 -38
  58. package/dist/{proof-Ds3T1-sE.mjs → proof-DC69vtxY.mjs} +38 -31
  59. package/dist/public-audience-DYFHzm_c.mjs +192 -0
  60. package/dist/{send-TicMA6nJ.mjs → send-BBRG1CKC.mjs} +2 -2
  61. package/dist/sig/accept.test.mjs +1 -1
  62. package/dist/sig/http.test.mjs +5 -5
  63. package/dist/sig/key.test.mjs +3 -3
  64. package/dist/sig/ld.test.mjs +4 -4
  65. package/dist/sig/mod.cjs +2 -2
  66. package/dist/sig/mod.js +2 -2
  67. package/dist/sig/owner.test.mjs +4 -4
  68. package/dist/sig/proof.test.mjs +78 -5
  69. package/dist/{std__assert-Duiq_YC9.mjs → std__assert-CRDpx_HF.mjs} +3 -38
  70. package/dist/testing/mod.d.mts +22 -0
  71. package/dist/utils/docloader.test.mjs +4 -4
  72. package/dist/utils/kv-cache.test.mjs +1 -1
  73. package/dist/utils/mod.cjs +1 -1
  74. package/dist/utils/mod.js +1 -1
  75. package/package.json +5 -5
  76. /package/dist/{accept-Dd__NiUL.mjs → accept-CPkZzmGN.mjs} +0 -0
  77. /package/dist/{activity-listener-Ck3JZ_hR.mjs → activity-listener-ell7W1s9.mjs} +0 -0
  78. /package/dist/{assert-ddO5KLpe.mjs → assert-DikXweDx.mjs} +0 -0
  79. /package/dist/{client-DEpOVgY1.mjs → client-D_1QpnWt.mjs} +0 -0
  80. /package/dist/{collection-BD6-SZ6O.mjs → collection-D-HqUuA2.mjs} +0 -0
  81. /package/dist/{keycache-CCSwkQcY.mjs → keycache-EGATflN-.mjs} +0 -0
  82. /package/dist/{keys-BAK-tUlf.mjs → keys-DGu1NFwu.mjs} +0 -0
  83. /package/dist/{kv-cache-B01V7s3h.mjs → kv-cache-U__xU4qR.mjs} +0 -0
  84. /package/dist/{kv-tL2TOE9X.mjs → kv-rV3vodCc.mjs} +0 -0
  85. /package/dist/{negotiation-DnsfFF8I.mjs → negotiation-SQvQgUqe.mjs} +0 -0
  86. /package/dist/{retry-B_E3V_Dx.mjs → retry-bMXBL97A.mjs} +0 -0
  87. /package/dist/{types-DCP0WLdt.mjs → types-J53Kw7so.mjs} +0 -0
@@ -1,7 +1,7 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  const require_chunk = require("./chunk-DDcVe30Y.cjs");
4
- const require_http = require("./http-Wm7tvhRa.cjs");
4
+ const require_http = require("./http-H-4FzBb3.cjs");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  let _fedify_vocab = require("@fedify/vocab");
7
7
  let _opentelemetry_api = require("@opentelemetry/api");
@@ -13,7 +13,7 @@ _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonl
13
13
  let json_canon = require("json-canon");
14
14
  json_canon = require_chunk.__toESM(json_canon);
15
15
  //#region src/sig/ld.ts
16
- const logger$1 = (0, _logtape_logtape.getLogger)([
16
+ const logger$3 = (0, _logtape_logtape.getLogger)([
17
17
  "fedify",
18
18
  "sig",
19
19
  "ld"
@@ -161,7 +161,7 @@ async function verifySignature(jsonLd, options = {}) {
161
161
  try {
162
162
  signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
163
163
  } catch (error) {
164
- logger$1.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
164
+ logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
165
165
  ...sig,
166
166
  error
167
167
  });
@@ -180,7 +180,7 @@ async function verifySignature(jsonLd, options = {}) {
180
180
  try {
181
181
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
182
182
  } catch (error) {
183
- logger$1.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
183
+ logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
184
184
  signatureOptions: sigOpts,
185
185
  error
186
186
  });
@@ -192,7 +192,7 @@ async function verifySignature(jsonLd, options = {}) {
192
192
  try {
193
193
  docHash = await hashJsonLd(document, options.contextLoader);
194
194
  } catch (error) {
195
- logger$1.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
195
+ logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
196
196
  document,
197
197
  error
198
198
  });
@@ -203,7 +203,7 @@ async function verifySignature(jsonLd, options = {}) {
203
203
  const messageBytes = encoder.encode(message);
204
204
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
205
205
  if (cached) {
206
- logger$1.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
206
+ logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
207
207
  keyId: sig.creator,
208
208
  ...sig
209
209
  });
@@ -217,7 +217,7 @@ async function verifySignature(jsonLd, options = {}) {
217
217
  if (key == null) return null;
218
218
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
219
219
  }
220
- logger$1.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}", {
220
+ logger$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
221
221
  keyId: sig.creator,
222
222
  ...sig,
223
223
  message
@@ -249,12 +249,12 @@ async function verifyJsonLd(jsonLd, options = {}) {
249
249
  const key = await verifySignature(jsonLd, options);
250
250
  if (key == null) return false;
251
251
  if (key.ownerId == null) {
252
- logger$1.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
252
+ logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
253
253
  return false;
254
254
  }
255
255
  attributions.delete(key.ownerId.href);
256
256
  if (attributions.size > 0) {
257
- logger$1.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
257
+ logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
258
258
  return false;
259
259
  }
260
260
  return true;
@@ -389,6 +389,385 @@ async function getKeyOwner(keyId, options) {
389
389
  return null;
390
390
  }
391
391
  //#endregion
392
+ //#region src/compat/preloaded-context-loader.ts
393
+ /**
394
+ * A restricted JSON-LD document loader that resolves only contexts bundled
395
+ * with Fedify.
396
+ *
397
+ * This is intentionally narrower than `getDocumentLoader()`: normalization
398
+ * helpers are also reached from verification paths that operate on inbound,
399
+ * attacker-controlled JSON-LD, so the default fallback must never fetch
400
+ * attacker-supplied context URLs.
401
+ */
402
+ const preloadedOnlyDocumentLoader = (url) => {
403
+ if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
404
+ contextUrl: null,
405
+ documentUrl: url,
406
+ document: _fedify_vocab_runtime.preloadedContexts[url]
407
+ });
408
+ return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
409
+ };
410
+ //#endregion
411
+ //#region src/compat/public-audience.ts
412
+ const logger$2 = (0, _logtape_logtape.getLogger)([
413
+ "fedify",
414
+ "compat",
415
+ "public-audience"
416
+ ]);
417
+ const PUBLIC_ADDRESSING_FIELDS = new Set([
418
+ "to",
419
+ "cc",
420
+ "bto",
421
+ "bcc",
422
+ "audience"
423
+ ]);
424
+ const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
425
+ const MAX_TRAVERSAL_DEPTH$1 = 64;
426
+ const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
427
+ function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
428
+ if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
429
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
430
+ if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
431
+ if (typeof value !== "object" || value == null) return false;
432
+ const record = value;
433
+ for (const key of Object.keys(record)) {
434
+ if (key === "@context") continue;
435
+ if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
436
+ }
437
+ return false;
438
+ }
439
+ function rewritePublicAudience(value, parentKey, depth = 0) {
440
+ if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
441
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
442
+ if (Array.isArray(value)) {
443
+ let changed = false;
444
+ const mapped = value.map((item) => {
445
+ const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
446
+ if (rewritten !== item) changed = true;
447
+ return rewritten;
448
+ });
449
+ return changed ? mapped : value;
450
+ }
451
+ if (typeof value !== "object" || value == null) return value;
452
+ const record = value;
453
+ let changed = false;
454
+ const normalized = Object.create(null);
455
+ for (const key of Object.keys(record)) {
456
+ const rewritten = key === "@context" ? record[key] : rewritePublicAudience(record[key], key, depth + 1);
457
+ if (rewritten !== record[key]) changed = true;
458
+ normalized[key] = rewritten;
459
+ }
460
+ return changed ? normalized : value;
461
+ }
462
+ /**
463
+ * Reports whether `value` carries an `@context` property anywhere inside
464
+ * its subtree (not counting the value itself). A nested `@context` can
465
+ * introduce a local term-definition scope that redefines `as:` or `Public`
466
+ * even when the top-level `@context` is safe, so the fast path must defer
467
+ * to the URDNA2015 equivalence check whenever one is present.
468
+ */
469
+ function hasNestedContext$1(value, depth = 0) {
470
+ if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
471
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
472
+ if (typeof value !== "object" || value == null) return false;
473
+ const record = value;
474
+ for (const key of Object.keys(record)) {
475
+ if (key === "@context") return true;
476
+ if (hasNestedContext$1(record[key], depth + 1)) return true;
477
+ }
478
+ return false;
479
+ }
480
+ /**
481
+ * Checks whether the `@context` of a JSON-LD document is guaranteed not
482
+ * to redefine the `as:` prefix or the bare `Public` term. Only documents
483
+ * whose `@context` is a string, or an array of strings, drawn from Fedify's
484
+ * preloaded context set AND including the ActivityStreams URL qualify,
485
+ * AND no nested subtree carries its own `@context` that might redefine
486
+ * those terms within a local scope. When all of that holds the rewrite
487
+ * is provably semantics-preserving and the URDNA2015 equivalence check
488
+ * can be skipped. Any other shape (unknown external URLs, inline
489
+ * objects at the top level, nested `@context` blocks) is treated as
490
+ * potentially unsafe.
491
+ */
492
+ function hasKnownSafeContext$1(jsonLd) {
493
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
494
+ const record = jsonLd;
495
+ if (!Object.hasOwn(record, "@context")) return false;
496
+ const ctx = record["@context"];
497
+ const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
498
+ if (entries == null || entries.length === 0) return false;
499
+ let hasAs = false;
500
+ for (const entry of entries) {
501
+ if (typeof entry !== "string") return false;
502
+ if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
503
+ if (entry === AS_CONTEXT_URL$1) hasAs = true;
504
+ }
505
+ if (!hasAs) return false;
506
+ for (const key of Object.keys(record)) {
507
+ if (key === "@context") continue;
508
+ if (hasNestedContext$1(record[key])) return false;
509
+ }
510
+ return true;
511
+ }
512
+ /**
513
+ * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
514
+ * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
515
+ * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
516
+ *
517
+ * Several ActivityPub implementations, Lemmy among them, match these
518
+ * fields as plain URLs without running JSON-LD expansion, and silently
519
+ * drop activities whose public addressing appears in CURIE form. This
520
+ * helper works around that gap.
521
+ *
522
+ * For documents whose `@context` is drawn entirely from Fedify's
523
+ * preloaded context set and includes the ActivityStreams URL, the
524
+ * rewrite is applied directly: the content of every preloaded non-AS
525
+ * context is known not to redefine the `as:` prefix or the bare `Public`
526
+ * term, so the semantics are preserved by construction. Any other
527
+ * shape (an inline object, an unknown external URL, and so on) is
528
+ * treated as potentially unsafe and gated on a JSON-LD equivalence
529
+ * check; both forms are canonicalized with URDNA2015 and the resulting
530
+ * N-Quads are compared. When they differ, the original document is
531
+ * returned unchanged. Canonicalization failures also fall back to the
532
+ * original document.
533
+ *
534
+ * When no `contextLoader` is supplied the helper falls back to an
535
+ * internal loader that resolves only the URLs in Fedify's
536
+ * preloaded-contexts set and rejects every other URL without issuing a
537
+ * network request. That behaviour is deliberately narrower than
538
+ * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
539
+ * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
540
+ * helper is reached from verification paths (`verifyProof()` /
541
+ * `verifyObject()`) that operate on inbound, potentially adversarial
542
+ * JSON-LD, and a default loader that fetches attacker-supplied
543
+ * `@context` URLs on the caller's behalf would be an SSRF vector.
544
+ * Canonicalization failures against the restricted loader fall back to
545
+ * the original document, same as any other canonicalization error.
546
+ * Callers that genuinely need the remote-fetch loader (for example
547
+ * applications that sign local JSON-LD against a custom vocabulary)
548
+ * should pass a `contextLoader` explicitly.
549
+ *
550
+ * Must be called before any signing step that canonicalizes the
551
+ * compact form byte-for-byte (for example, Object Integrity Proofs
552
+ * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
553
+ * matches what is sent on the wire.
554
+ */
555
+ async function normalizePublicAudience(jsonLd, contextLoader) {
556
+ if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
557
+ const normalized = rewritePublicAudience(jsonLd);
558
+ if (hasKnownSafeContext$1(jsonLd)) return normalized;
559
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
560
+ try {
561
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
562
+ format: "application/n-quads",
563
+ documentLoader: loader
564
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
565
+ format: "application/n-quads",
566
+ documentLoader: loader
567
+ })]);
568
+ if (before === after) return normalized;
569
+ logger$2.warn("Expanding the public audience CURIE to its full URI would change the canonical form of the activity; sending the activity as is. This usually means the active JSON-LD context redefines the `as:` prefix or the bare `Public` term.");
570
+ } catch (error) {
571
+ logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
572
+ }
573
+ return jsonLd;
574
+ }
575
+ //#endregion
576
+ //#region src/compat/outgoing-jsonld.ts
577
+ const logger$1 = (0, _logtape_logtape.getLogger)([
578
+ "fedify",
579
+ "compat",
580
+ "outgoing-jsonld"
581
+ ]);
582
+ const ATTACHMENT_FIELDS = new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
583
+ const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
584
+ const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
585
+ const MAX_TRAVERSAL_DEPTH = 64;
586
+ function isJsonLdListObject(value) {
587
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
588
+ }
589
+ function isJsonLdValueObject(value) {
590
+ return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
591
+ }
592
+ function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
593
+ if (Array.isArray(value)) {
594
+ if (seen.has(value)) return;
595
+ seen.add(value);
596
+ for (const item of value) yield* getContextObjects(item, seen);
597
+ return;
598
+ }
599
+ if (typeof value === "object" && value != null) {
600
+ if (seen.has(value)) return;
601
+ seen.add(value);
602
+ const record = value;
603
+ yield record;
604
+ for (const definition of Object.values(record)) {
605
+ if (typeof definition !== "object" || definition == null) continue;
606
+ const nestedContext = definition["@context"];
607
+ if (nestedContext == null) continue;
608
+ yield* getContextObjects(nestedContext, seen);
609
+ }
610
+ }
611
+ }
612
+ function isActivityStreamsAttachmentTerm(value) {
613
+ return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
614
+ }
615
+ /** @internal */
616
+ function isPreloadedContextAttachmentSafe(document) {
617
+ if (typeof document !== "object" || document == null) return true;
618
+ const context = document["@context"];
619
+ for (const contextObject of getContextObjects(context)) {
620
+ if (!Object.hasOwn(contextObject, "attachment")) continue;
621
+ if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
622
+ return false;
623
+ }
624
+ return true;
625
+ }
626
+ function getKnownSafeContextUrls() {
627
+ const urls = /* @__PURE__ */ new Set();
628
+ for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
629
+ else logger$1.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
630
+ return urls;
631
+ }
632
+ /**
633
+ * Wraps scalar ActivityStreams attachment properties in arrays.
634
+ */
635
+ function wrapScalarAttachments(jsonLd, depth = 0) {
636
+ if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
637
+ if (Array.isArray(jsonLd)) {
638
+ let normalized = null;
639
+ for (let i = 0; i < jsonLd.length; i++) {
640
+ const item = jsonLd[i];
641
+ const next = wrapScalarAttachments(item, depth + 1);
642
+ if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
643
+ if (normalized != null) normalized[i] = next;
644
+ }
645
+ return normalized ?? jsonLd;
646
+ }
647
+ if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
648
+ const record = jsonLd;
649
+ const keys = Object.keys(record);
650
+ let normalized = null;
651
+ for (let i = 0; i < keys.length; i++) {
652
+ const key = keys[i];
653
+ const value = record[key];
654
+ const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
655
+ const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
656
+ if (normalized == null && output !== value) {
657
+ const cloned = Object.create(null);
658
+ for (let j = 0; j < i; j++) {
659
+ const previousKey = keys[j];
660
+ cloned[previousKey] = record[previousKey];
661
+ }
662
+ normalized = cloned;
663
+ }
664
+ if (normalized != null) normalized[key] = output;
665
+ }
666
+ return normalized ?? jsonLd;
667
+ }
668
+ function hasNestedContext(value, depth = 0) {
669
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
670
+ if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
671
+ if (typeof value !== "object" || value == null) return false;
672
+ const record = value;
673
+ for (const key of Object.keys(record)) {
674
+ if (key === "@context") return true;
675
+ if (key === "@value" && isJsonLdValueObject(value)) continue;
676
+ if (hasNestedContext(record[key], depth + 1)) return true;
677
+ }
678
+ return false;
679
+ }
680
+ function exceedsTraversalDepth(value, depth = 0) {
681
+ if (depth >= MAX_TRAVERSAL_DEPTH) return true;
682
+ if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
683
+ if (typeof value !== "object" || value == null) return false;
684
+ const record = value;
685
+ for (const key of Object.keys(record)) {
686
+ if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
687
+ if (exceedsTraversalDepth(record[key], depth + 1)) return true;
688
+ }
689
+ return false;
690
+ }
691
+ function hasKnownSafeContext(jsonLd) {
692
+ if (typeof jsonLd !== "object" || jsonLd == null) return false;
693
+ const record = jsonLd;
694
+ if (!Object.hasOwn(record, "@context")) return false;
695
+ const context = record["@context"];
696
+ const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
697
+ if (entries == null || entries.length < 1) return false;
698
+ let hasActivityStreamsContext = false;
699
+ for (const entry of entries) {
700
+ if (typeof entry !== "string") return false;
701
+ if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
702
+ if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
703
+ }
704
+ if (!hasActivityStreamsContext) return false;
705
+ for (const key of Object.keys(record)) {
706
+ if (key === "@context") continue;
707
+ if (hasNestedContext(record[key])) return false;
708
+ }
709
+ return true;
710
+ }
711
+ function getLogSafeJsonLdMetadata(jsonLd) {
712
+ if (typeof jsonLd !== "object" || jsonLd == null) return {};
713
+ const record = jsonLd;
714
+ const context = record["@context"];
715
+ return {
716
+ id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
717
+ type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
718
+ context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
719
+ };
720
+ }
721
+ /**
722
+ * Ensures ActivityStreams attachment properties are represented as arrays
723
+ * when doing so preserves the JSON-LD semantics.
724
+ *
725
+ * JSON-LD compaction collapses single-item arrays into scalar values by
726
+ * default. Some ActivityPub implementations, Pixelfed among them, parse
727
+ * `attachment` as a plain JSON array rather than a JSON-LD property and reject
728
+ * otherwise valid objects whose single attachment is emitted as a scalar.
729
+ *
730
+ * When no `contextLoader` is supplied, the helper falls back to a restricted
731
+ * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
732
+ * every other URL without network access. Documents with custom, inline, or
733
+ * otherwise uncached contexts should pass a real `contextLoader` if they need
734
+ * the semantic-preservation check to succeed; otherwise canonicalization
735
+ * failures leave the original document unchanged.
736
+ */
737
+ async function normalizeAttachmentArrays(jsonLd, contextLoader) {
738
+ const normalized = wrapScalarAttachments(jsonLd);
739
+ if (normalized === jsonLd) return jsonLd;
740
+ if (exceedsTraversalDepth(jsonLd)) {
741
+ logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
742
+ return jsonLd;
743
+ }
744
+ if (hasKnownSafeContext(jsonLd)) return normalized;
745
+ const loader = contextLoader ?? preloadedOnlyDocumentLoader;
746
+ try {
747
+ const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
748
+ format: "application/n-quads",
749
+ documentLoader: loader
750
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
751
+ format: "application/n-quads",
752
+ documentLoader: loader
753
+ })]);
754
+ if (before === after) return normalized;
755
+ logger$1.warn("Wrapping scalar attachment values in arrays would change the canonical form of the JSON-LD document; leaving it unchanged. This usually means the active JSON-LD context redefines the `attachment` term. Document: {id}; type: {type}; context: {context}.", getLogSafeJsonLdMetadata(jsonLd));
756
+ } catch (error) {
757
+ logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
758
+ }
759
+ return jsonLd;
760
+ }
761
+ /**
762
+ * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
763
+ * to locally generated outgoing activities before they are signed, enqueued,
764
+ * or sent.
765
+ */
766
+ async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
767
+ jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
768
+ return await normalizeAttachmentArrays(jsonLd, contextLoader);
769
+ }
770
+ //#endregion
392
771
  //#region src/sig/proof.ts
393
772
  const logger = (0, _logtape_logtape.getLogger)([
394
773
  "fedify",
@@ -437,11 +816,12 @@ function hasProofLike(jsonLd) {
437
816
  async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
438
817
  require_http.validateCryptoKey(privateKey, "private");
439
818
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
440
- const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
819
+ let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
441
820
  format: "compact",
442
821
  contextLoader,
443
822
  context
444
823
  });
824
+ compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader);
445
825
  const msgCanon = (0, json_canon.default)(compactMsg);
446
826
  const encoder = new TextEncoder();
447
827
  const msgBytes = encoder.encode(msgCanon);
@@ -536,27 +916,22 @@ async function verifyProof(jsonLd, proof, options = {}) {
536
916
  });
537
917
  }
538
918
  async function verifyProofInternal(jsonLd, proof, options) {
539
- if (typeof jsonLd !== "object" || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
919
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
540
920
  const publicKeyPromise = require_http.fetchKey(proof.verificationMethodId, _fedify_vocab.Multikey, options);
541
- const proofCanon = (0, json_canon.default)({
921
+ const proofConfig = {
542
922
  "@context": jsonLd["@context"],
543
923
  type: "DataIntegrityProof",
544
924
  cryptosuite: proof.cryptosuite,
545
925
  verificationMethod: proof.verificationMethodId.href,
546
926
  proofPurpose: proof.proofPurpose,
547
927
  created: proof.created.toString()
548
- });
928
+ };
549
929
  const encoder = new TextEncoder();
550
- const proofBytes = encoder.encode(proofCanon);
930
+ const proofBytes = encoder.encode((0, json_canon.default)(proofConfig));
551
931
  const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
552
932
  const msg = { ...jsonLd };
553
933
  if ("proof" in msg) delete msg.proof;
554
- const msgCanon = (0, json_canon.default)(msg);
555
- const msgBytes = encoder.encode(msgCanon);
556
- const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
557
- const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
558
- digest.set(new Uint8Array(proofDigest), 0);
559
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
934
+ if ("https://w3id.org/security#proof" in msg) delete msg["https://w3id.org/security#proof"];
560
935
  let fetchedKey;
561
936
  try {
562
937
  fetchedKey = await publicKeyPromise;
@@ -585,7 +960,7 @@ async function verifyProofInternal(jsonLd, proof, options) {
585
960
  return await verifyProof(jsonLd, proof, {
586
961
  ...options,
587
962
  keyCache: {
588
- get: () => Promise.resolve(null),
963
+ get: () => Promise.resolve(void 0),
589
964
  set: async (keyId, key) => await options.keyCache?.set(keyId, key)
590
965
  }
591
966
  });
@@ -596,27 +971,36 @@ async function verifyProofInternal(jsonLd, proof, options) {
596
971
  });
597
972
  return null;
598
973
  }
599
- if (!await crypto.subtle.verify("Ed25519", publicKey.publicKey, proof.proofValue.slice(), digest)) {
600
- if (fetchedKey.cached) {
601
- logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
602
- keyId: proof.verificationMethodId.href,
603
- proof
604
- });
605
- return await verifyProof(jsonLd, proof, {
606
- ...options,
607
- keyCache: {
608
- get: () => Promise.resolve(void 0),
609
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
610
- }
611
- });
612
- }
613
- logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
974
+ const digest = new Uint8Array(proofDigest.byteLength + 32);
975
+ digest.set(new Uint8Array(proofDigest), 0);
976
+ const proofValue = proof.proofValue;
977
+ const verifyCandidate = async (candidate) => {
978
+ const msgBytes = encoder.encode((0, json_canon.default)(candidate));
979
+ const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
980
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
981
+ return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
982
+ };
983
+ if (await verifyCandidate(msg)) return publicKey;
984
+ const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
985
+ if (normalized !== msg && await verifyCandidate(normalized)) return publicKey;
986
+ if (fetchedKey.cached) {
987
+ logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
614
988
  keyId: proof.verificationMethodId.href,
615
989
  proof
616
990
  });
617
- return null;
991
+ return await verifyProof(jsonLd, proof, {
992
+ ...options,
993
+ keyCache: {
994
+ get: () => Promise.resolve(void 0),
995
+ set: async (keyId, key) => await options.keyCache?.set(keyId, key)
996
+ }
997
+ });
618
998
  }
619
- return publicKey;
999
+ logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1000
+ keyId: proof.verificationMethodId.href,
1001
+ proof
1002
+ });
1003
+ return null;
620
1004
  }
621
1005
  /**
622
1006
  * Verifies the given object. It will verify all the proofs in the object,
@@ -705,6 +1089,12 @@ Object.defineProperty(exports, "hasSignatureLike", {
705
1089
  return hasSignatureLike;
706
1090
  }
707
1091
  });
1092
+ Object.defineProperty(exports, "normalizeOutgoingActivityJsonLd", {
1093
+ enumerable: true,
1094
+ get: function() {
1095
+ return normalizeOutgoingActivityJsonLd;
1096
+ }
1097
+ });
708
1098
  Object.defineProperty(exports, "signJsonLd", {
709
1099
  enumerable: true,
710
1100
  get: function() {