@serfab/cadre-core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Node-only filesystem helpers: atomic file write, filename-safe encoding, and
3
+ * the ENOENT check, shared by `key-store-file.ts` and `file-durable-slot.ts`.
4
+ *
5
+ * This module imports `node:fs/promises`, so — like its consumers — it is kept
6
+ * OUT of the package's cross-platform default entry and is not itself an
7
+ * exported subpath; it is only reachable through the Node-only store modules.
8
+ */
9
+ import debug from 'debug';
10
+ import { mkdir, rm, rename, open } from 'node:fs/promises';
11
+ const log = debug('sereus:cadre:fs-atomic');
12
+ /** Best-effort POSIX permissions (ignored on Windows / unsupported FSes). */
13
+ export const DIR_MODE = 0o700;
14
+ export const FILE_MODE = 0o600;
15
+ /**
16
+ * Percent-encode a string into a filesystem-safe filename component. Beyond
17
+ * `encodeURIComponent` (which already escapes `/`, spaces, and unicode), this
18
+ * also escapes the unreserved characters `encodeURIComponent` leaves intact but
19
+ * that are unsafe in filenames on some platforms (notably `*` on Windows) — and
20
+ * `.`, so a file suffix appended by the caller is the only literal dot, making
21
+ * suffix-stripping unambiguous. Reversed by `decodeURIComponent`. The result
22
+ * contains only `A-Za-z0-9-_` and `%XX`.
23
+ */
24
+ export function encodeFileSafeComponent(component) {
25
+ return encodeURIComponent(component).replace(/[!'()*~.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
26
+ }
27
+ /** Whether an unknown error is a Node "file/dir not found" (ENOENT). */
28
+ export function isNotFound(error) {
29
+ return typeof error === 'object' && error !== null
30
+ && error.code === 'ENOENT';
31
+ }
32
+ /**
33
+ * Crash-atomic file write: a concurrent reader sees either the complete
34
+ * previous bytes or the complete new bytes, never a torn file. `dir` is created
35
+ * (0700) if absent; the data is written to `tmpPath` (created exclusively,
36
+ * 0600), fsync'd, then atomically renamed onto `finalPath`. A failure at any
37
+ * point removes the temp file and leaves the previous file untouched.
38
+ *
39
+ * `tmpPath` must be a sibling of `finalPath` (same directory) so the rename
40
+ * stays within one filesystem and is therefore atomic, and should carry a
41
+ * random component so concurrent writers (and crash-orphaned leftovers) are
42
+ * collide-free.
43
+ *
44
+ * Durability bar: the temp file is fsync'd before the rename so a power loss
45
+ * cannot surface a file whose bytes never reached the platter, and `dir` is
46
+ * fsync'd afterwards (best-effort — see {@link syncDirBestEffort}) so the
47
+ * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
48
+ * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
49
+ * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
50
+ * holds the destination open. That cross-process case is out of scope for the
51
+ * single-flight in-process callers here; such a failure surfaces to the caller
52
+ * with the previous file left intact.
53
+ */
54
+ export async function writeFileAtomically(dir, tmpPath, finalPath, data) {
55
+ await mkdir(dir, { recursive: true, mode: DIR_MODE });
56
+ // 'wx' creates the temp file exclusively; a name collision (astronomically
57
+ // unlikely given the caller's random component) fails here before we own anything.
58
+ const handle = await open(tmpPath, 'wx', FILE_MODE);
59
+ try {
60
+ try {
61
+ await handle.writeFile(data);
62
+ await handle.sync(); // land bytes on disk before the rename exposes them
63
+ }
64
+ finally {
65
+ await handle.close().catch(() => { });
66
+ }
67
+ await rename(tmpPath, finalPath);
68
+ }
69
+ catch (error) {
70
+ // Any failure after creation (write, sync, or rename): drop the temp
71
+ // file so a retry leaves no `.tmp` debris. The destination is only ever
72
+ // swapped by the atomic rename, so the previous bytes stay intact.
73
+ await rm(tmpPath, { force: true }).catch(() => { });
74
+ throw error;
75
+ }
76
+ await syncDirBestEffort(dir);
77
+ }
78
+ /**
79
+ * Best-effort fsync of a directory so a fresh file's directory entry is
80
+ * durable across power loss. Opening a directory for fsync is not portable
81
+ * (unsupported on Windows and some filesystems), and rename atomicity does not
82
+ * depend on it — so a failure here is logged and swallowed, never surfaced.
83
+ */
84
+ async function syncDirBestEffort(dir) {
85
+ let dirHandle;
86
+ try {
87
+ dirHandle = await open(dir, 'r');
88
+ await dirHandle.sync();
89
+ }
90
+ catch (error) {
91
+ log('directory fsync skipped for %s: %o', dir, error);
92
+ }
93
+ finally {
94
+ await dirHandle?.close().catch(() => { });
95
+ }
96
+ }
97
+ //# sourceMappingURL=fs-atomic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fs-atomic.js","sourceRoot":"","sources":["../src/fs-atomic.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAG3D,MAAM,GAAG,GAAG,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAE5C,6EAA6E;AAC7E,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,CAAC;AAC9B,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC;AAE/B;;;;;;;;GAQG;AACH,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACxD,OAAO,kBAAkB,CAAC,S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AC,CAAC;QACnD,MAAM,KAAK,CAAC;IACb,CAAC;IACD,MAAM,iBAAiB,CAAC,GAAG,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,iBAAiB,CAAC,GAAW;IAC3C,IAAI,SAAiC,CAAC;IACtC,IAAI,CAAC;QACJ,SAAS,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACjC,MAAM,SAAS,CAAC,IAAI,EAAE,CAAC;IACxB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,GAAG,CAAC,oCAAoC,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACV,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC1C,CAAC;AACF,CAAC"}
@@ -0,0 +1,49 @@
1
+ import type { PrivateKey } from '@libp2p/interface';
2
+ import { type KeyId, type KeyStore } from './key-store.js';
3
+ /**
4
+ * Load the node identity key from `keyStore`, generating and persisting a fresh
5
+ * Ed25519 key when the slot is empty.
6
+ *
7
+ * A rejected `get` (e.g. {@link KeyStoreAccessError} from a cancelled biometric
8
+ * prompt) **propagates** — we never fall through to generation on a read error,
9
+ * because that would silently orphan an existing but momentarily unreadable
10
+ * identity. Corrupt bytes in the slot likewise throw rather than regenerate.
11
+ *
12
+ * Idempotent in effect: a second call on a populated store loads the stored key
13
+ * and writes nothing.
14
+ *
15
+ * @param keyStore - Backend the identity is read from / persisted to.
16
+ * @param keyId - Slot id; defaults to {@link DEFAULT_IDENTITY_KEY_ID}.
17
+ * @returns The resolved libp2p private key.
18
+ */
19
+ export declare function loadOrCreateIdentityKey(keyStore: KeyStore, keyId?: KeyId): Promise<PrivateKey>;
20
+ /**
21
+ * Proof-of-possession signer for a node key, for out-of-band HTTP services that
22
+ * want to attribute a request to a peer id.
23
+ *
24
+ * Deliberately generic — it carries no ICE/TURN vocabulary, and the message it
25
+ * signs is the caller's business. The one consumer today is the reference apps'
26
+ * `loadIceConfig`, which signs the TURN credential issuer's peer assertion; those
27
+ * files mirror this interface structurally rather than importing it, so they stay
28
+ * dependency-free.
29
+ */
30
+ export interface PeerKeySigner {
31
+ /** base58btc peer id — the same string libp2p reports for this node. */
32
+ readonly peerId: string;
33
+ /** base64url of the libp2p protobuf-encoded public key. */
34
+ readonly publicKeyB64: string;
35
+ /** Sign the UTF-8 bytes of `message`; resolves to a base64url signature. */
36
+ sign(message: string): Promise<string>;
37
+ }
38
+ /**
39
+ * Wrap a libp2p private key as a {@link PeerKeySigner}.
40
+ *
41
+ * Ed25519 only: the peer id is derived as an identity multihash (so
42
+ * `publicKey.toString()` already *is* the base58btc peer id — no `@libp2p/peer-id`
43
+ * round trip needed), and verifiers of this proof accept nothing else.
44
+ *
45
+ * @param privateKey - The node's libp2p Ed25519 private key.
46
+ * @returns A signer exposing the peer id, the encoded public key, and `sign`.
47
+ * @throws If the key is not Ed25519.
48
+ */
49
+ export declare function peerKeySigner(privateKey: PrivateKey): PeerKeySigner;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * identity-key — the load-or-create rule for a {@link KeyStore}-backed node
3
+ * identity, plus the "prove you hold this node key" signer built on top of it.
4
+ *
5
+ * Both live here because both are needed *outside* `CadreNode`: an embedding app
6
+ * (the React Native reference app) has to resolve its identity key before the node
7
+ * is constructed, so it can sign an out-of-band HTTP request with the same key the
8
+ * node will then load. Keeping one copy of the load-or-create rule is load-bearing
9
+ * — a second copy that drifted could generate a fresh key and orphan the real
10
+ * identity.
11
+ *
12
+ * Dependency-free beyond `@libp2p/crypto` + `uint8arrays` (both already core
13
+ * dependencies), so this module is safe in every (RN / browser / Node) entry graph.
14
+ */
15
+ import debug from 'debug';
16
+ import { generateKeyPair, privateKeyToProtobuf, privateKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';
17
+ import { toString as uint8ArrayToString } from 'uint8arrays';
18
+ import { DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
19
+ const log = debug('sereus:cadre:identity-key');
20
+ /**
21
+ * Load the node identity key from `keyStore`, generating and persisting a fresh
22
+ * Ed25519 key when the slot is empty.
23
+ *
24
+ * A rejected `get` (e.g. {@link KeyStoreAccessError} from a cancelled biometric
25
+ * prompt) **propagates** — we never fall through to generation on a read error,
26
+ * because that would silently orphan an existing but momentarily unreadable
27
+ * identity. Corrupt bytes in the slot likewise throw rather than regenerate.
28
+ *
29
+ * Idempotent in effect: a second call on a populated store loads the stored key
30
+ * and writes nothing.
31
+ *
32
+ * @param keyStore - Backend the identity is read from / persisted to.
33
+ * @param keyId - Slot id; defaults to {@link DEFAULT_IDENTITY_KEY_ID}.
34
+ * @returns The resolved libp2p private key.
35
+ */
36
+ export async function loadOrCreateIdentityKey(keyStore, keyId = DEFAULT_IDENTITY_KEY_ID) {
37
+ // A rejection here (e.g. KeyStoreAccessError) must propagate — do NOT fall
38
+ // through to generation, which would orphan an existing but unreadable key.
39
+ const bytes = await keyStore.get(keyId);
40
+ if (bytes) {
41
+ // Corrupt/garbage bytes throw here; surface loudly rather than
42
+ // regenerating (which would orphan the real identity).
43
+ const loaded = privateKeyFromProtobuf(bytes);
44
+ log('Identity key loaded from key store (slot present)');
45
+ return loaded;
46
+ }
47
+ const generated = await generateKeyPair('Ed25519');
48
+ await keyStore.set(keyId, privateKeyToProtobuf(generated));
49
+ log('Identity key generated and persisted to key store (first run)');
50
+ return generated;
51
+ }
52
+ /**
53
+ * Wrap a libp2p private key as a {@link PeerKeySigner}.
54
+ *
55
+ * Ed25519 only: the peer id is derived as an identity multihash (so
56
+ * `publicKey.toString()` already *is* the base58btc peer id — no `@libp2p/peer-id`
57
+ * round trip needed), and verifiers of this proof accept nothing else.
58
+ *
59
+ * @param privateKey - The node's libp2p Ed25519 private key.
60
+ * @returns A signer exposing the peer id, the encoded public key, and `sign`.
61
+ * @throws If the key is not Ed25519.
62
+ */
63
+ export function peerKeySigner(privateKey) {
64
+ if (privateKey.type !== 'Ed25519') {
65
+ throw new Error(`peerKeySigner requires an Ed25519 key, got ${privateKey.type}`);
66
+ }
67
+ const publicKey = privateKey.publicKey;
68
+ // For Ed25519 the public key's digest is an identity multihash, so its string
69
+ // form is the peer id itself — the same value `peerIdFromPrivateKey` produces.
70
+ const peerId = publicKey.toString();
71
+ const publicKeyB64 = uint8ArrayToString(publicKeyToProtobuf(publicKey), 'base64url');
72
+ return {
73
+ peerId,
74
+ publicKeyB64,
75
+ async sign(message) {
76
+ const signature = await privateKey.sign(new TextEncoder().encode(message));
77
+ return uint8ArrayToString(signature, 'base64url');
78
+ }
79
+ };
80
+ }
81
+ //# sourceMappingURL=identity-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-key.js","sourceRoot":"","sources":["../src/identity-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACzH,OAAO,EAAE,QAAQ,IAAI,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE7D,OAAO,EAAE,uBAAuB,EAA6B,MAAM,gBAAgB,CAAC;AAEpF,MAAM,GAAG,GAAG,KAAK,CAAC,2BAA2B,CAAC,CAAC;AAE/C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,QAAkB,EAClB,QAAe,uBAAuB;IAEtC,2EAA2E;IAC3E,4EAA4E;IAC5E,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,IAAI,KAAK,EAAE,CAAC;QACV,+DAA+D;QAC/D,uDAAuD;QACvD,MAAM,MAAM,GAAG,sBAAsB,CAAC,KAAK,CAAC,CAAC;QAC7C,GAAG,CAAC,mDAAmD,CAAC,CAAC;QACzD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,SAAS,GAAG,MAAM,eAAe,CAAC,SAAS,CAAC,CAAC;IACnD,MAAM,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC,CAAC;IAC3D,GAAG,CAAC,+DAA+D,CAAC,CAAC;IACrE,OAAO,SAAS,CAAC;AACnB,CAAC;AAqBD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,aAAa,CAAC,UAAsB;IAClD,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,8CAA8C,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;IACnF,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC;IACvC,8EAA8E;IAC9E,+EAA+E;IAC/E,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,EAAE,CAAC;IACpC,MAAM,YAAY,GAAG,kBAAkB,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,WAAW,CAAC,CAAC;IAErF,OAAO;QACL,MAAM;QACN,YAAY;QACZ,KAAK,CAAC,IAAI,CAAC,OAAe;YACxB,MAAM,SAAS,GAAG,MAAM,UAAU,CAAC,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3E,OAAO,kBAAkB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QACpD,CAAC;KACF,CAAC;AACJ,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,23 +1,31 @@
1
1
  export * from './types.js';
2
2
  export { canonicalJson } from './canonical-json.js';
3
3
  export { CadreNode } from './cadre-node.js';
4
- export { ControlDatabase, buildAuthorizationMessage, type ControlDatabaseConfig, type ControlTable } from './control-database.js';
5
- export { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, type Ed25519KeyPair } from './ed25519-key.js';
4
+ export { ControlDatabase, MissingHostStrandError, buildAuthorizationMessage, formationVouchMessage, formationConsentMessage, REAPABLE_TABLES, type ReapableTable, type ControlDatabaseConfig, type ControlTable, type RevocableTable, type FormationUsageResult, type MembershipChangeListener, type GuardedDeleteListener, type RevokedRowRef } from './control-database.js';
5
+ export { CONTROL_WRITE_ATTEMPTS, CONTROL_WRITE_RETRY_BUDGET_MS, SCHEMA_INIT_ATTEMPTS, SCHEMA_INIT_RETRY_POLICY, isRetriableControlWriteFailure, isRetriableSchemaInitFailure, retryControlWrite, type ControlWriteRetryOptions } from './control-write-retry.js';
6
+ export { controlAuthorizationFields, type ControlDomain, type ControlAction } from './control-authorization.js';
7
+ export { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, requireEd25519PublicKeyB64, type Ed25519KeyPair } from './ed25519-key.js';
6
8
  export { InMemoryKeyStore, KeyStoreAccessError, DEFAULT_IDENTITY_KEY_ID, type KeyStore, type KeyId } from './key-store.js';
9
+ export { loadOrCreateIdentityKey, peerKeySigner, type PeerKeySigner } from './identity-key.js';
10
+ export { MemoryTrustedOwnerStore, PersistentTrustedOwnerStore, type TrustedOwnerStore, type TrustSource } from './trusted-owner-store.js';
11
+ export type { DurableSlot } from './node-local-snapshot.js';
12
+ export { MemoryBootstrapPeerStore, PersistentBootstrapPeerStore, type BootstrapPeerStore, type BootstrapPeerEntry } from './bootstrap-peer-store.js';
7
13
  export { StrandDatabase, type StrandDatabaseConfig } from './strand-database.js';
8
14
  export { StrandWatcher, type StrandWatcherCallbacks, type StrandQueryable, type SAppIdLookup, type StrandRowWithApp } from './strand-watcher.js';
9
15
  export { StrandInstanceManager, type StartStrandConfig, type ResumeStrandOverrides, getStrandStoragePath } from './strand-instance-manager.js';
16
+ export { StrandBackfill, DEFAULT_STRAND_BACKFILL, MAX_BLOCK_MESSAGE_BYTES, type StrandBackfillConfig, type StrandBackfillDeps, type StrandBackfillResult, type StrandBackfillPushClient } from './strand-backfill.js';
10
17
  export { HibernationManager, type HibernationCallbacks } from './hibernation-manager.js';
11
18
  export { ArachnodeStub, createArachnodeStub, type RingConfig } from './arachnode-stub.js';
12
19
  export { EnrollmentService, type MemberVerifier, type MemberRegistry } from './enrollment.js';
13
- export { StrandSolicitationService, createDefaultFormationResponseValidator, type DisclosureValidator, type FormationUsageRecorder, type ResolvedHostStrand, type StrandProvisioner, type FormationSigner, type FormationResponseValidator, type StrandSolicitationServiceOptions } from './strand-solicitation.js';
20
+ export { StrandSolicitationService, createDefaultFormationResponseValidator, type DisclosureValidator, type FormationUsageRecorder, type ResolvedHostStrand, type StrandProvisioner, type FormationResponseValidator, type StrandSolicitationServiceOptions } from './strand-solicitation.js';
21
+ export { createHttpFormationApprover, signFormationApproval, verifyFormationApproval, FormationApprovalError, type FormationApprovalRequest, type FormationVouchFields, type FormationApproval, type FormationApprover, type FormationApprovalFailure } from './formation-approval.js';
14
22
  export { ControlFormationUsageRecorder } from './control-formation-recorder.js';
15
23
  export { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
16
- export { signStrandPayload, verifyStrandPayload, bootstrapFounderMembership, issueInvite, consumeInvite, addMemberByManager, registerMemberPeer, addManager, removeManager, STRAND_ENGINE, STRAND_ENGINE_VERSION, type FounderBootstrapParams, type IssueInviteParams, type IssuedInvite, type ConsumeInviteParams, type AddMemberByManagerParams, type RegisterMemberPeerParams, type AddManagerParams, type RemoveManagerParams } from './strand-membership-writer.js';
24
+ export { signStrandPayload, verifyStrandPayload, signStrandApproval, generateStrandStampId, bootstrapFounderMembership, issueInvite, consumeInvite, cancelInvite, listOutstandingInvites, addMemberByManager, revokeMember, leaveStrand, registerMemberPeer, listMemberPeers, removeMemberPeer, addManager, admitManager, removeManager, STRAND_ENGINE, STRAND_ENGINE_VERSION, type FounderBootstrapParams, type IssueInviteParams, type IssuedInvite, type ConsumeInviteParams, type CancelInviteParams, type OutstandingInvite, type AddMemberByManagerParams, type RevokeMemberParams, type LeaveStrandParams, type RegisterMemberPeerParams, type RemoveOwnPeerParams, type RemoveMemberPeerByManagerParams, type RemoveMemberPeerParams, type AddManagerParams, type AdmitManagerParams, type RemoveManagerParams } from './strand-membership-writer.js';
17
25
  export { canonicalDatetime } from './canonical-datetime.js';
18
26
  export { StrandMemberRegistry, StrandMemberVerifier, memberRegistrationPayload, type StrandAdmission } from './strand-member-registry.js';
19
27
  export { SeedBootstrapService, SEED_PROTOCOL, ed25519PublicKeyB64FromPeerId, type SeedBootstrapConfig, type SeedEventCallbacks } from './seed-bootstrap.js';
20
- export { peerAuthorizationDigest, cadrePeerVoucherDigest, cadrePeerRemoveDigest, verifyPeerAuthorization } from './peer-authorization.js';
28
+ export { peerAuthorizationDigest, cadrePeerVoucherDigest, cadrePeerRemoveDigest, deviceTokenAddDigest, deviceTokenRemoveDigest, formationConsentDigest, verifyPeerAuthorization, verifyCadrePeerVoucher, verifyFormationConsent, type DeviceTokenAuthorizedRow } from './peer-authorization.js';
21
29
  export { StrandWakeService, dialWake, WAKE_PROTOCOL, type StrandWakeServiceOptions, type DialWakeOptions } from './strand-wake-protocol.js';
22
30
  export { StrandAddrService, collectStrandAddrs, STRAND_ADDR_PROTOCOL, type StrandAddrServiceOptions, type StrandAddrPeer, type CollectStrandAddrsOptions } from './strand-addr-protocol.js';
23
31
  export { peerRecordSignedPayload, signPeerRecord, verifyPeerRecordSignature, isPeerRecordFresh, isSignalingAddr, orderSignalingFirst, currentMemberTrustPolicy, DEFAULT_PEER_RECORD_MAX_AGE_MS, DEFAULT_PEER_RECORD_HEARTBEAT_MS } from './peer-record.js';
@@ -26,9 +34,11 @@ export { STRAND_WAKE_TYPE, type StrandWakePayload } from './strand-wake-payload.
26
34
  export type { PushNotifier, PushMessage, PushSendResult } from './push-notifier.js';
27
35
  export { validatePushCredentials, redactPushCredentials, REDACTED } from './push-credentials.js';
28
36
  export { PushFanoutService, DEFAULT_PUSH_COOLDOWN_MS, DEFAULT_PUSH_DEBOUNCE_MS, type PushFanoutOptions, type FanoutMember } from './push-fanout.js';
29
- export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE, type ControlCohortSelection } from './control-cohort.js';
30
- export { dbAnchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy, type SeedTrustPolicy, type SeedTrustContext, type SeedTrustDecision } from './seed-trust-policy.js';
37
+ export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE, type ControlCohortSelection } from './control-cohort.js';
38
+ export { anchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy, type SeedTrustPolicy, type SeedTrustContext, type SeedTrustDecision } from './seed-trust-policy.js';
31
39
  export { signSchema, verifySchema, assertSchemaSignature, SchemaVerificationError } from './schema-verification.js';
32
40
  export { FormationListener, dialFormation, isValidResponderCreatesResult, FORMATION_PROTOCOL, type FormationParty, type FormationContactMessage, type FormationResultMessage, type FormationProvisionResult, type FormationStrandInfo, type FormationDbConnectionInfo, type FormationListenerOptions, type FormationDialOptions, type ResponderProvisionOutcome } from './strand-formation-protocol.js';
33
41
  export { StrandFormationManager, createStrandFormationManager, type StrandFormationManagerConfig, type StrandFormationManagerOptions } from './strand-formation-manager.js';
42
+ export { createMembershipConnectionGater, STRANGER_OPEN_PROTOCOLS, DEFAULT_ENROLLMENT_WINDOW_MS, ADMISSION_DECISION_TIMEOUT_MS, type InboundAdmissionPolicy } from './membership-connection-gater.js';
43
+ export { circuitMultiaddrs, superviseRelayReservation, DEFAULT_RELAY_RESERVE_TIMEOUT_MS, DEFAULT_RELAY_RESERVE_POLL_MS, DEFAULT_RELAY_CHECK_MS, DEFAULT_RELAY_MIN_BACKOFF_MS, DEFAULT_RELAY_MAX_BACKOFF_MS, type RelayReservationStatus, type RelayReservationState, type RelayReserveOptions, type RelayReservationSupervisor, type RelayReservationSupervisorOptions } from './relay-reservation.js';
34
44
  export { classifyTransport, classifyConnectionPath, summarizeConnectionPaths, emptyConnectionPathSummary, DEFAULT_SETTLE_WINDOW_MS, type ConnectionPathKind, type ConnectionTransport, type ConnectionPath, type ConnectionPathSummary, type ConnectionLike } from './diagnostics/connection-path.js';
package/dist/index.js CHANGED
@@ -5,20 +5,46 @@ export { canonicalJson } from './canonical-json.js';
5
5
  // Main CadreNode class
6
6
  export { CadreNode } from './cadre-node.js';
7
7
  // Control database
8
- export { ControlDatabase, buildAuthorizationMessage } from './control-database.js';
8
+ export { ControlDatabase, MissingHostStrandError, buildAuthorizationMessage, formationVouchMessage, formationConsentMessage, REAPABLE_TABLES } from './control-database.js';
9
+ // Bounded retry for transient control-write failures (classifier + loop behind
10
+ // ControlDatabase.lockedWithRetry; exported so the integration package can drive the
11
+ // classifier against real engine errors)
12
+ export { CONTROL_WRITE_ATTEMPTS, CONTROL_WRITE_RETRY_BUDGET_MS, SCHEMA_INIT_ATTEMPTS, SCHEMA_INIT_RETRY_POLICY, isRetriableControlWriteFailure, isRetriableSchemaInitFailure, retryControlWrite } from './control-write-retry.js';
13
+ // Control-plane authorization field vector (the domain/action tagging every signer shares)
14
+ export { controlAuthorizationFields } from './control-authorization.js';
9
15
  // Ed25519 key bridge (libp2p Ed25519 -> base64url keypair)
10
- export { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate } from './ed25519-key.js';
16
+ export { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, requireEd25519PublicKeyB64 } from './ed25519-key.js';
11
17
  // Pluggable key store (backend-agnostic identity/owner key material seam).
12
18
  // Dependency-free: the interface, error, default slot id, and in-memory backend
13
19
  // are safe in every (RN/browser/Node) entry graph. The Node FileKeyStore is a
14
20
  // separate subpath module ('@serfab/cadre-core/key-store-file') so its node:fs
15
21
  // import never lands here.
16
22
  export { InMemoryKeyStore, KeyStoreAccessError, DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
23
+ // The KeyStore-backed identity rule, shared with embedding apps that need the
24
+ // node key BEFORE `CadreNode` exists (RN resolves it to sign its ICE-manifest
25
+ // request), plus the generic "prove you hold this node key" signer built on it.
26
+ export { loadOrCreateIdentityKey, peerKeySigner } from './identity-key.js';
27
+ // Node-local trusted-owner anchor: the NON-replicated, per-party record of
28
+ // out-of-band-established owner keys (the trust anchor the replicated OwnerKey
29
+ // table cannot be). Cross-platform: interface + in-memory store only — the
30
+ // file-backed store is the Node-only subpath
31
+ // '@serfab/cadre-core/trusted-owner-store-file' (same isolation as
32
+ // key-store-file) so node:fs never lands in this graph.
33
+ export { MemoryTrustedOwnerStore, PersistentTrustedOwnerStore } from './trusted-owner-store.js';
34
+ // Node-local cold-start bootstrap-peer store: the dial targets retained from an
35
+ // applied seed so a node that could not connect on its first try keeps retrying
36
+ // across restarts. Same cross-platform split as the trusted-owner anchor above —
37
+ // interface + in-memory store here, Node-only file backend behind the subpath
38
+ // '@serfab/cadre-core/bootstrap-peer-store-file'.
39
+ export { MemoryBootstrapPeerStore, PersistentBootstrapPeerStore } from './bootstrap-peer-store.js';
17
40
  // Strand database
18
41
  export { StrandDatabase } from './strand-database.js';
19
42
  // Strand management
20
43
  export { StrandWatcher } from './strand-watcher.js';
21
44
  export { StrandInstanceManager, getStrandStoragePath } from './strand-instance-manager.js';
45
+ // Strand peer-join block catch-up (push this strand's own blocks to each newly
46
+ // connected strand peer, so a late joiner physically holds pre-join blocks).
47
+ export { StrandBackfill, DEFAULT_STRAND_BACKFILL, MAX_BLOCK_MESSAGE_BYTES } from './strand-backfill.js';
22
48
  // Hibernation
23
49
  export { HibernationManager } from './hibernation-manager.js';
24
50
  // Arachnode (stub)
@@ -27,6 +53,9 @@ export { ArachnodeStub, createArachnodeStub } from './arachnode-stub.js';
27
53
  export { EnrollmentService } from './enrollment.js';
28
54
  // Strand Solicitation
29
55
  export { StrandSolicitationService, createDefaultFormationResponseValidator } from './strand-solicitation.js';
56
+ // Formation approval client: asks an invite's ValidationUrl hook whether ONE redemption
57
+ // may proceed, and checks the answer against the bytes the control database will verify.
58
+ export { createHttpFormationApprover, signFormationApproval, verifyFormationApproval, FormationApprovalError } from './formation-approval.js';
30
59
  // DB-backed FormationUsageRecorder (reads/writes the real CadreControl tables)
31
60
  export { ControlFormationUsageRecorder } from './control-formation-recorder.js';
32
61
  // Closed-strand member key generation (ed25519 protobuf, base64) + the
@@ -35,7 +64,7 @@ export { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-ke
35
64
  // Strand membership writer (founder bootstrap, invite issuance/consumption,
36
65
  // manager-admit, member-peer registration, manager rotation, + shared signing
37
66
  // primitives reused across the flows).
38
- export { signStrandPayload, verifyStrandPayload, bootstrapFounderMembership, issueInvite, consumeInvite, addMemberByManager, registerMemberPeer, addManager, removeManager, STRAND_ENGINE, STRAND_ENGINE_VERSION } from './strand-membership-writer.js';
67
+ export { signStrandPayload, verifyStrandPayload, signStrandApproval, generateStrandStampId, bootstrapFounderMembership, issueInvite, consumeInvite, cancelInvite, listOutstandingInvites, addMemberByManager, revokeMember, leaveStrand, registerMemberPeer, listMemberPeers, removeMemberPeer, addManager, admitManager, removeManager, STRAND_ENGINE, STRAND_ENGINE_VERSION } from './strand-membership-writer.js';
39
68
  // Engine-canonical datetime helper (shared by control + strand signed-write flows
40
69
  // so a signed timestamp byte-matches the datetime-coerced column the CHECK sees).
41
70
  export { canonicalDatetime } from './canonical-datetime.js';
@@ -45,7 +74,7 @@ export { StrandMemberRegistry, StrandMemberVerifier, memberRegistrationPayload }
45
74
  // Seed Bootstrap
46
75
  export { SeedBootstrapService, SEED_PROTOCOL, ed25519PublicKeyB64FromPeerId } from './seed-bootstrap.js';
47
76
  // Peer Authorization (shared owner-signature digest + offline verifier)
48
- export { peerAuthorizationDigest, cadrePeerVoucherDigest, cadrePeerRemoveDigest, verifyPeerAuthorization } from './peer-authorization.js';
77
+ export { peerAuthorizationDigest, cadrePeerVoucherDigest, cadrePeerRemoveDigest, deviceTokenAddDigest, deviceTokenRemoveDigest, formationConsentDigest, verifyPeerAuthorization, verifyCadrePeerVoucher, verifyFormationConsent } from './peer-authorization.js';
49
78
  // Strand Wake (control-network push-wake protocol)
50
79
  export { StrandWakeService, dialWake, WAKE_PROTOCOL } from './strand-wake-protocol.js';
51
80
  // Strand Address (control-network strand-address RPC) — wire types come via
@@ -67,15 +96,20 @@ export { validatePushCredentials, redactPushCredentials, REDACTED } from './push
67
96
  export { PushFanoutService, DEFAULT_PUSH_COOLDOWN_MS, DEFAULT_PUSH_DEBOUNCE_MS } from './push-fanout.js';
68
97
  // Control-cohort dial selection (backbone-preferential, bounded out-degree) +
69
98
  // the cadence/degree defaults the proactive reconcile routine reads.
70
- export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE } from './control-cohort.js';
99
+ export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE } from './control-cohort.js';
71
100
  // Seed trust policy (trust anchor for incoming seeds)
72
- export { dbAnchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy } from './seed-trust-policy.js';
101
+ export { anchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy } from './seed-trust-policy.js';
73
102
  // Schema Verification
74
103
  export { signSchema, verifySchema, assertSchemaSignature, SchemaVerificationError } from './schema-verification.js';
75
104
  // Strand Formation transport (native cadre-core protocol)
76
105
  export { FormationListener, dialFormation, isValidResponderCreatesResult, FORMATION_PROTOCOL } from './strand-formation-protocol.js';
77
106
  // Strand Formation manager (drives the native transport)
78
107
  export { StrandFormationManager, createStrandFormationManager } from './strand-formation-manager.js';
108
+ // Control-network inbound connection gate (membership defense-in-depth)
109
+ export { createMembershipConnectionGater, STRANGER_OPEN_PROTOCOLS, DEFAULT_ENROLLMENT_WINDOW_MS, ADMISSION_DECISION_TIMEOUT_MS } from './membership-connection-gater.js';
110
+ // Relay reservation via the bare `/p2p-circuit` search listener (fail-soft;
111
+ // the fail-fast alternative is `network.relayAddrs`, see relay-reservation.ts)
112
+ export { circuitMultiaddrs, superviseRelayReservation, DEFAULT_RELAY_RESERVE_TIMEOUT_MS, DEFAULT_RELAY_RESERVE_POLL_MS, DEFAULT_RELAY_CHECK_MS, DEFAULT_RELAY_MIN_BACKOFF_MS, DEFAULT_RELAY_MAX_BACKOFF_MS } from './relay-reservation.js';
79
113
  // Connection-path diagnostics (relayed vs direct classification + summary)
80
114
  export { classifyTransport, classifyConnectionPath, summarizeConnectionPaths, emptyConnectionPathSummary, DEFAULT_SETTLE_WINDOW_MS } from './diagnostics/connection-path.js';
81
115
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,cAAc,YAAY,CAAC;AAE3B,+DAA+D;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,uBAAuB;AACvB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,mBAAmB;AACnB,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAiD,MAAM,uBAAuB,CAAC;AAElI,2DAA2D;AAC3D,OAAO,EAAE,wBAAwB,EAAE,2BAA2B,EAAuB,MAAM,kBAAkB,CAAC;AAE9G,2EAA2E;AAC3E,gFAAgF;AAChF,8EAA8E;AAC9E,+EAA+E;AAC/E,2BAA2B;AAC3B,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,uBAAuB,EAGxB,MAAM,gBAAgB,CAAC;AAExB,kBAAkB;AAClB,OAAO,EAAE,cAAc,EAA6B,MAAM,sBAAsB,CAAC;AAEjF,oBAAoB;AACpB,OAAO,EACL,aAAa,EAKd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qBAAqB,EAGrB,oBAAoB,EACrB,MAAM,8BAA8B,CAAC;AAEtC,cAAc;AACd,OAAO,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AE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjG,oFAAoF;AACpF,gFAAgF;AAChF,wEAAwE;AACxE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,wBAAwB,EAGzB,MAAM,kBAAkB,CAAC;AAE1B,8EAA8E;AAC9E,qEAAqE;AACrE,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACtC,mCAAmC,EACnC,oCAAoC,EAErC,MAAM,qBAAqB,CAAC;AAE7B,sDAAsD;AACtD,OAAO,EACL,mBAAmB,EACnB,oBAAoB,EACpB,eAAe,EAIhB,MAAM,wBAAwB,CAAC;AAEhC,sBAAsB;AACtB,OAAO,EACL,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,uBAAuB,EACxB,MAAM,0BAA0B,CAAC;AAElC,0DAA0D;AAC1D,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,6BAA6B,EAC7B,kBAAkB,EAUnB,MAAM,gCAAgC,CAAC;AAExC,yDAAyD;AACzD,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAG7B,MAAM,+BAA+B,CAAC;AAEvC,wEAAwE;AACxE,OAAO,EACL,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,6BAA6B,EAE9B,MAAM,kCAAkC,CAAC;AAE1C,4EAA4E;AAC5E,+EAA+E;AAC/E,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,gCAAgC,EAChC,6BAA6B,EAC7B,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAM7B,MAAM,wBAAwB,CAAC;AAEhC,2EAA2E;AAC3E,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,0BAA0B,EAC1B,wBAAwB,EAMzB,MAAM,kCAAkC,CAAC"}
@@ -21,32 +21,10 @@ export declare class FileKeyStore implements KeyStore {
21
21
  * Crash-atomic write: a concurrent reader sees either the complete previous
22
22
  * bytes or the complete new bytes, never a torn slot. The new material is
23
23
  * written to a sibling temp file, fsync'd, then atomically renamed over the
24
- * slot. A failure at any point removes the temp file and leaves the previous
25
- * slot untouched.
24
+ * slot (see {@link writeFileAtomically}). A failure at any point removes the
25
+ * temp file and leaves the previous slot untouched.
26
26
  */
27
27
  set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
28
- /**
29
- * Write material to `tmpPath`, durably land it, then atomically swap it onto
30
- * `finalPath`.
31
- *
32
- * Durability bar: the temp file is fsync'd before the rename so a power loss
33
- * cannot surface a slot whose bytes never reached the platter, and the slot
34
- * directory is fsync'd afterwards (best-effort — see {@link syncDir}) so the
35
- * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
36
- * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
37
- * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
38
- * holds the destination open. That cross-process case is out of scope here
39
- * (the in-process identity path is single-flight); such a failure surfaces
40
- * to the caller with the previous slot left intact.
41
- */
42
- private writeSlotAtomically;
43
- /**
44
- * Best-effort fsync of the slot directory so a fresh slot's directory entry is
45
- * durable across power loss. Opening a directory for fsync is not portable
46
- * (unsupported on Windows and some filesystems), and rename atomicity does not
47
- * depend on it — so a failure here is logged and swallowed, never surfaced.
48
- */
49
- private syncDir;
50
28
  delete(keyId: KeyId): Promise<void>;
51
29
  list(): Promise<KeyId[]>;
52
30
  }
@@ -14,10 +14,11 @@
14
14
  * `node:fs` edge never reaches a bundler that cannot satisfy it.
15
15
  */
16
16
  import debug from 'debug';
17
- import { mkdir, readFile, rm, readdir, rename, open } from 'node:fs/promises';
17
+ import { readFile, rm, readdir } from 'node:fs/promises';
18
18
  import { join } from 'node:path';
19
19
  import { randomBytes } from 'node:crypto';
20
20
  import { KeyStoreAccessError } from './key-store.js';
21
+ import { encodeFileSafeComponent, isNotFound, writeFileAtomically } from './fs-atomic.js';
21
22
  const log = debug('sereus:cadre:key-store-file');
22
23
  /** Suffix appended to the encoded keyId to form a slot filename. */
23
24
  const SLOT_SUFFIX = '.key';
@@ -27,20 +28,14 @@ const SLOT_SUFFIX = '.key';
27
28
  * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
28
29
  */
29
30
  const TEMP_SUFFIX = '.tmp';
30
- /** Best-effort POSIX permissions (ignored on Windows / unsupported FSes). */
31
- const DIR_MODE = 0o700;
32
- const FILE_MODE = 0o600;
33
31
  /**
34
- * Percent-encode a keyId into a filesystem-safe filename component. Beyond
35
- * `encodeURIComponent` (which already escapes `/`, spaces, and unicode), this
36
- * also escapes the unreserved characters `encodeURIComponent` leaves intact but
37
- * that are unsafe in filenames on some platforms (notably `*` on Windows) — and
38
- * `.` so the `.key` suffix is the only literal dot, making suffix-stripping in
39
- * {@link decodeKeyId} unambiguous. {@link decodeKeyId} reverses every escape via
40
- * `decodeURIComponent`. The result contains only `A-Za-z0-9-_` and `%XX`.
32
+ * Percent-encode a keyId into a filesystem-safe filename component (see
33
+ * {@link encodeFileSafeComponent} — `.` is escaped so the `.key` suffix is the
34
+ * only literal dot, making suffix-stripping in {@link decodeKeyId} unambiguous;
35
+ * {@link decodeKeyId} reverses every escape via `decodeURIComponent`).
41
36
  */
42
37
  function encodeKeyId(keyId) {
43
- return encodeURIComponent(keyId).replace(/[!'()*~.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
38
+ return encodeFileSafeComponent(keyId);
44
39
  }
45
40
  /**
46
41
  * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
@@ -59,11 +54,6 @@ function decodeKeyId(fileName) {
59
54
  return undefined;
60
55
  }
61
56
  }
62
- /** Whether an unknown error is a Node "file/dir not found" (ENOENT). */
63
- function isNotFound(error) {
64
- return typeof error === 'object' && error !== null
65
- && error.code === 'ENOENT';
66
- }
67
57
  /**
68
58
  * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
69
59
  * containing the raw material bytes. The directory is created lazily on first
@@ -107,68 +97,11 @@ export class FileKeyStore {
107
97
  * Crash-atomic write: a concurrent reader sees either the complete previous
108
98
  * bytes or the complete new bytes, never a torn slot. The new material is
109
99
  * written to a sibling temp file, fsync'd, then atomically renamed over the
110
- * slot. A failure at any point removes the temp file and leaves the previous
111
- * slot untouched.
100
+ * slot (see {@link writeFileAtomically}). A failure at any point removes the
101
+ * temp file and leaves the previous slot untouched.
112
102
  */
113
103
  async set(keyId, keyMaterial) {
114
- await mkdir(this.dir, { recursive: true, mode: DIR_MODE });
115
- await this.writeSlotAtomically(this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
116
- }
117
- /**
118
- * Write material to `tmpPath`, durably land it, then atomically swap it onto
119
- * `finalPath`.
120
- *
121
- * Durability bar: the temp file is fsync'd before the rename so a power loss
122
- * cannot surface a slot whose bytes never reached the platter, and the slot
123
- * directory is fsync'd afterwards (best-effort — see {@link syncDir}) so the
124
- * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
125
- * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
126
- * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
127
- * holds the destination open. That cross-process case is out of scope here
128
- * (the in-process identity path is single-flight); such a failure surfaces
129
- * to the caller with the previous slot left intact.
130
- */
131
- async writeSlotAtomically(tmpPath, finalPath, keyMaterial) {
132
- // 'wx' creates the temp file exclusively; a name collision (astronomically
133
- // unlikely given the random component) fails here before we own anything.
134
- const handle = await open(tmpPath, 'wx', FILE_MODE);
135
- try {
136
- try {
137
- await handle.writeFile(keyMaterial);
138
- await handle.sync(); // land bytes on disk before the rename exposes them
139
- }
140
- finally {
141
- await handle.close().catch(() => { });
142
- }
143
- await rename(tmpPath, finalPath);
144
- }
145
- catch (error) {
146
- // Any failure after creation (write, sync, or rename): drop the temp
147
- // file so a retry leaves no `.tmp` debris. The slot is only ever
148
- // swapped by the atomic rename, so the previous bytes stay intact.
149
- await rm(tmpPath, { force: true }).catch(() => { });
150
- throw error;
151
- }
152
- await this.syncDir();
153
- }
154
- /**
155
- * Best-effort fsync of the slot directory so a fresh slot's directory entry is
156
- * durable across power loss. Opening a directory for fsync is not portable
157
- * (unsupported on Windows and some filesystems), and rename atomicity does not
158
- * depend on it — so a failure here is logged and swallowed, never surfaced.
159
- */
160
- async syncDir() {
161
- let dirHandle;
162
- try {
163
- dirHandle = await open(this.dir, 'r');
164
- await dirHandle.sync();
165
- }
166
- catch (error) {
167
- log('FileKeyStore: directory fsync skipped for %s: %o', this.dir, error);
168
- }
169
- finally {
170
- await dirHandle?.close().catch(() => { });
171
- }
104
+ await writeFileAtomically(this.dir, this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
172
105
  }
173
106
  async delete(keyId) {
174
107
  // force:true makes removing an absent slot a no-op (idempotent).
@@ -1 +1 @@
1
- {"version":3,"file":"key-store-file.js","sourceRoot":"","sources":["../src/key-store-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE9E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAErD,MAAM,GAAG,GAAG,KAAK,CAAC,6BAA6B,CAAC,CAAC;AAEjD,oEAAoE;AACpE,MAAM,WAAW,GAAG,MAAM,CAAC;AAE3B;;;;GAIG;AACH,MAAM,WAAW,GAAG,MAAM,CAAC;AAE3B,6EAA6E;AAC7E,MAAM,QAAQ,GAAG,KAAK,CAAC;AACvB,MAAM,SAAS,GAAG,KAAK,CAAC;AAExB;;;;;;;;GAQG;AACH,SAAS,WAAW,CAAC,KAAY;IAChC,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC,OAAO,CACvC,YAAY,EACZ,CAAC,CAAC,EAAE,EAAE,CA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