@kumiai/mls 0.4.1 → 0.5.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.
package/README.md CHANGED
@@ -10,6 +10,9 @@ 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
+ - `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
+ - `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
+ - `keyPackageRef` — the base64 KeyPackageRef a Welcome names, stable across a codec round trip. Use it as the identity of a stored package.
13
16
  - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
14
17
 
15
18
  ## Authority model
@@ -73,3 +76,13 @@ MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it doe
73
76
  - Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
74
77
 
75
78
  The follow-up revocation work will introduce a ledger entry that removes a DID's role from the roster, synced through the same GroupContext ledger-head extension the roster already rides. Once a revoked DID is no longer a roster member, the external-commit policy rejects its resync exactly as it rejects a stranger today.
79
+
80
+ ### ⚠️ Security: retain the last-resort bundle after Welcome
81
+
82
+ `createLastResortKeyPackageBundle` produces a `KeyPackageBundle` marked with the `last_resort` extension (draft-ietf-mls-extensions) — reusable by design, so a hub may hand the same one to every future inviter once the owner's ordinary pool is drained. `@kumiai/mls` never owns private key material: `processWelcome` takes the bundle as a caller-supplied parameter and does not persist it, so retention is entirely the host's responsibility. Delete a last-resort `privatePackage` after processing a Welcome — the way a host correctly would for an ordinary, single-use bundle — and the member is silently unaddable forever, which is the exact outage this feature exists to prevent. The host must keep the last-resort bundle's private half around, distinct from ordinary bundles, for as long as it may be reused. A `KeyPackageBundle` carries no marker of its own, so a host that persists bundles generically can recognize one with `bundle.publicPackage.extensions.some((e) => e.extensionType === LAST_RESORT_EXTENSION_TYPE)` — `LAST_RESORT_EXTENSION_TYPE` is exported for exactly this.
83
+
84
+ ### ⚠️ Security: rotate the last-resort bundle before it expires
85
+
86
+ A last-resort key package carries an MLS lifetime of `LAST_RESORT_LIFETIME_DAYS` (90). The inviter validates that lifetime when building the Add, so an expired package is refused at the far end with `Current time not within Lifetime` — and refused *no matter what the hub does*, because the hub stores opaque bytes and cannot see the expiry.
87
+
88
+ That makes the failure worse than an empty slot: the hub goes on reporting the slot as full and serving the dead package, so the availability floor looks healthy while every join through it fails. A host must generate and upload a fresh last-resort bundle before the window elapses, and keep the new private half. Uploading once at enrolment buys 90 days, not forever.
package/lib/anchor.d.ts CHANGED
@@ -38,6 +38,14 @@ export declare function encodeGroupAnchor(anchor: GroupAnchor): Uint8Array;
38
38
  * Tolerant decode: null on malformed bytes or wrong shape, never throws. `creatorDID` must be a
39
39
  * string and `version` a number; `app` is optional, so its absence isn't malformed. A consumer
40
40
  * needing a specific `app` shape validates that itself.
41
+ *
42
+ * Forward-compat gate: when `version > CURRENT_VERSION` (a future build wrote it), the returned
43
+ * anchor keeps `creatorDID` and `version` but drops `app` — the opaque payload may carry semantics
44
+ * this build has never seen, and a v1 consumer reading it as v1 (kubun keeps its recovery seed in
45
+ * `app`) cannot tell. `version` is preserved so a consumer distinguishes "future version, app
46
+ * 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.
41
49
  */
42
50
  export declare function decodeGroupAnchor(bytes: Uint8Array): GroupAnchor | null;
43
51
  export declare function buildGroupAnchorExtension(anchor: GroupAnchor): GroupContextExtension;
@@ -69,5 +77,9 @@ export declare function readGroupAnchorExtension(handle: GroupHandle): GroupCont
69
77
  * silently downgrading (the anchor is authenticated by the GroupInfo signature, so this guards
70
78
  * corruption, not forgery). Use {@link readGroupAnchorExtension} for bytes to copy into a
71
79
  * proposal — never a re-encode of this result.
80
+ *
81
+ * A future-version anchor is not corruption: {@link decodeGroupAnchor} decodes it (dropping `app`),
82
+ * so this returns a non-null anchor and the member joins. Only the payload a v1 build cannot
83
+ * interpret is withheld.
72
84
  */
73
85
  export declare function readGroupAnchor(handle: GroupHandle): GroupAnchor | null;
