@fedify/fedify 2.0.36-dev.2551 → 2.0.36-dev.2598

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 (53) hide show
  1. package/dist/{builder-Dndt590h.mjs → builder-B5hI5Xsn.mjs} +3 -3
  2. package/dist/compat/transformers.test.mjs +1 -1
  3. package/dist/{deno-D_rTMbAD.mjs → deno--OYa_lxj.mjs} +1 -1
  4. package/dist/{docloader-DpTrZ5sA.mjs → docloader-BXR2f83H.mjs} +2 -2
  5. package/dist/federation/builder.test.mjs +1 -1
  6. package/dist/federation/handler.test.mjs +8 -8
  7. package/dist/federation/idempotency.test.mjs +2 -2
  8. package/dist/federation/inbox.test.mjs +1 -1
  9. package/dist/federation/middleware.test.mjs +381 -8
  10. package/dist/federation/mod.cjs +1 -1
  11. package/dist/federation/mod.js +1 -1
  12. package/dist/federation/send.test.mjs +3 -3
  13. package/dist/federation/temporal.test.mjs +1 -1
  14. package/dist/federation/webfinger.test.mjs +1 -1
  15. package/dist/{http-DGD9d8-A.mjs → http-C3d2DXwF.mjs} +2 -2
  16. package/dist/{http-DbDnj-Q7.cjs → http-CO_IVq7x.cjs} +1 -1
  17. package/dist/{http-BS1CmlZ6.js → http-CfyVeGgF.js} +1 -1
  18. package/dist/{inbox-BwpBTbhH.mjs → inbox-huUE3IP8.mjs} +1 -1
  19. package/dist/{key-1Gf85RN1.mjs → key-D5e9c_yV.mjs} +1 -1
  20. package/dist/{kv-cache-BdA7HpfF.cjs → kv-cache-BMlo_kyv.cjs} +1 -1
  21. package/dist/{kv-cache-BARiicPE.js → kv-cache-Zw0soD-7.js} +1 -1
  22. package/dist/{ld-BuuOR_Ms.mjs → ld-9qfz9rP_.mjs} +99 -10
  23. package/dist/{middleware-D9TWYyT_.cjs → middleware-Ad6kTSBf.cjs} +1 -1
  24. package/dist/{middleware-CQRCnFB4.js → middleware-BKs_a9P1.js} +111 -15
  25. package/dist/{middleware-DDM0j-X6.mjs → middleware-BhYpLGA_.mjs} +119 -23
  26. package/dist/{middleware-C5Nypx4Z.mjs → middleware-CT1Lbohd.mjs} +1 -1
  27. package/dist/{middleware-DThg01d8.cjs → middleware-CXoG7ZAW.cjs} +112 -16
  28. package/dist/{mod-DVPS4yam.d.cts → mod-BA6vqC2S.d.cts} +19 -7
  29. package/dist/{mod-BS-jg3Wx.d.ts → mod-CL9Ep0uo.d.ts} +19 -7
  30. package/dist/mod.cjs +4 -4
  31. package/dist/mod.d.cts +1 -1
  32. package/dist/mod.d.ts +1 -1
  33. package/dist/mod.js +4 -4
  34. package/dist/nodeinfo/handler.test.mjs +1 -1
  35. package/dist/{owner-BI33UeIv.mjs → owner-R4ffU9Ht.mjs} +2 -2
  36. package/dist/{proof-vVwkNRv4.cjs → proof-BrreJTRF.cjs} +131 -18
  37. package/dist/{proof-BBHUW8ev.js → proof-CE8nwTF6.js} +132 -19
  38. package/dist/{proof-GM73LJjx.mjs → proof-CiBs9Q4l.mjs} +36 -12
  39. package/dist/{send-nImUK91D.mjs → send-DpvZgVSA.mjs} +2 -2
  40. package/dist/sig/http.test.mjs +2 -2
  41. package/dist/sig/key.test.mjs +2 -2
  42. package/dist/sig/ld.test.mjs +198 -4
  43. package/dist/sig/mod.cjs +2 -2
  44. package/dist/sig/mod.d.cts +1 -1
  45. package/dist/sig/mod.d.ts +1 -1
  46. package/dist/sig/mod.js +2 -2
  47. package/dist/sig/owner.test.mjs +1 -1
  48. package/dist/sig/proof.test.mjs +71 -2
  49. package/dist/{temporal-CfNFB7M_.mjs → temporal-Dd-J410Z.mjs} +1 -1
  50. package/dist/utils/docloader.test.mjs +2 -2
  51. package/dist/utils/mod.cjs +1 -1
  52. package/dist/utils/mod.js +1 -1
  53. package/package.json +5 -5
