@kumiai/mls 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +21 -9
  2. package/lib/anchor.d.ts +87 -0
  3. package/lib/anchor.js +124 -0
  4. package/lib/credential.d.ts +3 -12
  5. package/lib/credential.js +0 -13
  6. package/lib/envelope-fold.d.ts +35 -0
  7. package/lib/envelope-fold.js +86 -0
  8. package/lib/envelope.d.ts +53 -0
  9. package/lib/envelope.js +87 -0
  10. package/lib/fold.d.ts +68 -0
  11. package/lib/fold.js +53 -0
  12. package/lib/group-commit.d.ts +100 -0
  13. package/lib/group-commit.js +252 -0
  14. package/lib/group-context.d.ts +11 -0
  15. package/lib/group-context.js +33 -0
  16. package/lib/group-create.d.ts +19 -0
  17. package/lib/group-create.js +85 -0
  18. package/lib/group-credential.d.ts +6 -0
  19. package/lib/group-credential.js +39 -0
  20. package/lib/group-handle.d.ts +177 -0
  21. package/lib/group-handle.js +613 -0
  22. package/lib/group-info.d.ts +57 -0
  23. package/lib/group-info.js +85 -0
  24. package/lib/group-membership.d.ts +25 -0
  25. package/lib/group-membership.js +36 -0
  26. package/lib/group-welcome.d.ts +67 -0
  27. package/lib/group-welcome.js +178 -0
  28. package/lib/group.d.ts +7 -233
  29. package/lib/group.js +7 -653
  30. package/lib/head.d.ts +79 -0
  31. package/lib/head.js +150 -0
  32. package/lib/index.d.ts +11 -3
  33. package/lib/index.js +11 -3
  34. package/lib/ledger.d.ts +49 -0
  35. package/lib/ledger.js +67 -0
  36. package/lib/mutex.d.ts +14 -0
  37. package/lib/mutex.js +20 -0
  38. package/lib/policy.d.ts +71 -0
  39. package/lib/policy.js +191 -0
  40. package/lib/recovery.d.ts +227 -0
  41. package/lib/recovery.js +456 -0
  42. package/lib/roster.d.ts +45 -0
  43. package/lib/roster.js +72 -0
  44. package/lib/types.d.ts +31 -11
  45. package/package.json +2 -3
  46. package/lib/capability.d.ts +0 -47
  47. package/lib/capability.js +0 -79
