@fedify/fedify 2.1.30 → 2.1.32

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 (104) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-CTpfuuVp.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-CAM_bQXx.d.cts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CSddvgWN.d.ts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-CjDMsn4a.mjs → client-cpPaW7Ww.mjs} +189 -65
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +254 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/transformers.test.mjs +1 -1
  12. package/dist/{context-DLLaDau8.d.ts → context-DE2YrQwM.d.ts} +56 -13
  13. package/dist/{context-BNwv9Q1v.d.cts → context-y6ZUQCMf.d.cts} +56 -13
  14. package/dist/{deno-BATJ1hq6.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/docloader-DUXr9k_O.mjs +124 -0
  16. package/dist/federation/attachment-responses.test.d.mts +2 -0
  17. package/dist/federation/attachment-responses.test.mjs +182 -0
  18. package/dist/federation/builder.test.mjs +1 -1
  19. package/dist/federation/collection.test.mjs +1 -1
  20. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  21. package/dist/federation/delivery-attachments.test.mjs +280 -0
  22. package/dist/federation/handler.test.mjs +208 -16
  23. package/dist/federation/idempotency.test.mjs +2 -2
  24. package/dist/federation/inbox.test.mjs +1 -1
  25. package/dist/federation/middleware.test.mjs +1559 -26
  26. package/dist/federation/mod.cjs +1 -1
  27. package/dist/federation/mod.d.cts +2 -2
  28. package/dist/federation/mod.d.ts +2 -2
  29. package/dist/federation/mod.js +1 -1
  30. package/dist/federation/negotiation.test.mjs +1 -1
  31. package/dist/federation/retry.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +723 -68
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-CK3efjgM.js → http-BtbMAgTA.js} +176 -105
  36. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  37. package/dist/{http-BoR1M3W7.cjs → http-D5woFKA_.cjs} +177 -106
  38. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  39. package/dist/{http-Bjd6I92u.mjs → http-HX6wVyJh.mjs} +198 -98
  40. package/dist/{inbox-9MlBGgs9.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-ClQh9Qqh.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-BxSx_Iyp.cjs → kv-cache-B0V_e231.cjs} +59 -17
  43. package/dist/{kv-cache-ImApO425.js → kv-cache-BsDg-cT8.js} +60 -18
  44. package/dist/{ld-Crg0Xmwr.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-jL9p9V9G.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-CmD3lpy4.cjs → middleware-CrfRuKCf.cjs} +728 -143
  48. package/dist/{middleware-CE0b69gj.mjs → middleware-DiquMgtt.mjs} +444 -115
  49. package/dist/{middleware-C2AJFk8W.js → middleware-DunNtbo9.js} +727 -143
  50. package/dist/{middleware-Bi5D6DBT.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-DiuFTYUt.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CWJNbyju.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-BLDHhuW0.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-DNEgTI8M.d.ts → mod-REfljt0T.d.ts} +4 -9
  55. package/dist/{mod-Cn9GJ5ex.d.cts → mod-UvIGUHqW.d.cts} +4 -9
  56. package/dist/{mod-BmlfRBmU.d.cts → mod-sTa1Zzxk.d.cts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +8 -8
  59. package/dist/mod.d.ts +8 -8
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +764 -19
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.d.cts +1 -1
  65. package/dist/nodeinfo/mod.d.ts +1 -1
  66. package/dist/nodeinfo/mod.js +1 -1
  67. package/dist/nodeinfo/types.test.mjs +1 -1
  68. package/dist/otel/exporter.test.mjs +292 -30
  69. package/dist/otel/mod.cjs +36 -30
  70. package/dist/otel/mod.d.cts +13 -0
  71. package/dist/otel/mod.d.ts +13 -0
  72. package/dist/otel/mod.js +36 -30
  73. package/dist/{owner-BRoKojK1.mjs → owner-DwyDorZI.mjs} +2 -2
  74. package/dist/{proof-CHXVlsH_.cjs → proof-Be-4K4jn.cjs} +193 -46
  75. package/dist/{proof-DMIAezxz.mjs → proof-DYjmyrHh.mjs} +38 -13
  76. package/dist/{proof-7R4s10TJ.js → proof-Du4-5SHY.js} +187 -46
  77. package/dist/send-BGSfQkIK.mjs +416 -0
  78. package/dist/sig/http.test.mjs +506 -2
  79. package/dist/sig/key-types.test.d.mts +218 -0
  80. package/dist/sig/key-types.test.mjs +8 -0
  81. package/dist/sig/key.test.mjs +2 -2
  82. package/dist/sig/ld.test.mjs +573 -8
  83. package/dist/sig/mod.cjs +2 -2
  84. package/dist/sig/mod.d.cts +3 -3
  85. package/dist/sig/mod.d.ts +3 -3
  86. package/dist/sig/mod.js +2 -2
  87. package/dist/sig/owner.test.mjs +1 -1
  88. package/dist/sig/proof.test.mjs +95 -3
  89. package/dist/{temporal-DR0JahMu.mjs → temporal-CNCchWly.mjs} +3 -5
  90. package/dist/testing/mod.d.mts +1 -2177
  91. package/dist/{types-DRPjmHVV.cjs → types-B5wRhemi.cjs} +187 -63
  92. package/dist/{types-miAYfiGO.js → types-CXy2lRVU.js} +188 -64
  93. package/dist/utils/docloader.test.mjs +316 -32
  94. package/dist/utils/mod.cjs +1 -1
  95. package/dist/utils/mod.d.cts +1 -1
  96. package/dist/utils/mod.d.ts +1 -1
  97. package/dist/utils/mod.js +1 -1
  98. package/package.json +7 -7
  99. package/dist/docloader-OLWc7P2D.mjs +0 -82
  100. package/dist/send-BHIt_8ia.mjs +0 -260
  101. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  102. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  103. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  104. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -1,13 +1,14 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { c as fetchKey, f as validateCryptoKey, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, v as name, y as version } from "./http-CK3efjgM.js";
3
+ import { c as fetchKey, f as validateCryptoKey, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, v as name, y as version } from "./http-BtbMAgTA.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, getTypeId, isActor } from "@fedify/vocab";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
7
  import { encodeHex } from "byte-encodings/hex";
8
- import { getDocumentLoader } from "@fedify/vocab-runtime";
9
- import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
8
+ import { getDocumentLoader, preloadedContexts } from "@fedify/vocab-runtime";
10
9
  import jsonld from "@fedify/vocab-runtime/jsonld";
10
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
11
+ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
11
12
  import serialize from "json-canon";
12
13
  //#region src/sig/ld.ts
13
14
  const logger$2 = getLogger([
@@ -297,24 +298,110 @@ function assertSafeJsonLd(jsonLd) {
297
298
  }
298
299
  }
299
300
  }
301
+ const signatureTermDefinition = { "signature": "https://w3id.org/security#signature" };
302
+ const signatureDefiningContexts = new Set(["https://w3id.org/identity/v1", "https://w3id.org/security/v1"]);
303
+ const signatureFreeContexts = getSignatureFreeContexts();
304
+ function getSignatureFreeContexts() {
305
+ const urls = /* @__PURE__ */ new Set();
306
+ for (const [url, document] of globalThis.Object.entries(preloadedContexts)) {
307
+ if (typeof document !== "object" || document == null) continue;
308
+ const context = document["@context"];
309
+ if (typeof context !== "object" || context == null || Array.isArray(context)) continue;
310
+ const record = context;
311
+ if (!globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) urls.add(url);
312
+ }
313
+ return urls;
314
+ }
315
+ function getContextEntryEffect(entry) {
316
+ if (entry == null) return "resets";
317
+ if (typeof entry === "string") {
318
+ if (signatureDefiningContexts.has(entry)) return "defines";
319
+ if (signatureFreeContexts.has(entry)) return "absent";
320
+ return "unknown";
321
+ }
322
+ if (typeof entry !== "object") return "absent";
323
+ const record = entry;
324
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) {
325
+ const definition = record["signature"];
326
+ const contextProtected = record["@protected"] === true;
327
+ const imported = globalThis.Object.prototype.hasOwnProperty.call(record, "@import");
328
+ if (definition == null) {
329
+ if (contextProtected) return "defines";
330
+ return imported ? "unknown" : "resets";
331
+ }
332
+ if (typeof definition === "object" && !Array.isArray(definition)) {
333
+ const term = definition;
334
+ const protectedTerm = contextProtected || term["@protected"] === true;
335
+ if (globalThis.Object.prototype.hasOwnProperty.call(term, "@id") && term["@id"] == null) {
336
+ if (protectedTerm) return "defines";
337
+ return imported ? "unknown" : "resets";
338
+ }
339
+ }
340
+ return "defines";
341
+ }
342
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "@import")) return "unknown";
343
+ return "absent";
344
+ }
345
+ function getSignatureTermState(context) {
346
+ if (context == null) return "absent";
347
+ if (!Array.isArray(context)) {
348
+ const effect = getContextEntryEffect(context);
349
+ return effect === "defines" ? "defined" : effect === "unknown" ? "unknown" : "absent";
350
+ }
351
+ let state = "absent";
352
+ for (const entry of context) {
353
+ const effect = getContextEntryEffect(entry);
354
+ if (effect === "defines") state = "defined";
355
+ else if (effect === "resets") state = "absent";
356
+ else if (effect === "unknown" && state !== "defined") state = "unknown";
357
+ }
358
+ return state;
359
+ }
360
+ function prepareSignatureDocument(jsonLd) {
361
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) return jsonLd;
362
+ const document = jsonLd;
363
+ if (document["proof"] != null) return { ...document };
364
+ const context = document["@context"];
365
+ if (getSignatureTermState(context) !== "absent") return { ...document };
366
+ const definition = { ...signatureTermDefinition };
367
+ return {
368
+ ...document,
369
+ "@context": context == null ? [definition] : Array.isArray(context) ? [...context, definition] : [context, definition]
370
+ };
371
+ }
300
372
  /**
301
373
  * Attaches a LD signature to the given JSON-LD document.
374
+ *
375
+ * When the document's context does not already define the `signature`
376
+ * property, the returned document adds a minimal inline context for it.
377
+ * Without that definition, expanding the attached signature would produce a
378
+ * blank node predicate, which is not valid RDF. Documents that already carry
379
+ * a `proof` are left unchanged, since a new context definition would invalidate
380
+ * the proof. Documents whose context includes an unrecognized remote context
381
+ * are also left unchanged, since that context may already define `signature`.
302
382
  * @param jsonLd The JSON-LD document to attach the signature to. It is not
303
383
  * modified.
304
384
  * @param signature The signature to attach.
305
385
  * @returns The JSON-LD document with the attached signature.
306
386
  * @throws {TypeError} If the input document is not a valid JSON-LD document.
387
+ * Top-level arrays are rejected, since a Linked Data
388
+ * Signature is attached to a single node.
307
389
  * @since 1.0.0
308
390
  */
