@fedify/fedify 2.1.31 → 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 (97) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-isMRh_I6.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-jE7oGvRh.d.ts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-BZr7TGyu.mjs → client-cpPaW7Ww.mjs} +86 -11
  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-C0uGVzgk.d.ts → context-DE2YrQwM.d.ts} +30 -13
  13. package/dist/{context-CLaLxi49.d.cts → context-y6ZUQCMf.d.cts} +30 -13
  14. package/dist/{deno-CiaJqTcu.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/{docloader-DOrwedT7.mjs → docloader-DUXr9k_O.mjs} +2 -2
  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 +1185 -8
  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 +283 -3
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-Crml3gei.js → http-BtbMAgTA.js} +6 -4
  36. package/dist/{http-9IFUxdkp.d.cts → http-C8qLHs_Z.d.cts} +3 -3
  37. package/dist/{http-CRiVlZd5.cjs → http-D5woFKA_.cjs} +6 -4
  38. package/dist/{http-SbfezERn.d.ts → http-D8WmcRAF.d.ts} +3 -3
  39. package/dist/{http-A9mP2uM7.mjs → http-HX6wVyJh.mjs} +6 -4
  40. package/dist/{inbox-KESLudq4.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-Dg6-DV_O.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-Cqmm-yQa.cjs → kv-cache-B0V_e231.cjs} +1 -1
  43. package/dist/{kv-cache-DQcyZL5T.js → kv-cache-BsDg-cT8.js} +1 -1
  44. package/dist/{ld-COjDN6Nb.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-BtDQUCcz.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-BbgR7xOI.cjs → middleware-CrfRuKCf.cjs} +561 -101
  48. package/dist/{middleware-COFlKeYn.mjs → middleware-DiquMgtt.mjs} +378 -89
  49. package/dist/{middleware-DIW5S_5L.js → middleware-DunNtbo9.js} +560 -101
  50. package/dist/{middleware-CuQvczZd.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-LOEOKbYd.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CFRocFeQ.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-C7w-QVUv.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-BRnwh2oy.d.ts → mod-REfljt0T.d.ts} +3 -3
  55. package/dist/{mod-Co7LEK9X.d.cts → mod-UvIGUHqW.d.cts} +3 -3
  56. package/dist/{mod-CGUH8Ujp.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 +432 -5
  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/{owner-CFHq61cq.mjs → owner-DwyDorZI.mjs} +2 -2
  69. package/dist/{proof-0JkSC_pT.cjs → proof-Be-4K4jn.cjs} +193 -46
  70. package/dist/{proof-KSHlbPCG.mjs → proof-DYjmyrHh.mjs} +38 -13
  71. package/dist/{proof-DzksJFK7.js → proof-Du4-5SHY.js} +187 -46
  72. package/dist/{send-DaDe2YCb.mjs → send-BGSfQkIK.mjs} +92 -21
  73. package/dist/sig/http.test.mjs +2 -2
  74. package/dist/sig/key-types.test.d.mts +218 -0
  75. package/dist/sig/key-types.test.mjs +8 -0
  76. package/dist/sig/key.test.mjs +2 -2
  77. package/dist/sig/ld.test.mjs +573 -8
  78. package/dist/sig/mod.cjs +2 -2
  79. package/dist/sig/mod.d.cts +3 -3
  80. package/dist/sig/mod.d.ts +3 -3
  81. package/dist/sig/mod.js +2 -2
  82. package/dist/sig/owner.test.mjs +1 -1
  83. package/dist/sig/proof.test.mjs +95 -3
  84. package/dist/{temporal-DNGH8o2E.mjs → temporal-CNCchWly.mjs} +3 -5
  85. package/dist/testing/mod.d.mts +2 -2203
  86. package/dist/{types-DOvyymM4.cjs → types-B5wRhemi.cjs} +85 -10
  87. package/dist/{types-B1_pRFE_.js → types-CXy2lRVU.js} +86 -11
  88. package/dist/utils/docloader.test.mjs +2 -2
  89. package/dist/utils/mod.cjs +1 -1
  90. package/dist/utils/mod.d.cts +1 -1
  91. package/dist/utils/mod.d.ts +1 -1
  92. package/dist/utils/mod.js +1 -1
  93. package/package.json +6 -6
  94. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  95. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  96. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  97. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -1,15 +1,16 @@
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-CRiVlZd5.cjs");
4
+ const require_http = require("./http-D5woFKA_.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");
8
8
  let byte_encodings_hex = require("byte-encodings/hex");
9
9
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
10
- let byte_encodings_base64 = require("byte-encodings/base64");
11
10
  let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
12
11
  _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld);
