@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,140 @@
|
|
|
1
|
+
import { decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, } from "ts-mls";
|
|
2
|
+
import { decodeContent, encodeContent } from "../utils/encoding.js";
|
|
3
|
+
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
|
|
4
|
+
import { concatBytes, randomBytes } from "@noble/ciphers/utils.js";
|
|
5
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
7
|
+
import { logger } from "../utils/debug.js";
|
|
8
|
+
/**
|
|
9
|
+
* Diagnostics logger for group-event exporter/epoch tracing.
|
|
10
|
+
* Enable with `DEBUG=marmot-ts:group-crypto` (or `marmot-ts:*`).
|
|
11
|
+
*/
|
|
12
|
+
const cryptoLog = logger.extend("group-crypto");
|
|
13
|
+
/**
|
|
14
|
+
* Returns a short, non-reversible fingerprint of the 32-byte exporter-derived
|
|
15
|
+
* key so two clients can be compared without logging the secret itself.
|
|
16
|
+
*/
|
|
17
|
+
function keyFingerprint(key) {
|
|
18
|
+
return bytesToHex(sha256(key)).slice(0, 16);
|
|
19
|
+
}
|
|
20
|
+
/** Best-effort read of the MLS epoch from a ClientState for logging. */
|
|
21
|
+
function epochOf(state) {
|
|
22
|
+
try {
|
|
23
|
+
return String(state.groupContext.epoch);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return "?";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Derives the MIP-03 group-event encryption key for a group epoch.
|
|
31
|
+
*
|
|
32
|
+
* Uses the MLS Exporter (RFC 9420 §8.5) with label "marmot" and context
|
|
33
|
+
* "group-event" to produce a 32-byte ChaCha20-Poly1305 key.
|
|
34
|
+
*/
|
|
35
|
+
async function getGroupEventEncryptionKey(clientState, ciphersuite) {
|
|
36
|
+
return mlsExporter(clientState.keySchedule.exporterSecret, "marmot", new TextEncoder().encode("group-event"), 32, ciphersuite);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads a {@link NostrEvent} and returns the {@link MlsMessage} it contains.
|
|
40
|
+
* Decrypts group-event encrypted content using the exporter_secret from the group state.
|
|
41
|
+
*
|
|
42
|
+
* @param message - The Nostr event containing the encrypted MLS message
|
|
43
|
+
* @param clientState - The ClientState for the group (to get exporter_secret)
|
|
44
|
+
* @param ciphersuite - The ciphersuite implementation
|
|
45
|
+
* @returns The decoded MlsMessage
|
|
46
|
+
*/
|
|
47
|
+
export async function decryptGroupMessageEvent(message, clientState, ciphersuite) {
|
|
48
|
+
try {
|
|
49
|
+
const key = await getGroupEventEncryptionKey(clientState, ciphersuite);
|
|
50
|
+
const payload = decodeBase64(message.content);
|
|
51
|
+
if (payload.length < 28) {
|
|
52
|
+
throw new Error("Malformed group event content: expected at least 28 bytes");
|
|
53
|
+
}
|
|
54
|
+
const nonce = payload.subarray(0, 12);
|
|
55
|
+
const ciphertext = payload.subarray(12);
|
|
56
|
+
let serializedMessage;
|
|
57
|
+
try {
|
|
58
|
+
serializedMessage = chacha20poly1305(key, nonce, new Uint8Array(0)).decrypt(ciphertext);
|
|
59
|
+
}
|
|
60
|
+
catch (aeadError) {
|
|
61
|
+
cryptoLog("decrypt kind-445 FAILED (wrong-epoch exporter): localEpoch=%s exporterKey=%s eventId=%s", epochOf(clientState), keyFingerprint(key), message.id);
|
|
62
|
+
throw aeadError;
|
|
63
|
+
}
|
|
64
|
+
const decoded = decode(mlsMessageDecoder, serializedMessage);
|
|
65
|
+
if (!decoded)
|
|
66
|
+
throw new Error("Failed to decode MLS message");
|
|
67
|
+
cryptoLog("decrypt kind-445 ok: localEpoch=%s wireformat=%s exporterKey=%s eventId=%s", epochOf(clientState), decoded.wireformat, keyFingerprint(key), message.id);
|
|
68
|
+
return decoded;
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
throw new Error(`Failed to decrypt group message: ${formatError(error)}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Encrypts the content of a group event using MIP-03.
|
|
76
|
+
*
|
|
77
|
+
* @returns The encrypted content
|
|
78
|
+
*/
|
|
79
|
+
export async function createEncryptedGroupEventContent({ state, ciphersuite, message, }) {
|
|
80
|
+
const serializedMessage = encode(mlsMessageEncoder, message);
|
|
81
|
+
const key = await getGroupEventEncryptionKey(state, ciphersuite);
|
|
82
|
+
cryptoLog("encrypt kind-445: epoch=%s wireformat=%s exporterKey=%s bytes=%d", epochOf(state), message.wireformat, keyFingerprint(key), serializedMessage.length);
|
|
83
|
+
const nonce = randomBytes(12);
|
|
84
|
+
const ciphertext = chacha20poly1305(key, nonce, new Uint8Array(0)).encrypt(serializedMessage);
|
|
85
|
+
return encodeBase64(concatBytes(nonce, ciphertext));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Decrypts a kind 445 event and returns the {@link MlsMessage} it contains.
|
|
89
|
+
*
|
|
90
|
+
* @param event - The Nostr event containing the encrypted MLS message
|
|
91
|
+
* @param clientState - The ClientState for the group (to get exporter_secret)
|
|
92
|
+
* @param ciphersuite - The ciphersuite implementation
|
|
93
|
+
* @returns The event and the decoded MlsMessage
|
|
94
|
+
*/
|
|
95
|
+
export async function decryptGroupMessage(event, clientState, ciphersuite) {
|
|
96
|
+
const message = await decryptGroupMessageEvent(event, clientState, ciphersuite);
|
|
97
|
+
return { event, message };
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Decrypts multiple kind 445 events and returns the {@link MlsMessage} they contain.
|
|
101
|
+
*
|
|
102
|
+
* `read` and `unreadable` preserve the input order of `events`.
|
|
103
|
+
*
|
|
104
|
+
* @param events - The Nostr events containing the encrypted MLS messages
|
|
105
|
+
* @param clientState - The ClientState for the group (to get exporter_secret)
|
|
106
|
+
* @param ciphersuite - The ciphersuite implementation
|
|
107
|
+
* @returns An array of event and decoded MlsMessage pairs
|
|
108
|
+
*/
|
|
109
|
+
export async function decryptGroupMessages(events, clientState, ciphersuite) {
|
|
110
|
+
const results = await Promise.all(events.map(async (event) => {
|
|
111
|
+
try {
|
|
112
|
+
return {
|
|
113
|
+
ok: true,
|
|
114
|
+
pair: await decryptGroupMessage(event, clientState, ciphersuite),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return { ok: false, event };
|
|
119
|
+
}
|
|
120
|
+
}));
|
|
121
|
+
const read = [];
|
|
122
|
+
const unreadable = [];
|
|
123
|
+
for (const r of results)
|
|
124
|
+
(r.ok ? read.push(r.pair) : unreadable.push(r.event));
|
|
125
|
+
return { read, unreadable };
|
|
126
|
+
}
|
|
127
|
+
function decodeBase64(value) {
|
|
128
|
+
try {
|
|
129
|
+
return decodeContent(value, "base64");
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
throw new Error(`Invalid base64 group event content: ${formatError(error)}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function encodeBase64(value) {
|
|
136
|
+
return encodeContent(value, "base64");
|
|
137
|
+
}
|
|
138
|
+
function formatError(error) {
|
|
139
|
+
return error instanceof Error ? error.message : String(error);
|
|
140
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** @module @category Core - Group Messages */
|
|
2
|
+
// Crypto wrap/unwrap (peel): encrypt/decrypt the MLS bytes carried by a kind
|
|
3
|
+
// 445 event. The native-sensitive randomBytes/cipher site for group messages.
|
|
4
|
+
export * from "./group-message-crypto.js";
|
|
5
|
+
// Adapter: build + ephemerally-sign the routed Nostr event around the
|
|
6
|
+
// encrypted content.
|
|
7
|
+
export * from "./group-event.js";
|
|
8
|
+
// Engine-side classification: commit ordering and message-type predicates.
|
|
9
|
+
export * from "./group-message-classify.js";
|
|
10
|
+
// Application payload (rumor) JSON serialization.
|
|
11
|
+
export * from "./application-rumor.js";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { CiphersuiteImpl, ClientConfig, ClientState, ComponentData, GroupContextExtension } from "ts-mls";
|
|
2
|
+
import { AppComponentId } from "./components/index.js";
|
|
3
|
+
import { CompleteKeyPackage } from "./key-package.js";
|
|
4
|
+
import { type ProtocolProfile } from "./protocol-profile.js";
|
|
5
|
+
export interface CreateGroupParams {
|
|
6
|
+
/** Creator's complete key package (public + private) */
|
|
7
|
+
creatorKeyPackage: CompleteKeyPackage;
|
|
8
|
+
/**
|
|
9
|
+
* Initial app components seeded into the group's `app_data_dictionary`
|
|
10
|
+
* GroupContext extension. The `app_components` (`0x0001`) advertising entry is
|
|
11
|
+
* added automatically from {@link requiredComponentIds}.
|
|
12
|
+
*/
|
|
13
|
+
components: ComponentData[];
|
|
14
|
+
/**
|
|
15
|
+
* Component ids advertised in the `app_components` (`0x0001`) entry. Defaults
|
|
16
|
+
* to the ids present in {@link components}.
|
|
17
|
+
*/
|
|
18
|
+
requiredComponentIds?: AppComponentId[];
|
|
19
|
+
/** Additional group context extensions (optional) */
|
|
20
|
+
extensions?: GroupContextExtension[];
|
|
21
|
+
/** Cipher suite implementation for cryptographic operations */
|
|
22
|
+
ciphersuiteImpl: CiphersuiteImpl;
|
|
23
|
+
/**
|
|
24
|
+
* ts-mls `ClientConfig` (key-package equality, retention, padding, ...).
|
|
25
|
+
* Producer and receiver MUST agree — a mismatch is a silent group fork
|
|
26
|
+
* (AC-VENDOR-6). Defaults to ts-mls's own default when omitted.
|
|
27
|
+
*/
|
|
28
|
+
clientConfig?: ClientConfig;
|
|
29
|
+
/**
|
|
30
|
+
* The group's protocol profile (spec DD-0, `protocol-profile.ts`). `"legacy"` (the default): `required_capabilities`
|
|
31
|
+
* lists `0xf2f1`, exactly as before profiles existed. `"current"`: `0x8009` joins the `app_components` (`0x0001`)
|
|
32
|
+
* list and `required_capabilities` omits `0xf2f1`. The creator's KeyPackage must carry the proof in the same form.
|
|
33
|
+
* Throws when the resulting GroupContext does not classify as `profile` (e.g. a Legacy group asked to require
|
|
34
|
+
* `0x8009`, or caller-supplied `required_capabilities` that contradict the profile).
|
|
35
|
+
*/
|
|
36
|
+
profile?: ProtocolProfile;
|
|
37
|
+
}
|
|
38
|
+
export interface CreateGroupResult {
|
|
39
|
+
/** The ClientState for the created group */
|
|
40
|
+
clientState: ClientState;
|
|
41
|
+
}
|
|
42
|
+
export declare function createGroup(params: CreateGroupParams): Promise<CreateGroupResult>;
|
|
43
|
+
export type SimpleGroupOptions = {
|
|
44
|
+
description?: string;
|
|
45
|
+
adminPubkeys?: string[];
|
|
46
|
+
relays?: string[];
|
|
47
|
+
/** The group's protocol profile ({@link CreateGroupParams.profile}); default `"legacy"`. */
|
|
48
|
+
profile?: ProtocolProfile;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Creates a Marmot v2 group seeded with the default group components: a
|
|
52
|
+
* `group.profile.v1` (name + description), an `admin-policy.v1` (the creator
|
|
53
|
+
* plus any extra admins), and — when relays are supplied — a
|
|
54
|
+
* `transport.nostr.routing.v1` carrying a fresh nostr group id and the relays.
|
|
55
|
+
*/
|
|
56
|
+
export declare function createSimpleGroup(creatorKeyPackage: CompleteKeyPackage, ciphersuiteImpl: CiphersuiteImpl, groupName?: string, options?: SimpleGroupOptions): Promise<CreateGroupResult>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** @module @category Core - Group */
|
|
2
|
+
import { randomBytes } from "@noble/hashes/utils.js";
|
|
3
|
+
import { createGroup as MLSCreateGroup, } from "ts-mls";
|
|
4
|
+
import { marmotAuthService } from "./auth-service.js";
|
|
5
|
+
import { marmotRequiredCapabilitiesExtension } from "./capabilities.js";
|
|
6
|
+
import { adminPolicyEntry, appComponentsEntry, DEFAULT_GROUP_COMPONENT_IDS, GROUP_LIFECYCLE_COMPONENT_ID, groupLifecycleEntry, groupProtocolLifecycleValues, groupProfileEntry, makeAppComponentsExtension, nostrRoutingEntry, } from "./components/index.js";
|
|
7
|
+
import { getCredentialPubkey } from "./credential.js";
|
|
8
|
+
import { ACCOUNT_IDENTITY_PROOF_COMPONENT_ID } from "./components/ids.js";
|
|
9
|
+
import { marmotRequiredCapabilitiesExtensionForProfile, profileOf, } from "./protocol-profile.js";
|
|
10
|
+
export async function createGroup(params) {
|
|
11
|
+
const { creatorKeyPackage, components, requiredComponentIds, extensions = [], ciphersuiteImpl, clientConfig, profile = "legacy", } = params;
|
|
12
|
+
// The MLS group_id MUST be private and distinct from the public
|
|
13
|
+
// nostr_group_id carried by the transport.nostr.routing component.
|
|
14
|
+
const groupId = randomBytes(32);
|
|
15
|
+
// Advertise the required component ids (defaults to whatever was provided),
|
|
16
|
+
// then seed each component's state into the app_data_dictionary extension.
|
|
17
|
+
// A Current group requires the proof component 0x8009 (spec DD-0).
|
|
18
|
+
const requiredIds = [
|
|
19
|
+
...new Set([
|
|
20
|
+
...DEFAULT_GROUP_COMPONENT_IDS,
|
|
21
|
+
...(requiredComponentIds ?? components.map((c) => c.componentId)),
|
|
22
|
+
...(profile === "current" ? [ACCOUNT_IDENTITY_PROOF_COMPONENT_ID] : []),
|
|
23
|
+
]),
|
|
24
|
+
];
|
|
25
|
+
const initialComponents = components.some((component) => component.componentId === GROUP_LIFECYCLE_COMPONENT_ID)
|
|
26
|
+
? components
|
|
27
|
+
: [...components, groupLifecycleEntry(groupProtocolLifecycleValues.active)];
|
|
28
|
+
const appDataExtension = makeAppComponentsExtension([
|
|
29
|
+
appComponentsEntry(requiredIds),
|
|
30
|
+
...initialComponents,
|
|
31
|
+
]);
|
|
32
|
+
// Every Marmot group declares the protocol-mandatory required_capabilities so
|
|
33
|
+
// MLS enforces them on every add (capability-negotiation.md §5.2). A caller
|
|
34
|
+
// may override by supplying their own required_capabilities in `extensions`.
|
|
35
|
+
const hasRequiredCapabilities = extensions.some((e) => e.extensionType === marmotRequiredCapabilitiesExtension().extensionType);
|
|
36
|
+
const otherExtensions = [
|
|
37
|
+
...(hasRequiredCapabilities
|
|
38
|
+
? []
|
|
39
|
+
: [marmotRequiredCapabilitiesExtensionForProfile(profile)]),
|
|
40
|
+
...extensions,
|
|
41
|
+
];
|
|
42
|
+
// An AppDataUpdate replaces this extension in place in ts-mls. OpenMLS removes
|
|
43
|
+
// it and appends the updated dictionary. Starting Current groups with the
|
|
44
|
+
// dictionary last keeps their authenticated next-epoch GroupContexts identical.
|
|
45
|
+
const groupExtensions = profile === "current"
|
|
46
|
+
? [...otherExtensions, appDataExtension]
|
|
47
|
+
: [appDataExtension, ...otherExtensions];
|
|
48
|
+
// Checked only when a profile is asked for: a caller that omits it gets exactly the group it got before profiles
|
|
49
|
+
// existed (its own `required_capabilities` included).
|
|
50
|
+
const classified = profileOf({ extensions: groupExtensions });
|
|
51
|
+
if (params.profile !== undefined && classified !== profile)
|
|
52
|
+
throw new Error(`createGroup: the group context classifies as ${typeof classified === "string" ? classified : `invalid (${classified.invalid})`}, not ${profile}`);
|
|
53
|
+
const clientState = await MLSCreateGroup({
|
|
54
|
+
context: {
|
|
55
|
+
cipherSuite: ciphersuiteImpl,
|
|
56
|
+
authService: marmotAuthService,
|
|
57
|
+
clientConfig,
|
|
58
|
+
},
|
|
59
|
+
groupId,
|
|
60
|
+
keyPackage: creatorKeyPackage.publicPackage,
|
|
61
|
+
privateKeyPackage: creatorKeyPackage.privatePackage,
|
|
62
|
+
extensions: groupExtensions,
|
|
63
|
+
});
|
|
64
|
+
return { clientState };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Creates a Marmot v2 group seeded with the default group components: a
|
|
68
|
+
* `group.profile.v1` (name + description), an `admin-policy.v1` (the creator
|
|
69
|
+
* plus any extra admins), and — when relays are supplied — a
|
|
70
|
+
* `transport.nostr.routing.v1` carrying a fresh nostr group id and the relays.
|
|
71
|
+
*/
|
|
72
|
+
export async function createSimpleGroup(creatorKeyPackage, ciphersuiteImpl, groupName = "New Group", options) {
|
|
73
|
+
// The creator is always an admin (matches darkmatter's create flow).
|
|
74
|
+
const creatorPubkey = getCredentialPubkey(creatorKeyPackage.publicPackage.leafNode.credential);
|
|
75
|
+
const adminPubkeys = [
|
|
76
|
+
...new Set([creatorPubkey, ...(options?.adminPubkeys ?? [])]),
|
|
77
|
+
];
|
|
78
|
+
const components = [
|
|
79
|
+
groupProfileEntry({
|
|
80
|
+
name: groupName,
|
|
81
|
+
description: options?.description ?? "",
|
|
82
|
+
}),
|
|
83
|
+
adminPolicyEntry(adminPubkeys),
|
|
84
|
+
];
|
|
85
|
+
const relays = options?.relays ?? [];
|
|
86
|
+
if (relays.length > 0) {
|
|
87
|
+
components.push(nostrRoutingEntry({ nostrGroupId: randomBytes(32), relays }));
|
|
88
|
+
}
|
|
89
|
+
return createGroup({
|
|
90
|
+
creatorKeyPackage,
|
|
91
|
+
components,
|
|
92
|
+
ciphersuiteImpl,
|
|
93
|
+
...(options?.profile === undefined ? {} : { profile: options.profile }),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** @module @category Core - Inbound Processing */
|
|
2
|
+
/**
|
|
3
|
+
* Inbound-processing vocabulary (Marmot v2 `protocol-core/inbound-processing.md`
|
|
4
|
+
* + `foundation/errors.md`).
|
|
5
|
+
*
|
|
6
|
+
* Inbound processing turns transport bytes into Marmot protocol input and gives
|
|
7
|
+
* each input a disposition. Transport delivery is evidence that bytes exist, not
|
|
8
|
+
* that they define canonical group state — so order, timestamps, and transport
|
|
9
|
+
* ids never decide an outcome. The protocol-visible result of processing an
|
|
10
|
+
* input is its {@link Disposition}; an input that produces no application content
|
|
11
|
+
* is classified into a shared {@link InputCategory}.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* The shared input categories from `foundation/errors.md`. An input that does not
|
|
15
|
+
* produce application content maps to one of these. These are protocol-level
|
|
16
|
+
* outcome names; local APIs are not required to use these exact identifiers.
|
|
17
|
+
*/
|
|
18
|
+
export declare const inputCategories: {
|
|
19
|
+
/** The same protocol input was already seen. */
|
|
20
|
+
readonly duplicate: "duplicate";
|
|
21
|
+
/** The input is the client's own already-accounted-for output. */
|
|
22
|
+
readonly ownEcho: "own_echo";
|
|
23
|
+
/** The input targets another account, device, group, or routing id. */
|
|
24
|
+
readonly wrongRecipient: "wrong_recipient";
|
|
25
|
+
/** The client has no group state that can process the input. */
|
|
26
|
+
readonly unknownGroup: "unknown_group";
|
|
27
|
+
/** The input is represented by the current canonical state. */
|
|
28
|
+
readonly alreadyApplied: "already_applied";
|
|
29
|
+
/** The input is from an epoch the client will not process. */
|
|
30
|
+
readonly staleEpoch: "stale_epoch";
|
|
31
|
+
/** Bytes failed the owning document's parser or length rules. */
|
|
32
|
+
readonly invalidEncoding: "invalid_encoding";
|
|
33
|
+
/** A required MLS, Nostr, or component signature check failed. */
|
|
34
|
+
readonly invalidSignature: "invalid_signature";
|
|
35
|
+
/** The group requires a feature the client does not understand. */
|
|
36
|
+
readonly unsupportedRequiredFeature: "unsupported_required_feature";
|
|
37
|
+
/** The sender or committer is not allowed to make the change. */
|
|
38
|
+
readonly authorizationFailed: "authorization_failed";
|
|
39
|
+
/** The client would need retained state it no longer has. */
|
|
40
|
+
readonly missingHistory: "missing_history";
|
|
41
|
+
/** Publication or delivery failed at the transport layer. */
|
|
42
|
+
readonly transportRejected: "transport_rejected";
|
|
43
|
+
};
|
|
44
|
+
/** A shared input category value (the `snake_case` wire name). */
|
|
45
|
+
export type InputCategory = (typeof inputCategories)[keyof typeof inputCategories];
|
|
46
|
+
/**
|
|
47
|
+
* The protocol-visible disposition emitted for an inbound message.
|
|
48
|
+
*
|
|
49
|
+
* - `accepted` — the input was applied to (or is consistent with) canonical state
|
|
50
|
+
* on the selected branch; for an MLS application message this also delivers a
|
|
51
|
+
* payload.
|
|
52
|
+
* - `stale` — the input cannot affect the group; carries the {@link InputCategory}.
|
|
53
|
+
* - `deferred` — the input cannot be processed yet but could become processable
|
|
54
|
+
* when more protocol bytes arrive; MUST be retried.
|
|
55
|
+
* - `invalidated` — an MLS application message that decrypts only on a losing
|
|
56
|
+
* branch; reported, never delivered as accepted output.
|
|
57
|
+
*/
|
|
58
|
+
export type Disposition = {
|
|
59
|
+
kind: "accepted";
|
|
60
|
+
} | {
|
|
61
|
+
kind: "stale";
|
|
62
|
+
category: InputCategory;
|
|
63
|
+
} | {
|
|
64
|
+
kind: "deferred";
|
|
65
|
+
reason: DeferredReason;
|
|
66
|
+
} | {
|
|
67
|
+
kind: "invalidated";
|
|
68
|
+
};
|
|
69
|
+
/** Why an input was deferred (retry when the missing state becomes available). */
|
|
70
|
+
export declare const deferredReasons: {
|
|
71
|
+
/** An MLS application message for a future candidate epoch. */
|
|
72
|
+
readonly futureEpoch: "future_epoch";
|
|
73
|
+
/** A child commit whose parent branch is not yet available. */
|
|
74
|
+
readonly missingParent: "missing_parent";
|
|
75
|
+
/** Input received while the group is in PendingPublish or Merging. */
|
|
76
|
+
readonly groupBusy: "group_busy";
|
|
77
|
+
/** Local admission capacity is full; retry without transport redelivery. */
|
|
78
|
+
readonly capacity: "capacity";
|
|
79
|
+
};
|
|
80
|
+
/** A deferred-input reason. */
|
|
81
|
+
export type DeferredReason = (typeof deferredReasons)[keyof typeof deferredReasons];
|
|
82
|
+
/**
|
|
83
|
+
* Convergence outcome names (`PascalCase` in the spec) that map onto shared
|
|
84
|
+
* `snake_case` {@link InputCategory} values.
|
|
85
|
+
*/
|
|
86
|
+
export declare const convergenceOutcomeToCategory: {
|
|
87
|
+
/** A commit/state older than the retained anchor — needs history we dropped. */
|
|
88
|
+
readonly BeyondAnchor: "missing_history";
|
|
89
|
+
/** The required retained anchor is missing — needs history we dropped. */
|
|
90
|
+
readonly MissingRetainedAnchor: "missing_history";
|
|
91
|
+
/** Input for a group this client has been removed from — classified by its group, never decrypted. */
|
|
92
|
+
readonly SelfEvicted: "stale_epoch";
|
|
93
|
+
};
|
|
94
|
+
/** A convergence outcome name (`PascalCase`). */
|
|
95
|
+
export type ConvergenceOutcome = keyof typeof convergenceOutcomeToCategory;
|
|
96
|
+
/** Convenience constructors for dispositions. */
|
|
97
|
+
export declare const disposition: {
|
|
98
|
+
accepted: () => Disposition;
|
|
99
|
+
stale: (category: InputCategory) => Disposition;
|
|
100
|
+
deferred: (reason: DeferredReason) => Disposition;
|
|
101
|
+
invalidated: () => Disposition;
|
|
102
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** @module @category Core - Inbound Processing */
|
|
2
|
+
/**
|
|
3
|
+
* Inbound-processing vocabulary (Marmot v2 `protocol-core/inbound-processing.md`
|
|
4
|
+
* + `foundation/errors.md`).
|
|
5
|
+
*
|
|
6
|
+
* Inbound processing turns transport bytes into Marmot protocol input and gives
|
|
7
|
+
* each input a disposition. Transport delivery is evidence that bytes exist, not
|
|
8
|
+
* that they define canonical group state — so order, timestamps, and transport
|
|
9
|
+
* ids never decide an outcome. The protocol-visible result of processing an
|
|
10
|
+
* input is its {@link Disposition}; an input that produces no application content
|
|
11
|
+
* is classified into a shared {@link InputCategory}.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* The shared input categories from `foundation/errors.md`. An input that does not
|
|
15
|
+
* produce application content maps to one of these. These are protocol-level
|
|
16
|
+
* outcome names; local APIs are not required to use these exact identifiers.
|
|
17
|
+
*/
|
|
18
|
+
export const inputCategories = {
|
|
19
|
+
/** The same protocol input was already seen. */
|
|
20
|
+
duplicate: "duplicate",
|
|
21
|
+
/** The input is the client's own already-accounted-for output. */
|
|
22
|
+
ownEcho: "own_echo",
|
|
23
|
+
/** The input targets another account, device, group, or routing id. */
|
|
24
|
+
wrongRecipient: "wrong_recipient",
|
|
25
|
+
/** The client has no group state that can process the input. */
|
|
26
|
+
unknownGroup: "unknown_group",
|
|
27
|
+
/** The input is represented by the current canonical state. */
|
|
28
|
+
alreadyApplied: "already_applied",
|
|
29
|
+
/** The input is from an epoch the client will not process. */
|
|
30
|
+
staleEpoch: "stale_epoch",
|
|
31
|
+
/** Bytes failed the owning document's parser or length rules. */
|
|
32
|
+
invalidEncoding: "invalid_encoding",
|
|
33
|
+
/** A required MLS, Nostr, or component signature check failed. */
|
|
34
|
+
invalidSignature: "invalid_signature",
|
|
35
|
+
/** The group requires a feature the client does not understand. */
|
|
36
|
+
unsupportedRequiredFeature: "unsupported_required_feature",
|
|
37
|
+
/** The sender or committer is not allowed to make the change. */
|
|
38
|
+
authorizationFailed: "authorization_failed",
|
|
39
|
+
/** The client would need retained state it no longer has. */
|
|
40
|
+
missingHistory: "missing_history",
|
|
41
|
+
/** Publication or delivery failed at the transport layer. */
|
|
42
|
+
transportRejected: "transport_rejected",
|
|
43
|
+
};
|
|
44
|
+
/** Why an input was deferred (retry when the missing state becomes available). */
|
|
45
|
+
export const deferredReasons = {
|
|
46
|
+
/** An MLS application message for a future candidate epoch. */
|
|
47
|
+
futureEpoch: "future_epoch",
|
|
48
|
+
/** A child commit whose parent branch is not yet available. */
|
|
49
|
+
missingParent: "missing_parent",
|
|
50
|
+
/** Input received while the group is in PendingPublish or Merging. */
|
|
51
|
+
groupBusy: "group_busy",
|
|
52
|
+
/** Local admission capacity is full; retry without transport redelivery. */
|
|
53
|
+
capacity: "capacity",
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Convergence outcome names (`PascalCase` in the spec) that map onto shared
|
|
57
|
+
* `snake_case` {@link InputCategory} values.
|
|
58
|
+
*/
|
|
59
|
+
export const convergenceOutcomeToCategory = {
|
|
60
|
+
/** A commit/state older than the retained anchor — needs history we dropped. */
|
|
61
|
+
BeyondAnchor: inputCategories.missingHistory,
|
|
62
|
+
/** The required retained anchor is missing — needs history we dropped. */
|
|
63
|
+
MissingRetainedAnchor: inputCategories.missingHistory,
|
|
64
|
+
/** Input for a group this client has been removed from — classified by its group, never decrypted. */
|
|
65
|
+
SelfEvicted: inputCategories.staleEpoch,
|
|
66
|
+
};
|
|
67
|
+
/** Convenience constructors for dispositions. */
|
|
68
|
+
export const disposition = {
|
|
69
|
+
accepted: () => ({ kind: "accepted" }),
|
|
70
|
+
stale: (category) => ({
|
|
71
|
+
kind: "stale",
|
|
72
|
+
category,
|
|
73
|
+
}),
|
|
74
|
+
deferred: (reason) => ({
|
|
75
|
+
kind: "deferred",
|
|
76
|
+
reason,
|
|
77
|
+
}),
|
|
78
|
+
invalidated: () => ({ kind: "invalidated" }),
|
|
79
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export * from "./account-identity-proof.js";
|
|
2
|
+
export * from "./binary.js";
|
|
3
|
+
export * from "./components/index.js";
|
|
4
|
+
export * from "./capabilities.js";
|
|
5
|
+
export * from "./client-state.js";
|
|
6
|
+
export * from "./commit-authorization.js";
|
|
7
|
+
export * from "./convergence.js";
|
|
8
|
+
export { convergenceStatuses, type ConvergenceStatus } from "./convergence-status.js";
|
|
9
|
+
export type { MediaCryptoFields } from "./media/crypto.js";
|
|
10
|
+
export type { Rumor } from "../utils/nostr.js";
|
|
11
|
+
export * from "./credential.js";
|
|
12
|
+
export * from "./default-capabilities.js";
|
|
13
|
+
export * from "./extensions.js";
|
|
14
|
+
export * from "./group-lifecycle.js";
|
|
15
|
+
export * from "./inbound.js";
|
|
16
|
+
export * from "./group-members.js";
|
|
17
|
+
export * from "./group-message.js";
|
|
18
|
+
export * from "./group.js";
|
|
19
|
+
export * from "./key-package-event.js";
|
|
20
|
+
export * from "./key-package-eligibility.js";
|
|
21
|
+
export * from "./key-package.js";
|
|
22
|
+
export * from "./leaf-succession.js";
|
|
23
|
+
export * from "./relay-lists.js";
|
|
24
|
+
export * from "./media.js";
|
|
25
|
+
export * from "./protocol.js";
|
|
26
|
+
export * from "./protocol-profile.js";
|
|
27
|
+
export * from "./transport.js";
|
|
28
|
+
export * from "./retained-history.js";
|
|
29
|
+
export * from "./welcome.js";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export * from "./account-identity-proof.js";
|
|
2
|
+
export * from "./binary.js";
|
|
3
|
+
export * from "./components/index.js";
|
|
4
|
+
export * from "./capabilities.js";
|
|
5
|
+
export * from "./client-state.js";
|
|
6
|
+
export * from "./commit-authorization.js";
|
|
7
|
+
export * from "./convergence.js";
|
|
8
|
+
export { convergenceStatuses } from "./convergence-status.js";
|
|
9
|
+
export * from "./credential.js";
|
|
10
|
+
export * from "./default-capabilities.js";
|
|
11
|
+
export * from "./extensions.js";
|
|
12
|
+
export * from "./group-lifecycle.js";
|
|
13
|
+
export * from "./inbound.js";
|
|
14
|
+
export * from "./group-members.js";
|
|
15
|
+
export * from "./group-message.js";
|
|
16
|
+
export * from "./group.js";
|
|
17
|
+
export * from "./key-package-event.js";
|
|
18
|
+
export * from "./key-package-eligibility.js";
|
|
19
|
+
export * from "./key-package.js";
|
|
20
|
+
export * from "./leaf-succession.js";
|
|
21
|
+
export * from "./relay-lists.js";
|
|
22
|
+
export * from "./media.js";
|
|
23
|
+
export * from "./protocol.js";
|
|
24
|
+
export * from "./protocol-profile.js";
|
|
25
|
+
export * from "./transport.js";
|
|
26
|
+
export * from "./retained-history.js";
|
|
27
|
+
export * from "./welcome.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** @module @category Core - Key Package */
|
|
2
|
+
import type { NostrEvent } from "../utils/nostr.js";
|
|
3
|
+
import type { ClientState, GroupInfo } from "ts-mls";
|
|
4
|
+
/** The outcome of evaluating a KeyPackage against a group's add requirements. */
|
|
5
|
+
export interface KeyPackageEligibility {
|
|
6
|
+
/** True when the KeyPackage satisfies every add requirement (no reasons). */
|
|
7
|
+
eligible: boolean;
|
|
8
|
+
/** True when the KeyPackage's account is already a member of the group. */
|
|
9
|
+
alreadyMember: boolean;
|
|
10
|
+
/** The KeyPackage's MLS cipher suite id, or `-1` if the event was undecodable. */
|
|
11
|
+
cipherSuite: number;
|
|
12
|
+
/** Human-readable reasons the KeyPackage is not eligible (empty when it is). */
|
|
13
|
+
reasons: string[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Evaluates whether a candidate's KeyPackage event (kind 30443) can be added to a
|
|
17
|
+
* group, against every Marmot add requirement: cipher-suite match, the group's
|
|
18
|
+
* `required_capabilities` (extension/proposal/credential types), the
|
|
19
|
+
* agent-text-stream-QUIC `required_member_roles` policy, and whether the
|
|
20
|
+
* KeyPackage's account is already a member.
|
|
21
|
+
*
|
|
22
|
+
* This is the eligibility logic an app needs before sending an invite — the
|
|
23
|
+
* library's {@link createInviteIntent} only checks the credential identity. A
|
|
24
|
+
* `reasons` array of length 0 means the KeyPackage is safe to add; a non-empty
|
|
25
|
+
* array explains every failing requirement. Never throws: an undecodable
|
|
26
|
+
* KeyPackage yields `eligible: false` with an `undecodable: …` reason.
|
|
27
|
+
*
|
|
28
|
+
* @param state - The local group state to evaluate against (`group.state`).
|
|
29
|
+
* @param keyPackageEvent - The invitee's kind-30443 KeyPackage event.
|
|
30
|
+
*/
|
|
31
|
+
export declare function evaluateKeyPackageForGroup(state: ClientState | GroupInfo, keyPackageEvent: NostrEvent): KeyPackageEligibility;
|