@serfab/cadre-core 0.9.0 → 0.10.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 (162) hide show
  1. package/README.md +4 -2
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +918 -53
  9. package/dist/cadre-node.js +1843 -190
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-database.d.ts +990 -50
  15. package/dist/control-database.js +1459 -108
  16. package/dist/control-database.js.map +1 -1
  17. package/dist/control-formation-recorder.d.ts +89 -10
  18. package/dist/control-formation-recorder.js +129 -14
  19. package/dist/control-formation-recorder.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +774 -210
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +38 -4
  24. package/dist/control-stream.js +70 -4
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +151 -0
  27. package/dist/control-write-retry.js +411 -0
  28. package/dist/control-write-retry.js.map +1 -0
  29. package/dist/delegate-admission.d.ts +134 -0
  30. package/dist/delegate-admission.js +244 -0
  31. package/dist/delegate-admission.js.map +1 -0
  32. package/dist/device-token.d.ts +11 -11
  33. package/dist/device-token.js +14 -13
  34. package/dist/device-token.js.map +1 -1
  35. package/dist/ed25519-key.d.ts +26 -0
  36. package/dist/ed25519-key.js +56 -1
  37. package/dist/ed25519-key.js.map +1 -1
  38. package/dist/file-durable-slot.d.ts +20 -0
  39. package/dist/file-durable-slot.js +53 -0
  40. package/dist/file-durable-slot.js.map +1 -0
  41. package/dist/formation-approval.d.ts +157 -0
  42. package/dist/formation-approval.js +375 -0
  43. package/dist/formation-approval.js.map +1 -0
  44. package/dist/fs-atomic.d.ts +38 -0
  45. package/dist/fs-atomic.js +97 -0
  46. package/dist/fs-atomic.js.map +1 -0
  47. package/dist/identity-key.d.ts +49 -0
  48. package/dist/identity-key.js +81 -0
  49. package/dist/identity-key.js.map +1 -0
  50. package/dist/index.d.ts +16 -6
  51. package/dist/index.js +39 -5
  52. package/dist/index.js.map +1 -1
  53. package/dist/key-store-file.d.ts +2 -24
  54. package/dist/key-store-file.js +10 -77
  55. package/dist/key-store-file.js.map +1 -1
  56. package/dist/membership-connection-gater.d.ts +146 -0
  57. package/dist/membership-connection-gater.js +180 -0
  58. package/dist/membership-connection-gater.js.map +1 -0
  59. package/dist/node-local-snapshot.d.ts +109 -0
  60. package/dist/node-local-snapshot.js +182 -0
  61. package/dist/node-local-snapshot.js.map +1 -0
  62. package/dist/peer-authorization.d.ts +135 -18
  63. package/dist/peer-authorization.js +152 -21
  64. package/dist/peer-authorization.js.map +1 -1
  65. package/dist/peer-record.d.ts +21 -8
  66. package/dist/peer-record.js +26 -10
  67. package/dist/peer-record.js.map +1 -1
  68. package/dist/relay-addrs.d.ts +45 -0
  69. package/dist/relay-addrs.js +103 -0
  70. package/dist/relay-addrs.js.map +1 -0
  71. package/dist/relay-reservation.d.ts +266 -0
  72. package/dist/relay-reservation.js +613 -0
  73. package/dist/relay-reservation.js.map +1 -0
  74. package/dist/seed-bootstrap.d.ts +221 -56
  75. package/dist/seed-bootstrap.js +328 -188
  76. package/dist/seed-bootstrap.js.map +1 -1
  77. package/dist/seed-trust-policy.d.ts +47 -21
  78. package/dist/seed-trust-policy.js +24 -15
  79. package/dist/seed-trust-policy.js.map +1 -1
  80. package/dist/strand-addr-protocol.d.ts +42 -13
  81. package/dist/strand-addr-protocol.js +58 -52
  82. package/dist/strand-addr-protocol.js.map +1 -1
  83. package/dist/strand-backfill.d.ts +109 -0
  84. package/dist/strand-backfill.js +279 -0
  85. package/dist/strand-backfill.js.map +1 -0
  86. package/dist/strand-formation-manager.d.ts +38 -9
  87. package/dist/strand-formation-manager.js +120 -17
  88. package/dist/strand-formation-manager.js.map +1 -1
  89. package/dist/strand-formation-protocol.d.ts +103 -4
  90. package/dist/strand-formation-protocol.js +232 -4
  91. package/dist/strand-formation-protocol.js.map +1 -1
  92. package/dist/strand-instance-manager.d.ts +39 -1
  93. package/dist/strand-instance-manager.js +92 -14
  94. package/dist/strand-instance-manager.js.map +1 -1
  95. package/dist/strand-member-registry.d.ts +5 -5
  96. package/dist/strand-member-registry.js +18 -10
  97. package/dist/strand-member-registry.js.map +1 -1
  98. package/dist/strand-membership-writer.d.ts +482 -88
  99. package/dist/strand-membership-writer.js +757 -136
  100. package/dist/strand-membership-writer.js.map +1 -1
  101. package/dist/strand-solicitation.d.ts +99 -33
  102. package/dist/strand-solicitation.js +100 -52
  103. package/dist/strand-solicitation.js.map +1 -1
  104. package/dist/strand-transport-key.d.ts +40 -0
  105. package/dist/strand-transport-key.js +56 -0
  106. package/dist/strand-transport-key.js.map +1 -0
  107. package/dist/strand-wake-protocol.d.ts +9 -7
  108. package/dist/strand-wake-protocol.js +22 -46
  109. package/dist/strand-wake-protocol.js.map +1 -1
  110. package/dist/strand-watcher.d.ts +17 -2
  111. package/dist/strand-watcher.js +47 -3
  112. package/dist/strand-watcher.js.map +1 -1
  113. package/dist/trusted-owner-store-file.d.ts +12 -0
  114. package/dist/trusted-owner-store-file.js +39 -0
  115. package/dist/trusted-owner-store-file.js.map +1 -0
  116. package/dist/trusted-owner-store.d.ts +64 -0
  117. package/dist/trusted-owner-store.js +126 -0
  118. package/dist/trusted-owner-store.js.map +1 -0
  119. package/dist/types.d.ts +275 -20
  120. package/dist/types.js +13 -0
  121. package/dist/types.js.map +1 -1
  122. package/package.json +19 -8
  123. package/src/bootstrap-peer-store-file.ts +44 -0
  124. package/src/bootstrap-peer-store.ts +172 -0
  125. package/src/cadre-node.ts +1992 -202
  126. package/src/control-authorization.ts +114 -0
  127. package/src/control-database.ts +1704 -146
  128. package/src/control-formation-recorder.ts +172 -19
  129. package/src/control-schema.ts +786 -222
  130. package/src/control-stream.ts +81 -4
  131. package/src/control-write-retry.ts +473 -0
  132. package/src/delegate-admission.ts +302 -0
  133. package/src/device-token.ts +18 -13
  134. package/src/ed25519-key.ts +134 -69
  135. package/src/file-durable-slot.ts +61 -0
  136. package/src/formation-approval.ts +604 -0
  137. package/src/fs-atomic.ts +107 -0
  138. package/src/identity-key.ts +109 -0
  139. package/src/index.ts +136 -5
  140. package/src/key-store-file.ts +10 -81
  141. package/src/membership-connection-gater.ts +204 -0
  142. package/src/node-local-snapshot.ts +260 -0
  143. package/src/peer-authorization.ts +199 -21
  144. package/src/peer-record.ts +28 -10
  145. package/src/relay-addrs.ts +111 -0
  146. package/src/relay-reservation.ts +823 -0
  147. package/src/seed-bootstrap.ts +397 -197
  148. package/src/seed-trust-policy.ts +58 -25
  149. package/src/strand-addr-protocol.ts +84 -53
  150. package/src/strand-backfill.ts +366 -0
  151. package/src/strand-formation-manager.ts +145 -19
  152. package/src/strand-formation-protocol.ts +309 -8
  153. package/src/strand-instance-manager.ts +111 -14
  154. package/src/strand-member-registry.ts +18 -13
  155. package/src/strand-membership-writer.ts +1430 -640
  156. package/src/strand-solicitation.ts +155 -90
  157. package/src/strand-transport-key.ts +58 -0
  158. package/src/strand-wake-protocol.ts +29 -46
  159. package/src/strand-watcher.ts +66 -3
  160. package/src/trusted-owner-store-file.ts +41 -0
  161. package/src/trusted-owner-store.ts +171 -0
  162. package/src/types.ts +292 -21
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Delegate-peer admission grants for a party control node that also runs the
3
+ * circuit-relay server.
4
+ *
5
+ * A strand node runs as its own libp2p instance with its own transport peerId,
6
+ * derived from the cadre identity key + strandId (`strand-transport-key.ts`).
7
+ * That derivation uses the member's PRIVATE seed by design, so no third party —
8
+ * including a co-cadre relay — can recompute it. When a NAT'd member's strand
9
+ * node tries to reserve a circuit-relay slot on a sibling's control node, the
10
+ * relay's membership connection gater sees an unknown peerId and denies the
11
+ * connection, which kills the reservation and fails the strand's
12
+ * `libp2p.start()` outright.
13
+ *
14
+ * The resolution (docs/strands.md → "Relays and admission"): a party control
15
+ * node running a relay is party-private infrastructure — it relays for its own
16
+ * party's nodes, including the extra transport identities its members' strand
17
+ * nodes run as, and for nobody else. The mechanism is a **member-announced
18
+ * delegate grant**: before a member's control node starts a strand node, it
19
+ * tells its siblings (over the already-authenticated `/sereus/strand-addr/1.0.0`
20
+ * RPC) the derived peerId that strand node will use, and the receiver holds a
21
+ * short-lived, in-memory admission grant for exactly that peerId. The grant is
22
+ * consulted ONLY by the connection-level gate
23
+ * (`CadreNode.admitInboundControlConnection`); the fail-closed per-stream gate
24
+ * (`authorizeInboundControlStream`) never honors it, so a delegate gets the
25
+ * connection (all a circuit-relay `hop` reservation needs) and nothing more.
26
+ *
27
+ * A grant is a delegation of trust to an already-trusted member: the receiver
28
+ * cannot verify that the announced peerId really is the member's strand node,
29
+ * so an authorized member can hand CONNECTION-level access to a peerId of its
30
+ * choosing for up to {@link DELEGATE_GRANT_TTL_MS}. The caps below bound how
31
+ * far a buggy or compromised member can stretch that.
32
+ *
33
+ * The receiver side is {@link DelegateAdmissionStore}. The announcer side keeps
34
+ * its own throttle state (a "last announced at" map that `CadreNode` owns) and
35
+ * decides from it, per reconcile pass, which relays are due a re-announce —
36
+ * {@link dueRelayAnnounces} and {@link pruneStoppedStrandAnnounces} are that
37
+ * decision, pure and testable, kept here beside the TTL they are derived from.
38
+ */
39
+
40
+ import debug from 'debug';
41
+ import { multiaddr } from '@multiformats/multiaddr';
42
+ import { peerIdFromString } from '@libp2p/peer-id';
43
+
44
+ const log = debug('sereus:cadre:delegate-admission');
45
+
46
+ /**
47
+ * How long one announced delegate grant stays valid without a re-announce.
48
+ * Announcers refresh at half this (`CadreNode`'s reconcile pass), so a live
49
+ * strand's grant never lapses while its control node can still reach the relay.
50
+ */
51
+ export const DELEGATE_GRANT_TTL_MS = 30 * 60 * 1000;
52
+
53
+ /** Cap on live grants per announcing member (soonest-expiry evicted first). */
54
+ export const MAX_DELEGATE_GRANTS_PER_MEMBER = 32;
55
+
56
+ /** Cap on live grants in total (soonest-expiry evicted first). */
57
+ export const MAX_DELEGATE_GRANTS = 256;
58
+
59
+ /** One recorded delegate admission grant. */
60
+ interface DelegateGrant {
61
+ /** The authorized member whose control node announced this delegate. */
62
+ announcerPeerId: string;
63
+ /** The strand the delegate serves — diagnostics + per-strand replace semantics. */
64
+ strandId: string;
65
+ /** The delegate transport peerId the grant admits. */
66
+ delegatePeerId: string;
67
+ /** Epoch ms after which the grant is inert. */
68
+ expiresAt: number;
69
+ }
70
+
71
+ /**
72
+ * Composite map key for the per-(peer, strand) state on both sides: the
73
+ * receiver's replace-per-(announcer, strand) grant, and the announcer's
74
+ * per-(target, strand) throttle timestamp.
75
+ */
76
+ export function peerStrandKey(peerId: string, strandId: string): string {
77
+ return `${peerId}\n${strandId}`;
78
+ }
79
+
80
+ /** The `strandId` half of a {@link peerStrandKey}. */
81
+ function strandIdOfKey(key: string): string {
82
+ return key.slice(key.indexOf('\n') + 1);
83
+ }
84
+
85
+ /**
86
+ * In-memory store of delegate admission grants, keyed by (announcer, strandId)
87
+ * so a re-announce REPLACES the previous delegate peerId rather than
88
+ * accumulating — a restarted strand cannot leak grants. Expired entries are
89
+ * pruned lazily on every read/write. Injectable `now` keeps expiry testable
90
+ * without fake timers.
91
+ */
92
+ export class DelegateAdmissionStore {
93
+ private readonly grants = new Map<string, DelegateGrant>();
94
+ private readonly ttlMs: number;
95
+
96
+ constructor(ttlMs: number = DELEGATE_GRANT_TTL_MS) {
97
+ this.ttlMs = ttlMs;
98
+ }
99
+
100
+ /** Number of live (unexpired at last prune) grants — test/diagnostic surface. */
101
+ get size(): number {
102
+ return this.grants.size;
103
+ }
104
+
105
+ /**
106
+ * Record (or refresh) a grant: `delegatePeerId` acts on behalf of
107
+ * `announcerPeerId` for `strandId`, valid for the store's TTL from `now`.
108
+ * Enforces {@link MAX_DELEGATE_GRANTS_PER_MEMBER} and
109
+ * {@link MAX_DELEGATE_GRANTS}, evicting the soonest-expiry grant first —
110
+ * biased against the stalest delegation, never against the fresh announce.
111
+ */
112
+ grant(announcerPeerId: string, strandId: string, delegatePeerId: string, now: number = Date.now()): void {
113
+ this.prune(now);
114
+ const key = peerStrandKey(announcerPeerId, strandId);
115
+ if (!this.grants.has(key)) {
116
+ this.evictAtCap(
117
+ MAX_DELEGATE_GRANTS_PER_MEMBER,
118
+ (g) => g.announcerPeerId === announcerPeerId
119
+ );
120
+ this.evictAtCap(MAX_DELEGATE_GRANTS, () => true);
121
+ }
122
+ this.grants.set(key, { announcerPeerId, strandId, delegatePeerId, expiresAt: now + this.ttlMs });
123
+ log('Delegate grant recorded: %s → %s (strand %s, %d live)', announcerPeerId, delegatePeerId, strandId, this.grants.size);
124
+ }
125
+
126
+ /**
127
+ * Drop every grant. Called when the owning node stops: grants are scoped to
128
+ * the session that recorded them, and outliving it would admit delegates
129
+ * announced against a node that no longer exists.
130
+ */
131
+ clear(): void {
132
+ this.grants.clear();
133
+ }
134
+
135
+ /** Is `remotePeerId` covered by a live grant? Prunes expired entries as it goes. */
136
+ has(remotePeerId: string, now: number = Date.now()): boolean {
137
+ this.prune(now);
138
+ for (const grant of this.grants.values()) {
139
+ if (grant.delegatePeerId === remotePeerId) {
140
+ return true;
141
+ }
142
+ }
143
+ return false;
144
+ }
145
+
146
+ /** Drop every grant whose expiry has passed. */
147
+ private prune(now: number): void {
148
+ for (const [key, grant] of this.grants) {
149
+ if (grant.expiresAt <= now) {
150
+ this.grants.delete(key);
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * If the grants matching `filter` are at `cap`, evict the soonest-expiry one
157
+ * among them to make room for the insert the caller is about to do.
158
+ */
159
+ private evictAtCap(cap: number, filter: (grant: DelegateGrant) => boolean): void {
160
+ let count = 0;
161
+ let victimKey: string | undefined;
162
+ let victimExpiry = Number.POSITIVE_INFINITY;
163
+ for (const [key, grant] of this.grants) {
164
+ if (!filter(grant)) {
165
+ continue;
166
+ }
167
+ count++;
168
+ if (grant.expiresAt < victimExpiry) {
169
+ victimExpiry = grant.expiresAt;
170
+ victimKey = key;
171
+ }
172
+ }
173
+ if (count >= cap && victimKey !== undefined) {
174
+ const victim = this.grants.get(victimKey)!;
175
+ this.grants.delete(victimKey);
176
+ log('Delegate grant cap %d hit — evicted soonest-expiry grant %s → %s (strand %s)',
177
+ cap, victim.announcerPeerId, victim.delegatePeerId, victim.strandId);
178
+ }
179
+ }
180
+ }
181
+
182
+ /** A circuit relay named by a multiaddr, as an announce target. */
183
+ export interface CircuitRelayTarget {
184
+ /** The relay's peerId — the `<relay>` in `…/p2p/<relay>/p2p-circuit…`. */
185
+ relayPeerId: string;
186
+ /**
187
+ * The relay's DIRECT dial multiaddr (the prefix before `/p2p-circuit`),
188
+ * usable as a dial fallback when no connection to the relay is open yet.
189
+ */
190
+ relayAddr: string;
191
+ }
192
+
193
+ /**
194
+ * Extract the circuit relays named by a multiaddr list — for each
195
+ * `…/p2p/<relay>/p2p-circuit…` entry, the relay's peerId and its direct dial
196
+ * prefix. A bare `/p2p-circuit` (no relay named), a non-circuit addr, an
197
+ * unparsable addr, and an unparsable relay peerId are all skipped. A trailing
198
+ * `/p2p/<dst>` after the circuit component names the DESTINATION, never the
199
+ * relay, and is ignored. Deduplicated by relay peerId (first addr wins).
200
+ */
201
+ export function extractCircuitRelayTargets(addrs: string[]): CircuitRelayTarget[] {
202
+ const byRelay = new Map<string, CircuitRelayTarget>();
203
+ for (const addr of addrs) {
204
+ const target = circuitRelayTarget(addr);
205
+ if (target && !byRelay.has(target.relayPeerId)) {
206
+ byRelay.set(target.relayPeerId, target);
207
+ }
208
+ }
209
+ return [...byRelay.values()];
210
+ }
211
+
212
+ /**
213
+ * Of `relays`, the ones whose grant for `strandId` is due a re-announce: never
214
+ * announced to, or last announced at least half the TTL ago. Half, so a failed
215
+ * refresh has one more attempt before the grant lapses — a lapsed grant means
216
+ * the relay denies the strand node's reservation re-dial.
217
+ *
218
+ * `announceAt` is the announcer-side "last announced at" map, keyed by
219
+ * {@link peerStrandKey} on the peer announced TO.
220
+ */
221
+ export function dueRelayAnnounces(
222
+ announceAt: ReadonlyMap<string, number>,
223
+ relays: readonly CircuitRelayTarget[],
224
+ strandId: string,
225
+ now: number,
226
+ ttlMs: number = DELEGATE_GRANT_TTL_MS
227
+ ): CircuitRelayTarget[] {
228
+ return relays.filter(
229
+ (relay) => now - (announceAt.get(peerStrandKey(relay.relayPeerId, strandId)) ?? 0) >= ttlMs / 2
230
+ );
231
+ }
232
+
233
+ /**
234
+ * Drop `announceAt` entries whose strand is no longer running — a stopped
235
+ * strand needs no refresh, and without this the map grows for the node's
236
+ * lifetime. Mutates in place.
237
+ */
238
+ export function pruneStoppedStrandAnnounces(
239
+ announceAt: Map<string, number>,
240
+ runningStrandIds: ReadonlySet<string>
241
+ ): void {
242
+ for (const key of announceAt.keys()) {
243
+ if (!runningStrandIds.has(strandIdOfKey(key))) {
244
+ announceAt.delete(key);
245
+ }
246
+ }
247
+ }
248
+
249
+ /**
250
+ * The circuit relay named by `addr`, throwing when `addr` is unparsable or names
251
+ * no relay. The throwing form exists for CONFIG-facing callers (`relay-addrs.ts`),
252
+ * where a typo must fail loudly rather than cost the node its reachability;
253
+ * {@link extractCircuitRelayTargets} reads runtime-discovered addrs instead and
254
+ * logs-and-skips.
255
+ */
256
+ export function circuitRelayTargetOrThrow(addr: string): CircuitRelayTarget {
257
+ const target = parseCircuitRelayTarget(addr);
258
+ if (!target) {
259
+ throw new Error(`Multiaddr names no circuit relay (expected …/p2p/<relayPeerId>/p2p-circuit): ${addr}`);
260
+ }
261
+ return target;
262
+ }
263
+
264
+ /**
265
+ * The circuit relay named by `addr`; null when `addr` is well-formed but simply
266
+ * names no relay (a direct listen addr, a bare `/p2p-circuit`), and THROWS when
267
+ * `addr` is malformed (unparsable multiaddr, garbage relay peerId). The two
268
+ * callers want opposite things from the first case and the same thing from the
269
+ * second, so the distinction lives here rather than in either of them.
270
+ */
271
+ function parseCircuitRelayTarget(addr: string): CircuitRelayTarget | null {
272
+ const ma = multiaddr(addr);
273
+ const components = ma.getComponents();
274
+ const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
275
+ if (circuitIdx < 1) {
276
+ return null;
277
+ }
278
+ const relay = components[circuitIdx - 1];
279
+ if (relay.name !== 'p2p' || !relay.value) {
280
+ return null;
281
+ }
282
+ peerIdFromString(relay.value); // validate; throws on garbage
283
+ return {
284
+ relayPeerId: relay.value,
285
+ relayAddr: ma.decapsulate('/p2p-circuit').toString()
286
+ };
287
+ }
288
+
289
+ /**
290
+ * One-addr body of {@link extractCircuitRelayTargets}; null when `addr` names no
291
+ * relay. Only a MALFORMED addr logs — the addr lists this reads (a node's live
292
+ * multiaddrs, its configured listen addrs) are mostly direct addrs, and calling
293
+ * each of those "unparsable" is both wrong and per-announce noise.
294
+ */
295
+ function circuitRelayTarget(addr: string): CircuitRelayTarget | null {
296
+ try {
297
+ return parseCircuitRelayTarget(addr);
298
+ } catch (err) {
299
+ log('Skipping unparsable relay addr %s: %o', addr, err);
300
+ return null;
301
+ }
302
+ }
@@ -4,20 +4,20 @@
4
4
  * another peer's row.
5
5
  *
6
6
  * Modeled directly on {@link peerRecordSignedPayload} (peer-record.ts): the signed
7
- * payload is a single SHA-256 digest of a delimited string of the authenticated
8
- * fields. It is intentionally NOT JSON-canonicalized — a delimited digest is
9
- * trivially deterministic across node/browser/RN (plain string concat + sha256, no
10
- * key ordering) and is reconstructable inside the `DeviceToken.AuthorizedUpdate` SQL
11
- * constraint from the row's own columns:
7
+ * payload is a single SHA-256 digest over the shared domain-tagged field vector
8
+ * (see control-authorization.ts) — the crypto plugin's injective multi-field
9
+ * encoding, so no field split is ambiguous even with an opaque platform token. It
10
+ * is intentionally NOT JSON-canonicalized (deterministic across node/browser/RN,
11
+ * no key ordering) and is reconstructable inside the `DeviceToken.AuthorizedUpdate`
12
+ * SQL constraint from the row's own columns:
12
13
  *
13
- * digest(new.PeerId || '|' || new.Platform || '|' || new.Token || '|'
14
- * || cast(new.UpdatedAt as text))
14
+ * digest('CadreControl.DeviceToken', 'publish',
15
+ * new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text))
15
16
  *
16
17
  * Keep {@link deviceTokenSignedPayload} and that constraint byte-for-byte in sync.
17
- * The `'|'` delimiter is safe: a base58btc PeerId, a fixed `'fcm'`/`'apns'` platform
18
- * string, and a base-10 integer never contain it. The opaque platform token is the
19
- * last variable-length field before the integer stamp, so even a token containing a
20
- * `'|'` cannot create a collision with a different field split.
18
+ * The `'publish'` action tag marks this as a peer's SELF-signed record (signed with
19
+ * the peer's own key, not an owner key) and keeps it disjoint from every
20
+ * owner-signed digest.
21
21
  *
22
22
  * Unlike a peer-address record, a device-token record carries NO public key: the
23
23
  * signature is verified against the `CadrePeer.PublicKey` bound to the same PeerId
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
29
+ import { controlAuthorizationFields } from './control-authorization.js';
29
30
  import type { DeviceTokenRecord, PushPlatform } from './types.js';
30
31
 
31
32
  /**
@@ -34,8 +35,12 @@ import type { DeviceTokenRecord, PushPlatform } from './types.js';
34
35
  * base64url output of a single `digest(...)`, which round-trips cleanly.
35
36
  */
36
37
  export function deviceTokenSignedPayload(record: Omit<DeviceTokenRecord, 'sig'>): string {
37
- const joined = `${record.peerId}|${record.platform}|${record.token}|${record.updatedAt}`;
38
- return digest([joined], 'sha256', 'base64url') as string;
38
+ const fields = controlAuthorizationFields(
39
+ 'CadreControl.DeviceToken',
40
+ 'publish',
41
+ [record.peerId, record.platform, record.token, String(record.updatedAt)]
42
+ );
43
+ return digest(fields, 'sha256', 'base64url') as string;
39
44
  }
40
45
 
41
46
  /**
@@ -1,69 +1,134 @@
1
- import { toString as uint8ArrayToString } from 'uint8arrays';
2
- import { getPublicKey } from '@optimystic/quereus-plugin-crypto';
3
- import type { PrivateKey } from '@libp2p/interface';
4
-
5
- /**
6
- * An Ed25519 keypair expressed in the base64url form that
7
- * `@optimystic/quereus-plugin-crypto` (`sign`/`verify`/`getPublicKey`) consumes.
8
- * Generic bridge type — reused for owner keys, member keys, and any other
9
- * seed→public keypair the control/strand databases sign with.
10
- */
11
- export interface Ed25519KeyPair {
12
- /** 32-byte Ed25519 seed, base64url-encoded — the crypto-plugin private key. */
13
- privateKeyB64: string;
14
- /** 32-byte Ed25519 public key, base64url-encoded. */
15
- publicKeyB64: string;
16
- }
17
-
18
- /**
19
- * Bridge a libp2p Ed25519 private key into the base64url keypair used by the
20
- * control- and strand-database signing constraints.
21
- *
22
- * libp2p stores an Ed25519 private key as 64 raw bytes: the first 32 are the
23
- * seed (the actual scalar source), the last 32 are the public key — see
24
- * `@libp2p/crypto`'s `Ed25519PrivateKey`. `@optimystic/quereus-plugin-crypto`
25
- * (via `@noble/curves`) treats the 32-byte seed *as* the private key and
26
- * derives the public key from it with standard Ed25519. The two derivations
27
- * agree, so the node's peer identity and its signing key are one keypair:
28
- * `getPublicKey(privateKeyB64)` === `publicKeyB64`.
29
- *
30
- * @param privateKey - The node's libp2p Ed25519 private key.
31
- * @returns The base64url seed/public-key pair for signing operations.
32
- * @throws If the key is not Ed25519 or the raw bytes aren't the expected length.
33
- */
34
- export function ed25519KeyPairFromLibp2p(privateKey: PrivateKey): Ed25519KeyPair {
35
- if (privateKey.type !== 'Ed25519') {
36
- throw new Error(`ed25519KeyPairFromLibp2p requires an Ed25519 key, got ${privateKey.type}`);
37
- }
38
-
39
- const raw = privateKey.raw;
40
- if (raw.length !== 64) {
41
- throw new Error(`Expected a 64-byte Ed25519 raw private key (seed||public), got ${raw.length} bytes`);
42
- }
43
-
44
- const seed = raw.subarray(0, 32);
45
- const publicKeyRaw = privateKey.publicKey.raw;
46
- if (publicKeyRaw.length !== 32) {
47
- throw new Error(`Expected a 32-byte Ed25519 public key, got ${publicKeyRaw.length} bytes`);
48
- }
49
-
50
- return {
51
- privateKeyB64: uint8ArrayToString(seed, 'base64url'),
52
- publicKeyB64: uint8ArrayToString(publicKeyRaw, 'base64url'),
53
- };
54
- }
55
-
56
- /**
57
- * Derive the base64url Ed25519 public key from a base64url 32-byte private seed
58
- * — the same derivation the seed-bootstrap signer uses internally
59
- * (`SeedBootstrapService` constructor). Use this to enroll a standalone
60
- * (non-libp2p) key into the control DB before minting an invite, when the
61
- * key is *not* the node's peer identity (so `ed25519KeyPairFromLibp2p`,
62
- * which needs a libp2p key object, does not apply).
63
- *
64
- * @param privateKeyB64 - The base64url-encoded 32-byte Ed25519 seed.
65
- * @returns The base64url-encoded Ed25519 public key.
66
- */
67
- export function ed25519PublicKeyFromPrivate(privateKeyB64: string): string {
68
- return getPublicKey(privateKeyB64, 'ed25519', 'base64url', 'base64url') as string;
69
- }
1
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
2
+ import { getPublicKey } from '@optimystic/quereus-plugin-crypto';
3
+ import type { PrivateKey } from '@libp2p/interface';
4
+
5
+ /**
6
+ * An Ed25519 keypair expressed in the base64url form that
7
+ * `@optimystic/quereus-plugin-crypto` (`sign`/`verify`/`getPublicKey`) consumes.
8
+ * Generic bridge type — reused for owner keys, member keys, and any other
9
+ * seed→public keypair the control/strand databases sign with.
10
+ */
11
+ export interface Ed25519KeyPair {
12
+ /** 32-byte Ed25519 seed, base64url-encoded — the crypto-plugin private key. */
13
+ privateKeyB64: string;
14
+ /** 32-byte Ed25519 public key, base64url-encoded. */
15
+ publicKeyB64: string;
16
+ }
17
+
18
+ /**
19
+ * Bridge a libp2p Ed25519 private key into the base64url keypair used by the
20
+ * control- and strand-database signing constraints.
21
+ *
22
+ * libp2p stores an Ed25519 private key as 64 raw bytes: the first 32 are the
23
+ * seed (the actual scalar source), the last 32 are the public key — see
24
+ * `@libp2p/crypto`'s `Ed25519PrivateKey`. `@optimystic/quereus-plugin-crypto`
25
+ * (via `@noble/curves`) treats the 32-byte seed *as* the private key and
26
+ * derives the public key from it with standard Ed25519. The two derivations
27
+ * agree, so the node's peer identity and its signing key are one keypair:
28
+ * `getPublicKey(privateKeyB64)` === `publicKeyB64`.
29
+ *
30
+ * @param privateKey - The node's libp2p Ed25519 private key.
31
+ * @returns The base64url seed/public-key pair for signing operations.
32
+ * @throws If the key is not Ed25519 or the raw bytes aren't the expected length.
33
+ */
34
+ export function ed25519KeyPairFromLibp2p(privateKey: PrivateKey): Ed25519KeyPair {
35
+ if (privateKey.type !== 'Ed25519') {
36
+ throw new Error(`ed25519KeyPairFromLibp2p requires an Ed25519 key, got ${privateKey.type}`);
37
+ }
38
+
39
+ const raw = privateKey.raw;
40
+ if (raw.length !== 64) {
41
+ throw new Error(`Expected a 64-byte Ed25519 raw private key (seed||public), got ${raw.length} bytes`);
42
+ }
43
+
44
+ const seed = raw.subarray(0, 32);
45
+ const publicKeyRaw = privateKey.publicKey.raw;
46
+ if (publicKeyRaw.length !== 32) {
47
+ throw new Error(`Expected a 32-byte Ed25519 public key, got ${publicKeyRaw.length} bytes`);
48
+ }
49
+
50
+ return {
51
+ privateKeyB64: uint8ArrayToString(seed, 'base64url'),
52
+ publicKeyB64: uint8ArrayToString(publicKeyRaw, 'base64url'),
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Derive the base64url Ed25519 public key from a base64url 32-byte private seed
58
+ * — the same derivation the seed-bootstrap signer uses internally
59
+ * (`SeedBootstrapService` constructor). Use this to enroll a standalone
60
+ * (non-libp2p) key into the control DB before minting an invite, when the
61
+ * key is *not* the node's peer identity (so `ed25519KeyPairFromLibp2p`,
62
+ * which needs a libp2p key object, does not apply).
63
+ *
64
+ * @param privateKeyB64 - The base64url-encoded 32-byte Ed25519 seed.
65
+ * @returns The base64url-encoded Ed25519 public key.
66
+ */
67
+ export function ed25519PublicKeyFromPrivate(privateKeyB64: string): string {
68
+ return getPublicKey(privateKeyB64, 'ed25519', 'base64url', 'base64url') as string;
69
+ }
70
+
71
+ /** Longest rejected key value echoed back in an error — a real key is 43 base64url chars. */
72
+ const REJECTED_VALUE_ECHO_LIMIT = 64;
73
+
74
+ /**
75
+ * Render a rejected value for an error message, capped: owner keys now reach this check
76
+ * from remote-supplied fields (a `CadreInvite`'s `ownerKeys`, a donation request's
77
+ * `ownerKeys`), so an unbounded echo would let a peer turn one junk string into a
78
+ * megabyte of log line.
79
+ */
80
+ function describeRejected(value: string): string {
81
+ return value.length <= REJECTED_VALUE_ECHO_LIMIT
82
+ ? value
83
+ : `${value.slice(0, REJECTED_VALUE_ECHO_LIMIT)}… (${value.length} chars)`;
84
+ }
85
+
86
+ /**
87
+ * Reject a value that isn't shaped like a base64url-encoded 32-byte Ed25519 public key
88
+ * before it reaches the control database, where a malformed key would otherwise sit
89
+ * indistinguishable from a real one until some later, unrelated signature check fails.
90
+ *
91
+ * Trims first, reusing the blank-value message for an empty result so that case keeps its
92
+ * existing wording instead of a confusing base64url error. Every rejection names the offending
93
+ * value (capped, see {@link describeRejected}) — with several keys in one batch, the message is
94
+ * the only thing that says WHICH one. Does not check the decoded bytes
95
+ * are a valid point on the Ed25519 curve — a well-formed-but-off-curve key still fails
96
+ * signature verification later exactly like any other wrong key.
97
+ *
98
+ * **This rule is restated once outside this package**, in `validateOwnerKey`
99
+ * (`packages/cadre-provider/src/server/owner-key-validation.ts`): cadre-provider declares no
100
+ * `workspace:` dependencies and validates `POST /containers` pins over `uint8arrays`
101
+ * directly. Change the rule here and change it there — the copies are kept in step by
102
+ * hand, since neither package can import the other's. Each side pins its own copy to the
103
+ * same accept/reject table (`test/ed25519-key.spec.ts` here,
104
+ * `create-container-owner-keys.test.ts` there), so a change fails the suite of the
105
+ * package it was made in and lands the editor on this pointer.
106
+ *
107
+ * @param value - Candidate base64url-encoded Ed25519 public key.
108
+ * @param label - Human-readable name of the field, used in error messages.
109
+ * @returns The trimmed value, so callers write the same bytes they validated.
110
+ */
111
+ export function requireEd25519PublicKeyB64(value: string, label: string): string {
112
+ const trimmed = value.trim();
113
+ if (trimmed.length === 0) {
114
+ throw new Error(`A ${label} is required (received an empty or whitespace-only value)`);
115
+ }
116
+
117
+ let decoded: Uint8Array;
118
+ try {
119
+ decoded = uint8ArrayFromString(trimmed, 'base64url');
120
+ } catch (error) {
121
+ throw new Error(
122
+ `A ${label} must be a base64url-encoded Ed25519 public key (could not decode "${describeRejected(trimmed)}" as base64url)`,
123
+ { cause: error },
124
+ );
125
+ }
126
+
127
+ if (decoded.length !== 32) {
128
+ throw new Error(
129
+ `A ${label} must be a base64url-encoded 32-byte Ed25519 public key ("${describeRejected(trimmed)}" decoded to ${decoded.length} bytes)`,
130
+ );
131
+ }
132
+
133
+ return trimmed;
134
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Node-only {@link DurableSlot} backend: one JSON file per party under `dir`,
3
+ * at `<dir>/<name>.<encoded partyId>.json` (0600, atomically replaced on every
4
+ * save), so one directory can hold the same node-local record for several
5
+ * parties without cross-party leakage.
6
+ *
7
+ * This is the whole platform-specific part of the file-backed node-local
8
+ * stores (`trusted-owner-store-file.ts`, `bootstrap-peer-store-file.ts`); the
9
+ * load policy, envelope and write chain are cross-platform in
10
+ * `node-local-snapshot.ts`. Like its two importers, this module imports
11
+ * `node:fs/promises`, so it is kept OUT of the package's cross-platform
12
+ * default entry and is not itself an exported subpath.
13
+ */
14
+ import { readFile } from 'node:fs/promises';
15
+ import { join } from 'node:path';
16
+ import { randomBytes } from 'node:crypto';
17
+ import { encodeFileSafeComponent, isNotFound, writeFileAtomically } from './fs-atomic.js';
18
+ import type { DurableSlot } from './node-local-snapshot.js';
19
+
20
+ export class FileDurableSlot implements DurableSlot {
21
+ /** Filename-safe form of the party id, shared by the record and temp paths. */
22
+ private readonly encodedParty: string;
23
+
24
+ constructor(
25
+ private readonly dir: string,
26
+ private readonly name: string,
27
+ partyId: string
28
+ ) {
29
+ this.encodedParty = encodeFileSafeComponent(partyId);
30
+ }
31
+
32
+ /**
33
+ * The record's bytes as text. An absent file (ENOENT — including an absent
34
+ * directory) is `undefined`, a cold start. Every other read failure
35
+ * (EACCES, EISDIR, EIO, …) THROWS, per {@link DurableSlot.load}: the caller
36
+ * must not mistake an unreadable file for an empty one and snapshot-write
37
+ * over it.
38
+ */
39
+ async load(): Promise<string | undefined> {
40
+ try {
41
+ return (await readFile(this.filePath())).toString('utf8');
42
+ } catch (error) {
43
+ if (isNotFound(error)) return undefined;
44
+ throw new Error(`FileDurableSlot: ${this.filePath()} is present but unreadable`, { cause: error });
45
+ }
46
+ }
47
+
48
+ async save(text: string): Promise<void> {
49
+ await writeFileAtomically(this.dir, this.tempPath(), this.filePath(), new TextEncoder().encode(text));
50
+ }
51
+
52
+ private filePath(): string {
53
+ return join(this.dir, `${this.name}.${this.encodedParty}.json`);
54
+ }
55
+
56
+ /** Sibling temp path for the atomic replace (random component: collide-free). */
57
+ private tempPath(): string {
58
+ const unique = randomBytes(6).toString('hex');
59
+ return join(this.dir, `${this.name}.${this.encodedParty}.${unique}.tmp`);
60
+ }
61
+ }