12
+ let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
13
+ let byte_encodings_base64 = require("byte-encodings/base64");
13
14
  let json_canon = require("json-canon");
14
15
  json_canon = require_chunk.__toESM(json_canon);
15
16
  //#region src/sig/ld.ts
@@ -300,24 +301,110 @@ function assertSafeJsonLd(jsonLd) {
300
301
  }
301
302
  }
302
303
  }
304
+ const signatureTermDefinition = { "signature": "https://w3id.org/security#signature" };
305
+ const signatureDefiningContexts = new Set(["https://w3id.org/identity/v1", "https://w3id.org/security/v1"]);
306
+ const signatureFreeContexts = getSignatureFreeContexts();
307
+ function getSignatureFreeContexts() {
308
+ const urls = /* @__PURE__ */ new Set();
309
+ for (const [url, document] of globalThis.Object.entries(_fedify_vocab_runtime.preloadedContexts)) {
310
+ if (typeof document !== "object" || document == null) continue;
311
+ const context = document["@context"];
312
+ if (typeof context !== "object" || context == null || Array.isArray(context)) continue;
313
+ const record = context;
314
+ if (!globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) urls.add(url);
315
+ }
316
+ return urls;
317
+ }
318
+ function getContextEntryEffect(entry) {
319
+ if (entry == null) return "resets";
320
+ if (typeof entry === "string") {
321
+ if (signatureDefiningContexts.has(entry)) return "defines";
322
+ if (signatureFreeContexts.has(entry)) return "absent";
323
+ return "unknown";
324
+ }
325
+ if (typeof entry !== "object") return "absent";
326
+ const record = entry;
327
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) {
328
+ const definition = record["signature"];
329
+ const contextProtected = record["@protected"] === true;
330
+ const imported = globalThis.Object.prototype.hasOwnProperty.call(record, "@import");
331
+ if (definition == null) {
332
+ if (contextProtected) return "defines";
333
+ return imported ? "unknown" : "resets";
334
+ }
335
+ if (typeof definition === "object" && !Array.isArray(definition)) {
336
+ const term = definition;
337
+ const protectedTerm = contextProtected || term["@protected"] === true;
338
+ if (globalThis.Object.prototype.hasOwnProperty.call(term, "@id") && term["@id"] == null) {
339
+ if (protectedTerm) return "defines";
340
+ return imported ? "unknown" : "resets";
341
+ }
342
+ }
343
+ return "defines";
344
+ }
345
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "@import")) return "unknown";
346
+ return "absent";
347
+ }
348
+ function getSignatureTermState(context) {
349
+ if (context == null) return "absent";
350
+ if (!Array.isArray(context)) {
351
+ const effect = getContextEntryEffect(context);
352
+ return effect === "defines" ? "defined" : effect === "unknown" ? "unknown" : "absent";
353
+ }
354
+ let state = "absent";
355
+ for (const entry of context) {
356
+ const effect = getContextEntryEffect(entry);
357
+ if (effect === "defines") state = "defined";
358
+ else if (effect === "resets") state = "absent";
359
+ else if (effect === "unknown" && state !== "defined") state = "unknown";
360
+ }
361
+ return state;
362
+ }
363
+ function prepareSignatureDocument(jsonLd) {
364
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) return jsonLd;
365
+ const document = jsonLd;
366
+ if (document["proof"] != null) return { ...document };
367
+ const context = document["@context"];
368
+ if (getSignatureTermState(context) !== "absent") return { ...document };
369
+ const definition = { ...signatureTermDefinition };
370
+ return {
371
+ ...document,
372
+ "@context": context == null ? [definition] : Array.isArray(context) ? [...context, definition] : [context, definition]
373
+ };
374
+ }
303
375
  /**
304
376
  * Attaches a LD signature to the given JSON-LD document.
377
+ *
378
+ * When the document's context does not already define the `signature`
379
+ * property, the returned document adds a minimal inline context for it.
380
+ * Without that definition, expanding the attached signature would produce a
381
+ * blank node predicate, which is not valid RDF. Documents that already carry
382
+ * a `proof` are left unchanged, since a new context definition would invalidate
383
+ * the proof. Documents whose context includes an unrecognized remote context
384
+ * are also left unchanged, since that context may already define `signature`.
305
385
  * @param jsonLd The JSON-LD document to attach the signature to. It is not
306
386
  * modified.
307
387
  * @param signature The signature to attach.
308
388
  * @returns The JSON-LD document with the attached signature.
309
389
  * @throws {TypeError} If the input document is not a valid JSON-LD document.
390
+ * Top-level arrays are rejected, since a Linked Data
391
+ * Signature is attached to a single node.
310
392
  * @since 1.0.0
311
393
  */
