@serfab/cadre-core 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +587 -173
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/sealed-party-key.d.ts +32 -0
  34. package/dist/sealed-party-key.js +162 -0
  35. package/dist/sealed-party-key.js.map +1 -0
  36. package/dist/seed-bootstrap.d.ts +10 -3
  37. package/dist/seed-bootstrap.js +12 -0
  38. package/dist/seed-bootstrap.js.map +1 -1
  39. package/dist/strand-addr-protocol.d.ts +56 -6
  40. package/dist/strand-addr-protocol.js +57 -5
  41. package/dist/strand-addr-protocol.js.map +1 -1
  42. package/dist/strand-commit-durability.d.ts +33 -2
  43. package/dist/strand-commit-durability.js +44 -4
  44. package/dist/strand-commit-durability.js.map +1 -1
  45. package/dist/strand-database.d.ts +35 -5
  46. package/dist/strand-database.js +34 -10
  47. package/dist/strand-database.js.map +1 -1
  48. package/dist/strand-instance-manager.d.ts +133 -9
  49. package/dist/strand-instance-manager.js +266 -42
  50. package/dist/strand-instance-manager.js.map +1 -1
  51. package/dist/strand-membership-reconciler.d.ts +250 -51
  52. package/dist/strand-membership-reconciler.js +410 -66
  53. package/dist/strand-membership-reconciler.js.map +1 -1
  54. package/dist/strand-membership-writer.d.ts +7 -0
  55. package/dist/strand-membership-writer.js +9 -0
  56. package/dist/strand-membership-writer.js.map +1 -1
  57. package/dist/strand-party-key-rotation.d.ts +177 -0
  58. package/dist/strand-party-key-rotation.js +340 -0
  59. package/dist/strand-party-key-rotation.js.map +1 -0
  60. package/dist/strand-party-machines.d.ts +111 -0
  61. package/dist/strand-party-machines.js +258 -0
  62. package/dist/strand-party-machines.js.map +1 -0
  63. package/dist/strand-party-peers.d.ts +101 -0
  64. package/dist/strand-party-peers.js +49 -0
  65. package/dist/strand-party-peers.js.map +1 -0
  66. package/dist/strand-peer-redial.d.ts +34 -7
  67. package/dist/strand-peer-redial.js +46 -13
  68. package/dist/strand-peer-redial.js.map +1 -1
  69. package/dist/strand-revocation-enforcer.d.ts +15 -1
  70. package/dist/strand-revocation-enforcer.js +16 -9
  71. package/dist/strand-revocation-enforcer.js.map +1 -1
  72. package/dist/strand-transport-key.js +3 -0
  73. package/dist/strand-transport-key.js.map +1 -1
  74. package/dist/strand-watcher.d.ts +7 -4
  75. package/dist/strand-watcher.js +12 -7
  76. package/dist/strand-watcher.js.map +1 -1
  77. package/dist/types.d.ts +160 -13
  78. package/dist/types.js.map +1 -1
  79. package/package.json +9 -8
  80. package/src/cadre-node.ts +12252 -11528
  81. package/src/control-authorization.ts +41 -1
  82. package/src/control-database.ts +6123 -5603
  83. package/src/control-schema.ts +71 -7
  84. package/src/ed25519-key.ts +12 -1
  85. package/src/index.ts +957 -924
  86. package/src/machine-removal.ts +80 -1
  87. package/src/membership-connection-gater.ts +13 -1
  88. package/src/owner-keys.ts +2 -1
  89. package/src/owner-signer.ts +92 -94
  90. package/src/peer-authorization.ts +27 -3
  91. package/src/sealed-party-key.ts +190 -0
  92. package/src/seed-bootstrap.ts +17 -3
  93. package/src/strand-addr-protocol.ts +67 -6
  94. package/src/strand-commit-durability.ts +54 -5
  95. package/src/strand-database.ts +47 -11
  96. package/src/strand-instance-manager.ts +330 -42
  97. package/src/strand-membership-reconciler.ts +1310 -942
  98. package/src/strand-membership-writer.ts +10 -0
  99. package/src/strand-party-key-rotation.ts +436 -0
  100. package/src/strand-party-machines.ts +293 -0
  101. package/src/strand-party-peers.ts +129 -0
  102. package/src/strand-peer-redial.ts +61 -14
  103. package/src/strand-revocation-enforcer.ts +27 -9
  104. package/src/strand-transport-key.ts +3 -0
  105. package/src/strand-watcher.ts +12 -7
  106. package/src/types.ts +3112 -2963
@@ -18,6 +18,8 @@ import type {
18
18
  CadrePeerRow,
19
19
  MachineRemovalPlan,
20
20
  MachineRemovalRefusal,
21
+ PendingPartyKeyRotation,
22
+ StrandKeyRotationPlan,
21
23
  } from './types.js';
22
24
 
