@941design/marmot-engine 0.0.0-stage → 0.2.0-alpha.0

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 (196) hide show
  1. package/CHANGELOG.md +434 -0
  2. package/LICENSE +49 -0
  3. package/README.md +33 -2
  4. package/dist/audit/emitter.d.ts +17 -0
  5. package/dist/audit/emitter.js +30 -0
  6. package/dist/audit/helpers.d.ts +16 -0
  7. package/dist/audit/helpers.js +103 -0
  8. package/dist/audit/index.d.ts +6 -0
  9. package/dist/audit/index.js +6 -0
  10. package/dist/audit/recorder.d.ts +13 -0
  11. package/dist/audit/recorder.js +24 -0
  12. package/dist/audit/sink.d.ts +16 -0
  13. package/dist/audit/sink.js +27 -0
  14. package/dist/audit/types-internal.d.ts +7 -0
  15. package/dist/audit/types-internal.js +1 -0
  16. package/dist/audit/types.d.ts +289 -0
  17. package/dist/audit/types.js +2 -0
  18. package/dist/core/account-identity-proof.d.ts +165 -0
  19. package/dist/core/account-identity-proof.js +277 -0
  20. package/dist/core/application-rumor.d.ts +45 -0
  21. package/dist/core/application-rumor.js +120 -0
  22. package/dist/core/auth-service.d.ts +2 -0
  23. package/dist/core/auth-service.js +52 -0
  24. package/dist/core/binary.d.ts +142 -0
  25. package/dist/core/binary.js +363 -0
  26. package/dist/core/capabilities.d.ts +51 -0
  27. package/dist/core/capabilities.js +102 -0
  28. package/dist/core/client-state.d.ts +119 -0
  29. package/dist/core/client-state.js +226 -0
  30. package/dist/core/commit-authorization.d.ts +26 -0
  31. package/dist/core/commit-authorization.js +26 -0
  32. package/dist/core/components/admin-policy.d.ts +4 -0
  33. package/dist/core/components/admin-policy.js +69 -0
  34. package/dist/core/components/agent-text-stream.d.ts +51 -0
  35. package/dist/core/components/agent-text-stream.js +112 -0
  36. package/dist/core/components/app-components-list.d.ts +17 -0
  37. package/dist/core/components/app-components-list.js +35 -0
  38. package/dist/core/components/avatar-url.d.ts +12 -0
  39. package/dist/core/components/avatar-url.js +85 -0
  40. package/dist/core/components/bytes.d.ts +5 -0
  41. package/dist/core/components/bytes.js +18 -0
  42. package/dist/core/components/dictionary.d.ts +80 -0
  43. package/dist/core/components/dictionary.js +175 -0
  44. package/dist/core/components/disband-validation.d.ts +21 -0
  45. package/dist/core/components/disband-validation.js +173 -0
  46. package/dist/core/components/encrypted-media.d.ts +44 -0
  47. package/dist/core/components/encrypted-media.js +210 -0
  48. package/dist/core/components/group-lifecycle.d.ts +10 -0
  49. package/dist/core/components/group-lifecycle.js +32 -0
  50. package/dist/core/components/group-profile.d.ts +24 -0
  51. package/dist/core/components/group-profile.js +35 -0
  52. package/dist/core/components/host-safety.d.ts +9 -0
  53. package/dist/core/components/host-safety.js +148 -0
  54. package/dist/core/components/ids.d.ts +74 -0
  55. package/dist/core/components/ids.js +73 -0
  56. package/dist/core/components/index.d.ts +14 -0
  57. package/dist/core/components/index.js +14 -0
  58. package/dist/core/components/integrity.d.ts +141 -0
  59. package/dist/core/components/integrity.js +293 -0
  60. package/dist/core/components/message-retention.d.ts +17 -0
  61. package/dist/core/components/message-retention.js +26 -0
  62. package/dist/core/components/nostr-routing.d.ts +8 -0
  63. package/dist/core/components/nostr-routing.js +92 -0
  64. package/dist/core/components/url.d.ts +26 -0
  65. package/dist/core/components/url.js +44 -0
  66. package/dist/core/convergence-status.d.ts +84 -0
  67. package/dist/core/convergence-status.js +82 -0
  68. package/dist/core/convergence.d.ts +567 -0
  69. package/dist/core/convergence.js +1150 -0
  70. package/dist/core/credential.d.ts +16 -0
  71. package/dist/core/credential.js +64 -0
  72. package/dist/core/default-capabilities.d.ts +9 -0
  73. package/dist/core/default-capabilities.js +34 -0
  74. package/dist/core/extensions.d.ts +9 -0
  75. package/dist/core/extensions.js +5 -0
  76. package/dist/core/grease.d.ts +2 -0
  77. package/dist/core/grease.js +6 -0
  78. package/dist/core/group-event.d.ts +18 -0
  79. package/dist/core/group-event.js +30 -0
  80. package/dist/core/group-lifecycle.d.ts +42 -0
  81. package/dist/core/group-lifecycle.js +66 -0
  82. package/dist/core/group-members.d.ts +37 -0
  83. package/dist/core/group-members.js +99 -0
  84. package/dist/core/group-message-classify.d.ts +42 -0
  85. package/dist/core/group-message-classify.js +57 -0
  86. package/dist/core/group-message-crypto.d.ts +53 -0
  87. package/dist/core/group-message-crypto.js +140 -0
  88. package/dist/core/group-message.d.ts +5 -0
  89. package/dist/core/group-message.js +11 -0
  90. package/dist/core/group.d.ts +45 -0
  91. package/dist/core/group.js +78 -0
  92. package/dist/core/inbound.d.ts +102 -0
  93. package/dist/core/inbound.js +79 -0
  94. package/dist/core/index.d.ts +28 -0
  95. package/dist/core/index.js +26 -0
  96. package/dist/core/key-package-eligibility.d.ts +31 -0
  97. package/dist/core/key-package-eligibility.js +116 -0
  98. package/dist/core/key-package-event-decode.d.ts +43 -0
  99. package/dist/core/key-package-event-decode.js +118 -0
  100. package/dist/core/key-package-event-delete.d.ts +16 -0
  101. package/dist/core/key-package-event-delete.js +46 -0
  102. package/dist/core/key-package-event-encode.d.ts +28 -0
  103. package/dist/core/key-package-event-encode.js +102 -0
  104. package/dist/core/key-package-event.d.ts +4 -0
  105. package/dist/core/key-package-event.js +8 -0
  106. package/dist/core/key-package.d.ts +55 -0
  107. package/dist/core/key-package.js +115 -0
  108. package/dist/core/leaf-succession.d.ts +83 -0
  109. package/dist/core/leaf-succession.js +97 -0
  110. package/dist/core/media/canonical.d.ts +34 -0
  111. package/dist/core/media/canonical.js +57 -0
  112. package/dist/core/media/crypto.d.ts +79 -0
  113. package/dist/core/media/crypto.js +215 -0
  114. package/dist/core/media/imeta.d.ts +33 -0
  115. package/dist/core/media/imeta.js +188 -0
  116. package/dist/core/media/locator.d.ts +44 -0
  117. package/dist/core/media/locator.js +69 -0
  118. package/dist/core/media/types.d.ts +83 -0
  119. package/dist/core/media/types.js +12 -0
  120. package/dist/core/media.d.ts +6 -0
  121. package/dist/core/media.js +12 -0
  122. package/dist/core/protocol.d.ts +51 -0
  123. package/dist/core/protocol.js +41 -0
  124. package/dist/core/relay-lists.d.ts +52 -0
  125. package/dist/core/relay-lists.js +86 -0
  126. package/dist/core/retained-history.d.ts +78 -0
  127. package/dist/core/retained-history.js +59 -0
  128. package/dist/core/transport.d.ts +43 -0
  129. package/dist/core/transport.js +21 -0
  130. package/dist/core/welcome-event.d.ts +61 -0
  131. package/dist/core/welcome-event.js +116 -0
  132. package/dist/core/welcome-join.d.ts +155 -0
  133. package/dist/core/welcome-join.js +243 -0
  134. package/dist/core/welcome.d.ts +3 -0
  135. package/dist/core/welcome.js +6 -0
  136. package/dist/engine/admin-policy.d.ts +58 -0
  137. package/dist/engine/admin-policy.js +137 -0
  138. package/dist/engine/auto-committer.d.ts +39 -0
  139. package/dist/engine/auto-committer.js +42 -0
  140. package/dist/engine/delivered-payloads.d.ts +61 -0
  141. package/dist/engine/delivered-payloads.js +84 -0
  142. package/dist/engine/disband-request.d.ts +41 -0
  143. package/dist/engine/disband-request.js +86 -0
  144. package/dist/engine/disband-tombstone.d.ts +14 -0
  145. package/dist/engine/disband-tombstone.js +66 -0
  146. package/dist/engine/fork-recovery.d.ts +672 -0
  147. package/dist/engine/fork-recovery.js +1615 -0
  148. package/dist/engine/group-engine.d.ts +571 -0
  149. package/dist/engine/group-engine.js +5112 -0
  150. package/dist/engine/history-tree.d.ts +232 -0
  151. package/dist/engine/history-tree.js +651 -0
  152. package/dist/engine/index.d.ts +16 -0
  153. package/dist/engine/index.js +15 -0
  154. package/dist/engine/ingest-disposition.d.ts +5 -0
  155. package/dist/engine/ingest-disposition.js +63 -0
  156. package/dist/engine/ingest.d.ts +390 -0
  157. package/dist/engine/ingest.js +1258 -0
  158. package/dist/engine/ingestion-pool.d.ts +74 -0
  159. package/dist/engine/ingestion-pool.js +95 -0
  160. package/dist/engine/message-dedup.d.ts +16 -0
  161. package/dist/engine/message-dedup.js +20 -0
  162. package/dist/engine/own-commit-stamp.d.ts +30 -0
  163. package/dist/engine/own-commit-stamp.js +71 -0
  164. package/dist/engine/retained-store.d.ts +79 -0
  165. package/dist/engine/retained-store.js +133 -0
  166. package/dist/engine/sender-ratchet.d.ts +50 -0
  167. package/dist/engine/sender-ratchet.js +196 -0
  168. package/dist/engine/state-notifications.d.ts +122 -0
  169. package/dist/engine/state-notifications.js +173 -0
  170. package/dist/engine/tree-convergence.d.ts +41 -0
  171. package/dist/engine/tree-convergence.js +90 -0
  172. package/dist/engine/types.d.ts +366 -0
  173. package/dist/engine/types.js +14 -0
  174. package/dist/engine/wire-format.d.ts +77 -0
  175. package/dist/engine/wire-format.js +120 -0
  176. package/dist/index.d.ts +12 -0
  177. package/dist/index.js +1 -0
  178. package/dist/mls.d.ts +11 -0
  179. package/dist/mls.js +11 -0
  180. package/dist/utils/debug.d.ts +3 -0
  181. package/dist/utils/debug.js +3 -0
  182. package/dist/utils/encoding.d.ts +38 -0
  183. package/dist/utils/encoding.js +91 -0
  184. package/dist/utils/key-value.d.ts +18 -0
  185. package/dist/utils/key-value.js +2 -0
  186. package/dist/utils/nostr.d.ts +35 -0
  187. package/dist/utils/nostr.js +26 -0
  188. package/dist/utils/relay-url.d.ts +10 -0
  189. package/dist/utils/relay-url.js +23 -0
  190. package/dist/utils/tag-cardinality.d.ts +50 -0
  191. package/dist/utils/tag-cardinality.js +91 -0
  192. package/dist/utils/timestamp.d.ts +50 -0
  193. package/dist/utils/timestamp.js +95 -0
  194. package/dist/version.d.ts +112 -0
  195. package/dist/version.js +112 -0
  196. package/package.json +68 -3