@@ -1,11 +1,11 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { a as fetchActorDocument, d as name, f as version, i as exportJwk, l as validateCryptoKey, o as fetchKey, u as verifyKeyOwnership } from "./http-BS1CmlZ6.js";
3
+ import { a as fetchActorDocument, d as name, f as version, i as exportJwk, l as validateCryptoKey, o as fetchKey, u as verifyKeyOwnership } from "./http-CfyVeGgF.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";
8
+ import { getDocumentLoader, preloadedContexts } from "@fedify/vocab-runtime";
9
9
  import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
10
10
  import jsonld from "@fedify/vocab-runtime/jsonld";
11
11
  import serialize from "json-canon";
@@ -297,24 +297,110 @@ function assertSafeJsonLd(jsonLd) {
297
297
  }
298
298
  }
299
299
  }
300
+ const signatureTermDefinition = { "signature": "https://w3id.org/security#signature" };
301
+ const signatureDefiningContexts = new Set(["https://w3id.org/identity/v1", "https://w3id.org/security/v1"]);
302
+ const signatureFreeContexts = getSignatureFreeContexts();
303
+ function getSignatureFreeContexts() {
304
+ const urls = /* @__PURE__ */ new Set();
305
+ for (const [url, document] of globalThis.Object.entries(preloadedContexts)) {
306
+ if (typeof document !== "object" || document == null) continue;
307
+ const context = document["@context"];
308
+ if (typeof context !== "object" || context == null || Array.isArray(context)) continue;
309
+ const record = context;
310
+ if (!globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) urls.add(url);
311
+ }
312
+ return urls;
313
+ }
314
+ function getContextEntryEffect(entry) {
315
+ if (entry == null) return "resets";
316
+ if (typeof entry === "string") {
317
+ if (signatureDefiningContexts.has(entry)) return "defines";
318
+ if (signatureFreeContexts.has(entry)) return "absent";
319
+ return "unknown";
320
+ }
321
+ if (typeof entry !== "object") return "absent";
322
+ const record = entry;
323
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "signature")) {
324
+ const definition = record["signature"];
325
+ const contextProtected = record["@protected"] === true;
326
+ const imported = globalThis.Object.prototype.hasOwnProperty.call(record, "@import");
327
+ if (definition == null) {
328
+ if (contextProtected) return "defines";
329
+ return imported ? "unknown" : "resets";
330
+ }
331
+ if (typeof definition === "object" && !Array.isArray(definition)) {
332
+ const term = definition;
333
+ const protectedTerm = contextProtected || term["@protected"] === true;
334
+ if (globalThis.Object.prototype.hasOwnProperty.call(term, "@id") && term["@id"] == null) {
335
+ if (protectedTerm) return "defines";
336
+ return imported ? "unknown" : "resets";
337
+ }
338
+ }
339
+ return "defines";
340
+ }
341
+ if (globalThis.Object.prototype.hasOwnProperty.call(record, "@import")) return "unknown";
342
+ return "absent";
343
+ }
344
+ function getSignatureTermState(context) {
345
+ if (context == null) return "absent";
346
+ if (!Array.isArray(context)) {
347
+ const effect = getContextEntryEffect(context);
348
+ return effect === "defines" ? "defined" : effect === "unknown" ? "unknown" : "absent";
349
+ }
350
+ let state = "absent";
351
+ for (const entry of context) {
352
+ const effect = getContextEntryEffect(entry);
353
+ if (effect === "defines") state = "defined";
354
+ else if (effect === "resets") state = "absent";
355
+ else if (effect === "unknown" && state !== "defined") state = "unknown";
356
+ }
357
+ return state;
358
+ }
359
+ function prepareSignatureDocument(jsonLd) {
360
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) return jsonLd;
361
+ const document = jsonLd;
362
+ if (document["proof"] != null) return { ...document };
363
+ const context = document["@context"];
364
+ if (getSignatureTermState(context) !== "absent") return { ...document };
365
+ const definition = { ...signatureTermDefinition };
366
+ return {
367
+ ...document,
368
+ "@context": context == null ? [definition] : Array.isArray(context) ? [...context, definition] : [context, definition]
369
+ };
370
+ }
300
371
  /**
301
372
  * Attaches a LD signature to the given JSON-LD document.
373
+ *
374
+ * When the document's context does not already define the `signature`
375
+ * property, the returned document adds a minimal inline context for it.
376
+ * Without that definition, expanding the attached signature would produce a
377
+ * blank node predicate, which is not valid RDF. Documents that already carry
378
+ * a `proof` are left unchanged, since a new context definition would invalidate
379
+ * the proof. Documents whose context includes an unrecognized remote context
380
+ * are also left unchanged, since that context may already define `signature`.
302
381
  * @param jsonLd The JSON-LD document to attach the signature to. It is not
303
382
  * modified.
304
383
  * @param signature The signature to attach.
305
384
  * @returns The JSON-LD document with the attached signature.
306
385
  * @throws {TypeError} If the input document is not a valid JSON-LD document.
386
+ * Top-level arrays are rejected, since a Linked Data
387
+ * Signature is attached to a single node.
307
388
  * @since 1.0.0
308
389
  */
