@kumiai/mls 0.11.0 → 0.12.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 (48) hide show
  1. package/README.md +29 -1
  2. package/lib/authentication.d.ts +6 -2
  3. package/lib/authentication.js +207 -51
  4. package/lib/capability.d.ts +4 -0
  5. package/lib/capability.js +22 -10
  6. package/lib/controller-ingest.d.ts +19 -0
  7. package/lib/controller-ingest.js +117 -0
  8. package/lib/controller-log.d.ts +4 -3
  9. package/lib/controller-log.js +41 -14
  10. package/lib/credential.d.ts +8 -5
  11. package/lib/credential.js +32 -3
  12. package/lib/device-proof.d.ts +5 -0
  13. package/lib/embedded-resolver.d.ts +8 -18
  14. package/lib/embedded-resolver.js +52 -24
  15. package/lib/errors.d.ts +8 -2
  16. package/lib/errors.js +11 -0
  17. package/lib/group-commit.d.ts +11 -2
  18. package/lib/group-commit.js +154 -46
  19. package/lib/group-context.d.ts +4 -2
  20. package/lib/group-context.js +30 -6
  21. package/lib/group-create.js +44 -16
  22. package/lib/group-credential.js +22 -1
  23. package/lib/group-device.js +5 -15
  24. package/lib/group-handle.d.ts +12 -1
  25. package/lib/group-handle.js +89 -12
  26. package/lib/group-lifecycle.d.ts +31 -5
  27. package/lib/group-lifecycle.js +253 -155
  28. package/lib/group-membership.js +1 -1
  29. package/lib/group-welcome.d.ts +4 -0
  30. package/lib/group-welcome.js +14 -2
  31. package/lib/history.d.ts +6 -0
  32. package/lib/history.js +20 -1
  33. package/lib/index.d.ts +12 -7
  34. package/lib/index.js +11 -6
  35. package/lib/lifecycle-proof.d.ts +15 -6
  36. package/lib/lifecycle-proof.js +195 -126
  37. package/lib/lifecycle.d.ts +9 -6
  38. package/lib/lifecycle.js +194 -84
  39. package/lib/member-root.d.ts +88 -0
  40. package/lib/member-root.js +469 -0
  41. package/lib/recovery-verdict.d.ts +1 -1
  42. package/lib/recovery-verdict.js +30 -13
  43. package/lib/registry.d.ts +17 -6
  44. package/lib/registry.js +204 -20
  45. package/lib/stale-leaf.d.ts +2 -0
  46. package/lib/stale-leaf.js +9 -4
  47. package/lib/types.d.ts +3 -0
  48. package/package.json +4 -4
package/lib/index.d.ts CHANGED
@@ -2,29 +2,34 @@ 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
4
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
5
- export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
5
+ export { createDIDAuthenticationService, type DIDAuthenticationDependencies, type JudgingContext, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
6
6
  export { type MintLeafCapabilityParams, type MintTrustedGrantParams, mintLeafCapability, mintTrustedGrant, } from './capability.js';
7
7
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
8
+ export { effectDelta, type FoldOk, ingestControllerLog } from './controller-ingest.js';
9
+ export { memberDropIndices } from './controller-log.js';
8
10
  export { type ControllerBinding, didFromCredential, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
9
11
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
10
12
  export type { LeafBinding } from './device-proof.js';
13
+ export { createRegistryControllerResolver, prefixRelation } from './embedded-resolver.js';
11
14
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
12
15
  export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopeParams, foldEnvelope, } from './envelope-fold.js';
13
- export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
16
+ export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RecoveryKnowledgeError, type RecoveryKnowledgeReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
14
17
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
15
18
  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';
16
- export { type CommitResult, commitSelfRemovals, proposeSelfRemoval, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
19
+ 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';
17
21
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
18
- export { HISTORY_HORIZON, historySize } from './history.js';
22
+ export { epochEventCount, HISTORY_HORIZON, historySize, MAX_EPOCH_EVENTS_FOR_LEAVES, proofSize, SETTLE_PROMPT_EPOCH_EVENTS, settleAdvisory, } from './history.js';
19
23
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
20
24
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
21
- export { type AssertRecoveryBindingParams, assertRecoveryBinding } from './lifecycle.js';
25
+ export { type AssertRecoveryBindingParams, assertRecoveryBinding, attestedTreeTime, leafExpiry, } from './lifecycle.js';
26
+ 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';
22
27
  export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
23
28
  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';
24
29
  export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecoveryVerdict, type RecoveryRefusalReason, type RecoverySignerEligibleParams, type RecoveryVerdict, recoverySignerEligible, type SealRecoveryVerdictParams, sealRecoveryVerdict, } from './recovery-verdict.js';
25
- export { authority, beaconOf, type ControllerBeacon, type ControllerProjection, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, type Revocation, type RevokedEffect, registrySeed, revocationOf, } from './registry.js';
30
+ 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';
26
31
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
27
32
  export { mergeReceiveSecretTree } from './secret-tree.js';
28
- export { DuplicateMemberLeafError } from './stale-leaf.js';
33
+ export { bindingIssuedAt, DuplicateMemberLeafError } from './stale-leaf.js';
29
34
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
30
35
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/index.js CHANGED
@@ -3,24 +3,29 @@ export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCap
3
3
  export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability } from './authentication.js';