312
394
  function attachSignature(jsonLd, signature) {
313
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
314
- return {
315
- ...jsonLd,
316
- signature
317
- };
395
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
396
+ const output = prepareSignatureDocument(jsonLd);
397
+ output.signature = signature;
398
+ return output;
318
399
  }
319
400
  /**
320
401
  * Creates a LD signature for the given JSON-LD document.
402
+ *
403
+ * If the document's context does not define the `signature` property, the
404
+ * signature is computed over the document with a minimal inline definition
405
+ * added. Use {@link attachSignature} to attach the signature to that exact
406
+ * document. Documents that already carry a `proof`, or whose context includes
407
+ * an unrecognized remote context, are hashed unchanged.
321
408
  * @param jsonLd The JSON-LD document to sign.
322
409
  * @param privateKey The private key to sign the document.
323
410
  * @param keyId The ID of the public key that corresponds to the private key.
@@ -331,14 +418,17 @@ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, creat
331
418
  require_http.validateCryptoKey(privateKey, "private");
332
419
  if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
333
420
  const options = {
334
- "@context": "https://w3id.org/identity/v1",
335
421
  creator: keyId.href,
336
422
  created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
337
423
  };
338
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
424
+ const message = await hashJsonLd({
425
+ "@context": "https://w3id.org/identity/v1",
426
+ ...options
427
+ }, contextLoader) + await hashJsonLd(prepareSignatureDocument(jsonLd), contextLoader);
339
428
  const messageBytes = new TextEncoder().encode(message);
340
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
429
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), messageBytes);
341
430
  return {
431
+ "@context": "https://w3id.org/security/v1",
342
432
  ...options,
343
433
  type: "RsaSignature2017",
344
434
  signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
@@ -377,20 +467,23 @@ async function signJsonLd(jsonLd, privateKey, keyId, options) {
377
467
  }
378
468
  });
379
469
  }
380
- /**
381
- * Checks if the given JSON-LD document has a Linked Data Signature.
382
- * @param jsonLd The JSON-LD document to check.
383
- * @returns `true` if the document has a signature; `false` otherwise.
384
- * @since 1.0.0
385
- */
386
- function hasSignature(jsonLd) {
387
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
388
- if ("signature" in jsonLd) {
389
- const signature = jsonLd.signature;
390
- if (typeof signature !== "object" || signature == null) return false;
391
- 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";
392
- }
393
- return false;
470
+ /** @internal */
471
+ function hasVerifiableSignature(jsonLd) {
472
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || !("signature" in jsonLd)) return false;
473
+ const signature = jsonLd.signature;
474
+ if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return false;
475
+ 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";
476
+ }
477
+ /** @internal */
478
+ function describeSignatureShape(jsonLd) {
479
+ if (typeof jsonLd !== "object" || jsonLd == null || !("signature" in jsonLd)) return null;
480
+ const signature = jsonLd.signature;
481
+ const properties = typeof signature === "object" && signature != null ? globalThis.Object.keys(signature) : [];
482
+ return {
483
+ signatureKind: signature == null ? String(signature) : Array.isArray(signature) ? "array" : typeof signature,
484
+ signatureProperties: properties.sort().slice(0, 20).map((p) => p.slice(0, 80)),
485
+ signaturePropertyCount: properties.length
486
+ };
394
487
  }