package/lib/head.d.ts ADDED
@@ -0,0 +1,79 @@
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 recomputed head does not match the authenticated one — an inviter
12
+ * omitted, reordered, or truncated a ledger entry. Carries both heads for logging.
13
+ * Backs {@link assertHeadMatches}.
14
+ */
15
+ export declare class LedgerIncompleteError extends Error {
16
+ #private;
17
+ constructor(expected: Uint8Array, actual: Uint8Array);
18
+ /** The authenticated head from the group's GroupContext. Named apart from
19
+ * `expected`/`actual` on purpose: a test runner's diff formatter assigns those on
20
+ * any thrown Error, and a getter-only pair would turn an unexpected throw into a
21
+ * `Cannot set property` TypeError masking the real failure. */
22
+ get expectedHead(): Uint8Array;
23
+ /** The head recomputed from the entries the inviter supplied. */
24
+ get actualHead(): Uint8Array;
25
+ }
26
+ /** Genesis head for a group: `SHA256(DOMAIN ‖ groupID)`. Pure. The epoch-0 link of
27
+ * the chain, written into the GroupContext at group creation. */
28
+ export declare function genesisHead(groupID: string): Uint8Array;
29
+ /**
30
+ * Extend a head by a batch of entry ids, in envelope order: `head ← SHA256(head ‖
31
+ * frame(id))`, folded left to right. Pure, order- and length-sensitive (see
32
+ * {@link frameID}). An empty batch is a no-op — a commit with no entries does not
33
+ * move the head.
34
+ */
35
+ export declare function extendHead(head: Uint8Array, entryIDs: Array<string>): Uint8Array;
36
+ /**
37
+ * Recompute a head from genesis across an ordered id list. Pure. Composes with
38
+ * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
39
+ * `extendHead(extendHead(genesisHead(g), a), b)`, so a member can verify a head
40
+ * update by extending its own chain rather than refolding from genesis.
41
+ */
42
+ export declare function computeHead(groupID: string, entryIDs: Array<string>): Uint8Array;
43
+ /**
44
+ * Encode a head as LedgerHead extension data: one version byte
45
+ * (`LEDGER_HEAD_VERSION`) then the 32 digest bytes. A single canonical byte form —
46
+ * no JSON — so the commit policy can byte-compare it.
47
+ */
48
+ export declare function encodeLedgerHead(head: Uint8Array): Uint8Array;
49
+ /** Tolerant decode: null on any wrong length or unknown version byte, never throws.
50
+ * Only a version-`LEDGER_HEAD_VERSION`, `1 + 32`-byte buffer decodes. */
51
+ export declare function decodeLedgerHead(bytes: Uint8Array): LedgerHead | null;
52
+ /** Build the ledger-head GroupContext extension for a head digest. */
53
+ export declare function buildLedgerHeadExtension(head: Uint8Array): GroupContextExtension;
54
+ /**
55
+ * The head's raw GroupContext extension, verbatim, or null when genuinely absent.
56
+ * Never throws, never decodes — the source of the bytes a group-context-extensions
57
+ * proposal must copy and the commit policy byte-compares. Mirrors
58
+ * {@link readGroupAnchorExtension}.
59
+ */
60
+ export declare function readLedgerHeadExtension(handle: GroupHandle): GroupContextExtension | null;
61
+ /**
62
+ * Read and decode the ledger head. Null only when the extension is genuinely absent;
63
+ * a present-but-undecodable extension is corruption, not absence, and THROWS — a
64
+ * control gate fails closed rather than treating a tampered head as no head. For
65
+ * bytes to byte-compare or copy into a proposal use {@link readLedgerHeadExtension},
66
+ * never a re-encode of this result.
67
+ */
68
+ export declare function readLedgerHead(handle: GroupHandle): LedgerHead | null;
69
+ /**
70
+ * Whether a recomputed head equals the authenticated one — the predicate form of
71
+ * {@link assertHeadMatches}. Two entry points on one comparison: a fail-closed gate
72
+ * throws, a local invariant check reads the boolean.
73
+ */
74
+ export declare function headsMatch(expected: Uint8Array, actual: Uint8Array): boolean;
75
+ /**
76
+ * Assert a recomputed head matches the authenticated one, or throw
77
+ * {@link LedgerIncompleteError} carrying both. Returns for equal heads.
78
+ */
79
+ export declare function assertHeadMatches(expected: Uint8Array, actual: Uint8Array): void;
package/lib/head.js ADDED
@@ -0,0 +1,150 @@
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
+ /** Domain separator mixed into every genesis head so a head never collides with a
7
+ * raw SHA-256 of unrelated data (a bare group id, another protocol's digest of the
8
+ * same bytes). Fixed, non-empty, namespaced to this module and version. */ const DOMAIN = new TextEncoder().encode('kumiai/mls/ledger-head/v1');
9
+ const utf8 = new TextEncoder();
10
+ const SHA256_LENGTH = 32;
11
+ /**
12
+ * Thrown when a recomputed head does not match the authenticated one — an inviter
13
+ * omitted, reordered, or truncated a ledger entry. Carries both heads for logging.
14
+ * Backs {@link assertHeadMatches}.
15
+ */ export class LedgerIncompleteError extends Error {
16
+ #expected;
17
+ #actual;
18
+ constructor(expected, actual){
19
+ super('recomputed ledger head does not match the authenticated head');
20
+ this.name = 'LedgerIncompleteError';
21
+ this.#expected = expected;
22
+ this.#actual = actual;
23
+ }
24
+ /** The authenticated head from the group's GroupContext. Named apart from
25
+ * `expected`/`actual` on purpose: a test runner's diff formatter assigns those on
26
+ * any thrown Error, and a getter-only pair would turn an unexpected throw into a
27
+ * `Cannot set property` TypeError masking the real failure. */ get expectedHead() {
28
+ return this.#expected;
29
+ }
30
+ /** The head recomputed from the entries the inviter supplied. */ get actualHead() {
31
+ return this.#actual;
32
+ }
33
+ }
34
+ /**
35
+ * Length-frame one entry id: 4-byte big-endian length prefix before the id's UTF-8
36
+ * bytes. Makes id boundaries unambiguous, so `['ab','c']` and `['a','bc']` cannot
37
+ * fold to the same head.
38
+ */ function frameID(id) {
39
+ const bytes = utf8.encode(id);
40
+ const framed = new Uint8Array(4 + bytes.length);
41
+ const view = new DataView(framed.buffer);
42
+ view.setUint32(0, bytes.length, false);
43
+ framed.set(bytes, 4);
44
+ return framed;
45
+ }
46
+ /** Genesis head for a group: `SHA256(DOMAIN ‖ groupID)`. Pure. The epoch-0 link of
47
+ * the chain, written into the GroupContext at group creation. */ export function genesisHead(groupID) {
48
+ return sha256(concatBytes(DOMAIN, utf8.encode(groupID)));
49
+ }
50
+ /**
51
+ * Extend a head by a batch of entry ids, in envelope order: `head ← SHA256(head ‖
52
+ * frame(id))`, folded left to right. Pure, order- and length-sensitive (see
53
+ * {@link frameID}). An empty batch is a no-op — a commit with no entries does not
54
+ * move the head.
55
+ */ export function extendHead(head, entryIDs) {
56
+ let acc = head;
57
+ for (const id of entryIDs){
58
+ acc = sha256(concatBytes(acc, frameID(id)));
59
+ }
60
+ return acc;
61
+ }
62
+ /**
63
+ * Recompute a head from genesis across an ordered id list. Pure. Composes with
64
+ * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
65
+ * `extendHead(extendHead(genesisHead(g), a), b)`, so a member can verify a head
66
+ * update by extending its own chain rather than refolding from genesis.
67
+ */ export function computeHead(groupID, entryIDs) {
68
+ return extendHead(genesisHead(groupID), entryIDs);
69
+ }
70
+ /**
71
+ * Encode a head as LedgerHead extension data: one version byte
72
+ * (`LEDGER_HEAD_VERSION`) then the 32 digest bytes. A single canonical byte form —
73
+ * no JSON — so the commit policy can byte-compare it.
74
+ */ export function encodeLedgerHead(head) {
75
+ const bytes = new Uint8Array(1 + head.length);
76
+ bytes[0] = LEDGER_HEAD_VERSION;
77
+ bytes.set(head, 1);
78
+ return bytes;
79
+ }
80
+ /** Tolerant decode: null on any wrong length or unknown version byte, never throws.
81
+ * Only a version-`LEDGER_HEAD_VERSION`, `1 + 32`-byte buffer decodes. */ export function decodeLedgerHead(bytes) {
82
+ if (bytes.length !== 1 + SHA256_LENGTH || bytes[0] !== LEDGER_HEAD_VERSION) {
83
+ return null;
84
+ }
85
+ return {
86
+ v: LEDGER_HEAD_VERSION,
87
+ head: bytes.slice(1)
88
+ };
89
+ }
90
+ /** Build the ledger-head GroupContext extension for a head digest. */ export function buildLedgerHeadExtension(head) {
91
+ return makeCustomExtension({
92
+ extensionType: LEDGER_HEAD_EXTENSION_TYPE,
93
+ extensionData: encodeLedgerHead(head)
94
+ });
95
+ }
96
+ function findHeadExtension(handle) {
97
+ return handle.state.groupContext.extensions.find((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
98
+ }
99
+ /**
100
+ * The head's raw GroupContext extension, verbatim, or null when genuinely absent.
101
+ * Never throws, never decodes — the source of the bytes a group-context-extensions
102
+ * proposal must copy and the commit policy byte-compares. Mirrors
103
+ * {@link readGroupAnchorExtension}.
104
+ */ export function readLedgerHeadExtension(handle) {
105
+ return findHeadExtension(handle) ?? null;
106
+ }
107
+ /**
108
+ * Read and decode the ledger head. Null only when the extension is genuinely absent;
109
+ * a present-but-undecodable extension is corruption, not absence, and THROWS — a
110
+ * control gate fails closed rather than treating a tampered head as no head. For
111
+ * bytes to byte-compare or copy into a proposal use {@link readLedgerHeadExtension},
112
+ * never a re-encode of this result.
113
+ */ export function readLedgerHead(handle) {
114
+ const extension = findHeadExtension(handle);
115
+ if (extension == null) {
116
+ return null;
117
+ }
118
+ const data = extension.extensionData;
119
+ const head = data instanceof Uint8Array ? decodeLedgerHead(data) : null;
120
+ if (head == null) {
121
+ throw new Error('ledger head extension present but could not be decoded');
122
+ }
123
+ return head;
124
+ }
125
+ function bytesEqual(a, b) {
126
+ if (a.length !== b.length) {
127
+ return false;
128
+ }
129
+ for(let i = 0; i < a.length; i++){
130
+ if (a[i] !== b[i]) {
131
+ return false;
132
+ }
133
+ }
134
+ return true;
135
+ }
136
+ /**
137
+ * Whether a recomputed head equals the authenticated one — the predicate form of
138
+ * {@link assertHeadMatches}. Two entry points on one comparison: a fail-closed gate
139
+ * throws, a local invariant check reads the boolean.
140
+ */ export function headsMatch(expected, actual) {
141
+ return bytesEqual(expected, actual);
142
+ }
143
+ /**
144
+ * Assert a recomputed head matches the authenticated one, or throw
145
+ * {@link LedgerIncompleteError} carrying both. Returns for equal heads.
146
+ */ export function assertHeadMatches(expected, actual) {
147
+ if (!headsMatch(expected, actual)) {
148
+ throw new LedgerIncompleteError(expected, actual);
149
+ }
150
+ }
package/lib/index.d.ts CHANGED
@@ -1,9 +1,17 @@
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 ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
12
+ export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, 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 { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryRequest, RecoveryRequestError, type RecoveryRequestRejection, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, type SealedGroupInfoRejection, SealedLedgerError, type SealedLedgerRejection, type SealedReplyRejection, type SealGroupInfoParams, type SealLedgerParams, sealGroupInfo, sealLedger, type VerifiedRecoveryRequest, } from './recovery.js';
16
+ export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
9
17
  export type { GroupOptions, GroupSyncScope, Invite, KeyPackageBundle } from './types.js';
package/lib/index.js CHANGED
@@ -1,7 +1,15 @@
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, processWelcomeOnce, readMessageEpoch, removeMember, restoreGroup } from './group.js';
11
+ export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, 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 { createRecoveryRequest, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, RecoveryRequestError, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, SealedLedgerError, sealGroupInfo, sealLedger } from './recovery.js';
15
+ 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 {};