@kumiai/mls 0.12.3 → 0.13.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 (65) hide show
  1. package/lib/anchor.d.ts +6 -2
  2. package/lib/anchor.js +1 -1
  3. package/lib/authentication.d.ts +8 -3
  4. package/lib/authentication.js +139 -46
  5. package/lib/capability.js +16 -7
  6. package/lib/controller-ingest.d.ts +14 -2
  7. package/lib/controller-ingest.js +15 -8
  8. package/lib/controller-log.d.ts +12 -6
  9. package/lib/controller-log.js +29 -15
  10. package/lib/device-proof.d.ts +2 -1
  11. package/lib/device-proof.js +2 -1
  12. package/lib/embedded-resolver.d.ts +7 -2
  13. package/lib/embedded-resolver.js +16 -6
  14. package/lib/envelope-fold.d.ts +3 -2
  15. package/lib/envelope-fold.js +14 -6
  16. package/lib/fold.d.ts +17 -3
  17. package/lib/fold.js +9 -3
  18. package/lib/group-commit.d.ts +11 -2
  19. package/lib/group-commit.js +76 -32
  20. package/lib/group-context.d.ts +37 -3
  21. package/lib/group-context.js +65 -4
  22. package/lib/group-create.d.ts +5 -1
  23. package/lib/group-create.js +36 -14
  24. package/lib/group-credential.d.ts +13 -3
  25. package/lib/group-credential.js +17 -6
  26. package/lib/group-device.d.ts +32 -22
  27. package/lib/group-device.js +66 -51
  28. package/lib/group-handle.d.ts +87 -31
  29. package/lib/group-handle.js +377 -168
  30. package/lib/group-lifecycle.d.ts +44 -11
  31. package/lib/group-lifecycle.js +193 -85
  32. package/lib/group-membership.d.ts +6 -1
  33. package/lib/group-membership.js +2 -2
  34. package/lib/group-welcome.d.ts +5 -1
  35. package/lib/group-welcome.js +34 -10
  36. package/lib/head.d.ts +25 -5
  37. package/lib/head.js +17 -8
  38. package/lib/history.d.ts +14 -3
  39. package/lib/history.js +8 -5
  40. package/lib/index.d.ts +28 -1
  41. package/lib/index.js +1 -0
  42. package/lib/key-package-codec.d.ts +4 -1
  43. package/lib/key-package-codec.js +1 -1
  44. package/lib/ledger.d.ts +14 -6
  45. package/lib/ledger.js +56 -19
  46. package/lib/lifecycle-proof.d.ts +5 -4
  47. package/lib/lifecycle-proof.js +111 -51
  48. package/lib/lifecycle.d.ts +18 -9
  49. package/lib/lifecycle.js +184 -81
  50. package/lib/member-root.d.ts +54 -15
  51. package/lib/member-root.js +115 -53
  52. package/lib/policy.d.ts +5 -1
  53. package/lib/policy.js +1 -1
  54. package/lib/recovery-verdict.d.ts +12 -3
  55. package/lib/recovery-verdict.js +56 -22
  56. package/lib/recovery.d.ts +20 -5
  57. package/lib/recovery.js +117 -46
  58. package/lib/registry.d.ts +46 -10
  59. package/lib/registry.js +64 -38
  60. package/lib/roster.d.ts +7 -1
  61. package/lib/roster.js +18 -7
  62. package/lib/secret-tree.d.ts +5 -1
  63. package/lib/secret-tree.js +1 -1
  64. package/lib/types.d.ts +3 -0
  65. package/package.json +9 -5
