@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.
Files changed (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. 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
+ }