309
391
  function attachSignature(jsonLd, signature) {
310
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
311
- return {
312
- ...jsonLd,
313
- signature
314
- };
392
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
393
+ const output = prepareSignatureDocument(jsonLd);
394
+ output.signature = signature;
395
+ return output;
315
396
  }
316
397
  /**
317
398
  * Creates a LD signature for the given JSON-LD document.
399
+ *
400
+ * If the document's context does not define the `signature` property, the
401
+ * signature is computed over the document with a minimal inline definition
402
+ * added. Use {@link attachSignature} to attach the signature to that exact
403
+ * document. Documents that already carry a `proof`, or whose context includes
404
+ * an unrecognized remote context, are hashed unchanged.
318
405
  * @param jsonLd The JSON-LD document to sign.
319
406
  * @param privateKey The private key to sign the document.
320
407
  * @param keyId The ID of the public key that corresponds to the private key.
@@ -328,14 +415,17 @@ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, creat
328
415
  validateCryptoKey(privateKey, "private");
329
416
  if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
330
417
  const options = {
331
- "@context": "https://w3id.org/identity/v1",
332
418
  creator: keyId.href,
333
419
  created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
334
420
  };
335
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
421
+ const message = await hashJsonLd({
422
+ "@context": "https://w3id.org/identity/v1",
423
+ ...options
424
+ }, contextLoader) + await hashJsonLd(prepareSignatureDocument(jsonLd), contextLoader);
336
425
  const messageBytes = new TextEncoder().encode(message);
337
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
426
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", asCryptoKey(privateKey), messageBytes);
338
427
  return {
428
+ "@context": "https://w3id.org/security/v1",
339
429
  ...options,
340
430
  type: "RsaSignature2017",
341
431
  signatureValue: encodeBase64(signature)
@@ -374,20 +464,23 @@ async function signJsonLd(jsonLd, privateKey, keyId, options) {
374
464
  }
375
465
  });
376
466
  }
377
- /**
378
- * Checks if the given JSON-LD document has a Linked Data Signature.
379
- * @param jsonLd The JSON-LD document to check.
380
- * @returns `true` if the document has a signature; `false` otherwise.
381
- * @since 1.0.0
382
- */
383
- function hasSignature(jsonLd) {
384
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
385
- if ("signature" in jsonLd) {
386
- const signature = jsonLd.signature;
387
- if (typeof signature !== "object" || signature == null) return false;
388
- 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";
389
- }
390
- return false;
467
+ /** @internal */
468
+ function hasVerifiableSignature(jsonLd) {
469
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || !("signature" in jsonLd)) return false;
470
+ const signature = jsonLd.signature;
471
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return false;
472
+ 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";
473
+ }
474
+ /** @internal */
475
+ function describeSignatureShape(jsonLd) {
476
+ if (typeof jsonLd !== "object" || jsonLd == null || !("signature" in jsonLd)) return null;
477
+ const signature = jsonLd.signature;
478
+ const properties = typeof signature === "object" && signature != null ? globalThis.Object.keys(signature) : [];
479
+ return {
480
+ signatureKind: signature == null ? String(signature) : Array.isArray(signature) ? "array" : typeof signature,
481
+ signatureProperties: properties.sort().slice(0, 20).map((p) => p.slice(0, 80)),
482
+ signaturePropertyCount: properties.length
483
+ };
391
484
  }
