@kumiai/mls 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/lib/anchor.d.ts +10 -4
  2. package/lib/anchor.js +26 -2
  3. package/lib/authentication.d.ts +11 -14
  4. package/lib/authentication.js +127 -86
  5. package/lib/capability.d.ts +37 -0
  6. package/lib/capability.js +141 -0
  7. package/lib/device-proof.d.ts +1 -0
  8. package/lib/device-proof.js +8 -12
  9. package/lib/envelope-fold.d.ts +16 -1
  10. package/lib/envelope-fold.js +49 -9
  11. package/lib/errors.d.ts +18 -0
  12. package/lib/errors.js +33 -0
  13. package/lib/group-commit.d.ts +22 -35
  14. package/lib/group-commit.js +122 -103
  15. package/lib/group-context.d.ts +6 -2
  16. package/lib/group-context.js +11 -4
  17. package/lib/group-create.js +56 -11
  18. package/lib/group-credential.d.ts +3 -1
  19. package/lib/group-credential.js +17 -3
  20. package/lib/group-device.js +34 -21
  21. package/lib/group-handle.d.ts +21 -8
  22. package/lib/group-handle.js +207 -56
  23. package/lib/group-lifecycle.d.ts +32 -0
  24. package/lib/group-lifecycle.js +300 -0
  25. package/lib/group-membership.js +7 -3
  26. package/lib/group-welcome.d.ts +11 -2
  27. package/lib/group-welcome.js +113 -21
  28. package/lib/group.d.ts +2 -1
  29. package/lib/group.js +1 -0
  30. package/lib/history.d.ts +6 -0
  31. package/lib/history.js +26 -0
  32. package/lib/index.d.ts +10 -4
  33. package/lib/index.js +8 -2
  34. package/lib/lifecycle-proof.d.ts +24 -0
  35. package/lib/lifecycle-proof.js +193 -0
  36. package/lib/lifecycle.d.ts +44 -0
  37. package/lib/lifecycle.js +385 -0
  38. package/lib/policy.d.ts +20 -0
  39. package/lib/policy.js +7 -4
  40. package/lib/recovery-verdict.d.ts +43 -0
  41. package/lib/recovery-verdict.js +135 -0
  42. package/lib/recovery.d.ts +70 -0
  43. package/lib/recovery.js +110 -36
  44. package/lib/registry.d.ts +34 -7
  45. package/lib/registry.js +113 -15
  46. package/lib/roster.d.ts +1 -1
  47. package/lib/roster.js +2 -2
  48. package/lib/types.d.ts +13 -8
  49. package/package.json +4 -4
