@kumiai/mls 0.10.9 → 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 +8 -4
  3. package/lib/authentication.js +210 -54
  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 +10 -0
  9. package/lib/controller-log.js +71 -0
  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 -15
  14. package/lib/embedded-resolver.js +53 -16
  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 +102 -16
  26. package/lib/group-lifecycle.d.ts +31 -5
  27. package/lib/group-lifecycle.js +253 -154
  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 +196 -132
  37. package/lib/lifecycle.d.ts +9 -6
  38. package/lib/lifecycle.js +196 -86
  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 +32 -15
  43. package/lib/registry.d.ts +17 -6
  44. package/lib/registry.js +205 -21
  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,107 +1,91 @@
1
- import { didFromInception, foldLog } 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 { 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';
6
9
  import { parseMLSCredentialIdentity } from './credential.js';
7
- import { RevokeProofError } from './errors.js';
8
- import { controllerLogSize, HISTORY_HORIZON, historySize } from './history.js';
9
- 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';
10
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
+ }
11
33
  /** Authenticate replayable log data without reading any membership state. */ export function authenticateLifecycleProof(controllerID, verified, registry) {
12
34
  const controller = normalizeDID(controllerID);
13
35
  const subject = normalizeDID(verified.entry.subject);
14
36
  const value = verified.entry.value;
15
37
  const previous = registry.controllers.get(controller);
16
- const recorded = previous?.recordedLog ?? [];
17
38
  const floor = previous?.genFloor ?? 0;
18
- 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');
19
40
  const proof = value.proof;
20
- if (!Array.isArray(proof)) throw new RevokeProofError('no-rev');
21
- if (recorded.length === 0 && proof.length === 0) throw new RevokeProofError('no-rev');
22
- for (const signed of proof){
23
- const event = signed?.event;
24
- if (event == null || event.t !== 'icp' && event.t !== 'rot' && event.t !== 'rev') {
25
- throw new RevokeProofError('not-authority-signed');
26
- }
27
- if ('cap' in event && event.cap != null) throw new RevokeProofError('not-authority-signed');
28
- if (event.t === 'icp') {
29
- let inceptionDID;
30
- try {
31
- inceptionDID = didFromInception(event);
32
- } catch (cause) {
33
- const rejection = new RevokeProofError('not-authority-signed');
34
- rejection.cause = cause;
35
- throw rejection;
36
- }
37
- if (normalizeDID(inceptionDID) !== controller) throw new RevokeProofError('wrong-controller');
38
- } else if (event.i !== controller) {
39
- 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');
40
50
  }
41
- }
42
- // An old full chain must report the floor even though it cannot attach after a reset.
43
- if (proof.length > 0 && proof.every(({ event })=>event.g < floor)) {
44
- throw new RevokeProofError('generation-floor');
45
- }
46
- if (value.op === 'revoke' && recorded.length > 0 && proof[0]?.event.t === 'icp') {
47
- throw new RevokeProofError('detached');
48
- }
49
- if (value.op === 'revoke' && recorded.length > 0) {
50
- const generation = recorded.at(-1)?.event.g ?? 0;
51
- if (proof.some(({ event })=>event.g > generation)) throw new RevokeProofError('needs-reset');
52
- }
53
- const log = value.op === 'reset' ? proof : [
54
- ...recorded,
55
- ...proof
56
- ];
57
- const folded = foldLog(controller, log);
58
- if (!folded.ok) {
59
- const detached = folded.reason.includes('sequence') || folded.reason.includes('digest') || folded.reason.includes('prior') || folded.reason.includes('inception must');
60
- throw new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
61
- }
62
- for(let index = 1; index < folded.states.length; index++){
63
- if (folded.states[index]?.digest === folded.states[index - 1]?.digest) {
64
- throw new RevokeProofError('not-authority-signed');
65
- }
66
- }
67
- if (value.op === 'reset') {
68
- let position = -1;
69
- for(let index = 1; index < log.length; index++){
70
- if (log[index]?.event.g !== log[index - 1]?.event.g) position = index;
71
- }
72
- const generation = folded.states[position]?.gen;
73
- if (generation == null) throw new RevokeProofError('no-rev');
74
- if (generation <= floor) throw new RevokeProofError('generation-floor');
75
51
  return {
76
- recordedLog: [
77
- ...log
78
- ],
79
- genFloor: generation,
80
- logPosition: position
52
+ recordedLog: ingested.log,
53
+ genFloor: Math.max(floor, ingested.after.head.gen)
81
54
  };
82
55
  }
83
- let belowFloor = false;
84
- for(let index = 0; index < log.length; index++){
85
- const event = log[index]?.event;
86
- const state = folded.states[index];
87
- if (event?.t !== 'rev' || !('x' in event) || typeof event.x !== 'string' || state == null) continue;
88
- if (normalizeDID(event.x) !== subject) continue;
89
- if (![
90
- ...state.deny
91
- ].some((did)=>normalizeDID(did) === subject)) continue;
92
- if (state.gen < floor) {
93
- belowFloor = true;
94
- continue;
95
- }
96
- return {
97
- recordedLog: [
98
- ...log
99
- ],
100
- genFloor: floor,
101
- logPosition: index
102
- };
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);
103
78
  }