@@ -33,6 +33,7 @@ export async function processWelcome(params) {
33
33
  authService: {
34
34
  async validateCredential (credential, signaturePublicKey) {
35
35
  await verifyLeafCredential(credential, signaturePublicKey, {
36
+ crypto: options?.crypto,
36
37
  judging: ()=>({
37
38
  stage: 'structural',
38
39
  mode: 'rejudge'
@@ -57,7 +58,8 @@ export async function processWelcome(params) {
57
58
  id: identity.id,
58
59
  groupID: invite.groupID
59
60
  };
60
- const group = new GroupHandle({
61
+ const group = await GroupHandle.create({
62
+ crypto: options?.crypto,
61
63
  state,
62
64
  credential,
63
65
  context,
@@ -73,14 +75,23 @@ export async function processWelcome(params) {
73
75
  if (authenticated == null) {
74
76
  throw new Error('processWelcome: the group has no ledger head extension');
75
77
  }
76
- assertHeadMatches(authenticated.head, computeHead(invite.groupID, invite.ledgerEntries.map(ledgerEntryDigest)));
78
+ assertHeadMatches({
79
+ expected: authenticated.head,
80
+ actual: computeHead({
81
+ groupID: invite.groupID,
82
+ entryIDs: invite.ledgerEntries.map(ledgerEntryDigest)
83
+ })
84
+ });
77
85
  // Fold the invite's entries: the roster is seeded from the anchor and the fold grants
78
86
  // authority only to an admin-so-far, so a member-signed entry cannot promote anyone
79
87
  // even though applyLedgerEntries itself is the permissive primitive.
80
88
  if (group.anchor.controller == null) {
81
89
  let namesSelf = false;
82
90
  for (const token of invite.ledgerEntries){
83
- const verified = await verifyLedgerEntry(token);
91
+ const verified = await verifyLedgerEntry({
92
+ token,
93
+ crypto: options?.crypto
94
+ });
84
95
  if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === normalizeDID(identity.id)) namesSelf = true;
85
96
  }
86
97
  if (!namesSelf) throw new Error('processWelcome: the invite carries no role entry naming this identity');
@@ -163,6 +174,7 @@ export async function processWelcome(params) {
163
174
  if (anchor.controller != null && parsed.controller == null) throw new LeafBindingError('floating-refused');
164
175
  if (anchor.controller != null && parsed.controller != null && normalizeDID(parsed.controller.id) !== normalizeDID(anchor.controller)) throw new LeafBindingError('controller-mismatch');
165
176
  await verifyLeafCredential(leafCredential, signaturePublicKey, {
177
+ crypto: options?.crypto,
166
178
  judging: ()=>({
167
179
  stage: 'structural',
168
180
  mode: 'rejudge'
@@ -182,7 +194,10 @@ export async function processWelcome(params) {
182
194
  // ts-mls rejects the external join. Derive them from the GroupInfo being resynced
183
195
  // against, honoring an explicit capabilities override.
184
196
  const keyPackage = await generateKeyPackageWithKey({
185
- credential: makeMLSCredential(identity, controller),
197
+ credential: makeMLSCredential({
198
+ identity,
199
+ controller
200
+ }),
186
201
  signatureKeyPair: {
187
202
  signKey: identity.privateKey,
188
203
  publicKey: identity.publicKey
@@ -206,7 +221,8 @@ export async function processWelcome(params) {
206
221
  publicMessage
207
222
  };
208
223
  const commitMessage = encode(mlsMessageEncoder, framedCommit);
209
- const group = new GroupHandle({
224
+ const group = await GroupHandle.create({
225
+ crypto: options?.crypto,
210
226
  state: newState,
211
227
  credential,
212
228
  context,
@@ -238,7 +254,8 @@ export async function processWelcome(params) {
238
254
  ...previous
239
255
  }
240
256
  };
241
- const before = new GroupHandle({
257
+ const before = await GroupHandle.create({
258
+ crypto: options?.crypto,
242
259
  state: {
243
260
  ...newState,
244
261
  ratchetTree: beforeTree,
@@ -248,10 +265,17 @@ export async function processWelcome(params) {
248
265
  context: await resolveMlsContext(options, anchor)
249
266
  });
250
267
  if (ledgerEntries != null) {
251
- await before.bootstrapLedger(ledgerEntries);
252
- await group.bootstrapLedger(ledgerEntries);
268
+ await before.bootstrapLedger({
269
+ tokens: ledgerEntries
270
+ });
271
+ await group.bootstrapLedger({
272
+ tokens: ledgerEntries
273
+ });
253
274
  }
254
- await params.beforeBinding?.(group, before);
275
+ await params.beforeBinding?.({
276
+ pending: group,
277
+ source: before
278
+ });
255
279
  if (anchor.controller != null && controller == null) throw new LeafBindingError('floating-refused');
256
280
  assertBindingAuthorTime(controller);
257
281
  const gate = await prepareLifecycleGate({
@@ -266,7 +290,7 @@ export async function processWelcome(params) {
266
290
  }),
267
291
  externalLeaf: own.leaf
268
292
  });
269
- gate.check({
293
+ await gate.check({
270
294
  kind: 'commit',
271
295
  senderLeafIndex: undefined,
272
296
  proposals
package/lib/head.d.ts CHANGED
@@ -7,6 +7,10 @@ export type LedgerHead = {
7
7
  v: number;
8
8
  head: Uint8Array;
9
9
  };
10
+ export type LedgerIncompleteErrorParams = {
11
+ expected: Uint8Array;
12
+ actual: Uint8Array;
13
+ };
10
14
  /**
11
15
  * Thrown when a recomputed head does not match the authenticated one — an inviter
12
16
  * omitted, reordered, or truncated a ledger entry. Carries both heads for logging.
@@ -14,7 +18,7 @@ export type LedgerHead = {
14
18
  */
15
19
  export declare class LedgerIncompleteError extends Error {
16
20
  #private;
17
- constructor(expected: Uint8Array, actual: Uint8Array);
21
+ constructor({ expected, actual }: LedgerIncompleteErrorParams);
18
22
  /** The authenticated head from the group's GroupContext. Named apart from
19
23
  * `expected`/`actual` on purpose: a test runner's diff formatter assigns those on
20
24
  * any thrown Error, and a getter-only pair would turn an unexpected throw into a
@@ -26,20 +30,28 @@ export declare class LedgerIncompleteError extends Error {
26
30
  /** Genesis head for a group: `SHA256(DOMAIN ‖ groupID)`. Pure. The epoch-0 link of
27
31
  * the chain, written into the GroupContext at group creation. */
28
32
  export declare function genesisHead(groupID: string): Uint8Array;
33
+ export type ExtendHeadParams = {
34
+ head: Uint8Array;
35
+ entryIDs: Array<string>;
36
+ };
29
37
  /**
30
38
  * Extend a head by a batch of entry ids, in envelope order: `head ← SHA256(head ‖
31
39
  * frame(id))`, folded left to right. Pure, order- and length-sensitive (see
32
40
  * {@link frameID}). An empty batch is a no-op — a commit with no entries does not
33
41
  * move the head.
34
42
  */
35
- export declare function extendHead(head: Uint8Array, entryIDs: Array<string>): Uint8Array;
43
+ export declare function extendHead({ head, entryIDs }: ExtendHeadParams): Uint8Array;
44
+ export type ComputeHeadParams = {
45
+ groupID: string;
46
+ entryIDs: Array<string>;
47
+ };
36
48
  /**
37
49
  * Recompute a head from genesis across an ordered id list. Pure. Composes with
38
50
  * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
39
51
  * `extendHead(extendHead(genesisHead(g), a), b)`, so a member can verify a head
40
52
  * update by extending its own chain rather than refolding from genesis.
41
53
  */
42
- export declare function computeHead(groupID: string, entryIDs: Array<string>): Uint8Array;
54
+ export declare function computeHead({ groupID, entryIDs }: ComputeHeadParams): Uint8Array;
43
55
  /**
44
56
  * Encode a head as LedgerHead extension data: one version byte
45
57
  * (`LEDGER_HEAD_VERSION`) then the 32 digest bytes. A single canonical byte form —
@@ -66,14 +78,22 @@ export declare function readLedgerHeadExtension(handle: GroupHandle): GroupConte
66
78
  * never a re-encode of this result.
67
79
  */
68
80
  export declare function readLedgerHead(handle: GroupHandle): LedgerHead | null;
81
+ export type HeadsMatchParams = {
82
+ expected: Uint8Array;
83
+ actual: Uint8Array;
84
+ };
69
85
  /**
70
86
  * Whether a recomputed head equals the authenticated one — the predicate form of
71
87
  * {@link assertHeadMatches}. Two entry points on one comparison: a fail-closed gate
72
88
  * throws, a local invariant check reads the boolean.
73
89
  */
74
- export declare function headsMatch(expected: Uint8Array, actual: Uint8Array): boolean;
90
+ export declare function headsMatch({ expected, actual }: HeadsMatchParams): boolean;
91
+ export type AssertHeadMatchesParams = {
92
+ expected: Uint8Array;
93
+ actual: Uint8Array;
94
+ };
75
95
  /**
76
96
  * Assert a recomputed head matches the authenticated one, or throw
77
97
  * {@link LedgerIncompleteError} carrying both. Returns for equal heads.
78
98
  */
79
- export declare function assertHeadMatches(expected: Uint8Array, actual: Uint8Array): void;
99
+ export declare function assertHeadMatches({ expected, actual }: AssertHeadMatchesParams): void;
package/lib/head.js CHANGED
@@ -15,7 +15,7 @@ const SHA256_LENGTH = 32;
15
15
  */ export class LedgerIncompleteError extends Error {
16
16
  #expected;
17
17
  #actual;
18
- constructor(expected, actual){
18
+ constructor({ expected, actual }){
19
19
  super('recomputed ledger head does not match the authenticated head');
20
20
  this.name = 'LedgerIncompleteError';
21
21
  this.#expected = expected;
@@ -52,7 +52,7 @@ const SHA256_LENGTH = 32;
52
52
  * frame(id))`, folded left to right. Pure, order- and length-sensitive (see
53
53
  * {@link frameID}). An empty batch is a no-op — a commit with no entries does not
54
54
  * move the head.
55
- */ export function extendHead(head, entryIDs) {
55
+ */ export function extendHead({ head, entryIDs }) {
56
56
  let acc = head;
57
57
  for (const id of entryIDs){
58
58
  acc = sha256(concatBytes(acc, frameID(id)));
@@ -64,8 +64,11 @@ const SHA256_LENGTH = 32;
64
64
  * {@link extendHead}: `computeHead(g, [...a, ...b])` equals
65
65
  * `extendHead(extendHead(genesisHead(g), a), b)`, so a member can verify a head
66
66
  * update by extending its own chain rather than refolding from genesis.
67
- */ export function computeHead(groupID, entryIDs) {
68
- return extendHead(genesisHead(groupID), entryIDs);
67
+ */ export function computeHead({ groupID, entryIDs }) {
68
+ return extendHead({
69
+ head: genesisHead(groupID),
70
+ entryIDs
71
+ });
69
72
  }
70
73
  /**
71
74
  * Encode a head as LedgerHead extension data: one version byte
@@ -137,14 +140,20 @@ function bytesEqual(a, b) {
137
140
  * Whether a recomputed head equals the authenticated one — the predicate form of
138
141
  * {@link assertHeadMatches}. Two entry points on one comparison: a fail-closed gate
139
142
  * throws, a local invariant check reads the boolean.
140
- */ export function headsMatch(expected, actual) {
143
+ */ export function headsMatch({ expected, actual }) {
141
144
  return bytesEqual(expected, actual);
142
145
  }
143
146
  /**
144
147
  * Assert a recomputed head matches the authenticated one, or throw
145
148
  * {@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
+ */ export function assertHeadMatches({ expected, actual }) {
150
+ if (!headsMatch({
151
+ expected,
152
+ actual
153
+ })) {
154
+ throw new LedgerIncompleteError({
155
+ expected,
156
+ actual
157
+ });
149
158
  }
150
159
  }
package/lib/history.d.ts CHANGED
@@ -1,12 +1,23 @@
1
1
  import { type ControllerLog } from '@kokuin/controller';
2
+ import type { CryptoOptions } from '@kokuin/token';
2
3
  import { type ClientState } from 'ts-mls';
3
4
  import type { VerifiedLedgerEntry } from './ledger.js';
4
5
  export declare const HISTORY_HORIZON = 393216;
5
6
  export declare const MAX_EPOCH_EVENTS_FOR_LEAVES = 32;
6
7
  export declare const SETTLE_PROMPT_EPOCH_EVENTS = 24;
7
- export declare function epochEventCount(log: ControllerLog): number;
8
- export declare function settleAdvisory(log: ControllerLog): 'ok' | 'prompt' | 'blocked';
8
+ export type EpochEventCountParams = {
9
+ log: ControllerLog;
10
+ } & CryptoOptions;
11
+ export declare function epochEventCount({ log, ...options }: EpochEventCountParams): Promise<number>;
12
+ export type SettleAdvisoryParams = {
13
+ log: ControllerLog;
14
+ } & CryptoOptions;
15
+ export declare function settleAdvisory({ log, ...options }: SettleAdvisoryParams): Promise<'ok' | 'prompt' | 'blocked'>;
9
16
  export declare function controllerLogSize(events: ReadonlyArray<unknown>): number;
10
17
  export declare function proofSize(value: unknown): number;
18
+ export type HistorySizeParams = {
19
+ tree: ClientState['ratchetTree'];
20
+ entries: ReadonlyArray<VerifiedLedgerEntry>;
21
+ };
11
22
  /** Count validated controller history. Callers apply the horizon only to lifecycle groups. */
12
- export declare function historySize(tree: ClientState['ratchetTree'], entries: ReadonlyArray<VerifiedLedgerEntry>): number;
23
+ export declare function historySize({ tree, entries }: HistorySizeParams): number;
package/lib/history.js CHANGED
@@ -6,15 +6,18 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
6
6
  export const HISTORY_HORIZON = 393_216;
7
7
  export const MAX_EPOCH_EVENTS_FOR_LEAVES = 32;
8
8
  export const SETTLE_PROMPT_EPOCH_EVENTS = 24;
9
- export function epochEventCount(log) {
9
+ export async function epochEventCount({ log, ...options }) {
10
10
  const inception = log.chain[0]?.event;
11
11
  if (inception?.t !== 'icp') throw new Error('Missing controller inception');
12
- const folded = foldControllerLog(didFromInception(inception), log);
12
+ const folded = await foldControllerLog(didFromInception(inception), log, options);
13
13
  if (!folded.ok) throw new Error(folded.reason);
14
14
  return folded.applied.length;
15
15
  }
16
- export function settleAdvisory(log) {
17
- const count = epochEventCount(log);
16
+ export async function settleAdvisory({ log, ...options }) {
17
+ const count = await epochEventCount({
18
+ log,
19
+ ...options
20
+ });
18
21
  if (count > MAX_EPOCH_EVENTS_FOR_LEAVES) return 'blocked';
19
22
  return count >= SETTLE_PROMPT_EPOCH_EVENTS ? 'prompt' : 'ok';
20
23
  }
@@ -25,7 +28,7 @@ export function controllerLogSize(events) {
25
28
  export function proofSize(value) {
26
29
  return isControllerLog(value) ? controllerLogSize(value.chain) + controllerLogSize(value.events) : 0;
27
30
  }
28
- /** Count validated controller history. Callers apply the horizon only to lifecycle groups. */ export function historySize(tree, entries) {
31
+ /** Count validated controller history. Callers apply the horizon only to lifecycle groups. */ export function historySize({ tree, entries }) {
29
32
  let size = 0;
30
33
  for (const node of tree){
31
34
  if (node == null || node.nodeType !== nodeTypes.leaf) continue;
package/lib/index.d.ts CHANGED
@@ -1,34 +1,61 @@
1
1
  export type { EventsSource } from '@sozai/event';
2
2
  export type { Capabilities, GroupContextExtension, IncomingMessageCallback, KeyPackage, Proposal, ProposalWithSender, } from 'ts-mls';
3
3
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
4
+ export type { BuildCurrentGroupAnchorExtensionParams } from './anchor.js';
4
5
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
6
+ export type { DIDAuthenticationDependenciesMayKeepDeniedIssuerParams } from './authentication.js';
5
7
  export { createDIDAuthenticationService, type DIDAuthenticationDependencies, type JudgingContext, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
6
8
  export { type MintLeafCapabilityParams, type MintTrustedGrantParams, mintLeafCapability, mintTrustedGrant, } from './capability.js';
7
9
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
10
+ export type { EffectDeltaParams, IngestControllerLogParams } from './controller-ingest.js';
8
11
  export { effectDelta, type FoldOk, ingestControllerLog } from './controller-ingest.js';
12
+ export type { MemberDropIndicesParams } from './controller-log.js';
9
13
  export { memberDropIndices } from './controller-log.js';
10
14
  export { type ControllerBinding, didFromCredential, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
11
15
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
12
16
  export type { LeafBinding } from './device-proof.js';
17
+ export type { PrefixRelationParams } from './embedded-resolver.js';
13
18
  export { createRegistryControllerResolver, prefixRelation } from './embedded-resolver.js';
14
19
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
15
20
  export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopeParams, foldEnvelope, } from './envelope-fold.js';
16
21
  export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RecoveryKnowledgeError, type RecoveryKnowledgeReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
22
+ export type { FoldLedgerParams, LedgerReducerApplyParams, LedgerReducerVerifyAuthorityParams, } from './fold.js';
17
23
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
18
24
  export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, type SendAdmission, } from './group.js';
25
+ export type { CommitInviteParams, CommitLedgerEntriesParams } from './group-commit.js';
26
+ export { KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
27
+ export type { CreateGroupParams } from './group-create.js';
28
+ export type { CreateKeyPackageBundleParams, CreateLastResortKeyPackageBundleParams, MakeMLSCredentialParams, } from './group-credential.js';
29
+ export type { AddDeviceParams, AnnounceControllerBeaconParams, LabelDeviceParams, RegisterDeviceParams, RevokeDeviceParams, } from './group-device.js';
30
+ export type { CommitRejectedErrorParams, GroupHandleAdvanceSenderGenerationParams, GroupHandleBootstrapLedgerParams, GroupHandleDecryptParams, GroupHandleDecryptStagedParams, GroupHandleEncryptParams, GroupHandleExportSecretParams, GroupHandleProcessMessageParams, RegistryAtParams, } from './group-handle.js';
19
31
  export { registryAt } from './group-handle.js';
20
- export { attestTreeTime, type CommitResult, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, type RemovalEvidence, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets, } from './group-lifecycle.js';
32
+ export type { AttestTreeTimeParams, ControllerLogDeltaParams, PreservationClockParams, PublishControllerLogParams, RemovalEvidenceParams, RenewLeafParams, SurvivorTargetsParams, } from './group-lifecycle.js';
33
+ export { attestTreeTime, type CommitResult, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, type RemovalEvidence, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeProofInput, type RevokeWithProofParams, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets, } from './group-lifecycle.js';
34
+ export type { RemoveMemberParams } from './group-membership.js';
35
+ export type { JoinGroupExternalParamsBeforeBindingParams } from './group-welcome.js';
36
+ export type { AssertHeadMatchesParams, ComputeHeadParams, ExtendHeadParams, HeadsMatchParams, LedgerIncompleteErrorParams, } from './head.js';
21
37
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
38
+ export type { EpochEventCountParams, HistorySizeParams, SettleAdvisoryParams } from './history.js';
22
39
  export { epochEventCount, HISTORY_HORIZON, historySize, MAX_EPOCH_EVENTS_FOR_LEAVES, proofSize, SETTLE_PROMPT_EPOCH_EVENTS, settleAdvisory, } from './history.js';
40
+ export type { KeyPackageRefParams } from './key-package-codec.js';
23
41
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
42
+ export type { SignLedgerEntryParams, VerifyLedgerEntryParams } from './ledger.js';
24
43
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
44
+ export type { AttestedTreeTimeParams, LeafExpiryParams } from './lifecycle.js';
25
45
  export { type AssertRecoveryBindingParams, assertRecoveryBinding, attestedTreeTime, leafExpiry, } from './lifecycle.js';
46
+ export type { CascadeOfParams, ClaimsForParams, EffectiveAuthorityOfParams, EffectOfParams, MemberRootStatusParams, MemberRootsOfParams, } from './member-root.js';
26
47
  export { cascadeOf, claimsFor, type EffectClaim, type EvidenceSlot, effectiveAuthorityOf, effectOf, type LeafRef, type MemberRoot, type MemberRootStatus, memberRootStatus, memberRootsOf, type ProofRef, type RemovedEffect, type RemovedMember, } from './member-root.js';
48
+ export type { DefaultCommitPolicyParams } from './policy.js';
27
49
  export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
50
+ export type { RecoveryRequestErrorParams, SealedGroupInfoErrorParams, SealedLedgerErrorParams, VerifyRecoveryRequestParams, } from './recovery.js';
28
51
  export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openRecoveryGroupInfo, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryGroupInfo, 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, verifyRecoveryRequest, } from './recovery.js';
52
+ export type { ConfirmationKeyParams, ConfirmationTagParams } from './recovery-verdict.js';
29
53
  export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecoveryVerdict, type RecoveryRefusalReason, type RecoverySignerEligibleParams, type RecoveryVerdict, recoverySignerEligible, type SealRecoveryVerdictParams, sealRecoveryVerdict, } from './recovery-verdict.js';
54
+ export type { AssertRetainsKnownEffectsParams, AuthorityParams, BeaconOfParams, ControllerOfParams, FoldControlParams, RecordedLogOfParams, RegistryForLogParams, RevocationOfParams, } from './registry.js';
30
55
  export { assertRetainsKnownEffects, authority, beaconOf, type ControllerBeacon, type ControllerProjection, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, type Revocation, type RevokedEffect, recordedLogOf, registryForLog, registrySeed, revocationOf, } from './registry.js';
56
+ export type { FoldRosterParams } from './roster.js';
31
57
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
58
+ export type { MergeReceiveSecretTreeParams } from './secret-tree.js';
32
59
  export { mergeReceiveSecretTree } from './secret-tree.js';
33
60
  export { bindingIssuedAt, DuplicateMemberLeafError } from './stale-leaf.js';
34
61
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
package/lib/index.js CHANGED
@@ -13,6 +13,7 @@ export { foldEnvelope } from './envelope-fold.js';
13
13
  export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RecoveryKnowledgeError, RevokeProofError } from './errors.js';
14
14
  export { foldLedger } from './fold.js';
15
15
  export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
16
+ export { KUMIAI_KEY_RETENTION_CONFIG } from './group-context.js';
16
17
  export { registryAt } from './group-handle.js';
17
18
  export { attestTreeTime, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets } from './group-lifecycle.js';
18
19
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
@@ -63,6 +63,9 @@ export declare function encodePrivateKeyPackage(privatePackage: PrivateKeyPackag
63
63
  * keys match any public package.
64
64
  */
65
65
  export declare function decodePrivateKeyPackage(encoded: string): PrivateKeyPackage | null;
66
+ export type KeyPackageRefParams = {
67
+ keyPackage: KeyPackage;
68
+ } & GroupOptions;
66
69
  /**
67
70
  * The KeyPackageRef for a key package, base64 — the value a Welcome names to say which package its
68
71
  * encrypted group secrets are for, and the stable identity of a stored package.
@@ -70,4 +73,4 @@ export declare function decodePrivateKeyPackage(encoded: string): PrivateKeyPack
70
73
  * A hash over the package's canonical encoding, so a codec round trip does not change it. Derived
71
74
  * under the ciphersuite's hash, so `options` is threaded through rather than defaulted.
72
75
  */
73
- export declare function keyPackageRef(keyPackage: KeyPackage, options?: GroupOptions): Promise<string>;
76
+ export declare function keyPackageRef({ keyPackage, ...options }: KeyPackageRefParams): Promise<string>;
@@ -105,7 +105,7 @@ import { resolveMlsContext } from './group-context.js';
105
105
  *
106
106
  * A hash over the package's canonical encoding, so a codec round trip does not change it. Derived
107
107
  * under the ciphersuite's hash, so `options` is threaded through rather than defaulted.
108
- */ export async function keyPackageRef(keyPackage, options) {
108
+ */ export async function keyPackageRef({ keyPackage, ...options }) {
109
109
  const { cipherSuite } = await resolveMlsContext(options);
110
110
  return toB64(await makeKeyPackageRef(keyPackage, cipherSuite.hash));
111
111
  }
package/lib/ledger.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type SigningIdentity } from '@kokuin/token';
1
+ import { type CryptoOptions, type SigningIdentity } from '@kokuin/token';
2
2
  export declare const LEDGER_ENTRY_DIGEST_CACHE_SIZE = 4096;
3
3
  /** @internal */
4
4
  export declare function ledgerEntryDigestCacheSize(): number;
@@ -27,24 +27,32 @@ export type VerifiedLedgerEntry<TValue = unknown> = {
27
27
  issuer: string;
28
28
  entry: LedgerEntry<TValue>;
29
29
  };
30
+ export type SignLedgerEntryParams = {
31
+ identity: SigningIdentity;
32
+ entry: LedgerEntry;
33
+ };
30
34
  /**
31
35
  * Sign a ledger entry. The signer fills `iss` with its DID, so the signature
32
36
  * covers every claim field — including `groupID` and `ord` — and binds the
33
37
  * author. `ord` is signed only when present, so a claim without it never signs
34
38
  * an `ord: undefined` key. Returns the stringified token.
35
39
  */
36
- export declare function signLedgerEntry(identity: SigningIdentity, entry: LedgerEntry): Promise<string>;
40
+ export declare function signLedgerEntry({ identity, entry }: SignLedgerEntryParams): Promise<string>;
41
+ export type VerifyLedgerEntryParams = {
42
+ token: string;
43
+ } & CryptoOptions;
37
44
  /**
38
- * Verify a signed ledger token and extract its claim. Returns `null` (never
39
- * throws) when the token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
45
+ * Verify a signed ledger token and extract its claim. Returns `null` when the
46
+ * token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
40
47
  * returns those without checking a signature, so an attacker could forge an
41
48
  * arbitrary `iss`; `isVerifiedToken` rejects them), or structurally malformed.
42
49
  * A missing or non-string `groupID` is malformed, as is a missing or non-string
43
50
  * `type` or `subject`, or an `ord` present but not a string. The claim fields
44
51
  * come from the verified payload only; the issuer is the normalized verified
45
- * `iss`.
52
+ * `iss`. A provider failure rejects with the provider's error: it says nothing
53
+ * about the token, and a caller reading it as invalid would drop an authentic entry.
46
54
  */
47
- export declare function verifyLedgerEntry<TValue = unknown>(token: string): Promise<VerifiedLedgerEntry<TValue> | null>;
55
+ export declare function verifyLedgerEntry<TValue = unknown>({ token, ...options }: VerifyLedgerEntryParams): Promise<VerifiedLedgerEntry<TValue> | null>;
48
56
  /**
49
57
  * Content-addressed digest of a signed ledger token, used as the append-only
50
58
  * store's dedup key. Multibase-encoded SHA-256 multihash over the token bytes.
package/lib/ledger.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { nobleCrypto } from '@kokuin/crypto';
1
2
  import { encodeMultibase, isVerifiedToken, multihashSHA256, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
2
3
  const textEncoder = new TextEncoder();
3
4
  export const LEDGER_ENTRY_DIGEST_CACHE_SIZE = 4096;
@@ -10,38 +11,74 @@ const LEDGER_ENTRY_DIGEST_CACHE = new Map();
10
11
  * covers every claim field — including `groupID` and `ord` — and binds the
11
12
  * author. `ord` is signed only when present, so a claim without it never signs
12
13
  * an `ord: undefined` key. Returns the stringified token.
13
- */ export async function signLedgerEntry(identity, entry) {
14
+ */ export async function signLedgerEntry({ identity, entry }) {
14
15
  const signed = await identity.signToken({
15
- type: entry.type,
16
- groupID: entry.groupID,
17
- subject: entry.subject,
18
- value: entry.value,
19
- ...entry.ord === undefined ? {} : {
20
- ord: entry.ord
21
- }
22
- }, // Embed the long-form DID so each entry is self-verifying offline: the
23
- // ledger is the source of truth and receivers fold it long after first
24
- // contact, when the author's DID document may no longer be cached. No-op
25
- // for did:key (long form === id).
26
- {
16
+ payload: {
17
+ type: entry.type,
18
+ groupID: entry.groupID,
19
+ subject: entry.subject,
20
+ value: entry.value,
21
+ ...entry.ord === undefined ? {} : {
22
+ ord: entry.ord
23
+ }
24
+ },
27
25
  embedLongForm: true
28
26
  });
29
27
  return stringifyToken(signed);
30
28
  }
29
+ class ProviderFailure extends Error {
30
+ }
31
+ const OBSERVED_PROVIDERS = new WeakMap();
32
+ // `verifyToken` throws for a bad token and a failed provider alike, so mark the second. Stable per
33
+ // provider: Kokuin keys its verifier memo and call coalescing on this object.
34
+ function observedProvider(crypto) {
35
+ let observed = OBSERVED_PROVIDERS.get(crypto);
36
+ if (observed == null) {
37
+ observed = {
38
+ ...crypto,
39
+ verify: async (item)=>{
40
+ try {
41
+ return await crypto.verify(item);
42
+ } catch (cause) {
43
+ throw new ProviderFailure('Crypto provider failed', {
44
+ cause
45
+ });
46
+ }
47
+ },
48
+ verifyBatch: async (items)=>{
49
+ try {
50
+ return await crypto.verifyBatch(items);
51
+ } catch (cause) {
52
+ throw new ProviderFailure('Crypto provider failed', {
53
+ cause
54
+ });
55
+ }
56
+ }
57
+ };
58
+ OBSERVED_PROVIDERS.set(crypto, observed);
59
+ }
60
+ return observed;
61
+ }
31
62
  /**
32
- * Verify a signed ledger token and extract its claim. Returns `null` (never
33
- * throws) when the token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
63
+ * Verify a signed ledger token and extract its claim. Returns `null` when the
64
+ * token is unparseable, unsigned (`alg: 'none'` — `verifyToken`
34
65
  * returns those without checking a signature, so an attacker could forge an
35
66
  * arbitrary `iss`; `isVerifiedToken` rejects them), or structurally malformed.
36
67
  * A missing or non-string `groupID` is malformed, as is a missing or non-string
37
68
  * `type` or `subject`, or an `ord` present but not a string. The claim fields
38
69
  * come from the verified payload only; the issuer is the normalized verified
39
- * `iss`.
40
- */ export async function verifyLedgerEntry(token) {
70
+ * `iss`. A provider failure rejects with the provider's error: it says nothing
71
+ * about the token, and a caller reading it as invalid would drop an authentic entry.
72
+ */ export async function verifyLedgerEntry({ token, ...options }) {
41
73
  let verified;
42
74
  try {
43
- verified = await verifyToken(token);
44
- } catch {
75
+ verified = await verifyToken({
76
+ ...options,
77
+ crypto: observedProvider(options.crypto ?? nobleCrypto),
78
+ token: token
79
+ });
80
+ } catch (error) {
81
+ if (error instanceof ProviderFailure) throw error.cause;
45
82
  return null;
46
83
  }
47
84
  if (!isVerifiedToken(verified)) {
@@ -1,6 +1,7 @@
1
1
  import { type ControllerLog } from '@kokuin/controller';
2
+ import { type CryptoOptions } from '@kokuin/token';
2
3
  import { type LeafNode } from 'ts-mls';
3
- import { ingestControllerLog } from './controller-ingest.js';
4
+ import { type IngestedControllerLog } from './controller-ingest.js';
4
5
  import type { GroupHandle } from './group-handle.js';
5
6
  import type { VerifiedLedgerEntry } from './ledger.js';
6
7
  import { type RemovedEffect } from './member-root.js';
@@ -24,11 +25,11 @@ type AuthenticatedProof = {
24
25
  };
25
26
  };
26
27
  /** Keep controller merge limits inside the lifecycle proof error boundary. */
27
- export declare function mergeLifecycleProofLogs(controller: string, first: ControllerLog, second: ControllerLog): ControllerLog;
28
+ export declare function mergeLifecycleProofLogs(controller: string, first: ControllerLog, second: ControllerLog, options?: CryptoOptions): Promise<ControllerLog>;
28
29
  /** Reattach historical closures without reviving unapplied current-epoch events. */
29
- export declare function lifecycleProofLog(controller: string, ingested: ReturnType<typeof ingestControllerLog>, proof: ControllerLog): ControllerLog;
30
+ export declare function lifecycleProofLog(controller: string, ingested: IngestedControllerLog, proof: ControllerLog, options?: CryptoOptions): Promise<ControllerLog>;
30
31
  /** Authenticate replayable log data without reading any membership state. */
31
- export declare function authenticateLifecycleProof(controllerID: string, verified: VerifiedLedgerEntry<DeviceValue>, registry: DeviceRegistry): AuthenticatedProof;
32
+ export declare function authenticateLifecycleProof(controllerID: string, verified: VerifiedLedgerEntry<DeviceValue>, registry: DeviceRegistry, options?: CryptoOptions): Promise<AuthenticatedProof>;
32
33
  /**
33
34
  * A leaf that stays when its issuer is denied: in a group whose anchor names a controller, a
34
35
  * chained leaf of that controller carrying its holder's own valid grant from it, for a holder that