395
488
  /**
396
489
  * Detaches Linked Data Signatures from the given JSON-LD document.
@@ -407,6 +500,9 @@ function detachSignature(jsonLd) {
407
500
  }
408
501
  /**
409
502
  * Verifies Linked Data Signatures of the given JSON-LD document.
503
+ * Unmapped properties discarded during JSON-LD processing are tolerated, but
504
+ * their values are not authenticated by the signature. Other unsafe
505
+ * canonicalization warnings, including relative IRIs, remain rejected.
410
506
  * @param jsonLd The JSON-LD document to verify.
411
507
  * @param options Options for verifying the signature.
412
508
  * @returns The public key that signed the document or `null` if the signature
@@ -414,7 +510,11 @@ function detachSignature(jsonLd) {
414
510
  * @since 1.0.0
415
511
  */
416
512
  async function verifySignature(jsonLd, options = {}) {
417
- if (!hasSignature(jsonLd)) return null;
513
+ if (!hasVerifiableSignature(jsonLd)) {
514
+ const shape = describeSignatureShape(jsonLd);
515
+ if (shape != null) logger$2.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
516
+ return null;
517
+ }
418
518
  const sig = jsonLd.signature;
419
519
  let signature;
420
520
  try {
@@ -426,7 +526,14 @@ async function verifySignature(jsonLd, options = {}) {
426
526
  });
427
527
  return null;
428
528
  }
429
- const { key, cached } = await require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options);
529
+ let creator;
530
+ try {
531
+ creator = new URL(sig.creator);
532
+ } catch {
533
+ logger$2.debug("Failed to verify; signature creator is not a valid URL.");
534
+ return null;
535
+ }
536
+ const { key, cached } = await require_http.fetchKey(creator, _fedify_vocab.CryptographicKey, options);
430
537
  if (key == null) return null;