392
485
  /**
393
486
  * Detaches Linked Data Signatures from the given JSON-LD document.
@@ -404,6 +497,9 @@ function detachSignature(jsonLd) {
404
497
  }
405
498
  /**
406
499
  * Verifies Linked Data Signatures of the given JSON-LD document.
500
+ * Unmapped properties discarded during JSON-LD processing are tolerated, but
501
+ * their values are not authenticated by the signature. Other unsafe
502
+ * canonicalization warnings, including relative IRIs, remain rejected.
407
503
  * @param jsonLd The JSON-LD document to verify.
408
504
  * @param options Options for verifying the signature.
409
505
  * @returns The public key that signed the document or `null` if the signature
@@ -411,7 +507,11 @@ function detachSignature(jsonLd) {
411
507
  * @since 1.0.0
412
508
  */
413
509
  async function verifySignature(jsonLd, options = {}) {
414
- if (!hasSignature(jsonLd)) return null;
510
+ if (!hasVerifiableSignature(jsonLd)) {
511
+ const shape = describeSignatureShape(jsonLd);
512
+ if (shape != null) logger$2.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
513
+ return null;
514
+ }
415
515
  const sig = jsonLd.signature;
416
516
  let signature;
417
517
  try {
@@ -423,7 +523,14 @@ async function verifySignature(jsonLd, options = {}) {
423
523
  });
424
524
  return null;
425
525
  }