309
390
  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
- };
391
+ if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd)) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
392
+ const output = prepareSignatureDocument(jsonLd);
393
+ output.signature = signature;
394
+ return output;
315
395
  }
316
396
  /**
317
397
  * Creates a LD signature for the given JSON-LD document.
398
+ *
399
+ * If the document's context does not define the `signature` property, the
400
+ * signature is computed over the document with a minimal inline definition
401
+ * added. Use {@link attachSignature} to attach the signature to that exact
402
+ * document. Documents that already carry a `proof`, or whose context includes
403
+ * an unrecognized remote context, are hashed unchanged.
318
404
  * @param jsonLd The JSON-LD document to sign.
319
405
  * @param privateKey The private key to sign the document.
320
406
  * @param keyId The ID of the public key that corresponds to the private key.
@@ -328,14 +414,17 @@ async function createSignature(jsonLd, privateKey, keyId, { contextLoader, creat
328
414
  validateCryptoKey(privateKey, "private");
329
415
  if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
330
416
  const options = {
331
- "@context": "https://w3id.org/identity/v1",
332
417
  creator: keyId.href,
333
418
  created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
334
419
  };
335
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
420
+ const message = await hashJsonLd({
421
+ "@context": "https://w3id.org/identity/v1",
422
+ ...options
423
+ }, contextLoader) + await hashJsonLd(prepareSignatureDocument(jsonLd), contextLoader);
336
424
  const messageBytes = new TextEncoder().encode(message);
337
425
  const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
338
426
  return {
427
+ "@context": "https://w3id.org/security/v1",
339
428
  ...options,
340
429
  type: "RsaSignature2017",
341
430
  signatureValue: encodeBase64(signature)
@@ -727,7 +816,10 @@ const logger = getLogger([
727
816
  * @throws {TypeError} If the private key is invalid or unsupported.
728
817
  * @since 0.10.0
729
818
  */
730
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
819
+ async function createProof(object, privateKey, keyId, options = {}) {
820
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
821
+ }
822
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
731
823
  validateCryptoKey(privateKey, "private");
732
824
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
733
825
  const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -754,13 +846,25 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
754
846
  digest.set(new Uint8Array(proofDigest), 0);
755
847
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
756
848
  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
- });
849
+ return {
850
+ proof: new DataIntegrityProof({
851
+ cryptosuite: "eddsa-jcs-2022",
852
+ verificationMethod: keyId,
853
+ proofPurpose: "assertionMethod",
854
+ created: created ?? Temporal.Now.instant(),
855
+ proofValue: new Uint8Array(sig)
856
+ }),
857
+ jsonLd: compactMsg
858
+ };
859
+ }
860
+ function getJsonLdContextKey(value) {
861
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
862
+ return JSON.stringify(sortJsonKeys(context));
863
+ }
864
+ function sortJsonKeys(value) {
865
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
866
+ if (typeof value !== "object" || value == null) return value;
867
+ 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
868
  }
765
869
  /**
766
870
  * Signs the given object with the private key and returns the signed object.
@@ -776,9 +880,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
776
880
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
777
881
  try {
778
882
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
883
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
779
884
  const existingProofs = [];
780
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
781
- const proof = await createProof(object, privateKey, keyId, options);
885
+ let hasProofs = object.proofIds.length > 0;
886
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
887
+ hasProofs = true;
888
+ break;
889
+ }
890
+ if (hasProofs) {
891
+ let sameContext = true;
892
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
893
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
894
+ }
782
895
  if (span.isRecording()) {
783
896
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
784
897
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -1,8 +1,8 @@
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-D_rTMbAD.mjs";
5
- import { o as validateCryptoKey, r as fetchKey } from "./key-1Gf85RN1.mjs";
4
+ import { n as version, t as name } from "./deno--OYa_lxj.mjs";
5
+ import { o as validateCryptoKey, r as fetchKey } from "./key-D5e9c_yV.mjs";
6
6
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
7
7
  import { SpanStatusCode, trace } from "@opentelemetry/api";
8
8
  import { getLogger } from "@logtape/logtape";
@@ -24,7 +24,10 @@ const logger = getLogger([
24
24
  * @throws {TypeError} If the private key is invalid or unsupported.
25
25
  * @since 0.10.0
26
26
  */