431
538
  const sigOpts = {
432
539
  ...sig,
@@ -437,7 +544,7 @@ async function verifySignature(jsonLd, options = {}) {
437
544
  delete sigOpts.signatureValue;
438
545
  let sigOptsHash;
439
546
  try {
440
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
547
+ sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader, "verify");
441
548
  } catch (error) {
442
549
  logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
443
550
  signatureOptions: sigOpts,
@@ -449,7 +556,7 @@ async function verifySignature(jsonLd, options = {}) {
449
556
  delete document.signature;
450
557
  let docHash;
451
558
  try {
452
- docHash = await hashJsonLd(document, options.contextLoader);
559
+ docHash = await hashJsonLd(document, options.contextLoader, "verify");
453
560
  } catch (error) {
454
561
  logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
455
562
  document,
@@ -466,7 +573,7 @@ async function verifySignature(jsonLd, options = {}) {
466
573
  keyId: sig.creator,
467
574
  ...sig
468
575
  });
469
- const { key } = await require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
576
+ const { key } = await require_http.fetchKey(creator, _fedify_vocab.CryptographicKey, {
470
577
  ...options,
471
578
  keyCache: {
472
579
  get: () => Promise.resolve(void 0),
@@ -488,6 +595,8 @@ async function verifySignature(jsonLd, options = {}) {
488
595
  * Signatures. If the document is signed, this function verifies the signature
489
596
  * and checks if the document is attributed to the owner of the public key.
490
597
  * If the document is not signed, this function returns `false`.
598
+ * Unmapped properties discarded during JSON-LD processing are not
599
+ * authenticated, even when verification succeeds.
491
600
  * @param jsonLd The JSON-LD document to verify.
492
601
  * @param options Options for verifying the document.
493
602
  * @returns `true` if the document is authentic; `false` otherwise.
@@ -502,11 +611,12 @@ async function verifyCompactJsonLd(jsonLd, options = {}) {
502
611
  async function verifyJsonLdInternal(jsonLd, options, compact) {
503
612
  return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
504
613
  try {
505
- const verificationOptions = hasSignature(jsonLd) ? {
614
+ const hasLdSignature = hasVerifiableSignature(jsonLd);
615
+ const verificationOptions = hasLdSignature ? {
506
616
  ...options,
507
617
  contextLoader: getNormalizationContextLoader(options.contextLoader)
508
618
  } : options;
509
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
619
+ const compacted = compact ? hasLdSignature ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
510
620
  const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
511
621
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
512
622
  span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
@@ -540,10 +650,17 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
540
650
  }
541
651
  });
542
652
  }
543
- async function hashJsonLd(jsonLd, contextLoader) {
653
+ const tolerableVerificationWarnings = new Set(["blank node predicate", "invalid property"]);
654
+ function handleVerificationEvent({ event, next }) {
655
+ if (event.level === "warning" && !tolerableVerificationWarnings.has(event.code)) throw new TypeError(`Unsafe JSON-LD canonicalization warning: ${event.code}`);
656
+ next();
657
+ }
658
+ async function hashJsonLd(jsonLd, contextLoader, mode = "sign") {
544
659
  const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
545
660
  format: "application/n-quads",
546
- documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
661
+ documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
662
+ safe: mode === "sign",
663
+ eventHandler: mode === "verify" ? handleVerificationEvent : void 0
547
664
  });
548
665
  const encoder = new TextEncoder();
549
666
  return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
@@ -730,7 +847,10 @@ const logger = (0, _logtape_logtape.getLogger)([
730
847
  * @throws {TypeError} If the private key is invalid or unsupported.
731
848
  * @since 0.10.0
732
849
  */
733
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
850
+ async function createProof(object, privateKey, keyId, options = {}) {
851
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
852
+ }
853
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
734
854
  require_http.validateCryptoKey(privateKey, "private");
735
855
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
736
856
  const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -756,14 +876,26 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
756
876
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
757
877
  digest.set(new Uint8Array(proofDigest), 0);
758
878
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
759
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
760
- return new _fedify_vocab.DataIntegrityProof({
761
- cryptosuite: "eddsa-jcs-2022",
762
- verificationMethod: keyId,
763
- proofPurpose: "assertionMethod",
764
- created: created ?? Temporal.Now.instant(),
765
- proofValue: new Uint8Array(sig)
766
- });
879
+ const sig = await crypto.subtle.sign("Ed25519", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), digest);
880
+ return {
881
+ proof: new _fedify_vocab.DataIntegrityProof({
882
+ cryptosuite: "eddsa-jcs-2022",
883
+ verificationMethod: keyId,
884
+ proofPurpose: "assertionMethod",
885
+ created: created ?? Temporal.Now.instant(),
886
+ proofValue: new Uint8Array(sig)
887
+ }),
888
+ jsonLd: compactMsg
889
+ };
890
+ }
891
+ function getJsonLdContextKey(value) {
892
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
893
+ return JSON.stringify(sortJsonKeys(context));
894
+ }
895
+ function sortJsonKeys(value) {
896
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
897
+ if (typeof value !== "object" || value == null) return value;
898
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
767
899
  }
768
900
  /**
769
901
  * Signs the given object with the private key and returns the signed object.
@@ -779,9 +911,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
779
911
  return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(object).href } }, async (span) => {
780
912
  try {
781
913
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
914
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
782
915
  const existingProofs = [];
783
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
784
- const proof = await createProof(object, privateKey, keyId, options);
916
+ let hasProofs = object.proofIds.length > 0;
917
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
918
+ hasProofs = true;
919
+ break;
920
+ }
921
+ if (hasProofs) {
922
+ let sameContext = true;
923
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
924
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
925
+ }
785
926
  if (span.isRecording()) {
786
927
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
787
928
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -989,6 +1130,12 @@ Object.defineProperty(exports, "createSignature", {
989
1130
  return createSignature;
990
1131
  }
991
1132
  });
1133
+ Object.defineProperty(exports, "describeSignatureShape", {
1134
+ enumerable: true,
1135
+ get: function() {
1136
+ return describeSignatureShape;
1137
+ }
1138
+ });
992
1139
  Object.defineProperty(exports, "detachSignature", {
993
1140
  enumerable: true,
994
1141
  get: function() {
@@ -1013,10 +1160,10 @@ Object.defineProperty(exports, "getNormalizationContextLoader", {
1013
1160
  return getNormalizationContextLoader;
1014
1161
  }
1015
1162
  });
1016
- Object.defineProperty(exports, "hasSignature", {
1163
+ Object.defineProperty(exports, "hasVerifiableSignature", {
1017
1164
  enumerable: true,
1018
1165
  get: function() {
1019
- return hasSignature;
1166
+ return hasVerifiableSignature;
1020
1167
  }
1021
1168
  });
1022
1169
  Object.defineProperty(exports, "isClearlyMalformedContextReference", {
@@ -1,10 +1,11 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-CiaJqTcu.mjs";
5
- import { r as fetchKey, s as validateCryptoKey } from "./key-Dg6-DV_O.mjs";
4
+ import { n as version, t as name } from "./deno-L23b3Hba.mjs";
5
+ import { r as fetchKey, s as validateCryptoKey } from "./key-Dai3f5yI.mjs";
6
6
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
7
7
  import { SpanStatusCode, trace } from "@opentelemetry/api";
8
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
8
9
  import { getLogger } from "@logtape/logtape";
9
10
  import { encodeHex } from "byte-encodings/hex";
10
11
  import serialize from "json-canon";
@@ -24,7 +25,10 @@ const logger = getLogger([
24
25
  * @throws {TypeError} If the private key is invalid or unsupported.
25
26
  * @since 0.10.0
26
27
  */
27
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
28
+ async function createProof(object, privateKey, keyId, options = {}) {
29
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
30
+ }
31
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
28
32
  validateCryptoKey(privateKey, "private");
29
33
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
30
34
  const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -50,14 +54,26 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
50
54
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
51
55
  digest.set(new Uint8Array(proofDigest), 0);
52
56
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
53
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
54
- return new DataIntegrityProof({
55
- cryptosuite: "eddsa-jcs-2022",
56
- verificationMethod: keyId,
57
- proofPurpose: "assertionMethod",
58
- created: created ?? Temporal.Now.instant(),
59
- proofValue: new Uint8Array(sig)
60
- });
57
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
58
+ return {
59
+ proof: new DataIntegrityProof({
60
+ cryptosuite: "eddsa-jcs-2022",
61
+ verificationMethod: keyId,
62
+ proofPurpose: "assertionMethod",
63
+ created: created ?? Temporal.Now.instant(),
64
+ proofValue: new Uint8Array(sig)
65
+ }),
66
+ jsonLd: compactMsg
67
+ };
68
+ }
69
+ function getJsonLdContextKey(value) {
70
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
71
+ return JSON.stringify(sortJsonKeys(context));
72
+ }
73
+ function sortJsonKeys(value) {
74
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
75
+ if (typeof value !== "object" || value == null) return value;
76
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
61
77
  }
62
78
  /**
63
79
  * Signs the given object with the private key and returns the signed object.
@@ -73,9 +89,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
73
89
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
74
90
  try {
75
91
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
92
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
76
93
  const existingProofs = [];
77
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
78
- const proof = await createProof(object, privateKey, keyId, options);
94
+ let hasProofs = object.proofIds.length > 0;
95
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
96
+ hasProofs = true;
97
+ break;
98
+ }
99
+ if (hasProofs) {
100
+ let sameContext = true;
101
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
102
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
103
+ }
79
104
  if (span.isRecording()) {
80
105
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
81
106
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);