@@ -1,16 +1,16 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { generateKeyPackageWithKey, createGroup as mlsCreateGroup } from 'ts-mls';
3
- import { buildCurrentGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
3
+ import { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ import { verifyLeafCredential } from './authentication.js';
5
+ import { LeafBindingError } from './errors.js';
4
6
  import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
- import { makeMLSCredential } from './group-credential.js';
7
+ import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
6
8
  import { GroupHandle } from './group-handle.js';
7
9
  import { buildLedgerHeadExtension, genesisHead } from './head.js';
8
10
  /** Create a new MLS group. The identity becomes the sole member and admin. */ export async function createGroup(identity, groupID, options) {
9
- const context = await resolveMlsContext(options);
10
- // Every group is anchored at creation: creator is the epoch-0 admin, ledger head
11
- // starts at genesis. A caller-supplied anchor is left untouched (the caller owns
12
- // its contents); its `creatorDID` coupling to the creating identity is validated
13
- // below. A decode failure here is left to the fail-closed decode in the constructor.
11
+ assertBindingAuthorTime(options?.controller);
12
+ // A binding enriches a supplied anchor before genesis; standard anchor bytes stay untouched.
13
+ // Existing lifecycle fields must agree with the authored policy before the tree is validated.
14
14
  const extensions = [
15
15
  ...options?.extensions ?? []
16
16
  ];
@@ -21,15 +21,60 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
21
21
  if (suppliedAnchor != null && normalizeDID(suppliedAnchor.creatorDID) !== normalizeDID(identity.id)) {
22
22
  throw new Error(`createGroup: the anchor's creatorDID (${suppliedAnchor.creatorDID}) must be the creating identity (${identity.id})`);
23
23
  }
24
+ if (suppliedAnchor != null && suppliedAnchorData instanceof Uint8Array && options?.controller != null) {
25
+ const leafLifetime = options.leafLifetime ?? 86_400;
26
+ const trustedGrantLifetime = options.trustedGrantLifetime ?? 2_592_000;
27
+ if (suppliedAnchor.controller !== undefined && suppliedAnchor.controller !== options.controller.id) {
28
+ throw new LeafBindingError('controller-mismatch');
29
+ }
30
+ if (suppliedAnchor.leafLifetime !== undefined && suppliedAnchor.leafLifetime !== leafLifetime || suppliedAnchor.trustedGrantLifetime !== undefined && suppliedAnchor.trustedGrantLifetime !== trustedGrantLifetime) {
31
+ throw new Error('Lifecycle lifetime options must match the supplied anchor');
32
+ }
33
+ // Reading normally withholds future-version app payloads; authoring must preserve them.
34
+ const original = JSON.parse(new TextDecoder().decode(suppliedAnchorData));
35
+ extensions[extensions.indexOf(suppliedAnchorExtension)] = buildGroupAnchorExtension({
36
+ ...suppliedAnchor,
37
+ app: original.app,
38
+ controller: options.controller.id,
39
+ leafLifetime,
40
+ trustedGrantLifetime
41
+ });
42
+ }
43
+ }
44
+ if (suppliedAnchorExtension == null) {
45
+ extensions.push(options?.controller == null ? buildCurrentGroupAnchorExtension(identity.id) : buildGroupAnchorExtension({
46
+ creatorDID: identity.id,
47
+ version: 1,
48
+ controller: options.controller.id,
49
+ leafLifetime: options.leafLifetime ?? 86_400,
50
+ trustedGrantLifetime: options.trustedGrantLifetime ?? 2_592_000
51
+ }));
24
52
  }
25
- if (!extensions.some((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)) {
26
- extensions.push(buildCurrentGroupAnchorExtension(identity.id));
53
+ const anchorExtension = extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
54
+ const anchorData = anchorExtension?.extensionData;
55
+ const anchor = anchorData instanceof Uint8Array ? decodeGroupAnchor(anchorData) : null;
56
+ if (anchor == null) throw new Error('group anchor extension present but could not be decoded');
57
+ if (anchor.controller != null) {
58
+ if (options?.controller == null) throw new LeafBindingError('floating-refused');
59
+ if (normalizeDID(anchor.controller) !== normalizeDID(options.controller.id)) {
60
+ throw new LeafBindingError('controller-mismatch');
61
+ }
62
+ } else if (options?.controller != null) {
63
+ throw new LeafBindingError('controller-mismatch');
64
+ }
65
+ const context = await resolveMlsContext(options, anchor);
66
+ const mlsCredential = makeMLSCredential(identity, options?.controller);
67
+ if (options?.controller != null) {
68
+ await verifyLeafCredential(mlsCredential, identity.publicKey, {
69
+ leafLifetime: ()=>anchor.leafLifetime ?? 86_400,
70
+ trustedGrantLifetime: ()=>anchor.trustedGrantLifetime ?? 2_592_000
71
+ });
27
72
  }
28
73
  if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
29
74
  extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
30
75
  }
31
76
  const statePromise = generateKeyPackageWithKey({
32
- credential: makeMLSCredential(identity),
77
+ credential: mlsCredential,
33
78
  signatureKeyPair: {
34
79
  signKey: identity.privateKey,
35
80
  publicKey: identity.publicKey
@@ -64,7 +109,7 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
64
109
  };
65
110
  }
66
111
  export async function restoreGroup(params) {
67
- // Construction reseeds `{creator: 'admin'}` from the anchor in the restored state;
112
+ // Construction reseeds control authority from the anchor in the restored state;
68
113
  // an anchorless state throws (the same fail-closed guard).
69
114
  const group = new GroupHandle({
70
115
  state: params.state,
@@ -1,7 +1,9 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
2
  import { type Credential } from 'ts-mls';
3
+ import type { ControllerBinding } from './credential.js';
3
4
  import type { GroupOptions, KeyPackageBundle } from './types.js';
4
- export declare function makeMLSCredential(identity: OwnIdentity): Credential;
5
+ export declare function makeMLSCredential(identity: OwnIdentity, controller?: ControllerBinding): Credential;
6
+ export declare function assertBindingAuthorTime(controller?: ControllerBinding): void;
5
7
  /**
6
8
  * How long an ordinary, single-use key package stays valid, in days.
7
9
  *
@@ -1,8 +1,10 @@
1
- import { isPeer4 } from '@kokuin/token';
1
+ import { isPeer4, now } from '@kokuin/token';
2
2
  import { defaultCredentialTypes, generateKeyPackageWithKey, greaseExtensions, makeCustomExtension } from 'ts-mls';
3
3
  import { controlCapabilities } from './anchor.js';
4
+ import { verifyLeafCredential } from './authentication.js';
5
+ import { readCapability } from './capability.js';
4
6
  import { resolveMlsContext } from './group-context.js';
5
- export function makeMLSCredential(identity) {
7
+ export function makeMLSCredential(identity, controller) {
6
8
  const id = identity.id;
7
9
  const isPeer = isPeer4(id);
8
10
  if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
@@ -12,6 +14,7 @@ export function makeMLSCredential(identity) {
12
14
  v: 1,
13
15
  id
14
16
  };
17
+ if (controller != null) payload.controller = controller;
15
18
  if (isPeer) {
16
19
  payload.longForm = identity.longForm;
17
20
  }
@@ -20,6 +23,14 @@ export function makeMLSCredential(identity) {
20
23
  identity: new TextEncoder().encode(JSON.stringify(payload))
21
24
  };
22
25
  }
26
+ export function assertBindingAuthorTime(controller) {
27
+ if (controller == null) return;
28
+ const { iat, exp } = readCapability(controller.capability).payload;
29
+ const timestamp = now();
30
+ if (exp <= timestamp || iat > timestamp) {
31
+ throw new Error('Leaf capability is not valid at authoring time');
32
+ }
33
+ }
23
34
  /**
24
35
  * Shared key-package construction. An invitee leaf must advertise the control extension types or
25
36
  * ts-mls refuses to add it to an anchored group. An explicit `options.capabilities` override still
@@ -29,9 +40,12 @@ export function makeMLSCredential(identity) {
29
40
  * so `generateKeyPackageWithKey`'s own `params.extensions ?? greaseExtensions(...)` default still
30
41
  * applies for the ordinary path.
31
42
  */ async function buildBundle(identity, options, overrides = {}) {
43
+ assertBindingAuthorTime(options?.controller);
44
+ const credential = makeMLSCredential(identity, options?.controller);
45
+ if (options?.controller != null) await verifyLeafCredential(credential, identity.publicKey);
32
46
  const { cipherSuite } = await resolveMlsContext(options);
33
47
  const result = await generateKeyPackageWithKey({
34
- credential: makeMLSCredential(identity),
48
+ credential,
35
49
  signatureKeyPair: {
36
50
  signKey: identity.privateKey,
37
51
  publicKey: identity.publicKey
@@ -24,9 +24,12 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
24
24
  } : {}
25
25
  }
26
26
  });
27
- const result = await commitWithEntries(group, [], [
28
- token
29
- ], {
27
+ const result = await commitWithEntries({
28
+ group,
29
+ extraProposals: [],
30
+ enacted: [
31
+ token
32
+ ],
30
33
  requireAdmin: false
31
34
  });
32
35
  const newGroup = deriveGroup(group, result.newState);
@@ -55,9 +58,12 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
55
58
  capability: params.capability
56
59
  }
57
60
  });
58
- const result = await commitWithEntries(group, [], [
59
- token
60
- ], {
61
+ const result = await commitWithEntries({
62
+ group,
63
+ extraProposals: [],
64
+ enacted: [
65
+ token
66
+ ],
61
67
  requireAdmin: false
62
68
  });
63
69
  const newGroup = deriveGroup(group, result.newState);
@@ -103,11 +109,14 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
103
109
  keyPackage: params.keyPackage
104
110
  }
105
111
  };
106
- const result = await commitWithEntries(group, [
107
- addProposal
108
- ], [
109
- token
110
- ], {
112
+ const result = await commitWithEntries({
113
+ group,
114
+ extraProposals: [
115
+ addProposal
116
+ ],
117
+ enacted: [
118
+ token
119
+ ],
111
120
  ratchetTreeExtension: true,
112
121
  requireAdmin: false
113
122
  });
@@ -153,16 +162,18 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
153
162
  }
154
163
  }
155
164
  ];
156
- const result = await commitWithEntries(group, proposals, [
157
- token
158
- ], {
165
+ const result = await commitWithEntries({
166
+ group,
167
+ extraProposals: proposals,
168
+ enacted: [
169
+ token
170
+ ],
159
171
  requireAdmin: false
160
172
  });
161
173
  const newGroup = deriveGroup(group, result.newState);
162
- const enacted = await newGroup.applyLedgerEntries([
174
+ await newGroup.applyLedgerEntries([
163
175
  token
164
176
  ]);
165
- newGroup.emitControlEvents(enacted);
166
177
  return {
167
178
  commitMessage: encode(mlsMessageEncoder, result.commit),
168
179
  newGroup,
@@ -187,16 +198,18 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
187
198
  headDigest: params.headDigest
188
199
  }
189
200
  });
190
- const result = await commitWithEntries(group, [], [
191
- token
192
- ], {
201
+ const result = await commitWithEntries({
202
+ group,
203
+ extraProposals: [],
204
+ enacted: [
205
+ token
206
+ ],
193
207
  requireAdmin: false
194
208
  });
195
209
  const newGroup = deriveGroup(group, result.newState);
196
- const enacted = await newGroup.applyLedgerEntries([
210
+ await newGroup.applyLedgerEntries([
197
211
  token
198
212
  ]);
199
- newGroup.emitControlEvents(enacted);
200
213
  return {
201
214
  commitMessage: encode(mlsMessageEncoder, result.commit),
202
215
  newGroup,
@@ -4,6 +4,7 @@ import { type GroupAnchor } from './anchor.js';
4
4
  import { type GroupMember, type MemberCredential } from './credential.js';
5
5
  import { type LeafBinding } from './device-proof.js';
6
6
  import { type VerifiedLedgerEntry } from './ledger.js';
7
+ import { type CommitRejectionReason } from './lifecycle.js';
7
8
  import { type Mutex } from './mutex.js';
8
9
  import { type CommitPolicyContext } from './policy.js';
9
10
  import { type DeviceOp, type DeviceRegistry } from './registry.js';
@@ -15,6 +16,9 @@ export type GroupHandleEvents = {
15
16
  deviceRevoked: Array<{
16
17
  device: string;
17
18
  controller: string;
19
+ logPosition?: number;
20
+ reason?: 'reset';
21
+ cascadedFrom?: string;
18
22
  }>;
19
23
  controllerBeaconChanged: {
20
24
  controller: string;
@@ -22,13 +26,22 @@ export type GroupHandleEvents = {
22
26
  headDigest: string;
23
27
  };
24
28
  };
29
+ export type SendAdmission = {
30
+ epoch: number;
31
+ admissible: true;
32
+ } | {
33
+ epoch: number;
34
+ admissible: false;
35
+ reason: 'lapsed';
36
+ };
25
37
  /** The full emitter for a handle — module-internal, for deriveGroup to share it onward. */
26
38
  export declare function emitterOf(group: GroupHandle): EventEmitter<GroupHandleEvents>;
27
39
  /** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
28
40
  * commit. The handle is left at its pre-commit epoch. */
29
41
  export declare class CommitRejectedError extends Error {
30
42
  #private;
31
- constructor(proposals: Array<ProposalWithSender>, senderLeafIndex?: number);
43
+ constructor(proposals: Array<ProposalWithSender>, senderLeafIndex?: number, reason?: CommitRejectionReason);
44
+ get reason(): CommitRejectionReason;
32
45
  get proposals(): Array<ProposalWithSender>;
33
46
  get senderLeafIndex(): number | undefined;
34
47
  }
@@ -62,11 +75,15 @@ export type GroupHandleParams = {
62
75
  onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
63
76
  /** Shared event emitter; a derived handle inherits its parent's so subscriptions persist. */
64
77
  events?: EventEmitter<GroupHandleEvents>;
78
+ /** Defer authored control notifications until adoption. */
79
+ speculative?: boolean;
65
80
  };
66
81
  /** Mutable wrapper around MLS group state + Enkaku credential. */
67
82
  export declare class GroupHandle {
68
83
  #private;
69
84
  constructor(params: GroupHandleParams);
85
+ sendAdmission(): SendAdmission;
86
+ confirmAdopted(): void;
70
87
  get groupID(): string;
71
88
  get epoch(): bigint;
72
89
  get treeHash(): Uint8Array;
@@ -115,11 +132,10 @@ export declare class GroupHandle {
115
132
  }>;
116
133
  /**
117
134
  * @internal Fire notification events for the device entries just enacted in one operation.
118
- * Called from the commit path, from bootstrapLedger, and from the local write APIs — NEVER from
135
+ * Called after acceptance or adoption — NEVER from
119
136
  * the constructor or a fresh-join applyLedgerEntries, so a joiner is not replayed the whole
120
137
  * history as live events (it reads revokedDevices()/beaconOf for current state instead). Uses
121
- * `fire`: a throwing listener is swallowed and cannot break the fold. Reads controllerOf on the
122
- * POST-fold registry.
138
+ * `fire`: a throwing listener is swallowed and cannot break the fold. Reads the post-fold registry.
123
139
  */
124
140
  emitControlEvents(enacted: ReadonlyArray<VerifiedLedgerEntry>): void;
125
141
  /**
@@ -365,10 +381,7 @@ export declare class GroupHandle {
365
381
  persist?: (handle: GroupHandle) => Promise<void> | void;
366
382
  }): Promise<Uint8Array | null>;
367
383
  }
368
- /** Build the CommitPolicyContext both the receive gate and the send-side pending
369
- * filter judge against, so the two always agree. `entryIDs` are the ledger entry
370
- * ids this commit enacts (drives the expected head); `candidateRoster` is the
371
- * post-fold roster receivers install. */
384
+ /** Build policy inputs shared by author and receiver gates. Entry ids drive the expected head. */
372
385
  export declare function buildCommitPolicyContext(handle: GroupHandle, args: {
373
386
  baseRoster: RosterState;
374
387
  candidateRoster: RosterState;