23
25
  /**
@@ -92,6 +94,27 @@ export interface MachineRemovalPlanInput {
92
94
  canSign: boolean;
93
95
  invites: readonly CadreInviteStatus[];
94
96
  usages: readonly CadreInviteUsageRow[];
97
+ /** Every closed strand the party holds a membership key for, as this node runs it ({@link ClosedStrandState}). */
98
+ strands: readonly ClosedStrandState[];
99
+ }
100
+
101
+ /**
102
+ * One closed strand with a `StrandPartyKey` row, as `CadreNode.planMachineRemoval` reads it,
103
+ * for {@link planStrandKeyRotations}.
104
+ */
105
+ export interface ClosedStrandState {
106
+ strandId: string;
107
+ /**
108
+ * `live`: a tracked instance with a database; `hibernating`: a tracked instance with its
109
+ * runtime released, which a removal wakes; `none`: not tracked here (never launched, excluded
110
+ * by the strand filter), or tracked without a database (still syncing, mid-build).
111
+ */
112
+ runtime: 'live' | 'hibernating' | 'none';
113
+ /**
114
+ * Whether the party's current key holds a `Strand.Manager` row, read from the live database;
115
+ * `unknown` when there is none to read.
116
+ */
117
+ managerSeat: boolean | 'unknown';
95
118
  }
96
119
 
97
120
  /**
@@ -104,15 +127,71 @@ export interface MachineRemovalPlanInput {
104
127
  * or already redeemed by it and still redeemable (a multi-use invitation, or an open
105
128
  * invitation inside its lifetime). The schema's rule: keeping a device out is removing
106
129
  * its row and withdrawing the invitation.
130
+ *
131
+ * `strands` says where the party's key in each closed strand is replaced
132
+ * ({@link planStrandKeyRotations}); empty when no live row names the machine, since such a
133
+ * removal writes nothing.
107
134
  */
108
135
  export function planMachineRemoval(input: MachineRemovalPlanInput): MachineRemovalPlan {
136
+ const machine = input.machines.find((candidate) => candidate.peerId === input.peerId) ?? null;
109
137
  return {
110
- machine: input.machines.find((candidate) => candidate.peerId === input.peerId) ?? null,
138
+ machine,
111
139
  refusal: refusalFor(input),
112
140
  invitations: invitationsOpenTo(input),
141
+ strands: machine === null ? [] : planStrandKeyRotations(input.strands),
113
142
  };
114
143
  }
115
144
 
