@kumiai/mls 0.1.0 → 0.2.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.
package/lib/head.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ import { type GroupContextExtension } from 'ts-mls';
2
+ import type { GroupHandle } from './group.js';
3
+ /** Binary version tag for the encoded ledger-head extension. */
4
+ export declare const LEDGER_HEAD_VERSION = 1;
5
+ /** The parsed ledger-head extension: a version and the running chain digest. */
6
+ export type LedgerHead = {
7
+ v: number;
8
+ head: Uint8Array;
9
+ };
10
+ /**
11
+ * Thrown when a joiner's recomputed head does not match the authenticated one:
12
+ * an inviter omitted, reordered, or truncated a ledger entry. Carries both heads
13
+ * so a caller can log the mismatch. Thrown by the joiner's verification path in
14
+ * a later step; here it backs {@link assertHeadMatches}.
15
+ */
16
+ export declare class LedgerIncompleteError extends Error {
17
+ #private;
18
+ constructor(expected: Uint8Array, actual: Uint8Array);
19
+ /** The authenticated head read from the group's GroupContext. Named apart from
20
+ * `expected`/`actual` on purpose: a test runner's diff formatter assigns those
21
+ * two properties on any thrown Error, and a getter-only pair turns an
22
+ * unexpected throw into a `Cannot set property` TypeError instead of the real
23
+ * failure. */
24
+ get expectedHead(): Uint8Array;
25
+ /** The head recomputed from the entries the inviter supplied. */
26
+ get actualHead(): Uint8Array;
27
+ }
28
+ /**
29
+ * Genesis head for a group: `SHA256(DOMAIN ‖ groupID)`. Pure. The epoch-0 link
30
+ * of the chain, written into the GroupContext by group creation.
31
+ */
32
+ export declare function genesisHead(groupID: string): Uint8Array;
33
+ /**
34
+ * Extend a head by a batch of entry ids, in envelope order. Each id is a chain
35
+ * link: `head ← SHA256(head ‖ frame(id))`, folded left to right. Pure,
36
+ * order-sensitive, and length-sensitive (see {@link frameID}). An empty batch is
37
+ * a no-op — a commit carrying no entries does not move the head.
38
+ */
39
+ export declare function extendHead(head: Uint8Array, entryIDs: Array<string>): Uint8Array;
40
+ /**
41
+ * Recompute a head from genesis across an ordered id list. Pure. Composes with
42
+ * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
43
+ * `extendHead(extendHead(genesisHead(g), a), b)`, so an existing member verifies
44
+ * a head update by extending its own chain — never by refolding from genesis.
45
+ */
46
+ export declare function computeHead(groupID: string, entryIDs: Array<string>): Uint8Array;
47
+ /**
48
+ * Encode a head as the LedgerHead GroupContext extension data: one version byte
49
+ * (`LEDGER_HEAD_VERSION`) followed by the 32 digest bytes. A single canonical
50
+ * byte form — no JSON — so the value can be byte-compared in the commit policy.
51
+ */
52
+ export declare function encodeLedgerHead(head: Uint8Array): Uint8Array;
53
+ /**
54
+ * Tolerant decode: returns null on any wrong length or unknown version byte,
55
+ * never throws. Only a version-`LEDGER_HEAD_VERSION`, `1 + 32`-byte buffer
56
+ * decodes.
57
+ */
58
+ export declare function decodeLedgerHead(bytes: Uint8Array): LedgerHead | null;
59
+ /** Build the ledger-head GroupContext extension for a head digest. */
60
+ export declare function buildLedgerHeadExtension(head: Uint8Array): GroupContextExtension;
61
+ /**
62
+ * The head's raw GroupContext extension, exactly as it sits in the group, or
63
+ * null when genuinely absent. Never throws. Mirrors
64
+ * {@link readGroupAnchorExtension}: it does not decode — it is the source of the
65
+ * verbatim bytes a group-context-extensions proposal must copy and the commit
66
+ * policy byte-compares.
67
+ */
68
+ export declare function readLedgerHeadExtension(handle: GroupHandle): GroupContextExtension | null;
69
+ /**
70
+ * Read and decode the ledger head from a group handle. Returns null only when
71
+ * the head extension is genuinely absent. A present-but-undecodable extension is
72
+ * corruption, not absence, and throws — so a control gate fails closed rather
73
+ * than silently treating a tampered head as no head. For bytes to byte-compare
74
+ * or copy into a proposal, use {@link readLedgerHeadExtension}, never a
75
+ * re-encode of this result.
76
+ */
77
+ export declare function readLedgerHead(handle: GroupHandle): LedgerHead | null;
78
+ /**
79
+ * Assert a recomputed head matches the authenticated one, or throw
80
+ * {@link LedgerIncompleteError} carrying both. Returns for equal heads.
81
+ */
82
+ export declare function assertHeadMatches(expected: Uint8Array, actual: Uint8Array): void;
package/lib/head.js ADDED
@@ -0,0 +1,155 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ import { concatBytes } from '@noble/hashes/utils.js';
3
+ import { makeCustomExtension } from 'ts-mls';
4
+ import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
5
+ /** Binary version tag for the encoded ledger-head extension. */ export const LEDGER_HEAD_VERSION = 1;
6
+ /**
7
+ * Domain separator mixed into every genesis head so a head can never collide
8
+ * with a raw SHA-256 of unrelated data (e.g. a bare group id, or another
9
+ * protocol's digest of the same bytes). Fixed, non-empty, and namespaced to
10
+ * this module and version.
11
+ */ const DOMAIN = new TextEncoder().encode('kumiai/mls/ledger-head/v1');
12
+ const utf8 = new TextEncoder();
13
+ const SHA256_LENGTH = 32;
14
+ /**
15
+ * Thrown when a joiner's recomputed head does not match the authenticated one:
16
+ * an inviter omitted, reordered, or truncated a ledger entry. Carries both heads
17
+ * so a caller can log the mismatch. Thrown by the joiner's verification path in
18
+ * a later step; here it backs {@link assertHeadMatches}.
19
+ */ export class LedgerIncompleteError extends Error {
20
+ #expected;
21
+ #actual;
22
+ constructor(expected, actual){
23
+ super('recomputed ledger head does not match the authenticated head');
24
+ this.name = 'LedgerIncompleteError';
25
+ this.#expected = expected;
26
+ this.#actual = actual;
27
+ }
28
+ /** The authenticated head read from the group's GroupContext. Named apart from
29
+ * `expected`/`actual` on purpose: a test runner's diff formatter assigns those
30
+ * two properties on any thrown Error, and a getter-only pair turns an
31
+ * unexpected throw into a `Cannot set property` TypeError instead of the real
32
+ * failure. */ get expectedHead() {
33
+ return this.#expected;
34
+ }
35
+ /** The head recomputed from the entries the inviter supplied. */ get actualHead() {
36
+ return this.#actual;
37
+ }
38
+ }
39
+ /**
40
+ * Length-frame one entry id: a 4-byte big-endian length prefix before the id's
41
+ * UTF-8 bytes. The prefix makes the chain unambiguous about id boundaries, so
42
+ * `['ab','c']` and `['a','bc']` cannot fold to the same head.
43
+ */ function frameID(id) {
44
+ const bytes = utf8.encode(id);
45
+ const framed = new Uint8Array(4 + bytes.length);
46
+ const view = new DataView(framed.buffer);
47
+ view.setUint32(0, bytes.length, false);
48
+ framed.set(bytes, 4);
49
+ return framed;
50
+ }
51
+ /**
52
+ * Genesis head for a group: `SHA256(DOMAIN ‖ groupID)`. Pure. The epoch-0 link
53
+ * of the chain, written into the GroupContext by group creation.
54
+ */ export function genesisHead(groupID) {
55
+ return sha256(concatBytes(DOMAIN, utf8.encode(groupID)));
56
+ }
57
+ /**
58
+ * Extend a head by a batch of entry ids, in envelope order. Each id is a chain
59
+ * link: `head ← SHA256(head ‖ frame(id))`, folded left to right. Pure,
60
+ * order-sensitive, and length-sensitive (see {@link frameID}). An empty batch is
61
+ * a no-op — a commit carrying no entries does not move the head.
62
+ */ export function extendHead(head, entryIDs) {
63
+ let acc = head;
64
+ for (const id of entryIDs){
65
+ acc = sha256(concatBytes(acc, frameID(id)));
66
+ }
67
+ return acc;
68
+ }
69
+ /**
70
+ * Recompute a head from genesis across an ordered id list. Pure. Composes with
71
+ * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
72
+ * `extendHead(extendHead(genesisHead(g), a), b)`, so an existing member verifies
73
+ * a head update by extending its own chain — never by refolding from genesis.
74
+ */ export function computeHead(groupID, entryIDs) {
75
+ return extendHead(genesisHead(groupID), entryIDs);
76
+ }
77
+ /**
78
+ * Encode a head as the LedgerHead GroupContext extension data: one version byte
79
+ * (`LEDGER_HEAD_VERSION`) followed by the 32 digest bytes. A single canonical
80
+ * byte form — no JSON — so the value can be byte-compared in the commit policy.
81
+ */ export function encodeLedgerHead(head) {
82
+ const bytes = new Uint8Array(1 + head.length);
83
+ bytes[0] = LEDGER_HEAD_VERSION;
84
+ bytes.set(head, 1);
85
+ return bytes;
86
+ }
87
+ /**
88
+ * Tolerant decode: returns null on any wrong length or unknown version byte,
89
+ * never throws. Only a version-`LEDGER_HEAD_VERSION`, `1 + 32`-byte buffer
90
+ * decodes.
91
+ */ export function decodeLedgerHead(bytes) {
92
+ if (bytes.length !== 1 + SHA256_LENGTH || bytes[0] !== LEDGER_HEAD_VERSION) {
93
+ return null;
94
+ }
95
+ return {
96
+ v: LEDGER_HEAD_VERSION,
97
+ head: bytes.slice(1)
98
+ };
99
+ }
100
+ /** Build the ledger-head GroupContext extension for a head digest. */ export function buildLedgerHeadExtension(head) {
101
+ return makeCustomExtension({
102
+ extensionType: LEDGER_HEAD_EXTENSION_TYPE,
103
+ extensionData: encodeLedgerHead(head)
104
+ });
105
+ }
106
+ function findHeadExtension(handle) {
107
+ return handle.state.groupContext.extensions.find((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
108
+ }
109
+ /**
110
+ * The head's raw GroupContext extension, exactly as it sits in the group, or
111
+ * null when genuinely absent. Never throws. Mirrors
112
+ * {@link readGroupAnchorExtension}: it does not decode — it is the source of the
113
+ * verbatim bytes a group-context-extensions proposal must copy and the commit
114
+ * policy byte-compares.
115
+ */ export function readLedgerHeadExtension(handle) {
116
+ return findHeadExtension(handle) ?? null;
117
+ }
118
+ /**
119
+ * Read and decode the ledger head from a group handle. Returns null only when
120
+ * the head extension is genuinely absent. A present-but-undecodable extension is
121
+ * corruption, not absence, and throws — so a control gate fails closed rather
122
+ * than silently treating a tampered head as no head. For bytes to byte-compare
123
+ * or copy into a proposal, use {@link readLedgerHeadExtension}, never a
124
+ * re-encode of this result.
125
+ */ export function readLedgerHead(handle) {
126
+ const extension = findHeadExtension(handle);
127
+ if (extension == null) {
128
+ return null;
129
+ }
130
+ const data = extension.extensionData;
131
+ const head = data instanceof Uint8Array ? decodeLedgerHead(data) : null;
132
+ if (head == null) {
133
+ throw new Error('ledger head extension present but could not be decoded');
134
+ }
135
+ return head;
136
+ }
137
+ function bytesEqual(a, b) {
138
+ if (a.length !== b.length) {
139
+ return false;
140
+ }
141
+ for(let i = 0; i < a.length; i++){
142
+ if (a[i] !== b[i]) {
143
+ return false;
144
+ }
145
+ }
146
+ return true;
147
+ }
148
+ /**
149
+ * Assert a recomputed head matches the authenticated one, or throw
150
+ * {@link LedgerIncompleteError} carrying both. Returns for equal heads.
151
+ */ export function assertHeadMatches(expected, actual) {
152
+ if (!bytesEqual(expected, actual)) {
153
+ throw new LedgerIncompleteError(expected, actual);
154
+ }
155
+ }
package/lib/index.d.ts CHANGED
@@ -1,9 +1,16 @@
1
1
  export type { Capabilities, GroupContextExtension, IncomingMessageCallback, Proposal, ProposalWithSender, } from 'ts-mls';
2
2
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
3
+ export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
3
4
  export { createDIDAuthenticationService } from './authentication.js';
4
- export { createGroupCapability, type DelegateGroupMembershipParams, delegateGroupMembership, type GroupPermission, type ValidateGroupCapabilityParams, validateGroupCapability, } from './capability.js';
5
5
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
6
- export { extractPermission, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, populateCacheFromCredential, } from './credential.js';
6
+ export { type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, populateCacheFromCredential, } from './credential.js';
7
7
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
8
- export { type CommitInviteResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, createGroup, createInvite, createKeyPackageBundle, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleParams, type InspectGroupInfoResult, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, makeMLSCredential, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
8
+ export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
9
+ export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
10
+ export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
11
+ export { type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type LedgerLogEntry, makeMLSCredential, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
12
+ export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
13
+ export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
14
+ export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
15
+ export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
9
16
  export type { GroupOptions, GroupSyncScope, Invite, KeyPackageBundle } from './types.js';
package/lib/index.js CHANGED
@@ -1,7 +1,14 @@
1
1
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
2
+ export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension } from './anchor.js';
2
3
  export { createDIDAuthenticationService } from './authentication.js';
3
- export { createGroupCapability, delegateGroupMembership, validateGroupCapability } from './capability.js';
4
4
  export { decodeClientState, encodeClientState, sanitizeRatchetTree } from './codec.js';
5
- export { extractPermission, parseMLSCredentialIdentity, populateCacheFromCredential } from './credential.js';
5
+ export { parseMLSCredentialIdentity, populateCacheFromCredential } from './credential.js';
6
6
  export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
7
- export { CommitRejectedError, commitInvite, createGroup, createInvite, createKeyPackageBundle, exportGroupInfo, GroupHandle, inspectGroupInfo, joinGroupExternal, makeMLSCredential, processWelcome, readMessageEpoch, removeMember, restoreGroup } from './group.js';
7
+ export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
8
+ export { foldEnvelope } from './envelope-fold.js';
9
+ export { foldLedger } from './fold.js';
10
+ export { CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, exportGroupInfo, GroupHandle, inspectGroupInfo, joinGroupExternal, makeMLSCredential, processWelcome, readMessageEpoch, removeMember, restoreGroup } from './group.js';
11
+ export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
12
+ export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
13
+ export { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
14
+ export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
@@ -0,0 +1,49 @@
1
+ import { type SigningIdentity } from '@kokuin/token';
2
+ /**
3
+ * A control-ledger claim. The payload of a signed ledger token: `type` selects
4
+ * the reducer, `groupID` binds the claim to a single group, `subject` is the
5
+ * entity the claim is about, and `value` carries the claim data. The
6
+ * authenticated author is never part of this shape — it comes from the verified
7
+ * token's `iss`.
8
+ */
9
+ export type LedgerEntry<TValue = unknown> = {
10
+ type: string;
11
+ groupID: string;
12
+ subject: string;
13
+ value: TValue;
14
+ /**
15
+ * Consumer-supplied total-order key, signed with the rest of the claim.
16
+ * `@kumiai/mls` never reads it — kumiai orders by the epoch chain. Kubun sets
17
+ * it to its HLC. Optional.
18
+ */
19
+ ord?: string;
20
+ };
21
+ /** A ledger entry whose token signature has been cryptographically verified. */
22
+ export type VerifiedLedgerEntry<TValue = unknown> = {
23
+ /** Authenticated author DID (the verified token issuer), normalized. */
24
+ issuer: string;
25
+ entry: LedgerEntry<TValue>;
26
+ };
27
+ /**
28
+ * Sign a ledger entry. The signer fills `iss` with its DID, so the signature
29
+ * covers every claim field — including `groupID` and `ord` — and binds the
30
+ * author. `ord` is signed only when present, so a claim without it never signs
31
+ * an `ord: undefined` key. Returns the stringified token.
32
+ */
33
+ export declare function signLedgerEntry(identity: SigningIdentity, entry: LedgerEntry): Promise<string>;
34
+ /**
35
+ * Verify a signed ledger token and extract its claim. Returns `null` (never
36
+ * throws) when the token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
37
+ * returns those without checking a signature, so an attacker could forge an
38
+ * arbitrary `iss`; `isVerifiedToken` rejects them), or structurally malformed.
39
+ * A missing or non-string `groupID` is malformed, as is a missing or non-string
40
+ * `type` or `subject`, or an `ord` present but not a string. The claim fields
41
+ * come from the verified payload only; the issuer is the normalized verified
42
+ * `iss`.
43
+ */
44
+ export declare function verifyLedgerEntry<TValue = unknown>(token: string): Promise<VerifiedLedgerEntry<TValue> | null>;
45
+ /**
46
+ * Content-addressed digest of a signed ledger token, used as the append-only
47
+ * store's dedup key. Multibase-encoded SHA-256 multihash over the token bytes.
48
+ */
49
+ export declare function ledgerEntryDigest(signedToken: string): string;
package/lib/ledger.js ADDED
@@ -0,0 +1,67 @@
1
+ import { encodeMultibase, isVerifiedToken, multihashSHA256, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
2
+ const textEncoder = new TextEncoder();
3
+ /**
4
+ * Sign a ledger entry. The signer fills `iss` with its DID, so the signature
5
+ * covers every claim field — including `groupID` and `ord` — and binds the
6
+ * author. `ord` is signed only when present, so a claim without it never signs
7
+ * an `ord: undefined` key. Returns the stringified token.
8
+ */ export async function signLedgerEntry(identity, entry) {
9
+ const signed = await identity.signToken({
10
+ type: entry.type,
11
+ groupID: entry.groupID,
12
+ subject: entry.subject,
13
+ value: entry.value,
14
+ ...entry.ord === undefined ? {} : {
15
+ ord: entry.ord
16
+ }
17
+ }, // Embed the long-form DID so each entry is self-verifying offline: the
18
+ // ledger is the source of truth and receivers fold it long after first
19
+ // contact, when the author's DID document may no longer be cached. No-op
20
+ // for did:key (long form === id).
21
+ {
22
+ embedLongForm: true
23
+ });
24
+ return stringifyToken(signed);
25
+ }
26
+ /**
27
+ * Verify a signed ledger token and extract its claim. Returns `null` (never
28
+ * throws) when the token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
29
+ * returns those without checking a signature, so an attacker could forge an
30
+ * arbitrary `iss`; `isVerifiedToken` rejects them), or structurally malformed.
31
+ * A missing or non-string `groupID` is malformed, as is a missing or non-string
32
+ * `type` or `subject`, or an `ord` present but not a string. The claim fields
33
+ * come from the verified payload only; the issuer is the normalized verified
34
+ * `iss`.
35
+ */ export async function verifyLedgerEntry(token) {
36
+ let verified;
37
+ try {
38
+ verified = await verifyToken(token);
39
+ } catch {
40
+ return null;
41
+ }
42
+ if (!isVerifiedToken(verified)) {
43
+ return null;
44
+ }
45
+ const { iss, type, groupID, subject, value, ord } = verified.payload;
46
+ if (typeof type !== 'string' || typeof groupID !== 'string' || typeof subject !== 'string' || ord !== undefined && typeof ord !== 'string') {
47
+ return null;
48
+ }
49
+ return {
50
+ issuer: normalizeDID(iss),
51
+ entry: {
52
+ type,
53
+ groupID,
54
+ subject,
55
+ value,
56
+ ...ord === undefined ? {} : {
57
+ ord
58
+ }
59
+ }
60
+ };
61
+ }
62
+ /**
63
+ * Content-addressed digest of a signed ledger token, used as the append-only
64
+ * store's dedup key. Multibase-encoded SHA-256 multihash over the token bytes.
65
+ */ export function ledgerEntryDigest(signedToken) {
66
+ return encodeMultibase(multihashSHA256(textEncoder.encode(signedToken)));
67
+ }
package/lib/mutex.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A FIFO async serializer: `run` executes its callbacks one at a time, in the
3
+ * order they were called. A callback's rejection is delivered to its own caller
4
+ * but never stalls or poisons the queue for later callbacks — the chain always
5
+ * advances. Order is not reprioritized: callers rely on it to preserve causal
6
+ * order (e.g. the epoch at which an MLS message is produced).
7
+ *
8
+ * Deliberately dependency-free and generic, so it can move to `@sozai/async`
9
+ * unchanged; this package's only per-instance glue is a WeakMap keyed by handle.
10
+ */
11
+ export type Mutex = {
12
+ run: <T>(fn: () => Promise<T>) => Promise<T>;
13
+ };
14
+ export declare function createMutex(): Mutex;
package/lib/mutex.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A FIFO async serializer: `run` executes its callbacks one at a time, in the
3
+ * order they were called. A callback's rejection is delivered to its own caller
4
+ * but never stalls or poisons the queue for later callbacks — the chain always
5
+ * advances. Order is not reprioritized: callers rely on it to preserve causal
6
+ * order (e.g. the epoch at which an MLS message is produced).
7
+ *
8
+ * Deliberately dependency-free and generic, so it can move to `@sozai/async`
9
+ * unchanged; this package's only per-instance glue is a WeakMap keyed by handle.
10
+ */ export function createMutex() {
11
+ let chain = Promise.resolve();
12
+ const noop = ()=>{};
13
+ return {
14
+ run (fn) {
15
+ const result = chain.then(fn, fn);
16
+ chain = result.then(noop, noop);
17
+ return result;
18
+ }
19
+ };
20
+ }
@@ -0,0 +1,71 @@
1
+ import type { GroupContextExtension, IncomingMessageAction, ProposalWithSender } from 'ts-mls';
2
+ import type { RosterState } from './roster.js';
3
+ /**
4
+ * Everything the receiving-side gate needs, resolved by the caller. Pure: no
5
+ * group handle, no I/O. `didOfLeaf` maps a pre-commit ratchet-tree leaf index to
6
+ * its member DID (undefined for an empty or unresolvable leaf).
7
+ * `currentExtensions` is the pre-commit GroupContext extension list, the baseline
8
+ * the group-context-extensions rule pins. `externalCommitDID` is the DID resolved
9
+ * from an external commit's UpdatePath leaf (precomputed by the caller); undefined
10
+ * for a non-external commit.
11
+ */
12
+ export type CommitPolicyContext = {
13
+ /** Roster before this commit applies. Judges every proposal sender's authority:
14
+ * a promotion riding this same commit does not grant its subject commit authority. */
15
+ baseRoster: RosterState;
16
+ /** Roster after foldEnvelope applies this commit's group.role entries. Judges the
17
+ * removed target: a Remove of a leaf still `admin` here carried no demotion and is rejected. */
18
+ candidateRoster: RosterState;
19
+ didOfLeaf: (leafIndex: number) => string | undefined;
20
+ /** The pre-commit GroupContext extension list. A group_context_extensions commit
21
+ * may change nothing in it but the ledger_head entry. */
22
+ currentExtensions: Array<GroupContextExtension>;
23
+ /** The head extension bytes this commit must install: the current head extended by
24
+ * the commit's envelope entry ids, in envelope order. Equals the current head when
25
+ * the commit enacts nothing, so a commit that moves the head without enacting
26
+ * anything is rejected too. */
27
+ expectedHeadExtensionData: Uint8Array;
28
+ /** Whether the commit's envelope names any entries. */
29
+ commitEnactsEntries: boolean;
30
+ externalCommitDID?: string;
31
+ };
32
+ /** A commit or standalone proposal handed to the gate, matching the ts-mls callback shape. */
33
+ type IncomingMessage = {
34
+ kind: 'commit';
35
+ senderLeafIndex: number | undefined;
36
+ proposals: Array<ProposalWithSender>;
37
+ } | {
38
+ kind: 'proposal';
39
+ proposal: ProposalWithSender;
40
+ };
41
+ /**
42
+ * Pure receiving-side commit policy. Given the resolved context, decides whether
43
+ * an incoming commit or standalone proposal is admissible. Never throws.
44
+ *
45
+ * Per proposal the effective sender is the proposal's own `senderLeafIndex` when
46
+ * present, else the committer's — a commit may carry by-reference proposals
47
+ * authored by other members, so checking only the committer would let an admin
48
+ * launder a member's Remove. A commit is accepted only when every proposal
49
+ * passes its row; the first failing proposal rejects the whole commit. A commit
50
+ * with no proposals is a key rotation any member may make. When any proposal is
51
+ * an `external_init`, the whole commit is judged by the external-init rule rather
52
+ * than the per-proposal loop.
53
+ *
54
+ * One rule is not a proposal's own: a commit that enacts ledger entries must carry
55
+ * a group-context-extensions proposal, or it would enact entries without moving the
56
+ * head, and the head would stop covering the ledger.
57
+ */
58
+ export declare function defaultCommitPolicy(incoming: IncomingMessage, context: CommitPolicyContext): IncomingMessageAction;
59
+ /**
60
+ * Thrown by the caller's resolver path when the entry bodies an envelope names
61
+ * cannot be resolved from the ledger. Carries the unresolved ids. Defined here
62
+ * because it belongs to the commit-policy resolution boundary, but it is never
63
+ * thrown by {@link defaultCommitPolicy}, which is pure and total.
64
+ */
65
+ export declare class MissingLedgerEntriesError extends Error {
66
+ #private;
67
+ constructor(ids: Array<string>);
68
+ /** The entry ids named by the envelope that could not be resolved. */
69
+ get ids(): Array<string>;
70
+ }
71
+ export {};