@941design/marmot-engine 0.0.0-stage → 0.2.0-alpha.1
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.
- package/CHANGELOG.md +477 -0
- package/LICENSE +53 -0
- package/README.md +33 -2
- package/dist/audit/emitter.d.ts +17 -0
- package/dist/audit/emitter.js +30 -0
- package/dist/audit/helpers.d.ts +16 -0
- package/dist/audit/helpers.js +103 -0
- package/dist/audit/index.d.ts +6 -0
- package/dist/audit/index.js +6 -0
- package/dist/audit/recorder.d.ts +13 -0
- package/dist/audit/recorder.js +24 -0
- package/dist/audit/sink.d.ts +16 -0
- package/dist/audit/sink.js +27 -0
- package/dist/audit/types-internal.d.ts +7 -0
- package/dist/audit/types-internal.js +1 -0
- package/dist/audit/types.d.ts +289 -0
- package/dist/audit/types.js +2 -0
- package/dist/core/account-identity-proof.d.ts +165 -0
- package/dist/core/account-identity-proof.js +277 -0
- package/dist/core/application-rumor.d.ts +45 -0
- package/dist/core/application-rumor.js +120 -0
- package/dist/core/auth-service.d.ts +2 -0
- package/dist/core/auth-service.js +52 -0
- package/dist/core/binary.d.ts +142 -0
- package/dist/core/binary.js +363 -0
- package/dist/core/capabilities.d.ts +51 -0
- package/dist/core/capabilities.js +102 -0
- package/dist/core/client-state.d.ts +119 -0
- package/dist/core/client-state.js +226 -0
- package/dist/core/commit-authorization.d.ts +26 -0
- package/dist/core/commit-authorization.js +26 -0
- package/dist/core/components/admin-policy.d.ts +4 -0
- package/dist/core/components/admin-policy.js +69 -0
- package/dist/core/components/agent-text-stream.d.ts +51 -0
- package/dist/core/components/agent-text-stream.js +112 -0
- package/dist/core/components/app-components-list.d.ts +17 -0
- package/dist/core/components/app-components-list.js +35 -0
- package/dist/core/components/avatar-url.d.ts +12 -0
- package/dist/core/components/avatar-url.js +85 -0
- package/dist/core/components/bytes.d.ts +5 -0
- package/dist/core/components/bytes.js +18 -0
- package/dist/core/components/dictionary.d.ts +80 -0
- package/dist/core/components/dictionary.js +175 -0
- package/dist/core/components/disband-validation.d.ts +21 -0
- package/dist/core/components/disband-validation.js +173 -0
- package/dist/core/components/encrypted-media.d.ts +44 -0
- package/dist/core/components/encrypted-media.js +210 -0
- package/dist/core/components/group-lifecycle.d.ts +10 -0
- package/dist/core/components/group-lifecycle.js +32 -0
- package/dist/core/components/group-profile.d.ts +24 -0
- package/dist/core/components/group-profile.js +35 -0
- package/dist/core/components/host-safety.d.ts +9 -0
- package/dist/core/components/host-safety.js +148 -0
- package/dist/core/components/ids.d.ts +93 -0
- package/dist/core/components/ids.js +92 -0
- package/dist/core/components/index.d.ts +14 -0
- package/dist/core/components/index.js +14 -0
- package/dist/core/components/integrity.d.ts +141 -0
- package/dist/core/components/integrity.js +293 -0
- package/dist/core/components/message-retention.d.ts +17 -0
- package/dist/core/components/message-retention.js +26 -0
- package/dist/core/components/nostr-routing.d.ts +8 -0
- package/dist/core/components/nostr-routing.js +92 -0
- package/dist/core/components/url.d.ts +26 -0
- package/dist/core/components/url.js +44 -0
- package/dist/core/convergence-status.d.ts +84 -0
- package/dist/core/convergence-status.js +82 -0
- package/dist/core/convergence.d.ts +567 -0
- package/dist/core/convergence.js +1150 -0
- package/dist/core/credential.d.ts +16 -0
- package/dist/core/credential.js +64 -0
- package/dist/core/default-capabilities.d.ts +9 -0
- package/dist/core/default-capabilities.js +34 -0
- package/dist/core/extensions.d.ts +9 -0
- package/dist/core/extensions.js +5 -0
- package/dist/core/grease.d.ts +2 -0
- package/dist/core/grease.js +6 -0
- package/dist/core/group-event.d.ts +18 -0
- package/dist/core/group-event.js +30 -0
- package/dist/core/group-lifecycle.d.ts +42 -0
- package/dist/core/group-lifecycle.js +66 -0
- package/dist/core/group-members.d.ts +37 -0
- package/dist/core/group-members.js +99 -0
- package/dist/core/group-message-classify.d.ts +42 -0
- package/dist/core/group-message-classify.js +57 -0
- package/dist/core/group-message-crypto.d.ts +53 -0
- package/dist/core/group-message-crypto.js +140 -0
- package/dist/core/group-message.d.ts +5 -0
- package/dist/core/group-message.js +11 -0
- package/dist/core/group.d.ts +56 -0
- package/dist/core/group.js +95 -0
- package/dist/core/inbound.d.ts +102 -0
- package/dist/core/inbound.js +79 -0
- package/dist/core/index.d.ts +29 -0
- package/dist/core/index.js +27 -0
- package/dist/core/key-package-eligibility.d.ts +31 -0
- package/dist/core/key-package-eligibility.js +116 -0
- package/dist/core/key-package-event-decode.d.ts +43 -0
- package/dist/core/key-package-event-decode.js +118 -0
- package/dist/core/key-package-event-delete.d.ts +16 -0
- package/dist/core/key-package-event-delete.js +46 -0
- package/dist/core/key-package-event-encode.d.ts +28 -0
- package/dist/core/key-package-event-encode.js +117 -0
- package/dist/core/key-package-event.d.ts +4 -0
- package/dist/core/key-package-event.js +8 -0
- package/dist/core/key-package.d.ts +66 -0
- package/dist/core/key-package.js +147 -0
- package/dist/core/leaf-succession.d.ts +83 -0
- package/dist/core/leaf-succession.js +97 -0
- package/dist/core/media/canonical.d.ts +34 -0
- package/dist/core/media/canonical.js +57 -0
- package/dist/core/media/crypto.d.ts +79 -0
- package/dist/core/media/crypto.js +215 -0
- package/dist/core/media/imeta.d.ts +33 -0
- package/dist/core/media/imeta.js +188 -0
- package/dist/core/media/locator.d.ts +44 -0
- package/dist/core/media/locator.js +69 -0
- package/dist/core/media/types.d.ts +83 -0
- package/dist/core/media/types.js +12 -0
- package/dist/core/media.d.ts +6 -0
- package/dist/core/media.js +12 -0
- package/dist/core/protocol-profile.d.ts +262 -0
- package/dist/core/protocol-profile.js +535 -0
- package/dist/core/protocol.d.ts +51 -0
- package/dist/core/protocol.js +41 -0
- package/dist/core/relay-lists.d.ts +52 -0
- package/dist/core/relay-lists.js +86 -0
- package/dist/core/retained-history.d.ts +78 -0
- package/dist/core/retained-history.js +59 -0
- package/dist/core/transport.d.ts +43 -0
- package/dist/core/transport.js +21 -0
- package/dist/core/welcome-event.d.ts +61 -0
- package/dist/core/welcome-event.js +116 -0
- package/dist/core/welcome-join.d.ts +155 -0
- package/dist/core/welcome-join.js +243 -0
- package/dist/core/welcome.d.ts +3 -0
- package/dist/core/welcome.js +6 -0
- package/dist/engine/admin-policy.d.ts +75 -0
- package/dist/engine/admin-policy.js +137 -0
- package/dist/engine/auto-committer.d.ts +39 -0
- package/dist/engine/auto-committer.js +42 -0
- package/dist/engine/delivered-payloads.d.ts +61 -0
- package/dist/engine/delivered-payloads.js +84 -0
- package/dist/engine/disband-request.d.ts +41 -0
- package/dist/engine/disband-request.js +86 -0
- package/dist/engine/disband-tombstone.d.ts +14 -0
- package/dist/engine/disband-tombstone.js +66 -0
- package/dist/engine/fork-recovery.d.ts +672 -0
- package/dist/engine/fork-recovery.js +1615 -0
- package/dist/engine/group-engine.d.ts +571 -0
- package/dist/engine/group-engine.js +5134 -0
- package/dist/engine/history-tree.d.ts +232 -0
- package/dist/engine/history-tree.js +651 -0
- package/dist/engine/index.d.ts +16 -0
- package/dist/engine/index.js +15 -0
- package/dist/engine/ingest-disposition.d.ts +5 -0
- package/dist/engine/ingest-disposition.js +63 -0
- package/dist/engine/ingest.d.ts +390 -0
- package/dist/engine/ingest.js +1258 -0
- package/dist/engine/ingestion-pool.d.ts +74 -0
- package/dist/engine/ingestion-pool.js +95 -0
- package/dist/engine/message-dedup.d.ts +16 -0
- package/dist/engine/message-dedup.js +20 -0
- package/dist/engine/own-commit-stamp.d.ts +30 -0
- package/dist/engine/own-commit-stamp.js +71 -0
- package/dist/engine/retained-store.d.ts +79 -0
- package/dist/engine/retained-store.js +133 -0
- package/dist/engine/sender-ratchet.d.ts +50 -0
- package/dist/engine/sender-ratchet.js +196 -0
- package/dist/engine/state-notifications.d.ts +122 -0
- package/dist/engine/state-notifications.js +173 -0
- package/dist/engine/tree-convergence.d.ts +41 -0
- package/dist/engine/tree-convergence.js +90 -0
- package/dist/engine/types.d.ts +366 -0
- package/dist/engine/types.js +14 -0
- package/dist/engine/wire-format.d.ts +77 -0
- package/dist/engine/wire-format.js +120 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -0
- package/dist/mls.d.ts +11 -0
- package/dist/mls.js +11 -0
- package/dist/utils/debug.d.ts +3 -0
- package/dist/utils/debug.js +3 -0
- package/dist/utils/encoding.d.ts +38 -0
- package/dist/utils/encoding.js +91 -0
- package/dist/utils/key-value.d.ts +18 -0
- package/dist/utils/key-value.js +2 -0
- package/dist/utils/nostr.d.ts +35 -0
- package/dist/utils/nostr.js +26 -0
- package/dist/utils/relay-url.d.ts +10 -0
- package/dist/utils/relay-url.js +23 -0
- package/dist/utils/tag-cardinality.d.ts +50 -0
- package/dist/utils/tag-cardinality.js +91 -0
- package/dist/utils/timestamp.d.ts +50 -0
- package/dist/utils/timestamp.js +95 -0
- package/dist/version.d.ts +112 -0
- package/dist/version.js +112 -0
- package/package.json +68 -3
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** @module @category Core - Key Package */
|
|
2
|
+
import { defaultCredentialTypes, defaultCryptoProvider, getAppDataDictionary, generateKeyPackage as MLSGenerateKeyPackage, generateKeyPackageWithKey as MLSGenerateKeyPackageWithKey, makeKeyPackageRef, } from "ts-mls";
|
|
3
|
+
import { hexToBytes } from "@noble/hashes/utils.js";
|
|
4
|
+
import { createDefaultKeyPackageLifetime, isLifetimeWithinCap, } from "../utils/timestamp.js";
|
|
5
|
+
import { buildAccountIdentityProofExtension, } from "./account-identity-proof.js";
|
|
6
|
+
import { ensureMarmotCapabilities } from "./capabilities.js";
|
|
7
|
+
import { componentEntry, LAST_RESORT_COMPONENT_ID, makeAppComponentsExtension, makeLeafAppComponentsExtension, } from "./components/index.js";
|
|
8
|
+
import { getCredentialPubkey } from "./credential.js";
|
|
9
|
+
import { defaultCapabilities } from "./default-capabilities.js";
|
|
10
|
+
import { makeCurrentLeafAppDataExtension, marmotCapabilitiesForProfile, signCurrentAccountIdentityProof, verifyCurrentAccountIdentityProofForKey, } from "./protocol-profile.js";
|
|
11
|
+
/**
|
|
12
|
+
* Ensures a KeyPackage-level extensions array carries the last-resort marker:
|
|
13
|
+
* the empty-data `0x0004` component inside the KeyPackage-level
|
|
14
|
+
* `app_data_dictionary` extension (AC-VENDOR-8 conformance patch — replaces
|
|
15
|
+
* the legacy standalone `last_resort` MLS extension, which upstream
|
|
16
|
+
* marmot-ts used before this port).
|
|
17
|
+
*/
|
|
18
|
+
function ensureLastResortComponent(extensions) {
|
|
19
|
+
const existingDictionary = getAppDataDictionary(extensions);
|
|
20
|
+
if (existingDictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID))
|
|
21
|
+
return extensions;
|
|
22
|
+
const entries = [
|
|
23
|
+
...(existingDictionary ?? []),
|
|
24
|
+
componentEntry(LAST_RESORT_COMPONENT_ID, new Uint8Array(0)),
|
|
25
|
+
];
|
|
26
|
+
const dictionaryExtension = makeAppComponentsExtension(entries);
|
|
27
|
+
const withoutOldDictionary = extensions.filter((e) => getAppDataDictionary([e]) === undefined);
|
|
28
|
+
return [...withoutOldDictionary, dictionaryExtension];
|
|
29
|
+
}
|
|
30
|
+
/** Create default extensions for a key package */
|
|
31
|
+
export function keyPackageDefaultExtensions() {
|
|
32
|
+
return ensureLastResortComponent([]);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Reads whether a KeyPackage is marked reusable ("last resort"): the
|
|
36
|
+
* empty-data `0x0004` component inside its KeyPackage-level (not
|
|
37
|
+
* LeafNode-level) `app_data_dictionary` extension (AC-VENDOR-8).
|
|
38
|
+
*
|
|
39
|
+
* Deliberately reads `keyPackage.extensions` (the `KeyPackageTBS`-level
|
|
40
|
+
* field) rather than `keyPackage.leafNode.extensions` — the same component
|
|
41
|
+
* present only in the LeafNode-level dictionary does not count.
|
|
42
|
+
*/
|
|
43
|
+
export function isLastResortKeyPackage(keyPackage) {
|
|
44
|
+
let dictionary;
|
|
45
|
+
try {
|
|
46
|
+
dictionary = getAppDataDictionary(keyPackage.extensions);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
return (dictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID) ??
|
|
52
|
+
false);
|
|
53
|
+
}
|
|
54
|
+
/** Calculates a key package reference with the hash implementation based on the key package's cipher suite */
|
|
55
|
+
export async function calculateKeyPackageRef(keyPackage, cryptoProvider) {
|
|
56
|
+
const provider = cryptoProvider ?? defaultCryptoProvider;
|
|
57
|
+
const ciphersuiteImpl = await provider.getCiphersuiteImpl(keyPackage.cipherSuite);
|
|
58
|
+
return await makeKeyPackageRef(keyPackage, ciphersuiteImpl.hash);
|
|
59
|
+
}
|
|
60
|
+
/** Generate a marmot key package that is compliant with MIP-00 */
|
|
61
|
+
export async function generateKeyPackage({ credential, capabilities, lifetime, extensions, isLastResort = true, accountProofSigner, profile = "legacy", currentProof, ciphersuiteImpl, }) {
|
|
62
|
+
if (credential.credentialType !== defaultCredentialTypes.basic)
|
|
63
|
+
throw new Error("Marmot key packages must use a basic credential");
|
|
64
|
+
// Ensure the credential has a valid pubkey
|
|
65
|
+
const accountPubkey = getCredentialPubkey(credential);
|
|
66
|
+
if (profile === "current") {
|
|
67
|
+
const provider = currentProof ??
|
|
68
|
+
(accountProofSigner !== undefined && typeof accountProofSigner !== "function"
|
|
69
|
+
? (key) => signCurrentAccountIdentityProof({ ...key, signer: accountProofSigner })
|
|
70
|
+
: undefined);
|
|
71
|
+
if (provider === undefined)
|
|
72
|
+
throw new Error("generateKeyPackage: a Current-form KeyPackage needs `currentProof` or an `accountProofSigner` with `signEvent`");
|
|
73
|
+
const lifetimeCurrent = lifetime ?? createDefaultKeyPackageLifetime();
|
|
74
|
+
if (!isLifetimeWithinCap(lifetimeCurrent))
|
|
75
|
+
throw new Error(`generateKeyPackage: lifetime range ${lifetimeCurrent.notAfter - lifetimeCurrent.notBefore}s exceeds the 7,261,200s (84-day) cap`);
|
|
76
|
+
const signatureKeyPair = await ciphersuiteImpl.signature.keygen();
|
|
77
|
+
const accountIdentity = hexToBytes(accountPubkey);
|
|
78
|
+
const proof = await provider({
|
|
79
|
+
accountIdentity,
|
|
80
|
+
mlsSignaturePublicKey: signatureKeyPair.publicKey,
|
|
81
|
+
ciphersuite: ciphersuiteImpl.id,
|
|
82
|
+
});
|
|
83
|
+
// Never mint a leaf the group would reject: the provider's proof must bind this account and this key.
|
|
84
|
+
verifyCurrentAccountIdentityProofForKey(proof, accountIdentity, signatureKeyPair.publicKey, ciphersuiteImpl.id);
|
|
85
|
+
return await MLSGenerateKeyPackageWithKey({
|
|
86
|
+
credential,
|
|
87
|
+
capabilities: marmotCapabilitiesForProfile("current", capabilities),
|
|
88
|
+
lifetime: lifetimeCurrent,
|
|
89
|
+
extensions: isLastResort
|
|
90
|
+
? ensureLastResortComponent(extensions ?? [])
|
|
91
|
+
: (extensions ?? []),
|
|
92
|
+
signatureKeyPair,
|
|
93
|
+
leafNodeExtensions: [makeCurrentLeafAppDataExtension(proof)],
|
|
94
|
+
cipherSuite: ciphersuiteImpl,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const resolvedCapabilities = capabilities
|
|
98
|
+
? ensureMarmotCapabilities(capabilities)
|
|
99
|
+
: defaultCapabilities();
|
|
100
|
+
const resolvedLifetime = lifetime ?? createDefaultKeyPackageLifetime();
|
|
101
|
+
// WIRE-01 produce path: the cap must hold regardless of how lifetime is
|
|
102
|
+
// supplied. The default is always within cap, so this check only ever
|
|
103
|
+
// rejects an explicit caller-supplied `lifetime` override (D-09).
|
|
104
|
+
if (!isLifetimeWithinCap(resolvedLifetime))
|
|
105
|
+
throw new Error(`generateKeyPackage: lifetime range ${resolvedLifetime.notAfter - resolvedLifetime.notBefore}s exceeds the 7,261,200s (84-day) cap`);
|
|
106
|
+
// Marmot requires support for last_resort capability signaling (MIP-00),
|
|
107
|
+
// but individual KeyPackages may be single-use or last-resort reusable.
|
|
108
|
+
// `isLastResort` controls whether this KeyPackage is marked reusable.
|
|
109
|
+
const resolvedExtensions = isLastResort
|
|
110
|
+
? ensureLastResortComponent(extensions ?? [])
|
|
111
|
+
: (extensions ?? []);
|
|
112
|
+
// Advertise the supported app components on the LeafNode so this member can
|
|
113
|
+
// be added to groups that require them (matches darkmatter's leaf state).
|
|
114
|
+
const leafNodeExtensions = [
|
|
115
|
+
makeLeafAppComponentsExtension(),
|
|
116
|
+
];
|
|
117
|
+
// When an account signer is supplied, generate the leaf signature keypair
|
|
118
|
+
// first, bind it to the Nostr account with an identity proof, and carry the
|
|
119
|
+
// proof on the LeafNode (darkmatter validates this on every leaf).
|
|
120
|
+
if (accountProofSigner) {
|
|
121
|
+
const signatureKeyPair = await ciphersuiteImpl.signature.keygen();
|
|
122
|
+
leafNodeExtensions.push(await buildAccountIdentityProofExtension({
|
|
123
|
+
accountIdentity: hexToBytes(accountPubkey),
|
|
124
|
+
mlsSignaturePublicKey: signatureKeyPair.publicKey,
|
|
125
|
+
ciphersuite: ciphersuiteImpl.id,
|
|
126
|
+
signer: accountProofSigner,
|
|
127
|
+
}));
|
|
128
|
+
return await MLSGenerateKeyPackageWithKey({
|
|
129
|
+
credential,
|
|
130
|
+
capabilities: resolvedCapabilities,
|
|
131
|
+
lifetime: resolvedLifetime,
|
|
132
|
+
extensions: resolvedExtensions,
|
|
133
|
+
signatureKeyPair,
|
|
134
|
+
leafNodeExtensions,
|
|
135
|
+
cipherSuite: ciphersuiteImpl,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
// In v2, generateKeyPackage takes a single params object
|
|
139
|
+
return await MLSGenerateKeyPackage({
|
|
140
|
+
credential,
|
|
141
|
+
capabilities: resolvedCapabilities,
|
|
142
|
+
lifetime: resolvedLifetime,
|
|
143
|
+
extensions: resolvedExtensions,
|
|
144
|
+
leafNodeExtensions,
|
|
145
|
+
cipherSuite: ciphersuiteImpl,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { ClientState } from "ts-mls";
|
|
2
|
+
/**
|
|
3
|
+
* Locally authored (not vendored from marmot-ts; listed in VENDOR.md's
|
|
4
|
+
* "Locally authored (not vendored)" section).
|
|
5
|
+
*
|
|
6
|
+
* Key succession: what a leaf's signature key did between two group states.
|
|
7
|
+
*
|
|
8
|
+
* A device can replace the signature key of its own leaf in a commit's UpdatePath
|
|
9
|
+
* (RFC 9420; `SendIntent.selfUpdate.leafNodePatch`) or, in principle, through a
|
|
10
|
+
* committed Update proposal. Every consumer that keys a member by its leaf signature
|
|
11
|
+
* key reads such a replacement as the leaf *disappearing*. {@link leafKeySuccessions}
|
|
12
|
+
* is the one place that tells a replacement of a key in place from a removal: a
|
|
13
|
+
* pure function of a parent and a child `ClientState`.
|
|
14
|
+
*
|
|
15
|
+
* A succession is reported for a leaf index when the leaf is occupied in both
|
|
16
|
+
* states by the same account (same basic credential identity) and carries a
|
|
17
|
+
* different signature key in the child, and the child's leaf was written by the
|
|
18
|
+
* leaf itself: its leaf node source is `commit` (the committer's UpdatePath leaf)
|
|
19
|
+
* or `update` (a committed Update proposal). A Remove plus an Add into the same
|
|
20
|
+
* index yields a `key_package` leaf and is never a succession, nor is a different
|
|
21
|
+
* account at the index, nor a blank index.
|
|
22
|
+
*
|
|
23
|
+
* Consumers:
|
|
24
|
+
* - the equivocation-credit lineage clause (ADR-016 D2 rule 4, `convergence.ts`):
|
|
25
|
+
* only the `commit` successions of the committing leaf itself along a candidate
|
|
26
|
+
* path extend which key of that leaf earns credit;
|
|
27
|
+
* - `epic-marmot-removal-finality` Design Decision 2: its key-difference evidence
|
|
28
|
+
* for "the leaf was removed" takes this predicate as the "a rotation is not a
|
|
29
|
+
* removal" exception when it ships (that epic is design only; this module is
|
|
30
|
+
* the exception it adopts);
|
|
31
|
+
* - `@941design/marmot` (`history/notifications.ts`): `removedLeaves` skips a
|
|
32
|
+
* same-account leaf at the same index iff this reports the index, and
|
|
33
|
+
* `rotatedLeaves` maps the entries to notifications.
|
|
34
|
+
*
|
|
35
|
+
* Precondition: `child` is exactly ONE commit after `parent` (the commit that
|
|
36
|
+
* produced `child` was applied to `parent`). The predicate compares two trees
|
|
37
|
+
* and cannot see what happened between them: over a gap of several commits a
|
|
38
|
+
* Remove plus re-Add of the same account at an index followed by a self-update
|
|
39
|
+
* leaves a `commit`-source leaf with a new key and reads as a rotation. Call it
|
|
40
|
+
* per edge of a window (consecutive states), never on a tip pair.
|
|
41
|
+
*
|
|
42
|
+
* Pure and total: the module imports nothing but `ts-mls` and `./credential.js`,
|
|
43
|
+
* reads no clock, random source or I/O, and never throws, whatever the trees hold
|
|
44
|
+
* (non-basic or malformed credentials, blank nodes, trees of unequal width).
|
|
45
|
+
*/
|
|
46
|
+
/** One signature-key replacement of a leaf between a parent and a child state. */
|
|
47
|
+
export interface LeafKeySuccession {
|
|
48
|
+
/** The leaf index at which the key was replaced (the same in both states). */
|
|
49
|
+
readonly leafIndex: number;
|
|
50
|
+
/** Hex account pubkey: the (unchanged) basic-credential identity of the leaf. */
|
|
51
|
+
readonly account: string;
|
|
52
|
+
/** Hex signature public key the leaf held in the parent. */
|
|
53
|
+
readonly fromKey: string;
|
|
54
|
+
/** Hex signature public key the leaf holds in the child. */
|
|
55
|
+
readonly toKey: string;
|
|
56
|
+
/**
|
|
57
|
+
* How the child's leaf came about: `commit` (the committer's UpdatePath leaf, so
|
|
58
|
+
* the committer is the leaf itself) or `update` (a committed Update proposal; the
|
|
59
|
+
* committer may be any other leaf).
|
|
60
|
+
*/
|
|
61
|
+
readonly source: "commit" | "update";
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The signature-key successions between `parent` and `child`, ordered by leaf
|
|
65
|
+
* index: one entry for every leaf index occupied in both states by the same
|
|
66
|
+
* account whose signature key differs and whose child leaf has source `commit`
|
|
67
|
+
* or `update` (see the module header). Precondition: `child` is exactly one
|
|
68
|
+
* commit after `parent`; over a longer gap the result is NOT guaranteed (a Remove
|
|
69
|
+
* plus re-Add followed by a self-update reads as a rotation).
|
|
70
|
+
*
|
|
71
|
+
* Pure and total: never throws. Totality is per leaf, not per state: a leaf
|
|
72
|
+
* that cannot be read (missing or non-byte `signaturePublicKey`, non-basic or
|
|
73
|
+
* undecodable credential, unknown source) contributes no entry and leaves the
|
|
74
|
+
* other indices' verdicts untouched, so a malformed leaf never erases a
|
|
75
|
+
* genuine rotation elsewhere. This is deliberately NOT the whole-state `[]`
|
|
76
|
+
* reading: under ADR-017 R-1 an empty `succ(x)` would turn every other
|
|
77
|
+
* rotation on the edge into a positive removal fact, whereas R-1's fail-closed
|
|
78
|
+
* value is *absent*, which the removal-fact producer derives on its own when a
|
|
79
|
+
* leaf is unreadable. Only a state that is not a tree at all yields `[]`. Real
|
|
80
|
+
* ts-mls states cannot hold such leaves (`signaturePublicKey` is a required
|
|
81
|
+
* decoded `Uint8Array`); the guard exists for arbitrary input (AC-SUCC-4).
|
|
82
|
+
*/
|
|
83
|
+
export declare function leafKeySuccessions(parent: ClientState, child: ClientState): readonly LeafKeySuccession[];
|
|
@@ -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;
|