@serfab/cadre-core 1.13.0 → 1.15.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 (230) hide show
  1. package/README.md +293 -274
  2. package/dist/cadre-invite-protocol.d.ts +383 -0
  3. package/dist/cadre-invite-protocol.js +774 -0
  4. package/dist/cadre-invite-protocol.js.map +1 -0
  5. package/dist/cadre-join-request.d.ts +42 -0
  6. package/dist/cadre-join-request.js +144 -0
  7. package/dist/cadre-join-request.js.map +1 -0
  8. package/dist/cadre-node.d.ts +849 -210
  9. package/dist/cadre-node.js +1574 -374
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/claim-proof.d.ts +45 -0
  12. package/dist/claim-proof.js +132 -0
  13. package/dist/claim-proof.js.map +1 -0
  14. package/dist/control-authorization.d.ts +80 -19
  15. package/dist/control-authorization.js +55 -13
  16. package/dist/control-authorization.js.map +1 -1
  17. package/dist/control-cohort.js +1 -1
  18. package/dist/control-cohort.js.map +1 -1
  19. package/dist/control-database.d.ts +605 -108
  20. package/dist/control-database.js +1299 -280
  21. package/dist/control-database.js.map +1 -1
  22. package/dist/control-protocol-guard.d.ts +142 -0
  23. package/dist/control-protocol-guard.js +293 -0
  24. package/dist/control-protocol-guard.js.map +1 -0
  25. package/dist/control-schema.d.ts +1 -1
  26. package/dist/control-schema.js +817 -1067
  27. package/dist/control-schema.js.map +1 -1
  28. package/dist/control-stream.d.ts +4 -0
  29. package/dist/control-stream.js +22 -7
  30. package/dist/control-stream.js.map +1 -1
  31. package/dist/delegate-admission.d.ts +1 -1
  32. package/dist/delegate-admission.js +1 -1
  33. package/dist/device-token.d.ts +11 -9
  34. package/dist/device-token.js +14 -12
  35. package/dist/device-token.js.map +1 -1
  36. package/dist/ed25519-key.d.ts +22 -9
  37. package/dist/ed25519-key.js +47 -10
  38. package/dist/ed25519-key.js.map +1 -1
  39. package/dist/fetch-impl.d.ts +12 -0
  40. package/dist/fetch-impl.js +23 -0
  41. package/dist/fetch-impl.js.map +1 -0
  42. package/dist/file-durable-slot.js +2 -1
  43. package/dist/file-durable-slot.js.map +1 -1
  44. package/dist/file-safe-name.d.ts +25 -0
  45. package/dist/file-safe-name.js +29 -0
  46. package/dist/file-safe-name.js.map +1 -0
  47. package/dist/formation-approval.js +5 -11
  48. package/dist/formation-approval.js.map +1 -1
  49. package/dist/fs-atomic.d.ts +0 -19
  50. package/dist/fs-atomic.js +3 -24
  51. package/dist/fs-atomic.js.map +1 -1
  52. package/dist/index.d.ts +22 -10
  53. package/dist/index.js +54 -11
  54. package/dist/index.js.map +1 -1
  55. package/dist/invitation-bootstrap.d.ts +50 -12
  56. package/dist/invitation-bootstrap.js +76 -13
  57. package/dist/invitation-bootstrap.js.map +1 -1
  58. package/dist/joined-strand-store.d.ts +7 -0
  59. package/dist/joined-strand-store.js +9 -0
  60. package/dist/joined-strand-store.js.map +1 -1
  61. package/dist/key-store-file.js +2 -1
  62. package/dist/key-store-file.js.map +1 -1
  63. package/dist/link-budget.d.ts +25 -33
  64. package/dist/link-budget.js +25 -35
  65. package/dist/link-budget.js.map +1 -1
  66. package/dist/machine-removal.d.ts +78 -0
  67. package/dist/machine-removal.js +166 -0
  68. package/dist/machine-removal.js.map +1 -0
  69. package/dist/membership-connection-gater.d.ts +191 -151
  70. package/dist/membership-connection-gater.js +236 -173
  71. package/dist/membership-connection-gater.js.map +1 -1
  72. package/dist/node-claim-payload.d.ts +74 -0
  73. package/dist/node-claim-payload.js +224 -0
  74. package/dist/node-claim-payload.js.map +1 -0
  75. package/dist/node-default-transports.d.ts +27 -0
  76. package/dist/node-default-transports.js +35 -0
  77. package/dist/node-default-transports.js.map +1 -0
  78. package/dist/node-transports.d.ts +30 -0
  79. package/dist/node-transports.js +40 -0
  80. package/dist/node-transports.js.map +1 -0
  81. package/dist/owner-anchor-sync.d.ts +22 -0
  82. package/dist/owner-anchor-sync.js +143 -0
  83. package/dist/owner-anchor-sync.js.map +1 -0
  84. package/dist/peer-authorization.d.ts +113 -18
  85. package/dist/peer-authorization.js +225 -29
  86. package/dist/peer-authorization.js.map +1 -1
  87. package/dist/peer-dial.d.ts +143 -27
  88. package/dist/peer-dial.js +276 -31
  89. package/dist/peer-dial.js.map +1 -1
  90. package/dist/peer-join-backfill.d.ts +26 -2
  91. package/dist/peer-join-backfill.js +60 -12
  92. package/dist/peer-join-backfill.js.map +1 -1
  93. package/dist/peer-record.d.ts +17 -52
  94. package/dist/peer-record.js +20 -58
  95. package/dist/peer-record.js.map +1 -1
  96. package/dist/pending-join-runner.d.ts +66 -58
  97. package/dist/pending-join-runner.js +136 -145
  98. package/dist/pending-join-runner.js.map +1 -1
  99. package/dist/primary-lan-address.d.ts +8 -0
  100. package/dist/primary-lan-address.js +46 -0
  101. package/dist/primary-lan-address.js.map +1 -0
  102. package/dist/provider/client.d.ts +131 -0
  103. package/dist/provider/client.js +226 -0
  104. package/dist/provider/client.js.map +1 -0
  105. package/dist/provider/descriptor.d.ts +41 -0
  106. package/dist/provider/descriptor.js +103 -0
  107. package/dist/provider/descriptor.js.map +1 -0
  108. package/dist/provider/index.d.ts +9 -0
  109. package/dist/provider/index.js +10 -0
  110. package/dist/provider/index.js.map +1 -0
  111. package/dist/provider/oauth.d.ts +125 -0
  112. package/dist/provider/oauth.js +199 -0
  113. package/dist/provider/oauth.js.map +1 -0
  114. package/dist/provider/rent-node.d.ts +101 -0
  115. package/dist/provider/rent-node.js +220 -0
  116. package/dist/provider/rent-node.js.map +1 -0
  117. package/dist/push-fanout.d.ts +8 -2
  118. package/dist/push-fanout.js +8 -2
  119. package/dist/push-fanout.js.map +1 -1
  120. package/dist/relay-addrs.d.ts +9 -4
  121. package/dist/relay-addrs.js +9 -4
  122. package/dist/relay-addrs.js.map +1 -1
  123. package/dist/relay-reservation.d.ts +51 -16
  124. package/dist/relay-reservation.js +107 -24
  125. package/dist/relay-reservation.js.map +1 -1
  126. package/dist/seed-bootstrap.d.ts +165 -123
  127. package/dist/seed-bootstrap.js +313 -275
  128. package/dist/seed-bootstrap.js.map +1 -1
  129. package/dist/seed-trust-policy.d.ts +98 -37
  130. package/dist/seed-trust-policy.js +188 -2
  131. package/dist/seed-trust-policy.js.map +1 -1
  132. package/dist/strand-addr-protocol.d.ts +24 -26
  133. package/dist/strand-addr-protocol.js +19 -26
  134. package/dist/strand-addr-protocol.js.map +1 -1
  135. package/dist/strand-commit-durability.d.ts +54 -0
  136. package/dist/strand-commit-durability.js +74 -0
  137. package/dist/strand-commit-durability.js.map +1 -0
  138. package/dist/strand-database.d.ts +23 -8
  139. package/dist/strand-database.js +41 -13
  140. package/dist/strand-database.js.map +1 -1
  141. package/dist/strand-first-sync-gate.d.ts +7 -1
  142. package/dist/strand-first-sync-gate.js +7 -1
  143. package/dist/strand-first-sync-gate.js.map +1 -1
  144. package/dist/strand-formation-protocol.js +5 -2
  145. package/dist/strand-formation-protocol.js.map +1 -1
  146. package/dist/strand-fret-addrs.d.ts +19 -1
  147. package/dist/strand-fret-addrs.js +27 -9
  148. package/dist/strand-fret-addrs.js.map +1 -1
  149. package/dist/strand-instance-manager.d.ts +81 -19
  150. package/dist/strand-instance-manager.js +216 -105
  151. package/dist/strand-instance-manager.js.map +1 -1
  152. package/dist/strand-move.d.ts +124 -0
  153. package/dist/strand-move.js +438 -0
  154. package/dist/strand-move.js.map +1 -0
  155. package/dist/strand-network-config.js +7 -6
  156. package/dist/strand-network-config.js.map +1 -1
  157. package/dist/strand-peer-redial.d.ts +113 -0
  158. package/dist/strand-peer-redial.js +236 -0
  159. package/dist/strand-peer-redial.js.map +1 -0
  160. package/dist/strand-revocation-enforcer.d.ts +11 -11
  161. package/dist/strand-revocation-enforcer.js +11 -11
  162. package/dist/strand-wake-protocol.d.ts +13 -16
  163. package/dist/strand-wake-protocol.js +23 -27
  164. package/dist/strand-wake-protocol.js.map +1 -1
  165. package/dist/trusted-owner-store.d.ts +35 -5
  166. package/dist/trusted-owner-store.js +50 -8
  167. package/dist/trusted-owner-store.js.map +1 -1
  168. package/dist/types.d.ts +512 -89
  169. package/dist/types.js +10 -0
  170. package/dist/types.js.map +1 -1
  171. package/package.json +19 -10
  172. package/src/cadre-invite-protocol.ts +1052 -0
  173. package/src/cadre-join-request.ts +167 -0
  174. package/src/cadre-node.ts +1703 -386
  175. package/src/claim-proof.ts +147 -0
  176. package/src/control-authorization.ts +203 -117
  177. package/src/control-cohort.ts +1 -1
  178. package/src/control-database.ts +4663 -3453
  179. package/src/control-protocol-guard.ts +348 -0
  180. package/src/control-schema.ts +828 -1078
  181. package/src/control-stream.ts +26 -7
  182. package/src/delegate-admission.ts +1 -1
  183. package/src/device-token.ts +14 -10
  184. package/src/ed25519-key.ts +47 -10
  185. package/src/fetch-impl.ts +23 -0
  186. package/src/file-durable-slot.ts +64 -63
  187. package/src/file-safe-name.ts +32 -0
  188. package/src/formation-approval.ts +604 -610
  189. package/src/fs-atomic.ts +92 -117
  190. package/src/index.ts +789 -648
  191. package/src/invitation-bootstrap.ts +91 -13
  192. package/src/joined-strand-store.ts +508 -498
  193. package/src/key-store-file.ts +142 -141
  194. package/src/link-budget.ts +25 -36
  195. package/src/machine-removal.ts +216 -0
  196. package/src/membership-connection-gater.ts +259 -191
  197. package/src/node-claim-payload.ts +259 -0
  198. package/src/node-default-transports.ts +38 -0
  199. package/src/node-transports.ts +49 -0
  200. package/src/owner-anchor-sync.ts +171 -0
  201. package/src/peer-authorization.ts +258 -29
  202. package/src/peer-dial.ts +604 -315
  203. package/src/peer-join-backfill.ts +62 -11
  204. package/src/peer-record.ts +159 -197
  205. package/src/pending-join-runner.ts +729 -735
  206. package/src/primary-lan-address.ts +47 -0
  207. package/src/provider/client.ts +326 -0
  208. package/src/provider/descriptor.ts +129 -0
  209. package/src/provider/index.ts +59 -0
  210. package/src/provider/oauth.ts +285 -0
  211. package/src/provider/rent-node.ts +275 -0
  212. package/src/push-fanout.ts +8 -2
  213. package/src/relay-addrs.ts +9 -4
  214. package/src/relay-reservation.ts +1211 -1121
  215. package/src/seed-bootstrap.ts +1502 -1448
  216. package/src/seed-trust-policy.ts +353 -140
  217. package/src/strand-addr-protocol.ts +26 -35
  218. package/src/strand-commit-durability.ts +116 -0
  219. package/src/strand-database.ts +46 -14
  220. package/src/strand-first-sync-gate.ts +7 -1
  221. package/src/strand-formation-protocol.ts +1039 -1036
  222. package/src/strand-fret-addrs.ts +179 -145
  223. package/src/strand-instance-manager.ts +2026 -1883
  224. package/src/strand-move.ts +585 -0
  225. package/src/strand-network-config.ts +7 -6
  226. package/src/strand-peer-redial.ts +307 -0
  227. package/src/strand-revocation-enforcer.ts +11 -11
  228. package/src/strand-wake-protocol.ts +23 -30
  229. package/src/trusted-owner-store.ts +242 -171
  230. package/src/types.ts +2687 -2242
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The claim payload: what a host shows as a QR code (and as text) for a node that is
3
+ * waiting to be claimed, and what the owner's phone scans to claim it.
4
+ *
5
+ * `sereus-join:1.<base64url of canonical JSON>` where the JSON is
6
+ * `{ multiaddrs, peerId, secret }`: the node's peer id, every address the phone may
7
+ * dial it at (each ending in `/p2p/<peerId>`), and the node's one-time claim secret
8
+ * (`claim-proof.ts`). The phone hands all three to `CadreNode.claimNode`. The payload
9
+ * carries no party id: the claim supplies it, and the node records it.
10
+ *
11
+ * The decoder lives here, beside the encoder, because the phone and the host both need
12
+ * it and neither depends on the other. Imports only `@multiformats/multiaddr`,
13
+ * `@libp2p/peer-id` and `uint8arrays`, so it loads on React Native and in the browser.
14
+ */
15
+ import { peerIdFromString } from '@libp2p/peer-id';
16
+ import {
17
+ multiaddr,
18
+ CODE_DNS,
19
+ CODE_DNS4,
20
+ CODE_DNS6,
21
+ CODE_DNSADDR,
22
+ CODE_IP4,
23
+ CODE_IP6,
24
+ CODE_IP6ZONE,
25
+ CODE_P2P,
26
+ CODE_P2P_CIRCUIT,
27
+ CODE_WS,
28
+ CODE_WSS,
29
+ } from '@multiformats/multiaddr';
30
+ import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
31
+ import { canonicalJson } from './canonical-json.js';
32
+ import { parseClaimSecret } from './claim-proof.js';
33
+
34
+ /** Version 1 of the payload; the only one either side reads. */
35
+ export const NODE_CLAIM_PAYLOAD_PREFIX = 'sereus-join:1.';
36
+
37
+ export interface NodeClaimPayload {
38
+ /** The node's peer id. */
39
+ peerId: string;
40
+ /** Addresses the phone may dial the node at, each ending in `/p2p/<peerId>`. */
41
+ multiaddrs: string[];
42
+ /** The node's claim secret, base64url (`parseClaimSecret`). */
43
+ secret: string;
44
+ }
45
+
46
+ /** Encode a payload as the text the host shows. Refuses what {@link decodeNodeClaimPayload} would. */
47
+ export function encodeNodeClaimPayload(payload: NodeClaimPayload): string {
48
+ const checked = requireNodeClaimPayload(payload);
49
+ const json = canonicalJson({ multiaddrs: checked.multiaddrs, peerId: checked.peerId, secret: checked.secret });
50
+ return `${NODE_CLAIM_PAYLOAD_PREFIX}${uint8ArrayToString(new TextEncoder().encode(json), 'base64url')}`;
51
+ }
52
+
53
+ /**
54
+ * Decode the text a phone scanned or pasted. Refuses, naming the problem: any version but
55
+ * 1, a body that is not base64url JSON of the right shape, a peer id that does not parse,
56
+ * an empty address list, an address that does not parse or whose last `/p2p/` is not that
57
+ * peer id, and a secret {@link parseClaimSecret} refuses. The secret is never echoed.
58
+ */
59
+ export function decodeNodeClaimPayload(text: string): NodeClaimPayload {
60
+ const trimmed = text.trim();
61
+ if (!trimmed.startsWith(NODE_CLAIM_PAYLOAD_PREFIX)) {
62
+ throw new Error(`A claim payload must start with "${NODE_CLAIM_PAYLOAD_PREFIX}" (this one starts with "${trimmed.slice(0, NODE_CLAIM_PAYLOAD_PREFIX.length)}")`);
63
+ }
64
+ let parsed: unknown;
65
+ try {
66
+ const json = new TextDecoder().decode(uint8ArrayFromString(trimmed.slice(NODE_CLAIM_PAYLOAD_PREFIX.length), 'base64url'));
67
+ parsed = JSON.parse(json);
68
+ } catch (error) {
69
+ throw new Error('A claim payload must carry base64url-encoded JSON after its prefix', { cause: error });
70
+ }
71
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
72
+ throw new Error('A claim payload must decode to a JSON object');
73
+ }
74
+ const { peerId, multiaddrs, secret } = parsed as Record<string, unknown>;
75
+ if (typeof peerId !== 'string') throw new Error('A claim payload must name the node\'s peer id');
76
+ if (!Array.isArray(multiaddrs) || !multiaddrs.every((a): a is string => typeof a === 'string')) {
77
+ throw new Error('A claim payload must carry the node\'s addresses as a list of strings');
78
+ }
79
+ if (typeof secret !== 'string') throw new Error('A claim payload must carry the claim secret');
80
+ return requireNodeClaimPayload({ peerId, multiaddrs, secret });
81
+ }
82
+
83
+ /** How {@link selectNodeClaimAddresses} narrows a node's addresses. */
84
+ export interface NodeClaimAddressOptions {
85
+ /**
86
+ * The machine's LAN address, the one a phone at home reaches it on. A string keeps only
87
+ * the private addresses on that IP (dropping Docker bridges, VPN and other interfaces no
88
+ * phone can reach); `null` drops every private address (a machine reached only by its
89
+ * public name); absent keeps them all, for a caller that cannot tell.
90
+ */
91
+ lan?: string | null;
92
+ /** Keep addresses a phone cannot dial: plain TCP. Default false, since phones dial WebSocket and relay only. */
93
+ includeTcp?: boolean;
94
+ }
95
+
96
+ /**
97
+ * The addresses a node code should carry, from the ones a node knows it has (`/status`,
98
+ * a NAT layer's public addresses). A phone dials them in turn, each on its own timeout, so
99
+ * every address it cannot reach only delays a failing claim, and makes the QR code bigger.
100
+ *
101
+ * - Each gains `/p2p/<peerId>` when it lacks a destination; loopback, unspecified and
102
+ * unparsable ones are dropped, and so is plain TCP unless `includeTcp`.
103
+ * - Public names (`/dns*`) come first: they work away from home. Public IP addresses are
104
+ * kept only when there is no public name, since they reach the same machine.
105
+ * - Private addresses follow, narrowed by {@link NodeClaimAddressOptions.lan}; relay
106
+ * addresses last.
107
+ *
108
+ * Pure and dependency-light, like the codec beside it, so it loads on React Native too.
109
+ * Finding the LAN address is the caller's (Node: `@serfab/cadre-core/primary-lan-address`).
110
+ */
111
+ export function selectNodeClaimAddresses(reported: readonly string[], peerId: string, options: NodeClaimAddressOptions = {}): string[] {
112
+ const names: string[] = [];
113
+ const publicIps: string[] = [];
114
+ const privates: string[] = [];
115
+ const relayed: string[] = [];
116
+ for (const raw of reported) {
117
+ const classified = classifyClaimAddress(raw.trim(), peerId, options);
118
+ if (!classified) continue;
119
+ ({ name: names, public: publicIps, private: privates, relay: relayed })[classified.kind].push(classified.addr);
120
+ }
121
+ return [...new Set([...names, ...(names.length > 0 ? [] : publicIps), ...privates, ...relayed])];
122
+ }
123
+
124
+ /**
125
+ * `addr` as a node code carries it: with `/p2p/<peerId>` appended unless it already names a
126
+ * destination. A relay address that ends at its hop (`…/p2p/<relay>/p2p-circuit`) names none,
127
+ * so it gains the node's id too. Throws when `addr` does not parse. For callers that take
128
+ * exact addresses from an operator; {@link selectNodeClaimAddresses} applies it itself.
129
+ */
130
+ export function withClaimDestination(addr: string, peerId: string): string {
131
+ const trimmed = addr.trim();
132
+ return destinationPeerIdOf(trimmed) === null ? `${trimmed}/p2p/${peerId}` : trimmed;
133
+ }
134
+
135
+ /**
136
+ * Where a phone could dial an address from: a relayed address (`/p2p-circuit`), a public name,
137
+ * a public IP, a private (LAN, VPN, link-local) IP, or this machine's own loopback.
138
+ */
139
+ export type DialAddressKind = 'relay' | 'name' | 'public' | 'private' | 'loopback';
140
+
141
+ /**
142
+ * Classify `addr` for a phone dialing it, or undefined when no phone can dial it at all: it
143
+ * does not parse, names the unspecified address, or is plain TCP without `includeTcp` (phones
144
+ * dial WebSocket and relay only).
145
+ */
146
+ export function classifyDialAddress(addr: string, options: { includeTcp?: boolean } = {}): DialAddressKind | undefined {
147
+ const components = componentsOf(addr);
148
+ return components ? classifyComponents(components, options.includeTcp ?? false)?.kind : undefined;
149
+ }
150
+
151
+ type AddressComponents = ReturnType<ReturnType<typeof multiaddr>['getComponents']>;
152
+
153
+ function componentsOf(addr: string): AddressComponents | undefined {
154
+ try {
155
+ return multiaddr(addr).getComponents();
156
+ } catch {
157
+ return undefined;
158
+ }
159
+ }
160
+
161
+ /** {@link classifyDialAddress}, keeping the IP for a caller that narrows private addresses by it. */
162
+ function classifyComponents(components: AddressComponents, includeTcp: boolean): { kind: DialAddressKind; ip?: string } | undefined {
163
+ if (components.some((c) => c.code === CODE_P2P_CIRCUIT)) return { kind: 'relay' };
164
+ if (!includeTcp && !components.some((c) => c.code === CODE_WS || c.code === CODE_WSS)) return undefined;
165
+ const host = components[0];
166
+ if (!host?.value) return undefined;
167
+ if (host.code === CODE_DNS || host.code === CODE_DNS4 || host.code === CODE_DNS6 || host.code === CODE_DNSADDR) {
168
+ return { kind: host.value === 'localhost' ? 'loopback' : 'name' };
169
+ }
170
+ if (host.code !== CODE_IP4 && host.code !== CODE_IP6 && host.code !== CODE_IP6ZONE) return undefined;
171
+ const ip = host.code === CODE_IP6ZONE ? components[1]?.value ?? '' : host.value;
172
+ if (ip === '0.0.0.0' || ip === '::') return undefined;
173
+ if (ip.startsWith('127.') || ip === '::1') return { kind: 'loopback', ip };
174
+ if (host.code !== CODE_IP6ZONE && !isPrivateIp(ip)) return { kind: 'public', ip };
175
+ return { kind: 'private', ip };
176
+ }
177
+
178
+ /** One address's place in {@link selectNodeClaimAddresses}, or undefined to drop it. */
179
+ function classifyClaimAddress(addr: string, peerId: string, options: NodeClaimAddressOptions): { kind: Exclude<DialAddressKind, 'loopback'>; addr: string } | undefined {
180
+ const components = componentsOf(addr);
181
+ if (!components) return undefined;
182
+ const classified = classifyComponents(components, options.includeTcp ?? false);
183
+ if (!classified || classified.kind === 'loopback') return undefined;
184
+ if (classified.kind === 'private' && (options.lan === null || (options.lan !== undefined && classified.ip !== options.lan))) {
185
+ return undefined;
186
+ }
187
+ return { kind: classified.kind, addr: destinationIn(components) === null ? `${addr}/p2p/${peerId}` : addr };
188
+ }
189
+
190
+ /** RFC 1918, carrier-grade NAT (100.64/10), link-local, and IPv6 unique-local / link-local. */
191
+ function isPrivateIp(ip: string): boolean {
192
+ if (ip.includes(':')) return /^(f[cd]|fe[89ab])/i.test(ip);
193
+ const [a, b] = ip.split('.').map(Number) as [number, number];
194
+ return a === 10
195
+ || (a === 172 && b >= 16 && b <= 31)
196
+ || (a === 192 && b === 168)
197
+ || (a === 169 && b === 254)
198
+ || (a === 100 && b >= 64 && b <= 127);
199
+ }
200
+
201
+ /** The shape rules both directions apply. Returns the payload with its fields trimmed. */
202
+ function requireNodeClaimPayload(payload: NodeClaimPayload): NodeClaimPayload {
203
+ const peerId = parsePeerId(payload.peerId);
204
+ const multiaddrs = payload.multiaddrs.map((a) => a.trim());
205
+ if (multiaddrs.length === 0) throw new Error('A claim payload must carry at least one address for the node');
206
+ for (const addr of multiaddrs) requireAddressOf(addr, peerId);
207
+ // The secret is checked, never kept in a message: see `parseClaimSecret`.
208
+ parseClaimSecret(payload.secret);
209
+ return { peerId: peerId.toString(), multiaddrs, secret: payload.secret.trim() };
210
+ }
211
+
212
+ function parsePeerId(text: string): ReturnType<typeof peerIdFromString> {
213
+ try {
214
+ return peerIdFromString(text.trim());
215
+ } catch (error) {
216
+ throw new Error(`A claim payload's peer id does not parse ("${text}")`, { cause: error });
217
+ }
218
+ }
219
+
220
+ /** `addr` parses, and its destination (the last `/p2p/`, past any relay hop) is `peerId`. */
221
+ function requireAddressOf(addr: string, peerId: ReturnType<typeof peerIdFromString>): void {
222
+ let destination: string | null;
223
+ try {
224
+ destination = destinationPeerIdOf(addr);
225
+ } catch (error) {
226
+ throw new Error(`A claim payload address does not parse ("${addr}")`, { cause: error });
227
+ }
228
+ if (destination === null) {
229
+ throw new Error(`A claim payload address must end in /p2p/${peerId.toString()} ("${addr}" names no peer)`);
230
+ }
231
+ let named: ReturnType<typeof peerIdFromString>;
232
+ try {
233
+ named = peerIdFromString(destination);
234
+ } catch (error) {
235
+ throw new Error(`A claim payload address names a peer id that does not parse ("${addr}")`, { cause: error });
236
+ }
237
+ if (!named.equals(peerId)) {
238
+ throw new Error(`A claim payload address names another peer ("${addr}" is not an address of ${peerId.toString()})`);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * The peer an address reaches: its last `/p2p/` component. A relayed address
244
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<destination>`) names its destination after the
245
+ * circuit hop; one that ends at the hop names nobody. Same rule as
246
+ * `groupAddrsByPeerId` in `peer-addr-book.ts`. Throws when `addr` does not parse.
247
+ */
248
+ export function destinationPeerIdOf(addr: string): string | null {
249
+ return destinationIn(multiaddr(addr).getComponents());
250
+ }
251
+
252
+ function destinationIn(components: AddressComponents): string | null {
253
+ for (let i = components.length - 1; i >= 0; i--) {
254
+ const component = components[i]!;
255
+ if (component.code === CODE_P2P_CIRCUIT) return null;
256
+ if (component.code === CODE_P2P && component.value) return component.value;
257
+ }
258
+ return null;
259
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Node-only: `@optimystic/db-p2p`'s default transport list, for `NetworkConfig.defaultTransports`.
3
+ *
4
+ * A node with configured relays is built from an explicit transport list, so that libp2p's relay
5
+ * discovery can be switched off in it (`node-transports.ts`). A Node host that supplies no
6
+ * `network.transports` passes this function so that list still matches what db-p2p would have
7
+ * built. A subpath module (`@serfab/cadre-core/node-default-transports`), like `push-node`,
8
+ * because it names `@libp2p/tcp`: some bundlers (the NativeScript reference app's webpack) take
9
+ * its Node implementation rather than its browser stub, and that needs `net`, `os` and `path`.
10
+ */
11
+
12
+ import { tcp } from '@libp2p/tcp';
13
+ import { webSockets } from '@libp2p/websockets';
14
+ import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
15
+ import type { Libp2pTransports } from '@optimystic/db-p2p';
16
+ import type { ListenTransportOptions } from './relay-addrs.js';
17
+
18
+ /**
19
+ * TCP, WebSocket exactly when the node's listen entries switch it on, and the circuit-relay
20
+ * transport.
21
+ *
22
+ * Passing an explicit list makes db-p2p ignore `wsPort` for transports, which is why WebSocket is
23
+ * decided here from the same switch. Its other use of `wsPort`, a default WebSocket listen
24
+ * address, never applies: a node with configured relays always has explicit listen entries.
25
+ *
26
+ * NOTE: mirrors `createLibp2pNode`'s default list in
27
+ * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (cadre never sets its `disableTcp`). That file
28
+ * is the source of truth; if its defaults change, this list has to follow. If db-p2p ever takes an
29
+ * option to build its default list with relay discovery off, use that and drop this module and
30
+ * `NetworkConfig.defaultTransports`.
31
+ */
32
+ export function nodeDefaultTransports({ wsPort }: ListenTransportOptions): Libp2pTransports {
33
+ return [
34
+ tcp(),
35
+ ...(wsPort === undefined ? [] : [webSockets()]),
36
+ circuitRelayTransport()
37
+ ];
38
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The `transports` option for a cadre-built libp2p node, control and strand alike.
3
+ *
4
+ * A node whose bare `/p2p-circuit` search entries cadre generated for configured relays gets its
5
+ * transports through {@link withoutRelayDiscovery}, so libp2p's relay discovery cannot hand those
6
+ * slots to some other relay-capable peer before the per-relay supervisors fill them (see
7
+ * `relay-reservation.ts`, "WHY LIBP2P'S RELAY DISCOVERY IS SWITCHED OFF"). Every other node gets
8
+ * the embedder's list as it was, or no option at all, and `@optimystic/db-p2p` builds its own
9
+ * default list.
10
+ *
11
+ * The wrapper needs a list to wrap. React Native and browser embedders always supply one
12
+ * (`network.transports`); a Node host supplies the default list through
13
+ * `network.defaultTransports` instead, since db-p2p builds its default internally and it names
14
+ * `@libp2p/tcp`, which this module's graph must not reach (`node-default-transports.ts`).
15
+ */
16
+
17
+ import debug from 'debug';
18
+ import type { Libp2pTransports } from '@optimystic/db-p2p';
19
+ import { withoutRelayDiscovery } from './relay-reservation.js';
20
+ import type { ListenTransportOptions } from './relay-addrs.js';
21
+ import type { NetworkConfig } from './types.js';
22
+
23
+ const log = debug('sereus:cadre:node-transports');
24
+
25
+ /**
26
+ * The `transports` option to spread into a node's `createLibp2pNode` options.
27
+ *
28
+ * @param listenTransports what the node's resolved listen entries imply (`resolveTransportOptions`
29
+ * in `relay-addrs.ts`), handed to `network.defaultTransports`.
30
+ * @param relaySlotsSupervised whether cadre generated this node's bare `/p2p-circuit` entries for
31
+ * configured relays and runs a supervisor over them — `network.relayAddrs` on the control node,
32
+ * a non-empty relay list from `strandNodeAddrs` on a strand node.
33
+ */
34
+ export function nodeTransportsOption(
35
+ network: NetworkConfig | undefined,
36
+ listenTransports: ListenTransportOptions,
37
+ relaySlotsSupervised: boolean
38
+ ): { transports?: Libp2pTransports } {
39
+ if (!relaySlotsSupervised) {
40
+ return network?.transports ? { transports: network.transports } : {};
41
+ }
42
+ const transports = network?.transports ?? network?.defaultTransports?.(listenTransports);
43
+ if (transports === undefined) {
44
+ log('Relays are configured but no transport list was supplied (network.transports or ' +
45
+ 'network.defaultTransports); libp2p relay discovery stays on and can take their slots');
46
+ return {};
47
+ }
48
+ return { transports: withoutRelayDiscovery(transports) };
49
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * How the node-local trusted-owner anchor follows the replicated `OwnerKey` table along
3
+ * VERIFIABLE chains — the pure rule, with no I/O, so it can be tested without a database.
4
+ * `CadreNode.syncOwnerAnchor` reads the table, the tombstones and the invitation chain,
5
+ * calls {@link deriveOwnerAnchor}, and applies the difference to the store.
6
+ *
7
+ * Why not simply trust the table: an empty local copy can seat any key through the
8
+ * schema's genesis branch and that row replicates (`docs/architecture.md` → "Node-local
9
+ * trusted-owner anchor"). So every node grows its anchor only through rows whose stored
10
+ * proof verifies against a key it already trusts, on every membership refresh. The terms
11
+ * used throughout:
12
+ *
13
+ * - **base**: the anchor's entries whose provenance is not `chain` (trusted out of band).
14
+ * - **live row**: an `OwnerKey` row whose stamp no tombstone retires.
15
+ * - **kept**: a `chain` entry that still has a live row. A derived entry is state, not
16
+ * recomputed from the base each pass: it entered through a proof that verified then, and
17
+ * it stays until its own row is retired or a verifiable tombstone removes it. This is what
18
+ * lets an owner rotate (A adds A', A' removes A): A' keeps its place after A's row is
19
+ * retired, although nothing could re-derive it from the remaining base.
20
+ * - **derivable from S**: a live row whose stored proof verifies against S — owner-signed
21
+ * (`vouchSig` set): `vouchOwner` is in S and `verifyOwnerKeyVoucher` holds;
22
+ * invitation-admitted (`vouchSig` null, `vouchUsage` set): `verifyInvitationOwnerAdmission`
23
+ * holds with S as the anchor. The founding row (all three null) is never derivable:
24
+ * founders enter anchors only out of band.
25
+ * - **derived**: the least fixpoint from base ∪ kept — add every key whose live row is
26
+ * derivable from what is already in the set, until nothing changes. **chainDerived** is the
27
+ * keys whose live row was derivable in this pass, base keys included.
28
+ * - **removed**: a key K in derived is removed when an `OwnerKey` tombstone names K, its
29
+ * signer is in derived and is not K, its stored signature verifies
30
+ * (`verifyRevocationSigner`), AND K is not in chainDerived. The last condition is what
31
+ * makes a re-add win over an older tombstone: a removed owner re-added under a fresh
32
+ * stamp has a live derivable row again, and the old stamp's tombstone no longer applies.
33
+ * - **target** = derived minus removed. If that would be empty, no removal is applied this
34
+ * pass (target = derived) and the refused removals are reported for the caller to log.
35
+ *
36
+ * Every tombstone is judged against the pass-start set (derived) at once, so the outcome
37
+ * does not depend on the order they are read in: a signer that is itself removed in this
38
+ * pass still counts, and a mutual removal of the last two owners is refused rather than
39
+ * decided by read order.
40
+ *
41
+ * An owner C that a removed owner B had added therefore stays where it was already derived
42
+ * (its row is live) and cannot be derived on a machine that never held it (the chain from
43
+ * that machine's base runs through B's retired row) until a remaining owner re-adds it or
44
+ * an invitation pins it there. The rotation case above is the same shape with C = A', so the
45
+ * two cannot be told apart from replicated state; keeping is the only rule under which a
46
+ * sole owner can rotate at all.
47
+ */
48
+ import { verifyInvitationOwnerAdmission, verifyOwnerKeyVoucher, verifyRevocationSigner } from './peer-authorization.js';
49
+ import type { TrustSource } from './trusted-owner-store.js';
50
+ import type { InvitationChain, OwnerKeyRow, RevocationRow } from './types.js';
51
+
52
+ export interface OwnerAnchorInputs {
53
+ /** The party whose table is being read; every stored proof is judged for it, so a voucher or tombstone signed for another party neither seats nor removes a key. */
54
+ partyId: string;
55
+ /** The anchor at the start of the pass, every key with its provenance (`TrustedOwnerStore.sources`). */
56
+ anchor: ReadonlyMap<string, TrustSource>;
57
+ /** `OwnerKey` rows as read; rows whose stamp a tombstone in `tombstones` retires are dropped here too. */
58
+ rows: readonly OwnerKeyRow[];
59
+ /** `Revocation` rows; only those with `tableName === 'OwnerKey'` are consulted. */
60
+ tombstones: readonly RevocationRow[];
61
+ /** The usage and invitation rows, when some owner row is invitation-admitted; null skips those rows. */
62
+ chain: InvitationChain | null;
63
+ }
64
+
65
+ export interface OwnerAnchorDerivation {
66
+ /** The keys the anchor should hold after this pass. */
67
+ target: ReadonlySet<string>;
68
+ /** Keys whose verifiable removal was NOT applied because the anchor would have emptied. */
69
+ refusedRemovals: readonly string[];
70
+ }
71
+
72
+ /** The rule above, as one pure function. */
73
+ export function deriveOwnerAnchor({ partyId, anchor, rows, tombstones, chain }: OwnerAnchorInputs): OwnerAnchorDerivation {
74
+ const ownerTombstones = tombstones.filter(tombstone => tombstone.tableName === 'OwnerKey');
75
+ // NOTE: a stamp is retired by any tombstone that names it, verified or not — the same
76
+ // reading `queryCadrePeers` and `getOwnerKeys` give the table. A forged tombstone can
77
+ // therefore prune a derived entry (its row goes) but never seat or keep one; if tombstone
78
+ // pollution is ever closed at the write side, judge retirement by the verified signer too.
79
+ const retired = new Set(ownerTombstones.map(tombstone => tombstone.stampId));
80
+ const liveRows = rows.filter(row => !retired.has(row.stampId));
81
+
82
+ const derived = passStartSet(anchor, liveRows);
83
+ const chainDerived = deriveFixpoint(partyId, derived, liveRows, chain);
84
+
85
+ const removed = removedKeys(partyId, derived, chainDerived, ownerTombstones);
86
+ if (removed.size > 0 && removed.size === derived.size) {
87
+ return { target: derived, refusedRemovals: Array.from(removed) };
88
+ }
89
+ const target = new Set(Array.from(derived).filter(key => !removed.has(key)));
90
+ return { target, refusedRemovals: [] };
91
+ }
92
+
93
+ /** base ∪ kept: every out-of-band entry, and every `chain` entry whose row is still live. */
94
+ function passStartSet(anchor: ReadonlyMap<string, TrustSource>, liveRows: readonly OwnerKeyRow[]): Set<string> {
95
+ const liveKeys = new Set(liveRows.map(row => row.key));
96
+ const start = new Set<string>();
97
+ for (const [key, source] of anchor) {
98
+ if (source !== 'chain' || liveKeys.has(key)) {
99
+ start.add(key);
100
+ }
101
+ }
102
+ return start;
103
+ }
104
+
105
+ /**
106
+ * Grow `derived` to the least fixpoint and return chainDerived: every key whose live row was
107
+ * derivable. A row is judged once its voucher is in the set, and settled either way then:
108
+ * trust only grows within a pass, and a proof that failed against a trusted voucher cannot
109
+ * pass later, so no row is verified twice.
110
+ */
111
+ function deriveFixpoint(partyId: string, derived: Set<string>, liveRows: readonly OwnerKeyRow[], chain: InvitationChain | null): Set<string> {
112
+ const chainDerived = new Set<string>();
113
+ const pending = new Set(liveRows);
114
+ let progress = true;
115
+ while (progress) {
116
+ progress = false;
117
+ for (const row of pending) {
118
+ if (row.vouchOwner === null || !derived.has(row.vouchOwner)) {
119
+ continue;
120
+ }
121
+ pending.delete(row);
122
+ if (proofVerifies(partyId, row, derived, chain)) {
123
+ chainDerived.add(row.key);
124
+ derived.add(row.key);
125
+ progress = true;
126
+ }
127
+ }
128
+ }
129
+ return chainDerived;
130
+ }
131
+
132
+ /** Does `row`'s stored proof verify against `trusted`, for `partyId`, by the kind of proof it carries (see the module doc)? */
133
+ function proofVerifies(partyId: string, row: OwnerKeyRow, trusted: ReadonlySet<string>, chain: InvitationChain | null): boolean {
134
+ if (row.vouchOwner === null) {
135
+ return false;
136
+ }
137
+ if (row.vouchSig !== null) {
138
+ return verifyOwnerKeyVoucher(partyId, row.key, row.stampId, row.vouchOwner, row.vouchSig);
139
+ }
140
+ if (row.vouchUsage === null) {
141
+ return false;
142
+ }
143
+ const usage = chain?.usages.get(row.vouchUsage);
144
+ const invite = usage === undefined ? undefined : chain?.invites.get(usage.inviteKey);
145
+ if (usage === undefined || invite === undefined) {
146
+ return false;
147
+ }
148
+ return verifyInvitationOwnerAdmission(partyId, row, usage, invite, key => trusted.has(key));
149
+ }
150
+
151
+ /**
152
+ * The keys of `derived` that a verifiable tombstone removes (see the module doc), every
153
+ * tombstone judged against the same pass-start set. A tombstone for a key outside `derived`
154
+ * changes nothing and is skipped before any signature work.
155
+ */
156
+ function removedKeys(partyId: string, derived: ReadonlySet<string>, chainDerived: ReadonlySet<string>, ownerTombstones: readonly RevocationRow[]): Set<string> {
157
+ const removed = new Set<string>();
158
+ for (const tombstone of ownerTombstones) {
159
+ const key = tombstone.rowKey;
160
+ if (!derived.has(key) || chainDerived.has(key) || removed.has(key)) {
161
+ continue;
162
+ }
163
+ if (tombstone.signerKey === key || !derived.has(tombstone.signerKey)) {
164
+ continue;
165
+ }
166
+ if (verifyRevocationSigner(partyId, tombstone)) {
167
+ removed.add(key);
168
+ }
169
+ }
170
+ return removed;
171
+ }