145
+ /**
146
+ * Where each closed strand's party key is replaced ({@link StrandKeyRotationPlan.rotation}):
147
+ * `here` when the strand runs here with a manager seat, or hibernates here (the removal wakes it
148
+ * and learns the seat then); `another-party` when it runs here without one, so the new key is
149
+ * seated by the strand's host re-inviting the party, or its manager admitting the key by hand
150
+ * (docs/strands.md → "Replacing the party's key"); `later` when it does not run here.
151
+ */
152
+ export function planStrandKeyRotations(strands: readonly ClosedStrandState[]): StrandKeyRotationPlan[] {
153
+ return strands.map((strand) => ({ strandId: strand.strandId, rotation: rotationSite(strand) }));
154
+ }
155
+
156
+ function rotationSite(strand: ClosedStrandState): StrandKeyRotationPlan['rotation'] {
157
+ switch (strand.runtime) {
158
+ case 'none':
159
+ return 'later';
160
+ case 'hibernating':
161
+ return 'here';
162
+ case 'live':
163
+ return strand.managerSeat === false ? 'another-party' : 'here';
164
+ }
165
+ }
166
+
167
+ /**
168
+ * One closed strand with a pending party key, as `CadreNode.listPendingPartyKeyRotations` reads
169
+ * it, for {@link pendingRotationWaitingOn}. Both reads are `unknown` when there is no live
170
+ * database to read them from.
171
+ */
172
+ export interface PendingRotationStrandState extends ClosedStrandState {
173
+ /** Whether the strand is closed with every manager gone for good (`isStrandSealed`). */
174
+ sealed: boolean | 'unknown';
175
+ /** Whether the pending key already holds a `Strand.Member` row (`isStrandMember`). */
176
+ pendingKeySeated: boolean | 'unknown';
177
+ }
178
+
179
+ /**
180
+ * Who can move one pending replacement forward ({@link PendingPartyKeyRotation.waitingOn}). A seated
181
+ * key comes first, sealed strand included: members can still leave a sealed strand, so the driver
182
+ * finishes there, and only admitting a key is what the seal rules out. What is unknown answers
183
+ * `owner-machine`, the one state that sends the app to nobody outside the party.
184
+ */
185
+ export function pendingRotationWaitingOn(strand: PendingRotationStrandState): PendingPartyKeyRotation['waitingOn'] {
186
+ if (strand.runtime !== 'live' || strand.pendingKeySeated !== false) {
187
+ return 'owner-machine';
188
+ }
189
+ if (strand.sealed === true) {
190
+ return 'sealed';
191
+ }
192
+ return strand.managerSeat === false ? 'another-party' : 'owner-machine';
193
+ }
194
+
116
195
  function refusalFor(input: MachineRemovalPlanInput): MachineRemovalRefusal | null {
117
196
  if (!input.canSign) {
118
197
  return 'not-an-owner';
@@ -384,6 +384,14 @@ export class UnauthorizedReservationBudget {
384
384
  * (connection admitted outright / reservation admitted, see module doc); the
385
385
  * base gater's verdict is still honored first.
386
386
  *
387
+ * Whatever the verdict, a connection whose transport closed during the decision
388
+ * is denied. libp2p builds the muxer right after this hook, and yamux subscribes
389
+ * to the stream only then, so it misses the `close` event, stays `open`, and is
390
+ * handed the frames the dialer sent before hanging up. Replying to one throws, its
391
+ * abort throws again on the GoAway, and that second throw is an uncaught exception
392
+ * from an event listener. Only a decision spanning a macrotask opens this window,
393
+ * so the strand gate, whose verdict is a synchronous snapshot read, does not.
394
+ *
387
395
  * An `'admit-provisionally'` verdict admits the connection and arms a
388
396
  * `provisionalDeadlineMs` timer against it. When the timer fires the policy is
389
397
  * asked again, and the underlying `MultiaddrConnection` is closed unless it now
@@ -447,7 +455,11 @@ export function createMembershipConnectionGater(
447
455
  verdict = await decideInbound(remotePeerId);
448
456
  } catch (error) {
449
457
  log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
450
- return false;
458
+ verdict = 'admit';
459
+ }
460
+ if (maConn.status !== 'open') {
461
+ log('%s hung up during its admission decision — refusing the closed connection', remotePeerId);
462
+ return true;
451
463
  }
452
464
  if (verdict === 'admit-provisionally') {
453
465
  provisional.arm(remotePeerId, maConn);
package/src/owner-keys.ts CHANGED
@@ -60,7 +60,7 @@ const OWNER_KEY_REMOVAL_REFUSAL_REASON: Record<OwnerKeyRemovalRefusal, string> =
60
60
  'unknown': 'it is not a live owner key here',
61
61
  'last-owner': 'it is the only live owner key',
62
62
  'self': 'it is the owner key of this node, and an owner key cannot sign its own removal; ask another owner key',
63
- 'alone': 'this node has no connection to the rest of the cadre, and an owner key re-vouched now would reach no other machine; try again once connected',
63
+ 'alone': 'this node has no connection to the rest of the cadre, and a device or owner key re-vouched now might not reach the other machines; try again once connected',
64
64
  };
65
65
 
66
66
  /** An owner key as an approval prompt names it: `"label" (key)`, or the key alone when it has no label. */
@@ -169,6 +169,7 @@ export function revouchWithinPlan(plan: OwnerKeyRemovalPlan, revouch: RemoveOwne
169
169
  const peers = [...new Set(revouch?.peers ?? [])];
170
170
  const strayOwners = owners.filter((key) => !plan.dependents.owners.includes(key));
171
171
  const strayPeers = peers.filter((peerId) => !plan.dependents.peers.includes(peerId));
172
+ // NOTE: a row that moved off the key between the app's plan and this check (another owner's re-vouch, or the first-growth sweep re-signing a row with no `Sig` once the node reconnects) throws this plain error, and the apps' next Remove re-reads the plan. If users report the wording, give it a refusal code.
172
173
  if (strayOwners.length > 0 || strayPeers.length > 0) {
173
174
  throw new Error(
174
175
  `removeOwner: re-vouch names rows the removed owner key did not vouch: ${[...strayOwners, ...strayPeers].join(', ')}`,
@@ -1,94 +1,92 @@
1
- /**
2
- * The owner signer: the one interface a node's owner signatures go through
3
- * (`docs/architecture.md` → Owner Keys → The owner signer).
4
- *
5
- * cadre-core needs owner signatures, never an owner private key, so a backend that keeps the
6
- * key where the node cannot read it (a hardware key, a vault behind biometrics) fits the same
7
- * seam as {@link softwareOwnerSigner}.
8
- *
9
- * Imports only `@optimystic/quereus-plugin-crypto` and `uint8arrays`, so it loads on React
10
- * Native and in the browser.
11
- */
12
- import { toString as uint8ArrayToString } from 'uint8arrays';
13
- import { sign } from '@optimystic/quereus-plugin-crypto';
14
- import { ed25519PublicKeyFromPrivate, requireEd25519PrivateKeyB64 } from './ed25519-key.js';
15
-
16
- /** What a backend that asks the user shows them. */
17
- export interface OwnerSigningRequest {
18
- /** The cadre the signatures are for. Every owner digest already binds it (`party_id()`); a prompting backend shows it. */
19
- partyId: string;
20
- /** What the user is approving, in plain words ("Remove the machine 12D3…", "Add owner key ‹label›"). */
21
- action: string;
22
- }
23
-
24
- /** Signs one message (the raw bytes of an owner digest, e.g. `buildAuthorizationMessage` output); resolves to a base64url Ed25519 signature. */
25
- export type OwnerSign = (message: Uint8Array) => Promise<string>;
26
-
27
- /**
28
- * An owner key the node can ask for signatures.
29
- *
30
- * One action, one {@link approve} call, however many rows it signs: the control schema verifies
31
- * one signature per row, and one owner action writes several (a removal signs the delete and its
32
- * `Revocation` tombstone; a machine removal signs many). A hardware or biometric backend prompts
33
- * once per call, as PIV touch caching and the platform vaults' authentication-validity windows
34
- * allow. Handing the signer every digest up front was declined: each writer reads the stamps it
35
- * signs inside its write lock, so precomputing them would duplicate each writer's digest
36
- * construction outside it.
37
- */
38
- export interface OwnerSigner {
39
- /** base64url Ed25519 public key — the `OwnerKey.Key` this signer signs for. */
40
- readonly publicKey: string;
41
- /**
42
- * Run one user-approved action. A backend that prompts does so at most once per call and may
43
- * keep the user's presence until `body` settles. Rejects with {@link OwnerSigningDeclinedError}
44
- * when the user declines, and with whatever `body` rejects with otherwise.
45
- */
46
- approve<T>(request: OwnerSigningRequest, body: (sign: OwnerSign) => Promise<T>): Promise<T>;
47
- }
48
-
49
- /**
50
- * Run `body` inside the caller's open approval when it passes `sign`, else inside one new
51
- * approval of `signer` for `request`. An owner write that is sometimes a whole action and
52
- * sometimes one step of a larger one takes an optional `sign` and goes through this, so the
53
- * larger action still asks once.
54
- */
55
- export async function withinOwnerApproval<T>(
56
- signer: OwnerSigner,
57
- request: OwnerSigningRequest,
58
- sign: OwnerSign | undefined,
59
- body: (sign: OwnerSign) => Promise<T>
60
- ): Promise<T> {
61
- return sign ? await body(sign) : await signer.approve(request, body);
62
- }
63
-
64
- /** Thrown by a prompting backend when the user declines or the prompt times out. */
65
- export class OwnerSigningDeclinedError extends Error {
66
- readonly request: OwnerSigningRequest;
67
-
68
- constructor(request: OwnerSigningRequest, options?: { cause?: unknown }) {
69
- super(`Owner approval was declined or timed out: ${request.action}`, options);
70
- this.name = 'OwnerSigningDeclinedError';
71
- this.request = request;
72
- }
73
- }
74
-
75
- /**
76
- * An {@link OwnerSigner} over a private key held in memory: never prompts, signs whatever its
77
- * `approve` body asks. Its signed input is the digest bytes, base64url-encoded, so its signatures
78
- * are byte-for-byte those of any signer that signs the raw bytes with the same key (Ed25519 is
79
- * deterministic).
80
- *
81
- * @param privateKeyB64 - The owner key's 32-byte Ed25519 seed, base64url.
82
- * @throws If `privateKeyB64` is not a 32-byte seed in base64url.
83
- */
84
- export function softwareOwnerSigner(privateKeyB64: string): OwnerSigner {
85
- const privateKey = requireEd25519PrivateKeyB64(privateKeyB64, 'owner private key');
86
- const signMessage: OwnerSign = async (message) =>
87
- sign(uint8ArrayToString(message, 'base64url'), privateKey, 'ed25519', 'base64url', 'base64url', 'base64url') as string;
88
- return {
89
- publicKey: ed25519PublicKeyFromPrivate(privateKey),
90
- async approve<T>(_request: OwnerSigningRequest, body: (sign: OwnerSign) => Promise<T>): Promise<T> {
91
- return await body(signMessage);
92
- },
93
- };
94
- }
1
+ /**
2
+ * The owner signer: the one interface a node's owner signatures go through
3
+ * (`docs/architecture.md` → Owner Keys → The owner signer).
4
+ *
5
+ * cadre-core needs owner signatures, never an owner private key, so a backend that keeps the
6
+ * key where the node cannot read it (a hardware key, a vault behind biometrics) fits the same
7
+ * seam as {@link softwareOwnerSigner}.
8
+ *
9
+ * Imports only `@optimystic/quereus-plugin-crypto` and `uint8arrays`, so it loads on React
10
+ * Native and in the browser.
11
+ */
12
+ import { ed25519MessageSigner, ed25519PublicKeyFromPrivate, requireEd25519PrivateKeyB64 } from './ed25519-key.js';
13
+
14
+ /** What a backend that asks the user shows them. */
15
+ export interface OwnerSigningRequest {
16
+ /** The cadre the signatures are for. Every owner digest already binds it (`party_id()`); a prompting backend shows it. */
17
+ partyId: string;
18
+ /** What the user is approving, in plain words ("Remove the machine 12D3…", "Add owner key ‹label›"). */
19
+ action: string;
20
+ }
21
+
22
+ /** Signs one message (the raw bytes of an owner digest, e.g. `buildAuthorizationMessage` output); resolves to a base64url Ed25519 signature. */
23
+ export type OwnerSign = (message: Uint8Array) => Promise<string>;
24
+
25
+ /**
26
+ * An owner key the node can ask for signatures.
27
+ *
28
+ * One action, one {@link approve} call, however many rows it signs: the control schema verifies
29
+ * one signature per row, and one owner action writes several (a removal signs the delete and its
30
+ * `Revocation` tombstone; a machine removal signs many). A hardware or biometric backend prompts
31
+ * once per call, as PIV touch caching and the platform vaults' authentication-validity windows
32
+ * allow. Handing the signer every digest up front was declined: each writer reads the stamps it
33
+ * signs inside its write lock, so precomputing them would duplicate each writer's digest
34
+ * construction outside it.
35
+ */
36
+ export interface OwnerSigner {
37
+ /** base64url Ed25519 public key — the `OwnerKey.Key` this signer signs for. */
38
+ readonly publicKey: string;
39
+ /**
40
+ * Run one user-approved action. A backend that prompts does so at most once per call and may
41
+ * keep the user's presence until `body` settles. Rejects with {@link OwnerSigningDeclinedError}
42
+ * when the user declines, and with whatever `body` rejects with otherwise.
43
+ */
44
+ approve<T>(request: OwnerSigningRequest, body: (sign: OwnerSign) => Promise<T>): Promise<T>;
45
+ }
46
+
47
+ /**
48
+ * Run `body` inside the caller's open approval when it passes `sign`, else inside one new
49
+ * approval of `signer` for `request`. An owner write that is sometimes a whole action and
50
+ * sometimes one step of a larger one takes an optional `sign` and goes through this, so the
51
+ * larger action still asks once.
52
+ */
53
+ export async function withinOwnerApproval<T>(
54
+ signer: OwnerSigner,
55
+ request: OwnerSigningRequest,
56
+ sign: OwnerSign | undefined,
57
+ body: (sign: OwnerSign) => Promise<T>
58
+ ): Promise<T> {
59
+ return sign ? await body(sign) : await signer.approve(request, body);
60
+ }
61
+
62
+ /** Thrown by a prompting backend when the user declines or the prompt times out. */
63
+ export class OwnerSigningDeclinedError extends Error {
64
+ readonly request: OwnerSigningRequest;
65
+
66
+ constructor(request: OwnerSigningRequest, options?: { cause?: unknown }) {
67
+ super(`Owner approval was declined or timed out: ${request.action}`, options);
68
+ this.name = 'OwnerSigningDeclinedError';
69
+ this.request = request;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * An {@link OwnerSigner} over a private key held in memory: never prompts, signs whatever its
75
+ * `approve` body asks. Its signed input is the digest bytes, base64url-encoded, so its signatures
76
+ * are byte-for-byte those of any signer that signs the raw bytes with the same key (Ed25519 is
77
+ * deterministic).
78
+ *
79
+ * @param privateKeyB64 - The owner key's 32-byte Ed25519 seed, base64url.
80
+ * @throws If `privateKeyB64` is not a 32-byte seed in base64url.
81
+ */
82
+ export function softwareOwnerSigner(privateKeyB64: string): OwnerSigner {
83
+ const privateKey = requireEd25519PrivateKeyB64(privateKeyB64, 'owner private key');
84
+ const signBytes = ed25519MessageSigner(privateKey);
85
+ const signMessage: OwnerSign = async (message) => signBytes(message);
86
+ return {
87
+ publicKey: ed25519PublicKeyFromPrivate(privateKey),
88
+ async approve<T>(_request: OwnerSigningRequest, body: (sign: OwnerSign) => Promise<T>): Promise<T> {
89
+ return await body(signMessage);
90
+ },
91
+ };
92
+ }
@@ -1,9 +1,9 @@
1
1
  import debug from 'debug';
2
2
  import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
- import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields } from './control-authorization.js';
4
- import type { BoundControlDomain, CadreInviteSignedFields, ControlAction, OwnerGrantSignedFields, RevocableTable, UnboundControlDomain } from './control-authorization.js';
3
+ import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields, strandPeerRowFields } from './control-authorization.js';
4
+ import type { BoundControlDomain, CadreInviteSignedFields, ControlAction, OwnerGrantSignedFields, RevocableTable, StrandPeerSignedFields, UnboundControlDomain } from './control-authorization.js';
5
5
  import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
6
- import type { CadreInviteRow, CadreInviteUsageRow, CadrePeerVoucherFields, OwnerGrantRow, OwnerGrantUsageRow, OwnerKeyRow, RevocationRow } from './types.js';
6
+ import type { CadreInviteRow, CadreInviteUsageRow, CadrePeerVoucherFields, OwnerGrantRow, OwnerGrantUsageRow, OwnerKeyRow, RevocationRow, StrandPeerRow } from './types.js';
7
7
 
8
8
  const log = debug('sereus:cadre:peer-authorization');
9
9
 
@@ -444,6 +444,30 @@ export function verifyInvitationAdmission(
444
444
  }
445
445
  }
446
446
 
447
+ /**
448
+ * Canonical digest a machine signs to state its own peer id in one strand, with its own
449
+ * identity key rather than an owner key. SQL mirror: `StrandPeer.Authorized`.
450
+ */
451
+ export function strandPeerAddDigest(partyId: string, row: StrandPeerSignedFields): string {
452
+ return taggedDigest('CadreControl.StrandPeer', 'add', partyId, strandPeerRowFields(row));
453
+ }
454
+
455
+ /**
456
+ * Was a `StrandPeer` row signed by the machine it names, in `partyId`? Verified against the key
457
+ * derived from `peerId`, not against `CadrePeer.PublicKey` as the schema's check does, because
458
+ * that column is written by whoever seated the row and a replicated row never meets the check.
459
+ * Whether `peerId` is a machine of this party is the caller's question. Never throws.
460
+ */
461
+ export function verifyStrandPeerRow(partyId: string, row: StrandPeerRow): boolean {
462
+ try {
463
+ const publicKey = ed25519PublicKeyB64FromPeerId(row.peerId);
464
+ return publicKey !== null && verifyB64(strandPeerAddDigest(partyId, row), row.sig, publicKey);
465
+ } catch (error) {
466
+ log('verifyStrandPeerRow failed: %o', error);
467
+ return false;
468
+ }
469
+ }
470
+
447
471
  /**
448
472
  * Canonical digest an owner signs to seat an `OwnerGrant` row — the read-side mirror of
449
473
  * `ownerGrantAddMessage` in control-database.ts, base64url instead of raw bytes. The whole
@@ -0,0 +1,190 @@
1
+ /**
2
+ * The pending party key, sealed to the machines that remain: how `PendingStrandPartyKey.SealedKey`
3
+ * carries the key a party moves to after a machine removal (`docs/architecture.md` → "Removing a
4
+ * machine"). The row is written in the same control transaction as the removed machine's
5
+ * tombstone, so it reaches that machine; what it carries must open only for the others.
6
+ *
7
+ * One envelope per row, JSON `{ v: 1, eph, to: { <peerId>: { nonce, sealed } } }`:
8
+ *
9
+ * - `eph` is one ephemeral X25519 public key per envelope.
10
+ * - Per recipient, the shared secret is X25519 between the ephemeral key and the recipient's
11
+ * identity key converted to Montgomery form (`ed25519.utils.toMontgomery`); a recipient opens
12
+ * with its own seed converted the same way (`toMontgomerySecret`).
13
+ * - The wrapping key is HKDF-SHA256 over that secret, salted with the ephemeral public key and
14
+ * with the strand id in `info`, so an envelope copied onto another strand's row does not open.
15
+ * - The key is sealed with XChaCha20-Poly1305 under a random nonce.
16
+ *
17
+ * Recipients are keyed by control peer id, and the key sealed to is the one that peer id
18
+ * carries (`ed25519PublicKeyB64FromPeerId`), never a stored column. Pure functions, so a test
19
+ * drives them without a node; `@noble/curves`, `@noble/hashes` and `@noble/ciphers` are pure JS,
20
+ * so this loads on React Native and in the browser. No error carries key material.
21
+ *
22
+ * Cost: one X25519 operation for the ephemeral key plus one per recipient, per strand sealed, and
23
+ * one per strand opened (`packages/cadre-rn/src/native-ed25519.ts` has the device numbers).
24
+ */
25
+ import { ed25519, x25519 } from '@noble/curves/ed25519.js';
26
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
27
+ import { hkdf } from '@noble/hashes/hkdf.js';
28
+ import { sha256 } from '@noble/hashes/sha2.js';
29
+ import { randomBytes } from '@noble/hashes/utils.js';
30
+ import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
31
+ import { canonicalJson } from './canonical-json.js';
32
+
33
+ /** One machine a pending key is sealed to. */
34
+ export interface PartyKeyRecipient {
35
+ /** The machine's control peer id: its entry's key in the envelope. */
36
+ peerId: string;
37
+ /** The ed25519 identity key behind that peer id (base64url), as `ed25519PublicKeyB64FromPeerId` derives it. */
38
+ publicKeyB64: string;
39
+ }
40
+
41
+ /** The machine opening an envelope: its control peer id and the 32-byte ed25519 seed behind it (`ed25519KeyPairFromLibp2p`). */
42
+ export interface PartyKeyOpener {
43
+ peerId: string;
44
+ privateKeyB64: string;
45
+ }
46
+
47
+ const ENVELOPE_VERSION = 1;
48
+ /** Binds the derived key to its use and to one strand; the strand id follows. */
49
+ const HKDF_INFO_PREFIX = 'sereus:pending-party-key:v1:';
50
+ const KEY_BYTES = 32;
51
+ const X25519_PUBLIC_KEY_BYTES = 32;
52
+ const ED25519_KEY_BYTES = 32;
53
+ const XCHACHA_NONCE_BYTES = 24;
54
+ const POLY1305_TAG_BYTES = 16;
55
+ /** A sealed `StrandPartyKey.PrivateKey` is under 100 bytes; this bounds what a hostile row makes a reader decrypt. */
56
+ const MAX_SEALED_BYTES = 1024;
57
+
58
+ interface SealedEntry {
59
+ nonce: Uint8Array;
60
+ sealed: Uint8Array;
61
+ }
62
+
63
+ interface Envelope {
64
+ ephemeralPublic: Uint8Array;
65
+ to: Map<string, SealedEntry>;
66
+ }
67
+
68
+ /**
69
+ * Seal `privateKey` (a `StrandPartyKey.PrivateKey`) for `strandId` to every recipient. A
70
+ * recipient named twice gets one entry. With no recipients the envelope opens for nobody.
71
+ *
72
+ * @throws When a recipient's public key is not a 32-byte base64url ed25519 key.
73
+ */
74
+ export function sealPartyKey(privateKey: string, strandId: string, recipients: readonly PartyKeyRecipient[]): string {
75
+ const ephemeralSecret = x25519.utils.randomSecretKey();
76
+ const ephemeralPublic = x25519.getPublicKey(ephemeralSecret);
77
+ const plain = new TextEncoder().encode(privateKey);
78
+ const to: Record<string, { nonce: string; sealed: string }> = {};
79
+ try {
80
+ for (const recipient of recipients) {
81
+ const recipientPublic = ed25519.utils.toMontgomery(requireBytes(recipient.publicKeyB64, 'recipient public key', ED25519_KEY_BYTES, ED25519_KEY_BYTES));
82
+ const nonce = randomBytes(XCHACHA_NONCE_BYTES);
83
+ const sealed = withWrappingKey(x25519.getSharedSecret(ephemeralSecret, recipientPublic), ephemeralPublic, strandId,
84
+ (key) => xchacha20poly1305(key, nonce).encrypt(plain));
85
+ to[recipient.peerId] = { nonce: toBase64url(nonce), sealed: toBase64url(sealed) };
86
+ }
87
+ } finally {
88
+ ephemeralSecret.fill(0);
89
+ plain.fill(0);
90
+ }
91
+ return canonicalJson({ eph: toBase64url(ephemeralPublic), to, v: ENVELOPE_VERSION });
92
+ }
93
+
94
+ /**
95
+ * The plain key, or null when `self` is not a recipient.
96
+ *
97
+ * @throws When the envelope is malformed, or `self`'s entry does not open: the row was altered,
98
+ * or the envelope was sealed for another strand.
99
+ */
100
+ export function openPartyKey(sealed: string, strandId: string, self: PartyKeyOpener): string | null {
101
+ const envelope = parseEnvelope(sealed);
102
+ const entry = envelope.to.get(self.peerId);
103
+ if (entry === undefined) {
104
+ return null;
105
+ }
106
+ const secret = ed25519.utils.toMontgomerySecret(requireBytes(self.privateKeyB64, 'identity key', ED25519_KEY_BYTES, ED25519_KEY_BYTES));
107
+ let plain: Uint8Array;
108
+ try {
109
+ plain = withWrappingKey(x25519.getSharedSecret(secret, envelope.ephemeralPublic), envelope.ephemeralPublic, strandId,
110
+ (key) => xchacha20poly1305(key, entry.nonce).decrypt(entry.sealed));
111
+ } catch (error) {
112
+ throw new Error(`The pending party key of strand ${strandId} does not open for this machine: the row was altered, or it was sealed for another strand`, { cause: error });
113
+ } finally {
114
+ secret.fill(0);
115
+ }
116
+ return new TextDecoder().decode(plain);
117
+ }
118
+
119
+ /**
120
+ * The control peer ids the envelope is sealed to.
121
+ *
122
+ * @throws When the envelope is malformed.
123
+ */
124
+ export function partyKeyRecipients(sealed: string): string[] {
125
+ return [...parseEnvelope(sealed).to.keys()];
126
+ }
127
+
128
+ /** Derive the wrapping key for one recipient, run `use` over it, and zero both secrets after. */
129
+ function withWrappingKey(sharedSecret: Uint8Array, ephemeralPublic: Uint8Array, strandId: string, use: (key: Uint8Array) => Uint8Array): Uint8Array {
130
+ const key = hkdf(sha256, sharedSecret, ephemeralPublic, new TextEncoder().encode(`${HKDF_INFO_PREFIX}${strandId}`), KEY_BYTES);
131
+ try {
132
+ return use(key);
133
+ } finally {
134
+ sharedSecret.fill(0);
135
+ key.fill(0);
136
+ }
137
+ }
138
+
139
+ function parseEnvelope(sealed: string): Envelope {
140
+ let parsed: unknown;
141
+ try {
142
+ parsed = JSON.parse(sealed);
143
+ } catch {
144
+ // No cause: JSON.parse's message can quote the input.
145
+ throw new Error('A sealed party key must be JSON');
146
+ }
147
+ if (!isRecord(parsed)) {
148
+ throw new Error('A sealed party key must be a JSON object');
149
+ }
150
+ if (parsed.v !== ENVELOPE_VERSION) {
151
+ throw new Error(`A sealed party key must be version ${ENVELOPE_VERSION} (this one says ${JSON.stringify(parsed.v)})`);
152
+ }
153
+ if (!isRecord(parsed.to)) {
154
+ throw new Error('A sealed party key must name its recipients');
155
+ }
156
+ const to = new Map<string, SealedEntry>();
157
+ for (const [peerId, entry] of Object.entries(parsed.to)) {
158
+ if (!isRecord(entry)) {
159
+ throw new Error('Each recipient entry of a sealed party key must be an object');
160
+ }
161
+ to.set(peerId, {
162
+ nonce: requireBytes(entry.nonce, 'nonce', XCHACHA_NONCE_BYTES, XCHACHA_NONCE_BYTES),
163
+ sealed: requireBytes(entry.sealed, 'sealed key', POLY1305_TAG_BYTES, MAX_SEALED_BYTES),
164
+ });
165
+ }
166
+ return { ephemeralPublic: requireBytes(parsed.eph, 'ephemeral key', X25519_PUBLIC_KEY_BYTES, X25519_PUBLIC_KEY_BYTES), to };
167
+ }
168
+
169
+ function isRecord(value: unknown): value is Record<string, unknown> {
170
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
171
+ }
172
+
173
+ function requireBytes(value: unknown, field: string, minBytes: number, maxBytes: number): Uint8Array {
174
+ let bytes: Uint8Array | undefined;
175
+ if (typeof value === 'string') {
176
+ try {
177
+ bytes = uint8ArrayFromString(value, 'base64url');
178
+ } catch (error) {
179
+ throw new Error(`A sealed party key's ${field} must be base64url`, { cause: error });
180
+ }
181
+ }
182
+ if (bytes === undefined || bytes.length < minBytes || bytes.length > maxBytes) {
183
+ throw new Error(`A sealed party key's ${field} must be ${minBytes === maxBytes ? minBytes : `${minBytes} to ${maxBytes}`} bytes of base64url`);
184
+ }
185
+ return bytes;
186
+ }
187
+
188
+ function toBase64url(bytes: Uint8Array): string {
189
+ return uint8ArrayToString(bytes, 'base64url');
190
+ }
@@ -32,9 +32,9 @@ import type {
32
32
  PeerAddressRecord,
33
33
  DeviceTokenRecord,
34
34
  RevocationRow,
35
- MachineRemovalResult
35
+ MachineRemovalWrites
36
36
  } from './types.js';
37
- import type { CadrePeerRetouchMode, CadrePeerRetouchOutcome, ControlDatabase } from './control-database.js';
37
+ import type { CadrePeerRetouchMode, CadrePeerRetouchOutcome, ControlDatabase, StrandPartyKeySwap } from './control-database.js';
38
38
  import { generateStampId, ownerKeyLabel } from './control-database.js';
39
39
  import { canonicalJson } from './canonical-json.js';
40
40
  import { deviceTokenAddDigest } from './peer-authorization.js';
@@ -704,13 +704,27 @@ export class SeedBootstrapService {
704
704
  * transaction ({@link ControlDatabase.removeMachine}). What stays here is the owner-signer
705
705
  * precondition, checked before any read (see {@link removePeer}).
706
706
  */
707
- async removeMachine(target: Parameters<ControlDatabase['removeMachine']>[0], sign?: OwnerSign): Promise<MachineRemovalResult> {
707
+ async removeMachine(target: Parameters<ControlDatabase['removeMachine']>[0], sign?: OwnerSign): Promise<MachineRemovalWrites> {
708
708
  const ownerKey = this.requireOwnerSigner().publicKey;
709
709
  const controlDatabase = this.requireControlDatabase();
710
710
  return await this.withOwnerSign(`Remove the machine ${target.peerId} from the cadre`, sign, (approved) =>
711
711
  controlDatabase.removeMachine(target, ownerKey, approved));
712
712
  }
713
713
 
714
+ /**
715
+ * Move this party's membership key in each named strand from its old key to its new one in
716
+ * the control record, one transaction and one approval across all of them
717
+ * ({@link ControlDatabase.swapStrandPartyKeys}): the last step of a party key rotation
718
+ * (`strand-party-key-rotation.ts`). What stays here is the owner-signer precondition.
719
+ */
720
+ async swapStrandPartyKeys(entries: readonly StrandPartyKeySwap[], sign?: OwnerSign): Promise<string[]> {
721
+ const ownerKey = this.requireOwnerSigner().publicKey;
722
+ const controlDatabase = this.requireControlDatabase();
723
+ const where = entries.length === 1 ? `the strand ${entries[0]!.strandId}` : `${entries.length} strands`;
724
+ return await this.withOwnerSign(`Replace this cadre's membership key in ${where}`, sign, (approved) =>
725
+ controlDatabase.swapStrandPartyKeys(entries, ownerKey, approved));
726
+ }
727
+
714
728
  /**
715
729
  * Owner "re-touch" of an existing `CadrePeer` membership row, in one of two modes
716
730
  * ({@link CadrePeerRetouchMode}): `'rebroadcast'` bumps `UpdatedAt` and re-vouches the row so