@kumiai/mls 0.5.0 → 0.7.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.
@@ -1,2 +1,26 @@
1
+ import { type SignedEvent } from '@kokuin/controller';
1
2
  import type { AuthenticationService } from 'ts-mls';
2
- export declare function createDIDAuthenticationService(): AuthenticationService;
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
+ /** The action a management capability must grant to mutate a profile's device registry. */
8
+ export declare const MLS_DEVICES_ACT = "manage";
9
+ /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */
10
+ 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
+ */
17
+ export declare function verifyManagementCapability(params: {
18
+ capability?: string;
19
+ prefix: Array<SignedEvent>;
20
+ controllerID: string;
21
+ audience: string;
22
+ leafKey: Uint8Array;
23
+ }): Promise<boolean>;
24
+ export declare function createDIDAuthenticationService(deps?: {
25
+ deviceDenySet?: () => ReadonlySet<string>;
26
+ }): AuthenticationService;
@@ -1,6 +1,14 @@
1
- import { decodeMultibase, decodePeer4, getAlgorithmAndPublicKey, getSignatureInfo, isPeer4 } from '@kokuin/token';
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';
2
4
  import { defaultCredentialTypes } from 'ts-mls';
3
5
  import { parseMLSCredentialIdentity } from './credential.js';
6
+ 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
+ /** The action a management capability must grant to mutate a profile's device registry. */ export const MLS_DEVICES_ACT = 'manage';
10
+ /** The resource half — kumiai-namespaced, group-independent, per the kokuin management tier. */ export const MLS_DEVICES_RES = 'kumiai/devices';
11
+ const EMPTY_DENY = new Set();
4
12
  function constantTimeEqual(a, b) {
5
13
  if (a.length !== b.length) return false;
6
14
  let diff = 0;
@@ -10,7 +18,137 @@ function constantTimeEqual(a, b) {
10
18
  }
11
19
  return diff === 0;
12
20
  }
