@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/README.md CHANGED
@@ -65,7 +65,7 @@ consumed-key state while leaving the pending record. No database transaction or
65
65
  may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc` port's optional
66
66
  `pending` adapter calls `decryptStaged` for durable logged events.
67
67
 
68
- ## Authority model
68
+ ## Standard-group authority model
69
69
 
70
70
  Authority is a **roster**, folded from a signed **control ledger** and rooted at a genesis anchor installed in the GroupContext when the group is created. There is no capability chain: a member's right to act is decided by the roster every peer computes independently, not by a token the member carries.
71
71
  - **The ledger is an ordered log of enactments.** Each entry is a token signed by its issuer (a `kumiai.role` entry names a subject DID and grants it `admin` or `member` of the group). The log is replayable and position-dependent: the same claim recurring later is meaningful — a demotion back to a previously-held role is exactly that.
@@ -75,6 +75,31 @@ Authority is a **roster**, folded from a signed **control ledger** and rooted at
75
75
 
76
76
  The invite carries the full ordered ledger plus the invitee's new role entry last, so a joiner folds the same roster the group holds and cannot fork from a role change made before it joined.
77
77
 
78
+ ## Management tier
79
+
80
+ Lifecycle groups bind every leaf to one controller. Creation requires `controller` and an authoritative `controllerLog`.
81
+ The first ledger entry seeds the registry, including existing denials and removed incarnations.
82
+ `ControllerBinding` carries a chain-only `prefix` and either `capability` or `member: { add, g }` plus ordering-only `iat`.
83
+ Member-issued capabilities carry `mbr: { add, g }`. The registry-held log supplies their pinned keys and leases.
84
+ Member roots are supported only in lifecycle groups. Admission refuses removed or unavailable roots.
85
+
86
+ `publishControllerLog` publishes effect-free log changes and settlement.
87
+ `createInvite` and `renewLeaf` can bundle `controllerLog` changes.
88
+ `revokeWithProof(group, { log, deny?, remove?, survivors?, evidence? })` proves denials or incarnation removals.
89
+ The reset form is `{ reset: true, log }`. Proofs carry `ControllerLog` and exact `EffectClaim` references.
90
+ References identify a chain index, epoch event or reset snapshot.
91
+ Removing an incarnation cascades through its rooted leaves. Valid holder or survivor grants can preserve them until their substitute expiry.
92
+ `removalEvidence` captures removal evidence before settlement. Hosts retain it beside their controller store.
93
+
94
+ Tree time combines a preserved floor, root-issued token times and effective-member attestations over distinct pinned keys.
95
+ The quorum uses the second-highest attestation, or the highest for one effective key.
96
+ Membership leaves advance time through `attestTreeTime`, without attesting their binding `iat`.
97
+ Member-rooted admission is capped at 32 applied epoch events. `settleAdvisory()` prompts from 24 and blocks above 32.
98
+ Existing leaves, Welcome trees, root-issued admission and lifecycle entries are exempt.
99
+ Recovery refuses candidates that discard known lifecycle effects, floors or effective-key attestations.
100
+
101
+ The [lifecycle reference](../../docs/reference/mls-lifecycle.md) defines binding, proof, time and recovery contracts.
102
+
78
103
  ## External rejoin (stale device recovery)
79
104
 
80
105
  Each device owns its MLS leaf and ratchet state. A device that stays offline long enough for the group to advance epochs (adds, removes, key rotations) can no longer decrypt current application messages. Replaying every missed commit sequentially is expensive and may be impossible if intermediate commits are no longer available.
@@ -100,6 +125,9 @@ const { commitMessage, group } = await joinGroupExternal({
100
125
  // epoch — ready to encrypt/decrypt.
101
126
  ```
102
127
 
128
+ Core callers holding known state must call `assertRetainsKnownEffects` in `beforeBinding` before adoption. mls-rpc installs this check.
129
+
130
+
103
131
  ### Trust model
104
132
 