426
- const { key, cached } = await fetchKey(new URL(sig.creator), CryptographicKey, options);
526
+ let creator;
527
+ try {
528
+ creator = new URL(sig.creator);
529
+ } catch {
530
+ logger$2.debug("Failed to verify; signature creator is not a valid URL.");
531
+ return null;
532
+ }
533
+ const { key, cached } = await fetchKey(creator, CryptographicKey, options);
427
534
  if (key == null) return null;
428
535
  const sigOpts = {
429
536
  ...sig,
@@ -434,7 +541,7 @@ async function verifySignature(jsonLd, options = {}) {
434
541
  delete sigOpts.signatureValue;
435
542
  let sigOptsHash;
436
543
  try {
437
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
544
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader, "verify");
438
545
  } catch (error) {
439
546
  logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
440
547
  signatureOptions: sigOpts,
@@ -446,7 +553,7 @@ async function verifySignature(jsonLd, options = {}) {
446
553
  delete document.signature;
447
554
  let docHash;
448
555
  try {
449
- docHash = await hashJsonLd(document, options.contextLoader);
556
+ docHash = await hashJsonLd(document, options.contextLoader, "verify");
450
557
  } catch (error) {
451
558
  logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
452
559
  document,
@@ -463,7 +570,7 @@ async function verifySignature(jsonLd, options = {}) {
463
570
  keyId: sig.creator,
464
571
  ...sig
465
572
  });
466
- const { key } = await fetchKey(new URL(sig.creator), CryptographicKey, {
573
+ const { key } = await fetchKey(creator, CryptographicKey, {
467
574
  ...options,
468
575
  keyCache: {
469
576
  get: () => Promise.resolve(void 0),
@@ -485,6 +592,8 @@ async function verifySignature(jsonLd, options = {}) {
485
592
  * Signatures. If the document is signed, this function verifies the signature
486
593
  * and checks if the document is attributed to the owner of the public key.
487
594
  * If the document is not signed, this function returns `false`.
595
+ * Unmapped properties discarded during JSON-LD processing are not
596
+ * authenticated, even when verification succeeds.
488
597
  * @param jsonLd The JSON-LD document to verify.
489
598
  * @param options Options for verifying the document.
490
599
  * @returns `true` if the document is authentic; `false` otherwise.
@@ -499,11 +608,12 @@ async function verifyCompactJsonLd(jsonLd, options = {}) {
499
608
  async function verifyJsonLdInternal(jsonLd, options, compact) {
500
609
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("ld_signatures.verify", async (span) => {
501
610
  try {
502
- const verificationOptions = hasSignature(jsonLd) ? {
611
+ const hasLdSignature = hasVerifiableSignature(jsonLd);
612
+ const verificationOptions = hasLdSignature ? {
503
613
  ...options,
504
614
  contextLoader: getNormalizationContextLoader(options.contextLoader)
505
615
  } : options;
506
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
616
+ const compacted = compact ? hasLdSignature ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
507
617
  const object = await Object$1.fromJsonLd(compacted, verificationOptions);
508
618
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
509
619
  span.setAttribute("activitypub.object.type", getTypeId(object).href);
@@ -537,10 +647,17 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
537
647
  }
538
648
  });
539
649
  }
540
- async function hashJsonLd(jsonLd, contextLoader) {
650
+ const tolerableVerificationWarnings = new Set(["blank node predicate", "invalid property"]);
651
+ function handleVerificationEvent({ event, next }) {
652
+ if (event.level === "warning" && !tolerableVerificationWarnings.has(event.code)) throw new TypeError(`Unsafe JSON-LD canonicalization warning: ${event.code}`);
653
+ next();
654
+ }
655
+ async function hashJsonLd(jsonLd, contextLoader, mode = "sign") {
541
656
  const canon = await jsonld.canonize(jsonLd, {
542
657
  format: "application/n-quads",
543
- documentLoader: contextLoader ?? getDocumentLoader()
658
+ documentLoader: contextLoader ?? getDocumentLoader(),
659
+ safe: mode === "sign",
660
+ eventHandler: mode === "verify" ? handleVerificationEvent : void 0
544
661
  });
545
662
  const encoder = new TextEncoder();
546
663
  return encodeHex(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
@@ -727,7 +844,10 @@ const logger = getLogger([
727
844
  * @throws {TypeError} If the private key is invalid or unsupported.
728
845
  * @since 0.10.0
729
846
  */
730
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
847
+ async function createProof(object, privateKey, keyId, options = {}) {
848
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
849
+ }
850
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
731
851
  validateCryptoKey(privateKey, "private");
732
852
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
733
853
  const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -753,14 +873,26 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
753
873
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
754
874
  digest.set(new Uint8Array(proofDigest), 0);
755
875
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
756
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
757
- return new DataIntegrityProof({
758
- cryptosuite: "eddsa-jcs-2022",
759
- verificationMethod: keyId,
760
- proofPurpose: "assertionMethod",
761
- created: created ?? Temporal.Now.instant(),
762
- proofValue: new Uint8Array(sig)
763
- });
876
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
877
+ return {
878
+ proof: new DataIntegrityProof({
879
+ cryptosuite: "eddsa-jcs-2022",
880
+ verificationMethod: keyId,
881
+ proofPurpose: "assertionMethod",
882
+ created: created ?? Temporal.Now.instant(),
883
+ proofValue: new Uint8Array(sig)
884
+ }),
885
+ jsonLd: compactMsg
886
+ };
887
+ }
888
+ function getJsonLdContextKey(value) {
889
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
890
+ return JSON.stringify(sortJsonKeys(context));
891
+ }
892
+ function sortJsonKeys(value) {
893
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
894
+ if (typeof value !== "object" || value == null) return value;
895
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
764
896
  }
765
897
  /**
766
898
  * Signs the given object with the private key and returns the signed object.
@@ -776,9 +908,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
776
908
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
777
909
  try {
778
910
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
911
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
779
912
  const existingProofs = [];
780
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
781
- const proof = await createProof(object, privateKey, keyId, options);
913
+ let hasProofs = object.proofIds.length > 0;
914
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
915
+ hasProofs = true;
916
+ break;
917
+ }
918
+ if (hasProofs) {
919
+ let sameContext = true;
920
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
921
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
922
+ }
782
923
  if (span.isRecording()) {
783
924
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
784
925
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -950,4 +1091,4 @@ async function verifyObject(cls, jsonLd, options = {}) {
950
1091
  return object;
951
1092
  }
952
1093
  //#endregion
953
- export { signJsonLd as _, doesActorOwnKey as a, verifySignature as b, assertSafeJsonLd as c, createSignature as d, detachSignature as f, isInvalidUrlTypeError as g, isClearlyMalformedContextReference as h, verifyProof as i, attachSignature as l, hasSignature as m, signObject as n, getKeyOwner as o, getNormalizationContextLoader as p, verifyObject as r, InvalidContextReferenceError as s, createProof as t, compactJsonLd as u, verifyCompactJsonLd as v, wrapContextLoaderForJsonLd as x, verifyJsonLd as y };
1094
+ export { wrapContextLoaderForJsonLd as S, isInvalidUrlTypeError as _, doesActorOwnKey as a, verifyJsonLd as b, assertSafeJsonLd as c, createSignature as d, describeSignatureShape as f, isClearlyMalformedContextReference as g, hasVerifiableSignature as h, verifyProof as i, attachSignature as l, getNormalizationContextLoader as m, signObject as n, getKeyOwner as o, detachSignature as p, verifyObject as r, InvalidContextReferenceError as s, createProof as t, compactJsonLd as u, signJsonLd as v, verifySignature as x, verifyCompactJsonLd as y };