@serfab/cadre-core 0.7.1 → 0.9.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 (170) hide show
  1. package/README.md +11 -10
  2. package/dist/cadre-node.d.ts +818 -19
  3. package/dist/cadre-node.js +1952 -99
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/canonical-datetime.d.ts +33 -0
  6. package/dist/canonical-datetime.js +38 -0
  7. package/dist/canonical-datetime.js.map +1 -0
  8. package/dist/canonical-json.d.ts +12 -0
  9. package/dist/canonical-json.js +33 -0
  10. package/dist/canonical-json.js.map +1 -0
  11. package/dist/control-cohort.d.ts +63 -0
  12. package/dist/control-cohort.js +80 -0
  13. package/dist/control-cohort.js.map +1 -0
  14. package/dist/control-database.d.ts +279 -8
  15. package/dist/control-database.js +563 -134
  16. package/dist/control-database.js.map +1 -1
  17. package/dist/control-formation-recorder.d.ts +89 -0
  18. package/dist/control-formation-recorder.js +139 -0
  19. package/dist/control-formation-recorder.js.map +1 -0
  20. package/dist/control-schema.d.ts +12 -0
  21. package/dist/control-schema.js +223 -0
  22. package/dist/control-schema.js.map +1 -0
  23. package/dist/control-stream.d.ts +54 -0
  24. package/dist/control-stream.js +104 -0
  25. package/dist/control-stream.js.map +1 -0
  26. package/dist/device-token.d.ts +50 -0
  27. package/dist/device-token.js +66 -0
  28. package/dist/device-token.js.map +1 -0
  29. package/dist/diagnostics/connection-path.d.ts +118 -0
  30. package/dist/diagnostics/connection-path.js +204 -0
  31. package/dist/diagnostics/connection-path.js.map +1 -0
  32. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  33. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  34. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  35. package/dist/ed25519-key.d.ts +42 -0
  36. package/dist/ed25519-key.js +51 -0
  37. package/dist/ed25519-key.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +48 -0
  51. package/dist/peer-authorization.js +66 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-node.d.ts +38 -0
  63. package/dist/push-node.js +48 -0
  64. package/dist/push-node.js.map +1 -0
  65. package/dist/push-notifier-apns.d.ts +61 -0
  66. package/dist/push-notifier-apns.js +199 -0
  67. package/dist/push-notifier-apns.js.map +1 -0
  68. package/dist/push-notifier-fcm.d.ts +44 -0
  69. package/dist/push-notifier-fcm.js +182 -0
  70. package/dist/push-notifier-fcm.js.map +1 -0
  71. package/dist/push-notifier-shared.d.ts +18 -0
  72. package/dist/push-notifier-shared.js +25 -0
  73. package/dist/push-notifier-shared.js.map +1 -0
  74. package/dist/push-notifier.d.ts +52 -0
  75. package/dist/push-notifier.js +22 -0
  76. package/dist/push-notifier.js.map +1 -0
  77. package/dist/schema-verification.d.ts +11 -2
  78. package/dist/schema-verification.js +15 -4
  79. package/dist/schema-verification.js.map +1 -1
  80. package/dist/seed-bootstrap.d.ts +228 -21
  81. package/dist/seed-bootstrap.js +489 -168
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +63 -0
  84. package/dist/seed-trust-policy.js +56 -0
  85. package/dist/seed-trust-policy.js.map +1 -0
  86. package/dist/strand-addr-protocol.d.ts +132 -0
  87. package/dist/strand-addr-protocol.js +313 -0
  88. package/dist/strand-addr-protocol.js.map +1 -0
  89. package/dist/strand-cohort.d.ts +54 -0
  90. package/dist/strand-cohort.js +38 -0
  91. package/dist/strand-cohort.js.map +1 -0
  92. package/dist/strand-database.d.ts +54 -6
  93. package/dist/strand-database.js +88 -100
  94. package/dist/strand-database.js.map +1 -1
  95. package/dist/strand-formation-manager.d.ts +79 -19
  96. package/dist/strand-formation-manager.js +196 -104
  97. package/dist/strand-formation-manager.js.map +1 -1
  98. package/dist/strand-formation-protocol.d.ts +162 -0
  99. package/dist/strand-formation-protocol.js +279 -0
  100. package/dist/strand-formation-protocol.js.map +1 -0
  101. package/dist/strand-instance-manager.d.ts +73 -4
  102. package/dist/strand-instance-manager.js +167 -41
  103. package/dist/strand-instance-manager.js.map +1 -1
  104. package/dist/strand-member-key.d.ts +29 -0
  105. package/dist/strand-member-key.js +38 -0
  106. package/dist/strand-member-key.js.map +1 -0
  107. package/dist/strand-member-registry.d.ts +98 -0
  108. package/dist/strand-member-registry.js +129 -0
  109. package/dist/strand-member-registry.js.map +1 -0
  110. package/dist/strand-membership-writer.d.ts +361 -0
  111. package/dist/strand-membership-writer.js +449 -0
  112. package/dist/strand-membership-writer.js.map +1 -0
  113. package/dist/strand-solicitation.d.ts +77 -2
  114. package/dist/strand-solicitation.js +25 -4
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-wake-payload.d.ts +30 -0
  117. package/dist/strand-wake-payload.js +20 -0
  118. package/dist/strand-wake-payload.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +114 -0
  120. package/dist/strand-wake-protocol.js +257 -0
  121. package/dist/strand-wake-protocol.js.map +1 -0
  122. package/dist/strand-watcher.d.ts +6 -2
  123. package/dist/strand-watcher.js +57 -17
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/types.d.ts +436 -33
  126. package/dist/types.js +22 -5
  127. package/dist/types.js.map +1 -1
  128. package/package.json +18 -8
  129. package/src/cadre-node.ts +2981 -948
  130. package/src/canonical-datetime.ts +39 -0
  131. package/src/canonical-json.ts +30 -0
  132. package/src/control-cohort.ts +103 -0
  133. package/src/control-database.ts +948 -383
  134. package/src/control-formation-recorder.ts +151 -0
  135. package/src/control-schema.ts +222 -0
  136. package/src/control-stream.ts +128 -0
  137. package/src/device-token.ts +89 -0
  138. package/src/diagnostics/connection-path.ts +277 -0
  139. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  140. package/src/ed25519-key.ts +69 -0
  141. package/src/hibernation-manager.ts +197 -28
  142. package/src/index.ts +275 -79
  143. package/src/key-store-file.ts +203 -0
  144. package/src/key-store.ts +99 -0
  145. package/src/peer-authorization.ts +81 -0
  146. package/src/peer-record.ts +146 -0
  147. package/src/push-credentials.ts +84 -0
  148. package/src/push-fanout.ts +272 -0
  149. package/src/push-node.ts +64 -0
  150. package/src/push-notifier-apns.ts +247 -0
  151. package/src/push-notifier-fcm.ts +220 -0
  152. package/src/push-notifier-shared.ts +28 -0
  153. package/src/push-notifier.ts +52 -0
  154. package/src/schema-verification.ts +18 -4
  155. package/src/seed-bootstrap.ts +563 -223
  156. package/src/seed-trust-policy.ts +107 -0
  157. package/src/strand-addr-protocol.ts +410 -0
  158. package/src/strand-cohort.ts +77 -0
  159. package/src/strand-database.ts +113 -141
  160. package/src/strand-formation-manager.ts +233 -142
  161. package/src/strand-formation-protocol.ts +391 -0
  162. package/src/strand-instance-manager.ts +207 -56
  163. package/src/strand-member-key.ts +39 -0
  164. package/src/strand-member-registry.ts +177 -0
  165. package/src/strand-membership-writer.ts +640 -0
  166. package/src/strand-solicitation.ts +93 -4
  167. package/src/strand-wake-payload.ts +32 -0
  168. package/src/strand-wake-protocol.ts +331 -0
  169. package/src/strand-watcher.ts +61 -17
  170. package/src/types.ts +1032 -582
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Node-only file-backed {@link KeyStore}: one file per slot under a configured
3
+ * directory, holding the raw key material bytes.
4
+ *
5
+ * This module imports `node:fs/promises`, `node:path`, and `node:crypto`, so it
6
+ * is deliberately kept OUT of the package's cross-platform default entry
7
+ * (`./index.js`). Import it from the dedicated subpath instead:
8
+ *
9
+ * ```ts
10
+ * import { FileKeyStore } from '@serfab/cadre-core/key-store-file';
11
+ * ```
12
+ *
13
+ * A React Native / browser entry graph never resolves this path, so the
14
+ * `node:fs` edge never reaches a bundler that cannot satisfy it.
15
+ */
16
+ import debug from 'debug';
17
+ import { mkdir, readFile, rm, readdir, rename, open } from 'node:fs/promises';
18
+ import type { FileHandle } from 'node:fs/promises';
19
+ import { join } from 'node:path';
20
+ import { randomBytes } from 'node:crypto';
21
+ import type { KeyId, KeyStore } from './key-store.js';
22
+ import { KeyStoreAccessError } from './key-store.js';
23
+
24
+ const log = debug('sereus:cadre:key-store-file');
25
+
26
+ /** Suffix appended to the encoded keyId to form a slot filename. */
27
+ const SLOT_SUFFIX = '.key';
28
+
29
+ /**
30
+ * Suffix for the transient file written then atomically renamed over the slot.
31
+ * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
32
+ * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
33
+ */
34
+ const TEMP_SUFFIX = '.tmp';
35
+
36
+ /** Best-effort POSIX permissions (ignored on Windows / unsupported FSes). */
37
+ const DIR_MODE = 0o700;
38
+ const FILE_MODE = 0o600;
39
+
40
+ /**
41
+ * Percent-encode a keyId into a filesystem-safe filename component. Beyond
42
+ * `encodeURIComponent` (which already escapes `/`, spaces, and unicode), this
43
+ * also escapes the unreserved characters `encodeURIComponent` leaves intact but
44
+ * that are unsafe in filenames on some platforms (notably `*` on Windows) — and
45
+ * `.` so the `.key` suffix is the only literal dot, making suffix-stripping in
46
+ * {@link decodeKeyId} unambiguous. {@link decodeKeyId} reverses every escape via
47
+ * `decodeURIComponent`. The result contains only `A-Za-z0-9-_` and `%XX`.
48
+ */
49
+ function encodeKeyId(keyId: KeyId): string {
50
+ return encodeURIComponent(keyId).replace(
51
+ /[!'()*~.]/g,
52
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
53
+ );
54
+ }
55
+
56
+ /**
57
+ * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
58
+ * `undefined` for a `.key` filename this store did not write (a foreign file
59
+ * with an invalid percent-sequence), so {@link FileKeyStore.list} can skip it
60
+ * rather than letting one undecodable entry throw and break enumeration of every
61
+ * real slot.
62
+ */
63
+ function decodeKeyId(fileName: string): KeyId | undefined {
64
+ const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
65
+ try {
66
+ return decodeURIComponent(encoded);
67
+ } catch (error) {
68
+ log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ /** Whether an unknown error is a Node "file/dir not found" (ENOENT). */
74
+ function isNotFound(error: unknown): boolean {
75
+ return typeof error === 'object' && error !== null
76
+ && (error as { code?: unknown }).code === 'ENOENT';
77
+ }
78
+
79
+ /**
80
+ * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
81
+ * containing the raw material bytes. The directory is created lazily on first
82
+ * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
83
+ * a platform secure-enclave backend instead.
84
+ */
85
+ export class FileKeyStore implements KeyStore {
86
+ constructor(private readonly dir: string) {}
87
+
88
+ private slotPath(keyId: KeyId): string {
89
+ return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
90
+ }
91
+
92
+ /**
93
+ * Sibling path for the temp file written before the atomic rename. The random
94
+ * component makes concurrent {@link set}s to the same slot (and crash-orphaned
95
+ * leftovers) collide-free; it lives in the same directory as the slot so the
96
+ * final {@link rename} stays within one filesystem and is therefore atomic.
97
+ */
98
+ private tempPath(keyId: KeyId): string {
99
+ const unique = randomBytes(6).toString('hex');
100
+ return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
101
+ }
102
+
103
+ async get(keyId: KeyId): Promise<Uint8Array | undefined> {
104
+ try {
105
+ const buf = await readFile(this.slotPath(keyId));
106
+ // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
107
+ return new Uint8Array(buf);
108
+ } catch (error) {
109
+ // A missing slot is "empty" (undefined), NOT an error — so a
110
+ // load-or-create caller generates a key rather than mistaking a
111
+ // permission failure for absence. Any other failure (e.g. EACCES) is
112
+ // surfaced as access-denied so callers do not clobber an existing key.
113
+ if (isNotFound(error)) return undefined;
114
+ throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Crash-atomic write: a concurrent reader sees either the complete previous
120
+ * bytes or the complete new bytes, never a torn slot. The new material is
121
+ * written to a sibling temp file, fsync'd, then atomically renamed over the
122
+ * slot. A failure at any point removes the temp file and leaves the previous
123
+ * slot untouched.
124
+ */
125
+ async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
126
+ await mkdir(this.dir, { recursive: true, mode: DIR_MODE });
127
+ await this.writeSlotAtomically(this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
128
+ }
129
+
130
+ /**
131
+ * Write material to `tmpPath`, durably land it, then atomically swap it onto
132
+ * `finalPath`.
133
+ *
134
+ * Durability bar: the temp file is fsync'd before the rename so a power loss
135
+ * cannot surface a slot whose bytes never reached the platter, and the slot
136
+ * directory is fsync'd afterwards (best-effort — see {@link syncDir}) so the
137
+ * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
138
+ * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
139
+ * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
140
+ * holds the destination open. That cross-process case is out of scope here
141
+ * (the in-process identity path is single-flight); such a failure surfaces
142
+ * to the caller with the previous slot left intact.
143
+ */
144
+ private async writeSlotAtomically(tmpPath: string, finalPath: string, keyMaterial: Uint8Array): Promise<void> {
145
+ // 'wx' creates the temp file exclusively; a name collision (astronomically
146
+ // unlikely given the random component) fails here before we own anything.
147
+ const handle = await open(tmpPath, 'wx', FILE_MODE);
148
+ try {
149
+ try {
150
+ await handle.writeFile(keyMaterial);
151
+ await handle.sync(); // land bytes on disk before the rename exposes them
152
+ } finally {
153
+ await handle.close().catch(() => {});
154
+ }
155
+ await rename(tmpPath, finalPath);
156
+ } catch (error) {
157
+ // Any failure after creation (write, sync, or rename): drop the temp
158
+ // file so a retry leaves no `.tmp` debris. The slot is only ever
159
+ // swapped by the atomic rename, so the previous bytes stay intact.
160
+ await rm(tmpPath, { force: true }).catch(() => {});
161
+ throw error;
162
+ }
163
+ await this.syncDir();
164
+ }
165
+
166
+ /**
167
+ * Best-effort fsync of the slot directory so a fresh slot's directory entry is
168
+ * durable across power loss. Opening a directory for fsync is not portable
169
+ * (unsupported on Windows and some filesystems), and rename atomicity does not
170
+ * depend on it — so a failure here is logged and swallowed, never surfaced.
171
+ */
172
+ private async syncDir(): Promise<void> {
173
+ let dirHandle: FileHandle | undefined;
174
+ try {
175
+ dirHandle = await open(this.dir, 'r');
176
+ await dirHandle.sync();
177
+ } catch (error) {
178
+ log('FileKeyStore: directory fsync skipped for %s: %o', this.dir, error);
179
+ } finally {
180
+ await dirHandle?.close().catch(() => {});
181
+ }
182
+ }
183
+
184
+ async delete(keyId: KeyId): Promise<void> {
185
+ // force:true makes removing an absent slot a no-op (idempotent).
186
+ await rm(this.slotPath(keyId), { force: true });
187
+ }
188
+
189
+ async list(): Promise<KeyId[]> {
190
+ let entries: string[];
191
+ try {
192
+ entries = await readdir(this.dir);
193
+ } catch (error) {
194
+ // An absent directory means no slots yet — not a failure.
195
+ if (isNotFound(error)) return [];
196
+ throw new Error('FileKeyStore: failed to list key directory', { cause: error });
197
+ }
198
+ return entries
199
+ .filter((name) => name.endsWith(SLOT_SUFFIX))
200
+ .map(decodeKeyId)
201
+ .filter((id): id is KeyId => id !== undefined);
202
+ }
203
+ }
@@ -0,0 +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
+ }
@@ -0,0 +1,81 @@
1
+ import debug from 'debug';
2
+ import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
+
4
+ const log = debug('sereus:cadre:peer-authorization');
5
+
6
+ /**
7
+ * Canonical digest an owner signs to authorize a peer.
8
+ *
9
+ * This is the exact byte construction {@link SeedBootstrapService.authorizePeer}
10
+ * signs over when it inserts an authorized `CadrePeer` row:
11
+ * `digest([peerId], 'sha256', 'base64url')`. Factored into one place so the
12
+ * producer (owner signing) and the verifier (the offline `cadre enroll
13
+ * register` check) can never drift apart — change the digest here and both move
14
+ * together. The SQL mirror is the bare single-field `digest(coalesce(new.PeerId, old.PeerId))`.
15
+ */
16
+ export function peerAuthorizationDigest(peerId: string): string {
17
+ return digest([peerId], 'sha256', 'base64url') as string;
18
+ }
19
+
20
+ /**
21
+ * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
22
+ * and the owner re-touch update). Binds the peer id to the row's single-use
23
+ * `StampId` nonce, so a captured signed insert cannot be replayed (the `StampId` is
24
+ * unique) and — because {@link cadrePeerRemoveDigest} scopes a DIFFERENT payload — the
25
+ * stored voucher (`VouchSig`) cannot be replayed to authorize a delete.
26
+ *
27
+ * The SQL mirror is `digest(new.PeerId, new.StampId)` (two TEXT fields), matching the
28
+ * canonical multi-field framing in control-database.ts:buildAuthorizationMessage.
29
+ */
30
+ export function cadrePeerVoucherDigest(peerId: string, stampId: string): string {
31
+ return digest([peerId, stampId], 'sha256', 'base64url') as string;
32
+ }
33
+
34
+ /**
35
+ * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
36
+ * distinct payload from {@link cadrePeerVoucherDigest} (adds the `'remove'` action
37
+ * tag) so the row's stored voucher — a signature over the voucher digest — can never
38
+ * satisfy this delete check. The signature is supplied in write context and never
39
+ * stored, so no reader can replay it; binding the live row's `StampId` also invalidates
40
+ * any captured remove after a delete+reinsert (the nonce rotates).
41
+ *
42
+ * SQL mirror: `digest(old.PeerId, old.StampId, 'remove')`.
43
+ */
44
+ export function cadrePeerRemoveDigest(peerId: string, stampId: string): string {
45
+ return digest([peerId, stampId, 'remove'], 'sha256', 'base64url') as string;
46
+ }
47
+
48
+ /**
49
+ * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
50
+ * authorization digest, using `ownerPublicKey` (base64url).
51
+ *
52
+ * This is the mirror of the signing done in
53
+ * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
54
+ * {@link peerAuthorizationDigest}. A `true` result means the holder of the
55
+ * owner private key vouched for this peer ID — it does NOT mean the peer is
56
+ * registered anywhere.
57
+ *
58
+ * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
59
+ * any crypto failure resolves to `false` (callers want a verdict, not an
60
+ * exception). The catch is logged at debug.
61
+ */
62
+ export function verifyPeerAuthorization(
63
+ peerId: string,
64
+ ownerPublicKey: string,
65
+ signature: string
66
+ ): boolean {
67
+ try {
68
+ return verify(
69
+ peerAuthorizationDigest(peerId),
70
+ signature,
71
+ ownerPublicKey,
72
+ 'ed25519',
73
+ 'base64url',
74
+ 'base64url',
75
+ 'base64url'
76
+ );
77
+ } catch (error) {
78
+ log('verifyPeerAuthorization failed: %o', error);
79
+ return false;
80
+ }
81
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Peer-address record helpers: the single source of truth for the bytes a node
3
+ * signs when publishing its own `CadrePeer` row and re-verifies when resolving
4
+ * another peer's row.
5
+ *
6
+ * The signed payload is a single SHA-256 digest of a delimited string of the
7
+ * authenticated fields. It is intentionally NOT JSON-canonicalized: a delimited
8
+ * digest is trivially deterministic across node/browser/RN (plain string concat
9
+ * + sha256, no key ordering) and — crucially — is reconstructable inside the
10
+ * `CadrePeer.AuthorizedUpdate` SQL constraint from the row's own columns:
11
+ *
12
+ * digest(new.PeerId || '|' || new.Multiaddr || '|' || cast(new.UpdatedAt as text))
13
+ *
14
+ * Keep {@link peerRecordSignedPayload} and that constraint byte-for-byte in
15
+ * sync. The `'|'` delimiter is safe: a base58btc PeerId, a multiaddr (which uses
16
+ * `/`), and a base-10 integer never contain it.
17
+ *
18
+ * `publicKey` is deliberately excluded from the payload — it is the key the
19
+ * signature is verified *with* (so a signature already commits to exactly one
20
+ * key), and its binding to `peerId` is checked separately at resolve time.
21
+ */
22
+
23
+ import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
24
+ import type { PeerAddressRecord, PeerResolveTrustPolicy } from './types.js';
25
+
26
+ /**
27
+ * Default freshness ceiling for resolved peer-address records (15 minutes).
28
+ * A record older than this is treated as stale and filtered out, so a resolver
29
+ * never hands back a dead relay reservation. The publish path re-stamps at
30
+ * roughly half this interval (see {@link DEFAULT_PEER_RECORD_HEARTBEAT_MS}).
31
+ */
32
+ export const DEFAULT_PEER_RECORD_MAX_AGE_MS = 15 * 60 * 1000;
33
+
34
+ /**
35
+ * TTL heartbeat interval for re-publishing the self record — half the freshness
36
+ * ceiling, so a record is refreshed well before it can go stale.
37
+ */
38
+ export const DEFAULT_PEER_RECORD_HEARTBEAT_MS = DEFAULT_PEER_RECORD_MAX_AGE_MS / 2;
39
+
40
+ /** The signaling/relay prefix a WebRTC (or any relayed) dial path consumes. */
41
+ const SIGNALING_PREFIX = '/p2p-circuit';
42
+
43
+ /**
44
+ * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
45
+ * `CadrePeer.AuthorizedUpdate` constraint exactly; both sides take the default
46
+ * base64url output of a single `digest(...)`, which round-trips cleanly (unlike
47
+ * concatenating several base64url digests).
48
+ *
49
+ * @param peerId - base58btc libp2p peer id (the row key)
50
+ * @param multiaddr - the comma-joined `Multiaddr` string EXACTLY as stored
51
+ * @param updatedAt - epoch-ms freshness stamp
52
+ */
53
+ export function peerRecordSignedPayload(peerId: string, multiaddr: string, updatedAt: number): string {
54
+ const joined = `${peerId}|${multiaddr}|${updatedAt}`;
55
+ return digest([joined], 'sha256', 'base64url') as string;
56
+ }
57
+
58
+ /**
59
+ * Sign a peer-address record with the ed25519 private key behind its `peerId`.
60
+ * Returns a fully-populated {@link PeerAddressRecord} (the `addrs` order is
61
+ * preserved and is the order signed over).
62
+ *
63
+ * @param fields - the record fields to sign (signaling addr first by convention)
64
+ * @param privateKeyB64 - base64url ed25519 seed (see `ed25519KeyPairFromLibp2p`)
65
+ */
66
+ export function signPeerRecord(
67
+ fields: { peerId: string; publicKey: string; addrs: string[]; updatedAt: number },
68
+ privateKeyB64: string
69
+ ): PeerAddressRecord {
70
+ const payloadDigest = peerRecordSignedPayload(fields.peerId, fields.addrs.join(','), fields.updatedAt);
71
+ const sig = sign(
72
+ payloadDigest,
73
+ privateKeyB64,
74
+ 'ed25519',
75
+ 'base64url',
76
+ 'base64url',
77
+ 'base64url'
78
+ ) as string;
79
+ return { peerId: fields.peerId, publicKey: fields.publicKey, addrs: [...fields.addrs], updatedAt: fields.updatedAt, sig };
80
+ }
81
+
82
+ /**
83
+ * Verify a record's self-signature against its own `publicKey`. Reconstructs the
84
+ * signed bytes from the record exactly as {@link signPeerRecord} produced them.
85
+ * Returns false on a missing key/sig or any verification failure.
86
+ */
87
+ export function verifyPeerRecordSignature(record: PeerAddressRecord): boolean {
88
+ if (!record.publicKey || !record.sig) {
89
+ return false;
90
+ }
91
+ const payloadDigest = peerRecordSignedPayload(record.peerId, record.addrs.join(','), record.updatedAt);
92
+ return verify(
93
+ payloadDigest,
94
+ record.sig,
95
+ record.publicKey,
96
+ 'ed25519',
97
+ 'base64url',
98
+ 'base64url',
99
+ 'base64url'
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Freshness predicate: true when `updatedAt` is a positive stamp within
105
+ * `maxAgeMs` of `now`. A non-positive `updatedAt` (never self-published) is
106
+ * never fresh.
107
+ */
108
+ export function isPeerRecordFresh(updatedAt: number, maxAgeMs: number, now: number): boolean {
109
+ if (!(updatedAt > 0)) {
110
+ return false;
111
+ }
112
+ return now - updatedAt <= maxAgeMs;
113
+ }
114
+
115
+ /** True if `addr` is a `/p2p-circuit` signaling/relay multiaddr. */
116
+ export function isSignalingAddr(addr: string): boolean {
117
+ return addr.includes(SIGNALING_PREFIX);
118
+ }
119
+
120
+ /**
121
+ * Return `addrs` with signaling (`/p2p-circuit`) addrs first, otherwise stable.
122
+ * Used to present the WebRTC dial input ahead of direct addrs. Does NOT mutate
123
+ * the input and must not be used before signature verification (verification
124
+ * uses the original on-record order).
125
+ */
126
+ export function orderSignalingFirst(addrs: string[]): string[] {
127
+ const signaling = addrs.filter(isSignalingAddr);
128
+ const rest = addrs.filter(a => !isSignalingAddr(a));
129
+ return [...signaling, ...rest];
130
+ }
131
+
132
+ /**
133
+ * Default resolve trust gate: trust any peer that has a `CadrePeer` row.
134
+ *
135
+ * A row only exists because an owner signed its `AuthorizedInsert`, so row
136
+ * presence already means "owner-vouched member". This is the seam where a
137
+ * stricter policy (trust circle, pinned keys) plugs in — see
138
+ * {@link PeerResolveTrustPolicy}.
139
+ */
140
+ export function currentMemberTrustPolicy(): PeerResolveTrustPolicy {
141
+ return {
142
+ evaluate() {
143
+ return true;
144
+ },
145
+ };
146
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * push-credentials.ts — pure validation + log-redaction for {@link PushCredentials}.
3
+ *
4
+ * The platform-push credentials a deployment provisions (`cadre-host` from its
5
+ * secret store, `cadre-provider` from per-tenant config) are written into a
6
+ * spawned node's config under `CadreNodeConfig.push`. This module is the
7
+ * dependency-free seam those provisioners share to (a) reject a *partial* set
8
+ * before it reaches a node — a present platform block must carry all its required
9
+ * fields, or it fails fast at provisioning rather than at first push — and (b)
10
+ * produce a log-safe view that never leaks a private key.
11
+ *
12
+ * It imports only the *types* (erased at emit), so it pulls no node:crypto /
13
+ * node:http2 edge — a provisioner can import these functions without dragging in
14
+ * the FCM/APNs senders.
15
+ */
16
+
17
+ import type { PushCredentials, FcmCredentials, ApnsCredentials } from './types.js';
18
+
19
+ /** Marker substituted for every secret field by {@link redactPushCredentials}. */
20
+ export const REDACTED = '[redacted]';
21
+
22
+ /**
23
+ * Validate a resolved push-credential bundle, returning human-readable errors
24
+ * (empty ⇒ valid). Each platform block is optional, but a *present* block must
25
+ * carry every required field — a partial set (e.g. APNs `keyId` without
26
+ * `privateKey`) is a misconfiguration that must surface at provisioning time, not
27
+ * silently at the first wake. A bundle with neither platform is valid (push is
28
+ * opt-in); callers that require at least one platform check that separately.
29
+ */
30
+ export function validatePushCredentials(push: PushCredentials): string[] {
31
+ const errors: string[] = [];
32
+ if (push.fcm) errors.push(...validateFcm(push.fcm));
33
+ if (push.apns) errors.push(...validateApns(push.apns));
34
+ return errors;
35
+ }
36
+
37
+ function validateFcm(fcm: FcmCredentials): string[] {
38
+ return missingFields('fcm', fcm as unknown as Record<string, unknown>, [
39
+ 'projectId',
40
+ 'clientEmail',
41
+ 'privateKey',
42
+ ]);
43
+ }
44
+
45
+ function validateApns(apns: ApnsCredentials): string[] {
46
+ return missingFields('apns', apns as unknown as Record<string, unknown>, [
47
+ 'keyId',
48
+ 'teamId',
49
+ 'bundleId',
50
+ 'privateKey',
51
+ ]);
52
+ }
53
+
54
+ /** Names the required fields of `platform` that are missing or blank. */
55
+ function missingFields(platform: string, obj: Record<string, unknown>, required: string[]): string[] {
56
+ return required
57
+ .filter((f) => typeof obj[f] !== 'string' || (obj[f] as string).trim().length === 0)
58
+ .map((f) => `push.${platform}.${f} is required when a ${platform} credential block is present`);
59
+ }
60
+
61
+ /**
62
+ * Return a log-safe shallow copy of a push bundle with every private key replaced
63
+ * by {@link REDACTED}. Use this for ANY debug/log line that touches push config —
64
+ * `privateKey` fields are secrets and must never reach a log sink (the same rule
65
+ * the startup/seed tokens follow).
66
+ */
67
+ export function redactPushCredentials(push: PushCredentials): Record<string, unknown> {
68
+ const out: Record<string, unknown> = {};
69
+ if (push.fcm) {
70
+ out.fcm = { projectId: push.fcm.projectId, clientEmail: push.fcm.clientEmail, privateKey: REDACTED };
71
+ }
72
+ if (push.apns) {
73
+ out.apns = {
74
+ keyId: push.apns.keyId,
75
+ teamId: push.apns.teamId,
76
+ bundleId: push.apns.bundleId,
77
+ ...(push.apns.production !== undefined ? { production: push.apns.production } : {}),
78
+ privateKey: REDACTED,
79
+ };
80
+ }
81
+ if (push.cooldownMs !== undefined) out.cooldownMs = push.cooldownMs;
82
+ if (push.debounceMs !== undefined) out.debounceMs = push.debounceMs;
83
+ return out;
84
+ }