@serfab/cadre-core 0.7.1 → 0.8.1
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.
- package/README.md +9 -8
- package/dist/authority-key.d.ts +41 -0
- package/dist/authority-key.js +52 -0
- package/dist/authority-key.js.map +1 -0
- package/dist/cadre-node.d.ts +770 -11
- package/dist/cadre-node.js +1900 -88
- package/dist/cadre-node.js.map +1 -1
- package/dist/canonical-datetime.d.ts +33 -0
- package/dist/canonical-datetime.js +38 -0
- package/dist/canonical-datetime.js.map +1 -0
- package/dist/canonical-json.d.ts +12 -0
- package/dist/canonical-json.js +33 -0
- package/dist/canonical-json.js.map +1 -0
- package/dist/control-cohort.d.ts +63 -0
- package/dist/control-cohort.js +80 -0
- package/dist/control-cohort.js.map +1 -0
- package/dist/control-database.d.ts +259 -5
- package/dist/control-database.js +541 -128
- package/dist/control-database.js.map +1 -1
- package/dist/control-formation-recorder.d.ts +89 -0
- package/dist/control-formation-recorder.js +139 -0
- package/dist/control-formation-recorder.js.map +1 -0
- package/dist/control-schema.d.ts +12 -0
- package/dist/control-schema.js +199 -0
- package/dist/control-schema.js.map +1 -0
- package/dist/control-stream.d.ts +54 -0
- package/dist/control-stream.js +104 -0
- package/dist/control-stream.js.map +1 -0
- package/dist/device-token.d.ts +50 -0
- package/dist/device-token.js +66 -0
- package/dist/device-token.js.map +1 -0
- package/dist/diagnostics/connection-path.d.ts +118 -0
- package/dist/diagnostics/connection-path.js +204 -0
- package/dist/diagnostics/connection-path.js.map +1 -0
- package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
- package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
- package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
- package/dist/hibernation-manager.d.ts +79 -0
- package/dist/hibernation-manager.js +173 -23
- package/dist/hibernation-manager.js.map +1 -1
- package/dist/index.d.ts +25 -4
- package/dist/index.js +59 -4
- package/dist/index.js.map +1 -1
- package/dist/key-store-file.d.ts +52 -0
- package/dist/key-store-file.js +194 -0
- package/dist/key-store-file.js.map +1 -0
- package/dist/key-store.d.ts +75 -0
- package/dist/key-store.js +66 -0
- package/dist/key-store.js.map +1 -0
- package/dist/peer-authorization.d.ts +26 -0
- package/dist/peer-authorization.js +40 -0
- package/dist/peer-authorization.js.map +1 -0
- package/dist/peer-record.d.ts +89 -0
- package/dist/peer-record.js +117 -0
- package/dist/peer-record.js.map +1 -0
- package/dist/push-credentials.d.ts +34 -0
- package/dist/push-credentials.js +81 -0
- package/dist/push-credentials.js.map +1 -0
- package/dist/push-fanout.d.ts +137 -0
- package/dist/push-fanout.js +197 -0
- package/dist/push-fanout.js.map +1 -0
- package/dist/push-notifier-apns.d.ts +53 -0
- package/dist/push-notifier-apns.js +195 -0
- package/dist/push-notifier-apns.js.map +1 -0
- package/dist/push-notifier-fcm.d.ts +38 -0
- package/dist/push-notifier-fcm.js +183 -0
- package/dist/push-notifier-fcm.js.map +1 -0
- package/dist/push-notifier-shared.d.ts +18 -0
- package/dist/push-notifier-shared.js +25 -0
- package/dist/push-notifier-shared.js.map +1 -0
- package/dist/push-notifier.d.ts +71 -0
- package/dist/push-notifier.js +50 -0
- package/dist/push-notifier.js.map +1 -0
- package/dist/schema-verification.d.ts +11 -2
- package/dist/schema-verification.js +15 -4
- package/dist/schema-verification.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +197 -9
- package/dist/seed-bootstrap.js +396 -137
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/seed-trust-policy.d.ts +63 -0
- package/dist/seed-trust-policy.js +56 -0
- package/dist/seed-trust-policy.js.map +1 -0
- package/dist/strand-addr-protocol.d.ts +132 -0
- package/dist/strand-addr-protocol.js +313 -0
- package/dist/strand-addr-protocol.js.map +1 -0
- package/dist/strand-cohort.d.ts +54 -0
- package/dist/strand-cohort.js +38 -0
- package/dist/strand-cohort.js.map +1 -0
- package/dist/strand-database.d.ts +54 -6
- package/dist/strand-database.js +88 -100
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-formation-manager.d.ts +79 -19
- package/dist/strand-formation-manager.js +196 -104
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +162 -0
- package/dist/strand-formation-protocol.js +279 -0
- package/dist/strand-formation-protocol.js.map +1 -0
- package/dist/strand-instance-manager.d.ts +73 -4
- package/dist/strand-instance-manager.js +167 -41
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-member-key.d.ts +29 -0
- package/dist/strand-member-key.js +38 -0
- package/dist/strand-member-key.js.map +1 -0
- package/dist/strand-member-registry.d.ts +98 -0
- package/dist/strand-member-registry.js +129 -0
- package/dist/strand-member-registry.js.map +1 -0
- package/dist/strand-membership-writer.d.ts +361 -0
- package/dist/strand-membership-writer.js +449 -0
- package/dist/strand-membership-writer.js.map +1 -0
- package/dist/strand-solicitation.d.ts +77 -2
- package/dist/strand-solicitation.js +25 -4
- package/dist/strand-solicitation.js.map +1 -1
- package/dist/strand-wake-payload.d.ts +30 -0
- package/dist/strand-wake-payload.js +20 -0
- package/dist/strand-wake-payload.js.map +1 -0
- package/dist/strand-wake-protocol.d.ts +114 -0
- package/dist/strand-wake-protocol.js +257 -0
- package/dist/strand-wake-protocol.js.map +1 -0
- package/dist/strand-watcher.d.ts +6 -2
- package/dist/strand-watcher.js +57 -17
- package/dist/strand-watcher.js.map +1 -1
- package/dist/types.d.ts +406 -23
- package/dist/types.js +22 -5
- package/dist/types.js.map +1 -1
- package/package.json +14 -8
- package/src/authority-key.ts +68 -0
- package/src/cadre-node.ts +2937 -948
- package/src/canonical-datetime.ts +39 -0
- package/src/canonical-json.ts +30 -0
- package/src/control-cohort.ts +103 -0
- package/src/control-database.ts +931 -383
- package/src/control-formation-recorder.ts +151 -0
- package/src/control-schema.ts +198 -0
- package/src/control-stream.ts +128 -0
- package/src/device-token.ts +89 -0
- package/src/diagnostics/connection-path.ts +277 -0
- package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
- package/src/hibernation-manager.ts +197 -28
- package/src/index.ts +273 -79
- package/src/key-store-file.ts +203 -0
- package/src/key-store.ts +99 -0
- package/src/peer-authorization.ts +53 -0
- package/src/peer-record.ts +146 -0
- package/src/push-credentials.ts +84 -0
- package/src/push-fanout.ts +272 -0
- package/src/push-notifier-apns.ts +243 -0
- package/src/push-notifier-fcm.ts +221 -0
- package/src/push-notifier-shared.ts +28 -0
- package/src/push-notifier.ts +93 -0
- package/src/schema-verification.ts +18 -4
- package/src/seed-bootstrap.ts +464 -188
- package/src/seed-trust-policy.ts +107 -0
- package/src/strand-addr-protocol.ts +410 -0
- package/src/strand-cohort.ts +77 -0
- package/src/strand-database.ts +113 -141
- package/src/strand-formation-manager.ts +233 -142
- package/src/strand-formation-protocol.ts +391 -0
- package/src/strand-instance-manager.ts +207 -56
- package/src/strand-member-key.ts +39 -0
- package/src/strand-member-registry.ts +177 -0
- package/src/strand-membership-writer.ts +640 -0
- package/src/strand-solicitation.ts +93 -4
- package/src/strand-wake-payload.ts +32 -0
- package/src/strand-wake-protocol.ts +331 -0
- package/src/strand-watcher.ts +61 -17
- package/src/types.ts +1012 -582
package/dist/seed-bootstrap.js
CHANGED
|
@@ -3,24 +3,96 @@ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } fr
|
|
|
3
3
|
import { digest, sign, verify, getPublicKey } from '@optimystic/quereus-plugin-crypto';
|
|
4
4
|
import { multiaddr } from '@multiformats/multiaddr';
|
|
5
5
|
import { peerIdFromString } from '@libp2p/peer-id';
|
|
6
|
+
import { writeFrame, readStreamToEnd } from './control-stream.js';
|
|
7
|
+
import { canonicalJson } from './canonical-json.js';
|
|
8
|
+
import { peerAuthorizationDigest } from './peer-authorization.js';
|
|
9
|
+
import { dbAnchoredTrustPolicy, } from './seed-trust-policy.js';
|
|
6
10
|
const log = debug('sereus:cadre:seed-bootstrap');
|
|
7
11
|
/** Protocol ID for seed delivery */
|
|
8
12
|
export const SEED_PROTOCOL = '/sereus/seed/1.0.0';
|
|
9
13
|
/** Maximum seed message size (1MB) */
|
|
10
14
|
const MAX_SEED_SIZE = 1024 * 1024;
|
|
15
|
+
/** Default time the receiver waits for an inbound seed frame before aborting (ms). */
|
|
16
|
+
const DEFAULT_SEED_READ_TIMEOUT_MS = 10000;
|
|
17
|
+
/** Default cap on concurrent inbound seed streams a single peer can pin open. */
|
|
18
|
+
const DEFAULT_MAX_CONCURRENT_SEEDS = 100;
|
|
19
|
+
/**
|
|
20
|
+
* Decode a 4-byte big-endian length-prefixed frame; returns the body bytes.
|
|
21
|
+
*
|
|
22
|
+
* Guards every parse site against malformed input: a buffer too short to hold
|
|
23
|
+
* the prefix, a declared length exceeding `maxLength`, and a declared length
|
|
24
|
+
* exceeding the bytes actually present. Returns a view (`subarray`, no copy) —
|
|
25
|
+
* the body is handed straight to `TextDecoder`.
|
|
26
|
+
*/
|
|
27
|
+
export function decodeLengthPrefixedFrame(data, maxLength = MAX_SEED_SIZE) {
|
|
28
|
+
if (data.length < 4) {
|
|
29
|
+
throw new Error(`Seed frame too short: ${data.length} bytes, need ≥4 for length prefix`);
|
|
30
|
+
}
|
|
31
|
+
// Pass the full (buffer, byteOffset, byteLength) triple so the read is correct
|
|
32
|
+
// even for a non-zero-offset view, not just the fresh zero-offset arrays
|
|
33
|
+
// current callers pass.
|
|
34
|
+
const length = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(0, false);
|
|
35
|
+
const available = data.length - 4;
|
|
36
|
+
if (length > maxLength) {
|
|
37
|
+
throw new Error(`Seed frame declares length ${length} exceeding max ${maxLength}`);
|
|
38
|
+
}
|
|
39
|
+
if (length > available) {
|
|
40
|
+
throw new Error(`Seed frame declares length ${length} but only ${available} body bytes present`);
|
|
41
|
+
}
|
|
42
|
+
return data.subarray(4, 4 + length);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Derive the base64url ed25519 public key embedded in an Ed25519 libp2p PeerId.
|
|
46
|
+
*
|
|
47
|
+
* An Ed25519 PeerId is an identity multihash of the public key, so
|
|
48
|
+
* `peerIdFromString(id).publicKey.raw` is the 32-byte ed25519 key whose
|
|
49
|
+
* base64url form matches the `AuthorityKey.Key` representation (and
|
|
50
|
+
* `authorityKeyFromLibp2p().publicKeyB64`). Returns null for a non-Ed25519
|
|
51
|
+
* id, a missing embedded key, or any parse failure — callers treat null as
|
|
52
|
+
* "not an authority" rather than throwing.
|
|
53
|
+
*/
|
|
54
|
+
export function ed25519PublicKeyB64FromPeerId(peerId) {
|
|
55
|
+
try {
|
|
56
|
+
const parsed = peerIdFromString(peerId);
|
|
57
|
+
if (parsed.type !== 'Ed25519' || !parsed.publicKey) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return uint8ArrayToString(parsed.publicKey.raw, 'base64url');
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Canonical byte representation of the authenticated seed fields.
|
|
68
|
+
*
|
|
69
|
+
* Routes both the creator (`createSeed`) and the verifier
|
|
70
|
+
* (`validateSeedSignature`) through one builder so the signed bytes are
|
|
71
|
+
* identical regardless of key insertion order. `canonicalJson` sorts keys and
|
|
72
|
+
* drops `undefined`, so the signed payload is exactly `{ partyId, peers }` —
|
|
73
|
+
* the fields the producer actually emits.
|
|
74
|
+
*/
|
|
75
|
+
export function canonicalSeedPayload(seed) {
|
|
76
|
+
return canonicalJson({ partyId: seed.partyId, peers: seed.peers });
|
|
77
|
+
}
|
|
11
78
|
/**
|
|
12
79
|
* SeedBootstrapService handles control network seed generation and delivery.
|
|
13
80
|
*
|
|
14
81
|
* Seeds solve the cold-start problem: new nodes need control data to validate
|
|
15
82
|
* connections, but can't get data without connecting first. Seeds pre-populate
|
|
16
|
-
* the new node's cache with peer information
|
|
83
|
+
* the new node's cache with peer information.
|
|
17
84
|
*/
|
|
18
85
|
export class SeedBootstrapService {
|
|
19
86
|
constructor(config) {
|
|
20
87
|
this.libp2pNode = null;
|
|
21
88
|
this.controlDatabase = null;
|
|
89
|
+
/** In-flight inbound seed streams, used to enforce {@link maxConcurrentSeeds}. */
|
|
90
|
+
this.activeStreams = 0;
|
|
22
91
|
this.eventCallbacks = {};
|
|
23
92
|
this.config = config;
|
|
93
|
+
this.trustPolicy = config.trustPolicy ?? dbAnchoredTrustPolicy();
|
|
94
|
+
this.seedReadTimeoutMs = config.seedReadTimeoutMs ?? DEFAULT_SEED_READ_TIMEOUT_MS;
|
|
95
|
+
this.maxConcurrentSeeds = config.maxConcurrentSeeds ?? DEFAULT_MAX_CONCURRENT_SEEDS;
|
|
24
96
|
// Derive public key from private key if not provided
|
|
25
97
|
if (config.authorityPrivateKey && !config.authorityPublicKey) {
|
|
26
98
|
this.authorityPublicKey = getPublicKey(config.authorityPrivateKey, 'ed25519', 'base64url', 'base64url');
|
|
@@ -38,59 +110,171 @@ export class SeedBootstrapService {
|
|
|
38
110
|
this.eventCallbacks = callbacks;
|
|
39
111
|
}
|
|
40
112
|
/**
|
|
41
|
-
*
|
|
113
|
+
* Whether this service holds an authority private key, i.e. can produce the
|
|
114
|
+
* authority signatures that gate `CadrePeer` / `DeviceToken` inserts, deletes,
|
|
115
|
+
* and re-authorizations. A seed-listener-only service (`enableSeedListener`,
|
|
116
|
+
* no authority key) returns false: it can receive/apply seeds but cannot author
|
|
117
|
+
* or re-issue authority writes. Used by the write-while-alone re-replication
|
|
118
|
+
* drain to skip authority work on a non-authority node.
|
|
119
|
+
*/
|
|
120
|
+
canAuthorize() {
|
|
121
|
+
return !!this.config.authorityPrivateKey;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Initialize the service with libp2p node and control database.
|
|
125
|
+
*
|
|
126
|
+
* `registerHandler` (default true) gates registration of the shared inbound
|
|
127
|
+
* `/sereus/seed/1.0.0` handler on `libp2pNode`. Persistent services
|
|
128
|
+
* (`initializeSeedBootstrap`, `enableSeedListener`) own that handler and leave
|
|
129
|
+
* it on. The throwaway temp services CadreNode builds in `applySeed` /
|
|
130
|
+
* `dialInvite` pass `false`: they only need the stored `libp2pNode` /
|
|
131
|
+
* `controlDatabase` for dialing and known-key lookup, and must NOT bind a
|
|
132
|
+
* discarded closure to the shared node (a handler leak, and a second
|
|
133
|
+
* `handle()` of the same protocol throws `DuplicateProtocolHandlerError`).
|
|
42
134
|
*/
|
|
43
|
-
initialize(libp2pNode, controlDatabase) {
|
|
135
|
+
initialize(libp2pNode, controlDatabase, options) {
|
|
44
136
|
this.libp2pNode = libp2pNode;
|
|
45
137
|
this.controlDatabase = controlDatabase;
|
|
46
|
-
// Register the seed protocol handler
|
|
47
|
-
|
|
138
|
+
// Register the seed protocol handler unless the caller opted out (temp services).
|
|
139
|
+
if (options?.registerHandler ?? true) {
|
|
140
|
+
this.registerProtocolHandler();
|
|
141
|
+
}
|
|
48
142
|
log('SeedBootstrapService initialized');
|
|
49
143
|
}
|
|
50
144
|
/**
|
|
51
145
|
* Authorize a new peer to join the cadre.
|
|
52
146
|
* Signs the peer ID with the authority key and inserts into CadrePeer table.
|
|
147
|
+
*
|
|
148
|
+
* The authority vouches the `PublicKey <-> PeerId` binding: rather than trust a
|
|
149
|
+
* caller-supplied key, the binding is enforced by construction — `PublicKey` is
|
|
150
|
+
* DERIVED from the (Ed25519) `peerId`. A non-Ed25519 peer id yields a null
|
|
151
|
+
* `PublicKey`, and such a row can never be self-updated (it has no key to
|
|
152
|
+
* verify against), which is correct. The row is inserted with a fresh
|
|
153
|
+
* `UpdatedAt` but no self-signature (`Sig` null) — the authority cannot produce
|
|
154
|
+
* the peer's self-signature, so the peer must self-publish (see
|
|
155
|
+
* {@link CadreNode.registerSelf}) before the row resolves.
|
|
53
156
|
*/
|
|
54
157
|
async authorizePeer(options) {
|
|
55
158
|
const { peerId, multiaddrs } = options;
|
|
56
|
-
|
|
57
|
-
|
|
159
|
+
log('Authorizing peer: %s', peerId);
|
|
160
|
+
// CadrePeer.Multiaddr stores a comma-joined list; use '' when no addrs provided.
|
|
161
|
+
const multiaddrStr = multiaddrs?.length ? multiaddrs.join(',') : '';
|
|
162
|
+
await this.insertCadrePeerRow({
|
|
163
|
+
peerId,
|
|
164
|
+
publicKey: ed25519PublicKeyB64FromPeerId(peerId),
|
|
165
|
+
multiaddr: multiaddrStr,
|
|
166
|
+
updatedAt: Date.now(),
|
|
167
|
+
sig: null,
|
|
168
|
+
});
|
|
169
|
+
log('Peer %s authorized successfully', peerId);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Authority-signed INSERT of this node's OWN self-signed address record.
|
|
173
|
+
*
|
|
174
|
+
* Used by {@link CadreNode.registerSelf} when the node is not yet a member and
|
|
175
|
+
* is its own authority (it holds the authority key): the row is authority-signed
|
|
176
|
+
* (satisfying `AuthorizedInsert`) AND carries a valid self-`Sig`, so it resolves
|
|
177
|
+
* immediately without a follow-up self-update.
|
|
178
|
+
*/
|
|
179
|
+
async insertSelfPeerRecord(record) {
|
|
180
|
+
await this.insertCadrePeerRow({
|
|
181
|
+
peerId: record.peerId,
|
|
182
|
+
publicKey: record.publicKey,
|
|
183
|
+
multiaddr: record.addrs.join(','),
|
|
184
|
+
updatedAt: record.updatedAt,
|
|
185
|
+
sig: record.sig,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Shared authority-signed `CadrePeer` INSERT. Signs `digest(peerId)` with the
|
|
190
|
+
* authority key (satisfying `AuthorizedInsert`) and writes the full record
|
|
191
|
+
* row. The authority signature does NOT cover the address columns — those are
|
|
192
|
+
* vouched only as far as the authority asserts them, and a peer's own `Sig`
|
|
193
|
+
* (when present) is what makes the row resolvable.
|
|
194
|
+
*/
|
|
195
|
+
async insertCadrePeerRow(row) {
|
|
196
|
+
const signature = this.signPeerAuthorization(row.peerId);
|
|
197
|
+
if (!this.controlDatabase) {
|
|
198
|
+
throw new Error('Control database not initialized');
|
|
58
199
|
}
|
|
200
|
+
const db = this.controlDatabase.getDatabase();
|
|
201
|
+
await db.exec(`
|
|
202
|
+
insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig)
|
|
203
|
+
with context AuthorityKey = ?, Signature = ?
|
|
204
|
+
values (?, ?, ?, ?, ?)
|
|
205
|
+
`, [this.authorityPublicKey, signature, row.peerId, row.publicKey, row.multiaddr, row.updatedAt, row.sig]);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Authority-signed INSERT of a peer's OWN self-signed `DeviceToken` row.
|
|
209
|
+
*
|
|
210
|
+
* Counterpart to {@link insertSelfPeerRecord} for the device-token registry: the
|
|
211
|
+
* row is authority-signed (satisfying `DeviceToken.AuthorizedInsert`, which vouches
|
|
212
|
+
* membership exactly as `CadrePeer.AuthorizedInsert` does) AND carries the peer's
|
|
213
|
+
* own self-`Sig` over the token payload. The authority signature covers only the
|
|
214
|
+
* PeerId — it does NOT vouch the token contents; the peer's `Sig` (verified at
|
|
215
|
+
* resolve time against the bound `CadrePeer.PublicKey`) is what makes the row
|
|
216
|
+
* resolvable. Used by {@link CadreNode.registerDeviceToken} for the first publish
|
|
217
|
+
* when the node is its own authority.
|
|
218
|
+
*/
|
|
219
|
+
async insertSelfDeviceToken(record) {
|
|
220
|
+
const signature = this.signPeerAuthorization(record.peerId);
|
|
59
221
|
if (!this.controlDatabase) {
|
|
60
222
|
throw new Error('Control database not initialized');
|
|
61
223
|
}
|
|
62
|
-
log('Authorizing peer: %s', peerId);
|
|
63
|
-
// Sign the peer ID with the authority key
|
|
64
|
-
const peerIdDigest = digest(peerId, 'sha256', 'utf8', 'base64url');
|
|
65
|
-
const signature = sign(peerIdDigest, this.config.authorityPrivateKey, 'ed25519', 'base64url', 'base64url', 'base64url');
|
|
66
|
-
// Insert into CadrePeer table with authority context
|
|
67
224
|
const db = this.controlDatabase.getDatabase();
|
|
68
|
-
// CadrePeer.Multiaddr is NOT NULL; use empty string when no addrs provided
|
|
69
|
-
const multiaddrStr = multiaddrs?.length ? multiaddrs.join(',') : '';
|
|
70
225
|
await db.exec(`
|
|
71
|
-
insert into CadreControl.
|
|
226
|
+
insert into CadreControl.DeviceToken (PeerId, Platform, Token, UpdatedAt, Sig)
|
|
72
227
|
with context AuthorityKey = ?, Signature = ?
|
|
73
|
-
values (?, ?)
|
|
74
|
-
`, [this.authorityPublicKey, signature, peerId,
|
|
75
|
-
log('
|
|
228
|
+
values (?, ?, ?, ?, ?)
|
|
229
|
+
`, [this.authorityPublicKey, signature, record.peerId, record.platform, record.token, record.updatedAt, record.sig]);
|
|
230
|
+
log('Device token inserted (authority-signed): %s', record.peerId);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Authority-signed DELETE of a peer's `DeviceToken` row (logout / token
|
|
234
|
+
* invalidation). The `DeviceToken.AuthorizedInsert` constraint gates both insert
|
|
235
|
+
* AND delete on an authority signature over `digest(old.PeerId)`, so — like
|
|
236
|
+
* {@link removePeer} for `CadrePeer` — clearing a token requires the authority key.
|
|
237
|
+
*/
|
|
238
|
+
async deleteDeviceToken(peerId) {
|
|
239
|
+
const signature = this.signPeerAuthorization(peerId);
|
|
240
|
+
if (!this.controlDatabase) {
|
|
241
|
+
throw new Error('Control database not initialized');
|
|
242
|
+
}
|
|
243
|
+
const db = this.controlDatabase.getDatabase();
|
|
244
|
+
await db.exec(`
|
|
245
|
+
delete from CadreControl.DeviceToken
|
|
246
|
+
with context AuthorityKey = ?, Signature = ?
|
|
247
|
+
where PeerId = ?
|
|
248
|
+
`, [this.authorityPublicKey, signature, peerId]);
|
|
249
|
+
log('Device token removed (authority-signed): %s', peerId);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Sign a peer ID with the authority key for a `CadrePeer` / `DeviceToken`
|
|
253
|
+
* insert-or-delete. The signed bytes come from the shared
|
|
254
|
+
* {@link peerAuthorizationDigest} helper so the offline `cadre enroll register`
|
|
255
|
+
* verifier checks the exact same construction. Throws if no authority key is set.
|
|
256
|
+
*/
|
|
257
|
+
signPeerAuthorization(peerId) {
|
|
258
|
+
if (!this.config.authorityPrivateKey) {
|
|
259
|
+
throw new Error('Authority private key required to authorize peers');
|
|
260
|
+
}
|
|
261
|
+
return sign(peerAuthorizationDigest(peerId), this.config.authorityPrivateKey, 'ed25519', 'base64url', 'base64url', 'base64url');
|
|
76
262
|
}
|
|
77
263
|
/**
|
|
78
264
|
* Remove a peer from the cadre by authority signature.
|
|
79
265
|
*
|
|
80
266
|
* The constraint over CadrePeer's `check on insert, delete` validates a
|
|
81
|
-
* signature over `digest(old.PeerId
|
|
82
|
-
*
|
|
267
|
+
* signature over `digest(old.PeerId)` by an authority key. We use the same
|
|
268
|
+
* digest pattern as authorizePeer.
|
|
83
269
|
*/
|
|
84
270
|
async removePeer(peerId) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
271
|
+
// Same canonical digest as the authorizing INSERT (see peerAuthorizationDigest);
|
|
272
|
+
// also validates the authority key is present before touching the database.
|
|
273
|
+
const signature = this.signPeerAuthorization(peerId);
|
|
88
274
|
if (!this.controlDatabase) {
|
|
89
275
|
throw new Error('Control database not initialized');
|
|
90
276
|
}
|
|
91
277
|
log('Removing peer: %s', peerId);
|
|
92
|
-
const peerIdDigest = digest(peerId, 'sha256', 'utf8', 'base64url');
|
|
93
|
-
const signature = sign(peerIdDigest, this.config.authorityPrivateKey, 'ed25519', 'base64url', 'base64url', 'base64url');
|
|
94
278
|
const db = this.controlDatabase.getDatabase();
|
|
95
279
|
await db.exec(`
|
|
96
280
|
delete from CadreControl.CadrePeer
|
|
@@ -99,6 +283,44 @@ export class SeedBootstrapService {
|
|
|
99
283
|
`, [this.authorityPublicKey, signature, peerId]);
|
|
100
284
|
log('Peer %s removed successfully', peerId);
|
|
101
285
|
}
|
|
286
|
+
/**
|
|
287
|
+
* Authority "re-touch" of an existing `CadrePeer` membership row: bump
|
|
288
|
+
* `UpdatedAt` under the authority branch of `CadrePeer.AuthorizedUpdate` (a
|
|
289
|
+
* signature over `digest(peerId)` — the same construction {@link authorizePeer}
|
|
290
|
+
* uses) so the row is re-emitted as a fresh, broadcasting transaction.
|
|
291
|
+
*
|
|
292
|
+
* This is the write-while-alone re-replication primitive
|
|
293
|
+
* (`control-write-ensure-replicated`): a membership row that committed
|
|
294
|
+
* local-only (its block's cluster ≤1 at insert) is pushed to the cohort once it
|
|
295
|
+
* grows, by re-issuing this monotonic bump. It is an UPDATE (not the original
|
|
296
|
+
* INSERT) because the row already exists locally; a re-INSERT would hit the
|
|
297
|
+
* `PeerId` PK. Only the freshness stamp changes — `PublicKey` / `Multiaddr` /
|
|
298
|
+
* `Sig` are left intact — so it is safe over a row whose peer has not
|
|
299
|
+
* self-published (`Sig` null); the caller must skip a row that already carries a
|
|
300
|
+
* self-`Sig` (that row is the owning peer's to refresh, and bumping `UpdatedAt`
|
|
301
|
+
* without re-signing would invalidate its self-signature).
|
|
302
|
+
*
|
|
303
|
+
* @param peerId - the membership row to re-touch.
|
|
304
|
+
* @param updatedAt - the strictly-increasing freshness stamp to write.
|
|
305
|
+
* @throws if no authority private key is configured (a non-authority cannot
|
|
306
|
+
* re-sign another peer's row) or the control database is not initialized.
|
|
307
|
+
*/
|
|
308
|
+
async reauthorizePeer(peerId, updatedAt) {
|
|
309
|
+
// Reuses the exact digest authorizePeer signs (peerAuthorizationDigest), which
|
|
310
|
+
// the authority branch of AuthorizedUpdate verifies; throws if no authority key.
|
|
311
|
+
const signature = this.signPeerAuthorization(peerId);
|
|
312
|
+
if (!this.controlDatabase) {
|
|
313
|
+
throw new Error('Control database not initialized');
|
|
314
|
+
}
|
|
315
|
+
const db = this.controlDatabase.getDatabase();
|
|
316
|
+
await db.exec(`
|
|
317
|
+
update CadreControl.CadrePeer
|
|
318
|
+
with context AuthorityKey = ?, Signature = ?
|
|
319
|
+
set UpdatedAt = ?
|
|
320
|
+
where PeerId = ?
|
|
321
|
+
`, [this.authorityPublicKey, signature, updatedAt, peerId]);
|
|
322
|
+
log('Peer %s re-authorized (UpdatedAt=%d) for write-while-alone re-replication', peerId, updatedAt);
|
|
323
|
+
}
|
|
102
324
|
/**
|
|
103
325
|
* Create a seed from the current control network state.
|
|
104
326
|
* The seed contains peer information and is signed by an authority.
|
|
@@ -118,9 +340,9 @@ export class SeedBootstrapService {
|
|
|
118
340
|
partyId: this.config.partyId,
|
|
119
341
|
peers,
|
|
120
342
|
};
|
|
121
|
-
// Sign the seed
|
|
122
|
-
const seedJson =
|
|
123
|
-
const seedDigest = digest(seedJson, 'sha256', '
|
|
343
|
+
// Sign the seed over its canonical byte representation
|
|
344
|
+
const seedJson = canonicalSeedPayload(seedData);
|
|
345
|
+
const seedDigest = digest([seedJson], 'sha256', 'base64url');
|
|
124
346
|
const signature = sign(seedDigest, this.config.authorityPrivateKey, 'ed25519', 'base64url', 'base64url', 'base64url');
|
|
125
347
|
const seed = {
|
|
126
348
|
...seedData,
|
|
@@ -132,9 +354,20 @@ export class SeedBootstrapService {
|
|
|
132
354
|
}
|
|
133
355
|
/**
|
|
134
356
|
* Apply a seed to populate the peer cache and enable connections.
|
|
135
|
-
*
|
|
357
|
+
*
|
|
358
|
+
* Validates the seed signature, then evaluates a trust anchor for the
|
|
359
|
+
* `signerKey` that does NOT come from the seed body: the receiver's
|
|
360
|
+
* `AuthorityKey` table (DB-anchored), optionally augmented by pinned keys or
|
|
361
|
+
* TOFU via the configured/overriding `SeedTrustPolicy`. A forged
|
|
362
|
+
* self-asserting seed — one that merely lists its own signer as an authority
|
|
363
|
+
* peer — no longer passes.
|
|
364
|
+
*
|
|
365
|
+
* @param seed - The seed to apply (already transport-decoded).
|
|
366
|
+
* @param options.trustPolicy - Per-call policy override (e.g. a
|
|
367
|
+
* `pinnedKeyTrustPolicy` derived from a `CadreInvite`) used instead of the
|
|
368
|
+
* service-configured default for this seed only.
|
|
136
369
|
*/
|
|
137
|
-
async applySeed(seed) {
|
|
370
|
+
async applySeed(seed, options) {
|
|
138
371
|
if (!this.libp2pNode) {
|
|
139
372
|
return { success: false, peersAdded: 0, error: 'Service not initialized' };
|
|
140
373
|
}
|
|
@@ -143,10 +376,24 @@ export class SeedBootstrapService {
|
|
|
143
376
|
if (!this.validateSeedSignature(seed)) {
|
|
144
377
|
return { success: false, peersAdded: 0, error: 'Invalid seed signature' };
|
|
145
378
|
}
|
|
146
|
-
//
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
379
|
+
// Evaluate the trust anchor for the signer key. The known-authority set is
|
|
380
|
+
// sourced from the receiver's control DB, never from the seed itself; a
|
|
381
|
+
// cold-start node with no DB and no override therefore sees an empty set.
|
|
382
|
+
const knownAuthorityKeys = this.controlDatabase
|
|
383
|
+
? await this.controlDatabase.getAuthorityKeys()
|
|
384
|
+
: new Set();
|
|
385
|
+
const policy = options?.trustPolicy ?? this.trustPolicy;
|
|
386
|
+
const decision = await policy.evaluate({
|
|
387
|
+
partyId: seed.partyId,
|
|
388
|
+
signerKey: seed.signerKey,
|
|
389
|
+
knownAuthorityKeys,
|
|
390
|
+
});
|
|
391
|
+
if (!decision.trusted) {
|
|
392
|
+
return {
|
|
393
|
+
success: false,
|
|
394
|
+
peersAdded: 0,
|
|
395
|
+
error: decision.reason ?? 'Signer key not trusted by trust policy',
|
|
396
|
+
};
|
|
150
397
|
}
|
|
151
398
|
let peersAdded = 0;
|
|
152
399
|
// Add peers to the peer store
|
|
@@ -212,20 +459,14 @@ export class SeedBootstrapService {
|
|
|
212
459
|
const rawStream = await this.libp2pNode.dialProtocol(addr, SEED_PROTOCOL);
|
|
213
460
|
const stream = rawStream;
|
|
214
461
|
try {
|
|
215
|
-
// Send the seed message
|
|
462
|
+
// Send the seed message as one length-prefixed frame (shared writer).
|
|
216
463
|
const message = {
|
|
217
464
|
partyId: seed.partyId,
|
|
218
465
|
peers: seed.peers,
|
|
219
|
-
transactions: seed.transactions,
|
|
220
466
|
signature: seed.signature,
|
|
221
467
|
signerKey: seed.signerKey,
|
|
222
468
|
};
|
|
223
|
-
|
|
224
|
-
// Write length-prefixed message using libp2p 3.x send() API
|
|
225
|
-
const lengthBytes = new Uint8Array(4);
|
|
226
|
-
new DataView(lengthBytes.buffer).setUint32(0, messageBytes.length, false);
|
|
227
|
-
stream.send(lengthBytes);
|
|
228
|
-
stream.send(messageBytes);
|
|
469
|
+
writeFrame(stream, message);
|
|
229
470
|
// In libp2p v3.x, close() closes the write end only (signals EOF),
|
|
230
471
|
// while the read end remains open for receiving the ack.
|
|
231
472
|
await stream.close();
|
|
@@ -242,8 +483,8 @@ export class SeedBootstrapService {
|
|
|
242
483
|
offset += chunk.length;
|
|
243
484
|
}
|
|
244
485
|
// Parse length-prefixed response
|
|
245
|
-
const
|
|
246
|
-
const responseJson = new TextDecoder().decode(
|
|
486
|
+
const responseBody = decodeLengthPrefixedFrame(responseData);
|
|
487
|
+
const responseJson = new TextDecoder().decode(responseBody);
|
|
247
488
|
const ack = JSON.parse(responseJson);
|
|
248
489
|
log('Seed delivery response: accepted=%s', ack.accepted);
|
|
249
490
|
return ack;
|
|
@@ -271,14 +512,11 @@ export class SeedBootstrapService {
|
|
|
271
512
|
*/
|
|
272
513
|
validateSeedSignature(seed) {
|
|
273
514
|
try {
|
|
274
|
-
// Reconstruct the signed
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
};
|
|
280
|
-
const seedJson = JSON.stringify(seedData);
|
|
281
|
-
const seedDigest = digest(seedJson, 'sha256', 'utf8', 'base64url');
|
|
515
|
+
// Reconstruct the signed bytes via the shared canonical payload builder so
|
|
516
|
+
// verification is independent of key order. The payload is the fixed
|
|
517
|
+
// `{ partyId, peers }` the producer emits.
|
|
518
|
+
const seedJson = canonicalSeedPayload(seed);
|
|
519
|
+
const seedDigest = digest([seedJson], 'sha256', 'base64url');
|
|
282
520
|
return verify(seedDigest, seed.signature, seed.signerKey, 'ed25519', 'base64url', 'base64url', 'base64url');
|
|
283
521
|
}
|
|
284
522
|
catch (error) {
|
|
@@ -288,120 +526,135 @@ export class SeedBootstrapService {
|
|
|
288
526
|
}
|
|
289
527
|
/**
|
|
290
528
|
* Query peers from the control database.
|
|
529
|
+
*
|
|
530
|
+
* Authority identity is sourced from the `AuthorityKey` table, not from the
|
|
531
|
+
* transport peer ID. An Ed25519 libp2p PeerId embeds its public key (identity
|
|
532
|
+
* multihash), so each peer's ed25519 key is derivable from its `PeerId`; a
|
|
533
|
+
* peer is an authority iff that derived key is in the `AuthorityKey` set.
|
|
534
|
+
* This makes any authority node markable — not just the local one — and ties
|
|
535
|
+
* `isAuthority` to the control table rather than to `peerId === self`.
|
|
291
536
|
*/
|
|
292
537
|
async queryPeers() {
|
|
293
538
|
if (!this.controlDatabase) {
|
|
294
539
|
return [];
|
|
295
540
|
}
|
|
541
|
+
const authorityKeys = await this.controlDatabase.getAuthorityKeys();
|
|
296
542
|
const db = this.controlDatabase.getDatabase();
|
|
297
543
|
const peers = [];
|
|
298
|
-
// First, get all authority keys
|
|
299
|
-
const authorityKeys = new Set();
|
|
300
|
-
for await (const row of db.eval('select Key from CadreControl.AuthorityKey')) {
|
|
301
|
-
authorityKeys.add(row.Key);
|
|
302
|
-
}
|
|
303
544
|
// Query CadrePeer table
|
|
304
545
|
for await (const row of db.eval('select PeerId, Multiaddr from CadreControl.CadrePeer')) {
|
|
305
546
|
const peerId = row.PeerId;
|
|
306
547
|
const multiaddr = row.Multiaddr;
|
|
307
|
-
//
|
|
308
|
-
|
|
548
|
+
// Derive the peer's ed25519 key from its PeerId; a non-Ed25519 peer or an
|
|
549
|
+
// unparsable id yields null and is treated as a non-authority rather than
|
|
550
|
+
// failing the whole seed creation.
|
|
551
|
+
const pubKeyB64 = ed25519PublicKeyB64FromPeerId(peerId);
|
|
552
|
+
const isAuthority = pubKeyB64 !== null && authorityKeys.has(pubKeyB64);
|
|
309
553
|
peers.push({
|
|
310
554
|
peerId,
|
|
311
555
|
multiaddrs: multiaddr ? multiaddr.split(',') : [],
|
|
312
556
|
isAuthority,
|
|
313
|
-
...(isAuthority
|
|
557
|
+
...(isAuthority ? { publicKey: pubKeyB64 } : {}),
|
|
314
558
|
});
|
|
315
559
|
}
|
|
316
560
|
return peers;
|
|
317
561
|
}
|
|
318
562
|
/**
|
|
319
|
-
* Register the seed protocol handler.
|
|
563
|
+
* Register the seed protocol handler. The inbound closure just delegates to
|
|
564
|
+
* {@link handleSeedStream} — extracted as a method so it has a unit-test seam
|
|
565
|
+
* (mirroring wake's `handleStream`) the inline closure never had.
|
|
320
566
|
*/
|
|
321
567
|
registerProtocolHandler() {
|
|
322
568
|
if (!this.libp2pNode)
|
|
323
569
|
return;
|
|
324
|
-
this.libp2pNode.handle(SEED_PROTOCOL, async (rawStream, rawConnection) => {
|
|
325
|
-
const stream = rawStream;
|
|
570
|
+
void this.libp2pNode.handle(SEED_PROTOCOL, async (rawStream, rawConnection) => {
|
|
326
571
|
const remotePeerId = rawConnection.remotePeer.toString();
|
|
327
|
-
|
|
572
|
+
await this.handleSeedStream(rawStream, remotePeerId);
|
|
573
|
+
});
|
|
574
|
+
log('Registered seed protocol handler: %s', SEED_PROTOCOL);
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Read one inbound seed frame, apply it, and write the ack.
|
|
578
|
+
*
|
|
579
|
+
* Hardened against a buggy/compromised own-cadre node: a concurrency cap (over
|
|
580
|
+
* {@link maxConcurrentSeeds}, reply without applying), a read timeout (a peer
|
|
581
|
+
* that never half-closes is aborted inside `readStreamToEnd`), and the existing
|
|
582
|
+
* malformed/oversized-frame guard — all reported as a non-accepting
|
|
583
|
+
* {@link SeedAckMessage} rather than a dropped/hung stream.
|
|
584
|
+
*/
|
|
585
|
+
async handleSeedStream(stream, remotePeerId) {
|
|
586
|
+
log('Incoming seed delivery from: %s', remotePeerId);
|
|
587
|
+
if (this.activeStreams >= this.maxConcurrentSeeds) {
|
|
588
|
+
log('Rejecting seed from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrentSeeds);
|
|
589
|
+
const ack = { accepted: false, reason: 'Too many concurrent seed deliveries' };
|
|
328
590
|
try {
|
|
329
|
-
|
|
330
|
-
const chunks = [];
|
|
331
|
-
let totalLength = 0;
|
|
332
|
-
for await (const chunk of stream) {
|
|
333
|
-
const bytes = chunk instanceof Uint8Array ? chunk : chunk.subarray();
|
|
334
|
-
chunks.push(bytes);
|
|
335
|
-
totalLength += bytes.length;
|
|
336
|
-
if (totalLength > MAX_SEED_SIZE) {
|
|
337
|
-
throw new Error('Seed message too large');
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
const data = new Uint8Array(totalLength);
|
|
341
|
-
let offset = 0;
|
|
342
|
-
for (const chunk of chunks) {
|
|
343
|
-
data.set(chunk, offset);
|
|
344
|
-
offset += chunk.length;
|
|
345
|
-
}
|
|
346
|
-
// Parse length-prefixed message
|
|
347
|
-
const messageLength = new DataView(data.buffer, data.byteOffset).getUint32(0, false);
|
|
348
|
-
const messageJson = new TextDecoder().decode(data.slice(4, 4 + messageLength));
|
|
349
|
-
const message = JSON.parse(messageJson);
|
|
350
|
-
// Emit seed received event
|
|
351
|
-
this.eventCallbacks.onSeedReceived?.(message.partyId, remotePeerId);
|
|
352
|
-
// Convert to seed and apply
|
|
353
|
-
const seed = {
|
|
354
|
-
partyId: message.partyId,
|
|
355
|
-
peers: message.peers,
|
|
356
|
-
transactions: message.transactions,
|
|
357
|
-
signature: message.signature,
|
|
358
|
-
signerKey: message.signerKey,
|
|
359
|
-
};
|
|
360
|
-
const result = await this.applySeed(seed);
|
|
361
|
-
// Emit appropriate event based on result
|
|
362
|
-
if (result.success) {
|
|
363
|
-
this.eventCallbacks.onSeedApplied?.(seed.partyId, result.peersAdded);
|
|
364
|
-
}
|
|
365
|
-
else {
|
|
366
|
-
this.eventCallbacks.onSeedError?.(seed.partyId, result.error ?? 'Unknown error');
|
|
367
|
-
}
|
|
368
|
-
// Send acknowledgment using libp2p 3.x send() API
|
|
369
|
-
const ack = {
|
|
370
|
-
accepted: result.success,
|
|
371
|
-
reason: result.error,
|
|
372
|
-
};
|
|
373
|
-
const ackBytes = new TextEncoder().encode(JSON.stringify(ack));
|
|
374
|
-
const lengthBytes = new Uint8Array(4);
|
|
375
|
-
new DataView(lengthBytes.buffer).setUint32(0, ackBytes.length, false);
|
|
376
|
-
stream.send(lengthBytes);
|
|
377
|
-
stream.send(ackBytes);
|
|
591
|
+
writeFrame(stream, ack);
|
|
378
592
|
}
|
|
379
|
-
catch
|
|
380
|
-
|
|
381
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
382
|
-
// Emit error event
|
|
383
|
-
this.eventCallbacks.onSeedError?.(this.config.partyId, errorMessage);
|
|
384
|
-
// Send error acknowledgment
|
|
385
|
-
const ack = {
|
|
386
|
-
accepted: false,
|
|
387
|
-
reason: errorMessage,
|
|
388
|
-
};
|
|
389
|
-
const ackBytes = new TextEncoder().encode(JSON.stringify(ack));
|
|
390
|
-
const lengthBytes = new Uint8Array(4);
|
|
391
|
-
new DataView(lengthBytes.buffer).setUint32(0, ackBytes.length, false);
|
|
392
|
-
try {
|
|
393
|
-
stream.send(lengthBytes);
|
|
394
|
-
stream.send(ackBytes);
|
|
395
|
-
}
|
|
396
|
-
catch {
|
|
397
|
-
// Ignore send errors
|
|
398
|
-
}
|
|
593
|
+
catch {
|
|
594
|
+
// Ignore send errors on the reject path.
|
|
399
595
|
}
|
|
400
|
-
|
|
596
|
+
try {
|
|
401
597
|
await stream.close();
|
|
402
598
|
}
|
|
403
|
-
|
|
404
|
-
|
|
599
|
+
catch {
|
|
600
|
+
// Ignore close errors.
|
|
601
|
+
}
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
this.activeStreams++;
|
|
605
|
+
try {
|
|
606
|
+
// Read the seed frame to EOF (bounded + size-capped), then decode it.
|
|
607
|
+
const data = await readStreamToEnd(stream, {
|
|
608
|
+
maxBytes: MAX_SEED_SIZE,
|
|
609
|
+
timeoutMs: this.seedReadTimeoutMs,
|
|
610
|
+
label: 'Seed',
|
|
611
|
+
});
|
|
612
|
+
const messageBody = decodeLengthPrefixedFrame(data);
|
|
613
|
+
const messageJson = new TextDecoder().decode(messageBody);
|
|
614
|
+
const message = JSON.parse(messageJson);
|
|
615
|
+
// Emit seed received event
|
|
616
|
+
this.eventCallbacks.onSeedReceived?.(message.partyId, remotePeerId);
|
|
617
|
+
// Convert to seed and apply
|
|
618
|
+
const seed = {
|
|
619
|
+
partyId: message.partyId,
|
|
620
|
+
peers: message.peers,
|
|
621
|
+
signature: message.signature,
|
|
622
|
+
signerKey: message.signerKey,
|
|
623
|
+
};
|
|
624
|
+
const result = await this.applySeed(seed);
|
|
625
|
+
// Emit appropriate event based on result
|
|
626
|
+
if (result.success) {
|
|
627
|
+
this.eventCallbacks.onSeedApplied?.(seed.partyId, result.peersAdded);
|
|
628
|
+
}
|
|
629
|
+
else {
|
|
630
|
+
this.eventCallbacks.onSeedError?.(seed.partyId, result.error ?? 'Unknown error');
|
|
631
|
+
}
|
|
632
|
+
const ack = { accepted: result.success, reason: result.error };
|
|
633
|
+
writeFrame(stream, ack);
|
|
634
|
+
}
|
|
635
|
+
catch (error) {
|
|
636
|
+
log('Error handling seed delivery: %o', error);
|
|
637
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
638
|
+
// Emit error event
|
|
639
|
+
this.eventCallbacks.onSeedError?.(this.config.partyId, errorMessage);
|
|
640
|
+
// Send error acknowledgment (best-effort on the still-open write side).
|
|
641
|
+
const ack = { accepted: false, reason: errorMessage };
|
|
642
|
+
try {
|
|
643
|
+
writeFrame(stream, ack);
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
// Ignore send errors
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
finally {
|
|
650
|
+
this.activeStreams--;
|
|
651
|
+
try {
|
|
652
|
+
await stream.close();
|
|
653
|
+
}
|
|
654
|
+
catch {
|
|
655
|
+
// Ignore close errors.
|
|
656
|
+
}
|
|
657
|
+
}
|
|
405
658
|
}
|
|
406
659
|
/**
|
|
407
660
|
* Shutdown the service.
|
|
@@ -474,16 +727,22 @@ export class SeedBootstrapService {
|
|
|
474
727
|
else {
|
|
475
728
|
authorityAddrs = this.libp2pNode.getMultiaddrs().map(a => a.toString());
|
|
476
729
|
}
|
|
730
|
+
// Carry the cadre's authority keys out-of-band so a cold-start invitee can
|
|
731
|
+
// pin the trusted authority set before applying any seed.
|
|
732
|
+
const authorityKeys = this.controlDatabase
|
|
733
|
+
? Array.from(await this.controlDatabase.getAuthorityKeys())
|
|
734
|
+
: [];
|
|
477
735
|
const now = Date.now();
|
|
478
736
|
const invite = {
|
|
479
737
|
partyId: this.config.partyId,
|
|
480
738
|
authorityAddrs,
|
|
739
|
+
authorityKeys: authorityKeys.length ? authorityKeys : undefined,
|
|
481
740
|
token,
|
|
482
741
|
createdAt: now,
|
|
483
742
|
expiresAt: expiresIn ? now + expiresIn : undefined,
|
|
484
743
|
};
|
|
485
744
|
const encodedInvite = this.encodeInvite(invite);
|
|
486
|
-
log('Invite created with %d authority addresses', authorityAddrs.length);
|
|
745
|
+
log('Invite created with %d authority addresses, %d authority keys', authorityAddrs.length, authorityKeys.length);
|
|
487
746
|
return { invite, encodedInvite };
|
|
488
747
|
}
|
|
489
748
|
/**
|