@kumiai/mls 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +23 -0
  2. package/lib/anchor.d.ts +10 -4
  3. package/lib/anchor.js +26 -2
  4. package/lib/authentication.d.ts +11 -14
  5. package/lib/authentication.js +127 -86
  6. package/lib/capability.d.ts +37 -0
  7. package/lib/capability.js +141 -0
  8. package/lib/codec.js +2 -1
  9. package/lib/device-proof.d.ts +1 -0
  10. package/lib/device-proof.js +8 -12
  11. package/lib/envelope-fold.d.ts +16 -1
  12. package/lib/envelope-fold.js +49 -9
  13. package/lib/errors.d.ts +18 -0
  14. package/lib/errors.js +33 -0
  15. package/lib/group-commit.d.ts +22 -35
  16. package/lib/group-commit.js +122 -103
  17. package/lib/group-context.d.ts +6 -2
  18. package/lib/group-context.js +11 -4
  19. package/lib/group-create.js +56 -11
  20. package/lib/group-credential.d.ts +3 -1
  21. package/lib/group-credential.js +17 -3
  22. package/lib/group-device.js +34 -21
  23. package/lib/group-handle.d.ts +60 -24
  24. package/lib/group-handle.js +331 -77
  25. package/lib/group-info.d.ts +8 -0
  26. package/lib/group-info.js +29 -1
  27. package/lib/group-lifecycle.d.ts +32 -0
  28. package/lib/group-lifecycle.js +300 -0
  29. package/lib/group-membership.js +7 -3
  30. package/lib/group-welcome.d.ts +13 -4
  31. package/lib/group-welcome.js +113 -21
  32. package/lib/group.d.ts +3 -2
  33. package/lib/group.js +2 -1
  34. package/lib/history.d.ts +6 -0
  35. package/lib/history.js +26 -0
  36. package/lib/index.d.ts +10 -4
  37. package/lib/index.js +9 -3
  38. package/lib/lifecycle-proof.d.ts +24 -0
  39. package/lib/lifecycle-proof.js +193 -0
  40. package/lib/lifecycle.d.ts +44 -0
  41. package/lib/lifecycle.js +385 -0
  42. package/lib/policy.d.ts +20 -0
  43. package/lib/policy.js +8 -4
  44. package/lib/recovery-verdict.d.ts +43 -0
  45. package/lib/recovery-verdict.js +135 -0
  46. package/lib/recovery.d.ts +70 -0
  47. package/lib/recovery.js +110 -36
  48. package/lib/registry.d.ts +34 -7
  49. package/lib/registry.js +113 -15
  50. package/lib/roster.d.ts +1 -1
  51. package/lib/roster.js +2 -2
  52. package/lib/types.d.ts +13 -8
  53. package/lib/welcome-refs.d.ts +2 -1
  54. package/package.json +6 -6
