@serfab/cadre-core 0.9.0 → 0.11.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 (193) hide show
  1. package/README.md +255 -253
  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 +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  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-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Merging verified cadre addresses into a libp2p node's **address book** (its
3
+ * peerStore), so that every layer below cadre-core which dials by bare peer id
4
+ * — Optimystic's cluster client, repo client, FRET ping/announce, all funnelling
5
+ * into `libp2p.dialProtocol(peerId, …)` — has an address to use for a sibling
6
+ * whose connection has dropped, instead of failing with `NoValidAddressesError`
7
+ * until the next reconcile pass happens to re-dial it.
8
+ *
9
+ * Shared by the control-cohort reconcile pass and the strand one (both in
10
+ * `CadreNode`): each resolves a peer's addresses its own way and then needs
11
+ * exactly this write, with exactly this workaround.
12
+ *
13
+ * Two exports, in the order a caller uses them: {@link groupAddrsByPeerId} turns
14
+ * a flat address list into per-peer groups (the strand path starts from the
15
+ * peer-agnostic union the strand-addr RPC returns), and {@link mergePeerAddrs}
16
+ * writes one peer's group.
17
+ */
18
+
19
+ import debug from 'debug';
20
+ import { peerIdFromString } from '@libp2p/peer-id';
21
+ import type { Address, Peer, PeerId, PeerStore, TagOptions } from '@libp2p/interface';
22
+ import { multiaddr, CODE_P2P, CODE_P2P_CIRCUIT, type Multiaddr } from '@multiformats/multiaddr';
23
+
24
+ const log = debug('sereus:cadre:peer-addr-book');
25
+
26
+ /** Outcome of one address-book merge, for logging and tests. */
27
+ export type MergeAddrsResult = 'merged' | 'restamped' | 'skipped' | 'failed';
28
+
29
+ /**
30
+ * The slice of a libp2p node {@link mergePeerAddrs} touches. Structurally
31
+ * satisfied by `Libp2p`; narrow so a caller (or a test) can pass a bare
32
+ * peerStore holder.
33
+ */
34
+ export interface PeerAddrBookHost {
35
+ peerStore: PeerStore;
36
+ }
37
+
38
+ /**
39
+ * Write `addrs` into `host`'s address book for `peerId`, best-effort. `peerId`
40
+ * may be the string form callers hold (a `CadrePeer.PeerId` column, a strand-addr
41
+ * RPC result); parsing it is part of the best-effort contract below, so no caller
42
+ * has to wrap this in a second try/catch of its own.
43
+ *
44
+ * - **Empty `addrs` writes nothing** and reports `'skipped'`. That is how a
45
+ * revoked / stale / untrusted peer's existing entry is allowed to age out on
46
+ * its own: the caller resolves `[]` for it, and nothing here refreshes it.
47
+ * - Otherwise the addresses are merged, and — see the timestamp trap below —
48
+ * re-saved when the merge alone leaves them invisible (`'restamped'`).
49
+ * - Any throw (unparsable peer id, datastore failure, a peerStore double without
50
+ * `merge`) is logged and folded to `'failed'`. Callers are best-effort loops:
51
+ * an address-book failure must never abort a reconcile pass.
52
+ *
53
+ * NOTE: `peerStore.merge` cannot refresh an address's `observed` timestamp in
54
+ * `@libp2p/peer-store` 12.0.10 — `to-peer-pb.js` shadows its own loop variable
55
+ * (`…addresses?.find(addr => uint8ArrayEquals(addr.multiaddr, addr.multiaddr))`,
56
+ * always true, so it returns the FIRST stored address's timestamp), and every
57
+ * read filters out addresses older than `MAX_ADDRESS_AGE` (1 hour). So an entry
58
+ * silently dies at the one-hour mark and no amount of re-merging revives it —
59
+ * not even merging a brand-new address. The `save` below is the workaround:
60
+ * `save` is the one write path that omits `existingPeer` and therefore stamps
61
+ * `Date.now()`. Drop it once upstream stamps `Date.now()` on merge.
62
+ *
63
+ * NOTE: raising the store's own `maxAddressAge` (libp2p forwards `init.peerStore`
64
+ * straight into `persistentPeerStore`) would sidestep the bug in one line, and is
65
+ * deliberately NOT done: expiry is load-bearing here. Only *verified* addresses
66
+ * come through this helper, and the design relies on everything else — the
67
+ * cold-start seed entries, identify-learned addresses — still ageing out on the
68
+ * stock schedule. A global age bump would keep those alive too.
69
+ *
70
+ * NOTE: if the store ever REJECTS an address we hand it, the restamp repeats
71
+ * every pass forever — `allVisible` stays false, and `save` re-submits the same
72
+ * rejected address. libp2p wires the store's `addressFilter` to
73
+ * `connectionGater.filterMultiaddrForPeer`, which nothing in this repo implements
74
+ * today (`createMembershipConnectionGater` gates dials, not addresses), so the
75
+ * loop is unreachable. If an app ever supplies that gater hook via
76
+ * `NetworkConfig.connectionGater`, bound the retry — the cost is one redundant
77
+ * datastore write per gated sibling per reconcile pass.
78
+ */
79
+ export async function mergePeerAddrs(
80
+ host: PeerAddrBookHost,
81
+ peerId: PeerId | string,
82
+ addrs: Multiaddr[]
83
+ ): Promise<MergeAddrsResult> {
84
+ if (addrs.length === 0) {
85
+ return 'skipped';
86
+ }
87
+ try {
88
+ const id = typeof peerId === 'string' ? peerIdFromString(peerId) : peerId;
89
+ const peer = await host.peerStore.merge(id, { multiaddrs: addrs });
90
+ // The returned Peer is already expiry-filtered, so it says whether the merge
91
+ // is actually VISIBLE — which is the only question that matters downstream.
92
+ if (allVisible(peer.addresses, addrs, id)) {
93
+ return 'merged';
94
+ }
95
+ await host.peerStore.save(id, restampData(peer, addrs, id));
96
+ return 'restamped';
97
+ } catch (error) {
98
+ log('mergePeerAddrs: address-book write for %s failed: %o', peerId.toString(), error);
99
+ return 'failed';
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Group multiaddr strings by the peer id in their final `/p2p/` component — the
105
+ * attribution step between a flat, peer-agnostic address list and the per-peer
106
+ * writes {@link mergePeerAddrs} takes.
107
+ *
108
+ * The **last** `/p2p/` component is the addressed peer, not the first: a relayed
109
+ * address (`…/p2p/<relay>/p2p-circuit/p2p/<dst>`) names the relay first and the
110
+ * destination last, while a direct address (`…/tcp/…/p2p/<dst>`) names only the
111
+ * destination. Taking the last therefore attributes both shapes to the peer the
112
+ * address actually reaches.
113
+ *
114
+ * Three shapes are dropped rather than attributed, because none of them names a
115
+ * peer the address reaches: one that does not parse, one carrying no `/p2p/`
116
+ * component at all (a peer advertising a bare listen addr), and one whose
117
+ * `p2p-circuit` comes AFTER its last `/p2p/` (`…/p2p/<relay>/p2p-circuit`) — that
118
+ * last one is a relay hop with the destination missing, so its trailing peer id
119
+ * is the RELAY's and filing it under the relay would claim the relay is reachable
120
+ * at a circuit leading nowhere. Duplicates collapse within a group. Insertion
121
+ * order is preserved, both between groups and inside one.
122
+ */
123
+ export function groupAddrsByPeerId(addrs: string[]): Map<string, Multiaddr[]> {
124
+ const groups = new Map<string, Multiaddr[]>();
125
+ const seen = new Set<string>();
126
+ for (const addr of addrs) {
127
+ const attributed = attributeAddr(addr);
128
+ if (!attributed) {
129
+ continue;
130
+ }
131
+ const key = `${attributed.peerId}\n${addr}`;
132
+ if (seen.has(key)) {
133
+ continue;
134
+ }
135
+ seen.add(key);
136
+ const group = groups.get(attributed.peerId);
137
+ if (group) {
138
+ group.push(attributed.multiaddr);
139
+ } else {
140
+ groups.set(attributed.peerId, [attributed.multiaddr]);
141
+ }
142
+ }
143
+ return groups;
144
+ }
145
+
146
+ /**
147
+ * Parse one address and pull out the peer id it addresses (its last `/p2p/`
148
+ * value); null when the address is unparsable or names no destination. Every case
149
+ * is logged at the same level — an unattributable address is a sibling telling us
150
+ * something we cannot use, which is worth seeing but never worth throwing over.
151
+ */
152
+ function attributeAddr(addr: string): { peerId: string; multiaddr: Multiaddr } | null {
153
+ let parsed: Multiaddr;
154
+ try {
155
+ parsed = multiaddr(addr);
156
+ } catch (error) {
157
+ log('groupAddrsByPeerId: skipping unparsable addr %s: %o', addr, error);
158
+ return null;
159
+ }
160
+ const peerId = lastAddressedPeerId(parsed);
161
+ if (peerId === null) {
162
+ log('groupAddrsByPeerId: skipping addr naming no destination peer: %s', addr);
163
+ return null;
164
+ }
165
+ return { peerId, multiaddr: parsed };
166
+ }
167
+
168
+ /**
169
+ * The peer id a parsed address reaches: its last `/p2p/` value, or null when it
170
+ * has none — or when a `p2p-circuit` sits after it, which makes that value the
171
+ * relay's rather than a destination's (see {@link groupAddrsByPeerId}). Walking
172
+ * backwards, meeting the circuit first is exactly that case.
173
+ */
174
+ function lastAddressedPeerId(parsed: Multiaddr): string | null {
175
+ const components = parsed.getComponents();
176
+ for (let i = components.length - 1; i >= 0; i--) {
177
+ const component = components[i];
178
+ if (component.code === CODE_P2P_CIRCUIT) {
179
+ return null;
180
+ }
181
+ if (component.code === CODE_P2P && component.value) {
182
+ return component.value;
183
+ }
184
+ }
185
+ return null;
186
+ }
187
+
188
+ /**
189
+ * The peerStore strips a trailing `/p2p/<peerId>` from an address it stores when
190
+ * that id is the address's FIRST `/p2p/` component (`dedupe-addresses.js`), so a
191
+ * plain address round-trips without its suffix while a relayed one — whose first
192
+ * `/p2p/` names the relay — keeps it. Comparing and de-duplicating on this
193
+ * suffix-stripped form matches either shape.
194
+ */
195
+ function addrKey(addr: string, peerId: PeerId): string {
196
+ const suffix = `/p2p/${peerId.toString()}`;
197
+ return addr.endsWith(suffix) ? addr.slice(0, -suffix.length) : addr;
198
+ }
199
+
200
+ /** Is every address in `addrs` readable back from the stored, expiry-filtered set? */
201
+ function allVisible(stored: Address[], addrs: Multiaddr[], peerId: PeerId): boolean {
202
+ const keys = new Set(stored.map((a) => addrKey(a.multiaddr.toString(), peerId)));
203
+ return addrs.every((addr) => keys.has(addrKey(addr.toString(), peerId)));
204
+ }
205
+
206
+ /**
207
+ * The full `save` payload for a restamp: `save` re-uses the `patch` strategy with
208
+ * no existing peer, so every field it is not handed is DROPPED — and Optimystic
209
+ * classifies peers by their peerStore protocol list (`libp2p-key-network.ts`
210
+ * `membershipOf`), so losing protocols here would break cluster/repo routing.
211
+ * Everything therefore carries forward from the just-merged `peer`.
212
+ *
213
+ * The read-modify-write is NOT atomic against a concurrent `identify` write to
214
+ * the same entry. The loss window is milliseconds and costs at most one identify
215
+ * update, recovered by the next identify push — not worth a lock.
216
+ *
217
+ * A tag's remaining TTL is not carried: the public `Tag` type exposes only
218
+ * `value`, so the stored expiry is unreadable from here and the tag comes back
219
+ * non-expiring. `publicKey` is likewise not passed, which is lossless for the
220
+ * Ed25519 peer ids a cadre uses (the key is embedded in the id).
221
+ */
222
+ function restampData(peer: Peer, addrs: Multiaddr[], peerId: PeerId): {
223
+ addresses: Address[];
224
+ protocols: string[];
225
+ metadata: Map<string, Uint8Array | undefined>;
226
+ tags: Map<string, TagOptions | undefined>;
227
+ peerRecordEnvelope?: Uint8Array;
228
+ } {
229
+ const addresses = new Map<string, Address>();
230
+ for (const address of peer.addresses) {
231
+ addresses.set(addrKey(address.multiaddr.toString(), peerId), address);
232
+ }
233
+ for (const addr of addrs) {
234
+ const key = addrKey(addr.toString(), peerId);
235
+ if (!addresses.has(key)) {
236
+ // Uncertified, matching what `merge`'s own `multiaddrs` path would have
237
+ // stored; an address already present keeps whatever flag it carried.
238
+ addresses.set(key, { multiaddr: addr, isCertified: false });
239
+ }
240
+ }
241
+ return {
242
+ addresses: [...addresses.values()],
243
+ protocols: peer.protocols,
244
+ metadata: new Map<string, Uint8Array | undefined>(peer.metadata),
245
+ tags: new Map<string, TagOptions | undefined>(
246
+ [...peer.tags].map(([name, tag]) => [name, { value: tag.value }])
247
+ ),
248
+ peerRecordEnvelope: peer.peerRecordEnvelope
249
+ };
250
+ }
@@ -1,81 +1,259 @@
1
- import debug from 'debug';
2
- import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
-
4
- const log = debug('sereus:cadre:peer-authorization');
5
-
6
- /**
7
- * Canonical digest an owner signs to authorize a peer.
8
- *
9
- * This is the exact byte construction {@link SeedBootstrapService.authorizePeer}
10
- * signs over when it inserts an authorized `CadrePeer` row:
11
- * `digest([peerId], 'sha256', 'base64url')`. Factored into one place so the
12
- * producer (owner signing) and the verifier (the offline `cadre enroll
13
- * register` check) can never drift apart — change the digest here and both move
14
- * together. The SQL mirror is the bare single-field `digest(coalesce(new.PeerId, old.PeerId))`.
15
- */
16
- export function peerAuthorizationDigest(peerId: string): string {
17
- return digest([peerId], 'sha256', 'base64url') as string;
18
- }
19
-
20
- /**
21
- * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
22
- * and the owner re-touch update). Binds the peer id to the row's single-use
23
- * `StampId` nonce, so a captured signed insert cannot be replayed (the `StampId` is
24
- * unique) and — because {@link cadrePeerRemoveDigest} scopes a DIFFERENT payload — the
25
- * stored voucher (`VouchSig`) cannot be replayed to authorize a delete.
26
- *
27
- * The SQL mirror is `digest(new.PeerId, new.StampId)` (two TEXT fields), matching the
28
- * canonical multi-field framing in control-database.ts:buildAuthorizationMessage.
29
- */
30
- export function cadrePeerVoucherDigest(peerId: string, stampId: string): string {
31
- return digest([peerId, stampId], 'sha256', 'base64url') as string;
32
- }
33
-
34
- /**
35
- * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
36
- * distinct payload from {@link cadrePeerVoucherDigest} (adds the `'remove'` action
37
- * tag) so the row's stored voucher — a signature over the voucher digest — can never
38
- * satisfy this delete check. The signature is supplied in write context and never
39
- * stored, so no reader can replay it; binding the live row's `StampId` also invalidates
40
- * any captured remove after a delete+reinsert (the nonce rotates).
41
- *
42
- * SQL mirror: `digest(old.PeerId, old.StampId, 'remove')`.
43
- */
44
- export function cadrePeerRemoveDigest(peerId: string, stampId: string): string {
45
- return digest([peerId, stampId, 'remove'], 'sha256', 'base64url') as string;
46
- }
47
-
48
- /**
49
- * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
50
- * authorization digest, using `ownerPublicKey` (base64url).
51
- *
52
- * This is the mirror of the signing done in
53
- * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
54
- * {@link peerAuthorizationDigest}. A `true` result means the holder of the
55
- * owner private key vouched for this peer ID — it does NOT mean the peer is
56
- * registered anywhere.
57
- *
58
- * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
59
- * any crypto failure resolves to `false` (callers want a verdict, not an
60
- * exception). The catch is logged at debug.
61
- */
62
- export function verifyPeerAuthorization(
63
- peerId: string,
64
- ownerPublicKey: string,
65
- signature: string
66
- ): boolean {
67
- try {
68
- return verify(
69
- peerAuthorizationDigest(peerId),
70
- signature,
71
- ownerPublicKey,
72
- 'ed25519',
73
- 'base64url',
74
- 'base64url',
75
- 'base64url'
76
- );
77
- } catch (error) {
78
- log('verifyPeerAuthorization failed: %o', error);
79
- return false;
80
- }
81
- }
1
+ import debug from 'debug';
2
+ import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
+ import { controlAuthorizationFields } from './control-authorization.js';
4
+ import type { ControlAction, ControlDomain, RevocableTable } from './control-authorization.js';
5
+
6
+ const log = debug('sereus:cadre:peer-authorization');
7
+
8
+ /**
9
+ * base64url SHA-256 digest over the shared domain-tagged field vector (see
10
+ * control-authorization.ts). The base64url twin of
11
+ * control-database.ts:buildAuthorizationMessage (which returns the same digest as raw
12
+ * bytes): sign either encoding with input encoding to match and the signed bytes agree.
13
+ */
14
+ function taggedDigest(domain: ControlDomain, action: ControlAction, rowFields: string[]): string {
15
+ return digest(controlAuthorizationFields(domain, action, rowFields), 'sha256', 'base64url') as string;
16
+ }
17
+
18
+ /**
19
+ * Canonical digest an owner signs to vouch a peer's ENROLLMENT — the offline
20
+ * credential `cadre enroll register` verifies. No table checks this digest, so it
21
+ * carries its own `'Cadre.Enrollment'` domain tag to stay disjoint from every
22
+ * CadreControl table rule (pre-tag it collided with the `DeviceToken` owner digests,
23
+ * so an enrollment vouch doubled as a push-token delete approval).
24
+ *
25
+ * Factored into one place so the producer (owner signing) and the verifier (the
26
+ * offline `cadre enroll register` check) can never drift apart — change the digest
27
+ * here and both move together.
28
+ */
29
+ export function peerAuthorizationDigest(peerId: string): string {
30
+ return taggedDigest('Cadre.Enrollment', 'vouch', [peerId]);
31
+ }
32
+
33
+ /**
34
+ * The `CadreControl.DeviceToken` columns {@link deviceTokenAddDigest} binds, in the
35
+ * schema's order. A whole-row struct rather than six positional strings, so a caller
36
+ * cannot silently transpose `platform` and `token` (both opaque strings) and mint a
37
+ * signature over a row it did not mean to approve.
38
+ *
39
+ * Structurally satisfied by a `DeviceTokenRecord` spread with the row's `stampId`;
40
+ * `types.ts:DeviceTokenRecord` deliberately does NOT carry the stamp — it is the
41
+ * SELF-signed record shape, and the peer's own `Sig` does not cover `StampId`.
42
+ * `updatedAt` / `sig` are nullable because the columns are: both sign as `''` when
43
+ * absent, mirroring the schema's `coalesce(...)`.
44
+ */
45
+ export interface DeviceTokenAuthorizedRow {
46
+ peerId: string;
47
+ platform: string;
48
+ token: string;
49
+ updatedAt: number | null;
50
+ sig: string | null;
51
+ stampId: string;
52
+ }
53
+
54
+ /**
55
+ * Canonical digest an owner signs to authorize a `DeviceToken` INSERT — the WHOLE row,
56
+ * ending in its single-use `StampId` nonce. SQL mirror:
57
+ * `digest('CadreControl.DeviceToken', 'add', new.PeerId, new.Platform, new.Token,
58
+ * coalesce(cast(new.UpdatedAt as text), ''), coalesce(new.Sig, ''), new.StampId)` in
59
+ * `DeviceToken.AuthorizedInsert`.
60
+ *
61
+ * Binding every column means a captured approval can only ever reproduce the exact row
62
+ * it approved — never one carrying attacker-chosen `Platform`/`Token`/`UpdatedAt` — and
63
+ * binding the stamp makes it single-use: while the row lives the `unique` column blocks
64
+ * a replay, and after a clear the stamp is retired permanently into
65
+ * `CadreControl.Revocation` (`DeviceToken.NotRevoked`). This matters more here than for
66
+ * `CadrePeer`: a resurrected push token has NO freshness ceiling to retire it
67
+ * (`CadreNode.resolveDeviceToken` defaults `maxAgeMs` to infinity by design), so stamp
68
+ * retirement is the only thing that sticks.
69
+ *
70
+ * Distinct from {@link deviceTokenRemoveDigest} so a captured insert approval can never
71
+ * be replayed to delete the token, and vice versa.
72
+ */
73
+ export function deviceTokenAddDigest(row: DeviceTokenAuthorizedRow): string {
74
+ return taggedDigest('CadreControl.DeviceToken', 'add', [
75
+ row.peerId,
76
+ row.platform,
77
+ row.token,
78
+ row.updatedAt === null ? '' : String(row.updatedAt),
79
+ row.sig ?? '',
80
+ row.stampId,
81
+ ]);
82
+ }
83
+
84
+ /**
85
+ * Canonical digest an owner signs to authorize a `DeviceToken` DELETE, bound to the
86
+ * STORED row's (PeerId, StampId). SQL mirror:
87
+ * `digest('CadreControl.DeviceToken', 'remove', old.PeerId, old.StampId)` in
88
+ * `DeviceToken.AuthorizedDelete`.
89
+ *
90
+ * A narrower vector than {@link deviceTokenAddDigest} on purpose (the same split
91
+ * `CadrePeer` makes): the clear approval names only which row is being retired, so it
92
+ * cannot be re-cut into an insert approval, and it is dead the moment the stamp it
93
+ * names is tombstoned.
94
+ */
95
+ export function deviceTokenRemoveDigest(peerId: string, stampId: string): string {
96
+ return taggedDigest('CadreControl.DeviceToken', 'remove', [peerId, stampId]);
97
+ }
98
+
99
+ /**
100
+ * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
101
+ * and the owner re-touch update — same semantics, deliberately the same digest).
102
+ * Binds the peer id to the row's single-use `StampId` nonce, so a captured signed
103
+ * insert cannot be replayed — while the row lives the `unique` column blocks it, and
104
+ * after a removal the stamp is retired permanently into `CadreControl.Revocation`
105
+ * (`CadrePeer.NotRevoked`) — and, because {@link cadrePeerRemoveDigest} scopes a
106
+ * DIFFERENT payload, the stored voucher (`VouchSig`) cannot be replayed to authorize
107
+ * a delete. The domain tag keeps the stored, replicated `VouchSig` useless against
108
+ * every OTHER table's rules.
109
+ *
110
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId)`.
111
+ */
112
+ export function cadrePeerVoucherDigest(peerId: string, stampId: string): string {
113
+ return taggedDigest('CadreControl.CadrePeer', 'vouch', [peerId, stampId]);
114
+ }
115
+
116
+ /**
117
+ * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
118
+ * distinct payload from {@link cadrePeerVoucherDigest} (the `'remove'` action tag)
119
+ * so the row's stored voucher — a signature over the voucher digest — can never
120
+ * satisfy this delete check. The signature is supplied in write context and never
121
+ * stored, so no reader can replay it; a captured remove is also dead after the
122
+ * delete lands, because a re-added row carries a FRESH `StampId` (the removed row's
123
+ * stamp is retired into `CadreControl.Revocation` and never reused).
124
+ *
125
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'remove', old.PeerId, old.StampId)`.
126
+ */
127
+ export function cadrePeerRemoveDigest(peerId: string, stampId: string): string {
128
+ return taggedDigest('CadreControl.CadrePeer', 'remove', [peerId, stampId]);
129
+ }
130
+
131
+ /**
132
+ * Canonical digest an owner signs to APPEND a `CadreControl.Revocation` tombstone —
133
+ * the row retiring `stampId` for the named guarded table, and recording `rowKey`
134
+ * (the removed row's primary key: OwnerKey.Key / ValidationKey.Key /
135
+ * CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id) as which row was retired.
136
+ * SQL mirror:
137
+ * `digest('CadreControl.Revocation', 'remove', new.TableName, new.RowKey, new.StampId)`
138
+ * in `Revocation.Authorized`.
139
+ *
140
+ * Its own `'CadreControl.Revocation'` domain tag makes it disjoint from the
141
+ * `'CadreControl.CadrePeer'` (or `OwnerKey` / `ValidationKey` / `Strand`)
142
+ * `'remove'` digest the same owner signs in the SAME transaction for the delete
143
+ * this tombstone accompanies — a removal signature is not a retirement
144
+ * signature and cannot be replayed as one.
145
+ */
146
+ export function revocationDigest(tableName: RevocableTable, rowKey: string, stampId: string): string {
147
+ return taggedDigest('CadreControl.Revocation', 'remove', [tableName, rowKey, stampId]);
148
+ }
149
+
150
+ /**
151
+ * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
152
+ * authorization digest, using `ownerPublicKey` (base64url).
153
+ *
154
+ * This is the mirror of the signing done in
155
+ * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
156
+ * {@link peerAuthorizationDigest}. A `true` result means the holder of the
157
+ * owner private key vouched for this peer ID — it does NOT mean the peer is
158
+ * registered anywhere.
159
+ *
160
+ * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
161
+ * any crypto failure resolves to `false` (callers want a verdict, not an
162
+ * exception). The catch is logged at debug.
163
+ */
164
+ export function verifyPeerAuthorization(
165
+ peerId: string,
166
+ ownerPublicKey: string,
167
+ signature: string
168
+ ): boolean {
169
+ try {
170
+ return verify(
171
+ peerAuthorizationDigest(peerId),
172
+ signature,
173
+ ownerPublicKey,
174
+ 'ed25519',
175
+ 'base64url',
176
+ 'base64url',
177
+ 'base64url'
178
+ );
179
+ } catch (error) {
180
+ log('verifyPeerAuthorization failed: %o', error);
181
+ return false;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Verify that `signature` is a valid owner ed25519 signature over the
187
+ * `CadrePeer` voucher digest for (`peerId`, `stampId`) — the read-side mirror
188
+ * of the voucher {@link ControlDatabase.insertCadrePeer} signs and persists into
189
+ * `VouchOwner`/`VouchSig` (see {@link cadrePeerVoucherDigest}).
190
+ *
191
+ * A `true` result means the holder of `ownerPublicKey` vouched THIS membership
192
+ * row (the peer id bound to the row's single-use `StampId` nonce). It says
193
+ * nothing about whether that owner key is itself trustworthy — the caller must
194
+ * separately check the key against the node-local trusted-owner anchor
195
+ * (`TrustedOwnerStore`), never the replicated `OwnerKey` table.
196
+ *
197
+ * Returns a boolean and never throws (same contract as
198
+ * {@link verifyPeerAuthorization}): malformed input or any crypto failure
199
+ * resolves to `false`, logged at debug.
200
+ */
201
+ export function verifyCadrePeerVoucher(
202
+ peerId: string,
203
+ stampId: string,
204
+ ownerPublicKey: string,
205
+ signature: string
206
+ ): boolean {
207
+ try {
208
+ return verify(
209
+ cadrePeerVoucherDigest(peerId, stampId),
210
+ signature,
211
+ ownerPublicKey,
212
+ 'ed25519',
213
+ 'base64url',
214
+ 'base64url',
215
+ 'base64url'
216
+ );
217
+ } catch (error) {
218
+ log('verifyCadrePeerVoucher failed: %o', error);
219
+ return false;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Canonical digest a JOINING peer signs to consent to ONE `FormationUsage`
225
+ * redemption — the read-side mirror of `formationConsentMessage` in
226
+ * control-database.ts, base64url-encoded instead of raw bytes (see
227
+ * {@link taggedDigest}). That doc comment carries the field-vector rationale
228
+ * (notably why `strandId` is not signed); the two vectors must not drift, which
229
+ * peer-authorization.spec.ts pins by signing one form and verifying the other.
230
+ */
231
+ export function formationConsentDigest(
232
+ token: string, usageStampId: string, peerKey: string, disclosure: string
233
+ ): string {
234
+ return taggedDigest('CadreControl.FormationUsage', 'consent', [token, usageStampId, peerKey, disclosure]);
235
+ }
236
+
237
+ /**
238
+ * Verify that `row.peerSig` is a valid ed25519 signature over the joining peer's
239
+ * consent digest (see {@link formationConsentDigest}) — the row's OWN `peerKey`.
240
+ *
241
+ * Unlike {@link verifyCadrePeerVoucher} there is no separate enrolled/owner row to
242
+ * look up: the identity IS the key carried on the row, so a forged consent would
243
+ * need that joiner's own private key. Returns a boolean and never throws (same
244
+ * contract as the siblings above): malformed input or any crypto failure resolves
245
+ * to `false`, logged at debug.
246
+ */
247
+ export function verifyFormationConsent(row: {
248
+ token: string; usageStampId: string; peerKey: string; disclosure: string; peerSig: string;
249
+ }): boolean {
250
+ try {
251
+ return verify(
252
+ formationConsentDigest(row.token, row.usageStampId, row.peerKey, row.disclosure),
253
+ row.peerSig, row.peerKey, 'ed25519', 'base64url', 'base64url', 'base64url'
254
+ );
255
+ } catch (error) {
256
+ log('verifyFormationConsent failed: %o', error);
257
+ return false;
258
+ }
259
+ }