27
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
27
+ async function createProof(object, privateKey, keyId, options = {}) {
28
+ return (await createProofInternal(object, privateKey, keyId, options)).proof;
29
+ }
30
+ async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}) {
28
31
  validateCryptoKey(privateKey, "private");
29
32
  if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
30
33
  const compactMsg = await object.clone({ proofs: [] }).toJsonLd({
@@ -51,13 +54,25 @@ async function createProof(object, privateKey, keyId, { contextLoader, context,
51
54
  digest.set(new Uint8Array(proofDigest), 0);
52
55
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
53
56
  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
+ return {
58
+ proof: new DataIntegrityProof({
59
+ cryptosuite: "eddsa-jcs-2022",
60
+ verificationMethod: keyId,
61
+ proofPurpose: "assertionMethod",
62
+ created: created ?? Temporal.Now.instant(),
63
+ proofValue: new Uint8Array(sig)
64
+ }),
65
+ jsonLd: compactMsg
66
+ };
67
+ }
68
+ function getJsonLdContextKey(value) {
69
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
70
+ return JSON.stringify(sortJsonKeys(context));
71
+ }
72
+ function sortJsonKeys(value) {
73
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
74
+ if (typeof value !== "object" || value == null) return value;
75
+ 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
76
  }
62
77
  /**
63
78
  * Signs the given object with the private key and returns the signed object.
@@ -73,9 +88,18 @@ async function signObject(object, privateKey, keyId, options = {}) {
73
88
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
74
89
  try {
75
90
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
91
+ const { proof, jsonLd } = await createProofInternal(object, privateKey, keyId, options);
76
92
  const existingProofs = [];
77
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
78
- const proof = await createProof(object, privateKey, keyId, options);
93
+ let hasProofs = object.proofIds.length > 0;
94
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
95
+ hasProofs = true;
96
+ break;
97
+ }
98
+ if (hasProofs) {
99
+ let sameContext = true;
100
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
101
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
102
+ }
79
103
  if (span.isRecording()) {
80
104
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
81
105
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
@@ -1,8 +1,8 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-D_rTMbAD.mjs";
5
- import { r as doubleKnockScoped } from "./http-DGD9d8-A.mjs";
4
+ import { n as version, t as name } from "./deno--OYa_lxj.mjs";
5
+ import { r as doubleKnockScoped } from "./http-C3d2DXwF.mjs";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
7
  import { FetchError, UrlError } from "@fedify/vocab-runtime";
8
8
  import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
@@ -7,8 +7,8 @@ import { i as assertExists, t as assertStringIncludes } from "../std__assert-Dfl
7
7
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
8
8
  import { t as assert } from "../assert-BhQd8QHP.mjs";
9
9
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
10
- import { t as exportJwk } from "../key-1Gf85RN1.mjs";
11
- import { a as formatRfc9421SignatureParameters, c as signRequest, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-DGD9d8-A.mjs";
10
+ import { t as exportJwk } from "../key-D5e9c_yV.mjs";
11
+ import { a as formatRfc9421SignatureParameters, c as signRequest, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-C3d2DXwF.mjs";
12
12
  import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-CCxRJhWa.mjs";
13
13
  import { mockDocumentLoader, test } from "@fedify/fixture";
14
14
  import { FetchError, exportSpki } from "@fedify/vocab-runtime";
@@ -6,9 +6,9 @@ import { n as assertStrictEquals } from "../std__assert-DflMZha5.mjs";
6
6
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
7
7
  import { t as assert } from "../assert-BhQd8QHP.mjs";
8
8
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
9
- import { a as importJwk, i as generateCryptoKeyPair, o as validateCryptoKey, r as fetchKey, t as exportJwk } from "../key-1Gf85RN1.mjs";
9
+ import { a as importJwk, i as generateCryptoKeyPair, o as validateCryptoKey, r as fetchKey, t as exportJwk } from "../key-D5e9c_yV.mjs";
10
10
  import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CCxRJhWa.mjs";
11
- import { g as wrapContextLoaderForJsonLd } from "../ld-BuuOR_Ms.mjs";
11
+ import { g as wrapContextLoaderForJsonLd } from "../ld-9qfz9rP_.mjs";
12
12
  import { mockDocumentLoader, test } from "@fedify/fixture";
13
13
  import { CryptographicKey, Multikey, Person } from "@fedify/vocab";
14
14
  import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
@@ -5,12 +5,13 @@ import { t as assertEquals } from "../assert_equals-Ew3jOFa3.mjs";
5
5
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
6
6
  import { n as assertInstanceOf, t as assert } from "../assert-BhQd8QHP.mjs";
7
7
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
8
- import { i as generateCryptoKeyPair } from "../key-1Gf85RN1.mjs";
8
+ import { i as generateCryptoKeyPair } from "../key-D5e9c_yV.mjs";
9
9
  import { a as rsaPrivateKey3, c as rsaPublicKey3, i as rsaPrivateKey2, n as ed25519PrivateKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CCxRJhWa.mjs";
10
- import { a as compactJsonLd, d as isInvalidUrlTypeError, f as signJsonLd, h as verifySignature, i as attachSignature, m as verifyJsonLd, n as UnsafeJsonLdError, o as createSignature, s as detachSignature } from "../ld-BuuOR_Ms.mjs";
10
+ import { a as compactJsonLd, d as isInvalidUrlTypeError, f as signJsonLd, h as verifySignature, i as attachSignature, m as verifyJsonLd, n as UnsafeJsonLdError, o as createSignature, s as detachSignature } from "../ld-9qfz9rP_.mjs";
11
11
  import { mockDocumentLoader, test } from "@fedify/fixture";
12
12
  import { CryptographicKey } from "@fedify/vocab";
13
13
  import { encodeBase64 } from "byte-encodings/base64";
14
+ import jsonld from "@fedify/vocab-runtime/jsonld";
14
15
  //#region src/sig/ld.test.ts
15
16
  test("isInvalidUrlTypeError()", () => {
16
17
  assert(isInvalidUrlTypeError(/* @__PURE__ */ new TypeError("Invalid URL string.")));
@@ -25,22 +26,84 @@ test("isInvalidUrlTypeError()", () => {
25
26
  });
26
27
  test("attachSignature()", () => {
27
28
  const sig = {
28
- "@context": "https://w3id.org/identity/v1",
29
+ "@context": "https://w3id.org/security/v1",
29
30
  type: "RsaSignature2017",
30
31
  creator: "https://activitypub.academy/users/brauca_darradiul#main-key",
31
32
  created: "2024-09-12T16:50:46Z",
32
33
  signatureValue: "asdf"
33
34
  };
35
+ const signatureTerm = { "signature": "https://w3id.org/security#signature" };
34
36
  const doc = {
35
37
  "@context": "https://www.w3.org/ns/activitystreams",
36
38
  id: "https://example.com/1"
37
39
  };
38
40
  assertEquals(attachSignature(doc, sig), {
39
41
  ...doc,
42
+ "@context": ["https://www.w3.org/ns/activitystreams", signatureTerm],
43
+ signature: sig
44
+ });
45
+ const arrayDoc = {
46
+ "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"],
47
+ id: "https://example.com/1"
48
+ };
49
+ assertEquals(attachSignature(arrayDoc, sig), {
50
+ ...arrayDoc,
51
+ "@context": [...arrayDoc["@context"], signatureTerm],
52
+ signature: sig
53
+ });
54
+ for (const context of [
55
+ ["https://w3id.org/identity/v1", "https://www.w3.org/ns/activitystreams"],
56
+ ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
57
+ ["https://www.w3.org/ns/activitystreams", signatureTerm],
58
+ { "signature": "https://w3id.org/security#signature" }
59
+ ]) {
60
+ const contextDoc = {
61
+ "@context": context,
62
+ id: "https://example.com/1"
63
+ };
64
+ assertEquals(attachSignature(contextDoc, sig), {
65
+ ...contextDoc,
66
+ signature: sig
67
+ });
68
+ }
69
+ assertEquals(attachSignature({
70
+ "@context": null,
71
+ id: "https://example.com/1"
72
+ }, sig), {
73
+ "@context": [signatureTerm],
74
+ id: "https://example.com/1",
75
+ signature: sig
76
+ });
77
+ const resetDoc = {
78
+ "@context": [
79
+ "https://w3id.org/security/v1",
80
+ null,
81
+ "https://www.w3.org/ns/activitystreams"
82
+ ],
83
+ id: "https://example.com/1"
84
+ };
85
+ assertEquals(attachSignature(resetDoc, sig), {
86
+ ...resetDoc,
87
+ "@context": [...resetDoc["@context"], signatureTerm],
88
+ signature: sig
89
+ });
90
+ const disabledTermDoc = {
91
+ "@context": [{ "signature": { "@id": null } }, "https://www.w3.org/ns/activitystreams"],
92
+ id: "https://example.com/1"
93
+ };
94
+ assertEquals(attachSignature(disabledTermDoc, sig), {
95
+ ...disabledTermDoc,
96
+ "@context": [...disabledTermDoc["@context"], signatureTerm],
97
+ signature: sig
98
+ });
99
+ assertEquals(attachSignature({ id: "https://example.com/1" }, sig), {
100
+ id: "https://example.com/1",
101
+ "@context": [signatureTerm],
40
102
  signature: sig
41
103
  });
42
104
  assertThrows(() => attachSignature(null, sig), TypeError);
43
105
  assertThrows(() => attachSignature(1234, sig), TypeError);
106
+ assertThrows(() => attachSignature([], sig), TypeError);
44
107
  });
45
108
  test("createSignature()", async () => {
46
109
  const doc = {
@@ -48,7 +111,9 @@ test("createSignature()", async () => {
48
111
  id: "https://example.com/1",
49
112
  type: "Create"
50
113
  };
51
- assertEquals(await verifySignature(attachSignature(doc, await createSignature(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader })), {
114
+ const sig = await createSignature(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader });
115
+ assertEquals(sig["@context"], "https://w3id.org/security/v1");
116
+ assertEquals(await verifySignature(attachSignature(doc, sig), {
52
117
  documentLoader: mockDocumentLoader,
53
118
  contextLoader: mockDocumentLoader
54
119
  }), rsaPublicKey2);
@@ -66,6 +131,135 @@ test("signJsonLd()", async () => {
66
131
  contextLoader: mockDocumentLoader
67
132
  }));
68
133
  });
134
+ test("signJsonLd() defines the signature term when the context lacks it", async () => {
135
+ const signed = await signJsonLd({
136
+ "@context": "https://www.w3.org/ns/activitystreams",
137
+ id: "https://example.com/notes/1",
138
+ type: "Note",
139
+ content: "Hello"
140
+ }, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader });
141
+ assert(Array.isArray(signed["@context"]));
142
+ assertEquals(signed["@context"][1], { "signature": "https://w3id.org/security#signature" });
143
+ assert((await jsonld.canonize(signed, {
144
+ format: "application/n-quads",
145
+ documentLoader: mockDocumentLoader
146
+ })).includes("<https://w3id.org/security#signature>"));
147
+ assertEquals(await verifySignature(signed, {
148
+ documentLoader: mockDocumentLoader,
149
+ contextLoader: mockDocumentLoader
150
+ }), rsaPublicKey2);
151
+ });
152
+ test("signJsonLd() signs documents that use the signature term", async () => {
153
+ const signatureTerm = { "signature": "https://w3id.org/security#signature" };
154
+ for (const object of [{
155
+ type: "Note",
156
+ signature: "nested value"
157
+ }, { type: "signature" }]) {
158
+ const doc = {
159
+ "@context": ["https://www.w3.org/ns/activitystreams", { "@vocab": "https://example.com/" }],
160
+ id: "https://example.com/1",
161
+ type: "Create",
162
+ object
163
+ };
164
+ const signed = await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader });
165
+ assertEquals(signed["@context"], [...doc["@context"], signatureTerm]);
166
+ assertEquals(signed["object"], object);
167
+ assertEquals(await verifySignature(signed, {
168
+ documentLoader: mockDocumentLoader,
169
+ contextLoader: mockDocumentLoader
170
+ }), rsaPublicKey2);
171
+ }
172
+ });
173
+ test("signJsonLd() does not share the inline signature definition", async () => {
174
+ const doc = {
175
+ "@context": "https://www.w3.org/ns/activitystreams",
176
+ id: "https://example.com/notes/1",
177
+ type: "Note"
178
+ };
179
+ const firstContext = (await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader }))["@context"];
180
+ firstContext[1]["signature"] = "https://example.com/signature";
181
+ assertEquals((await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader }))["@context"][1], { "signature": "https://w3id.org/security#signature" });
182
+ });
183
+ test("signJsonLd() respects a protected null signature definition", async () => {
184
+ for (const context of [{
185
+ "@protected": true,
186
+ "signature": { "@id": null }
187
+ }, { "signature": {
188
+ "@id": null,
189
+ "@protected": true
190
+ } }]) {
191
+ const doc = {
192
+ "@context": ["https://www.w3.org/ns/activitystreams", context],
193
+ id: "https://example.com/1",
194
+ type: "Note"
195
+ };
196
+ const signed = await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader: mockDocumentLoader });
197
+ assertEquals(signed["@context"], doc["@context"]);
198
+ assertEquals(await verifySignature(signed, {
199
+ documentLoader: mockDocumentLoader,
200
+ contextLoader: mockDocumentLoader
201
+ }), rsaPublicKey2);
202
+ }
203
+ });
204
+ test("signJsonLd() respects protection from imported contexts", async () => {
205
+ const importUrl = "https://example.com/contexts/imported-protected";
206
+ const contextLoader = async (url) => {
207
+ if (new URL(url).href === importUrl) return {
208
+ contextUrl: null,
209
+ documentUrl: url,
210
+ document: { "@context": {
211
+ "@protected": true,
212
+ "name": "https://example.com/name"
213
+ } }
214
+ };
215
+ return await mockDocumentLoader(url);
216
+ };
217
+ for (const signature of [null, { "@id": null }]) {
218
+ const doc = {
219
+ "@context": ["https://www.w3.org/ns/activitystreams", {
220
+ "@import": importUrl,
221
+ signature
222
+ }],
223
+ id: "https://example.com/1",
224
+ type: "Note",
225
+ name: "Alice"
226
+ };
227
+ const signed = await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader });
228
+ assertEquals(signed["@context"], doc["@context"]);
229
+ assertEquals(await verifySignature(signed, {
230
+ documentLoader: mockDocumentLoader,
231
+ contextLoader
232
+ }), rsaPublicKey2);
233
+ }
234
+ });
235
+ test("signJsonLd() leaves unrecognized remote contexts unchanged", async () => {
236
+ const contextUrl = "https://example.com/contexts/custom";
237
+ const contextLoader = async (url) => {
238
+ if (new URL(url).href === contextUrl) return {
239
+ contextUrl: null,
240
+ documentUrl: url,
241
+ document: { "@context": {
242
+ "@protected": true,
243
+ "signature": {
244
+ "@id": "https://w3id.org/security#signature",
245
+ "@type": "@id"
246
+ }
247
+ } }
248
+ };
249
+ return await mockDocumentLoader(url);
250
+ };
251
+ const doc = {
252
+ "@context": ["https://www.w3.org/ns/activitystreams", contextUrl],
253
+ id: "https://example.com/1",
254
+ type: "Note"
255
+ };
256
+ const signed = await signJsonLd(doc, rsaPrivateKey2, rsaPublicKey2.id, { contextLoader });
257
+ assertEquals(signed["@context"], doc["@context"]);
258
+ assertEquals(await verifySignature(signed, {
259
+ documentLoader: mockDocumentLoader,
260
+ contextLoader
261
+ }), rsaPublicKey2);
262
+ });
69
263
  const document = {
70
264
  "@context": ["https://www.w3.org/ns/activitystreams", {
71
265
  "ostatus": "http://ostatus.org#",
package/dist/sig/mod.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
- const require_http = require("../http-DbDnj-Q7.cjs");
5
- const require_proof = require("../proof-vVwkNRv4.cjs");
4
+ const require_http = require("../http-CO_IVq7x.cjs");
5
+ const require_proof = require("../proof-BrreJTRF.cjs");
6
6
  exports.attachSignature = require_proof.attachSignature;
7
7
  exports.createProof = require_proof.createProof;
8
8
  exports.createSignature = require_proof.createSignature;
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.temporal" />
2
2
  import { a as signRequest, c as FetchKeyResult, d as fetchKey, f as generateCryptoKeyPair, i as VerifyRequestOptions, l as KeyCache, n as HttpMessageSignaturesSpecDeterminer, o as verifyRequest, p as importJwk, r as SignRequestOptions, s as FetchKeyOptions, t as HttpMessageSignaturesSpec, u as exportJwk } from "../http-DFqAb11b.cjs";
3
3
  import { i as getKeyOwner, n as GetKeyOwnerOptions, r as doesActorOwnKey, t as DoesActorOwnKeyOptions } from "../owner-B3hNQCG8.cjs";
4
- import { _ as verifyJsonLd, a as createProof, c as verifyProof, d as VerifyJsonLdOptions, f as VerifySignatureOptions, g as signJsonLd, h as detachSignature, i as VerifyProofOptions, l as CreateSignatureOptions, m as createSignature, n as SignObjectOptions, o as signObject, p as attachSignature, r as VerifyObjectOptions, s as verifyObject, t as CreateProofOptions, u as SignJsonLdOptions, v as verifySignature } from "../mod-DVPS4yam.cjs";
4
+ import { _ as verifyJsonLd, a as createProof, c as verifyProof, d as VerifyJsonLdOptions, f as VerifySignatureOptions, g as signJsonLd, h as detachSignature, i as VerifyProofOptions, l as CreateSignatureOptions, m as createSignature, n as SignObjectOptions, o as signObject, p as attachSignature, r as VerifyObjectOptions, s as verifyObject, t as CreateProofOptions, u as SignJsonLdOptions, v as verifySignature } from "../mod-BA6vqC2S.cjs";
5
5
  export { CreateProofOptions, CreateSignatureOptions, DoesActorOwnKeyOptions, FetchKeyOptions, FetchKeyResult, GetKeyOwnerOptions, HttpMessageSignaturesSpec, HttpMessageSignaturesSpecDeterminer, KeyCache, SignJsonLdOptions, SignObjectOptions, SignRequestOptions, VerifyJsonLdOptions, VerifyObjectOptions, VerifyProofOptions, VerifyRequestOptions, VerifySignatureOptions, attachSignature, createProof, createSignature, detachSignature, doesActorOwnKey, exportJwk, fetchKey, generateCryptoKeyPair, getKeyOwner, importJwk, signJsonLd, signObject, signRequest, verifyJsonLd, verifyObject, verifyProof, verifyRequest, verifySignature };
package/dist/sig/mod.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.temporal" />
2
2
  import { a as signRequest, c as FetchKeyResult, d as fetchKey, f as generateCryptoKeyPair, i as VerifyRequestOptions, l as KeyCache, n as HttpMessageSignaturesSpecDeterminer, o as verifyRequest, p as importJwk, r as SignRequestOptions, s as FetchKeyOptions, t as HttpMessageSignaturesSpec, u as exportJwk } from "../http-Cd8UD1ym.js";
3
3
  import { i as getKeyOwner, n as GetKeyOwnerOptions, r as doesActorOwnKey, t as DoesActorOwnKeyOptions } from "../owner-CiBPcC6F.js";
4
- import { _ as verifyJsonLd, a as createProof, c as verifyProof, d as VerifyJsonLdOptions, f as VerifySignatureOptions, g as signJsonLd, h as detachSignature, i as VerifyProofOptions, l as CreateSignatureOptions, m as createSignature, n as SignObjectOptions, o as signObject, p as attachSignature, r as VerifyObjectOptions, s as verifyObject, t as CreateProofOptions, u as SignJsonLdOptions, v as verifySignature } from "../mod-BS-jg3Wx.js";
4
+ import { _ as verifyJsonLd, a as createProof, c as verifyProof, d as VerifyJsonLdOptions, f as VerifySignatureOptions, g as signJsonLd, h as detachSignature, i as VerifyProofOptions, l as CreateSignatureOptions, m as createSignature, n as SignObjectOptions, o as signObject, p as attachSignature, r as VerifyObjectOptions, s as verifyObject, t as CreateProofOptions, u as SignJsonLdOptions, v as verifySignature } from "../mod-CL9Ep0uo.js";
5
5
  export { CreateProofOptions, CreateSignatureOptions, DoesActorOwnKeyOptions, FetchKeyOptions, FetchKeyResult, GetKeyOwnerOptions, HttpMessageSignaturesSpec, HttpMessageSignaturesSpecDeterminer, KeyCache, SignJsonLdOptions, SignObjectOptions, SignRequestOptions, VerifyJsonLdOptions, VerifyObjectOptions, VerifyProofOptions, VerifyRequestOptions, VerifySignatureOptions, attachSignature, createProof, createSignature, detachSignature, doesActorOwnKey, exportJwk, fetchKey, generateCryptoKeyPair, getKeyOwner, importJwk, signJsonLd, signObject, signRequest, verifyJsonLd, verifyObject, verifyProof, verifyRequest, verifySignature };
package/dist/sig/mod.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { c as importJwk, i as exportJwk, n as signRequest, o as fetchKey, r as verifyRequest, s as generateCryptoKeyPair } from "../http-BS1CmlZ6.js";
4
- import { _ as signJsonLd, a as doesActorOwnKey, b as verifySignature, d as createSignature, f as detachSignature, i as verifyProof, l as attachSignature, n as signObject, o as getKeyOwner, r as verifyObject, t as createProof, y as verifyJsonLd } from "../proof-BBHUW8ev.js";
3
+ import { c as importJwk, i as exportJwk, n as signRequest, o as fetchKey, r as verifyRequest, s as generateCryptoKeyPair } from "../http-CfyVeGgF.js";
4
+ import { _ as signJsonLd, a as doesActorOwnKey, b as verifySignature, d as createSignature, f as detachSignature, i as verifyProof, l as attachSignature, n as signObject, o as getKeyOwner, r as verifyObject, t as createProof, y as verifyJsonLd } from "../proof-CE8nwTF6.js";
5
5
  export { attachSignature, createProof, createSignature, detachSignature, doesActorOwnKey, exportJwk, fetchKey, generateCryptoKeyPair, getKeyOwner, importJwk, signJsonLd, signObject, signRequest, verifyJsonLd, verifyObject, verifyProof, verifyRequest, verifySignature };
@@ -6,7 +6,7 @@ import "../std__assert-DflMZha5.mjs";
6
6
  import { r as assertFalse } from "../assert_throws-D4DNWrux.mjs";
7
7
  import { t as assert } from "../assert-BhQd8QHP.mjs";
8
8
  import { o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-CCxRJhWa.mjs";
9
- import { n as getKeyOwner, t as doesActorOwnKey } from "../owner-BI33UeIv.mjs";
9
+ import { n as getKeyOwner, t as doesActorOwnKey } from "../owner-R4ffU9Ht.mjs";
10
10
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
11
11
  import { Create, CryptographicKey, lookupObject } from "@fedify/vocab";
12
12
  //#region src/sig/owner.test.ts