105
133
  An external commit is enforced as a **resync of an existing roster member**, never a new join. Every receiver runs the commit policy on it: the committing DID (resolved from the commit's own UpdatePath leaf credential) must be in the roster, and the commit's proposals must be exactly one `external_init` plus one `remove` of the leaf whose DID equals that committer — nothing else. A stranger in no roster who obtains a leaked `GroupInfo` is rejected; a legitimate member rejoining is accepted. New members never arrive this way — they join through Welcome.
@@ -1,16 +1,20 @@
1
- import { type SignedEvent } from '@kokuin/controller';
1
+ import type { SignedEvent } from '@kokuin/controller';
2
2
  import type { AuthenticationService, Credential } from 'ts-mls';
3
3
  import { type MLSCredentialIdentity } from './credential.js';
4
4
  import { type DeviceRegistry } from './registry.js';
5
5
  export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
6
6
  /** The action a management capability must grant to mutate a profile's device registry. */
7
7
  export declare const MLS_DEVICES_ACT = "manage";
8
- /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */
8
+ /** The resource half — kumiai-namespaced and group-independent. */
9
9
  export declare const MLS_DEVICES_RES = "kumiai/devices";
10
+ export type JudgingContext = {
11
+ registry?: DeviceRegistry;
12
+ stage: 'structural' | 'full';
13
+ mode: 'admit' | 'retain' | 'rejudge';
14
+ };
10
15
  export type DIDAuthenticationDependencies = {
11
16
  deviceDenySet?: () => ReadonlySet<string>;
12
- /** Registry context permits authenticated post-reset subject admission. */
13
- deviceRegistry?: () => DeviceRegistry | undefined;
17
+ judging?: () => JudgingContext;
14
18
  leafLifetime?: () => number | undefined;
15
19
  trustedGrantLifetime?: () => number | undefined;
16
20
  /**
@@ -1,16 +1,18 @@
1
- import { assertCapabilityToken, assertValidDelegation, checkCapability, hasPermission } from '@kokuin/capability';
2
- import { foldLog } from '@kokuin/controller';
1
+ import { assertCapabilityToken, assertNonExpired, assertValidDelegation, assertValidIssuedAt, assertValidNotBefore, checkCapability, hasPermission } from '@kokuin/capability';
3
2
  import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, getVerifier, isPeer4, normalizeDID, verifyToken } from '@kokuin/token';
4
3
  import { fromB64U, fromUTF } from '@sozai/codec';
5
4
  import { defaultCredentialTypes } from 'ts-mls';
6
5
  import { assertCapabilityLifetime, assertControllerGrant, capabilityKey, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, MLS_LEAF_ACT, MLS_LEAF_RES, readCapability } from './capability.js';
6
+ import { foldChain } from './controller-log.js';
7
7
  import { parseMLSCredentialIdentity } from './credential.js';
8
- import { createEmbeddedControllerResolver } from './embedded-resolver.js';
8
+ import { createRegistryControllerResolver, prefixRelation } from './embedded-resolver.js';
9
9
  import { LeafBindingError } from './errors.js';
10
- import { denySetOf, mayReadmitResetDevice } from './registry.js';
10
+ import { epochEventCount, MAX_EPOCH_EVENTS_FOR_LEAVES } from './history.js';
11
+ import { effectiveAuthorityOf, memberRootStatus, memberRootsOf } from './member-root.js';
12
+ import { denySetOf, mayReadmitResetDevice, recordedLogOf } from './registry.js';
11
13
  export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
12
14
  /** The action a management capability must grant to mutate a profile's device registry. */ export const MLS_DEVICES_ACT = 'manage';
13
- /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */ export const MLS_DEVICES_RES = 'kumiai/devices';
15
+ /** The resource half — kumiai-namespaced and group-independent. */ export const MLS_DEVICES_RES = 'kumiai/devices';
14
16
  const EMPTY_DENY = new Set();
15
17
  function constantTimeEqual(a, b) {
16
18
  if (a.length !== b.length) return false;
@@ -72,7 +74,7 @@ function isDenied(denied, did) {
72
74
  return denied.has(did) || denied.has(normalizeDID(did));
73
75
  }
74
76
  /** Authenticate only embedded proof, using the token's issuance as its reference time. */ async function verifyPinnedCapability(params) {
75
- if (!params.controllerID.startsWith('did:kokuin:') || !foldLog(params.controllerID, params.prefix).ok) {
77
+ if (!params.controllerID.startsWith('did:kokuin:') || !foldChain(params.controllerID, params.prefix).ok) {
76
78
  throw new LeafBindingError('controller-mismatch');
77
79
  }
78
80
  const token = readCapability(params.capability);
@@ -92,11 +94,29 @@ function isDenied(denied, did) {
92
94
  throw new LeafBindingError('confirmation-invalid');
93
95
  }
94
96
  const denySet = params.denySet ?? EMPTY_DENY;
95
- const resolver = createEmbeddedControllerResolver({
97
+ const base = params.resolver ?? createRegistryControllerResolver({
96
98
  controllerID: params.controllerID,
97
- prefix: params.prefix,
98
- denySet
99
- });
99
+ prefix: params.prefix
100
+ }).frozen();
101
+ const resolver = {
102
+ ...base,
103
+ async resolveDenySet (did) {
104
+ await base.resolveDenySet?.(did);
105
+ return denySet;
106
+ }
107
+ };
108
+ const check = async (claims)=>{
109
+ if (params.stage === 'structural') return;
110
+ await checkCapability(params.permission, claims, {
111
+ atTime: payload.iat,
112
+ methods: [
113
+ resolver
114
+ ],
115
+ maxDepth: 1,
116
+ // Kokuin forwards this ceiling to the parent; local bounds still apply to each grant.
117
+ maxMemberGrantLifetime: MAX_TRUSTED_GRANT_LIFETIME
118
+ });
119
+ };
100
120
  if (payload.cap === undefined) {
101
121
  assertControllerGrant(payload, params.controllerID);
102
122
  const verified = await verifyToken(params.capability, {
@@ -108,6 +128,7 @@ function isDenied(denied, did) {
108
128
  allowUnsigned: false
109
129
  });
110
130
  assertCapabilityToken(verified);
131
+ await check(payload);
111
132
  return;
112
133
  }
113
134
  if (params.directOnly) throw new LeafBindingError('chain-depth');
@@ -127,32 +148,28 @@ function isDenied(denied, did) {
127
148
  throw new LeafBindingError('self-issued');
128
149
  }
129
150
  if (payload.exp > parent.payload.exp) throw new LeafBindingError('child-outlives-parent');
130
- if (isDenied(denySet, payload.iss)) throw new LeafBindingError('denied-issuer');
151
+ if (params.stage !== 'structural' && isDenied(denySet, payload.iss)) throw new LeafBindingError('denied-issuer');
131
152
  const issuerKey = capabilityKey(parent.payload);
132
153
  if (token.header.alg !== issuerKey.alg) throw new LeafBindingError('signature-invalid');
133
154
  if (!await getVerifier(token.header.alg)(fromB64U(token.signature), fromUTF(token.data), issuerKey.publicKey)) {
134
155
  throw new LeafBindingError('signature-invalid');
135
156
  }
136
- // checkCapability treats iss === sub as a root grant, so it does not walk that parent.
137
- if (normalizeDID(payload.iss) === normalizeDID(payload.sub)) {
138
- const verifiedParent = await verifyToken(parentRaw, {
139
- atTime: payload.iat,
140
- methods: [
141
- resolver
142
- ],
143
- historic: true,
144
- allowUnsigned: false
145
- });
146
- assertCapabilityToken(verifiedParent);
147
- assertValidDelegation(verifiedParent.payload, payload, payload.iat);
148
- }
149
- await checkCapability(params.permission, payload, {
157
+ assertNonExpired(payload, payload.iat);
158
+ assertValidIssuedAt(payload, payload.iat);
159
+ assertValidNotBefore(payload, payload.iat);
160
+ const verifiedParent = await verifyToken(parentRaw, {
150
161
  atTime: payload.iat,
151
162
  methods: [
152
163
  resolver
153
164
  ],
154
- maxDepth: 1
165
+ historic: true,
166
+ allowUnsigned: false
155
167
  });
168
+ assertCapabilityToken(verifiedParent);
169
+ assertValidDelegation(verifiedParent.payload, payload, payload.iat);
170
+ // A self-issued child bypasses kokuin's parent walk.
171
+ if (normalizeDID(payload.iss) === normalizeDID(payload.sub)) await check(parent.payload);
172
+ await check(payload);
156
173
  }
157
174
  function withoutIssuer(denied, capability) {
158
175
  const issuer = normalizeDID(readCapability(capability).payload.iss);
@@ -163,8 +180,13 @@ function withoutIssuer(denied, capability) {
163
180
  /** Structural evidence gate also used before MLS invokes its boolean authentication adapter. */ export function checkHolderEvidence(parsed, signaturePublicKey, trustedGrantLifetime = MAX_TRUSTED_GRANT_LIFETIME) {
164
181
  const binding = parsed.controller;
165
182
  if (binding == null) return;
183
+ if (binding.member != null) return;
184
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
166
185
  const leafPayload = readCapability(binding.capability).payload;
167
- if (leafPayload.cap === undefined) return;
186
+ if (leafPayload.cap === undefined) {
187
+ if (binding.holderGrant != null) throw new LeafBindingError('holder-evidence-mismatch');
188
+ return;
189
+ }
168
190
  if (binding.holderGrant == null) throw new LeafBindingError('missing-holder-evidence');
169
191
  try {
170
192
  const grant = readCapability(binding.holderGrant).payload;
@@ -175,6 +197,7 @@ function withoutIssuer(denied, capability) {
175
197
  res: MLS_LEAF_RES
176
198
  }, grant)) throw new LeafBindingError('holder-evidence-mismatch');
177
199
  } catch (cause) {
200
+ if (cause instanceof LeafBindingError && cause.reason === 'lifetime-cap' && readCapability(binding.holderGrant).payload.mbr != null) throw cause;
178
201
  const error = new LeafBindingError('holder-evidence-mismatch');
179
202
  error.cause = cause;
180
203
  throw error;
@@ -187,7 +210,8 @@ function withoutIssuer(denied, capability) {
187
210
  * issued its capability does not take that binding away.
188
211
  */ export function hasHolderEvidence(parsed, signaturePublicKey, denied, trustedGrantLifetime) {
189
212
  const binding = parsed.controller;
190
- if (binding == null || isDenied(denied, parsed.id)) return false;
213
+ if (binding == null || binding.member != null || isDenied(denied, parsed.id)) return false;
214
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
191
215
  try {
192
216
  if (readCapability(binding.capability).payload.cap === undefined) return false;
193
217
  return checkHolderEvidence(parsed, signaturePublicKey, trustedGrantLifetime) != null;
@@ -201,59 +225,190 @@ function withoutIssuer(denied, capability) {
201
225
  }
202
226
  const parsed = parseMLSCredentialIdentity(credential.identity);
203
227
  if (!matchesLeafKey(parsed, signaturePublicKey)) throw new LeafBindingError('identity-change');
204
- const registry = deps.deviceRegistry?.();
205
- const denied = deps.deviceDenySet?.() ?? (registry == null ? EMPTY_DENY : denySetOf(registry));
228
+ const judging = deps.judging?.() ?? {
229
+ stage: 'full',
230
+ mode: 'admit'
231
+ };
232
+ const registry = judging.registry;
233
+ const structural = judging.stage === 'structural';
234
+ const denied = structural ? EMPTY_DENY : deps.deviceDenySet?.() ?? (registry == null ? EMPTY_DENY : denySetOf(registry));
206
235
  if (isDenied(denied, parsed.id) && (registry == null || !mayReadmitResetDevice(registry, parsed))) throw new LeafBindingError('denied-id');
207
236
  // Exempt only this holder; every issuer remains subject to the full deny set.
208
237
  const denySet = isDenied(denied, parsed.id) ? new Set([
209
238
  ...denied
210
239
  ].filter((did)=>normalizeDID(did) !== normalizeDID(parsed.id))) : denied;
211
- if (parsed.controller == null) return;
212
- if (registry != null) {
213
- const folded = foldLog(parsed.controller.id, parsed.controller.prefix);
240
+ const binding = parsed.controller;
241
+ if (binding == null) return;
242
+ if (!structural && registry != null) {
243
+ const folded = foldChain(binding.id, binding.prefix);
214
244
  if (!folded.ok) throw new LeafBindingError('controller-mismatch');
215
- if ((folded.states.at(-1)?.gen ?? 0) < (registry.controllers.get(normalizeDID(parsed.controller.id))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
245
+ if ((folded.states.at(-1)?.gen ?? 0) < (registry.controllers.get(normalizeDID(binding.id))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
216
246
  }
217
247
  try {
218
- // The holder grant does not inherit the leaf capability's issuer exception.
219
- const leafDenySet = deps.mayKeepDeniedIssuer?.(credential, signaturePublicKey) && hasHolderEvidence(parsed, signaturePublicKey, denySet, deps.trustedGrantLifetime?.()) ? withoutIssuer(denySet, parsed.controller.capability) : denySet;
220
- await verifyPinnedCapability({
221
- capability: parsed.controller.capability,
222
- prefix: parsed.controller.prefix,
223
- controllerID: parsed.controller.id,
248
+ const roots = memberRootsOf(binding, parsed.id);
249
+ const primary = roots[0];
250
+ const checkEpochCap = ()=>{
251
+ if (judging.mode !== 'admit' || primary?.root.kind !== 'member' || registry == null) return;
252
+ const log = recordedLogOf(registry, binding.id);
253
+ if (log != null && epochEventCount(log) > MAX_EPOCH_EVENTS_FOR_LEAVES) throw new LeafBindingError('epoch-cap');
254
+ };
255
+ if (!structural && registry == null && roots.some(({ root })=>root.kind === 'member')) throw new LeafBindingError('controller-mismatch');
256
+ const frozen = createRegistryControllerResolver({
257
+ controllerID: binding.id,
258
+ prefix: binding.prefix,
259
+ registry: structural ? undefined : registry
260
+ }).frozen();
261
+ if (binding.member != null) {
262
+ if (!binding.id.startsWith('did:kokuin:') || !foldChain(binding.id, binding.prefix).ok) throw new LeafBindingError('controller-mismatch');
263
+ if (structural) return;
264
+ if (registry == null) throw new LeafBindingError('controller-mismatch');
265
+ const root = primary?.root;
266
+ if (root == null) throw new LeafBindingError('member-unavailable');
267
+ const status = memberRootStatus(registry, binding.id, root);
268
+ if (status.status === 'removed') {
269
+ if (judging.mode === 'admit') throw new LeafBindingError('member-removed');
270
+ const authority = effectiveAuthorityOf({
271
+ did: parsed.id,
272
+ binding,
273
+ leafKey: signaturePublicKey
274
+ }, registry, binding.id);
275
+ if (!('root' in authority)) throw new LeafBindingError('member-removed');
276
+ const substitute = authority.slot === 'holder' ? binding.holderGrant : registry.controllers.get(normalizeDID(binding.id))?.survivorGrants.get(normalizeDID(parsed.id));
277
+ if (substitute == null) throw new LeafBindingError('member-removed');
278
+ await verifyPinnedCapability({
279
+ capability: substitute,
280
+ resolver: frozen,
281
+ prefix: binding.prefix,
282
+ controllerID: binding.id,
283
+ audience: parsed.id,
284
+ permission: {
285
+ act: MLS_LEAF_ACT,
286
+ res: MLS_LEAF_RES
287
+ },
288
+ leafKey: signaturePublicKey,
289
+ denySet,
290
+ directOnly: true,
291
+ trustedGrant: true,
292
+ trustedGrantLifetime: deps.trustedGrantLifetime?.()
293
+ });
294
+ return;
295
+ }
296
+ const unavailable = ()=>{
297
+ if (judging.mode !== 'retain') throw new LeafBindingError('member-unavailable');
298
+ };
299
+ const projection = registry.controllers.get(normalizeDID(binding.id));
300
+ if (status.status !== 'effective' || prefixRelation(projection?.recordedLog, binding.prefix) !== 'contained') {
301
+ unavailable();
302
+ return;
303
+ }
304
+ let member;
305
+ try {
306
+ member = await frozen.resolveMember?.(binding.id, {
307
+ did: parsed.id,
308
+ add: binding.member.add,
309
+ gen: binding.member.g
310
+ });
311
+ } catch {
312
+ unavailable();
313
+ return;
314
+ }
315
+ if (member == null) {
316
+ unavailable();
317
+ return;
318
+ }
319
+ if (!constantTimeEqual(member.key.publicKey, signaturePublicKey)) throw new LeafBindingError('confirmation-invalid');
320
+ checkEpochCap();
321
+ return;
322
+ }
323
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
324
+ const common = {
325
+ prefix: binding.prefix,
326
+ controllerID: binding.id,
224
327
  audience: parsed.id,
225
328
  permission: {
226
329
  act: MLS_LEAF_ACT,
227
330
  res: MLS_LEAF_RES
228
331
  },
229
332
  leafKey: signaturePublicKey,
230
- denySet: leafDenySet,
333
+ resolver: frozen,
231
334
  leafLifetime: deps.leafLifetime?.(),
232
335
  trustedGrantLifetime: deps.trustedGrantLifetime?.()
233
- });
234
- const holderGrant = checkHolderEvidence(parsed, signaturePublicKey, deps.trustedGrantLifetime?.());
235
- if (holderGrant != null) {
336
+ };
337
+ const verifyHolder = async (capability, stage)=>{
236
338
  try {
237
339
  await verifyPinnedCapability({
238
- capability: holderGrant,
239
- prefix: parsed.controller.prefix,
240
- controllerID: parsed.controller.id,
241
- audience: parsed.id,
242
- permission: {
243
- act: MLS_LEAF_ACT,
244
- res: MLS_LEAF_RES
245
- },
246
- leafKey: signaturePublicKey,
340
+ ...common,
341
+ capability,
342
+ stage,
247
343
  denySet,
248
- trustedGrantLifetime: deps.trustedGrantLifetime?.(),
249
344
  directOnly: true,
250
345
  trustedGrant: true
251
346
  });
252
347
  } catch (cause) {
348
+ if (cause instanceof LeafBindingError && cause.reason === 'lifetime-cap') throw cause;
253
349
  const error = new LeafBindingError('holder-evidence-mismatch');
254
350
  error.cause = cause;
255
351
  throw error;
256
352
  }
353
+ };
354
+ // Authenticate every carried signature before consulting current authority or substitutes.
355
+ await verifyPinnedCapability({
356
+ ...common,
357
+ capability: binding.capability,
358
+ stage: 'structural'
359
+ });
360
+ const holderGrant = checkHolderEvidence(parsed, signaturePublicKey, common.trustedGrantLifetime);
361
+ if (holderGrant != null) await verifyHolder(holderGrant, 'structural');
362
+ if (structural) return;
363
+ checkEpochCap();
364
+ if (primary?.root.kind === 'member') {
365
+ const status = registry == null ? {
366
+ status: 'unavailable'
367
+ } : memberRootStatus(registry, binding.id, primary.root);
368
+ if (judging.mode === 'admit') {
369
+ if (status.status === 'removed') throw new LeafBindingError('member-removed');
370
+ if (status.status === 'unavailable') throw new LeafBindingError('member-unavailable');
371
+ }
372
+ const projection = registry?.controllers.get(normalizeDID(binding.id));
373
+ const unavailable = status.status === 'unavailable' || status.status !== 'removed' && prefixRelation(projection?.recordedLog, binding.prefix) !== 'contained';
374
+ if (unavailable) {
375
+ if (judging.mode === 'retain') return;
376
+ throw new LeafBindingError('member-unavailable');
377
+ }
378
+ if (registry == null) throw new LeafBindingError('member-unavailable');
379
+ const authority = effectiveAuthorityOf({
380
+ did: parsed.id,
381
+ binding,
382
+ leafKey: signaturePublicKey
383
+ }, registry, binding.id);
384
+ if ('status' in authority) {
385
+ if (authority.status === 'unavailable' && judging.mode === 'retain') return;
386
+ throw new LeafBindingError(authority.status === 'removed' ? 'member-removed' : 'member-unavailable');
387
+ }
388
+ if (authority.slot === 'holder' || authority.slot === 'survivor') {
389
+ const substitute = authority.slot === 'holder' ? holderGrant : projection?.survivorGrants.get(normalizeDID(parsed.id));
390
+ if (substitute == null) throw new LeafBindingError('member-removed');
391
+ await verifyHolder(substitute, 'full');
392
+ return;
393
+ }
394
+ }
395
+ // The holder grant does not inherit the leaf capability's issuer exception.
396
+ const leafDenySet = deps.mayKeepDeniedIssuer?.(credential, signaturePublicKey) && hasHolderEvidence(parsed, signaturePublicKey, denySet, common.trustedGrantLifetime) ? withoutIssuer(denySet, binding.capability) : denySet;
397
+ await verifyPinnedCapability({
398
+ ...common,
399
+ capability: binding.capability,
400
+ denySet: leafDenySet
401
+ });
402
+ if (holderGrant != null) {
403
+ const holder = roots.find(({ slot })=>slot === 'holder');
404
+ if (holder?.root.kind === 'member' && registry != null) {
405
+ const status = memberRootStatus(registry, binding.id, holder.root);
406
+ if (status.status === 'unavailable' || status.status !== 'removed' && prefixRelation(registry.controllers.get(normalizeDID(binding.id))?.recordedLog, binding.prefix) !== 'contained') {
407
+ if (judging.mode === 'retain') return;
408
+ throw new LeafBindingError('member-unavailable');
409
+ }
410
+ }
411
+ await verifyHolder(holderGrant, 'full');
257
412
  }
258
413
  } catch (error) {
259
414
  if (error instanceof LeafBindingError) throw error;
@@ -265,6 +420,7 @@ function withoutIssuer(denied, capability) {
265
420
  /** Management grants are direct controller grants, verified at their issuance time. */ export async function verifyManagementCapability(params) {
266
421
  if (params.capability == null) return false;
267
422
  try {
423
+ if (readCapability(params.capability).payload.mbr != null) return false;
268
424
  await verifyPinnedCapability({
269
425
  ...params,
270
426
  capability: params.capability,
@@ -30,6 +30,10 @@ export type MintLeafCapabilityParams = {
30
30
  leafKey: Uint8Array;
31
31
  exp: number;
32
32
  parent?: string;
33
+ member?: {
34
+ add: string;
35
+ g: number;
36
+ };
33
37
  };
34
38
  export type MintTrustedGrantParams = Omit<MintLeafCapabilityParams, 'parent'>;
35
39
  export declare function mintLeafCapability(params: MintLeafCapabilityParams): Promise<string>;
package/lib/capability.js CHANGED
@@ -53,7 +53,9 @@ export function capabilityKey(payload) {
53
53
  return key;
54
54
  }
55
55
  export function assertControllerGrant(payload, controllerID) {
56
- if (normalizeDID(payload.iss) !== normalizeDID(controllerID)) {
56
+ const member = payload.mbr;
57
+ if (member !== undefined && (member == null || typeof member !== 'object' || Array.isArray(member) || Object.keys(member).length !== 2 || typeof member.add !== 'string' || member.add.length === 0 || !Number.isSafeInteger(member.g) || member.g < 0)) throw new LeafBindingError('issuer-mismatch');
58
+ if (member === undefined && normalizeDID(payload.iss) !== normalizeDID(controllerID)) {
57
59
  throw new LeafBindingError('issuer-mismatch');
58
60
  }
59
61
  if (normalizeDID(payload.sub) !== normalizeDID(controllerID)) {
@@ -88,7 +90,10 @@ function issuingPayload(params, maximum) {
88
90
  res: MLS_LEAF_RES,
89
91
  cnf,
90
92
  iat,
91
- exp: params.exp
93
+ exp: params.exp,
94
+ ...params.member == null ? {} : {
95
+ mbr: params.member
96
+ }
92
97
  };
93
98
  }
94
99
  export async function mintLeafCapability(params) {
@@ -97,10 +102,12 @@ export async function mintLeafCapability(params) {
97
102
  throw new LeafBindingError('self-issued');
98
103
  }
99
104
  if (params.parent == null) {
100
- assertControllerGrant({
101
- ...payload,
102
- iss: params.signer.id
103
- }, params.controllerID);
105
+ if (params.member == null) {
106
+ assertControllerGrant({
107
+ ...payload,
108
+ iss: params.signer.id
109
+ }, params.controllerID);
110
+ }
104
111
  } else {
105
112
  // Issuing has no controller prefix; receivers authenticate the embedded parent.
106
113
  const parent = readCapability(params.parent);
@@ -133,9 +140,14 @@ export async function mintLeafCapability(params) {
133
140
  }
134
141
  export async function mintTrustedGrant(params) {
135
142
  const payload = issuingPayload(params, MAX_TRUSTED_GRANT_LIFETIME);
136
- assertControllerGrant({
137
- ...payload,
138
- iss: params.signer.id
139
- }, params.controllerID);
143
+ if (normalizeDID(params.audience) === normalizeDID(params.signer.id)) {
144
+ throw new LeafBindingError('self-issued');
145
+ }
146
+ if (params.member == null) {
147
+ assertControllerGrant({
148
+ ...payload,
149
+ iss: params.signer.id
150
+ }, params.controllerID);
151
+ }
140
152
  return stringifyToken(await params.signer.signToken(payload));
141
153
  }
@@ -0,0 +1,19 @@
1
+ import { type ControllerLog, type FoldResult, type KeyState } from '@kokuin/controller';
2
+ import type { ControllerProjection } from './registry.js';
3
+ export type FoldOk = Extract<FoldResult, {
4
+ ok: true;
5
+ }>;
6
+ export declare function ingestControllerLog(controller: string, recorded: ControllerLog | undefined, proof: ControllerLog, previous?: ControllerProjection): {
7
+ log: ControllerLog;
8
+ before?: FoldOk;
9
+ after: FoldOk;
10
+ introduced: Array<string>;
11
+ };
12
+ export declare function effectDelta(before: KeyState | undefined, after: KeyState): {
13
+ denied: Array<string>;
14
+ removed: Array<{
15
+ did: string;
16
+ add: string;
17
+ }>;
18
+ generation: boolean;
19
+ };
@@ -0,0 +1,117 @@
1
+ import { authoritativeLog, digestOf, isControllerLog, isEpochEventShape, LOG_FORKED, LOG_NOT_AUTHORITATIVE, mergeLogs } from '@kokuin/controller';
2
+ import { normalizeDID } from '@kokuin/token';
3
+ import { foldControllerLog, isDetachedFoldReason } from './controller-log.js';
4
+ import { RevokeProofError } from './errors.js';
5
+ const authenticatedFolds = new WeakMap();
6
+ export function ingestControllerLog(controller, recorded, proof, previous) {
7
+ const did = normalizeDID(controller);
8
+ let before;
9
+ if (recorded != null) {
10
+ const cached = authenticatedFolds.get(recorded);
11
+ const folded = cached?.controller === did && cached.digest === digestOf(recorded) ? structuredClone(cached.folded) : foldControllerLog(did, recorded);
12
+ if (!folded.ok) throw new RevokeProofError('not-authority-signed');
13
+ before = folded;
14
+ }
15
+ if (!isControllerLog(proof)) throw new RevokeProofError('not-authority-signed');
16
+ const first = proof.chain[0]?.event;
17
+ let chain = proof.chain;
18
+ if (first == null) {
19
+ if (recorded == null) throw new RevokeProofError('detached');
20
+ chain = recorded.chain;
21
+ } else if (first.t !== 'icp') {
22
+ if (recorded == null || first.p !== before?.states.at(-1)?.digest) throw new RevokeProofError('detached');
23
+ if (proof.chain.some(({ event })=>event.g > (before?.head.gen ?? 0))) throw new RevokeProofError('needs-reset');
24
+ chain = [
25
+ ...recorded.chain,
26
+ ...proof.chain
27
+ ];
28
+ }
29
+ for (const { event } of chain){
30
+ if (event.t !== 'icp' && event.t !== 'rot' || 'cap' in event && event.cap != null) throw new RevokeProofError('not-authority-signed');
31
+ }
32
+ const joined = {
33
+ chain,
34
+ events: proof.events
35
+ };
36
+ const folded = foldControllerLog(did, {
37
+ chain,
38
+ events: []
39
+ });
40
+ if (!folded.ok) {
41
+ throw new RevokeProofError(isDetachedFoldReason(folded.reason) ? 'detached' : 'not-authority-signed');
42
+ }
43
+ for(let index = 1; index < folded.states.length; index++){
44
+ if (folded.states[index]?.digest === folded.states[index - 1]?.digest) throw new RevokeProofError('not-authority-signed');
45
+ }
46
+ if (first?.t === 'icp' && before != null && folded.head.gen <= before.head.gen) throw new RevokeProofError('detached');
47
+ let authoritative;
48
+ try {
49
+ const loaded = recorded == null ? joined : mergeLogs(did, recorded, joined);
50
+ authoritative = authoritativeLog({
51
+ did,
52
+ loaded,
53
+ seen: recorded,
54
+ context: 'device registry'
55
+ });
56
+ } catch (cause) {
57
+ const message = cause instanceof Error ? cause.message : String(cause);
58
+ const detached = message.includes(LOG_FORKED) || message.includes(LOG_NOT_AUTHORITATIVE) || isDetachedFoldReason(message);
59
+ const error = new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
60
+ error.cause = cause;
61
+ throw error;
62
+ }
63
+ const { log, result: after } = authoritative;
64
+ const applied = new Set(before?.applied);
65
+ const introduced = after.applied.filter((digest)=>!applied.has(digest));
66
+ const newlyApplied = new Set(introduced);
67
+ // Saturation bounds stored copies, but every newly applied author still needs endorsement.
68
+ for (const signed of proof.events){
69
+ if (!isEpochEventShape(signed)) continue;
70
+ const { event } = signed;
71
+ if (!newlyApplied.has(digestOf(event)) || event.by == null) continue;
72
+ const author = before?.head.members.get(event.by);
73
+ const tombstone = previous?.removedMembers.get(event.by);
74
+ if (tombstone != null && (author == null || normalizeDID(tombstone.did) === normalizeDID(author.did)) || author != null && (author.removed || !author.effective)) throw new RevokeProofError('not-endorsed');
75
+ }
76
+ // Bind the authenticated prefix to its bytes, even if a caller mutates the returned log.
77
+ authenticatedFolds.set(log, {
78
+ controller: did,
79
+ digest: digestOf(log),
80
+ folded: structuredClone(after)
81
+ });
82
+ return {
83
+ log,
84
+ ...before == null ? {} : {
85
+ before
86
+ },
87
+ after,
88
+ introduced
89
+ };
90
+ }
91
+ export function effectDelta(before, after) {
92
+ const denials = (state)=>{
93
+ return new Set([
94
+ ...state?.deny ?? []
95
+ ].filter((target)=>target.startsWith('did:')).map(normalizeDID));
96
+ };
97
+ const prior = denials(before);
98
+ const denied = [
99
+ ...denials(after)
100
+ ].filter((did)=>!prior.has(did)).sort();
101
+ const removed = [];
102
+ for (const [add, member] of before?.members ?? []){
103
+ if (!member.effective) continue;
104
+ const held = after.members.get(add);
105
+ if (held?.effective && normalizeDID(held.did) === normalizeDID(member.did)) continue;
106
+ removed.push({
107
+ did: normalizeDID(member.did),
108
+ add
109
+ });
110
+ }
111
+ removed.sort((a, b)=>a.did.localeCompare(b.did) || a.add.localeCompare(b.add));
112
+ return {
113
+ denied,
114
+ removed,
115
+ generation: after.gen !== (before?.gen ?? 0)
116
+ };
117
+ }