104
- 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
+ };
105
89
  }
106
90
  /**
107
91
  * A leaf that stays when its issuer is denied: in a group whose anchor names a controller, a
@@ -132,7 +116,7 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
132
116
  return cascadedFrom === effect.cascadedFrom;
133
117
  });
134
118
  }
135
- /** 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) {
136
120
  const controllerID = group.anchor.controller;
137
121
  if (controllerID == null) throw new RevokeProofError('wrong-controller');
138
122
  const controller = normalizeDID(controllerID);
@@ -142,78 +126,158 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
142
126
  if (verified.entry.groupID !== group.groupID || issuerController == null || normalizeDID(issuerController) !== controller) {
143
127
  throw new RevokeProofError('wrong-controller');
144
128
  }
145
- const previous = group.registry.controllers.get(controller);
129
+ const previous = registry.controllers.get(controller);
146
130
  const leaves = group.listMembers().map((member)=>{
147
131
  const binding = group.bindingOfDID(member.id);
148
- const capability = binding?.capability == null ? undefined : readCapability(binding.capability);
149
- const parent = capability?.payload.cap;
150
- const parentRaw = Array.isArray(parent) ? parent[0] : parent;
151
- const issuer = parentRaw == null || capability == null ? undefined : normalizeDID(capability.payload.iss);
152
- const attested = parentRaw == null ? capability?.payload.iat : readCapability(parentRaw).payload.iat;
153
- const folded = binding?.prefix == null ? undefined : foldLog(controller, binding.prefix);
132
+ const folded = binding?.prefix == null ? undefined : foldChain(controller, binding.prefix);
154
133
  return {
155
134
  did: normalizeDID(member.id),
156
135
  leafIndex: member.leafIndex,
157
- issuer,
158
- exempt: isExemptMember(group, member.leafIndex),
159
136
  generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
160
- attested: binding?.controller != null && normalizeDID(binding.controller) === controller ? attested : undefined,
161
137
  prefix: binding?.prefix ?? []
162
138
  };
163
139
  });
164
140
  const timeFloor = previous?.timeFloor ?? 0;
165
141
  if (value.op === 'clock') {
166
- const treeTime = Math.max(timeFloor, ...leaves.map((leaf)=>leaf.attested ?? 0));
167
142
  if (subject !== controller) throw new RevokeProofError('wrong-controller');
168
- 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))) {
169
149
  throw new RevokeProofError('effects-mismatch');
170
150
  }
171
151
  return {
172
152
  controller,
173
- recordedLog: previous?.recordedLog ?? [],
153
+ recordedLog: previous?.recordedLog ?? {
154
+ chain: [],
155
+ events: []
156
+ },
174
157
  genFloor: previous?.genFloor ?? 0,
175
- timeFloor: value.time,
158
+ timeFloor: value.attest === true ? timeFloor : value.time,
176
159
  revoked: [],
160
+ removed: [],
177
161
  removeLeafIndices: []
178
162
  };
179
163
  }
180
- const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
181
- const revoked = [];
182
- if (value.op === 'revoke') {
183
- const record = group.registry.devices.get(subject);
184
- if (record?.status === 'revoked' && !isResetOnly(record)) throw new RevokeProofError('effects-mismatch');
185
- revoked.push({
186
- did: subject
187
- });
188
- } else if (value.op === 'reset') {
189
- for (const leaf of leaves){
190
- if (leaf.generation != null && leaf.generation < authenticated.genFloor) revoked.push({
191
- did: leaf.did
192
- });
193
- }
194
- } else {
195
- 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
+ };
196
181
  }
197
- const direct = new Set(revoked.map(({ did })=>did));
198
- for (const leaf of leaves){
199
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did) && !leaf.exempt) {
200
- revoked.push({
201
- did: leaf.did,
202
- cascadedFrom: leaf.issuer
203
- });
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
+ }
204
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
+ });
205
233
  }
206
- if (!effectsMatch(value.revoked, revoked)) throw new RevokeProofError('effects-mismatch');
207
- const affected = new Set(revoked.map(({ did })=>did));
208
- 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));
209
268
  const before = historySize(group.state.ratchetTree, group.ledger.map(({ verified })=>verified));
210
- 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);
211
270
  if (after > HISTORY_HORIZON && after > before) throw new RevokeProofError('too-large');
212
271
  return {
213
272
  controller,
214
273
  ...authenticated,
215
274
  timeFloor,
216
- revoked,
217
- removeLeafIndices: removed.map(({ leafIndex })=>leafIndex)
275
+ ...cascade
218
276
  };
219
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;