@serfab/cadre-core 0.10.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.
- package/README.md +255 -255
- package/dist/cadre-node.d.ts +203 -28
- package/dist/cadre-node.js +445 -84
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-cohort.d.ts +26 -0
- package/dist/control-cohort.js +26 -0
- package/dist/control-cohort.js.map +1 -1
- package/dist/control-database.d.ts +82 -117
- package/dist/control-database.js +217 -295
- package/dist/control-database.js.map +1 -1
- package/dist/control-formation-recorder.d.ts +8 -7
- package/dist/control-formation-recorder.js +8 -7
- package/dist/control-formation-recorder.js.map +1 -1
- package/dist/control-schema.d.ts +1 -1
- package/dist/control-schema.js +789 -774
- package/dist/control-schema.js.map +1 -1
- package/dist/control-write-retry.d.ts +15 -5
- package/dist/control-write-retry.js +19 -18
- package/dist/control-write-retry.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/peer-addr-book.d.ts +92 -0
- package/dist/peer-addr-book.js +220 -0
- package/dist/peer-addr-book.js.map +1 -0
- package/dist/seed-bootstrap.d.ts +7 -0
- package/dist/seed-bootstrap.js +15 -13
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/strand-cohort.d.ts +4 -37
- package/dist/strand-cohort.js +4 -15
- package/dist/strand-cohort.js.map +1 -1
- package/dist/strand-database.d.ts +11 -16
- package/dist/strand-database.js +19 -7
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-formation-manager.d.ts +8 -8
- package/dist/strand-formation-manager.js +15 -18
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +52 -21
- package/dist/strand-instance-manager.js +100 -34
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-membership-writer.d.ts +6 -4
- package/dist/strand-membership-writer.js +38 -36
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/types.d.ts +39 -31
- package/dist/types.js.map +1 -1
- package/package.json +8 -7
- package/src/arachnode-stub.ts +159 -159
- package/src/bootstrap-peer-store-file.ts +44 -44
- package/src/bootstrap-peer-store.ts +172 -172
- package/src/cadre-node.ts +5158 -4771
- package/src/canonical-json.ts +30 -30
- package/src/control-authorization.ts +114 -114
- package/src/control-cohort.ts +130 -103
- package/src/control-database.ts +2406 -2506
- package/src/control-formation-recorder.ts +305 -304
- package/src/control-schema.ts +801 -786
- package/src/control-stream.ts +205 -205
- package/src/control-write-retry.ts +483 -473
- package/src/delegate-admission.ts +302 -302
- package/src/device-token.ts +94 -94
- package/src/diagnostics/connection-path.ts +277 -277
- package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
- package/src/ed25519-key.ts +134 -134
- package/src/enrollment.ts +199 -199
- package/src/file-durable-slot.ts +61 -61
- package/src/formation-approval.ts +604 -604
- package/src/fs-atomic.ts +107 -107
- package/src/hibernation-manager.ts +437 -437
- package/src/identity-key.ts +109 -109
- package/src/index.ts +1 -0
- package/src/key-store-file.ts +132 -132
- package/src/key-store.ts +99 -99
- package/src/membership-connection-gater.ts +204 -204
- package/src/node-local-snapshot.ts +260 -260
- package/src/peer-addr-book.ts +250 -0
- package/src/peer-authorization.ts +259 -259
- package/src/peer-record.ts +164 -164
- package/src/push-credentials.ts +84 -84
- package/src/push-node.ts +64 -64
- package/src/push-notifier-apns.ts +247 -247
- package/src/push-notifier-fcm.ts +220 -220
- package/src/push-notifier-shared.ts +28 -28
- package/src/push-notifier.ts +52 -52
- package/src/relay-addrs.ts +111 -111
- package/src/relay-reservation.ts +823 -823
- package/src/seed-bootstrap.ts +15 -15
- package/src/seed-trust-policy.ts +140 -140
- package/src/strand-addr-protocol.ts +441 -441
- package/src/strand-backfill.ts +366 -366
- package/src/strand-cohort.ts +38 -77
- package/src/strand-database.ts +202 -204
- package/src/strand-formation-manager.ts +491 -494
- package/src/strand-formation-protocol.ts +692 -692
- package/src/strand-instance-manager.ts +108 -50
- package/src/strand-member-key.ts +39 -39
- package/src/strand-member-registry.ts +182 -182
- package/src/strand-membership-writer.ts +1432 -1430
- package/src/strand-solicitation.ts +472 -472
- package/src/strand-transport-key.ts +58 -58
- package/src/strand-wake-payload.ts +32 -32
- package/src/strand-wake-protocol.ts +314 -314
- package/src/strand-watcher.ts +314 -314
- package/src/trusted-owner-store-file.ts +41 -41
- package/src/trusted-owner-store.ts +171 -171
- package/src/types.ts +1309 -1303
package/src/key-store.ts
CHANGED
|
@@ -1,99 +1,99 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Backend-agnostic store for raw private key material.
|
|
3
|
-
*
|
|
4
|
-
* Mobile cadre nodes hold sensitive key material at rest: the libp2p
|
|
5
|
-
* peer/node identity key and (in the single-key reference model) the owner
|
|
6
|
-
* signing key derived from it. This module defines the seam those keys flow
|
|
7
|
-
* through so a platform-secure backend (iOS Keychain / Android Keystore) can be
|
|
8
|
-
* plugged in without `@serfab/cadre-core` taking any platform dependency.
|
|
9
|
-
*
|
|
10
|
-
* This file is dependency-free (no node:/RN imports) so it is safe in every
|
|
11
|
-
* entry graph. The Node reference {@link FileKeyStore} lives in a separate
|
|
12
|
-
* subpath module (`./key-store-file.js`) so its `node:fs` import never lands in
|
|
13
|
-
* the cross-platform default entry.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
/** Opaque identifier for a stored key slot (e.g. 'cadre/identity'). */
|
|
17
|
-
export type KeyId = string;
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Default slot id for the node identity key. `CadreNode` reads/persists its
|
|
21
|
-
* libp2p identity here when a {@link KeyStore} is configured without an explicit
|
|
22
|
-
* `identityKeyId`.
|
|
23
|
-
*/
|
|
24
|
-
export const DEFAULT_IDENTITY_KEY_ID: KeyId = 'cadre/identity';
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Backend-agnostic store for raw private key material. Implementations may be
|
|
28
|
-
* file-based, OS-keyring, or platform secure-enclave backed (iOS Keychain /
|
|
29
|
-
* Android Keystore). The interface makes no assumption about the backend and
|
|
30
|
-
* never logs, returns, or throws key material.
|
|
31
|
-
*
|
|
32
|
-
* Key material is raw bytes (e.g. libp2p protobuf-serialized private keys).
|
|
33
|
-
* Text-only backends encode/decode (base64) internally; byte-native backends
|
|
34
|
-
* (LevelDB) store as-is.
|
|
35
|
-
*/
|
|
36
|
-
export interface KeyStore {
|
|
37
|
-
/** Resolves to the stored material, or undefined if the slot is empty. */
|
|
38
|
-
get(keyId: KeyId): Promise<Uint8Array | undefined>;
|
|
39
|
-
|
|
40
|
-
/** Writes/overwrites the slot. */
|
|
41
|
-
set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
|
|
42
|
-
|
|
43
|
-
/** Removes the slot. Idempotent — succeeds even if absent. */
|
|
44
|
-
delete(keyId: KeyId): Promise<void>;
|
|
45
|
-
|
|
46
|
-
/** Enumerates the keyIds this store knows about. */
|
|
47
|
-
list(): Promise<KeyId[]>;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Thrown by {@link KeyStore.get} when access was denied or could not be
|
|
52
|
-
* satisfied (e.g. a biometric/device-unlock prompt was cancelled or failed).
|
|
53
|
-
* Distinguishes "access refused" from "slot empty" (which is a plain `undefined`
|
|
54
|
-
* return). Biometric gating itself is out of scope here, but `get` rejecting
|
|
55
|
-
* with this error is the contract a gated backend uses, so callers must not
|
|
56
|
-
* treat it as "no key" (which would trigger key regeneration and silent
|
|
57
|
-
* identity loss).
|
|
58
|
-
*
|
|
59
|
-
* Carries only the {@link keyId} — never key material — so it is safe to log.
|
|
60
|
-
*/
|
|
61
|
-
export class KeyStoreAccessError extends Error {
|
|
62
|
-
readonly keyId: KeyId;
|
|
63
|
-
|
|
64
|
-
constructor(keyId: KeyId, message: string, options?: { cause?: unknown }) {
|
|
65
|
-
super(message, options);
|
|
66
|
-
this.name = 'KeyStoreAccessError';
|
|
67
|
-
this.keyId = keyId;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* In-memory {@link KeyStore} backed by a `Map`. For tests and ephemeral nodes;
|
|
73
|
-
* nothing is persisted across process restarts. Dependency-free, so it is safe
|
|
74
|
-
* in every entry graph.
|
|
75
|
-
*
|
|
76
|
-
* Material is defensively copied on both {@link set} and {@link get} so a caller
|
|
77
|
-
* mutating its own buffer cannot alter stored state (and vice versa), matching
|
|
78
|
-
* the fresh-buffer semantics a file/keyring backend produces.
|
|
79
|
-
*/
|
|
80
|
-
export class InMemoryKeyStore implements KeyStore {
|
|
81
|
-
private readonly slots = new Map<KeyId, Uint8Array>();
|
|
82
|
-
|
|
83
|
-
async get(keyId: KeyId): Promise<Uint8Array | undefined> {
|
|
84
|
-
const stored = this.slots.get(keyId);
|
|
85
|
-
return stored ? stored.slice() : undefined;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
|
|
89
|
-
this.slots.set(keyId, keyMaterial.slice());
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async delete(keyId: KeyId): Promise<void> {
|
|
93
|
-
this.slots.delete(keyId);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async list(): Promise<KeyId[]> {
|
|
97
|
-
return [...this.slots.keys()];
|
|
98
|
-
}
|
|
99
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Backend-agnostic store for raw private key material.
|
|
3
|
+
*
|
|
4
|
+
* Mobile cadre nodes hold sensitive key material at rest: the libp2p
|
|
5
|
+
* peer/node identity key and (in the single-key reference model) the owner
|
|
6
|
+
* signing key derived from it. This module defines the seam those keys flow
|
|
7
|
+
* through so a platform-secure backend (iOS Keychain / Android Keystore) can be
|
|
8
|
+
* plugged in without `@serfab/cadre-core` taking any platform dependency.
|
|
9
|
+
*
|
|
10
|
+
* This file is dependency-free (no node:/RN imports) so it is safe in every
|
|
11
|
+
* entry graph. The Node reference {@link FileKeyStore} lives in a separate
|
|
12
|
+
* subpath module (`./key-store-file.js`) so its `node:fs` import never lands in
|
|
13
|
+
* the cross-platform default entry.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Opaque identifier for a stored key slot (e.g. 'cadre/identity'). */
|
|
17
|
+
export type KeyId = string;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Default slot id for the node identity key. `CadreNode` reads/persists its
|
|
21
|
+
* libp2p identity here when a {@link KeyStore} is configured without an explicit
|
|
22
|
+
* `identityKeyId`.
|
|
23
|
+
*/
|
|
24
|
+
export const DEFAULT_IDENTITY_KEY_ID: KeyId = 'cadre/identity';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Backend-agnostic store for raw private key material. Implementations may be
|
|
28
|
+
* file-based, OS-keyring, or platform secure-enclave backed (iOS Keychain /
|
|
29
|
+
* Android Keystore). The interface makes no assumption about the backend and
|
|
30
|
+
* never logs, returns, or throws key material.
|
|
31
|
+
*
|
|
32
|
+
* Key material is raw bytes (e.g. libp2p protobuf-serialized private keys).
|
|
33
|
+
* Text-only backends encode/decode (base64) internally; byte-native backends
|
|
34
|
+
* (LevelDB) store as-is.
|
|
35
|
+
*/
|
|
36
|
+
export interface KeyStore {
|
|
37
|
+
/** Resolves to the stored material, or undefined if the slot is empty. */
|
|
38
|
+
get(keyId: KeyId): Promise<Uint8Array | undefined>;
|
|
39
|
+
|
|
40
|
+
/** Writes/overwrites the slot. */
|
|
41
|
+
set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
|
|
42
|
+
|
|
43
|
+
/** Removes the slot. Idempotent — succeeds even if absent. */
|
|
44
|
+
delete(keyId: KeyId): Promise<void>;
|
|
45
|
+
|
|
46
|
+
/** Enumerates the keyIds this store knows about. */
|
|
47
|
+
list(): Promise<KeyId[]>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Thrown by {@link KeyStore.get} when access was denied or could not be
|
|
52
|
+
* satisfied (e.g. a biometric/device-unlock prompt was cancelled or failed).
|
|
53
|
+
* Distinguishes "access refused" from "slot empty" (which is a plain `undefined`
|
|
54
|
+
* return). Biometric gating itself is out of scope here, but `get` rejecting
|
|
55
|
+
* with this error is the contract a gated backend uses, so callers must not
|
|
56
|
+
* treat it as "no key" (which would trigger key regeneration and silent
|
|
57
|
+
* identity loss).
|
|
58
|
+
*
|
|
59
|
+
* Carries only the {@link keyId} — never key material — so it is safe to log.
|
|
60
|
+
*/
|
|
61
|
+
export class KeyStoreAccessError extends Error {
|
|
62
|
+
readonly keyId: KeyId;
|
|
63
|
+
|
|
64
|
+
constructor(keyId: KeyId, message: string, options?: { cause?: unknown }) {
|
|
65
|
+
super(message, options);
|
|
66
|
+
this.name = 'KeyStoreAccessError';
|
|
67
|
+
this.keyId = keyId;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* In-memory {@link KeyStore} backed by a `Map`. For tests and ephemeral nodes;
|
|
73
|
+
* nothing is persisted across process restarts. Dependency-free, so it is safe
|
|
74
|
+
* in every entry graph.
|
|
75
|
+
*
|
|
76
|
+
* Material is defensively copied on both {@link set} and {@link get} so a caller
|
|
77
|
+
* mutating its own buffer cannot alter stored state (and vice versa), matching
|
|
78
|
+
* the fresh-buffer semantics a file/keyring backend produces.
|
|
79
|
+
*/
|
|
80
|
+
export class InMemoryKeyStore implements KeyStore {
|
|
81
|
+
private readonly slots = new Map<KeyId, Uint8Array>();
|
|
82
|
+
|
|
83
|
+
async get(keyId: KeyId): Promise<Uint8Array | undefined> {
|
|
84
|
+
const stored = this.slots.get(keyId);
|
|
85
|
+
return stored ? stored.slice() : undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
|
|
89
|
+
this.slots.set(keyId, keyMaterial.slice());
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async delete(keyId: KeyId): Promise<void> {
|
|
93
|
+
this.slots.delete(keyId);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async list(): Promise<KeyId[]> {
|
|
97
|
+
return [...this.slots.keys()];
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -1,204 +1,204 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Control-network inbound connection gate (defense-in-depth).
|
|
3
|
-
*
|
|
4
|
-
* Layer 2 of the membership enforcement chain: the PRIMARY gates are per-stream
|
|
5
|
-
* — every sensitive sereus control protocol rejects a peer that fails the
|
|
6
|
-
* voucher-anchored membership check (wake and strand-addr via
|
|
7
|
-
* `CadreNode.isAuthorizedMember`; the Optimystic control-DB protocols via the
|
|
8
|
-
* materialized-snapshot gate `CadreNode.authorizeInboundControlStream`), and
|
|
9
|
-
* the replicated rows an outsider *can* still write are disbelieved at read
|
|
10
|
-
* time. This module adds the opportunistic connection-level layer on top: a
|
|
11
|
-
* peer this node can positively determine is NOT authorized is refused at the
|
|
12
|
-
* encrypted-connection checkpoint, before any protocol negotiation, so a
|
|
13
|
-
* known-nothing outsider is never even in the conversation.
|
|
14
|
-
*
|
|
15
|
-
* ## The stranger allowlist (the ONE place it is defined)
|
|
16
|
-
*
|
|
17
|
-
* A libp2p connection gater decides per CONNECTION, before protocols are
|
|
18
|
-
* negotiated, so "allow seed, deny repo" cannot be expressed here — instead the
|
|
19
|
-
* policy admits a connection whenever a legitimate stranger interaction could be
|
|
20
|
-
* riding it, and the per-stream gates take over. The complete set of protocols a
|
|
21
|
-
* NOT-yet-authorized peer may legitimately speak on a control node is:
|
|
22
|
-
*
|
|
23
|
-
* - `/sereus/seed/1.0.0` ({@link SEED_PROTOCOL}) — enrollment seed delivery.
|
|
24
|
-
* An owner dials a brand-new node to seed it (the new node has no members
|
|
25
|
-
* yet, so its gate is inert), and an invited phone dials the owner before it
|
|
26
|
-
* is authorized (admitted via the enrollment window `CadreNode.createInvite`
|
|
27
|
-
* opens). The handler's own trust decision is the anchored seed-trust policy.
|
|
28
|
-
* - `/sereus/formation/1.0.0` ({@link FORMATION_PROTOCOL}) — cross-party
|
|
29
|
-
* strand formation via open invitations. Stranger-facing BY DESIGN: the
|
|
30
|
-
* initiator is another party, and its token is only checkable inside the
|
|
31
|
-
* protocol. The exemption is therefore keyed on EXPECTATION of a stranger,
|
|
32
|
-
* not capability to serve one: stranger denial is suspended only while this
|
|
33
|
-
* node has at least one UNEXPIRED, NOT-FULLY-CONSUMED open invitation
|
|
34
|
-
* outstanding (`StrandSolicitationService.hasOutstandingInvitation` — the
|
|
35
|
-
* tokens this process minted or published, plus any still-redeemable
|
|
36
|
-
* `FormationInvite` row the usage recorder can see). Merely registering the
|
|
37
|
-
* responder (`CadreNode.initializeStrandSolicitation`) does NOT suspend it,
|
|
38
|
-
* so an app that registers eagerly at node bring-up keeps a live gate. The
|
|
39
|
-
* handler's own trust decision remains the per-token check, which is
|
|
40
|
-
* strictly finer than this one: a peer admitted here can still be rejected
|
|
41
|
-
* in-protocol for a bogus or spent token.
|
|
42
|
-
*
|
|
43
|
-
* There is one further connection-level carve-out, which is NOT a protocol
|
|
44
|
-
* exemption and needs no stranger window:
|
|
45
|
-
*
|
|
46
|
-
* - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
|
|
47
|
-
* node runs as a separate libp2p identity whose peerId no sibling can
|
|
48
|
-
* recompute, so a relay-running control node would deny its circuit-relay
|
|
49
|
-
* reservation. Before starting a strand node, a member's control node
|
|
50
|
-
* announces that peerId over the already-authenticated strand-addr RPC, and
|
|
51
|
-
* the receiver holds a short-lived grant for it
|
|
52
|
-
* (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION and
|
|
53
|
-
* nothing else — a reservation needs no stream — and is deliberately
|
|
54
|
-
* invisible to the per-stream gate below, so a delegate still gets refused
|
|
55
|
-
* on every members-only protocol.
|
|
56
|
-
*
|
|
57
|
-
* Everything else a control node handles — the Optimystic control-DB protocols
|
|
58
|
-
* (`/optimystic/control-<party>/{repo,cluster,sync,block-transfer}/…`), wake
|
|
59
|
-
* (`/sereus/strand-wake/1.0.0`), and strand-addr (`/sereus/strand-addr/1.0.0`)
|
|
60
|
-
* — is members-only, and every one of them enforces that per-stream. Wake and
|
|
61
|
-
* strand-addr check `isAuthorizedMember` inside their handlers; the four
|
|
62
|
-
* control-DB protocols are gated by the fail-closed
|
|
63
|
-
* `CadreNode.authorizeInboundControlStream` (wired as libp2p's
|
|
64
|
-
* `authorizeInboundStream` upstream hook), which judges each inbound stream
|
|
65
|
-
* against the MATERIALIZED authorized-peer snapshot — synchronous and
|
|
66
|
-
* in-memory, because a live DB read from inside the gate would deadlock into
|
|
67
|
-
* mutual denial. The two layers complement, not duplicate: this connection
|
|
68
|
-
* gate is fail-open over a live DB read (deny only on positive proof of an
|
|
69
|
-
* outsider), the stream gate is fail-closed over the snapshot and has NO
|
|
70
|
-
* stranger carve-outs — an enrollment window admits a stranger's connection
|
|
71
|
-
* for seed delivery, yet its repo streams are still refused.
|
|
72
|
-
*
|
|
73
|
-
* ## Fail-open, deliberately
|
|
74
|
-
*
|
|
75
|
-
* This layer only ever denies on a POSITIVE determination of "unauthorized
|
|
76
|
-
* outsider while no stranger path is open". Any error, missing dependency, or
|
|
77
|
-
* ambiguous state admits the connection and defers to the fail-closed stream
|
|
78
|
-
* gates — a DB hiccup must not partition a legitimate cadre.
|
|
79
|
-
*/
|
|
80
|
-
|
|
81
|
-
import debug from 'debug';
|
|
82
|
-
import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
|
|
83
|
-
import { SEED_PROTOCOL } from './seed-bootstrap.js';
|
|
84
|
-
import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
|
|
85
|
-
|
|
86
|
-
const log = debug('sereus:cadre:connection-gater');
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* The protocols a not-yet-authorized peer may legitimately speak on a control
|
|
90
|
-
* node (see the module doc above for why each is open and where its own trust
|
|
91
|
-
* decision lives). Exported as the single reference point so the allowlist
|
|
92
|
-
* cannot silently drift across modules.
|
|
93
|
-
*/
|
|
94
|
-
export const STRANGER_OPEN_PROTOCOLS: readonly string[] = [SEED_PROTOCOL, FORMATION_PROTOCOL];
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* How long `CadreNode.createInvite` holds the inbound gate open for strangers
|
|
98
|
-
* when the invite carries no explicit expiry: the invitee must dial in before
|
|
99
|
-
* it is authorized, and an expiry-less invite gives the gate no bound of its
|
|
100
|
-
* own. Redeeming after this window still works once the owner re-mints (or the
|
|
101
|
-
* caller re-opens the window via `CadreNode.openEnrollmentWindow`).
|
|
102
|
-
*/
|
|
103
|
-
export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Deadline for one admission decision, after which the connection is ADMITTED.
|
|
107
|
-
*
|
|
108
|
-
* libp2p awaits `denyInboundEncryptedConnection` inside the inbound upgrade
|
|
109
|
-
* WITHOUT racing its inbound-upgrade timeout signal (unlike the pre-encryption
|
|
110
|
-
* `denyInboundConnection` hook), so a decision that never settles wedges that
|
|
111
|
-
* upgrade forever — the connection-manager's inbound-upgrade slot is taken by
|
|
112
|
-
* `acceptIncomingConnection` and released in the `finally` that never runs. The
|
|
113
|
-
* real policy reads the control DB (`listAuthorizedMembers`), which can pull
|
|
114
|
-
* over the network, so "never settles" is reachable. Bounding it here keeps the
|
|
115
|
-
* fail-open contract honest: a slow decision admits rather than silently
|
|
116
|
-
* failing closed (or not at all).
|
|
117
|
-
*/
|
|
118
|
-
export const ADMISSION_DECISION_TIMEOUT_MS = 2_000;
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* The admission decision the gate defers to — implemented by
|
|
122
|
-
* `CadreNode.admitInboundControlConnection` (enrollment windows, anchor state,
|
|
123
|
-
* bootstrap infra, the authorized-member set). Kept injectable so the gater's
|
|
124
|
-
* composition/fail-open behavior is unit-testable without a full node.
|
|
125
|
-
*/
|
|
126
|
-
export interface InboundAdmissionPolicy {
|
|
127
|
-
/** Should an inbound encrypted connection from this peer be admitted? */
|
|
128
|
-
admitInbound(remotePeerId: string): Promise<boolean> | boolean;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Build the control node's connection gater: the caller-supplied gater (if any)
|
|
133
|
-
* with membership admission composed onto `denyInboundEncryptedConnection` —
|
|
134
|
-
* the earliest checkpoint where the remote's authenticated PeerId is known.
|
|
135
|
-
*
|
|
136
|
-
* Composition semantics: every hook of `base` is preserved as-is; on the
|
|
137
|
-
* inbound-encrypted hook a deny from EITHER the base gater or the admission
|
|
138
|
-
* policy denies. A policy error — or a decision slower than
|
|
139
|
-
* `decisionTimeoutMs` — admits (fail-open, see module doc); the base gater's
|
|
140
|
-
* verdict is still honored first.
|
|
141
|
-
*
|
|
142
|
-
* NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
|
|
143
|
-
* prototype methods; every caller in this repo (and libp2p's own default)
|
|
144
|
-
* supplies a plain object. If a class-based gater ever shows up, delegate
|
|
145
|
-
* per-hook instead of spreading.
|
|
146
|
-
*
|
|
147
|
-
* Deny timing, as observed by the denied dialer: noise negotiates the muxer in
|
|
148
|
-
* the security handshake's early data, so the DIALER's upgrade may complete
|
|
149
|
-
* (its `dial()` resolves) before this receiver-side hook runs. The deny then
|
|
150
|
-
* aborts the receiver's upgrade — the receiver never registers the connection
|
|
151
|
-
* and never creates its muxer, so no protocol can ever be negotiated — and the
|
|
152
|
-
* dialer sees its "open" connection close moments later.
|
|
153
|
-
*
|
|
154
|
-
* Control node only: strand cohort nodes legitimately connect cross-party
|
|
155
|
-
* peers, so `CadreNode` threads the raw configured gater to them unchanged.
|
|
156
|
-
*/
|
|
157
|
-
export function createMembershipConnectionGater(
|
|
158
|
-
policy: InboundAdmissionPolicy,
|
|
159
|
-
base?: ConnectionGater,
|
|
160
|
-
decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
|
|
161
|
-
): ConnectionGater {
|
|
162
|
-
return {
|
|
163
|
-
...base,
|
|
164
|
-
denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
|
|
165
|
-
if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
|
|
166
|
-
return true;
|
|
167
|
-
}
|
|
168
|
-
const remotePeerId = peerId.toString();
|
|
169
|
-
try {
|
|
170
|
-
return !(await admitWithinDeadline(policy, remotePeerId, decisionTimeoutMs));
|
|
171
|
-
} catch (error) {
|
|
172
|
-
log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
|
|
173
|
-
return false;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Run the admission decision under {@link ADMISSION_DECISION_TIMEOUT_MS},
|
|
181
|
-
* resolving to "admit" if it has not settled in time (see that constant for why
|
|
182
|
-
* an unbounded await is not safe here). The timer is always cleared so a decided
|
|
183
|
-
* connection never holds the event loop open.
|
|
184
|
-
*/
|
|
185
|
-
async function admitWithinDeadline(
|
|
186
|
-
policy: InboundAdmissionPolicy,
|
|
187
|
-
remotePeerId: string,
|
|
188
|
-
timeoutMs: number
|
|
189
|
-
): Promise<boolean> {
|
|
190
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
191
|
-
try {
|
|
192
|
-
return await Promise.race([
|
|
193
|
-
Promise.resolve(policy.admitInbound(remotePeerId)),
|
|
194
|
-
new Promise<boolean>((resolve) => {
|
|
195
|
-
timer = setTimeout(() => {
|
|
196
|
-
log('admitInbound exceeded %dms for %s — admitting (fail-open; stream gates decide)', timeoutMs, remotePeerId);
|
|
197
|
-
resolve(true);
|
|
198
|
-
}, timeoutMs);
|
|
199
|
-
})
|
|
200
|
-
]);
|
|
201
|
-
} finally {
|
|
202
|
-
clearTimeout(timer);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Control-network inbound connection gate (defense-in-depth).
|
|
3
|
+
*
|
|
4
|
+
* Layer 2 of the membership enforcement chain: the PRIMARY gates are per-stream
|
|
5
|
+
* — every sensitive sereus control protocol rejects a peer that fails the
|
|
6
|
+
* voucher-anchored membership check (wake and strand-addr via
|
|
7
|
+
* `CadreNode.isAuthorizedMember`; the Optimystic control-DB protocols via the
|
|
8
|
+
* materialized-snapshot gate `CadreNode.authorizeInboundControlStream`), and
|
|
9
|
+
* the replicated rows an outsider *can* still write are disbelieved at read
|
|
10
|
+
* time. This module adds the opportunistic connection-level layer on top: a
|
|
11
|
+
* peer this node can positively determine is NOT authorized is refused at the
|
|
12
|
+
* encrypted-connection checkpoint, before any protocol negotiation, so a
|
|
13
|
+
* known-nothing outsider is never even in the conversation.
|
|
14
|
+
*
|
|
15
|
+
* ## The stranger allowlist (the ONE place it is defined)
|
|
16
|
+
*
|
|
17
|
+
* A libp2p connection gater decides per CONNECTION, before protocols are
|
|
18
|
+
* negotiated, so "allow seed, deny repo" cannot be expressed here — instead the
|
|
19
|
+
* policy admits a connection whenever a legitimate stranger interaction could be
|
|
20
|
+
* riding it, and the per-stream gates take over. The complete set of protocols a
|
|
21
|
+
* NOT-yet-authorized peer may legitimately speak on a control node is:
|
|
22
|
+
*
|
|
23
|
+
* - `/sereus/seed/1.0.0` ({@link SEED_PROTOCOL}) — enrollment seed delivery.
|
|
24
|
+
* An owner dials a brand-new node to seed it (the new node has no members
|
|
25
|
+
* yet, so its gate is inert), and an invited phone dials the owner before it
|
|
26
|
+
* is authorized (admitted via the enrollment window `CadreNode.createInvite`
|
|
27
|
+
* opens). The handler's own trust decision is the anchored seed-trust policy.
|
|
28
|
+
* - `/sereus/formation/1.0.0` ({@link FORMATION_PROTOCOL}) — cross-party
|
|
29
|
+
* strand formation via open invitations. Stranger-facing BY DESIGN: the
|
|
30
|
+
* initiator is another party, and its token is only checkable inside the
|
|
31
|
+
* protocol. The exemption is therefore keyed on EXPECTATION of a stranger,
|
|
32
|
+
* not capability to serve one: stranger denial is suspended only while this
|
|
33
|
+
* node has at least one UNEXPIRED, NOT-FULLY-CONSUMED open invitation
|
|
34
|
+
* outstanding (`StrandSolicitationService.hasOutstandingInvitation` — the
|
|
35
|
+
* tokens this process minted or published, plus any still-redeemable
|
|
36
|
+
* `FormationInvite` row the usage recorder can see). Merely registering the
|
|
37
|
+
* responder (`CadreNode.initializeStrandSolicitation`) does NOT suspend it,
|
|
38
|
+
* so an app that registers eagerly at node bring-up keeps a live gate. The
|
|
39
|
+
* handler's own trust decision remains the per-token check, which is
|
|
40
|
+
* strictly finer than this one: a peer admitted here can still be rejected
|
|
41
|
+
* in-protocol for a bogus or spent token.
|
|
42
|
+
*
|
|
43
|
+
* There is one further connection-level carve-out, which is NOT a protocol
|
|
44
|
+
* exemption and needs no stranger window:
|
|
45
|
+
*
|
|
46
|
+
* - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
|
|
47
|
+
* node runs as a separate libp2p identity whose peerId no sibling can
|
|
48
|
+
* recompute, so a relay-running control node would deny its circuit-relay
|
|
49
|
+
* reservation. Before starting a strand node, a member's control node
|
|
50
|
+
* announces that peerId over the already-authenticated strand-addr RPC, and
|
|
51
|
+
* the receiver holds a short-lived grant for it
|
|
52
|
+
* (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION and
|
|
53
|
+
* nothing else — a reservation needs no stream — and is deliberately
|
|
54
|
+
* invisible to the per-stream gate below, so a delegate still gets refused
|
|
55
|
+
* on every members-only protocol.
|
|
56
|
+
*
|
|
57
|
+
* Everything else a control node handles — the Optimystic control-DB protocols
|
|
58
|
+
* (`/optimystic/control-<party>/{repo,cluster,sync,block-transfer}/…`), wake
|
|
59
|
+
* (`/sereus/strand-wake/1.0.0`), and strand-addr (`/sereus/strand-addr/1.0.0`)
|
|
60
|
+
* — is members-only, and every one of them enforces that per-stream. Wake and
|
|
61
|
+
* strand-addr check `isAuthorizedMember` inside their handlers; the four
|
|
62
|
+
* control-DB protocols are gated by the fail-closed
|
|
63
|
+
* `CadreNode.authorizeInboundControlStream` (wired as libp2p's
|
|
64
|
+
* `authorizeInboundStream` upstream hook), which judges each inbound stream
|
|
65
|
+
* against the MATERIALIZED authorized-peer snapshot — synchronous and
|
|
66
|
+
* in-memory, because a live DB read from inside the gate would deadlock into
|
|
67
|
+
* mutual denial. The two layers complement, not duplicate: this connection
|
|
68
|
+
* gate is fail-open over a live DB read (deny only on positive proof of an
|
|
69
|
+
* outsider), the stream gate is fail-closed over the snapshot and has NO
|
|
70
|
+
* stranger carve-outs — an enrollment window admits a stranger's connection
|
|
71
|
+
* for seed delivery, yet its repo streams are still refused.
|
|
72
|
+
*
|
|
73
|
+
* ## Fail-open, deliberately
|
|
74
|
+
*
|
|
75
|
+
* This layer only ever denies on a POSITIVE determination of "unauthorized
|
|
76
|
+
* outsider while no stranger path is open". Any error, missing dependency, or
|
|
77
|
+
* ambiguous state admits the connection and defers to the fail-closed stream
|
|
78
|
+
* gates — a DB hiccup must not partition a legitimate cadre.
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
import debug from 'debug';
|
|
82
|
+
import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
|
|
83
|
+
import { SEED_PROTOCOL } from './seed-bootstrap.js';
|
|
84
|
+
import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
|
|
85
|
+
|
|
86
|
+
const log = debug('sereus:cadre:connection-gater');
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The protocols a not-yet-authorized peer may legitimately speak on a control
|
|
90
|
+
* node (see the module doc above for why each is open and where its own trust
|
|
91
|
+
* decision lives). Exported as the single reference point so the allowlist
|
|
92
|
+
* cannot silently drift across modules.
|
|
93
|
+
*/
|
|
94
|
+
export const STRANGER_OPEN_PROTOCOLS: readonly string[] = [SEED_PROTOCOL, FORMATION_PROTOCOL];
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* How long `CadreNode.createInvite` holds the inbound gate open for strangers
|
|
98
|
+
* when the invite carries no explicit expiry: the invitee must dial in before
|
|
99
|
+
* it is authorized, and an expiry-less invite gives the gate no bound of its
|
|
100
|
+
* own. Redeeming after this window still works once the owner re-mints (or the
|
|
101
|
+
* caller re-opens the window via `CadreNode.openEnrollmentWindow`).
|
|
102
|
+
*/
|
|
103
|
+
export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Deadline for one admission decision, after which the connection is ADMITTED.
|
|
107
|
+
*
|
|
108
|
+
* libp2p awaits `denyInboundEncryptedConnection` inside the inbound upgrade
|
|
109
|
+
* WITHOUT racing its inbound-upgrade timeout signal (unlike the pre-encryption
|
|
110
|
+
* `denyInboundConnection` hook), so a decision that never settles wedges that
|
|
111
|
+
* upgrade forever — the connection-manager's inbound-upgrade slot is taken by
|
|
112
|
+
* `acceptIncomingConnection` and released in the `finally` that never runs. The
|
|
113
|
+
* real policy reads the control DB (`listAuthorizedMembers`), which can pull
|
|
114
|
+
* over the network, so "never settles" is reachable. Bounding it here keeps the
|
|
115
|
+
* fail-open contract honest: a slow decision admits rather than silently
|
|
116
|
+
* failing closed (or not at all).
|
|
117
|
+
*/
|
|
118
|
+
export const ADMISSION_DECISION_TIMEOUT_MS = 2_000;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The admission decision the gate defers to — implemented by
|
|
122
|
+
* `CadreNode.admitInboundControlConnection` (enrollment windows, anchor state,
|
|
123
|
+
* bootstrap infra, the authorized-member set). Kept injectable so the gater's
|
|
124
|
+
* composition/fail-open behavior is unit-testable without a full node.
|
|
125
|
+
*/
|
|
126
|
+
export interface InboundAdmissionPolicy {
|
|
127
|
+
/** Should an inbound encrypted connection from this peer be admitted? */
|
|
128
|
+
admitInbound(remotePeerId: string): Promise<boolean> | boolean;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Build the control node's connection gater: the caller-supplied gater (if any)
|
|
133
|
+
* with membership admission composed onto `denyInboundEncryptedConnection` —
|
|
134
|
+
* the earliest checkpoint where the remote's authenticated PeerId is known.
|
|
135
|
+
*
|
|
136
|
+
* Composition semantics: every hook of `base` is preserved as-is; on the
|
|
137
|
+
* inbound-encrypted hook a deny from EITHER the base gater or the admission
|
|
138
|
+
* policy denies. A policy error — or a decision slower than
|
|
139
|
+
* `decisionTimeoutMs` — admits (fail-open, see module doc); the base gater's
|
|
140
|
+
* verdict is still honored first.
|
|
141
|
+
*
|
|
142
|
+
* NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
|
|
143
|
+
* prototype methods; every caller in this repo (and libp2p's own default)
|
|
144
|
+
* supplies a plain object. If a class-based gater ever shows up, delegate
|
|
145
|
+
* per-hook instead of spreading.
|
|
146
|
+
*
|
|
147
|
+
* Deny timing, as observed by the denied dialer: noise negotiates the muxer in
|
|
148
|
+
* the security handshake's early data, so the DIALER's upgrade may complete
|
|
149
|
+
* (its `dial()` resolves) before this receiver-side hook runs. The deny then
|
|
150
|
+
* aborts the receiver's upgrade — the receiver never registers the connection
|
|
151
|
+
* and never creates its muxer, so no protocol can ever be negotiated — and the
|
|
152
|
+
* dialer sees its "open" connection close moments later.
|
|
153
|
+
*
|
|
154
|
+
* Control node only: strand cohort nodes legitimately connect cross-party
|
|
155
|
+
* peers, so `CadreNode` threads the raw configured gater to them unchanged.
|
|
156
|
+
*/
|
|
157
|
+
export function createMembershipConnectionGater(
|
|
158
|
+
policy: InboundAdmissionPolicy,
|
|
159
|
+
base?: ConnectionGater,
|
|
160
|
+
decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
|
|
161
|
+
): ConnectionGater {
|
|
162
|
+
return {
|
|
163
|
+
...base,
|
|
164
|
+
denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
|
|
165
|
+
if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
const remotePeerId = peerId.toString();
|
|
169
|
+
try {
|
|
170
|
+
return !(await admitWithinDeadline(policy, remotePeerId, decisionTimeoutMs));
|
|
171
|
+
} catch (error) {
|
|
172
|
+
log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Run the admission decision under {@link ADMISSION_DECISION_TIMEOUT_MS},
|
|
181
|
+
* resolving to "admit" if it has not settled in time (see that constant for why
|
|
182
|
+
* an unbounded await is not safe here). The timer is always cleared so a decided
|
|
183
|
+
* connection never holds the event loop open.
|
|
184
|
+
*/
|
|
185
|
+
async function admitWithinDeadline(
|
|
186
|
+
policy: InboundAdmissionPolicy,
|
|
187
|
+
remotePeerId: string,
|
|
188
|
+
timeoutMs: number
|
|
189
|
+
): Promise<boolean> {
|
|
190
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
191
|
+
try {
|
|
192
|
+
return await Promise.race([
|
|
193
|
+
Promise.resolve(policy.admitInbound(remotePeerId)),
|
|
194
|
+
new Promise<boolean>((resolve) => {
|
|
195
|
+
timer = setTimeout(() => {
|
|
196
|
+
log('admitInbound exceeded %dms for %s — admitting (fail-open; stream gates decide)', timeoutMs, remotePeerId);
|
|
197
|
+
resolve(true);
|
|
198
|
+
}, timeoutMs);
|
|
199
|
+
})
|
|
200
|
+
]);
|
|
201
|
+
} finally {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
}
|
|
204
|
+
}
|