@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/README.md CHANGED
@@ -1,16 +1,28 @@
1
1
  # @kumiai/mls
2
2
 
3
- Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](https://github.com/LukaJCB/ts-mls) with DID-based capabilities, giving every member a `MemberCredential` that ties their MLS leaf to a signed capability chain.
3
+ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](https://github.com/LukaJCB/ts-mls) with DID-based identity and a signed control ledger, giving every member a `MemberCredential` that ties their MLS leaf to their DID, and a group-wide roster that decides who may add, remove, and rotate.
4
4
 
5
5
  ## Capabilities
6
6
 
7
- - `createGroup` — admin creates a new group with themselves as sole member
8
- - `createInvite` + `commitInvite` — admin delegates a capability and produces the MLS Commit + Welcome
9
- - `processWelcome` — invitee joins after validating the capability chain
10
- - `removeMember` — admin evicts a leaf and rotates keys
11
- - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState`
7
+ - `createGroup` — creator opens a new group as its sole member and first admin
8
+ - `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome
9
+ - `processWelcome` — invitee joins after folding the ledger the invite carries and checking its head
10
+ - `commitLedgerEntries` — an admin promotes or demotes by committing signed `group.role` entries
11
+ - `removeMember` — an admin evicts a leaf and rotates keys
12
+ - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState` and the stored ledger tokens
12
13
  - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
13
14
 
15
+ ## Authority model
16
+
17
+ Authority is a **roster**, folded from a signed **control ledger** and rooted at a genesis anchor installed in the GroupContext when the group is created. There is no capability chain: a member's right to act is decided by the roster every peer computes independently, not by a token the member carries.
18
+
19
+ - **The ledger is an ordered log of enactments.** Each entry is a token signed by its issuer (a `group.role` entry names a subject DID and grants `admin` or `member`). The log is replayable and position-dependent: the same claim recurring later is meaningful — a demotion back to a previously-held role is exactly that.
20
+ - **The roster is the fold.** `foldRoster` applies each entry only if its issuer was an admin *in the state so far, at that entry's own position*. A token signed by a since-demoted admin is dead paper whoever carries it. The fold starts from the anchor (`{creator: 'admin'}`), so no one can promote themselves by padding an invite.
21
+ - **Enactment is admin-only, structurally.** Entries reach the group inside a commit, and a commit that enacts entries must extend the GroupContext ledger-head extension by exactly those ids, in order. Moving the head needs a `group_context_extensions` proposal, which needs admin. A plain member's only permitted proposal is `update`; attaching an envelope to it fails for want of a head move. The write path runs the receivers' own fold before authoring, so it never builds a commit the group would reject.
22
+ - **`GroupPermission` is `'admin' | 'member'` — there is no read-only tier.** It cannot exist: a group member holds the epoch secrets, which is what membership *is* in MLS. A `read` member derives the same application keys as any other member and can decrypt everything. Read-only observers do not belong in the group; gate them outside MLS, at the transport or storage layer.
23
+
24
+ The invite carries the full ordered ledger plus the invitee's new role entry last, so a joiner folds the same roster the group holds and cannot fork from a role change made before it joined.
25
+
14
26
  ## External rejoin (stale device recovery)
15
27
 
16
28
  Each device owns its MLS leaf and ratchet state. A device that stays offline long enough for the group to advance epochs (adds, removes, key rotations) can no longer decrypt current application messages. Replaying every missed commit sequentially is expensive and may be impossible if intermediate commits are no longer available.
@@ -38,7 +50,7 @@ const { commitMessage, group } = await joinGroupExternal({
38
50
 
39
51
  ### Trust model
40
52
 
41
- Stale rejoin reuses the caller's previously accepted credential. The capability chain is **not** re-validated during `joinGroupExternal` — we trust what the caller already stored from `processWelcome`. Existing members validate the commit sender's identity as part of normal MLS processing.
53
+ An external commit is enforced as a **resync of an existing roster member**, never a new join. Every receiver runs the commit policy on it: the committing DID (resolved from the commit's own UpdatePath leaf credential) must be in the roster, and the commit's proposals must be exactly one `external_init` plus one `remove` of the leaf whose DID equals that committer — nothing else. A stranger in no roster who obtains a leaked `GroupInfo` is rejected; a legitimate member rejoining is accepted. New members never arrive this way — they join through Welcome.
42
54
 
43
55
  ### Transport
44
56
 
@@ -55,9 +67,9 @@ Stale rejoin reuses the caller's previously accepted credential. The capability
55
67
 
56
68
  ### ⚠️ Security: removal is not revocation
57
69
 
58
- MLS has no cryptographic member revocation. A device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed from the group**, provided it can still obtain a fresh `GroupInfo`. Consumers must assume a removed member can rejoin until capability-level revocation lands in a follow-up spec. Mitigations available today:
70
+ MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `group.role` grant, which lives in the roster independently of MLS membership. So a device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed** — its DID is still a roster member, so the external-commit policy admits the resync — provided it can still obtain a fresh `GroupInfo`. (The policy stops *strangers*, who are in no roster; it does not stop a removed member.) Consumers must assume a removed member can rejoin until role revocation lands in a follow-up spec. Mitigations available today:
59
71
 
60
72
  - Rotate the group: create a new group, migrate non-removed members via fresh invites, abandon the old group.
61
73
  - Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
62
74
 
63
- The follow-up capability-revocation work will introduce signed `RevokeMember` tokens synced via a GroupContext extension, with member-side enforcement in `processMessage`.
75
+ The follow-up revocation work will introduce a ledger entry that removes a DID's role from the roster, synced through the same GroupContext ledger-head extension the roster already rides. Once a revoked DID is no longer a roster member, the external-commit policy rejects its resync exactly as it rejects a stranger today.
@@ -0,0 +1,87 @@
1
+ import type { Capabilities, GroupContextExtension } from 'ts-mls';
2
+ import type { GroupHandle } from './group.js';
3
+ /**
4
+ * MLS GroupContext extension type carrying the genesis anchor. A uint16 outside
5
+ * the MLS default extension types (1–5) and clear of every reserved GREASE
6
+ * value, so it can never collide with a ts-mls built-in or a probing extension.
7
+ */
8
+ export declare const GROUP_ANCHOR_EXTENSION_TYPE = 61696;
9
+ /**
10
+ * MLS GroupContext extension type carrying the control-ledger head. Its update
11
+ * logic arrives in a later step, but its type is reserved and advertised from
12
+ * the outset (see {@link controlCapabilities}) so an anchored group can later
13
+ * grow a head without every member's leaf being rejected.
14
+ */
15
+ export declare const LEDGER_HEAD_EXTENSION_TYPE = 61697;
16
+ /**
17
+ * Genesis anchor baked into the MLS GroupContext at group creation: the creator
18
+ * DID is the epoch-0 admin. It survives every epoch and is authenticated by the
19
+ * GroupInfo signature, so every joiner reads the same value. Treated as
20
+ * immutable for the lifetime of the group.
21
+ */
22
+ export type GroupAnchor = {
23
+ creatorDID: string;
24
+ version: number;
25
+ /**
26
+ * Opaque consumer payload, written once at group creation. `@kumiai/mls`
27
+ * never reads or interprets it — it is any JSON value the consumer chooses. A
28
+ * consumer holding raw bytes encodes them to a JSON-safe form (e.g. base64)
29
+ * itself; the anchor container is already JSON, so it does not double-encode.
30
+ * Kubun stores its recovery seed here.
31
+ */
32
+ app?: unknown;
33
+ };
34
+ /** Serialize an anchor to its GroupContext extension bytes. */
35
+ export declare function encodeGroupAnchor(anchor: GroupAnchor): Uint8Array;
36
+ /**
37
+ * Tolerant decode: returns null on malformed bytes or wrong shape, never
38
+ * throws. `creatorDID` must be a string and `version` a number; `app` is
39
+ * optional and any JSON value, so an anchor without it is valid, not malformed.
40
+ * (A consumer that requires a specific `app` shape enforces that in its own
41
+ * decode of `app`, not here.)
42
+ */
43
+ export declare function decodeGroupAnchor(bytes: Uint8Array): GroupAnchor | null;
44
+ /** Build the genesis-anchor GroupContext extension for an anchor value. */
45
+ export declare function buildGroupAnchorExtension(anchor: GroupAnchor): GroupContextExtension;
46
+ /** Build the anchor extension for a freshly created group at the current version. */
47
+ export declare function buildCurrentGroupAnchorExtension(creatorDID: string, app?: unknown): GroupContextExtension;
48
+ /**
49
+ * Leaf-node capabilities advertising both control GroupContext extension types
50
+ * (genesis anchor and ledger head). RFC 9420 requires every member leaf to
51
+ * advertise each custom GroupContext extension type, or `commitInvite` rejects
52
+ * the added leaf. Both types are advertised from the outset — even before the
53
+ * ledger head carries data — so an anchored group can later grow a head without
54
+ * re-admitting members. Pass these at both `createGroup` (creator leaf) and
55
+ * `createKeyPackageBundle` (invitee leaf) so a control group can be joined.
56
+ *
57
+ * Idempotent: each type appears exactly once even if the defaults already carry
58
+ * it.
59
+ */
60
+ export declare function controlCapabilities(): Capabilities;
61
+ /**
62
+ * The anchor's raw GroupContext extension, exactly as it sits in the group, or
63
+ * null when genuinely absent. Unlike {@link readGroupAnchor} this does not
64
+ * decode — it is the source of the verbatim bytes a future group-context-
65
+ * extensions (GCE) proposal must copy.
66
+ *
67
+ * A GCE proposal replaces the *entire* GroupContext extension list, so every
68
+ * ledger-head update must re-include the anchor unchanged, and the receiving
69
+ * commit policy byte-compares the proposed anchor's `extensionData` against its
70
+ * own. Re-encoding a decoded {@link GroupAnchor} instead of copying these bytes
71
+ * can make that comparison fail on identical content (JSON key order, number
72
+ * formatting, dropped `undefined` keys) — an intermittent failure that looks
73
+ * exactly like an anchor-tampering attack. The decoded anchor is for reading;
74
+ * these bytes are for round-tripping.
75
+ */
76
+ export declare function readGroupAnchorExtension(handle: GroupHandle): GroupContextExtension | null;
77
+ /**
78
+ * Read and decode the genesis anchor from a group handle. Returns null only
79
+ * when the anchor extension is genuinely absent. A present-but-undecodable
80
+ * extension is corruption, not absence, and throws — so a control gate reads it
81
+ * as "anchor unreadable" and fails closed rather than silently downgrading. (The
82
+ * anchor is written once at creation and authenticated by the GroupInfo
83
+ * signature, so this is a corruption guard, not a forgery path.) For bytes to
84
+ * copy into a proposal, use {@link readGroupAnchorExtension}, never a re-encode
85
+ * of this result.
86
+ */
87
+ export declare function readGroupAnchor(handle: GroupHandle): GroupAnchor | null;
package/lib/anchor.js ADDED
@@ -0,0 +1,124 @@
1
+ import { defaultCapabilities, makeCustomExtension } from 'ts-mls';
2
+ /**
3
+ * MLS GroupContext extension type carrying the genesis anchor. A uint16 outside
4
+ * the MLS default extension types (1–5) and clear of every reserved GREASE
5
+ * value, so it can never collide with a ts-mls built-in or a probing extension.
6
+ */ export const GROUP_ANCHOR_EXTENSION_TYPE = 0xf100;
7
+ /**
8
+ * MLS GroupContext extension type carrying the control-ledger head. Its update
9
+ * logic arrives in a later step, but its type is reserved and advertised from
10
+ * the outset (see {@link controlCapabilities}) so an anchored group can later
11
+ * grow a head without every member's leaf being rejected.
12
+ */ export const LEDGER_HEAD_EXTENSION_TYPE = 0xf101;
13
+ const CURRENT_VERSION = 1;
14
+ const encoder = new TextEncoder();
15
+ const decoder = new TextDecoder();
16
+ /** Serialize an anchor to its GroupContext extension bytes. */ export function encodeGroupAnchor(anchor) {
17
+ return encoder.encode(JSON.stringify(anchor));
18
+ }
19
+ /**
20
+ * Tolerant decode: returns null on malformed bytes or wrong shape, never
21
+ * throws. `creatorDID` must be a string and `version` a number; `app` is
22
+ * optional and any JSON value, so an anchor without it is valid, not malformed.
23
+ * (A consumer that requires a specific `app` shape enforces that in its own
24
+ * decode of `app`, not here.)
25
+ */ export function decodeGroupAnchor(bytes) {
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(decoder.decode(bytes));
29
+ } catch {
30
+ return null;
31
+ }
32
+ if (parsed == null || typeof parsed !== 'object') {
33
+ return null;
34
+ }
35
+ const record = parsed;
36
+ if (typeof record.creatorDID !== 'string' || typeof record.version !== 'number') {
37
+ return null;
38
+ }
39
+ const anchor = {
40
+ creatorDID: record.creatorDID,
41
+ version: record.version
42
+ };
43
+ if ('app' in record && record.app !== undefined) {
44
+ anchor.app = record.app;
45
+ }
46
+ return anchor;
47
+ }
48
+ /** Build the genesis-anchor GroupContext extension for an anchor value. */ export function buildGroupAnchorExtension(anchor) {
49
+ return makeCustomExtension({
50
+ extensionType: GROUP_ANCHOR_EXTENSION_TYPE,
51
+ extensionData: encodeGroupAnchor(anchor)
52
+ });
53
+ }
54
+ /** Build the anchor extension for a freshly created group at the current version. */ export function buildCurrentGroupAnchorExtension(creatorDID, app) {
55
+ return buildGroupAnchorExtension({
56
+ creatorDID,
57
+ version: CURRENT_VERSION,
58
+ app
59
+ });
60
+ }
61
+ /**
62
+ * Leaf-node capabilities advertising both control GroupContext extension types
63
+ * (genesis anchor and ledger head). RFC 9420 requires every member leaf to
64
+ * advertise each custom GroupContext extension type, or `commitInvite` rejects
65
+ * the added leaf. Both types are advertised from the outset — even before the
66
+ * ledger head carries data — so an anchored group can later grow a head without
67
+ * re-admitting members. Pass these at both `createGroup` (creator leaf) and
68
+ * `createKeyPackageBundle` (invitee leaf) so a control group can be joined.
69
+ *
70
+ * Idempotent: each type appears exactly once even if the defaults already carry
71
+ * it.
72
+ */ export function controlCapabilities() {
73
+ const base = defaultCapabilities();
74
+ const extensions = new Set(base.extensions);
75
+ extensions.add(GROUP_ANCHOR_EXTENSION_TYPE);
76
+ extensions.add(LEDGER_HEAD_EXTENSION_TYPE);
77
+ return {
78
+ ...base,
79
+ extensions: [
80
+ ...extensions
81
+ ]
82
+ };
83
+ }
84
+ function findAnchorExtension(handle) {
85
+ return handle.state.groupContext.extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
86
+ }
87
+ /**
88
+ * The anchor's raw GroupContext extension, exactly as it sits in the group, or
89
+ * null when genuinely absent. Unlike {@link readGroupAnchor} this does not
90
+ * decode — it is the source of the verbatim bytes a future group-context-
91
+ * extensions (GCE) proposal must copy.
92
+ *
93
+ * A GCE proposal replaces the *entire* GroupContext extension list, so every
94
+ * ledger-head update must re-include the anchor unchanged, and the receiving
95
+ * commit policy byte-compares the proposed anchor's `extensionData` against its
96
+ * own. Re-encoding a decoded {@link GroupAnchor} instead of copying these bytes
97
+ * can make that comparison fail on identical content (JSON key order, number
98
+ * formatting, dropped `undefined` keys) — an intermittent failure that looks
99
+ * exactly like an anchor-tampering attack. The decoded anchor is for reading;
100
+ * these bytes are for round-tripping.
101
+ */ export function readGroupAnchorExtension(handle) {
102
+ return findAnchorExtension(handle) ?? null;
103
+ }
104
+ /**
105
+ * Read and decode the genesis anchor from a group handle. Returns null only
106
+ * when the anchor extension is genuinely absent. A present-but-undecodable
107
+ * extension is corruption, not absence, and throws — so a control gate reads it
108
+ * as "anchor unreadable" and fails closed rather than silently downgrading. (The
109
+ * anchor is written once at creation and authenticated by the GroupInfo
110
+ * signature, so this is a corruption guard, not a forgery path.) For bytes to
111
+ * copy into a proposal, use {@link readGroupAnchorExtension}, never a re-encode
112
+ * of this result.
113
+ */ export function readGroupAnchor(handle) {
114
+ const extension = findAnchorExtension(handle);
115
+ if (extension == null) {
116
+ return null;
117
+ }
118
+ const data = extension.extensionData;
119
+ const anchor = data instanceof Uint8Array ? decodeGroupAnchor(data) : null;
120
+ if (anchor == null) {
121
+ throw new Error('group anchor extension present but could not be decoded');
122
+ }
123
+ return anchor;
124
+ }
@@ -1,15 +1,10 @@
1
- import type { CapabilityToken } from '@kokuin/capability';
2
- import { type DIDCache, type SignedToken } from '@kokuin/token';
3
- import type { GroupPermission } from './capability.js';
1
+ import { type DIDCache } from '@kokuin/token';
4
2
  /**
5
- * Local member state (never serialized to the MLS leaf). Tracks the capability
6
- * chain proving group membership.
3
+ * Local member state (never serialized to the MLS leaf). `id` is the member's own
4
+ * DID; `groupID` names the group the handle belongs to.
7
5
  */
8
6
  export type MemberCredential = {
9
7
  id: string;
10
- capabilityChain: Array<string>;
11
- capability: CapabilityToken;
12
- permission: GroupPermission;
13
8
  groupID: string;
14
9
  };
15
10
  /**
@@ -37,7 +32,3 @@ export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCre
37
32
  * No-op for did:key.
38
33
  */
39
34
  export declare function populateCacheFromCredential(parsed: MLSCredentialIdentity, cache: DIDCache): Promise<void>;
40
- /**
41
- * Extracts the permission level from a capability token's actions.
42
- */
43
- export declare function extractPermission(token: SignedToken): GroupPermission;
package/lib/credential.js CHANGED
@@ -38,16 +38,3 @@ export function parseMLSCredentialIdentity(identity) {
38
38
  }
39
39
  await cache.set(shortForm, doc);
40
40
  }
41
- /**
42
- * Extracts the permission level from a capability token's actions.
43
- */ export function extractPermission(token) {
44
- const payload = token.payload;
45
- const actions = Array.isArray(payload.act) ? payload.act : [
46
- payload.act
47
- ];
48
- if (actions.includes('*')) return 'admin';
49
- if (actions.includes('admin')) return 'admin';
50
- if (actions.includes('member')) return 'member';
51
- if (actions.includes('read')) return 'read';
52
- throw new Error('Invalid capability: no recognized permission level');
53
- }
@@ -0,0 +1,35 @@
1
+ import type { FoldInput } from './fold.js';
2
+ import type { VerifiedLedgerEntry } from './ledger.js';
3
+ import { type RosterState } from './roster.js';
4
+ /**
5
+ * The outcome of folding an envelope's control entries. On accept: the candidate
6
+ * roster (base ∪ this envelope's group.role entries) and the non-group entries to
7
+ * surface to the consumer, in envelope order. On reject: a reason and the offending
8
+ * entry id. A rejection is a value — the caller turns it into a commit rejection.
9
+ */
10
+ export type EnvelopeFoldResult = {
11
+ ok: true;
12
+ roster: RosterState;
13
+ surfaced: Array<VerifiedLedgerEntry>;
14
+ } | {
15
+ ok: false;
16
+ reason: string;
17
+ entryID: string;
18
+ };
19
+ /**
20
+ * Fold an envelope's verified entries against a base roster, enforcing that every
21
+ * entry is admin-authored in state-so-far. Pure, never throws.
22
+ *
23
+ * The strict, commit-side counterpart to {@link foldRoster}: where the roster fold
24
+ * silently drops an unauthorized or unrelated entry (correct for hostile ingest),
25
+ * a commit envelope must reject the moment anything is off, so `ledger_head` never
26
+ * covers an entry the ledger does not hold.
27
+ *
28
+ * One pass, one rule. `baseRoster` is the state folded from the ledger the handle
29
+ * already holds; this reasons only about *this* envelope's new entries, using it as
30
+ * the starting state-so-far and mutating a copy as `group.role` entries apply. Every
31
+ * entry's issuer must be an admin at its own position — the universal invariant that
32
+ * subsumes `group.role`'s own authority rule. State-so-far, not a pre-commit
33
+ * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
34
+ */
35
+ export declare function foldEnvelope(baseRoster: RosterState, entries: Array<FoldInput>, groupID: string): EnvelopeFoldResult;
@@ -0,0 +1,86 @@
1
+ import { adminCount, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
2
+ const GROUP_TYPE_PREFIX = 'group.';
3
+ function isRoleValue(value) {
4
+ return value === 'admin' || value === 'member';
5
+ }
6
+ /**
7
+ * Fold an envelope's verified entries against a base roster, enforcing that every
8
+ * entry is admin-authored in state-so-far. Pure, never throws.
9
+ *
10
+ * The strict, commit-side counterpart to {@link foldRoster}: where the roster fold
11
+ * silently drops an unauthorized or unrelated entry (correct for hostile ingest),
12
+ * a commit envelope must reject the moment anything is off, so `ledger_head` never
13
+ * covers an entry the ledger does not hold.
14
+ *
15
+ * One pass, one rule. `baseRoster` is the state folded from the ledger the handle
16
+ * already holds; this reasons only about *this* envelope's new entries, using it as
17
+ * the starting state-so-far and mutating a copy as `group.role` entries apply. Every
18
+ * entry's issuer must be an admin at its own position — the universal invariant that
19
+ * subsumes `group.role`'s own authority rule. State-so-far, not a pre-commit
20
+ * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
21
+ */ export function foldEnvelope(baseRoster, entries, groupID) {
22
+ let workingRoster = {
23
+ roles: new Map(baseRoster.roles)
24
+ };
25
+ const surfaced = [];
26
+ for (const { verified, entryID } of entries){
27
+ const { entry, issuer } = verified;
28
+ // An entry signed for another group is a replay, even though it verified.
29
+ if (entry.groupID !== groupID) {
30
+ return {
31
+ ok: false,
32
+ reason: 'cross-group entry',
33
+ entryID
34
+ };
35
+ }
36
+ // The universal invariant: the issuer must be an admin in state-so-far.
37
+ if (workingRoster.roles.get(issuer) !== 'admin') {
38
+ return {
39
+ ok: false,
40
+ reason: `non-admin issuer '${issuer}'`,
41
+ entryID
42
+ };
43
+ }
44
+ if (entry.type === ROLE_ENTRY_TYPE) {
45
+ if (!isRoleValue(entry.value)) {
46
+ return {
47
+ ok: false,
48
+ reason: 'invalid role value',
49
+ entryID
50
+ };
51
+ }
52
+ const roleEntry = {
53
+ issuer,
54
+ entry: {
55
+ ...entry,
56
+ value: entry.value
57
+ }
58
+ };
59
+ workingRoster = roleReducer.apply(roleEntry, workingRoster);
60
+ // A group with zero admins can never again add, remove, promote, or demote.
61
+ if (adminCount(workingRoster) === 0) {
62
+ return {
63
+ ok: false,
64
+ reason: 'would empty the admin set',
65
+ entryID
66
+ };
67
+ }
68
+ continue;
69
+ }
70
+ // `group.*` is reserved for @kumiai/mls; an unknown one fails closed.
71
+ if (entry.type.startsWith(GROUP_TYPE_PREFIX)) {
72
+ return {
73
+ ok: false,
74
+ reason: 'unknown group.* type',
75
+ entryID
76
+ };
77
+ }
78
+ // Notarized (verified, admin-authored, group-scoped) and handed on unread.
79
+ surfaced.push(verified);
80
+ }
81
+ return {
82
+ ok: true,
83
+ roster: workingRoster,
84
+ surfaced
85
+ };
86
+ }
@@ -0,0 +1,53 @@
1
+ /** The only control-envelope version this build interprets. */
2
+ export declare const CONTROL_ENVELOPE_VERSION = 1;
3
+ /** Cleartext on the wire; authenticated by the AEAD AAD and the FramedContent signature. */
4
+ export type ControlEnvelope = {
5
+ /** Unknown version ⇒ reject the commit. A client that cannot interpret
6
+ * authority-bearing data must not accept a commit that depends on it. */
7
+ v: 1;
8
+ /** Content-addressed ids of the control-ledger entries this commit enacts, in
9
+ * fold order. Every entry is admin-issued and covered by `ledger_head`.
10
+ * Absent when the commit writes no ledger entries. */
11
+ entries?: Array<string>;
12
+ /** Opaque consumer payload. Never verified, never ordered, never chained.
13
+ * A JSON value, not bytes — the container is already JSON, so a byte field
14
+ * would be base64 in JSON. `unknown`, not `any`: the library must not be
15
+ * able to read it by accident. */
16
+ app?: unknown;
17
+ };
18
+ /**
19
+ * The outcome of decoding arbitrary `authenticatedData`. A rejection is a value,
20
+ * not a throw: the commit policy asks "valid or not" without a try/catch, because
21
+ * "this commit carries a control envelope I cannot interpret" is a normal outcome
22
+ * that maps to *reject the commit*, not a crash. `reason` is for logging, not
23
+ * control flow.
24
+ */
25
+ export type DecodeResult = {
26
+ ok: true;
27
+ envelope: ControlEnvelope;
28
+ } | {
29
+ ok: false;
30
+ reason: string;
31
+ };
32
+ /**
33
+ * Serialize an envelope to the bytes that ride in a commit's `authenticatedData`.
34
+ * JSON, matching the ledger-head container's discipline. Absent `entries`/`app`
35
+ * emit no key — an encode of `{ v: 1 }` carries neither `"entries"` nor `"app"`.
36
+ * These bytes are not byte-compared across peers, so a single canonical byte form
37
+ * is not required; only gratuitous non-determinism (undefined keys) is avoided.
38
+ */
39
+ export declare function encodeControlEnvelope(envelope: ControlEnvelope): Uint8Array;
40
+ /**
41
+ * Decode arbitrary `authenticatedData` bytes. NEVER throws. Returns either a
42
+ * usable envelope or a rejection the commit policy turns into a commit rejection.
43
+ *
44
+ * Zero-length bytes are not an error: an ordinary commit that enacts no ledger
45
+ * entries (a key rotation, an Update, a self-Remove, or a client predating this
46
+ * envelope) carries empty `authenticatedData` and decodes to a bare `{ v: 1 }`.
47
+ * Rejecting it would reject every ordinary commit.
48
+ *
49
+ * Everything else fails closed: non-UTF-8 bytes, malformed JSON, a non-object, a
50
+ * missing or non-`1` `v`, or `entries` present but not an array of strings all
51
+ * become a rejection. Unknown keys are tolerated and dropped.
52
+ */
53
+ export declare function decodeControlEnvelope(bytes: Uint8Array): DecodeResult;
@@ -0,0 +1,87 @@
1
+ /** The only control-envelope version this build interprets. */ export const CONTROL_ENVELOPE_VERSION = 1;
2
+ const utf8Encode = new TextEncoder();
3
+ const utf8Decode = new TextDecoder();
4
+ /**
5
+ * Serialize an envelope to the bytes that ride in a commit's `authenticatedData`.
6
+ * JSON, matching the ledger-head container's discipline. Absent `entries`/`app`
7
+ * emit no key — an encode of `{ v: 1 }` carries neither `"entries"` nor `"app"`.
8
+ * These bytes are not byte-compared across peers, so a single canonical byte form
9
+ * is not required; only gratuitous non-determinism (undefined keys) is avoided.
10
+ */ export function encodeControlEnvelope(envelope) {
11
+ const json = {
12
+ v: envelope.v
13
+ };
14
+ if (envelope.entries !== undefined) {
15
+ json.entries = envelope.entries;
16
+ }
17
+ if (envelope.app !== undefined) {
18
+ json.app = envelope.app;
19
+ }
20
+ return utf8Encode.encode(JSON.stringify(json));
21
+ }
22
+ function isStringArray(value) {
23
+ return Array.isArray(value) && value.every((entry)=>typeof entry === 'string');
24
+ }
25
+ /**
26
+ * Decode arbitrary `authenticatedData` bytes. NEVER throws. Returns either a
27
+ * usable envelope or a rejection the commit policy turns into a commit rejection.
28
+ *
29
+ * Zero-length bytes are not an error: an ordinary commit that enacts no ledger
30
+ * entries (a key rotation, an Update, a self-Remove, or a client predating this
31
+ * envelope) carries empty `authenticatedData` and decodes to a bare `{ v: 1 }`.
32
+ * Rejecting it would reject every ordinary commit.
33
+ *
34
+ * Everything else fails closed: non-UTF-8 bytes, malformed JSON, a non-object, a
35
+ * missing or non-`1` `v`, or `entries` present but not an array of strings all
36
+ * become a rejection. Unknown keys are tolerated and dropped.
37
+ */ export function decodeControlEnvelope(bytes) {
38
+ if (bytes.length === 0) {
39
+ return {
40
+ ok: true,
41
+ envelope: {
42
+ v: CONTROL_ENVELOPE_VERSION
43
+ }
44
+ };
45
+ }
46
+ let value;
47
+ try {
48
+ value = JSON.parse(utf8Decode.decode(bytes));
49
+ } catch {
50
+ return {
51
+ ok: false,
52
+ reason: 'control envelope is not valid JSON'
53
+ };
54
+ }
55
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
56
+ return {
57
+ ok: false,
58
+ reason: 'control envelope is not a JSON object'
59
+ };
60
+ }
61
+ const obj = value;
62
+ if (obj.v !== CONTROL_ENVELOPE_VERSION) {
63
+ return {
64
+ ok: false,
65
+ reason: `unsupported control envelope version: ${String(obj.v)}`
66
+ };
67
+ }
68
+ const envelope = {
69
+ v: CONTROL_ENVELOPE_VERSION
70
+ };
71
+ if ('entries' in obj) {
72
+ if (!isStringArray(obj.entries)) {
73
+ return {
74
+ ok: false,
75
+ reason: 'control envelope entries is not an array of strings'
76
+ };
77
+ }
78
+ envelope.entries = obj.entries;
79
+ }
80
+ if ('app' in obj) {
81
+ envelope.app = obj.app;
82
+ }
83
+ return {
84
+ ok: true,
85
+ envelope
86
+ };
87
+ }
package/lib/fold.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { GroupAnchor } from './anchor.js';
2
+ import type { VerifiedLedgerEntry } from './ledger.js';
3
+ /**
4
+ * A per-type projection over the control ledger. The fold stays free of any
5
+ * admin/circle semantics: a reducer owns its own initial state (derived from
6
+ * the genesis anchor), its authority rule, and its fold step, so a new ledger
7
+ * type plugs in as a parameter with zero edits to {@link foldLedger}.
8
+ */
9
+ export type LedgerReducer<TValue, TState> = {
10
+ /** Ledger entry `type` this reducer projects; entries of any other type are dropped. */
11
+ type: string;
12
+ /**
13
+ * Initial fold state, derived from the genesis anchor. The anchor is the
14
+ * authenticated epoch-0 root (e.g. the creator DID is the first admin), so
15
+ * seeding from it is what makes the very first claims evaluable.
16
+ */
17
+ seed(anchor: GroupAnchor): TState;
18
+ /** Is the verified issuer allowed to make this claim, given the state so far? */
19
+ verifyAuthority(verified: VerifiedLedgerEntry<TValue>, stateSoFar: TState): boolean;
20
+ /** Fold step: return the next state after applying an authorized claim. */
21
+ apply(verified: VerifiedLedgerEntry<TValue>, stateSoFar: TState): TState;
22
+ };
23
+ /**
24
+ * A verified entry paired with its content-addressed id. The id identifies the
25
+ * entry in drop notices. Order is the caller's responsibility — see
26
+ * {@link foldLedger}.
27
+ */
28
+ export type FoldInput<TValue = unknown> = {
29
+ verified: VerifiedLedgerEntry<TValue>;
30
+ entryID: string;
31
+ };
32
+ /** Why an entry was skipped during the fold, for an optional observer. */
33
+ export type FoldDrop = {
34
+ entryID: string;
35
+ type: string;
36
+ reason: string;
37
+ };
38
+ /**
39
+ * Replay the ledger into a single reducer's projection.
40
+ *
41
+ * Signatures are verified at ingest, not here — this fold evaluates AUTHORITY:
42
+ * whether each issuer was allowed to make its claim given the state accumulated
43
+ * from strictly-earlier entries. Evaluating against state-so-far (never the
44
+ * final state) is what makes rotation sound: a key authorized when it made a
45
+ * claim can be revoked later without retroactively invalidating that claim.
46
+ *
47
+ * Folds `entries` in exactly the order given — it imposes no order of its own.
48
+ * The caller supplies the total order (kumiai derives it from the authenticated
49
+ * epoch chain), so ordering lives with the caller, not the fold. Full replay
50
+ * only: it takes the whole entry set and folds it. There is no incremental
51
+ * apply, per-type watermark, or dependency entry point by design — a reducer
52
+ * whose authority reads another entry type cannot be driven safely by a
53
+ * per-type incremental applier, so the only fold entry point replays everything.
54
+ *
55
+ * The fold itself does not filter by `groupID`: the caller passes only entries
56
+ * for the group being folded, so a `groupID` mismatch is dropped by the caller
57
+ * before the fold, or by a reducer's own `type` / `verifyAuthority` check. No
58
+ * group logic lives here.
59
+ *
60
+ * Pure — no clock, no randomness, no I/O — and the input array is never mutated
61
+ * (nothing here writes to it, and there is no copy-to-sort). A claim of an
62
+ * unrelated type or one whose authority fails is dropped (never thrown) so a
63
+ * single bad entry can never abort the projection. Drops are silent unless an
64
+ * `onDrop` observer is supplied — the fold runs on every authority check, where
65
+ * authority-failed drops are expected, so the caller decides whether to surface
66
+ * them rather than the fold emitting to the console.
67
+ */
68
+ export declare function foldLedger<TValue, TState>(entries: Array<FoldInput<TValue>>, anchor: GroupAnchor, reducer: LedgerReducer<TValue, TState>, onDrop?: (drop: FoldDrop) => void): TState;