@@ -0,0 +1,97 @@
1
+ /** @module @category Core - Leaf key succession */
2
+ import { defaultCredentialTypes, leafNodeSources, nodeTypes } from "ts-mls";
3
+ import { getCredentialPubkey } from "./credential.js";
4
+ const HEX = "0123456789abcdef";
5
+ function toHex(bytes) {
6
+ let out = "";
7
+ for (let i = 0; i < bytes.length; i++) {
8
+ const byte = bytes[i];
9
+ out += HEX[byte >> 4] + HEX[byte & 15];
10
+ }
11
+ return out;
12
+ }
13
+ function sameBytes(a, b) {
14
+ if (a.length !== b.length)
15
+ return false;
16
+ for (let i = 0; i < a.length; i++)
17
+ if (a[i] !== b[i])
18
+ return false;
19
+ return true;
20
+ }
21
+ /** The leaf at node index `nodeIndex` of `tree`, or `undefined` when blank, a parent node, or out of range. */
22
+ function leafAt(tree, nodeIndex) {
23
+ const node = tree[nodeIndex];
24
+ if (node === undefined || node === null || node.nodeType !== nodeTypes.leaf)
25
+ return undefined;
26
+ const leaf = node.leaf;
27
+ return typeof leaf === "object" && leaf !== null ? leaf : undefined;
28
+ }
29
+ /** The hex account pubkey of `leaf`'s basic credential, or `undefined` when it has none (non-basic or malformed). */
30
+ function accountOf(leaf) {
31
+ try {
32
+ if (leaf.credential.credentialType !== defaultCredentialTypes.basic)
33
+ return undefined;
34
+ return getCredentialPubkey(leaf.credential);
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /**
41
+ * The signature-key successions between `parent` and `child`, ordered by leaf
42
+ * index: one entry for every leaf index occupied in both states by the same
43
+ * account whose signature key differs and whose child leaf has source `commit`
44
+ * or `update` (see the module header). Precondition: `child` is exactly one
45
+ * commit after `parent`; over a longer gap the result is NOT guaranteed (a Remove
46
+ * plus re-Add followed by a self-update reads as a rotation).
47
+ *
48
+ * Pure and total: never throws. Totality is per leaf, not per state: a leaf
49
+ * that cannot be read (missing or non-byte `signaturePublicKey`, non-basic or
50
+ * undecodable credential, unknown source) contributes no entry and leaves the
51
+ * other indices' verdicts untouched, so a malformed leaf never erases a
52
+ * genuine rotation elsewhere. This is deliberately NOT the whole-state `[]`
53
+ * reading: under ADR-017 R-1 an empty `succ(x)` would turn every other
54
+ * rotation on the edge into a positive removal fact, whereas R-1's fail-closed
55
+ * value is *absent*, which the removal-fact producer derives on its own when a
56
+ * leaf is unreadable. Only a state that is not a tree at all yields `[]`. Real
57
+ * ts-mls states cannot hold such leaves (`signaturePublicKey` is a required
58
+ * decoded `Uint8Array`); the guard exists for arbitrary input (AC-SUCC-4).
59
+ */
60
+ export function leafKeySuccessions(parent, child) {
61
+ const out = [];
62
+ try {
63
+ const width = Math.min(parent.ratchetTree.length, child.ratchetTree.length);
64
+ for (let nodeIndex = 0; nodeIndex < width; nodeIndex += 2) {
65
+ const before = leafAt(parent.ratchetTree, nodeIndex);
66
+ const after = leafAt(child.ratchetTree, nodeIndex);
67
+ if (before === undefined || after === undefined)
68
+ continue;
69
+ const source = after.leafNodeSource === leafNodeSources.commit
70
+ ? "commit"
71
+ : after.leafNodeSource === leafNodeSources.update
72
+ ? "update"
73
+ : undefined;
74
+ if (source === undefined)
75
+ continue;
76
+ if (!(before.signaturePublicKey instanceof Uint8Array) || !(after.signaturePublicKey instanceof Uint8Array))
77
+ continue;
78
+ if (sameBytes(before.signaturePublicKey, after.signaturePublicKey))
79
+ continue;
80
+ const account = accountOf(before);
81
+ if (account === undefined || account !== accountOf(after))
82
+ continue;
83
+ out.push({
84
+ leafIndex: nodeIndex / 2,
85
+ account,
86
+ fromKey: toHex(before.signaturePublicKey),
87
+ toKey: toHex(after.signaturePublicKey),
88
+ source,
89
+ });
90
+ }
91
+ }
92
+ catch {
93
+ // A state that is not a well-formed tree has no successions (total: never throws).
94
+ return [];
95
+ }
96
+ return out;
97
+ }
@@ -0,0 +1,34 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Canonicalizes a MIME type for use in `encrypted-media-v1` cryptographic
4
+ * operations (key derivation and AEAD AAD).
5
+ *
6
+ * Sender and receiver MUST apply this identical algorithm
7
+ * (`features/encrypted-media.md` — Media Type Canonicalization):
8
+ *
9
+ * 1. take the substring before the first `;`, dropping any parameters
10
+ * 2. trim leading and trailing ASCII whitespace
11
+ * 3. lowercase using ASCII case folding only
12
+ * 4. reject if the result is empty or does not contain `/`
13
+ * 5. apply the canonical alias `image/jpg` → `image/jpeg`
14
+ *
15
+ * Adding an alias or normalization step is a breaking media-version change.
16
+ *
17
+ * @param mimeType - The raw MIME type string
18
+ * @returns The canonical MIME type
19
+ * @throws If the canonical result is empty or has no `/`
20
+ */
21
+ export declare function canonicalizeMimeType(mimeType: string): string;
22
+ /**
23
+ * Returns `true` iff {@link canonicalizeMimeType} accepts `value` (it is a
24
+ * non-empty `type/subtype` string).
25
+ *
26
+ * @internal
27
+ */
28
+ export declare function isValidMimeType(value: string): boolean;
29
+ /**
30
+ * Returns true iff `value` is valid hex with the expected encoded byte length.
31
+ *
32
+ * @internal
33
+ */
34
+ export declare function isValidHex(value: string, expectedBytes: number): boolean;
@@ -0,0 +1,57 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Canonicalizes a MIME type for use in `encrypted-media-v1` cryptographic
4
+ * operations (key derivation and AEAD AAD).
5
+ *
6
+ * Sender and receiver MUST apply this identical algorithm
7
+ * (`features/encrypted-media.md` — Media Type Canonicalization):
8
+ *
9
+ * 1. take the substring before the first `;`, dropping any parameters
10
+ * 2. trim leading and trailing ASCII whitespace
11
+ * 3. lowercase using ASCII case folding only
12
+ * 4. reject if the result is empty or does not contain `/`
13
+ * 5. apply the canonical alias `image/jpg` → `image/jpeg`
14
+ *
15
+ * Adding an alias or normalization step is a breaking media-version change.
16
+ *
17
+ * @param mimeType - The raw MIME type string
18
+ * @returns The canonical MIME type
19
+ * @throws If the canonical result is empty or has no `/`
20
+ */
21
+ export function canonicalizeMimeType(mimeType) {
22
+ // Steps 1–3: strip parameters, trim, ASCII-lowercase.
23
+ const base = mimeType
24
+ .split(";")[0]
25
+ .trim()
26
+ .replace(/[A-Z]/g, (c) => c.toLowerCase());
27
+ // Step 4: reject empty or `/`-less results.
28
+ const slash = base.indexOf("/");
29
+ if (slash <= 0 || slash >= base.length - 1) {
30
+ throw new Error(`invalid media type: ${JSON.stringify(mimeType)}`);
31
+ }
32
+ // Step 5: canonical alias.
33
+ return base === "image/jpg" ? "image/jpeg" : base;
34
+ }
35
+ /**
36
+ * Returns `true` iff {@link canonicalizeMimeType} accepts `value` (it is a
37
+ * non-empty `type/subtype` string).
38
+ *
39
+ * @internal
40
+ */
41
+ export function isValidMimeType(value) {
42
+ try {
43
+ canonicalizeMimeType(value);
44
+ return true;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /**
51
+ * Returns true iff `value` is valid hex with the expected encoded byte length.
52
+ *
53
+ * @internal
54
+ */
55
+ export function isValidHex(value, expectedBytes) {
56
+ return value.length === expectedBytes * 2 && /^[0-9a-f]+$/.test(value);
57
+ }
@@ -0,0 +1,79 @@
1
+ import { type CiphersuiteImpl, type ClientState } from "ts-mls";
2
+ import { type EncryptMediaFileResult, type MediaAttachment } from "./types.js";
3
+ /** The crypto-relevant subset of a {@link MediaAttachment}. */
4
+ export type MediaCryptoFields = Pick<MediaAttachment, "plaintextSha256" | "mediaType" | "filename">;
5
+ /**
6
+ * Derives the per-file encryption key for an `encrypted-media-v1` attachment.
7
+ *
8
+ * ```
9
+ * media_secret = MLS-Exporter("marmot", "encrypted-media", 32) at source_epoch
10
+ * file_key = HKDF-Expand(media_secret,
11
+ * "encrypted-media-v1" || 0x00 || plaintext_sha256_bytes ||
12
+ * 0x00 || media_type || 0x00 || filename || 0x00 || "key", 32)
13
+ * ```
14
+ *
15
+ * HKDF is HKDF-SHA256 with `media_secret` used directly as the PRK (Expand
16
+ * only, no Extract). The key is deterministic for a given source epoch + file.
17
+ *
18
+ * The source epoch is the MLS epoch of the application message that carried the
19
+ * attachment. The caller MUST pass the `ClientState` for that epoch: on send,
20
+ * the current state; on receive, the retained state for the message's source
21
+ * epoch (see `features/encrypted-media.md` — Key Derivation).
22
+ *
23
+ * @param clientState - The MLS `ClientState` for the attachment's source epoch
24
+ * @param ciphersuite - The ciphersuite implementation used by the group
25
+ * @param attachment - Provides `plaintextSha256`, `mediaType`, and `filename`
26
+ * @returns 32-byte ChaCha20-Poly1305 encryption key
27
+ */
28
+ export declare function deriveMediaEncryptionKey(clientState: ClientState, ciphersuite: CiphersuiteImpl, attachment: MediaCryptoFields): Promise<Uint8Array>;
29
+ /**
30
+ * Encrypts a media file for an `encrypted-media-v1` attachment.
31
+ *
32
+ * Uses ChaCha20-Poly1305 AEAD with a random 12-byte nonce. The AAD binds the
33
+ * scheme version, plaintext hash, canonical MIME type, and filename. Computes
34
+ * `ciphertextSha256 = SHA256(encrypted)` and returns a {@link MediaAttachment}
35
+ * with `locators` left empty for the caller to fill after upload.
36
+ *
37
+ * @param file - The plaintext file bytes to encrypt
38
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
39
+ * @param fields - Provides `plaintextSha256`, `mediaType`, and `filename`;
40
+ * optional `dim`/`thumbhash` are carried through onto the result
41
+ * @returns Encrypted blob and a populated {@link MediaAttachment}
42
+ */
43
+ export declare function encryptMediaFile(file: Uint8Array, fileKey: Uint8Array, fields: MediaCryptoFields & Pick<Partial<MediaAttachment>, "dim" | "thumbhash">): EncryptMediaFileResult;
44
+ /**
45
+ * Decrypts a fetched `encrypted-media-v1` blob.
46
+ *
47
+ * Performs the receive-side integrity checks in order
48
+ * (`features/encrypted-media.md` — Validation):
49
+ *
50
+ * 1. the fetched bytes match `ciphertextSha256`
51
+ * 2. ChaCha20-Poly1305 authentication succeeds
52
+ * 3. the decrypted bytes match `plaintextSha256`
53
+ *
54
+ * @param encrypted - The encrypted blob downloaded from a blob store
55
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
56
+ * @param attachment - The parsed attachment from the message's `imeta` tag
57
+ * @returns The decrypted file bytes
58
+ * @throws If any integrity check fails or required fields are missing
59
+ */
60
+ export declare function decryptMediaFile(encrypted: Uint8Array, fileKey: Uint8Array, attachment: MediaAttachment): Uint8Array;
61
+ /**
62
+ * Decrypts a fetched `encrypted-media-v1` blob, trying each candidate key in
63
+ * order until one authenticates the ciphertext.
64
+ *
65
+ * The media file key is derived from the source-epoch media exporter secret
66
+ * (`features/encrypted-media.md` — Key Derivation), but the source epoch is not
67
+ * carried in the `imeta` tag. Rather than thread the source epoch through every
68
+ * caller, the receiver supplies one key per still-retained epoch (current epoch
69
+ * first) and relies on the AEAD tag to identify the right one. The ciphertext
70
+ * hash is verified once; only the cheap AEAD open is retried per key.
71
+ *
72
+ * @param encrypted - The encrypted blob downloaded from a blob store
73
+ * @param fileKeys - Candidate keys from {@link deriveMediaEncryptionKey}, one
74
+ * per retained epoch; tried in order. MUST be non-empty.
75
+ * @param attachment - The parsed attachment from the message's `imeta` tag
76
+ * @returns The decrypted file bytes from the first key that authenticates
77
+ * @throws If no candidate key authenticates the ciphertext, or a check fails
78
+ */
79
+ export declare function decryptMediaFileWithKeys(encrypted: Uint8Array, fileKeys: Uint8Array[], attachment: MediaAttachment): Uint8Array;
@@ -0,0 +1,215 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
3
+ import { equalBytes } from "@noble/ciphers/utils.js";
4
+ import { expand as hkdf_expand } from "@noble/hashes/hkdf.js";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { bytesToHex, concatBytes, hexToBytes, randomBytes, } from "@noble/hashes/utils.js";
7
+ import { mlsExporter } from "ts-mls";
8
+ import { canonicalizeMimeType } from "./canonical.js";
9
+ import { ENCRYPTED_MEDIA_VERSION, } from "./types.js";
10
+ const enc = new TextEncoder();
11
+ /** Scheme label used in all `encrypted-media-v1` cryptographic contexts. */
12
+ const SCHEME = enc.encode(ENCRYPTED_MEDIA_VERSION);
13
+ const SEP = new Uint8Array([0x00]);
14
+ /** MLS exporter label and context used to obtain the base media secret. */
15
+ const MLS_EXPORTER_LABEL = "marmot";
16
+ const MLS_EXPORTER_CONTEXT = enc.encode("encrypted-media");
17
+ /**
18
+ * Builds the `0x00`-separated field block shared by the key-derivation context
19
+ * and the AEAD AAD: `plaintext_sha256_bytes || 0x00 || media_type || 0x00 ||
20
+ * filename`. The MIME type is canonicalized; no length prefixes are used.
21
+ *
22
+ * @internal
23
+ */
24
+ function mediaFieldBlock(fields) {
25
+ if (!fields.plaintextSha256)
26
+ throw new Error("attachment.plaintextSha256 is required");
27
+ if (!fields.mediaType)
28
+ throw new Error("attachment.mediaType is required");
29
+ const plaintextHashBytes = hexToBytes(fields.plaintextSha256);
30
+ const canonicalMime = enc.encode(canonicalizeMimeType(fields.mediaType));
31
+ const filenameBytes = enc.encode(fields.filename);
32
+ return concatBytes(plaintextHashBytes, SEP, canonicalMime, SEP, filenameBytes);
33
+ }
34
+ /**
35
+ * Builds the ChaCha20-Poly1305 AAD for `encrypted-media-v1`:
36
+ * `"encrypted-media-v1" || 0x00 || plaintext_sha256_bytes || 0x00 ||
37
+ * media_type || 0x00 || filename`.
38
+ *
39
+ * @internal
40
+ */
41
+ function buildAad(fields) {
42
+ return concatBytes(SCHEME, SEP, mediaFieldBlock(fields));
43
+ }
44
+ /**
45
+ * Derives the per-file encryption key for an `encrypted-media-v1` attachment.
46
+ *
47
+ * ```
48
+ * media_secret = MLS-Exporter("marmot", "encrypted-media", 32) at source_epoch
49
+ * file_key = HKDF-Expand(media_secret,
50
+ * "encrypted-media-v1" || 0x00 || plaintext_sha256_bytes ||
51
+ * 0x00 || media_type || 0x00 || filename || 0x00 || "key", 32)
52
+ * ```
53
+ *
54
+ * HKDF is HKDF-SHA256 with `media_secret` used directly as the PRK (Expand
55
+ * only, no Extract). The key is deterministic for a given source epoch + file.
56
+ *
57
+ * The source epoch is the MLS epoch of the application message that carried the
58
+ * attachment. The caller MUST pass the `ClientState` for that epoch: on send,
59
+ * the current state; on receive, the retained state for the message's source
60
+ * epoch (see `features/encrypted-media.md` — Key Derivation).
61
+ *
62
+ * @param clientState - The MLS `ClientState` for the attachment's source epoch
63
+ * @param ciphersuite - The ciphersuite implementation used by the group
64
+ * @param attachment - Provides `plaintextSha256`, `mediaType`, and `filename`
65
+ * @returns 32-byte ChaCha20-Poly1305 encryption key
66
+ */
67
+ export async function deriveMediaEncryptionKey(clientState, ciphersuite, attachment) {
68
+ const mediaSecret = await mlsExporter(clientState.keySchedule.exporterSecret, MLS_EXPORTER_LABEL, MLS_EXPORTER_CONTEXT, 32, ciphersuite);
69
+ // info = scheme || 0x00 || plaintext_sha256 || 0x00 || media_type || 0x00 ||
70
+ // filename || 0x00 || "key"
71
+ const info = concatBytes(SCHEME, SEP, mediaFieldBlock(attachment), SEP, enc.encode("key"));
72
+ return hkdf_expand(sha256, mediaSecret, info, 32);
73
+ }
74
+ /**
75
+ * Encrypts a media file for an `encrypted-media-v1` attachment.
76
+ *
77
+ * Uses ChaCha20-Poly1305 AEAD with a random 12-byte nonce. The AAD binds the
78
+ * scheme version, plaintext hash, canonical MIME type, and filename. Computes
79
+ * `ciphertextSha256 = SHA256(encrypted)` and returns a {@link MediaAttachment}
80
+ * with `locators` left empty for the caller to fill after upload.
81
+ *
82
+ * @param file - The plaintext file bytes to encrypt
83
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
84
+ * @param fields - Provides `plaintextSha256`, `mediaType`, and `filename`;
85
+ * optional `dim`/`thumbhash` are carried through onto the result
86
+ * @returns Encrypted blob and a populated {@link MediaAttachment}
87
+ */
88
+ export function encryptMediaFile(file, fileKey, fields) {
89
+ if (!fields.plaintextSha256)
90
+ throw new Error("attachment.plaintextSha256 is required");
91
+ if (!fields.mediaType)
92
+ throw new Error("attachment.mediaType is required");
93
+ const mediaType = canonicalizeMimeType(fields.mediaType);
94
+ const nonce = randomBytes(12);
95
+ const aad = buildAad({ ...fields, mediaType });
96
+ const encrypted = chacha20poly1305(fileKey, nonce, aad).encrypt(file);
97
+ const attachment = {
98
+ version: ENCRYPTED_MEDIA_VERSION,
99
+ locators: [],
100
+ ciphertextSha256: bytesToHex(sha256(encrypted)),
101
+ plaintextSha256: fields.plaintextSha256,
102
+ nonce: bytesToHex(nonce),
103
+ mediaType,
104
+ filename: fields.filename,
105
+ ...(fields.dim !== undefined ? { dim: fields.dim } : {}),
106
+ ...(fields.thumbhash !== undefined ? { thumbhash: fields.thumbhash } : {}),
107
+ };
108
+ return { encrypted, attachment };
109
+ }
110
+ /**
111
+ * Validates the receive-side fields, decodes the nonce, and verifies the
112
+ * fetched bytes match `ciphertextSha256` — the key-independent checks shared by
113
+ * the single-key and multi-key decrypt paths.
114
+ *
115
+ * @internal
116
+ * @returns The decoded 12-byte nonce and the AEAD AAD
117
+ */
118
+ function prepareMediaDecrypt(encrypted, attachment) {
119
+ if (!attachment.plaintextSha256)
120
+ throw new Error("attachment.plaintextSha256 is required");
121
+ if (!attachment.ciphertextSha256)
122
+ throw new Error("attachment.ciphertextSha256 is required");
123
+ if (!attachment.mediaType)
124
+ throw new Error("attachment.mediaType is required");
125
+ if (!attachment.nonce)
126
+ throw new Error("attachment.nonce is required");
127
+ const nonce = hexToBytes(attachment.nonce);
128
+ if (nonce.length !== 12) {
129
+ throw new Error(`attachment.nonce must be 24 hex characters (12 bytes), got ${attachment.nonce.length} characters`);
130
+ }
131
+ // Ciphertext integrity: fetched bytes MUST match ciphertext_sha256. This is
132
+ // key-independent, so it runs once even when multiple candidate keys follow.
133
+ if (!equalBytes(sha256(encrypted), hexToBytes(attachment.ciphertextSha256))) {
134
+ throw new Error("encrypted-media-v1 integrity check failed: ciphertext hash does not match ciphertext_sha256");
135
+ }
136
+ return { nonce, aad: buildAad(attachment) };
137
+ }
138
+ /**
139
+ * AEAD-opens a verified `encrypted-media-v1` blob with one candidate key and
140
+ * checks the plaintext hash. Returns the plaintext on success, or `undefined`
141
+ * when the key fails authentication (the caller may try another epoch's key).
142
+ * A successful AEAD open whose plaintext hash mismatches is a genuine integrity
143
+ * failure and throws.
144
+ *
145
+ * @internal
146
+ */
147
+ function openMediaFile(encrypted, fileKey, nonce, aad, plaintextSha256) {
148
+ let decrypted;
149
+ try {
150
+ decrypted = chacha20poly1305(fileKey, nonce, aad).decrypt(encrypted);
151
+ }
152
+ catch {
153
+ // ChaCha20-Poly1305 authentication failed — wrong key for this ciphertext.
154
+ return undefined;
155
+ }
156
+ // The AEAD tag authenticated, so this is the right key; the plaintext hash
157
+ // MUST match. A mismatch here is corruption, not a wrong-key signal.
158
+ if (!equalBytes(sha256(decrypted), hexToBytes(plaintextSha256))) {
159
+ throw new Error("encrypted-media-v1 integrity check failed: plaintext hash does not match plaintext_sha256");
160
+ }
161
+ return decrypted;
162
+ }
163
+ /**
164
+ * Decrypts a fetched `encrypted-media-v1` blob.
165
+ *
166
+ * Performs the receive-side integrity checks in order
167
+ * (`features/encrypted-media.md` — Validation):
168
+ *
169
+ * 1. the fetched bytes match `ciphertextSha256`
170
+ * 2. ChaCha20-Poly1305 authentication succeeds
171
+ * 3. the decrypted bytes match `plaintextSha256`
172
+ *
173
+ * @param encrypted - The encrypted blob downloaded from a blob store
174
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
175
+ * @param attachment - The parsed attachment from the message's `imeta` tag
176
+ * @returns The decrypted file bytes
177
+ * @throws If any integrity check fails or required fields are missing
178
+ */
179
+ export function decryptMediaFile(encrypted, fileKey, attachment) {
180
+ const { nonce, aad } = prepareMediaDecrypt(encrypted, attachment);
181
+ const decrypted = openMediaFile(encrypted, fileKey, nonce, aad, attachment.plaintextSha256);
182
+ if (!decrypted) {
183
+ throw new Error("encrypted-media-v1 decryption failed: ciphertext did not authenticate under the supplied key");
184
+ }
185
+ return decrypted;
186
+ }
187
+ /**
188
+ * Decrypts a fetched `encrypted-media-v1` blob, trying each candidate key in
189
+ * order until one authenticates the ciphertext.
190
+ *
191
+ * The media file key is derived from the source-epoch media exporter secret
192
+ * (`features/encrypted-media.md` — Key Derivation), but the source epoch is not
193
+ * carried in the `imeta` tag. Rather than thread the source epoch through every
194
+ * caller, the receiver supplies one key per still-retained epoch (current epoch
195
+ * first) and relies on the AEAD tag to identify the right one. The ciphertext
196
+ * hash is verified once; only the cheap AEAD open is retried per key.
197
+ *
198
+ * @param encrypted - The encrypted blob downloaded from a blob store
199
+ * @param fileKeys - Candidate keys from {@link deriveMediaEncryptionKey}, one
200
+ * per retained epoch; tried in order. MUST be non-empty.
201
+ * @param attachment - The parsed attachment from the message's `imeta` tag
202
+ * @returns The decrypted file bytes from the first key that authenticates
203
+ * @throws If no candidate key authenticates the ciphertext, or a check fails
204
+ */
205
+ export function decryptMediaFileWithKeys(encrypted, fileKeys, attachment) {
206
+ if (fileKeys.length === 0)
207
+ throw new Error("decryptMediaFileWithKeys: at least one key is required");
208
+ const { nonce, aad } = prepareMediaDecrypt(encrypted, attachment);
209
+ for (const fileKey of fileKeys) {
210
+ const decrypted = openMediaFile(encrypted, fileKey, nonce, aad, attachment.plaintextSha256);
211
+ if (decrypted)
212
+ return decrypted;
213
+ }
214
+ throw new Error("encrypted-media-v1 decryption failed: ciphertext did not authenticate under any retained epoch key");
215
+ }
@@ -0,0 +1,33 @@
1
+ import { type MediaAttachment } from "./types.js";
2
+ /**
3
+ * Serializes a {@link MediaAttachment} into an `encrypted-media-v1` `imeta`
4
+ * tag array (`features/encrypted-media.md` — Message Shape).
5
+ *
6
+ * Field order follows the spec: `v`, `locator`…, `ciphertext_sha256`,
7
+ * `plaintext_sha256`, `nonce`, `m`, `filename`, optional `dim`, optional
8
+ * `thumbhash`. The attachment MUST carry at least one locator.
9
+ *
10
+ * @param attachment - A populated attachment (locators filled in after upload)
11
+ * @returns A Nostr tag array beginning with `"imeta"`
12
+ */
13
+ export declare function encodeMediaImetaTag(attachment: MediaAttachment): string[];
14
+ /**
15
+ * Parses an `imeta` tag into a {@link MediaAttachment}, or returns `null` if the
16
+ * tag is not a valid `encrypted-media-v1` attachment.
17
+ *
18
+ * A `null` result means the media reference is invalid and MUST be dropped (the
19
+ * containing message should be dropped too for a host-safety failure). See
20
+ * {@link decodeMediaImetaTag} for the exact conditions.
21
+ *
22
+ * @param tag - A raw `imeta` tag array from a Nostr event
23
+ */
24
+ export declare function parseMediaImetaTag(tag: string[]): MediaAttachment | null;
25
+ /**
26
+ * Extracts all valid `encrypted-media-v1` attachments from a tag list.
27
+ *
28
+ * Non-`imeta` tags and `imeta` tags that fail validation are skipped.
29
+ *
30
+ * @param tags - The `tags` array from a Nostr event or rumor
31
+ * @returns Array of valid {@link MediaAttachment} objects (may be empty)
32
+ */
33
+ export declare function getMediaAttachments(tags: string[][]): MediaAttachment[];