13
- export function createDIDAuthenticationService() {
21
+ /**
22
+ * Whether `signaturePublicKey` is the key the parsed identity's DID authenticates with — the
23
+ * floating-leaf binding, shared by floating validation and the bound branch (a bound leaf is a
24
+ * floating leaf plus a controller attribution). `did:peer:4` binds through the long-form
25
+ * authentication verification methods; every other form is a `did:key` whose key IS its identifier.
26
+ */ function matchesLeafKey(parsed, signaturePublicKey) {
27
+ if (isPeer4(parsed.id)) {
28
+ if (parsed.longForm == null) return false;
29
+ let decoded;
30
+ try {
31
+ decoded = decodePeer4(parsed.longForm);
32
+ } catch {
33
+ return false;
34
+ }
35
+ if (decoded.shortForm !== parsed.id) return false;
36
+ // Only verification methods referenced by `authentication` are
37
+ // permitted to sign for authentication — per DID Core. Reject MLS
38
+ // leaves bound to keys outside that set (KEM keys, assertion-only
39
+ // keys, etc.) even if the byte comparison would otherwise match.
40
+ const authIDs = new Set(decoded.doc.authentication ?? []);
41
+ if (authIDs.size === 0) return false;
42
+ for (const vm of decoded.doc.verificationMethod ?? []){
43
+ if (!authIDs.has(vm.id)) continue;
44
+ if (typeof vm.publicKeyMultibase !== 'string') continue;
45
+ let vmBytes;
46
+ try {
47
+ vmBytes = decodeMultibase(vm.publicKeyMultibase);
48
+ } catch {
49
+ continue;
50
+ }
51
+ // Validate multicodec prefix and strip it; rejects unknown codecs
52
+ // (e.g. X25519 KEM keys, future PQ codecs) instead of blindly
53
+ // comparing 2-byte-truncated bytes.
54
+ const stripped = getAlgorithmAndPublicKey(vmBytes);
55
+ if (stripped == null) continue;
56
+ const [, publicKeyBytes] = stripped;
57
+ if (constantTimeEqual(publicKeyBytes, signaturePublicKey)) return true;
58
+ }
59
+ return false;
60
+ }
61
+ try {
62
+ const [, publicKeyFromDID] = getSignatureInfo(parsed.id);
63
+ return constantTimeEqual(publicKeyFromDID, signaturePublicKey);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
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) {
75
+ const resolver = createEmbeddedControllerResolver({
76
+ controllerID: params.controllerID,
77
+ prefix: params.prefix
78
+ });
79
+ let verified;
80
+ try {
81
+ verified = await verifyToken(params.capability, {
82
+ methods: [
83
+ resolver
84
+ ],
85
+ historic: true,
86
+ allowUnsigned: false
87
+ });
88
+ } catch {
89
+ return false;
90
+ }
91
+ try {
92
+ 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;
100
+ }
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
128
+ });
129
+ }
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) {
136
+ 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
+ });
149
+ }
150
+ export function createDIDAuthenticationService(deps = {}) {
151
+ const deviceDenySet = deps.deviceDenySet ?? (()=>EMPTY_DENY);
14
152
  return {
15
153
  async validateCredential (credential, signaturePublicKey) {
16
154
  if (credential.credentialType !== defaultCredentialTypes.basic) {
@@ -22,46 +160,14 @@ export function createDIDAuthenticationService() {
22
160
  } catch {
23
161
  return false;
24
162
  }
25
- if (isPeer4(parsed.id)) {
26
- if (parsed.longForm == null) return false;
27
- let decoded;
163
+ if (parsed.controller != null) {
28
164
  try {
29
- decoded = decodePeer4(parsed.longForm);
165
+ return await validateBoundLeaf(parsed, signaturePublicKey, deviceDenySet);
30
166
  } catch {
31
167
  return false;
32
168
  }
33
- if (decoded.shortForm !== parsed.id) return false;
34
- // Only verification methods referenced by `authentication` are
35
- // permitted to sign for authentication — per DID Core. Reject MLS
36
- // leaves bound to keys outside that set (KEM keys, assertion-only
37
- // keys, etc.) even if the byte comparison would otherwise match.
38
- const authIDs = new Set(decoded.doc.authentication ?? []);
39
- if (authIDs.size === 0) return false;
40
- for (const vm of decoded.doc.verificationMethod ?? []){
41
- if (!authIDs.has(vm.id)) continue;
42
- if (typeof vm.publicKeyMultibase !== 'string') continue;
43
- let vmBytes;
44
- try {
45
- vmBytes = decodeMultibase(vm.publicKeyMultibase);
46
- } catch {
47
- continue;
48
- }
49
- // Validate multicodec prefix and strip it; rejects unknown codecs
50
- // (e.g. X25519 KEM keys, future PQ codecs) instead of blindly
51
- // comparing 2-byte-truncated bytes.
52
- const stripped = getAlgorithmAndPublicKey(vmBytes);
53
- if (stripped == null) continue;
54
- const [, publicKeyBytes] = stripped;
55
- if (constantTimeEqual(publicKeyBytes, signaturePublicKey)) return true;
56
- }
57
- return false;
58
- }
59
- try {
60
- const [, publicKeyFromDID] = getSignatureInfo(parsed.id);
61
- return constantTimeEqual(publicKeyFromDID, signaturePublicKey);
62
- } catch {
63
- return false;
64
169
  }
170
+ return matchesLeafKey(parsed, signaturePublicKey);
65
171
  }
66
172
  };
67
173
  }
@@ -1,5 +1,6 @@
1
- import { type DIDCache } from '@kokuin/token';
1
+ import type { SignedEvent } from '@kokuin/controller';
2
2
  import { type Credential } from 'ts-mls';
3
+ import type { ControllerBeacon } from './registry.js';
3
4
  /**
4
5
  * Local member state (never serialized to the MLS leaf). `id` is the member's own
5
6
  * DID; `groupID` names the group the handle belongs to.
@@ -22,24 +23,45 @@ export type MemberCredential = {
22
23
  * That tolerance is not a courtesy owed to a transition; there is no version of this code that
23
24
  * can stop honoring it without refusing leaves nothing is wrong with.
24
25
  */
26
+ /**
27
+ * Opt-in binding that makes an MLS leaf a *device of a `did:kokuin:` controller*. Present ⟺ bound.
28
+ * `id` names the profile DID; `prefix` is the authority-only controller-log prefix folded (sync) to
29
+ * verify the delegation; `capability` is the delegation token binding this device under the profile.
30
+ * All three are verification inputs — only the profile `id` is surfaced into `GroupMember`.
31
+ */
32
+ export type ControllerBinding = {
33
+ id: string;
34
+ prefix: Array<SignedEvent>;
35
+ capability: string;
36
+ };
25
37
  export type MLSCredentialIdentity = {
26
38
  v?: 1;
27
39
  id: string;
28
40
  longForm?: string;
41
+ controller?: ControllerBinding;
29
42
  };
30
43
  export type GroupMember = {
31
44
  /** MLS leaf index (ratchet-tree array position / 2, matching findMemberLeafIndex). */
32
45
  leafIndex: number;
33
46
  /** DID parsed from the leaf's MLS credential identity. */
34
47
  id: string;
48
+ /**
49
+ * The resolvable form of `id`: the leaf's `longForm` for did:peer:4, and `id` itself for
50
+ * did:key, where long form and short form are the same string. Never absent.
51
+ *
52
+ * This is why `@kumiai/mls` holds no DID cache. Every document a consumer can reach is
53
+ * already inside a signed artifact — a current member's in this leaf, which is signed and
54
+ * can never be rewritten, and a ledger author's in their own token, which `signLedgerEntry`
55
+ * gives `{ embedLongForm: true }` for exactly that reason. A cache alongside those would be
56
+ * an unsigned second copy of authenticated state.
57
+ */
58
+ longForm: string;
59
+ /** For a bound leaf: the authenticated `did:kokuin:` controller (profile) DID. Absent for floating leaves. */
60
+ controller?: string;
61
+ /** For a bound leaf: the controller's advisory folded log beacon, when one has been announced. */
62
+ controllerBeacon?: ControllerBeacon;
35
63
  };
36
64
  export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCredentialIdentity;
37
- /**
38
- * If the parsed credential carries a did:peer:4 long form, decode it and write
39
- * to the cache. Hash binding is enforced (decoded short form must equal `id`).
40
- * No-op for did:key.
41
- */
42
- export declare function populateCacheFromCredential(parsed: MLSCredentialIdentity, cache: DIDCache): Promise<void>;
43
65
  /**
44
66
  * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
45
67
  *
package/lib/credential.js CHANGED
@@ -1,4 +1,4 @@
1
- import { decodePeer4, isPeer4, normalizeDID } from '@kokuin/token';
1
+ import { normalizeDID } from '@kokuin/token';
2
2
  import { defaultCredentialTypes, isDefaultCredential } from 'ts-mls';
3
3
  export function parseMLSCredentialIdentity(identity) {
4
4
  const text = new TextDecoder().decode(identity);
@@ -35,20 +35,30 @@ export function parseMLSCredentialIdentity(identity) {
35
35
  if (typeof candidate.longForm === 'string') {
36
36
  result.longForm = candidate.longForm;
37
37
  }
38
- return result;
39
- }
40
- /**
41
- * If the parsed credential carries a did:peer:4 long form, decode it and write
42
- * to the cache. Hash binding is enforced (decoded short form must equal `id`).
43
- * No-op for did:key.
44
- */ export async function populateCacheFromCredential(parsed, cache) {
45
- if (parsed.longForm == null) return;
46
- if (!isPeer4(parsed.id)) return;
47
- const { shortForm, doc } = decodePeer4(parsed.longForm);
48
- if (shortForm !== parsed.id) {
49
- throw new Error('Credential longForm does not match credential.id');
38
+ if ('controller' in candidate) {
39
+ const c = candidate.controller;
40
+ if (c == null || typeof c !== 'object') {
41
+ throw new Error('Invalid MLS credential: controller must be an object when present');
42
+ }
43
+ const cc = c;
44
+ if (typeof cc.id !== 'string') {
45
+ throw new Error('Invalid MLS credential: controller.id must be a string');
46
+ }
47
+ if (typeof cc.capability !== 'string') {
48
+ throw new Error('Invalid MLS credential: controller.capability must be a string');
49
+ }
50
+ if (!Array.isArray(cc.prefix)) {
51
+ throw new Error('Invalid MLS credential: controller.prefix must be an array');
52
+ }
53
+ // Structural only — the prefix events are validated cryptographically by the fold in
54
+ // validateCredential, never here (parse stays pure/structural, like longForm).
55
+ result.controller = {
56
+ id: cc.id,
57
+ prefix: cc.prefix,
58
+ capability: cc.capability
59
+ };
50
60
  }
51
- await cache.set(shortForm, doc);
61
+ return result;
52
62
  }
53
63
  /**
54
64
  * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
package/lib/crypto.js CHANGED
@@ -13,6 +13,7 @@ import { ed25519, x25519 } from '@noble/curves/ed25519.js';
13
13
  import { expand as hkdfExpand, extract as hkdfExtract } from '@noble/hashes/hkdf.js';
14
14
  import { hmac } from '@noble/hashes/hmac.js';
15
15
  import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
16
+ import { concatBytes } from '@noble/hashes/utils.js';
16
17
  import { createRuntime } from '@sozai/runtime';
17
18
  // ---------------------------------------------------------------------------
18
19
  // Helpers
@@ -26,17 +27,6 @@ function constantTimeEqual(a, b) {
26
27
  }
27
28
  return diff === 0;
28
29
  }
29
- function concatBytes(...arrays) {
30
- let totalLen = 0;
31
- for (const a of arrays)totalLen += a.length;
32
- const result = new Uint8Array(totalLen);
33
- let offset = 0;
34
- for (const a of arrays){
35
- result.set(a, offset);
36
- offset += a.length;
37
- }
38
- return result;
39
- }
40
30
  function i2osp(value, w) {
41
31
  const result = new Uint8Array(w);
42
32
  let n = value;
@@ -0,0 +1,33 @@
1
+ import type { SignedEvent } from '@kokuin/controller';
2
+ import type { VerifiedLedgerEntry } from './ledger.js';
3
+ import type { DeviceValue } from './registry.js';
4
+ /** What the tree yields about a leaf for the device-proof gate: its binding, prefix, and leaf key. */
5
+ export type LeafBinding = {
6
+ /** The bound profile DID, or undefined for a floating leaf. */
7
+ controller?: string;
8
+ /** The embedded controller log prefix (present iff bound), for resolving a capability signature. */
9
+ prefix?: Array<SignedEvent>;
10
+ /** The leaf's MLS signature public key. */
11
+ leafKey: Uint8Array;
12
+ };
13
+ /** The pure inputs the gate reads: leaf bindings (from the pre-commit tree) and controllerOf. */
14
+ export type DeviceProofContext = {
15
+ bindingOfDID: (did: string) => LeafBinding | undefined;
16
+ controllerOf: (deviceDID: string) => string | undefined;
17
+ };
18
+ /**
19
+ * The acceptance-pipeline gate for one `kumiai.device` entry. Returns whether the entry is
20
+ * authorized; the caller rejects the WHOLE commit on any false.
21
+ *
22
+ * - beacon (`op: 'beacon'`): the issuer must be a bound device of the controller named as
23
+ * `subject`. Advisory and self-scoped — no capability.
24
+ * - self-register (`op: 'register'`, `subject === issuer`): the issuer's own leaf must be bound to
25
+ * `value.controller`. Leaf-attested — no capability.
26
+ * - manage ops (co-device register, add, revoke, label): the issuer must be a bound device of the
27
+ * authorized profile (`value.controller` for register/add, `controllerOf(subject)` for
28
+ * revoke/label), presenting that profile's management capability, `cnf`-pinned to the issuer's
29
+ * leaf key and `exp`-bounded. The profile's log prefix comes from the issuer's OWN bound leaf.
30
+ *
31
+ * Pure of the fold — runs only where the tree is present (never on a bootstrap re-fold).
32
+ */
33
+ export declare function verifyDeviceEntry(verified: VerifiedLedgerEntry<DeviceValue>, ctx: DeviceProofContext): Promise<boolean>;
@@ -0,0 +1,56 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { verifyManagementCapability } from './authentication.js';
3
+ /**
4
+ * The acceptance-pipeline gate for one `kumiai.device` entry. Returns whether the entry is
5
+ * authorized; the caller rejects the WHOLE commit on any false.
6
+ *
7
+ * - beacon (`op: 'beacon'`): the issuer must be a bound device of the controller named as
8
+ * `subject`. Advisory and self-scoped — no capability.
9
+ * - self-register (`op: 'register'`, `subject === issuer`): the issuer's own leaf must be bound to
10
+ * `value.controller`. Leaf-attested — no capability.
11
+ * - manage ops (co-device register, add, revoke, label): the issuer must be a bound device of the
12
+ * authorized profile (`value.controller` for register/add, `controllerOf(subject)` for
13
+ * revoke/label), presenting that profile's management capability, `cnf`-pinned to the issuer's
14
+ * leaf key and `exp`-bounded. The profile's log prefix comes from the issuer's OWN bound leaf.
15
+ *
16
+ * Pure of the fold — runs only where the tree is present (never on a bootstrap re-fold).
17
+ */ export async function verifyDeviceEntry(verified, ctx) {
18
+ const issuer = normalizeDID(verified.issuer);
19
+ const subject = normalizeDID(verified.entry.subject);
20
+ const value = verified.entry.value;
21
+ if (value.op === 'beacon') {
22
+ // Self-scoped, low-stakes: the issuer must be a bound device of the controller named as
23
+ // `subject`. Advisory state that gates nothing, so NO management capability is required —
24
+ // unlike revoke/label, which manage another device's binding.
25
+ const binding = ctx.bindingOfDID(issuer);
26
+ if (binding?.controller == null) return false;
27
+ return normalizeDID(binding.controller) === subject;
28
+ }
29
+ if (value.op === 'register' && subject === issuer) {
30
+ const binding = ctx.bindingOfDID(issuer);
31
+ if (binding?.controller == null || value.controller == null) return false;
32
+ return normalizeDID(binding.controller) === normalizeDID(value.controller);
33
+ }
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
+ }
46
+ const binding = ctx.bindingOfDID(issuer);
47
+ if (binding?.controller == null || binding.prefix == null) return false;
48
+ if (normalizeDID(binding.controller) !== authorizedProfile) return false;
49
+ return await verifyManagementCapability({
50
+ capability: value.capability,
51
+ prefix: binding.prefix,
52
+ controllerID: authorizedProfile,
53
+ audience: issuer,
54
+ leafKey: binding.leafKey
55
+ });
56
+ }
@@ -0,0 +1,16 @@
1
+ import { type SignedEvent } from '@kokuin/controller';
2
+ import type { DIDMethodResolver } from '@kokuin/token';
3
+ /**
4
+ * A `did:kokuin:` resolver whose log is the prefix EMBEDDED in an MLS leaf — never fetched
5
+ * externally. `loadLog` answers only for `controllerID`, returning the embedded `prefix`, and
6
+ * `undefined` for any other DID, so no code path can reach a sidecar. `resolveDenySet` is overridden
7
+ * to answer from the injected group-folded set (freshness), rather than the prefix's frozen head.
8
+ *
9
+ * A per-leaf, one-shot instance: the prefix is small, verification is single-pass, and no `history`
10
+ * store is configured. This is the adapter the Slice 1 spike verified to run with zero external I/O.
11
+ */
12
+ export declare function createEmbeddedControllerResolver(params: {
13
+ controllerID: string;
14
+ prefix: Array<SignedEvent>;
15
+ denySet?: ReadonlySet<string>;
16
+ }): DIDMethodResolver;
@@ -0,0 +1,21 @@
1
+ import { createControllerResolver } from '@kokuin/controller';
2
+ const EMPTY = new Set();
3
+ /**
4
+ * A `did:kokuin:` resolver whose log is the prefix EMBEDDED in an MLS leaf — never fetched
5
+ * externally. `loadLog` answers only for `controllerID`, returning the embedded `prefix`, and
6
+ * `undefined` for any other DID, so no code path can reach a sidecar. `resolveDenySet` is overridden
7
+ * to answer from the injected group-folded set (freshness), rather than the prefix's frozen head.
8
+ *
9
+ * A per-leaf, one-shot instance: the prefix is small, verification is single-pass, and no `history`
10
+ * store is configured. This is the adapter the Slice 1 spike verified to run with zero external I/O.
11
+ */ export function createEmbeddedControllerResolver(params) {
12
+ const base = createControllerResolver({
13
+ loadLog: async (did)=>did === params.controllerID ? params.prefix : undefined
14
+ });
15
+ return {
16
+ ...base,
17
+ async resolveDenySet (_did) {
18
+ return params.denySet ?? EMPTY;
19
+ }
20
+ };
21
+ }
@@ -1,15 +1,18 @@
1
1
  import type { FoldInput } from './fold.js';
2
2
  import type { VerifiedLedgerEntry } from './ledger.js';
3
+ import { type DeviceRegistry } from './registry.js';
3
4
  import { type RosterState } from './roster.js';
4
5
  /**
5
6
  * The outcome of folding an envelope's control entries. On accept: the candidate
6
- * roster (base ∪ this envelope's kumiai.role entries) and the non-group entries to
7
- * surface to the consumer, in envelope order. On reject: a reason and the offending
8
- * entry id. A rejection is a value — the caller turns it into a commit rejection.
7
+ * roster (base ∪ this envelope's kumiai.role entries), the candidate registry (base ∪
8
+ * this envelope's kumiai.device entries), and the non-group entries to surface to the
9
+ * consumer, in envelope order. On reject: a reason and the offending entry id. A
10
+ * rejection is a value — the caller turns it into a commit rejection.
9
11
  */
10
12
  export type EnvelopeFoldResult = {
11
13
  ok: true;
12
14
  roster: RosterState;
15
+ registry: DeviceRegistry;
13
16
  surfaced: Array<VerifiedLedgerEntry>;
14
17
  } | {
15
18
  ok: false;
@@ -33,4 +36,4 @@ export declare const GROUP_TYPE_PREFIX = "kumiai.";
33
36
  * subsumes `kumiai.role`'s own authority rule. State-so-far, not a pre-commit
34
37
  * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
35
38
  */
36
- export declare function foldEnvelope(baseRoster: RosterState, entries: Array<FoldInput>, groupID: string): EnvelopeFoldResult;
39
+ export declare function foldEnvelope(baseRoster: RosterState, baseRegistry: DeviceRegistry, entries: Array<FoldInput>, groupID: string): EnvelopeFoldResult;
@@ -1,3 +1,4 @@
1
+ import { authority, DEVICE_ENTRY_TYPE, isDeviceValue, registryApply } from './registry.js';
1
2
  import { adminCount, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
2
3
  export const GROUP_TYPE_PREFIX = 'kumiai.';
3
4
  function isRoleValue(value) {
@@ -18,10 +19,14 @@ function isRoleValue(value) {
18
19
  * entry's issuer must be an admin at its own position — the universal invariant that
19
20
  * subsumes `kumiai.role`'s own authority rule. State-so-far, not a pre-commit
20
21
  * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
21
- */ export function foldEnvelope(baseRoster, entries, groupID) {
22
+ */ export function foldEnvelope(baseRoster, baseRegistry, entries, groupID) {
22
23
  let workingRoster = {
23
24
  roles: new Map(baseRoster.roles)
24
25
  };
26
+ let workingRegistry = {
27
+ devices: new Map(baseRegistry.devices),
28
+ controllers: new Map(baseRegistry.controllers)
29
+ };
25
30
  const surfaced = [];
26
31
  for (const { verified, entryID } of entries){
27
32
  const { entry, issuer } = verified;
@@ -33,8 +38,30 @@ function isRoleValue(value) {
33
38
  entryID
34
39
  };
35
40
  }
36
- // The universal invariant: the issuer must be an admin in state-so-far.
37
- if (workingRoster.roles.get(issuer) !== 'admin') {
41
+ // The typed exception to the admin invariant: a device entry is authorized by a proof in the
42
+ // acceptance pipeline, not a roster role. The fold applies it structurally and threads the
43
+ // registry that later authority checks read.
44
+ if (entry.type === DEVICE_ENTRY_TYPE) {
45
+ if (!isDeviceValue(entry.value)) {
46
+ return {
47
+ ok: false,
48
+ reason: 'malformed kumiai.device value',
49
+ entryID
50
+ };
51
+ }
52
+ const value = entry.value;
53
+ workingRegistry = registryApply({
54
+ issuer,
55
+ entry: {
56
+ ...entry,
57
+ value
58
+ }
59
+ }, workingRegistry);
60
+ continue;
61
+ }
62
+ // The universal invariant, now authority-aware: the issuer's AUTHORITY (controller ?? id,
63
+ // read off the registry-so-far) must be an admin in state-so-far.
64
+ if (workingRoster.roles.get(authority(workingRegistry, issuer)) !== 'admin') {
38
65
  return {
39
66
  ok: false,
40
67
  reason: `non-admin issuer '${issuer}'`,
@@ -81,6 +108,7 @@ function isRoleValue(value) {
81
108
  return {
82
109
  ok: true,
83
110
  roster: workingRoster,
111
+ registry: workingRegistry,
84
112
  surfaced
85
113
  };
86
114
  }
@@ -73,7 +73,10 @@ export declare function createInvite(params: CreateInviteParams): Promise<Create
73
73
  * proposal advancing the head by exactly those ids, in envelope order. An empty list
74
74
  * moves no head and carries no envelope.
75
75
  */
76
- export declare function commitWithEntries(group: GroupHandle, extraProposals: Array<DefaultProposal>, enacted: Array<string>, ratchetTreeExtension?: boolean): Promise<Awaited<ReturnType<typeof createCommit>>>;
76
+ export declare function commitWithEntries(group: GroupHandle, extraProposals: Array<DefaultProposal>, enacted: Array<string>, options?: {
77
+ ratchetTreeExtension?: boolean;
78
+ requireAdmin?: boolean;
79
+ }): Promise<Awaited<ReturnType<typeof createCommit>>>;
77
80
  export type CommitLedgerEntriesResult = {
78
81
  /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
79
82
  commitMessage: Uint8Array;