package/lib/anchor.js CHANGED
@@ -25,6 +25,14 @@ export function encodeGroupAnchor(anchor) {
25
25
  * Tolerant decode: null on malformed bytes or wrong shape, never throws. `creatorDID` must be a
26
26
  * string and `version` a number; `app` is optional, so its absence isn't malformed. A consumer
27
27
  * needing a specific `app` shape validates that itself.
28
+ *
29
+ * Forward-compat gate: when `version > CURRENT_VERSION` (a future build wrote it), the returned
30
+ * anchor keeps `creatorDID` and `version` but drops `app` — the opaque payload may carry semantics
31
+ * this build has never seen, and a v1 consumer reading it as v1 (kubun keeps its recovery seed in
32
+ * `app`) cannot tell. `version` is preserved so a consumer distinguishes "future version, app
33
+ * 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.
28
36
  */ export function decodeGroupAnchor(bytes) {
29
37
  let parsed;
30
38
  try {
@@ -43,7 +51,12 @@ export function encodeGroupAnchor(anchor) {
43
51
  creatorDID: record.creatorDID,
44
52
  version: record.version
45
53
  };
46
- if ('app' in record && record.app !== undefined) {
54
+ // Withhold the app payload from a future build's anchor: a version this build
55
+ // has never seen may carry a payload with v2 semantics, and handing it to a
56
+ // consumer under v1 expectations is exactly the silent misread this guards.
57
+ // The structural fields (creatorDID, version) stay usable, so the member still
58
+ // joins — only the opaque payload it provably cannot interpret is dropped.
59
+ if (record.version <= CURRENT_VERSION && 'app' in record && record.app !== undefined) {
47
60
  anchor.app = record.app;
48
61
  }
49
62
  return anchor;
@@ -102,6 +115,10 @@ function findAnchorExtension(handle) {
102
115
  * silently downgrading (the anchor is authenticated by the GroupInfo signature, so this guards
103
116
  * corruption, not forgery). Use {@link readGroupAnchorExtension} for bytes to copy into a
104
117
  * proposal — never a re-encode of this result.
118
+ *
119
+ * A future-version anchor is not corruption: {@link decodeGroupAnchor} decodes it (dropping `app`),
120
+ * so this returns a non-null anchor and the member joins. Only the payload a v1 build cannot
121
+ * interpret is withheld.
105
122
  */ export function readGroupAnchor(handle) {
106
123
  const extension = findAnchorExtension(handle);
107
124
  if (extension == null) {
@@ -1,4 +1,5 @@
1
1
  import { type DIDCache } from '@kokuin/token';
2
+ import { type Credential } from 'ts-mls';
2
3
  /**
3
4
  * Local member state (never serialized to the MLS leaf). `id` is the member's own
4
5
  * DID; `groupID` names the group the handle belongs to.
@@ -39,3 +40,22 @@ export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCre
39
40
  * No-op for did:key.
40
41
  */
41
42
  export declare function populateCacheFromCredential(parsed: MLSCredentialIdentity, cache: DIDCache): Promise<void>;
43
+ /**
44
+ * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
45
+ *
46
+ * Total by contract. The receive-side commit policy calls this on a leaf inside an untrusted
47
+ * commit, and `defaultCommitPolicy` is pure and total — a malformed credential must read as
48
+ * "no DID", never throw past the policy boundary. Every rejection `parseMLSCredentialIdentity`
49
+ * raises collapses to `undefined` here: non-JSON bytes, a non-object value, an unsupported `v`, a
50
+ * non-string `id`, a non-string `longForm`.
51
+ *
52
+ * `credentialType !== basic` does not narrow on its own: `CredentialCustom.credentialType` is a
53
+ * bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
54
+ *
55
+ * Syntax is not validated. An identity naming an arbitrary string returns that string, which no
56
+ * roster grants — a lookup miss, and deliberately distinct from a credential that names nothing.
57
+ *
58
+ * Not re-exported from the package index: `policy.ts` is the only consumer today, and widening the
59
+ * surface is cheap to do later and impossible to undo.
60
+ */
61
+ export declare function didFromCredential(credential: Credential): string | undefined;
package/lib/credential.js CHANGED
@@ -1,4 +1,5 @@
1
- import { decodePeer4, isPeer4 } from '@kokuin/token';
1
+ import { decodePeer4, isPeer4, normalizeDID } from '@kokuin/token';
2
+ import { defaultCredentialTypes, isDefaultCredential } from 'ts-mls';
2
3
  export function parseMLSCredentialIdentity(identity) {
3
4
  const text = new TextDecoder().decode(identity);
4
5
  let parsed;
@@ -49,3 +50,30 @@ export function parseMLSCredentialIdentity(identity) {
49
50
  }
50
51
  await cache.set(shortForm, doc);
51
52
  }
53
+ /**
54
+ * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
55
+ *
56
+ * Total by contract. The receive-side commit policy calls this on a leaf inside an untrusted
57
+ * commit, and `defaultCommitPolicy` is pure and total — a malformed credential must read as
58
+ * "no DID", never throw past the policy boundary. Every rejection `parseMLSCredentialIdentity`
59
+ * raises collapses to `undefined` here: non-JSON bytes, a non-object value, an unsupported `v`, a
60
+ * non-string `id`, a non-string `longForm`.
61
+ *
62
+ * `credentialType !== basic` does not narrow on its own: `CredentialCustom.credentialType` is a
63
+ * bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
64
+ *
65
+ * Syntax is not validated. An identity naming an arbitrary string returns that string, which no
66
+ * roster grants — a lookup miss, and deliberately distinct from a credential that names nothing.
67
+ *
68
+ * Not re-exported from the package index: `policy.ts` is the only consumer today, and widening the
69
+ * surface is cheap to do later and impossible to undo.
70
+ */ export function didFromCredential(credential) {
71
+ if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
72
+ return undefined;
73
+ }
74
+ try {
75
+ return normalizeDID(parseMLSCredentialIdentity(credential.identity).id);
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ }
@@ -3,6 +3,39 @@ import { createCommit, type DefaultProposal, type KeyPackage } from 'ts-mls';
3
3
  import { type GroupHandle } from './group-handle.js';
4
4
  import { type GroupPermission } from './roster.js';
5
5
  import type { Invite } from './types.js';
6
+ export type InviteRecipientMismatchErrorParams = {
7
+ groupID: string;
8
+ expectedDID: string;
9
+ actualDID: string;
10
+ };
11
+ /**
12
+ * Thrown by {@link commitInvite} when the supplied key package's credential DID is not the
13
+ * identity the invite's enacted role entry grants a role to.
14
+ *
15
+ * Distinct from an ordinary rejection on purpose: the expected trigger is a key-package store
16
+ * that served the wrong owner's package, and adding the package anyway would put a different
17
+ * identity in the group than the one the roster grants the role to. A host should alert on this.
18
+ *
19
+ * The same error also fires for any invite whose trailing `kumiai.role` entry names someone
20
+ * other than the intended invitee — hand-built, tampered, or reordered — with an otherwise
21
+ * honest key package. A host seeing this should not assume a store compromise on that basis
22
+ * alone.
23
+ *
24
+ * The receive-side add rule in {@link defaultCommitPolicy} does NOT close this residual, though it
25
+ * is easy to assume it would. That rule rejects an Add whose DID the candidate roster grants
26
+ * nothing; in the reordered case the trailing grant's subject IS granted, so the Add passes and the
27
+ * intended invitee is left holding a grant it never joined against. Closing it needs this binding to
28
+ * seek the enacted entry matching the key package's DID rather than reading the last one.
29
+ */
30
+ export declare class InviteRecipientMismatchError extends Error {
31
+ #private;
32
+ constructor(params: InviteRecipientMismatchErrorParams);
33
+ get groupID(): string;
34
+ /** DID the invite's enacted role entry grants to. */
35
+ get expectedDID(): string;
36
+ /** DID the supplied key package presents. */
37
+ get actualDID(): string;
38
+ }
6
39
  export type CreateInviteParams = {
7
40
  group: GroupHandle;
8
41
  identity: SigningIdentity;
@@ -1,6 +1,7 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { createCommit, defaultProposalTypes, encode, mlsMessageEncoder } from 'ts-mls';
2
+ import { createCommit, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsMessageEncoder } from 'ts-mls';
3
3
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ import { parseMLSCredentialIdentity } from './credential.js';
4
5
  import { encodeControlEnvelope } from './envelope.js';
5
6
  import { foldEnvelope } from './envelope-fold.js';
6
7
  import { buildCommitPolicyContext, deriveGroup, mutexFor } from './group-handle.js';
@@ -8,6 +9,45 @@ import { buildLedgerHeadExtension, extendHead, readLedgerHead } from './head.js'
8
9
  import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
9
10
  import { defaultCommitPolicy } from './policy.js';
10
11
  import { ROLE_ENTRY_TYPE } from './roster.js';
12
+ /**
13
+ * Thrown by {@link commitInvite} when the supplied key package's credential DID is not the
14
+ * identity the invite's enacted role entry grants a role to.
15
+ *
16
+ * Distinct from an ordinary rejection on purpose: the expected trigger is a key-package store
17
+ * that served the wrong owner's package, and adding the package anyway would put a different
18
+ * identity in the group than the one the roster grants the role to. A host should alert on this.
19
+ *
20
+ * The same error also fires for any invite whose trailing `kumiai.role` entry names someone
21
+ * other than the intended invitee — hand-built, tampered, or reordered — with an otherwise
22
+ * honest key package. A host seeing this should not assume a store compromise on that basis
23
+ * alone.
24
+ *
25
+ * The receive-side add rule in {@link defaultCommitPolicy} does NOT close this residual, though it
26
+ * is easy to assume it would. That rule rejects an Add whose DID the candidate roster grants
27
+ * nothing; in the reordered case the trailing grant's subject IS granted, so the Add passes and the
28
+ * intended invitee is left holding a grant it never joined against. Closing it needs this binding to
29
+ * seek the enacted entry matching the key package's DID rather than reading the last one.
30
+ */ export class InviteRecipientMismatchError extends Error {
31
+ #groupID;
32
+ #expectedDID;
33
+ #actualDID;
34
+ constructor(params){
35
+ super(`commitInvite: the key package presents ${params.actualDID}, but the invite grants a role to ${params.expectedDID}`);
36
+ this.name = 'InviteRecipientMismatchError';
37
+ this.#groupID = params.groupID;
38
+ this.#expectedDID = params.expectedDID;
39
+ this.#actualDID = params.actualDID;
40
+ }
41
+ get groupID() {
42
+ return this.#groupID;
43
+ }
44
+ /** DID the invite's enacted role entry grants to. */ get expectedDID() {
45
+ return this.#expectedDID;
46
+ }
47
+ /** DID the supplied key package presents. */ get actualDID() {
48
+ return this.#actualDID;
49
+ }
50
+ }
11
51
  /**
12
52
  * Create an invite for a new member. Does NOT add them — call commitInvite with
13
53
  * their key package for that.
@@ -227,6 +267,47 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
227
267
  throw new Error(`commitInvite: invite is for group ${invite.groupID}, not ${group.groupID}`);
228
268
  }
229
269
  const enacted = entriesAddedByInvite(group, invite);
270
+ // Bind the leaf that joins to the role this same commit grants. Without it the joining
271
+ // identity is decided by whoever supplied the key package bytes — a store that served the
272
+ // wrong owner's package admits that owner while the roster names someone else, and neither
273
+ // side can see the disagreement from its own state.
274
+ //
275
+ // The LAST role entry, because an invite may legitimately carry an unrelated promotion
276
+ // riding the same commit, and createInvite puts the invitee's own grant last.
277
+ //
278
+ // The `groupID` check is belt-and-braces: `foldEnvelope` already hard-rejects any
279
+ // cross-group entry in `enacted`, so no invite reaching this point can carry one.
280
+ let grantedTo = null;
281
+ for (const token of enacted){
282
+ const verified = await verifyLedgerEntry(token);
283
+ if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === group.groupID) {
284
+ grantedTo = verified.entry.subject;
285
+ }
286
+ }
287
+ if (grantedTo == null) {
288
+ throw new Error(`commitInvite: the invite enacts no ${ROLE_ENTRY_TYPE} entry for this group, so there is no recipient to bind the key package to`);
289
+ }
290
+ const expectedDID = normalizeDID(grantedTo);
291
+ // `credentialType !== basic` does not narrow on its own: CredentialCustom.credentialType is a
292
+ // bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
293
+ //
294
+ // This inlines the same credential->DID chain `didFromCredential` (credential.ts) implements
295
+ // for the receive-side policy, kept separate deliberately: this path needs to distinguish a
296
+ // non-basic credential from a malformed-JSON failure for its error messages, and that helper
297
+ // is deliberately unexported. The two must stay in agreement — if they diverge, the committer
298
+ // authors a commit every receiver rejects, a liveness failure rather than a security one.
299
+ const credential = keyPackage.leafNode.credential;
300
+ if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
301
+ throw new Error('commitInvite: the key package carries a non-basic credential, which names no DID to bind');
302
+ }
303
+ const actualDID = normalizeDID(parseMLSCredentialIdentity(credential.identity).id);
304
+ if (actualDID !== expectedDID) {
305
+ throw new InviteRecipientMismatchError({
306
+ groupID: group.groupID,
307
+ expectedDID,
308
+ actualDID
309
+ });
310
+ }
230
311
  const addProposal = {
231
312
  proposalType: defaultProposalTypes.add,
232
313
  add: {
@@ -2,5 +2,61 @@ import { type OwnIdentity } from '@kokuin/token';
2
2
  import { type Credential } from 'ts-mls';
3
3
  import type { GroupOptions, KeyPackageBundle } from './types.js';
4
4
  export declare function makeMLSCredential(identity: OwnIdentity): Credential;
5
+ /**
6
+ * How long an ordinary, single-use key package stays valid, in days.
7
+ *
8
+ * Pinned here rather than left to ts-mls's unexported `defaultLifetime()` (~15 days): the top-up
9
+ * cadence `@kumiai/mls-hub`'s pool is built around is this number, and a dependency's private
10
+ * default can move under a patch bump. 30 sits well under the 4-month `maximumTotalLifetime` ts-mls
11
+ * declares, and makes a weekly top-up comfortable rather than marginal.
12
+ */
13
+ export declare const ORDINARY_KEY_PACKAGE_LIFETIME_DAYS = 30;
5
14
  /** Generate a key package for joining groups. */
6
15
  export declare function createKeyPackageBundle(identity: OwnIdentity, options?: GroupOptions): Promise<KeyPackageBundle>;
16
+ /**
17
+ * The `last_resort` KeyPackage extension from draft-ietf-mls-extensions (NOT RFC 9420, which has
18
+ * no such extension). Its presence marks a key package as reusable by design; its data is empty.
19
+ *
20
+ * Needs no entry in the leaf's capabilities, so `controlCapabilities()` is unaffected: RFC 9420's
21
+ * capabilities rule binds leaf-node extensions and this one is KeyPackage-only, and neither draft
22
+ * -05 (which this value matches) nor -08 adds an advertisement clause.
23
+ *
24
+ * Draft -08 moved the feature to MLS Component Type `0x00000004` inside `app_data_dictionary`, but
25
+ * `0x000A` is what deployed implementations ship (OpenMLS `main`: `ExtensionType::LastResort => 10`).
26
+ * Anyone migrating must revisit `controlCapabilities()`, because -08 *does* ask clients to advertise
27
+ * `app_data_dictionary` support. See `docs/reference/reserved-namespaces.md`.
28
+ */
29
+ export declare const LAST_RESORT_EXTENSION_TYPE = 10;
30
+ /**
31
+ * How long a last-resort key package stays valid, in days.
32
+ *
33
+ * ts-mls's own `defaultLifetime()` is ~15 days, which is right for a single-use package but wrong
34
+ * for a standing availability floor: the slot would go full-but-dead a fortnight after upload, and
35
+ * the failure is silent in the worst way — the hub keeps serving the expired package and every Add
36
+ * fails at the *inviter*, who checks the lifetime when building the commit.
37
+ *
38
+ * 90 days sits under the 4-month `maximumTotalLifetime` ts-mls declares (currently unenforced, but
39
+ * designing above a declared ceiling is a bet against a future release).
40
+ *
41
+ * **This is a rotation deadline, not a solution.** A host must re-upload before it elapses, or the
42
+ * floor disappears exactly when it is needed.
43
+ */
44
+ export declare const LAST_RESORT_LIFETIME_DAYS = 90;
45
+ /**
46
+ * Generate a reusable last-resort key package for joining groups.
47
+ *
48
+ * A hub may serve this one repeatedly without consuming it, so the owner stays addable to a group
49
+ * even after their ordinary single-use packages have been drained. Upload it through the hub's
50
+ * last-resort slot, never through the ordinary pool.
51
+ *
52
+ * **The caller must retain `privatePackage` after processing a Welcome** rather than deleting it
53
+ * as it would for an ordinary bundle: the same package can be handed to another inviter later.
54
+ * `@kumiai/mls` never owns private packages — `processWelcome` takes the bundle as a parameter —
55
+ * so nothing here can enforce that for you.
56
+ *
57
+ * **The caller must also re-upload before {@link LAST_RESORT_LIFETIME_DAYS} elapses.** The package
58
+ * carries an MLS lifetime, and an inviter validates it when building the Add — so an unrotated
59
+ * package stops working while the hub still reports the slot as full and keeps serving it. Both
60
+ * obligations fail the same way: silently, and precisely when the floor is needed.
61
+ */
62
+ export declare function createLastResortKeyPackageBundle(identity: OwnIdentity, options?: GroupOptions): Promise<KeyPackageBundle>;
@@ -1,5 +1,5 @@
1
1
  import { isPeer4 } from '@kokuin/token';
2
- import { defaultCredentialTypes, generateKeyPackageWithKey } from 'ts-mls';
2
+ import { defaultCredentialTypes, generateKeyPackageWithKey, greaseExtensions, makeCustomExtension } from 'ts-mls';
3
3
  import { controlCapabilities } from './anchor.js';
4
4
  import { resolveMlsContext } from './group-context.js';
5
5
  export function makeMLSCredential(identity) {
@@ -20,7 +20,15 @@ export function makeMLSCredential(identity) {
20
20
  identity: new TextEncoder().encode(JSON.stringify(payload))
21
21
  };
22
22
  }
23
- /** Generate a key package for joining groups. */ export async function createKeyPackageBundle(identity, options) {
23
+ /**
24
+ * Shared key-package construction. An invitee leaf must advertise the control extension types or
25
+ * ts-mls refuses to add it to an anchored group. An explicit `options.capabilities` override still
26
+ * wins.
27
+ *
28
+ * `extensions` is left genuinely absent (not passed as `undefined`) when the caller supplies none,
29
+ * so `generateKeyPackageWithKey`'s own `params.extensions ?? greaseExtensions(...)` default still
30
+ * applies for the ordinary path.
31
+ */ async function buildBundle(identity, options, overrides = {}) {
24
32
  const { cipherSuite } = await resolveMlsContext(options);
25
33
  const result = await generateKeyPackageWithKey({
26
34
  credential: makeMLSCredential(identity),
@@ -29,12 +37,104 @@ export function makeMLSCredential(identity) {
29
37
  publicKey: identity.publicKey
30
38
  },
31
39
  cipherSuite,
32
- // An invitee leaf must advertise the control extension types or ts-mls
33
- // refuses to add it to an anchored group. An explicit override still wins.
34
- capabilities: options?.capabilities ?? controlCapabilities()
40
+ capabilities: options?.capabilities ?? controlCapabilities(),
41
+ // Omitted entirely for the ordinary path, so ts-mls applies its own defaults.
42
+ ...overrides.extensions != null ? {
43
+ extensions: overrides.extensions
44
+ } : {},
45
+ ...overrides.lifetime != null ? {
46
+ lifetime: overrides.lifetime
47
+ } : {}
35
48
  });
36
49
  return {
37
50
  ...result,
38
51
  ownerDID: identity.id
39
52
  };
40
53
  }
54
+ /**
55
+ * How long an ordinary, single-use key package stays valid, in days.
56
+ *
57
+ * Pinned here rather than left to ts-mls's unexported `defaultLifetime()` (~15 days): the top-up
58
+ * cadence `@kumiai/mls-hub`'s pool is built around is this number, and a dependency's private
59
+ * default can move under a patch bump. 30 sits well under the 4-month `maximumTotalLifetime` ts-mls
60
+ * declares, and makes a weekly top-up comfortable rather than marginal.
61
+ */ export const ORDINARY_KEY_PACKAGE_LIFETIME_DAYS = 30;
62
+ /** Back-dated a day, as ts-mls's own default is, so peer clock skew cannot invalidate a fresh package. */ function ordinaryLifetime() {
63
+ const nowSeconds = Math.floor(Date.now() / 1000);
64
+ return {
65
+ notBefore: BigInt(nowSeconds - 86_400),
66
+ notAfter: BigInt(nowSeconds + ORDINARY_KEY_PACKAGE_LIFETIME_DAYS * 86_400)
67
+ };
68
+ }
69
+ /** Generate a key package for joining groups. */ export async function createKeyPackageBundle(identity, options) {
70
+ return buildBundle(identity, options, {
71
+ lifetime: ordinaryLifetime()
72
+ });
73
+ }
74
+ /**
75
+ * The `last_resort` KeyPackage extension from draft-ietf-mls-extensions (NOT RFC 9420, which has
76
+ * no such extension). Its presence marks a key package as reusable by design; its data is empty.
77
+ *
78
+ * Needs no entry in the leaf's capabilities, so `controlCapabilities()` is unaffected: RFC 9420's
79
+ * capabilities rule binds leaf-node extensions and this one is KeyPackage-only, and neither draft
80
+ * -05 (which this value matches) nor -08 adds an advertisement clause.
81
+ *
82
+ * Draft -08 moved the feature to MLS Component Type `0x00000004` inside `app_data_dictionary`, but
83
+ * `0x000A` is what deployed implementations ship (OpenMLS `main`: `ExtensionType::LastResort => 10`).
84
+ * Anyone migrating must revisit `controlCapabilities()`, because -08 *does* ask clients to advertise
85
+ * `app_data_dictionary` support. See `docs/reference/reserved-namespaces.md`.
86
+ */ export const LAST_RESORT_EXTENSION_TYPE = 0x000a;
87
+ /**
88
+ * How long a last-resort key package stays valid, in days.
89
+ *
90
+ * ts-mls's own `defaultLifetime()` is ~15 days, which is right for a single-use package but wrong
91
+ * for a standing availability floor: the slot would go full-but-dead a fortnight after upload, and
92
+ * the failure is silent in the worst way — the hub keeps serving the expired package and every Add
93
+ * fails at the *inviter*, who checks the lifetime when building the commit.
94
+ *
95
+ * 90 days sits under the 4-month `maximumTotalLifetime` ts-mls declares (currently unenforced, but
96
+ * designing above a declared ceiling is a bet against a future release).
97
+ *
98
+ * **This is a rotation deadline, not a solution.** A host must re-upload before it elapses, or the
99
+ * floor disappears exactly when it is needed.
100
+ */ export const LAST_RESORT_LIFETIME_DAYS = 90;
101
+ /** Back-dated a day, as ts-mls's own default is, so peer clock skew cannot invalidate a fresh package. */ function lastResortLifetime() {
102
+ const nowSeconds = Math.floor(Date.now() / 1000);
103
+ return {
104
+ notBefore: BigInt(nowSeconds - 86_400),
105
+ notAfter: BigInt(nowSeconds + LAST_RESORT_LIFETIME_DAYS * 86_400)
106
+ };
107
+ }
108
+ /**
109
+ * Generate a reusable last-resort key package for joining groups.
110
+ *
111
+ * A hub may serve this one repeatedly without consuming it, so the owner stays addable to a group
112
+ * even after their ordinary single-use packages have been drained. Upload it through the hub's
113
+ * last-resort slot, never through the ordinary pool.
114
+ *
115
+ * **The caller must retain `privatePackage` after processing a Welcome** rather than deleting it
116
+ * as it would for an ordinary bundle: the same package can be handed to another inviter later.
117
+ * `@kumiai/mls` never owns private packages — `processWelcome` takes the bundle as a parameter —
118
+ * so nothing here can enforce that for you.
119
+ *
120
+ * **The caller must also re-upload before {@link LAST_RESORT_LIFETIME_DAYS} elapses.** The package
121
+ * carries an MLS lifetime, and an inviter validates it when building the Add — so an unrotated
122
+ * package stops working while the hub still reports the slot as full and keeps serving it. Both
123
+ * obligations fail the same way: silently, and precisely when the floor is needed.
124
+ */ export async function createLastResortKeyPackageBundle(identity, options) {
125
+ return buildBundle(identity, options, {
126
+ // Supplying `extensions` at all suppresses ts-mls's own default of
127
+ // `greaseExtensions(defaultGreaseConfig)`. `defaultGreaseConfig` is not exported, so its 0.1
128
+ // probability is restated here — dropping the spread would silently cost the stack its GREASE.
129
+ extensions: [
130
+ ...greaseExtensions({
131
+ probabilityPerGreaseValue: 0.1
132
+ }),
133
+ makeCustomExtension({
134
+ extensionType: LAST_RESORT_EXTENSION_TYPE,
135
+ extensionData: new Uint8Array(0)
136
+ })
137
+ ],
138
+ lifetime: lastResortLifetime()
139
+ });
140
+ }
package/lib/group.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createInvite, } from './group-commit.js';
1
+ export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createInvite, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, } from './group-commit.js';
2
2
  export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGroup, } from './group-create.js';
3
- export { createKeyPackageBundle, makeMLSCredential } from './group-credential.js';
3
+ export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, } from './group-credential.js';
4
4
  export { CommitRejectedError, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
5
5
  export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch, } from './group-info.js';
6
6
  export { type RemoveMemberResult, removeMember } from './group-membership.js';
package/lib/group.js CHANGED
@@ -1,6 +1,6 @@
1
- export { commitInvite, commitLedgerEntries, createInvite } from './group-commit.js';
1
+ export { commitInvite, commitLedgerEntries, createInvite, InviteRecipientMismatchError } from './group-commit.js';
2
2
  export { createGroup, restoreGroup } from './group-create.js';
3
- export { createKeyPackageBundle, makeMLSCredential } from './group-credential.js';
3
+ export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS } from './group-credential.js';
4
4
  export { CommitRejectedError, GroupHandle } from './group-handle.js';
5
5
  export { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch } from './group-info.js';
6
6
  export { removeMember } from './group-membership.js';
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Capabilities, GroupContextExtension, IncomingMessageCallback, Proposal, ProposalWithSender, } from 'ts-mls';
1
+ export type { Capabilities, GroupContextExtension, IncomingMessageCallback, KeyPackage, Proposal, ProposalWithSender, } from 'ts-mls';
2
2
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
3
3
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
4
4
  export { createDIDAuthenticationService } from './authentication.js';
@@ -8,10 +8,12 @@ export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCrypto
8
8
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
9
9
  export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
10
10
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
11
- export { type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type LedgerLogEntry, makeMLSCredential, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
11
+ export { type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
12
12
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
13
+ export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
13
14
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
14
15
  export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
15
16
  export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryRequest, RecoveryRequestError, type RecoveryRequestRejection, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, type SealedGroupInfoRejection, SealedLedgerError, type SealedLedgerRejection, type SealedReplyRejection, type SealGroupInfoParams, type SealLedgerParams, sealGroupInfo, sealLedger, type VerifiedRecoveryRequest, } from './recovery.js';
16
17
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
17
- export type { GroupOptions, GroupSyncScope, Invite, KeyPackageBundle } from './types.js';
18
+ export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
19
+ export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/index.js CHANGED
@@ -7,9 +7,11 @@ export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
7
7
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
8
8
  export { foldEnvelope } from './envelope-fold.js';
9
9
  export { foldLedger } from './fold.js';
10
- export { CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, exportGroupInfo, GroupHandle, inspectGroupInfo, joinGroupExternal, makeMLSCredential, processWelcome, processWelcomeOnce, readMessageEpoch, removeMember, restoreGroup } from './group.js';
10
+ export { CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readMessageEpoch, removeMember, restoreGroup } from './group.js';
11
11
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
12
+ export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
12
13
  export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
13
14
  export { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
14
15
  export { createRecoveryRequest, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, RecoveryRequestError, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, SealedLedgerError, sealGroupInfo, sealLedger } from './recovery.js';
15
16
  export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
17
+ export { welcomeKeyPackageRefs } from './welcome-refs.js';
@@ -0,0 +1,73 @@
1
+ import { type KeyPackage, type PrivateKeyPackage } from 'ts-mls';
2
+ import type { GroupOptions } from './types.js';
3
+ /**
4
+ * Serialize a key package to the string form the hub stores.
5
+ *
6
+ * Returns a `string` rather than the `Uint8Array` every other encoder in this package returns
7
+ * (`encodeGroupAnchor`, `encodeClientState`, `encodeLedgerHead`), and the deviation is the point.
8
+ * Those blobs are read only by the process that wrote them; this one is a wire format two peers
9
+ * must agree on before either has met the other. `@sozai/codec` exports both `toB64` and `toB64U`
10
+ * and they are not interchangeable, so handing bytes back and leaving the string step to each host
11
+ * is precisely how an uploader and a fetcher end up disagreeing about packages already sitting in
12
+ * a hub. One canonical form, decided here, removes the choice.
13
+ */
14
+ export declare function encodeKeyPackage(keyPackage: KeyPackage): string;
15
+ /**
16
+ * Parse a key package from its stored string form, or `null` if the string is not exactly one.
17
+ *
18
+ * **A successful decode proves well-formedness and nothing else.** No signature is verified, no
19
+ * lifetime is checked, no capability is inspected. ts-mls performs all of those at Add time, on
20
+ * the inviter, with the group context in hand — which a decoder does not have. Repeating them
21
+ * here would be redundant where it duplicated that gate and actively misleading where it did not,
22
+ * because a caller could reasonably read "it decoded" as "it is safe to add". It is not.
23
+ *
24
+ * Strict in three separate ways, each closing a path by which one package gains a second string
25
+ * form:
26
+ *
27
+ * 1. `fromB64` throws on a bad alphabet rather than returning a sentinel, so the throw is absorbed.
28
+ * 2. The re-encode comparison requires the input to be the canonical base64 of its own bytes.
29
+ * `fromB64` trims surrounding whitespace and tolerates some padding variation, and the hub
30
+ * stores and compares *strings* — so a byte-level guarantee alone never reaches the layer that
31
+ * needs it.
32
+ * 3. `keyPackageDecoder` is called directly rather than through ts-mls's `decode()`, which is
33
+ * `dec(t, 0)?.[0]` and discards the consumed length — silently accepting trailing garbage. The
34
+ * length is compared against the input instead.
35
+ *
36
+ * `keyPackageDecoder`'s own type says it returns `undefined` on failure, never throws — true for
37
+ * a buffer that is simply too short for a fixed-size field, but a variable-length field whose
38
+ * declared length overruns the buffer (truncated input, not merely short input) makes
39
+ * `varLenDataDecoder` throw `CodecError` instead. That throw is absorbed separately from
40
+ * `fromB64`'s, in its own `try`, so the two failure paths stay independent.
41
+ *
42
+ * One canonical representation per package is what any later attempt to dedup or identify a
43
+ * package by its stored form depends on.
44
+ */
45
+ export declare function decodeKeyPackage(encoded: string): KeyPackage | null;
46
+ /**
47
+ * Serialize a private key package for durable storage.
48
+ *
49
+ * A reusable last-resort package must outlive the process that generated it, making this a
50
+ * persistence format two versions of one host must agree on — hence one canonical form here, as
51
+ * with {@link encodeKeyPackage}.
52
+ *
53
+ * **The result is secret key material.** Never publish or log it; store it where the host stores
54
+ * private keys.
55
+ */
56
+ export declare function encodePrivateKeyPackage(privatePackage: PrivateKeyPackage): string;
57
+ /**
58
+ * Parse a stored private key package, or `null` if the string is not exactly one.
59
+ *
60
+ * Strict in the same three ways {@link decodeKeyPackage} is, and for the same reasons.
61
+ *
62
+ * A successful decode proves well-formedness and nothing else — in particular it does not prove the
63
+ * keys match any public package.
64
+ */
65
+ export declare function decodePrivateKeyPackage(encoded: string): PrivateKeyPackage | null;
66
+ /**
67
+ * The KeyPackageRef for a key package, base64 — the value a Welcome names to say which package its
68
+ * encrypted group secrets are for, and the stable identity of a stored package.
69
+ *
70
+ * A hash over the package's canonical encoding, so a codec round trip does not change it. Derived
71
+ * under the ciphersuite's hash, so `options` is threaded through rather than defaulted.
72
+ */
73
+ export declare function keyPackageRef(keyPackage: KeyPackage, options?: GroupOptions): Promise<string>;
@@ -0,0 +1,111 @@
1
+ import { fromB64, toB64 } from '@sozai/codec';
2
+ import { encode, keyPackageDecoder, keyPackageEncoder, makeKeyPackageRef, privateKeyPackageDecoder, privateKeyPackageEncoder } from 'ts-mls';
3
+ import { resolveMlsContext } from './group-context.js';
4
+ /**
5
+ * Serialize a key package to the string form the hub stores.
6
+ *
7
+ * Returns a `string` rather than the `Uint8Array` every other encoder in this package returns
8
+ * (`encodeGroupAnchor`, `encodeClientState`, `encodeLedgerHead`), and the deviation is the point.
9
+ * Those blobs are read only by the process that wrote them; this one is a wire format two peers
10
+ * must agree on before either has met the other. `@sozai/codec` exports both `toB64` and `toB64U`
11
+ * and they are not interchangeable, so handing bytes back and leaving the string step to each host
12
+ * is precisely how an uploader and a fetcher end up disagreeing about packages already sitting in
13
+ * a hub. One canonical form, decided here, removes the choice.
14
+ */ export function encodeKeyPackage(keyPackage) {
15
+ return toB64(encode(keyPackageEncoder, keyPackage));
16
+ }
17
+ /**
18
+ * Parse a key package from its stored string form, or `null` if the string is not exactly one.
19
+ *
20
+ * **A successful decode proves well-formedness and nothing else.** No signature is verified, no
21
+ * lifetime is checked, no capability is inspected. ts-mls performs all of those at Add time, on
22
+ * the inviter, with the group context in hand — which a decoder does not have. Repeating them
23
+ * here would be redundant where it duplicated that gate and actively misleading where it did not,
24
+ * because a caller could reasonably read "it decoded" as "it is safe to add". It is not.
25
+ *
26
+ * Strict in three separate ways, each closing a path by which one package gains a second string
27
+ * form:
28
+ *
29
+ * 1. `fromB64` throws on a bad alphabet rather than returning a sentinel, so the throw is absorbed.
30
+ * 2. The re-encode comparison requires the input to be the canonical base64 of its own bytes.
31
+ * `fromB64` trims surrounding whitespace and tolerates some padding variation, and the hub
32
+ * stores and compares *strings* — so a byte-level guarantee alone never reaches the layer that
33
+ * needs it.
34
+ * 3. `keyPackageDecoder` is called directly rather than through ts-mls's `decode()`, which is
35
+ * `dec(t, 0)?.[0]` and discards the consumed length — silently accepting trailing garbage. The
36
+ * length is compared against the input instead.
37
+ *
38
+ * `keyPackageDecoder`'s own type says it returns `undefined` on failure, never throws — true for
39
+ * a buffer that is simply too short for a fixed-size field, but a variable-length field whose
40
+ * declared length overruns the buffer (truncated input, not merely short input) makes
41
+ * `varLenDataDecoder` throw `CodecError` instead. That throw is absorbed separately from
42
+ * `fromB64`'s, in its own `try`, so the two failure paths stay independent.
43
+ *
44
+ * One canonical representation per package is what any later attempt to dedup or identify a
45
+ * package by its stored form depends on.
46
+ */ export function decodeKeyPackage(encoded) {
47
+ let bytes;
48
+ try {
49
+ bytes = fromB64(encoded);
50
+ } catch {
51
+ return null;
52
+ }
53
+ if (toB64(bytes) !== encoded) return null;
54
+ let decoded;
55
+ try {
56
+ decoded = keyPackageDecoder(bytes, 0);
57
+ } catch {
58
+ return null;
59
+ }
60
+ // The tuple's second element is the CONSUMED LENGTH (ts-mls's `mapDecoders` returns
61
+ // `cursor - offset`), so this is a whole-input check, not an offset comparison.
62
+ if (decoded == null || decoded[1] !== bytes.length) return null;
63
+ return decoded[0];
64
+ }
65
+ /**
66
+ * Serialize a private key package for durable storage.
67
+ *
68
+ * A reusable last-resort package must outlive the process that generated it, making this a
69
+ * persistence format two versions of one host must agree on — hence one canonical form here, as
70
+ * with {@link encodeKeyPackage}.
71
+ *
72
+ * **The result is secret key material.** Never publish or log it; store it where the host stores
73
+ * private keys.
74
+ */ export function encodePrivateKeyPackage(privatePackage) {
75
+ return toB64(encode(privateKeyPackageEncoder, privatePackage));
76
+ }
77
+ /**
78
+ * Parse a stored private key package, or `null` if the string is not exactly one.
79
+ *
80
+ * Strict in the same three ways {@link decodeKeyPackage} is, and for the same reasons.
81
+ *
82
+ * A successful decode proves well-formedness and nothing else — in particular it does not prove the
83
+ * keys match any public package.
84
+ */ export function decodePrivateKeyPackage(encoded) {
85
+ let bytes;
86
+ try {
87
+ bytes = fromB64(encoded);
88
+ } catch {
89
+ return null;
90
+ }
91
+ if (toB64(bytes) !== encoded) return null;
92
+ let decoded;
93
+ try {
94
+ decoded = privateKeyPackageDecoder(bytes, 0);
95
+ } catch {
96
+ return null;
97
+ }
98
+ // The tuple's second element is the CONSUMED LENGTH, so this is a whole-input check.
99
+ if (decoded == null || decoded[1] !== bytes.length) return null;
100
+ return decoded[0];
101
+ }
102
+ /**
103
+ * The KeyPackageRef for a key package, base64 — the value a Welcome names to say which package its
104
+ * encrypted group secrets are for, and the stable identity of a stored package.
105
+ *
106
+ * A hash over the package's canonical encoding, so a codec round trip does not change it. Derived
107
+ * under the ciphersuite's hash, so `options` is threaded through rather than defaulted.
108
+ */ export async function keyPackageRef(keyPackage, options) {
109
+ const { cipherSuite } = await resolveMlsContext(options);
110
+ return toB64(await makeKeyPackageRef(keyPackage, cipherSuite.hash));
111
+ }
package/lib/policy.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { defaultProposalTypes, isDefaultProposal } from 'ts-mls';
3
3
  import { LEDGER_HEAD_EXTENSION_TYPE, RESERVED_EXTENSION_TYPE } from './anchor.js';
4
+ import { didFromCredential } from './credential.js';
4
5
  function bytesEqual(a, b) {
5
6
  if (a.length !== b.length) {
6
7
  return false;
@@ -77,12 +78,44 @@ function bytesEqual(a, b) {
77
78
  /**
78
79
  * Apply one proposal's row for the given effective sender. Unknown/custom types fail closed.
79
80
  * `external_init` is judged at the commit level, never here — a standalone one rejects.
81
+ *
82
+ * An `add` is admin-gated AND bound to the roster: the added leaf's credential must name a DID
83
+ * the candidate roster holds a role for — was ever granted one, not necessarily by this commit.
84
+ * `roleReducer.apply` only ever sets a role, never clears it (see roster.ts), so this does not
85
+ * guarantee current membership matches the roster's intent, only that no leaf joins under a DID
86
+ * the roster never recognized.
80
87
  */ function evaluateProposal(proposal, effectiveSender, context) {
81
88
  if (!isDefaultProposal(proposal)) {
82
89
  return 'reject';
83
90
  }
84
91
  switch(proposal.proposalType){
85
92
  case defaultProposalTypes.add:
93
+ {
94
+ if (!isAdmin(context, effectiveSender)) {
95
+ return 'reject';
96
+ }
97
+ // Bind the leaf that joins to the roster this commit produces, mirroring the binding
98
+ // `commitInvite` enforces where the commit is authored. Without it only an honest inviter
99
+ // refuses to admit an identity the roster never granted a role to; a receiver applies the
100
+ // commit and Welcomes the wrong member with no way to see the disagreement.
101
+ //
102
+ // `candidateRoster`, not `baseRoster`: an honest invite's grant for the invitee rides the
103
+ // same commit as the Add, so it exists only after the fold.
104
+ //
105
+ // Membership, not provenance: the question is whether the added DID holds a role, never
106
+ // whether this commit granted it. A re-add — a second device, a rejoin after removal —
107
+ // enacts no entry and must keep working.
108
+ //
109
+ // A credential that names no DID (non-`basic`, or malformed) is rejected rather than
110
+ // trusted. `didFromCredential` is total, so nothing here can throw past this boundary.
111
+ const addedDID = didFromCredential(proposal.add.keyPackage.leafNode.credential);
112
+ if (addedDID === undefined) {
113
+ return 'reject';
114
+ }
115
+ return context.candidateRoster.roles.has(addedDID) ? 'accept' : 'reject';
116
+ }
117
+ // Split from `add` above only so they stop sharing an arm that reads `proposal.add`.
118
+ // Neither carries a leaf, so neither has anything to bind to the roster.
86
119
  case defaultProposalTypes.psk:
87
120
  case defaultProposalTypes.reinit:
88
121
  return isAdmin(context, effectiveSender) ? 'accept' : 'reject';
@@ -5,7 +5,7 @@ import type { MlsContext } from 'ts-mls';
5
5
  * ts-mls ships `decryptSenderData` but does not re-export it (its `exports` map exposes
6
6
  * only `.`), so this package reproduces the derivation from primitives the live
7
7
  * `CiphersuiteImpl` does expose. Frozen wire format — see the backlog note
8
- * `ts-mls-v2-stable-upgrade.md`: delete this module and delegate to ts-mls once stable
8
+ * `ts-mls-upstream.md`: delete this module and delegate to ts-mls once stable
9
9
  * re-exports its own.
10
10
  */
11
11
  /** The PrivateMessage fields sender-data decrypt reads, narrowed off a decoded frame. */
package/lib/types.d.ts CHANGED
@@ -49,13 +49,6 @@ export type GroupOptions = {
49
49
  /** Optional resolver for did:peer:4 short forms not in cache. */
50
50
  resolver?: DIDResolver;
51
51
  };
52
- export type GroupSyncScope = {
53
- groupID: string;
54
- models: Array<{
55
- modelID: string;
56
- filter?: Record<string, unknown>;
57
- }>;
58
- };
59
52
  export type Invite = {
60
53
  /** Group ID the invite is for */
61
54
  groupID: string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The KeyPackageRefs a Welcome names, base64 — one per set of encrypted group secrets it carries.
3
+ *
4
+ * Same encoding as {@link keyPackageRef}, so a holder of several retained bundles can pick the one
5
+ * this Welcome is for by comparison instead of trying each until one decrypts.
6
+ *
7
+ * Accepts framed `MLSMessage(Welcome)` bytes or a pre-decoded ts-mls Welcome, exactly as
8
+ * `processWelcome` does — the same value reaches both.
9
+ */
10
+ export declare function welcomeKeyPackageRefs(welcome: Uint8Array | unknown): Array<string>;
@@ -0,0 +1,25 @@
1
+ import { toB64 } from '@sozai/codec';
2
+ import { decode, mlsMessageDecoder, wireformats } from 'ts-mls';
3
+ /**
4
+ * The KeyPackageRefs a Welcome names, base64 — one per set of encrypted group secrets it carries.
5
+ *
6
+ * Same encoding as {@link keyPackageRef}, so a holder of several retained bundles can pick the one
7
+ * this Welcome is for by comparison instead of trying each until one decrypts.
8
+ *
9
+ * Accepts framed `MLSMessage(Welcome)` bytes or a pre-decoded ts-mls Welcome, exactly as
10
+ * `processWelcome` does — the same value reaches both.
11
+ */ export function welcomeKeyPackageRefs(welcome) {
12
+ let resolved = welcome;
13
+ if (welcome instanceof Uint8Array) {
14
+ const decoded = decode(mlsMessageDecoder, welcome);
15
+ if (decoded == null || decoded.wireformat !== wireformats.mls_welcome) {
16
+ throw new Error('welcomeKeyPackageRefs: expected a framed MLSMessage(Welcome)');
17
+ }
18
+ resolved = decoded.welcome;
19
+ }
20
+ const secrets = resolved?.secrets;
21
+ if (!Array.isArray(secrets)) {
22
+ throw new Error('welcomeKeyPackageRefs: not a Welcome');
23
+ }
24
+ return secrets.map((secret)=>toB64(secret.newMember));
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -28,10 +28,14 @@
28
28
  "@kokuin/token": "^0.3.0",
29
29
  "@noble/ciphers": "^2.1.1",
30
30
  "@noble/curves": "^2.0.1",
31
- "@noble/hashes": "^2.0.0",
31
+ "@noble/hashes": "^2.2.0",
32
+ "@sozai/codec": "^0.3.0",
32
33
  "@sozai/runtime": "^0.1.0",
33
34
  "ts-mls": "2.0.0-rc.13"
34
35
  },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
35
39
  "scripts": {
36
40
  "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
37
41
  "build:clean": "del lib",