@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,244 @@
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
+ import debug from 'debug';
40
+ import { multiaddr } from '@multiformats/multiaddr';
41
+ import { peerIdFromString } from '@libp2p/peer-id';
42
+ const log = debug('sereus:cadre:delegate-admission');
43
+ /**
44
+ * How long one announced delegate grant stays valid without a re-announce.
45
+ * Announcers refresh at half this (`CadreNode`'s reconcile pass), so a live
46
+ * strand's grant never lapses while its control node can still reach the relay.
47
+ */
48
+ export const DELEGATE_GRANT_TTL_MS = 30 * 60 * 1000;
49
+ /** Cap on live grants per announcing member (soonest-expiry evicted first). */
50
+ export const MAX_DELEGATE_GRANTS_PER_MEMBER = 32;
51
+ /** Cap on live grants in total (soonest-expiry evicted first). */
52
+ export const MAX_DELEGATE_GRANTS = 256;
53
+ /**
54
+ * Composite map key for the per-(peer, strand) state on both sides: the
55
+ * receiver's replace-per-(announcer, strand) grant, and the announcer's
56
+ * per-(target, strand) throttle timestamp.
57
+ */
58
+ export function peerStrandKey(peerId, strandId) {
59
+ return `${peerId}\n${strandId}`;
60
+ }
61
+ /** The `strandId` half of a {@link peerStrandKey}. */
62
+ function strandIdOfKey(key) {
63
+ return key.slice(key.indexOf('\n') + 1);
64
+ }
65
+ /**
66
+ * In-memory store of delegate admission grants, keyed by (announcer, strandId)
67
+ * so a re-announce REPLACES the previous delegate peerId rather than
68
+ * accumulating — a restarted strand cannot leak grants. Expired entries are
69
+ * pruned lazily on every read/write. Injectable `now` keeps expiry testable
70
+ * without fake timers.
71
+ */
72
+ export class DelegateAdmissionStore {
73
+ constructor(ttlMs = DELEGATE_GRANT_TTL_MS) {
74
+ this.grants = new Map();
75
+ this.ttlMs = ttlMs;
76
+ }
77
+ /** Number of live (unexpired at last prune) grants — test/diagnostic surface. */
78
+ get size() {
79
+ return this.grants.size;
80
+ }
81
+ /**
82
+ * Record (or refresh) a grant: `delegatePeerId` acts on behalf of
83
+ * `announcerPeerId` for `strandId`, valid for the store's TTL from `now`.
84
+ * Enforces {@link MAX_DELEGATE_GRANTS_PER_MEMBER} and
85
+ * {@link MAX_DELEGATE_GRANTS}, evicting the soonest-expiry grant first —
86
+ * biased against the stalest delegation, never against the fresh announce.
87
+ */
88
+ grant(announcerPeerId, strandId, delegatePeerId, now = Date.now()) {
89
+ this.prune(now);
90
+ const key = peerStrandKey(announcerPeerId, strandId);
91
+ if (!this.grants.has(key)) {
92
+ this.evictAtCap(MAX_DELEGATE_GRANTS_PER_MEMBER, (g) => g.announcerPeerId === announcerPeerId);
93
+ this.evictAtCap(MAX_DELEGATE_GRANTS, () => true);
94
+ }
95
+ this.grants.set(key, { announcerPeerId, strandId, delegatePeerId, expiresAt: now + this.ttlMs });
96
+ log('Delegate grant recorded: %s → %s (strand %s, %d live)', announcerPeerId, delegatePeerId, strandId, this.grants.size);
97
+ }
98
+ /**
99
+ * Drop every grant. Called when the owning node stops: grants are scoped to
100
+ * the session that recorded them, and outliving it would admit delegates
101
+ * announced against a node that no longer exists.
102
+ */
103
+ clear() {
104
+ this.grants.clear();
105
+ }
106
+ /** Is `remotePeerId` covered by a live grant? Prunes expired entries as it goes. */
107
+ has(remotePeerId, now = Date.now()) {
108
+ this.prune(now);
109
+ for (const grant of this.grants.values()) {
110
+ if (grant.delegatePeerId === remotePeerId) {
111
+ return true;
112
+ }
113
+ }
114
+ return false;
115
+ }
116
+ /** Drop every grant whose expiry has passed. */
117
+ prune(now) {
118
+ for (const [key, grant] of this.grants) {
119
+ if (grant.expiresAt <= now) {
120
+ this.grants.delete(key);
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * If the grants matching `filter` are at `cap`, evict the soonest-expiry one
126
+ * among them to make room for the insert the caller is about to do.
127
+ */
128
+ evictAtCap(cap, filter) {
129
+ let count = 0;
130
+ let victimKey;
131
+ let victimExpiry = Number.POSITIVE_INFINITY;
132
+ for (const [key, grant] of this.grants) {
133
+ if (!filter(grant)) {
134
+ continue;
135
+ }
136
+ count++;
137
+ if (grant.expiresAt < victimExpiry) {
138
+ victimExpiry = grant.expiresAt;
139
+ victimKey = key;
140
+ }
141
+ }
142
+ if (count >= cap && victimKey !== undefined) {
143
+ const victim = this.grants.get(victimKey);
144
+ this.grants.delete(victimKey);
145
+ log('Delegate grant cap %d hit — evicted soonest-expiry grant %s → %s (strand %s)', cap, victim.announcerPeerId, victim.delegatePeerId, victim.strandId);
146
+ }
147
+ }
148
+ }
149
+ /**
150
+ * Extract the circuit relays named by a multiaddr list — for each
151
+ * `…/p2p/<relay>/p2p-circuit…` entry, the relay's peerId and its direct dial
152
+ * prefix. A bare `/p2p-circuit` (no relay named), a non-circuit addr, an
153
+ * unparsable addr, and an unparsable relay peerId are all skipped. A trailing
154
+ * `/p2p/<dst>` after the circuit component names the DESTINATION, never the
155
+ * relay, and is ignored. Deduplicated by relay peerId (first addr wins).
156
+ */
157
+ export function extractCircuitRelayTargets(addrs) {
158
+ const byRelay = new Map();
159
+ for (const addr of addrs) {
160
+ const target = circuitRelayTarget(addr);
161
+ if (target && !byRelay.has(target.relayPeerId)) {
162
+ byRelay.set(target.relayPeerId, target);
163
+ }
164
+ }
165
+ return [...byRelay.values()];
166
+ }
167
+ /**
168
+ * Of `relays`, the ones whose grant for `strandId` is due a re-announce: never
169
+ * announced to, or last announced at least half the TTL ago. Half, so a failed
170
+ * refresh has one more attempt before the grant lapses — a lapsed grant means
171
+ * the relay denies the strand node's reservation re-dial.
172
+ *
173
+ * `announceAt` is the announcer-side "last announced at" map, keyed by
174
+ * {@link peerStrandKey} on the peer announced TO.
175
+ */
176
+ export function dueRelayAnnounces(announceAt, relays, strandId, now, ttlMs = DELEGATE_GRANT_TTL_MS) {
177
+ return relays.filter((relay) => now - (announceAt.get(peerStrandKey(relay.relayPeerId, strandId)) ?? 0) >= ttlMs / 2);
178
+ }
179
+ /**
180
+ * Drop `announceAt` entries whose strand is no longer running — a stopped
181
+ * strand needs no refresh, and without this the map grows for the node's
182
+ * lifetime. Mutates in place.
183
+ */
184
+ export function pruneStoppedStrandAnnounces(announceAt, runningStrandIds) {
185
+ for (const key of announceAt.keys()) {
186
+ if (!runningStrandIds.has(strandIdOfKey(key))) {
187
+ announceAt.delete(key);
188
+ }
189
+ }
190
+ }
191
+ /**
192
+ * The circuit relay named by `addr`, throwing when `addr` is unparsable or names
193
+ * no relay. The throwing form exists for CONFIG-facing callers (`relay-addrs.ts`),
194
+ * where a typo must fail loudly rather than cost the node its reachability;
195
+ * {@link extractCircuitRelayTargets} reads runtime-discovered addrs instead and
196
+ * logs-and-skips.
197
+ */
198
+ export function circuitRelayTargetOrThrow(addr) {
199
+ const target = parseCircuitRelayTarget(addr);
200
+ if (!target) {
201
+ throw new Error(`Multiaddr names no circuit relay (expected …/p2p/<relayPeerId>/p2p-circuit): ${addr}`);
202
+ }
203
+ return target;
204
+ }
205
+ /**
206
+ * The circuit relay named by `addr`; null when `addr` is well-formed but simply
207
+ * names no relay (a direct listen addr, a bare `/p2p-circuit`), and THROWS when
208
+ * `addr` is malformed (unparsable multiaddr, garbage relay peerId). The two
209
+ * callers want opposite things from the first case and the same thing from the
210
+ * second, so the distinction lives here rather than in either of them.
211
+ */
212
+ function parseCircuitRelayTarget(addr) {
213
+ const ma = multiaddr(addr);
214
+ const components = ma.getComponents();
215
+ const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
216
+ if (circuitIdx < 1) {
217
+ return null;
218
+ }
219
+ const relay = components[circuitIdx - 1];
220
+ if (relay.name !== 'p2p' || !relay.value) {
221
+ return null;
222
+ }
223
+ peerIdFromString(relay.value); // validate; throws on garbage
224
+ return {
225
+ relayPeerId: relay.value,
226
+ relayAddr: ma.decapsulate('/p2p-circuit').toString()
227
+ };
228
+ }
229
+ /**
230
+ * One-addr body of {@link extractCircuitRelayTargets}; null when `addr` names no
231
+ * relay. Only a MALFORMED addr logs — the addr lists this reads (a node's live
232
+ * multiaddrs, its configured listen addrs) are mostly direct addrs, and calling
233
+ * each of those "unparsable" is both wrong and per-announce noise.
234
+ */
235
+ function circuitRelayTarget(addr) {
236
+ try {
237
+ return parseCircuitRelayTarget(addr);
238
+ }
239
+ catch (err) {
240
+ log('Skipping unparsable relay addr %s: %o', addr, err);
241
+ return null;
242
+ }
243
+ }
244
+ //# sourceMappingURL=delegate-admission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegate-admission.js","sourceRoot":"","sources":["../src/delegate-admission.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;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C,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,aAAa,CAAC,CAAC;IACzE,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,KAAK,GAAG,UAAU,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;IACzC,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QACzC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,gBAAgB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,8BAA8B;IAC7D,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,KAAK;QACxB,SAAS,EAAE,EAAE,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,QAAQ,EAAE;KACrD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,IAAY;IACtC,IAAI,CAAC;QACH,OAAO,uBAAuB,CAAC,IAAI,CAAC,CAAC;IACvC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,GAAG,CAAC,uCAAuC,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -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
@@ -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
@@ -25,14 +25,15 @@
25
25
  * membership row already lives.
26
26
  */
27
27
  import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
28
+ import { controlAuthorizationFields } from './control-authorization.js';
28
29
  /**
29
30
  * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
30
31
  * `DeviceToken.AuthorizedUpdate` constraint exactly; both sides take the default
31
32
  * base64url output of a single `digest(...)`, which round-trips cleanly.
32
33
  */
33
34
  export function deviceTokenSignedPayload(record) {
34
- const joined = `${record.peerId}|${record.platform}|${record.token}|${record.updatedAt}`;
35
- return digest([joined], 'sha256', 'base64url');
35
+ const fields = controlAuthorizationFields('CadreControl.DeviceToken', 'publish', [record.peerId, record.platform, record.token, String(record.updatedAt)]);
36
+ return digest(fields, 'sha256', 'base64url');
36
37
  }
37
38
  /**
38
39
  * Sign a device-token record with the ed25519 private key behind its `peerId`.
@@ -1 +1 @@
1
- {"version":3,"file":"device-token.js","sourceRoot":"","sources":["../src/device-token.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAGzE;;;;GAIG;AACH,MAAM,UAAU,wB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AAW,EACX,WAAW,CACZ,CAAC;AACJ,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,CAAC;AAC7C,CAAC"}
@@ -40,3 +40,29 @@ export declare function ed25519KeyPairFromLibp2p(privateKey: PrivateKey): Ed2551
40
40
  * @returns The base64url-encoded Ed25519 public key.
41
41
  */
42
42
  export declare function ed25519PublicKeyFromPrivate(privateKeyB64: string): string;
43
+ /**
44
+ * Reject a value that isn't shaped like a base64url-encoded 32-byte Ed25519 public key
45
+ * before it reaches the control database, where a malformed key would otherwise sit
46
+ * indistinguishable from a real one until some later, unrelated signature check fails.
47
+ *
48
+ * Trims first, reusing the blank-value message for an empty result so that case keeps its
49
+ * existing wording instead of a confusing base64url error. Every rejection names the offending
50
+ * value (capped, see {@link describeRejected}) — with several keys in one batch, the message is
51
+ * the only thing that says WHICH one. Does not check the decoded bytes
52
+ * are a valid point on the Ed25519 curve — a well-formed-but-off-curve key still fails
53
+ * signature verification later exactly like any other wrong key.
54
+ *
55
+ * **This rule is restated once outside this package**, in `validateOwnerKey`
56
+ * (`packages/cadre-provider/src/server/owner-key-validation.ts`): cadre-provider declares no
57
+ * `workspace:` dependencies and validates `POST /containers` pins over `uint8arrays`
58
+ * directly. Change the rule here and change it there — the copies are kept in step by
59
+ * hand, since neither package can import the other's. Each side pins its own copy to the
60
+ * same accept/reject table (`test/ed25519-key.spec.ts` here,
61
+ * `create-container-owner-keys.test.ts` there), so a change fails the suite of the
62
+ * package it was made in and lands the editor on this pointer.
63
+ *
64
+ * @param value - Candidate base64url-encoded Ed25519 public key.
65
+ * @param label - Human-readable name of the field, used in error messages.
66
+ * @returns The trimmed value, so callers write the same bytes they validated.
67
+ */
68
+ export declare function requireEd25519PublicKeyB64(value: string, label: string): string;
@@ -1,4 +1,4 @@
1
- import { toString as uint8ArrayToString } from 'uint8arrays';
1
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
2
2
  import { getPublicKey } from '@optimystic/quereus-plugin-crypto';
3
3
  /**
4
4
  * Bridge a libp2p Ed25519 private key into the base64url keypair used by the
@@ -48,4 +48,59 @@ export function ed25519KeyPairFromLibp2p(privateKey) {
48
48
  export function ed25519PublicKeyFromPrivate(privateKeyB64) {
49
49
  return getPublicKey(privateKeyB64, 'ed25519', 'base64url', 'base64url');
50
50
  }
51
+ /** Longest rejected key value echoed back in an error — a real key is 43 base64url chars. */
52
+ const REJECTED_VALUE_ECHO_LIMIT = 64;
53
+ /**
54
+ * Render a rejected value for an error message, capped: owner keys now reach this check
55
+ * from remote-supplied fields (a `CadreInvite`'s `ownerKeys`, a donation request's
56
+ * `ownerKeys`), so an unbounded echo would let a peer turn one junk string into a
57
+ * megabyte of log line.
58
+ */
59
+ function describeRejected(value) {
60
+ return value.length <= REJECTED_VALUE_ECHO_LIMIT
61
+ ? value
62
+ : `${value.slice(0, REJECTED_VALUE_ECHO_LIMIT)}… (${value.length} chars)`;
63
+ }
64
+ /**
65
+ * Reject a value that isn't shaped like a base64url-encoded 32-byte Ed25519 public key
66
+ * before it reaches the control database, where a malformed key would otherwise sit
67
+ * indistinguishable from a real one until some later, unrelated signature check fails.
68
+ *
69
+ * Trims first, reusing the blank-value message for an empty result so that case keeps its
70
+ * existing wording instead of a confusing base64url error. Every rejection names the offending
71
+ * value (capped, see {@link describeRejected}) — with several keys in one batch, the message is
72
+ * the only thing that says WHICH one. Does not check the decoded bytes
73
+ * are a valid point on the Ed25519 curve — a well-formed-but-off-curve key still fails
74
+ * signature verification later exactly like any other wrong key.
75
+ *
76
+ * **This rule is restated once outside this package**, in `validateOwnerKey`
77
+ * (`packages/cadre-provider/src/server/owner-key-validation.ts`): cadre-provider declares no
78
+ * `workspace:` dependencies and validates `POST /containers` pins over `uint8arrays`
79
+ * directly. Change the rule here and change it there — the copies are kept in step by
80
+ * hand, since neither package can import the other's. Each side pins its own copy to the
81
+ * same accept/reject table (`test/ed25519-key.spec.ts` here,
82
+ * `create-container-owner-keys.test.ts` there), so a change fails the suite of the
83
+ * package it was made in and lands the editor on this pointer.
84
+ *
85
+ * @param value - Candidate base64url-encoded Ed25519 public key.
86
+ * @param label - Human-readable name of the field, used in error messages.
87
+ * @returns The trimmed value, so callers write the same bytes they validated.
88
+ */
89
+ export function requireEd25519PublicKeyB64(value, label) {
90
+ const trimmed = value.trim();
91
+ if (trimmed.length === 0) {
92
+ throw new Error(`A ${label} is required (received an empty or whitespace-only value)`);
93
+ }
94
+ let decoded;
95
+ try {
96
+ decoded = uint8ArrayFromString(trimmed, 'base64url');
97
+ }
98
+ catch (error) {
99
+ throw new Error(`A ${label} must be a base64url-encoded Ed25519 public key (could not decode "${describeRejected(trimmed)}" as base64url)`, { cause: error });
100
+ }
101
+ if (decoded.length !== 32) {
102
+ throw new Error(`A ${label} must be a base64url-encoded 32-byte Ed25519 public key ("${describeRejected(trimmed)}" decoded to ${decoded.length} bytes)`);
103
+ }
104
+ return trimmed;
105
+ }
51
106
  //# sourceMappingURL=ed25519-key.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ed25519-key.js","sourceRoot":"","sources":["../src/ed25519-key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAgBjE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,wBAAwB,CAAC,UAAsB;IAC7D,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,yDAAyD,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;IAC9F,CAAC;IAED,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC;IAC3B,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,kEAAkE,GA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oB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,KAAK,KAAK,sEAAsE,gBAAgB,CAAC,OAAO,CAAC,iBAAiB,EAC1H,EAAE,KAAK,EAAE,KAAK,EAAE,CACjB,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,KAAK,KAAK,6DAA6D,gBAAgB,CAAC,OAAO,CAAC,gBAAgB,OAAO,CAAC,MAAM,SAAS,CACxI,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { DurableSlot } from './node-local-snapshot.js';
2
+ export declare class FileDurableSlot implements DurableSlot {
3
+ private readonly dir;
4
+ private readonly name;
5
+ /** Filename-safe form of the party id, shared by the record and temp paths. */
6
+ private readonly encodedParty;
7
+ constructor(dir: string, name: string, partyId: string);
8
+ /**
9
+ * The record's bytes as text. An absent file (ENOENT — including an absent
10
+ * directory) is `undefined`, a cold start. Every other read failure
11
+ * (EACCES, EISDIR, EIO, …) THROWS, per {@link DurableSlot.load}: the caller
12
+ * must not mistake an unreadable file for an empty one and snapshot-write
13
+ * over it.
14
+ */
15
+ load(): Promise<string | undefined>;
16
+ save(text: string): Promise<void>;
17
+ private filePath;
18
+ /** Sibling temp path for the atomic replace (random component: collide-free). */
19
+ private tempPath;
20
+ }
@@ -0,0 +1,53 @@
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
+ export class FileDurableSlot {
19
+ constructor(dir, name, partyId) {
20
+ this.dir = dir;
21
+ this.name = name;
22
+ this.encodedParty = encodeFileSafeComponent(partyId);
23
+ }
24
+ /**
25
+ * The record's bytes as text. An absent file (ENOENT — including an absent
26
+ * directory) is `undefined`, a cold start. Every other read failure
27
+ * (EACCES, EISDIR, EIO, …) THROWS, per {@link DurableSlot.load}: the caller
28
+ * must not mistake an unreadable file for an empty one and snapshot-write
29
+ * over it.
30
+ */
31
+ async load() {
32
+ try {
33
+ return (await readFile(this.filePath())).toString('utf8');
34
+ }
35
+ catch (error) {
36
+ if (isNotFound(error))
37
+ return undefined;
38
+ throw new Error(`FileDurableSlot: ${this.filePath()} is present but unreadable`, { cause: error });
39
+ }
40
+ }
41
+ async save(text) {
42
+ await writeFileAtomically(this.dir, this.tempPath(), this.filePath(), new TextEncoder().encode(text));
43
+ }
44
+ filePath() {
45
+ return join(this.dir, `${this.name}.${this.encodedParty}.json`);
46
+ }
47
+ /** Sibling temp path for the atomic replace (random component: collide-free). */
48
+ tempPath() {
49
+ const unique = randomBytes(6).toString('hex');
50
+ return join(this.dir, `${this.name}.${this.encodedParty}.${unique}.tmp`);
51
+ }
52
+ }
53
+ //# sourceMappingURL=file-durable-slot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-durable-slot.js","sourceRoot":"","sources":["../src/file-durable-slot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC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