@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,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
+ }
@@ -1,89 +1,94 @@
1
- /**
2
- * Device-token record helpers: the single source of truth for the bytes a node
3
- * signs when publishing its own `DeviceToken` row and re-verifies when resolving
4
- * another peer's row.
5
- *
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:
12
- *
13
- * digest(new.PeerId || '|' || new.Platform || '|' || new.Token || '|'
14
- * || cast(new.UpdatedAt as text))
15
- *
16
- * 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.
21
- *
22
- * Unlike a peer-address record, a device-token record carries NO public key: the
23
- * signature is verified against the `CadrePeer.PublicKey` bound to the same PeerId
24
- * (the resolver supplies it), so the key binding is checked exactly once, where the
25
- * membership row already lives.
26
- */
27
-
28
- import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
29
- import type { DeviceTokenRecord, PushPlatform } from './types.js';
30
-
31
- /**
32
- * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
33
- * `DeviceToken.AuthorizedUpdate` constraint exactly; both sides take the default
34
- * base64url output of a single `digest(...)`, which round-trips cleanly.
35
- */
36
- 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;
39
- }
40
-
41
- /**
42
- * Sign a device-token record with the ed25519 private key behind its `peerId`.
43
- * Returns a fully-populated {@link DeviceTokenRecord}.
44
- *
45
- * @param fields - the record fields to sign
46
- * @param privateKeyB64 - base64url ed25519 seed (see `ed25519KeyPairFromLibp2p`)
47
- */
48
- export function signDeviceTokenRecord(
49
- fields: Omit<DeviceTokenRecord, 'sig'>,
50
- privateKeyB64: string
51
- ): DeviceTokenRecord {
52
- const payloadDigest = deviceTokenSignedPayload(fields);
53
- const sig = sign(
54
- payloadDigest,
55
- privateKeyB64,
56
- 'ed25519',
57
- 'base64url',
58
- 'base64url',
59
- 'base64url'
60
- ) as string;
61
- return { peerId: fields.peerId, platform: fields.platform, token: fields.token, updatedAt: fields.updatedAt, sig };
62
- }
63
-
64
- /**
65
- * Verify a record's self-signature against the `CadrePeer.PublicKey` (base64url)
66
- * bound to its `peerId`. Reconstructs the signed bytes from the record exactly as
67
- * {@link signDeviceTokenRecord} produced them. Returns false on a missing key/sig or
68
- * any verification failure.
69
- */
70
- export function verifyDeviceTokenSignature(record: DeviceTokenRecord, publicKeyB64: string): boolean {
71
- if (!publicKeyB64 || !record.sig) {
72
- return false;
73
- }
74
- const payloadDigest = deviceTokenSignedPayload(record);
75
- return verify(
76
- payloadDigest,
77
- record.sig,
78
- publicKeyB64,
79
- 'ed25519',
80
- 'base64url',
81
- 'base64url',
82
- 'base64url'
83
- );
84
- }
85
-
86
- /** Narrow an arbitrary stored string to a known {@link PushPlatform}. */
87
- export function isPushPlatform(value: string): value is PushPlatform {
88
- return value === 'fcm' || value === 'apns';
89
- }
1
+ /**
2
+ * Device-token record helpers: the single source of truth for the bytes a node
3
+ * signs when publishing its own `DeviceToken` row and re-verifies when resolving
4
+ * another peer's row.
5
+ *
6
+ * Modeled directly on {@link peerRecordSignedPayload} (peer-record.ts): the signed
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:
13
+ *
14
+ * digest('CadreControl.DeviceToken', 'publish',
15
+ * new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text))
16
+ *
17
+ * Keep {@link deviceTokenSignedPayload} and that constraint byte-for-byte in sync.
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
+ *
22
+ * Unlike a peer-address record, a device-token record carries NO public key: the
23
+ * signature is verified against the `CadrePeer.PublicKey` bound to the same PeerId
24
+ * (the resolver supplies it), so the key binding is checked exactly once, where the
25
+ * membership row already lives.
26
+ */
27
+
28
+ import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
29
+ import { controlAuthorizationFields } from './control-authorization.js';
30
+ import type { DeviceTokenRecord, PushPlatform } from './types.js';
31
+
32
+ /**
33
+ * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
34
+ * `DeviceToken.AuthorizedUpdate` constraint exactly; both sides take the default
35
+ * base64url output of a single `digest(...)`, which round-trips cleanly.
36
+ */
37
+ export function deviceTokenSignedPayload(record: Omit<DeviceTokenRecord, 'sig'>): 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;
44
+ }
45
+
46
+ /**
47
+ * Sign a device-token record with the ed25519 private key behind its `peerId`.
48
+ * Returns a fully-populated {@link DeviceTokenRecord}.
49
+ *
50
+ * @param fields - the record fields to sign
51
+ * @param privateKeyB64 - base64url ed25519 seed (see `ed25519KeyPairFromLibp2p`)
52
+ */
53
+ export function signDeviceTokenRecord(
54
+ fields: Omit<DeviceTokenRecord, 'sig'>,
55
+ privateKeyB64: string
56
+ ): DeviceTokenRecord {
57
+ const payloadDigest = deviceTokenSignedPayload(fields);
58
+ const sig = sign(
59
+ payloadDigest,
60
+ privateKeyB64,
61
+ 'ed25519',
62
+ 'base64url',
63
+ 'base64url',
64
+ 'base64url'
65
+ ) as string;
66
+ return { peerId: fields.peerId, platform: fields.platform, token: fields.token, updatedAt: fields.updatedAt, sig };
67
+ }
68
+
69
+ /**
70
+ * Verify a record's self-signature against the `CadrePeer.PublicKey` (base64url)
71
+ * bound to its `peerId`. Reconstructs the signed bytes from the record exactly as
72
+ * {@link signDeviceTokenRecord} produced them. Returns false on a missing key/sig or
73
+ * any verification failure.
74
+ */
75
+ export function verifyDeviceTokenSignature(record: DeviceTokenRecord, publicKeyB64: string): boolean {
76
+ if (!publicKeyB64 || !record.sig) {
77
+ return false;
78
+ }
79
+ const payloadDigest = deviceTokenSignedPayload(record);
80
+ return verify(
81
+ payloadDigest,
82
+ record.sig,
83
+ publicKeyB64,
84
+ 'ed25519',
85
+ 'base64url',
86
+ 'base64url',
87
+ 'base64url'
88
+ );
89
+ }
90
+
91
+ /** Narrow an arbitrary stored string to a known {@link PushPlatform}. */
92
+ export function isPushPlatform(value: string): value is PushPlatform {
93
+ return value === 'fcm' || value === 'apns';
94
+ }