4
4
  export { mintLeafCapability, mintTrustedGrant } from './capability.js';
5
5
  export { decodeClientState, encodeClientState, sanitizeRatchetTree } from './codec.js';
6
+ export { effectDelta, ingestControllerLog } from './controller-ingest.js';
7
+ export { memberDropIndices } from './controller-log.js';
6
8
  export { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
7
9
  export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
10
+ export { createRegistryControllerResolver, prefixRelation } from './embedded-resolver.js';
8
11
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
9
12
  export { foldEnvelope } from './envelope-fold.js';
10
- export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
13
+ export { ClientStateReservationError, HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RecoveryKnowledgeError, RevokeProofError } from './errors.js';
11
14
  export { foldLedger } from './fold.js';
12
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';
13
- export { commitSelfRemovals, proposeSelfRemoval, removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
16
+ export { registryAt } from './group-handle.js';
17
+ export { attestTreeTime, commitSelfRemovals, controllerLogDelta, preservationClock, proposeSelfRemoval, publishControllerLog, removalEvidence, removeLapsedLeaves, renewLeaf, revokeWithProof, survivorTargets } from './group-lifecycle.js';
14
18
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
15
- export { HISTORY_HORIZON, historySize } from './history.js';
19
+ export { epochEventCount, HISTORY_HORIZON, historySize, MAX_EPOCH_EVENTS_FOR_LEAVES, proofSize, SETTLE_PROMPT_EPOCH_EVENTS, settleAdvisory } from './history.js';
16
20
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
17
21
  export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
18
- export { assertRecoveryBinding } from './lifecycle.js';
22
+ export { assertRecoveryBinding, attestedTreeTime, leafExpiry } from './lifecycle.js';
23
+ export { cascadeOf, claimsFor, effectiveAuthorityOf, effectOf, memberRootStatus, memberRootsOf } from './member-root.js';
19
24
  export { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
20
25
  export { createRecoveryRequest, openRecoveryGroupInfo, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, RecoveryRequestError, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, SealedLedgerError, sealGroupInfo, sealLedger, verifyRecoveryRequest } from './recovery.js';
21
26
  export { confirmationKey, confirmationTag, openRecoveryVerdict, recoverySignerEligible, sealRecoveryVerdict } from './recovery-verdict.js';
22
- export { authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, registrySeed, revocationOf } from './registry.js';
27
+ export { assertRetainsKnownEffects, authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, recordedLogOf, registryForLog, registrySeed, revocationOf } from './registry.js';
23
28
  export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
24
29
  export { mergeReceiveSecretTree } from './secret-tree.js';
25
- export { DuplicateMemberLeafError } from './stale-leaf.js';
30
+ export { bindingIssuedAt, DuplicateMemberLeafError } from './stale-leaf.js';
26
31
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
@@ -1,24 +1,32 @@
1
- import { type SignedEvent } from '@kokuin/controller';
1
+ import { type ControllerLog } from '@kokuin/controller';
2
2
  import { type LeafNode } from 'ts-mls';
3
+ import { ingestControllerLog } from './controller-ingest.js';
3
4
  import type { GroupHandle } from './group-handle.js';
4
5
  import type { VerifiedLedgerEntry } from './ledger.js';
6
+ import { type RemovedEffect } from './member-root.js';
5
7
  import { type DeviceRegistry, type DeviceValue, type RevokedEffect } from './registry.js';
6
8
  export { controllerLogSize, HISTORY_HORIZON } from './history.js';
7
9
  /** Derived from a proof and the pre-commit tree; proposal comparison belongs to the commit gate. */
8
10
  export type LifecycleProofEffects = {
9
11
  controller: string;
10
- recordedLog: Array<SignedEvent>;
12
+ recordedLog: ControllerLog;
11
13
  genFloor: number;
12
14
  timeFloor: number;
13
- logPosition?: number;
14
15
  revoked: Array<RevokedEffect>;
16
+ removed: Array<RemovedEffect>;
15
17
  removeLeafIndices: Array<number>;
16
18
  };
17
19
  type AuthenticatedProof = {
18
- recordedLog: Array<SignedEvent>;
20
+ recordedLog: ControllerLog;
19
21
  genFloor: number;
20
- logPosition: number;
22
+ resetRef?: {
23
+ snapshot: number;
24
+ };
21
25
  };
26
+ /** Keep controller merge limits inside the lifecycle proof error boundary. */
27
+ export declare function mergeLifecycleProofLogs(controller: string, first: ControllerLog, second: ControllerLog): ControllerLog;
28
+ /** Reattach historical closures without reviving unapplied current-epoch events. */
29
+ export declare function lifecycleProofLog(controller: string, ingested: ReturnType<typeof ingestControllerLog>, proof: ControllerLog): ControllerLog;
22
30
  /** Authenticate replayable log data without reading any membership state. */
23
31
  export declare function authenticateLifecycleProof(controllerID: string, verified: VerifiedLedgerEntry<DeviceValue>, registry: DeviceRegistry): AuthenticatedProof;
24
32
  /**
@@ -30,4 +38,5 @@ export declare function isEvidencedChild(group: GroupHandle, leaf: LeafNode, den
30
38
  /** Whether the member at `leafIndex` is an evidenced child that a cascade leaves in place. */
31
39
  export declare function isExemptMember(group: GroupHandle, leafIndex: number): boolean;
32
40
  /** Verify live effects while all leaves still describe the epoch before the commit. */
33
- export declare function verifyLifecycleProof(group: GroupHandle, verified: VerifiedLedgerEntry<DeviceValue>): Promise<LifecycleProofEffects>;
41
+ export declare function lifecycleProofEffects(group: GroupHandle, verified: VerifiedLedgerEntry<DeviceValue>, registry?: DeviceRegistry): Promise<LifecycleProofEffects>;
42
+ export declare function verifyLifecycleProof(group: GroupHandle, verified: VerifiedLedgerEntry<DeviceValue>, registry?: DeviceRegistry): Promise<LifecycleProofEffects>;
@@ -1,102 +1,91 @@
1
- import { didFromInception } from '@kokuin/controller';
2
- import { normalizeDID } from '@kokuin/token';
1
+ import { assertCapabilityToken, checkCapability } from '@kokuin/capability';
2
+ import { isControllerLog, LOG_TOO_LARGE, mergeLogs } from '@kokuin/controller';
3
+ import { normalizeDID, verifyToken } from '@kokuin/token';
3
4
  import { defaultCredentialTypes, isDefaultCredential, nodeTypes } from 'ts-mls';
4
5
  import { hasHolderEvidence } from './authentication.js';
5
- import { readCapability } from './capability.js';
6
- import { foldChain, isDetachedFoldReason, revokesSubject } from './controller-log.js';
6
+ import { assertCapabilityLifetime, assertControllerGrant, capabilityKey, MLS_LEAF_ACT, MLS_LEAF_RES, readCapability } from './capability.js';
7
+ import { effectDelta, ingestControllerLog } from './controller-ingest.js';
8
+ import { foldChain, foldControllerLog } from './controller-log.js';
7
9
  import { parseMLSCredentialIdentity } from './credential.js';
8
- import { RevokeProofError } from './errors.js';
9
- import { controllerLogSize, HISTORY_HORIZON, historySize } from './history.js';
10
- import { denySetOf, isResetOnly } from './registry.js';
10
+ import { createRegistryControllerResolver } from './embedded-resolver.js';
11
+ import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
12
+ import { controllerLogSize, HISTORY_HORIZON, historySize, proofSize } from './history.js';
13
+ import { attestedTreeTime, isLapsed, leafAt } from './lifecycle.js';
14
+ import { cascadeOf, effectiveAttestingMembers, effectProofContext, memberRootStatus } from './member-root.js';
15
+ import { denySetOf, registryApply } from './registry.js';
11
16
  export { controllerLogSize, HISTORY_HORIZON } from './history.js';
17
+ /** Keep controller merge limits inside the lifecycle proof error boundary. */ export function mergeLifecycleProofLogs(controller, first, second) {
18
+ try {
19
+ return mergeLogs(controller, first, second);
20
+ } catch (cause) {
21
+ if (!(cause instanceof Error) || !cause.message.startsWith(LOG_TOO_LARGE)) throw cause;
22
+ const error = new RevokeProofError('too-large');
23
+ error.cause = cause;
24
+ throw error;
25
+ }
26
+ }
27
+ /** Reattach historical closures without reviving unapplied current-epoch events. */ export function lifecycleProofLog(controller, ingested, proof) {
28
+ return mergeLifecycleProofLogs(controller, ingested.log, {
29
+ chain: ingested.log.chain,
30
+ events: proof.events.filter(({ event })=>event.e !== ingested.after.head.epoch)
31
+ });
32
+ }
12
33
  /** Authenticate replayable log data without reading any membership state. */ export function authenticateLifecycleProof(controllerID, verified, registry) {
13
34
  const controller = normalizeDID(controllerID);
14
35
  const subject = normalizeDID(verified.entry.subject);
15
36
  const value = verified.entry.value;
16
37
  const previous = registry.controllers.get(controller);
17
- const recorded = previous?.recordedLog ?? [];
18
38
  const floor = previous?.genFloor ?? 0;
19
- if (value.controller != null && normalizeDID(value.controller) !== controller || value.op === 'reset' && subject !== controller) throw new RevokeProofError('wrong-controller');
39
+ if (value.controller != null && normalizeDID(value.controller) !== controller || subject !== controller) throw new RevokeProofError('wrong-controller');
20
40
  const proof = value.proof;
21
- if (!Array.isArray(proof)) throw new RevokeProofError('no-rev');
22
- if (recorded.length === 0 && proof.length === 0) throw new RevokeProofError('no-rev');
23
- for (const signed of proof){
24
- const event = signed?.event;
25
- if (event == null || event.t !== 'icp' && event.t !== 'rot') {
26
- throw new RevokeProofError('not-authority-signed');
27
- }
28
- if ('cap' in event && event.cap != null) throw new RevokeProofError('not-authority-signed');
29
- if (event.t === 'icp') {
30
- let inceptionDID;
31
- try {
32
- inceptionDID = didFromInception(event);
33
- } catch (cause) {
34
- const rejection = new RevokeProofError('not-authority-signed');
35
- rejection.cause = cause;
36
- throw rejection;
37
- }
38
- if (normalizeDID(inceptionDID) !== controller) throw new RevokeProofError('wrong-controller');
39
- } else if (event.i !== controller) {
40
- throw new RevokeProofError('wrong-controller');
41
+ if (value.op === 'log' || value.op === 'seed') {
42
+ if (!isControllerLog(proof)) throw new RevokeProofError('not-authority-signed');
43
+ if (value.op === 'seed' ? previous?.recordedLog != null : previous?.recordedLog == null) throw new RevokeProofError('detached');
44
+ const ingested = ingestControllerLog(controller, previous?.recordedLog, proof, previous);
45
+ if (value.op === 'log') {
46
+ if (ingested.introduced.length === 0 && ingested.before?.states.at(-1)?.digest === ingested.after.states.at(-1)?.digest) throw new RevokeProofError('effects-mismatch');
47
+ const delta = effectDelta(ingested.before?.head, ingested.after.head);
48
+ if (delta.generation) throw new RevokeProofError('needs-reset');
49
+ if (delta.denied.length > 0 || delta.removed.length > 0) throw new RevokeProofError('effects-mismatch');
41
50
  }
42
- }
43
- // An old full chain must report the floor even though it cannot attach after a reset.
44
- if (proof.length > 0 && proof.every(({ event })=>event.g < floor)) {
45
- throw new RevokeProofError('generation-floor');
46
- }
47
- if (value.op === 'revoke' && recorded.length > 0 && proof[0]?.event.t === 'icp') {
48
- throw new RevokeProofError('detached');
49
- }
50
- if (value.op === 'revoke' && recorded.length > 0) {
51
- const generation = recorded.at(-1)?.event.g ?? 0;
52
- if (proof.some(({ event })=>event.g > generation)) throw new RevokeProofError('needs-reset');
53
- }
54
- const log = value.op === 'reset' ? proof : [
55
- ...recorded,
56
- ...proof
57
- ];
58
- const folded = foldChain(controller, log);
59
- if (!folded.ok) {
60
- const detached = isDetachedFoldReason(folded.reason);
61
- throw new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
62
- }
63
- for(let index = 1; index < folded.states.length; index++){
64
- if (folded.states[index]?.digest === folded.states[index - 1]?.digest) {
65
- throw new RevokeProofError('not-authority-signed');
66
- }
67
- }
68
- if (value.op === 'reset') {
69
- let position = -1;
70
- for(let index = 1; index < log.length; index++){
71
- if (log[index]?.event.g !== log[index - 1]?.event.g) position = index;
72
- }
73
- const generation = folded.states[position]?.gen;
74
- if (generation == null) throw new RevokeProofError('no-rev');
75
- if (generation <= floor) throw new RevokeProofError('generation-floor');
76
51
  return {
77
- recordedLog: [
78
- ...log
79
- ],
80
- genFloor: generation,
81
- logPosition: position
52
+ recordedLog: ingested.log,
53
+ genFloor: Math.max(floor, ingested.after.head.gen)
82
54
  };
83
55
  }
84
- let belowFloor = false;
85
- for (const [index, state] of folded.states.entries()){
86
- if (!revokesSubject(log, folded.states, index, subject)) continue;
87
- if (state.gen < floor) {
88
- belowFloor = true;
89
- continue;
90
- }
91
- return {
92
- recordedLog: [
93
- ...log
94
- ],
95
- genFloor: floor,
96
- logPosition: index
97
- };
56
+ if (!isControllerLog(proof)) throw new RevokeProofError('no-rev');
57
+ if (proof.chain.length > 0 && proof.chain.every(({ event })=>event.g < floor)) throw new RevokeProofError('generation-floor');
58
+ if (value.op === 'reset' && proof.chain[0]?.event.t === 'icp' && proof.chain.every(({ event })=>event.g <= floor)) throw new RevokeProofError('generation-floor');
59
+ if (value.op === 'revoke' && proof.chain.some(({ event })=>event.g > (previous?.genFloor ?? 0))) throw new RevokeProofError('needs-reset');
60
+ const ingested = ingestControllerLog(controller, previous?.recordedLog, proof, previous);
61
+ if (ingested.after.head.saturated) throw new RevokeProofError('too-large');
62
+ const delta = effectDelta(ingested.before?.head, ingested.after.head);
63
+ if (value.op === 'reset') {
64
+ if (!delta.generation || ingested.after.head.gen <= floor) throw new RevokeProofError('generation-floor');
65
+ } else if (delta.generation) throw new RevokeProofError('needs-reset');
66
+ const proofLog = lifecycleProofLog(controller, ingested, proof);
67
+ const context = effectProofContext(controller, proofLog);
68
+ const expected = context.claimsFor(previous?.recordedLog, floor);
69
+ if (value.effects == null || value.effects.length === 0 && value.op !== 'reset') throw new RevokeProofError('no-rev');
70
+ const target = (claim)=>claim.kind === 'deny' ? `deny:${normalizeDID(claim.did)}` : `remove:${normalizeDID(claim.member.did)}:${claim.member.add}`;
71
+ if (value.effects.length !== expected.length || expected.some((claim, index)=>{
72
+ const declared = value.effects?.[index];
73
+ return declared == null || target(claim) !== target(declared);
74
+ })) throw new RevokeProofError('effects-mismatch');
75
+ for (const claim of value.effects){
76
+ if (value.op !== 'reset' && 'snapshot' in claim.ref) throw new RevokeProofError('no-rev');
77
+ context.effectOf(claim, floor);
98
78
  }
99
- throw new RevokeProofError(belowFloor ? 'generation-floor' : 'no-rev');
79
+ const resetIndex = value.op === 'reset' ? ingested.log.chain.findIndex(({ event }, index, chain)=>index > 0 && event.g > (chain[index - 1]?.event.g ?? 0)) : -1;
80
+ return {
81
+ recordedLog: ingested.log,
82
+ genFloor: Math.max(floor, ingested.after.head.gen),
83
+ ...resetIndex < 0 ? {} : {
84
+ resetRef: {
85
+ snapshot: resetIndex
86
+ }
87
+ }
88
+ };
100
89
  }
101
90
  /**
102
91
  * A leaf that stays when its issuer is denied: in a group whose anchor names a controller, a
@@ -127,7 +116,7 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
127
116
  return cascadedFrom === effect.cascadedFrom;
128
117
  });
129
118
  }
130
- /** Verify live effects while all leaves still describe the epoch before the commit. */ export async function verifyLifecycleProof(group, verified) {
119
+ /** Verify live effects while all leaves still describe the epoch before the commit. */ export async function lifecycleProofEffects(group, verified, registry = group.registry) {
131
120
  const controllerID = group.anchor.controller;
132
121
  if (controllerID == null) throw new RevokeProofError('wrong-controller');
133
122
  const controller = normalizeDID(controllerID);
@@ -137,78 +126,158 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
137
126
  if (verified.entry.groupID !== group.groupID || issuerController == null || normalizeDID(issuerController) !== controller) {
138
127
  throw new RevokeProofError('wrong-controller');
139
128
  }
140
- const previous = group.registry.controllers.get(controller);
129
+ const previous = registry.controllers.get(controller);
141
130
  const leaves = group.listMembers().map((member)=>{
142
131
  const binding = group.bindingOfDID(member.id);
143
- const capability = binding?.capability == null ? undefined : readCapability(binding.capability);
144
- const parent = capability?.payload.cap;
145
- const parentRaw = Array.isArray(parent) ? parent[0] : parent;
146
- const issuer = parentRaw == null || capability == null ? undefined : normalizeDID(capability.payload.iss);
147
- const attested = parentRaw == null ? capability?.payload.iat : readCapability(parentRaw).payload.iat;
148
132
  const folded = binding?.prefix == null ? undefined : foldChain(controller, binding.prefix);
149
133
  return {
150
134
  did: normalizeDID(member.id),
151
135
  leafIndex: member.leafIndex,
152
- issuer,
153
- exempt: isExemptMember(group, member.leafIndex),
154
136
  generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
155
- attested: binding?.controller != null && normalizeDID(binding.controller) === controller ? attested : undefined,
156
137
  prefix: binding?.prefix ?? []
157
138
  };
158
139
  });
159
140
  const timeFloor = previous?.timeFloor ?? 0;
160
141
  if (value.op === 'clock') {
161
- const treeTime = Math.max(timeFloor, ...leaves.map((leaf)=>leaf.attested ?? 0));
162
142
  if (subject !== controller) throw new RevokeProofError('wrong-controller');
163
- if (value.time == null || !Number.isFinite(value.time) || value.time <= timeFloor || value.time > treeTime) {
143
+ if (value.time == null || !Number.isFinite(value.time)) throw new RevokeProofError('effects-mismatch');
144
+ if (value.attest === true) {
145
+ const folded = previous?.recordedLog == null ? undefined : foldControllerLog(controller, previous.recordedLog);
146
+ const eligible = effectiveAttestingMembers(folded?.ok ? folded.head : undefined, previous, value.time).some(([, member])=>normalizeDID(member.did) === normalizeDID(verified.issuer) && value.time > (previous?.attestations.get(member.key) ?? 0));
147
+ if (!eligible) throw new RevokeProofError('effects-mismatch');
148
+ } else if (value.time <= timeFloor || value.time > Math.max(attestedTreeTime(group.state.ratchetTree, group.registry, controller), attestedTreeTime(group.state.ratchetTree, registry, controller))) {
164
149
  throw new RevokeProofError('effects-mismatch');
165
150
  }
166
151
  return {
167
152
  controller,
168
- recordedLog: previous?.recordedLog ?? [],
153
+ recordedLog: previous?.recordedLog ?? {
154
+ chain: [],
155
+ events: []
156
+ },
169
157
  genFloor: previous?.genFloor ?? 0,
170
- timeFloor: value.time,
158
+ timeFloor: value.attest === true ? timeFloor : value.time,
171
159
  revoked: [],
160
+ removed: [],
172
161
  removeLeafIndices: []
173
162
  };
174
163
  }
175
- const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
176
- const revoked = [];
177
- if (value.op === 'revoke') {
178
- const record = group.registry.devices.get(subject);
179
- if (record?.status === 'revoked' && !isResetOnly(record)) throw new RevokeProofError('effects-mismatch');
180
- revoked.push({
181
- did: subject
182
- });
183
- } else if (value.op === 'reset') {
184
- for (const leaf of leaves){
185
- if (leaf.generation != null && leaf.generation < authenticated.genFloor) revoked.push({
186
- did: leaf.did
187
- });
188
- }
189
- } else {
190
- throw new RevokeProofError('no-rev');
164
+ const authenticated = authenticateLifecycleProof(controller, verified, registry);
165
+ if (value.op === 'log') {
166
+ const index = group.findMemberLeafIndex(verified.issuer);
167
+ const leaf = index == null ? undefined : leafAt(group.state.ratchetTree, index);
168
+ if (leaf == null) throw new RevokeProofError('wrong-controller');
169
+ if (denySetOf(registry).has(normalizeDID(verified.issuer))) throw new LeafBindingError('denied-id');
170
+ if (isLapsed(group, leaf, registry)) throw new LeafLapsedError('lapsed');
171
+ const before = historySize(group.state.ratchetTree, group.ledger.map(({ verified })=>verified));
172
+ if (before + proofSize(value.proof) > HISTORY_HORIZON) throw new RevokeProofError('too-large');
173
+ return {
174
+ controller,
175
+ ...authenticated,
176
+ timeFloor,
177
+ revoked: [],
178
+ removed: [],
179
+ removeLeafIndices: []
180
+ };
191
181
  }
192
- const direct = new Set(revoked.map(({ did })=>did));
193
- for (const leaf of leaves){
194
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did) && !leaf.exempt) {
195
- revoked.push({
196
- did: leaf.did,
197
- cascadedFrom: leaf.issuer
198
- });
182
+ if (value.op !== 'revoke' && value.op !== 'reset') throw new RevokeProofError('no-rev');
183
+ const candidate = registryApply({
184
+ ...verified,
185
+ entry: {
186
+ ...verified.entry,
187
+ value: {
188
+ ...value,
189
+ revoked: []
190
+ }
199
191
  }
192
+ }, registry, controller);
193
+ for (const raw of value.survivors ?? []){
194
+ const { payload } = readCapability(raw);
195
+ assertControllerGrant(payload, controller);
196
+ if (payload.mbr == null || payload.cap != null) throw new LeafBindingError('issuer-mismatch');
197
+ assertCapabilityLifetime(payload, group.anchor.trustedGrantLifetime ?? 2_592_000);
198
+ const leaf = group.bindingOfDID(payload.aud);
199
+ const key = capabilityKey(payload).publicKey;
200
+ if (leaf?.controller !== controller || key.length !== leaf.leafKey.length || key.some((byte, index)=>byte !== leaf.leafKey[index])) throw new LeafBindingError('confirmation-invalid');
201
+ const status = memberRootStatus(candidate, controller, {
202
+ kind: 'member',
203
+ did: payload.iss,
204
+ add: payload.mbr.add,
205
+ gen: payload.mbr.g
206
+ });
207
+ if (status.status !== 'effective') throw new LeafBindingError(status.status === 'removed' ? 'member-removed' : 'member-unavailable');
208
+ const resolver = createRegistryControllerResolver({
209
+ controllerID: controller,
210
+ prefix: candidate.controllers.get(controller)?.recordedLog?.chain ?? [],
211
+ registry: candidate
212
+ }).frozen();
213
+ const token = await verifyToken(raw, {
214
+ methods: [
215
+ resolver
216
+ ],
217
+ historic: true,
218
+ atTime: payload.iat,
219
+ allowUnsigned: false
220
+ });
221
+ assertCapabilityToken(token);
222
+ await checkCapability({
223
+ act: MLS_LEAF_ACT,
224
+ res: MLS_LEAF_RES
225
+ }, payload, {
226
+ atTime: payload.iat,
227
+ methods: [
228
+ resolver
229
+ ],
230
+ maxDepth: 1,
231
+ maxMemberGrantLifetime: group.anchor.trustedGrantLifetime ?? 2_592_000
232
+ });
200
233
  }
201
- if (!effectsMatch(value.revoked, revoked)) throw new RevokeProofError('effects-mismatch');
202
- const affected = new Set(revoked.map(({ did })=>did));
203
- const removed = leaves.filter(({ did })=>affected.has(did));
234
+ const resetRef = authenticated.resetRef;
235
+ if (value.op === 'reset' && resetRef == null) throw new RevokeProofError('no-rev');
236
+ const resetDIDs = new Set(value.op === 'reset' ? leaves.filter((leaf)=>leaf.generation != null && leaf.generation < authenticated.genFloor).map(({ did })=>did) : []);
237
+ const claims = resetRef == null ? [
238
+ ...value.effects ?? []
239
+ ] : [
240
+ ...[
241
+ ...resetDIDs
242
+ ].map((did)=>({
243
+ kind: 'deny',
244
+ did,
245
+ ref: resetRef
246
+ })),
247
+ ...(value.effects ?? []).filter((claim)=>claim.kind !== 'deny' || !resetDIDs.has(normalizeDID(claim.did)))
248
+ ];
249
+ const cascade = cascadeOf(group.listMembers().flatMap((member)=>{
250
+ const binding = group.bindingOfDID(member.id);
251
+ if (binding?.controller == null || binding.prefix == null) return [];
252
+ return [
253
+ {
254
+ did: member.id,
255
+ leafIndex: member.leafIndex,
256
+ binding: {
257
+ ...binding,
258
+ id: binding.controller,
259
+ prefix: binding.prefix
260
+ },
261
+ leafKey: binding.leafKey
262
+ }
263
+ ];
264
+ }), claims, registry, candidate, controller);
265
+ if (value.op === 'reset') cascade.revoked = cascade.revoked.filter(({ did, cascadedFrom })=>resetDIDs.has(did) || cascadedFrom != null);
266
+ const affected = new Set(cascade.removeLeafIndices);
267
+ const removed = leaves.filter(({ leafIndex })=>affected.has(leafIndex));
204
268
  const before = historySize(group.state.ratchetTree, group.ledger.map(({ verified })=>verified));
205
- const after = before + controllerLogSize(value.proof ?? []) - removed.reduce((size, leaf)=>size + controllerLogSize(leaf.prefix), 0);
269
+ const after = before + proofSize(value.proof) - removed.reduce((size, leaf)=>size + controllerLogSize(leaf.prefix), 0);
206
270
  if (after > HISTORY_HORIZON && after > before) throw new RevokeProofError('too-large');
207
271
  return {
208
272
  controller,
209
273
  ...authenticated,
210
274
  timeFloor,
211
- revoked,
212
- removeLeafIndices: removed.map(({ leafIndex })=>leafIndex)
275
+ ...cascade
213
276
  };
214
277
  }
278
+ export async function verifyLifecycleProof(group, verified, registry = group.registry) {
279
+ const effects = await lifecycleProofEffects(group, verified, registry);
280
+ const value = verified.entry.value;
281
+ if ((value.op === 'revoke' || value.op === 'reset') && (!effectsMatch(value.revoked, effects.revoked) || !effectsMatch(value.removed, effects.removed))) throw new RevokeProofError('effects-mismatch');
282
+ return effects;
283
+ }
@@ -1,19 +1,22 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
2
  import { type ClientState, type GroupContextExtension, type IncomingMessageCallback, type LeafNode } from 'ts-mls';
3
+ import { type JudgingContext } from './authentication.js';
3
4
  import { type ControllerBinding } from './credential.js';
4
- import type { GroupHandle } from './group-handle.js';
5
+ import { type GroupHandle } from './group-handle.js';
5
6
  import type { VerifiedLedgerEntry } from './ledger.js';
6
7
  import { type CommitPolicyContext } from './policy.js';
7
8
  import { type DeviceRegistry } from './registry.js';
8
9
  export type CommitRejectionReason = 'binding' | 'lapse' | 'floor' | 'policy' | 'invalid';
9
10
  export declare function rejectionReason(error: unknown): CommitRejectionReason;
10
11
  export declare function leafAt(tree: ClientState['ratchetTree'], index: number): LeafNode | undefined;
11
- export declare function treeTime(group: GroupHandle, controllerID: string): number;
12
- export declare function isLapsed(group: GroupHandle, leaf: LeafNode): boolean;
13
- export declare function validateEntry(group: GroupHandle, leaf: LeafNode, previous?: LeafNode): Promise<void>;
12
+ export declare function attestedTreeTime(tree: ClientState['ratchetTree'], registry: DeviceRegistry, controllerID: string): number;
13
+ export declare function treeTime(group: GroupHandle, controllerID: string, registry?: DeviceRegistry): number;
14
+ export declare function isLapsed(group: GroupHandle, leaf: LeafNode, registry?: DeviceRegistry): boolean;
15
+ export declare function leafExpiry(binding: ControllerBinding, registry: DeviceRegistry, controller: string): number | undefined;
16
+ export declare function validateEntry(group: GroupHandle, leaf: LeafNode, previous?: LeafNode, judging?: JudgingContext): Promise<void>;
14
17
  /** The same credential and key a tree already holds at that leaf index. */
15
18
  export declare function isUnchangedLeaf(tree: ClientState['ratchetTree'], index: number, leaf: Pick<LeafNode, 'credential' | 'signaturePublicKey'>): boolean;
16
- export declare function validateWelcomeTree(group: GroupHandle): Promise<void>;
19
+ export declare function validateWelcomeTree(group: GroupHandle, judging?: JudgingContext): Promise<void>;
17
20
  type IncomingMessage = Parameters<IncomingMessageCallback>[0];
18
21
  export type PrepareLifecycleGateParams = {
19
22
  group: GroupHandle;
@@ -34,7 +37,7 @@ export type AssertSenderNotLapsedParams = {
34
37
  leafIndex: number | null | undefined;
35
38
  extensions: Array<GroupContextExtension>;
36
39
  };
37
- /** Historical messages use the tree and clock floor authenticated in their own epoch. */
40
+ /** Historical messages use the tree and registry authenticated in their own epoch. */
38
41
  export declare function assertSenderNotLapsed(params: AssertSenderNotLapsedParams): void;
39
42
  export type AssertRecoveryBindingParams = {
40
43
  group: GroupHandle;