package/README.md CHANGED
@@ -10,10 +10,33 @@ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](htt
10
10
  - `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
11
11
  - `removeMember` — an admin evicts a leaf and rotates keys
12
12
  - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState` and the stored ledger tokens
13
+ - `GroupHandle.processMessage(message, { persist? })` and `bootstrapLedger(tokens, { persist? })` — persist accepted commits, proposals, or a ledger bootstrap before notifications; a rejected persist restores the prior in-memory state. Application-message receive ratchets are not persisted by this option. Persist runs under the handle mutex, so it must not call back into that handle. Writes must be atomic: rejection must leave storage unchanged.
13
14
  - `encodeKeyPackage` + `decodeKeyPackage` — convert a key package to and from the opaque string a hub stores; decode is strict and returns `null` rather than throwing
14
15
  - `encodePrivateKeyPackage` + `decodePrivateKeyPackage` — the canonical string form of a key package's **private** half, for a host that must persist it across restarts (a reusable last-resort package outlives the process that made it). Secret material: never publish or log it.
15
16
  - `keyPackageRef` — the base64 KeyPackageRef a Welcome names, stable across a codec round trip. Use it as the identity of a stored package.
16
17
  - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
18
+ - `GroupHandle.decryptStaged` — open an app frame while withholding its consumed-key state until
19
+ a host has atomically saved that state and its pending delivery record
20
+ - `readMessageAAD(bytes)` — read a PrivateMessage's cleartext authenticated data without a key;
21
+ returns `null` for unreadable bytes and never throws
22
+
23
+ ## Persisting a staged app open
24
+
25
+ `await group.decryptStaged(message, { expectedAAD }, async (stagedState, opened) => { ... })`
26
+ computes the post-open state under the handle mutex but does not adopt it until the callback
27
+ resolves. `stagedState` is encoded `ClientState`, in the same format the host already stores for
28
+ `restoreGroup`; save these bytes as the group's handle state, together with the pending record,
29
+ in one atomic transaction. `opened` contains `payload`, authenticated `senderDID`, and `aad`.
30
+ An unnamed sender is rejected before the callback. If opening or persistence fails, the live
31
+ state and its message key remain available for retry. After persistence succeeds, the handle
32
+ adopts the staged state and the same frame cannot open again.
33
+
34
+ The callback runs while the handle mutex is held. It must not call this handle or its peer.
35
+ The host must order earlier handle saves before the staged write and reject older writes at the
36
+ same epoch using a monotonic state version; otherwise an earlier delayed save can overwrite the
37
+ consumed-key state while leaving the pending record. No database transaction or single connection
38
+ may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc` port's optional
39
+ `pending` adapter calls `decryptStaged` for durable logged events.
17
40
 
18
41
  ## Authority model
19
42
 
package/lib/anchor.d.ts CHANGED
@@ -20,12 +20,18 @@ export declare const LEDGER_HEAD_EXTENSION_TYPE = 61697;
20
20
  */
21
21
  export declare const RESERVED_EXTENSION_TYPE = 61698;
22
22
  /**
23
- * Genesis anchor baked into the MLS GroupContext at creation: the creator DID is the epoch-0
24
- * admin. Survives every epoch, authenticated by the GroupInfo signature, treated as immutable.
23
+ * Genesis anchor baked into the MLS GroupContext at creation: the controller or creator DID is
24
+ * the epoch-0 admin. Survives every epoch, authenticated by the GroupInfo signature, treated as immutable.
25
25
  */
26
26
  export type GroupAnchor = {
27
27
  creatorDID: string;
28
28
  version: number;
29
+ /** Immutable lifecycle controller. All peers must understand the same release's lifecycle rules. */
30
+ controller?: string;
31
+ /** Seconds, default 86,400, maximum 604,800. */
32
+ leafLifetime?: number;
33
+ /** Seconds, default 2,592,000, maximum 31,536,000. */
34
+ trustedGrantLifetime?: number;
29
35
  /**
30
36
  * Opaque consumer payload written once at creation; `@kumiai/mls` never reads or interprets
31
37
  * it. A consumer holding raw bytes must JSON-safe-encode them (e.g. base64) itself. Kubun
@@ -44,8 +50,8 @@ export declare function encodeGroupAnchor(anchor: GroupAnchor): Uint8Array;
44
50
  * this build has never seen, and a v1 consumer reading it as v1 (kubun keeps its recovery seed in
45
51
  * `app`) cannot tell. `version` is preserved so a consumer distinguishes "future version, app
46
52
  * withheld" from "genuinely no app". Contract this rests on: a `version` bump means `app` semantics
47
- * changed and nothing else; any future control-relevant field must go in a new extension type, never
48
- * inside the anchor where a version-tolerant older peer would silently ignore it.
53
+ * changed and nothing else. Lifecycle fields are validated regardless of version, and lifecycle
54
+ * peers must run a release that understands them.
49
55
  */
50
56
  export declare function decodeGroupAnchor(bytes: Uint8Array): GroupAnchor | null;
51
57
  export declare function buildGroupAnchorExtension(anchor: GroupAnchor): GroupContextExtension;
package/lib/anchor.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { defaultCapabilities, makeCustomExtension } from 'ts-mls';
2
+ import { MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME } from './capability.js';
2
3
  /**
3
4
  * MLS GroupContext extension type for the genesis anchor. A uint16 outside the MLS default
4
5
  * range (1–5) and clear of GREASE values, so it never collides with a built-in or a probe.
@@ -31,8 +32,8 @@ export function encodeGroupAnchor(anchor) {
31
32
  * this build has never seen, and a v1 consumer reading it as v1 (kubun keeps its recovery seed in
32
33
  * `app`) cannot tell. `version` is preserved so a consumer distinguishes "future version, app
33
34
  * withheld" from "genuinely no app". Contract this rests on: a `version` bump means `app` semantics
34
- * changed and nothing else; any future control-relevant field must go in a new extension type, never
35
- * inside the anchor where a version-tolerant older peer would silently ignore it.
35
+ * changed and nothing else. Lifecycle fields are validated regardless of version, and lifecycle
36
+ * peers must run a release that understands them.
36
37
  */ export function decodeGroupAnchor(bytes) {
37
38
  let parsed;
38
39
  try {
@@ -47,10 +48,33 @@ export function encodeGroupAnchor(anchor) {
47
48
  if (typeof record.creatorDID !== 'string' || typeof record.version !== 'number') {
48
49
  return null;
49
50
  }
51
+ if ('controller' in record && (typeof record.controller !== 'string' || !record.controller.startsWith('did:kokuin:'))) {
52
+ return null;
53
+ }
54
+ for (const [field, maximum] of [
55
+ [
56
+ 'leafLifetime',
57
+ MAX_LEAF_LIFETIME
58
+ ],
59
+ [
60
+ 'trustedGrantLifetime',
61
+ MAX_TRUSTED_GRANT_LIFETIME
62
+ ]
63
+ ]){
64
+ if (field in record) {
65
+ const value = record[field];
66
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > maximum) {
67
+ return null;
68
+ }
69
+ }
70
+ }
50
71
  const anchor = {
51
72
  creatorDID: record.creatorDID,
52
73
  version: record.version
53
74
  };
75
+ if (typeof record.controller === 'string') anchor.controller = record.controller;
76
+ if (typeof record.leafLifetime === 'number') anchor.leafLifetime = record.leafLifetime;
77
+ if (typeof record.trustedGrantLifetime === 'number') anchor.trustedGrantLifetime = record.trustedGrantLifetime;
54
78
  // Withhold the app payload from a future build's anchor: a version this build
55
79
  // has never seen may carry a payload with v2 semantics, and handing it to a
56
80
  // consumer under v1 expectations is exactly the silent misread this guards.
@@ -1,19 +1,18 @@
1
1
  import { type SignedEvent } from '@kokuin/controller';
2
- import type { AuthenticationService } from 'ts-mls';
3
- /** The action a device capability must grant for a leaf to authenticate as a kumiai MLS leaf. */
4
- export declare const MLS_LEAF_ACT = "authenticate";
5
- /** The resource half of that grant — kumiai-namespaced, group-independent. */
6
- export declare const MLS_LEAF_RES = "kumiai/mls-leaf";
2
+ import type { AuthenticationService, Credential } from 'ts-mls';
3
+ export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
7
4
  /** The action a management capability must grant to mutate a profile's device registry. */
8
5
  export declare const MLS_DEVICES_ACT = "manage";
9
6
  /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */
10
7
  export declare const MLS_DEVICES_RES = "kumiai/devices";
11
- /**
12
- * Verify a management capability presented by a manage-op's issuer device: the authorized profile
13
- * (`controllerID`) issued a `kumiai/devices` grant to that device (`audience`), `cnf`-pinned to the
14
- * device's leaf key and `exp`-bounded. Verified against the profile's log prefix (embedded in the
15
- * issuer's own bound leaf), never fetched. Returns false on any failure.
16
- */
8
+ export type DIDAuthenticationDependencies = {
9
+ deviceDenySet?: () => ReadonlySet<string>;
10
+ leafLifetime?: () => number | undefined;
11
+ trustedGrantLifetime?: () => number | undefined;
12
+ };
13
+ /** Internal throwing boundary for entry gates; ts-mls consumes the boolean adapter below. */
14
+ export declare function verifyLeafCredential(credential: Credential, signaturePublicKey: Uint8Array, deps?: DIDAuthenticationDependencies): Promise<void>;
15
+ /** Management grants are direct controller grants, verified at their issuance time. */
17
16
  export declare function verifyManagementCapability(params: {
18
17
  capability?: string;
19
18
  prefix: Array<SignedEvent>;
@@ -21,6 +20,4 @@ export declare function verifyManagementCapability(params: {
21
20
  audience: string;
22
21
  leafKey: Uint8Array;
23
22
  }): Promise<boolean>;
24
- export declare function createDIDAuthenticationService(deps?: {
25
- deviceDenySet?: () => ReadonlySet<string>;
26
- }): AuthenticationService;
23
+ export declare function createDIDAuthenticationService(deps?: DIDAuthenticationDependencies): AuthenticationService;
@@ -1,11 +1,13 @@
1
- import { assertCapabilityToken, assertDeviceCapabilityPolicy, assertValidIssuedAt, hasPermission } from '@kokuin/capability';
2
- import { tryDecodeKey } from '@kokuin/controller';
3
- import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, isPeer4, normalizeDID, verifyToken } from '@kokuin/token';
1
+ import { assertCapabilityToken, assertValidDelegation, checkCapability, hasPermission } from '@kokuin/capability';
2
+ import { foldLog } from '@kokuin/controller';
3
+ import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, getVerifier, isPeer4, normalizeDID, verifyToken } from '@kokuin/token';
4
+ import { fromB64U, fromUTF } from '@sozai/codec';
4
5
  import { defaultCredentialTypes } from 'ts-mls';
6
+ import { assertCapabilityLifetime, assertControllerGrant, capabilityKey, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, MLS_LEAF_ACT, MLS_LEAF_RES, readCapability } from './capability.js';
5
7
  import { parseMLSCredentialIdentity } from './credential.js';
6
8
  import { createEmbeddedControllerResolver } from './embedded-resolver.js';
7
- /** The action a device capability must grant for a leaf to authenticate as a kumiai MLS leaf. */ export const MLS_LEAF_ACT = 'authenticate';
8
- /** The resource half of that grant — kumiai-namespaced, group-independent. */ export const MLS_LEAF_RES = 'kumiai/mls-leaf';
9
+ import { LeafBindingError } from './errors.js';
10
+ export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
9
11
  /** The action a management capability must grant to mutate a profile's device registry. */ export const MLS_DEVICES_ACT = 'manage';
10
12
  /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */ export const MLS_DEVICES_RES = 'kumiai/devices';
11
13
  const EMPTY_DENY = new Set();
@@ -65,109 +67,148 @@ function constantTimeEqual(a, b) {
65
67
  return false;
66
68
  }
67
69
  }
68
- /**
69
- * The shared capability-verification core: verify a `cnf`-pinned, `exp`-bounded @kokuin/capability
70
- * grant against a controller's EMBEDDED log prefix (no external I/O), asserting it grants
71
- * `permission` to `audience` and pins `leafKey`. Returns false on any failure. Optionally pins the
72
- * issuer (`requireIssuer`) — the embedded resolver already answers only for `controllerID`, so the
73
- * issuer is pinned there too; the explicit check is belt-and-braces for the manage path.
74
- */ async function verifyPinnedCapability(params) {
70
+ function isDenied(denied, did) {
71
+ return denied.has(did) || denied.has(normalizeDID(did));
72
+ }
73
+ /** Authenticate only embedded proof, using the token's issuance as its reference time. */ async function verifyPinnedCapability(params) {
74
+ if (!params.controllerID.startsWith('did:kokuin:') || !foldLog(params.controllerID, params.prefix).ok) {
75
+ throw new LeafBindingError('controller-mismatch');
76
+ }
77
+ const token = readCapability(params.capability);
78
+ const payload = token.payload;
79
+ const leafLifetime = Math.min(params.leafLifetime ?? MAX_LEAF_LIFETIME, MAX_LEAF_LIFETIME);
80
+ assertCapabilityLifetime(payload, leafLifetime);
81
+ if (normalizeDID(payload.sub) !== normalizeDID(params.controllerID)) {
82
+ throw new LeafBindingError('subject-mismatch');
83
+ }
84
+ if (normalizeDID(payload.aud) !== normalizeDID(params.audience)) {
85
+ throw new LeafBindingError('audience-mismatch');
86
+ }
87
+ if (!hasPermission(params.permission, payload)) throw new LeafBindingError('permission-denied');
88
+ const leafKey = capabilityKey(payload);
89
+ if (!constantTimeEqual(leafKey.publicKey, params.leafKey)) {
90
+ throw new LeafBindingError('confirmation-invalid');
91
+ }
92
+ const denySet = params.denySet ?? EMPTY_DENY;
75
93
  const resolver = createEmbeddedControllerResolver({
76
94
  controllerID: params.controllerID,
77
- prefix: params.prefix
95
+ prefix: params.prefix,
96
+ denySet
78
97
  });
79
- let verified;
80
- try {
81
- verified = await verifyToken(params.capability, {
98
+ if (payload.cap === undefined) {
99
+ assertControllerGrant(payload, params.controllerID);
100
+ const verified = await verifyToken(params.capability, {
82
101
  methods: [
83
102
  resolver
84
103
  ],
85
104
  historic: true,
105
+ atTime: payload.iat,
86
106
  allowUnsigned: false
87
107
  });
88
- } catch {
89
- return false;
90
- }
91
- try {
92
108
  assertCapabilityToken(verified);
93
- if (params.requireIssuer != null && normalizeDID(verified.payload.iss) !== normalizeDID(params.requireIssuer)) return false;
94
- if (normalizeDID(verified.payload.aud) !== normalizeDID(params.audience)) return false;
95
- if (!hasPermission(params.permission, verified.payload)) return false;
96
- assertValidIssuedAt(verified.payload);
97
- assertDeviceCapabilityPolicy(verified.payload);
98
- } catch {
99
- return false;
109
+ return;
100
110
  }
101
- const kid = verified.payload.cnf?.kid;
102
- if (typeof kid !== 'string') return false;
103
- const pinned = tryDecodeKey(kid);
104
- return pinned != null && constantTimeEqual(pinned.publicKey, params.leafKey);
105
- }
106
- /**
107
- * Validate a bound leaf: the device authenticates against its own leaf key (floating check), and the
108
- * embedded controller proof shows the profile authorised THIS device with THIS key. All sync — the
109
- * prefix is folded through the embedded resolver, never fetched. Returns false on any failure.
110
- */ async function validateBoundLeaf(parsed, signaturePublicKey, deviceDenySet) {
111
- const controller = parsed.controller;
112
- if (controller == null) return false;
113
- if (!controller.id.startsWith('did:kokuin:')) return false;
114
- if (!matchesLeafKey(parsed, signaturePublicKey)) return false;
115
- // Deny governs the capability-mediated (bound) leaf; checked before the capability verify so a
116
- // revoked device is rejected regardless of an otherwise-valid grant.
117
- if (deviceDenySet().has(normalizeDID(parsed.id))) return false;
118
- return await verifyPinnedCapability({
119
- capability: controller.capability,
120
- prefix: controller.prefix,
121
- controllerID: controller.id,
122
- audience: parsed.id,
123
- permission: {
124
- act: MLS_LEAF_ACT,
125
- res: MLS_LEAF_RES
126
- },
127
- leafKey: signaturePublicKey
111
+ if (params.directOnly) throw new LeafBindingError('chain-depth');
112
+ const parents = Array.isArray(payload.cap) ? payload.cap : [
113
+ payload.cap
114
+ ];
115
+ const parentRaw = parents[0];
116
+ if (parents.length !== 1 || parentRaw == null) throw new LeafBindingError('chain-depth');
117
+ const parent = readCapability(parentRaw);
118
+ if (parent.payload.cap !== undefined) throw new LeafBindingError('chain-depth');
119
+ assertControllerGrant(parent.payload, params.controllerID);
120
+ assertCapabilityLifetime(parent.payload, Math.min(params.trustedGrantLifetime ?? MAX_TRUSTED_GRANT_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME));
121
+ if (normalizeDID(payload.iss) !== normalizeDID(parent.payload.aud)) {
122
+ throw new LeafBindingError('issuer-mismatch');
123
+ }
124
+ if (normalizeDID(payload.aud) === normalizeDID(payload.iss)) {
125
+ throw new LeafBindingError('self-issued');
126
+ }
127
+ if (payload.exp > parent.payload.exp) throw new LeafBindingError('child-outlives-parent');
128
+ if (isDenied(denySet, payload.iss)) throw new LeafBindingError('denied-issuer');
129
+ const issuerKey = capabilityKey(parent.payload);
130
+ if (token.header.alg !== issuerKey.alg) throw new LeafBindingError('signature-invalid');
131
+ if (!await getVerifier(token.header.alg)(fromB64U(token.signature), fromUTF(token.data), issuerKey.publicKey)) {
132
+ throw new LeafBindingError('signature-invalid');
133
+ }
134
+ // checkCapability treats iss === sub as a root grant, so it does not walk that parent.
135
+ if (normalizeDID(payload.iss) === normalizeDID(payload.sub)) {
136
+ const verifiedParent = await verifyToken(parentRaw, {
137
+ atTime: payload.iat,
138
+ methods: [
139
+ resolver
140
+ ],
141
+ historic: true,
142
+ allowUnsigned: false
143
+ });
144
+ assertCapabilityToken(verifiedParent);
145
+ assertValidDelegation(verifiedParent.payload, payload, payload.iat);
146
+ }
147
+ await checkCapability(params.permission, payload, {
148
+ atTime: payload.iat,
149
+ methods: [
150
+ resolver
151
+ ],
152
+ maxDepth: 1
128
153
  });
129
154
  }
130
- /**
131
- * Verify a management capability presented by a manage-op's issuer device: the authorized profile
132
- * (`controllerID`) issued a `kumiai/devices` grant to that device (`audience`), `cnf`-pinned to the
133
- * device's leaf key and `exp`-bounded. Verified against the profile's log prefix (embedded in the
134
- * issuer's own bound leaf), never fetched. Returns false on any failure.
135
- */ export async function verifyManagementCapability(params) {
155
+ /** Internal throwing boundary for entry gates; ts-mls consumes the boolean adapter below. */ export async function verifyLeafCredential(credential, signaturePublicKey, deps = {}) {
156
+ if (credential.credentialType !== defaultCredentialTypes.basic) {
157
+ throw new Error('Unsupported MLS credential type');
158
+ }
159
+ const parsed = parseMLSCredentialIdentity(credential.identity);
160
+ if (!matchesLeafKey(parsed, signaturePublicKey)) throw new LeafBindingError('identity-change');
161
+ const denySet = deps.deviceDenySet?.() ?? EMPTY_DENY;
162
+ if (isDenied(denySet, parsed.id)) throw new LeafBindingError('denied-id');
163
+ if (parsed.controller == null) return;
164
+ try {
165
+ await verifyPinnedCapability({
166
+ capability: parsed.controller.capability,
167
+ prefix: parsed.controller.prefix,
168
+ controllerID: parsed.controller.id,
169
+ audience: parsed.id,
170
+ permission: {
171
+ act: MLS_LEAF_ACT,
172
+ res: MLS_LEAF_RES
173
+ },
174
+ leafKey: signaturePublicKey,
175
+ denySet,
176
+ leafLifetime: deps.leafLifetime?.(),
177
+ trustedGrantLifetime: deps.trustedGrantLifetime?.()
178
+ });
179
+ } catch (error) {
180
+ if (error instanceof LeafBindingError) throw error;
181
+ const rejection = new LeafBindingError('signature-invalid');
182
+ rejection.cause = error;
183
+ throw rejection;
184
+ }
185
+ }
186
+ /** Management grants are direct controller grants, verified at their issuance time. */ export async function verifyManagementCapability(params) {
136
187
  if (params.capability == null) return false;
137
- return await verifyPinnedCapability({
138
- capability: params.capability,
139
- prefix: params.prefix,
140
- controllerID: params.controllerID,
141
- audience: params.audience,
142
- permission: {
143
- act: MLS_DEVICES_ACT,
144
- res: MLS_DEVICES_RES
145
- },
146
- leafKey: params.leafKey,
147
- requireIssuer: params.controllerID
148
- });
188
+ try {
189
+ await verifyPinnedCapability({
190
+ ...params,
191
+ capability: params.capability,
192
+ permission: {
193
+ act: MLS_DEVICES_ACT,
194
+ res: MLS_DEVICES_RES
195
+ },
196
+ directOnly: true
197
+ });
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
149
202
  }
150
203
  export function createDIDAuthenticationService(deps = {}) {
151
- const deviceDenySet = deps.deviceDenySet ?? (()=>EMPTY_DENY);
152
204
  return {
153
205
  async validateCredential (credential, signaturePublicKey) {
154
- if (credential.credentialType !== defaultCredentialTypes.basic) {
155
- return false;
156
- }
157
- let parsed;
158
206
  try {
159
- parsed = parseMLSCredentialIdentity(credential.identity);
207
+ await verifyLeafCredential(credential, signaturePublicKey, deps);
208
+ return true;
160
209
  } catch {
161
210
  return false;
162
211
  }
163
- if (parsed.controller != null) {
164
- try {
165
- return await validateBoundLeaf(parsed, signaturePublicKey, deviceDenySet);
166
- } catch {
167
- return false;
168
- }
169
- }
170
- return matchesLeafKey(parsed, signaturePublicKey);
171
212
  }
172
213
  };
173
214
  }
@@ -0,0 +1,37 @@
1
+ import { type CapabilityPayload } from '@kokuin/capability';
2
+ import { type SignedToken, type SigningIdentity } from '@kokuin/token';
3
+ /** The action a device capability must grant for a leaf to authenticate as a kumiai MLS leaf. */
4
+ export declare const MLS_LEAF_ACT = "authenticate";
5
+ /** The resource half of that grant — kumiai-namespaced, group-independent. */
6
+ export declare const MLS_LEAF_RES = "kumiai/mls-leaf";
7
+ export declare const MAX_LEAF_LIFETIME = 604800;
8
+ export declare const MAX_TRUSTED_GRANT_LIFETIME = 31536000;
9
+ type LeafCapabilityPayload = CapabilityPayload & {
10
+ iat: number;
11
+ exp: number;
12
+ nbf?: number;
13
+ cap?: string | Array<string>;
14
+ };
15
+ /** Decode only; callers must authenticate the signed bytes before trusting these claims. */
16
+ export declare function readCapability(raw: string): SignedToken<LeafCapabilityPayload>;
17
+ /** Unvalidated time claims, as read from a decoded token. */
18
+ export type CapabilityTimeClaims = {
19
+ iat?: unknown;
20
+ exp?: unknown;
21
+ nbf?: unknown;
22
+ };
23
+ export declare function assertCapabilityLifetime(payload: CapabilityTimeClaims, maximum: number): void;
24
+ export declare function capabilityKey(payload: CapabilityPayload): import("@kokuin/controller").TaggedKey;
25
+ export declare function assertControllerGrant(payload: CapabilityPayload, controllerID: string): void;
26
+ export type MintLeafCapabilityParams = {
27
+ signer: SigningIdentity;
28
+ controllerID: string;
29
+ audience: string;
30
+ leafKey: Uint8Array;
31
+ exp: number;
32
+ parent?: string;
33
+ };
34
+ export type MintTrustedGrantParams = Omit<MintLeafCapabilityParams, 'parent'>;
35
+ export declare function mintLeafCapability(params: MintLeafCapabilityParams): Promise<string>;
36
+ export declare function mintTrustedGrant(params: MintTrustedGrantParams): Promise<string>;
37
+ export {};
@@ -0,0 +1,141 @@
1
+ import { audienceConfirmation, hasPermission } from '@kokuin/capability';
2
+ import { tryDecodeKey } from '@kokuin/controller';
3
+ import { isSignedToken, normalizeDID, now, stringifyToken } from '@kokuin/token';
4
+ import { b64uToJSON } from '@sozai/codec';
5
+ import { LeafBindingError } from './errors.js';
6
+ /** The action a device capability must grant for a leaf to authenticate as a kumiai MLS leaf. */ export const MLS_LEAF_ACT = 'authenticate';
7
+ /** The resource half of that grant — kumiai-namespaced, group-independent. */ export const MLS_LEAF_RES = 'kumiai/mls-leaf';
8
+ export const MAX_LEAF_LIFETIME = 604800;
9
+ export const MAX_TRUSTED_GRANT_LIFETIME = 31536000;
10
+ /** Decode only; callers must authenticate the signed bytes before trusting these claims. */ export function readCapability(raw) {
11
+ const parts = raw.split('.');
12
+ const [header, payload, signature] = parts;
13
+ if (parts.length !== 3 || !header || !payload || !signature) {
14
+ throw new Error('Invalid capability encoding');
15
+ }
16
+ const token = {
17
+ header: b64uToJSON(header),
18
+ payload: b64uToJSON(payload),
19
+ signature,
20
+ data: `${header}.${payload}`
21
+ };
22
+ if (!isSignedToken(token)) throw new Error('Invalid signed capability');
23
+ const claims = token.payload;
24
+ if (typeof claims.sub !== 'string' || typeof claims.aud !== 'string') {
25
+ throw new Error('Invalid capability subject or audience');
26
+ }
27
+ for (const part of [
28
+ claims.act,
29
+ claims.res
30
+ ]){
31
+ if (typeof part !== 'string' && !(Array.isArray(part) && part.every((value)=>typeof value === 'string'))) {
32
+ throw new Error('Invalid capability permission');
33
+ }
34
+ }
35
+ return token;
36
+ }
37
+ export function assertCapabilityLifetime(payload, maximum) {
38
+ const { iat, exp, nbf } = payload;
39
+ if (typeof iat !== 'number' || !Number.isFinite(iat) || typeof exp !== 'number' || !Number.isFinite(exp) || exp <= iat || exp - iat > maximum || !Number.isFinite(maximum) || maximum <= 0) {
40
+ throw new LeafBindingError('lifetime-cap');
41
+ }
42
+ if (nbf !== undefined && (typeof nbf !== 'number' || !Number.isFinite(nbf))) {
43
+ throw new Error('Invalid capability not-before claim');
44
+ }
45
+ }
46
+ export function capabilityKey(payload) {
47
+ const cnf = payload.cnf;
48
+ if (cnf == null || typeof cnf !== 'object' || Object.keys(cnf).length !== 1 || typeof cnf.kid !== 'string') {
49
+ throw new LeafBindingError('confirmation-invalid');
50
+ }
51
+ const key = tryDecodeKey(cnf.kid);
52
+ if (key == null || key.alg !== 'EdDSA') throw new Error('Invalid capability confirmation key');
53
+ return key;
54
+ }
55
+ export function assertControllerGrant(payload, controllerID) {
56
+ if (normalizeDID(payload.iss) !== normalizeDID(controllerID)) {
57
+ throw new LeafBindingError('issuer-mismatch');
58
+ }
59
+ if (normalizeDID(payload.sub) !== normalizeDID(controllerID)) {
60
+ throw new LeafBindingError('subject-mismatch');
61
+ }
62
+ }
63
+ function issuingPayload(params, maximum) {
64
+ if (!params.controllerID.startsWith('did:kokuin:')) {
65
+ throw new LeafBindingError('controller-mismatch');
66
+ }
67
+ const iat = now();
68
+ assertCapabilityLifetime({
69
+ iat,
70
+ exp: params.exp
71
+ }, maximum);
72
+ const cnf = audienceConfirmation({
73
+ alg: 'EdDSA',
74
+ publicKey: params.leafKey
75
+ });
76
+ capabilityKey({
77
+ iss: params.signer.id,
78
+ sub: params.controllerID,
79
+ aud: params.audience,
80
+ act: MLS_LEAF_ACT,
81
+ res: MLS_LEAF_RES,
82
+ cnf
83
+ });
84
+ return {
85
+ sub: params.controllerID,
86
+ aud: params.audience,
87
+ act: MLS_LEAF_ACT,
88
+ res: MLS_LEAF_RES,
89
+ cnf,
90
+ iat,
91
+ exp: params.exp
92
+ };
93
+ }
94
+ export async function mintLeafCapability(params) {
95
+ const payload = issuingPayload(params, MAX_LEAF_LIFETIME);
96
+ if (normalizeDID(params.audience) === normalizeDID(params.signer.id)) {
97
+ throw new LeafBindingError('self-issued');
98
+ }
99
+ if (params.parent == null) {
100
+ assertControllerGrant({
101
+ ...payload,
102
+ iss: params.signer.id
103
+ }, params.controllerID);
104
+ } else {
105
+ // Issuing has no controller prefix; receivers authenticate the embedded parent.
106
+ const parent = readCapability(params.parent);
107
+ if (parent.payload.cap !== undefined) throw new LeafBindingError('chain-depth');
108
+ assertControllerGrant(parent.payload, params.controllerID);
109
+ if (!hasPermission({
110
+ act: MLS_LEAF_ACT,
111
+ res: MLS_LEAF_RES
112
+ }, parent.payload)) {
113
+ throw new Error('Parent does not grant leaf authentication');
114
+ }
115
+ assertCapabilityLifetime(parent.payload, MAX_TRUSTED_GRANT_LIFETIME);
116
+ if (normalizeDID(parent.payload.aud) !== normalizeDID(params.signer.id)) {
117
+ throw new LeafBindingError('issuer-mismatch');
118
+ }
119
+ const key = capabilityKey(parent.payload);
120
+ if (!key.publicKey.every((byte, index)=>byte === params.signer.publicKey[index]) || key.publicKey.length !== params.signer.publicKey.length) {
121
+ throw new LeafBindingError('issuer-mismatch');
122
+ }
123
+ if (payload.exp > parent.payload.exp) throw new LeafBindingError('child-outlives-parent');
124
+ if (parent.payload.iat > payload.iat || parent.payload.exp < payload.iat || parent.payload.nbf != null && parent.payload.nbf > payload.iat) {
125
+ throw new Error('Parent capability is not valid at issuance');
126
+ }
127
+ return stringifyToken(await params.signer.signToken({
128
+ ...payload,
129
+ cap: params.parent
130
+ }));
131
+ }
132
+ return stringifyToken(await params.signer.signToken(payload));
133
+ }
134
+ export async function mintTrustedGrant(params) {
135
+ const payload = issuingPayload(params, MAX_TRUSTED_GRANT_LIFETIME);
136
+ assertControllerGrant({
137
+ ...payload,
138
+ iss: params.signer.id
139
+ }, params.controllerID);
140
+ return stringifyToken(await params.signer.signToken(payload));
141
+ }
package/lib/codec.js CHANGED
@@ -29,7 +29,8 @@ export function decodeClientState(encoded) {
29
29
  if (encoded[0] !== CLIENT_STATE_VERSION) {
30
30
  throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
31
31
  }
32
- return decode(clientStateDecoder, encoded.subarray(1));
32
+ // A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
33
+ return decode(clientStateDecoder, encoded.slice(1));
33
34
  }
34
35
  export function encodeClientState(state) {
35
36
  const body = encode(clientStateEncoder, state);
@@ -7,6 +7,7 @@ export type LeafBinding = {
7
7
  controller?: string;
8
8
  /** The embedded controller log prefix (present iff bound), for resolving a capability signature. */
9
9
  prefix?: Array<SignedEvent>;
10
+ capability?: string;
10
11
  /** The leaf's MLS signature public key. */
11
12
  leafKey: Uint8Array;
12
13
  };
@@ -26,23 +26,19 @@ import { verifyManagementCapability } from './authentication.js';
26
26
  if (binding?.controller == null) return false;
27
27
  return normalizeDID(binding.controller) === subject;
28
28
  }
29
+ if (value.op === 'reset' || value.op === 'clock' || value.proof !== undefined) return false;
30
+ const recordedController = ctx.controllerOf(subject);
31
+ const subjectBinding = ctx.bindingOfDID(subject);
32
+ const subjectController = value.op === 'register' || value.op === 'add' ? value.controller : recordedController;
33
+ if (subjectController == null) return false;
34
+ if (recordedController != null && normalizeDID(recordedController) !== normalizeDID(subjectController)) return false;
35
+ if (subjectBinding != null && (subjectBinding.controller == null || normalizeDID(subjectBinding.controller) !== normalizeDID(subjectController))) return false;
29
36
  if (value.op === 'register' && subject === issuer) {
30
37
  const binding = ctx.bindingOfDID(issuer);
31
38
  if (binding?.controller == null || value.controller == null) return false;
32
39
  return normalizeDID(binding.controller) === normalizeDID(value.controller);
33
40
  }
34
- const authorizedProfile = value.op === 'register' || value.op === 'add' ? value.controller == null ? undefined : normalizeDID(value.controller) : ctx.controllerOf(subject) // revoke / label — the registry already binds the subject
35
- ;
36
- if (authorizedProfile == null) return false;
37
- // Cross-profile rebind guard: a register/add must never overwrite a subject already bound to a
38
- // DIFFERENT controller. Without this, a manager of profile P could re-bind another profile Q's
39
- // active device to P (flipping its authority), then revoke it — evicting Q's device in two
40
- // commits. Self-register (subject === issuer) returned earlier; a brand-new subject
41
- // (controllerOf undefined) and a same-controller re-register both stay allowed.
42
- if (value.op === 'register' || value.op === 'add') {
43
- const existingController = ctx.controllerOf(subject);
44
- if (existingController != null && existingController !== authorizedProfile) return false;
45
- }
41
+ const authorizedProfile = normalizeDID(subjectController);
46
42
  const binding = ctx.bindingOfDID(issuer);
47
43
  if (binding?.controller == null || binding.prefix == null) return false;
48
44
  if (normalizeDID(binding.controller) !== authorizedProfile) return false;