@serfab/cadre-host 0.11.0 → 0.13.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 (46) hide show
  1. package/README.md +406 -296
  2. package/dist/bin/host.d.ts +11 -7
  3. package/dist/bin/host.js +40 -12
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/installer/config.d.ts +4 -4
  6. package/dist/installer/config.js +5 -39
  7. package/dist/installer/config.js.map +1 -1
  8. package/dist/installer/identity.d.ts +8 -1
  9. package/dist/installer/identity.js +8 -1
  10. package/dist/installer/identity.js.map +1 -1
  11. package/dist/orchestrator/host-process-orchestrator.d.ts +2 -2
  12. package/dist/orchestrator/host-process-orchestrator.js +14 -4
  13. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  14. package/dist/server/routes/bootstrap-node-validation.d.ts +96 -0
  15. package/dist/server/routes/bootstrap-node-validation.js +178 -0
  16. package/dist/server/routes/bootstrap-node-validation.js.map +1 -0
  17. package/dist/server/routes/grants.js +8 -25
  18. package/dist/server/routes/grants.js.map +1 -1
  19. package/dist/server/routes/provision-request-validation.d.ts +45 -0
  20. package/dist/server/routes/provision-request-validation.js +97 -0
  21. package/dist/server/routes/provision-request-validation.js.map +1 -0
  22. package/dist/server/settings-store.d.ts +1 -1
  23. package/dist/server/settings-store.js +5 -1
  24. package/dist/server/settings-store.js.map +1 -1
  25. package/package.json +5 -4
  26. package/src/__tests__/cli.smoke.test.ts +8 -3
  27. package/src/__tests__/global-setup.ts +9 -4
  28. package/src/__tests__/orchestrator-node-identity.test.ts +204 -204
  29. package/src/__tests__/orchestrator.test.ts +951 -951
  30. package/src/bin/__tests__/cli-reference.test.ts +167 -0
  31. package/src/bin/host.ts +1326 -1299
  32. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  33. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  34. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  35. package/src/installer/__tests__/config.test.ts +134 -112
  36. package/src/installer/config.ts +5 -43
  37. package/src/installer/identity.ts +8 -1
  38. package/src/nat/__tests__/nat-service.test.ts +515 -497
  39. package/src/orchestrator/host-process-orchestrator.ts +1143 -1133
  40. package/src/server/__tests__/bootstrap-node-validation.test.ts +134 -0
  41. package/src/server/__tests__/grants-route.test.ts +326 -263
  42. package/src/server/__tests__/settings-route.test.ts +8 -7
  43. package/src/server/routes/bootstrap-node-validation.ts +187 -0
  44. package/src/server/routes/grants.ts +9 -26
  45. package/src/server/routes/provision-request-validation.ts +105 -0
  46. package/src/server/settings-store.ts +41 -37
@@ -1,497 +1,515 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
- import { mkdtempSync, rmSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
-
6
- import { NatService, createNatHandlers } from '../nat-service.js';
7
- import { ExternalIpDetector } from '../external-ip.js';
8
- import type { PortMapper, PortMappingResult } from '../port-mapper.js';
9
- import type { SecretsStore } from '../secrets/index.js';
10
- import { ddnsAccount } from '../secrets/index.js';
11
- import type { CadreNodeLike } from '../nat-service.js';
12
- import { OwnerNodeUnavailableError } from '../../owner/owner-node-client.js';
13
-
14
- class StubMapper implements PortMapper {
15
- mapCalls = 0;
16
- unmapCalls = 0;
17
- stopCalls = 0;
18
- externalIpValue: string | null = '203.0.113.10';
19
- mapFails = false;
20
- async map(o: { externalPort: number; internalPort: number; protocol?: 'tcp' | 'udp'; ttlMs?: number }): Promise<PortMappingResult> {
21
- this.mapCalls++;
22
- if (this.mapFails) throw new Error('router refused');
23
- return {
24
- mode: 'auto-upnp',
25
- externalIp: this.externalIpValue,
26
- externalPort: o.externalPort,
27
- internalPort: o.internalPort,
28
- protocol: o.protocol ?? 'tcp',
29
- leaseExpiresAt: new Date(Date.now() + (o.ttlMs ?? 60_000)),
30
- };
31
- }
32
- async verify() { return true; }
33
- async externalIp() { return this.externalIpValue; }
34
- async unmap() { this.unmapCalls++; }
35
- async stop() { this.stopCalls++; }
36
- }
37
-
38
- function makeSecrets(seed: Record<string, string> = {}): SecretsStore {
39
- const m = new Map(Object.entries(seed));
40
- return {
41
- async set(a, v) { m.set(a, v); },
42
- async get(a) { return m.has(a) ? m.get(a)! : null; },
43
- async delete(a) { return m.delete(a); },
44
- async list() { return [...m.keys()]; },
45
- };
46
- }
47
-
48
- function makeNode(peerId = '12D3KooWHost', addrs: string[] = ['/ip4/192.168.1.10/tcp/4001']): CadreNodeLike {
49
- return {
50
- getPeerId: () => peerId,
51
- getMultiaddrs: () => addrs,
52
- };
53
- }
54
-
55
- /**
56
- * A node that mimics a freshly spawned owner child: `getPeerId` throws
57
- * `OwnerNodeUnavailableError` for the first `failTimes` calls (admin channel
58
- * not bound yet), then returns a real peer ID. Exposes the call count so tests
59
- * can assert how many attempts the retry loop made.
60
- */
61
- function makeFlakyNode(
62
- failTimes: number,
63
- peerId = '12D3KooWFlaky',
64
- addrs: string[] = ['/ip4/192.168.1.10/tcp/4001'],
65
- ): { node: CadreNodeLike; peerIdCalls: () => number } {
66
- let calls = 0;
67
- const node: CadreNodeLike = {
68
- getPeerId: async () => {
69
- calls += 1;
70
- if (calls <= failTimes) throw new OwnerNodeUnavailableError('admin channel not bound yet');
71
- return peerId;
72
- },
73
- getMultiaddrs: async () => addrs,
74
- };
75
- return { node, peerIdCalls: () => calls };
76
- }
77
-
78
- function makeDetector(opts: { router?: string | null; pub?: string | null }): ExternalIpDetector {
79
- return new ExternalIpDetector({
80
- routerProbe: opts.router === undefined ? undefined : async () => opts.router ?? null,
81
- fetch: (async () => ({
82
- ok: opts.pub != null,
83
- status: opts.pub != null ? 200 : 500,
84
- async text() { return opts.pub ?? ''; },
85
- })) as unknown as typeof fetch,
86
- publicIpUrls: ['https://stub.test'],
87
- });
88
- }
89
-
90
- let tmpRoot: string;
91
- beforeEach(() => {
92
- tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-nat-svc-'));
93
- });
94
- afterEach(() => {
95
- try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
96
- });
97
-
98
- describe('NatService', () => {
99
- it('start() runs port mapping, detects IP, status reflects auto-upnp', async () => {
100
- const mapper = new StubMapper();
101
- const svc = new NatService({
102
- rootDir: tmpRoot,
103
- cadreNode: makeNode(),
104
- secretsStore: makeSecrets(),
105
- portMapper: mapper,
106
- externalIpDetector: makeDetector({ router: '203.0.113.10', pub: '203.0.113.10' }),
107
- });
108
- await svc.start();
109
- const s = svc.getStatus();
110
- expect(s.portMode).toBe('auto-upnp');
111
- expect(s.externalPort).toBe(4001);
112
- expect(s.externalIp).toBe('203.0.113.10');
113
- expect(s.directReachability).toBe('reachable');
114
- expect(mapper.mapCalls).toBe(1);
115
- });
116
-
117
- it('detects CGNAT and flags directReachability=cgnat', async () => {
118
- const mapper = new StubMapper();
119
- const svc = new NatService({
120
- rootDir: tmpRoot,
121
- cadreNode: makeNode(),
122
- secretsStore: makeSecrets(),
123
- portMapper: mapper,
124
- externalIpDetector: makeDetector({ router: '100.64.0.5', pub: '203.0.113.10' }),
125
- });
126
- await svc.start();
127
- const s = svc.getStatus();
128
- expect(s.cgnatDetected).toBe(true);
129
- expect(s.directReachability).toBe('cgnat');
130
- });
131
-
132
- it('flips portMode to failed when mapper throws', async () => {
133
- const mapper = new StubMapper();
134
- mapper.mapFails = true;
135
- const svc = new NatService({
136
- rootDir: tmpRoot,
137
- cadreNode: makeNode(),
138
- secretsStore: makeSecrets(),
139
- portMapper: mapper,
140
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
141
- });
142
- await svc.start();
143
- expect(svc.getStatus().portMode).toBe('failed');
144
- expect(svc.getStatus().directReachability).toBe('unreachable');
145
- });
146
-
147
- it('stop() unmaps and is idempotent', async () => {
148
- const mapper = new StubMapper();
149
- const svc = new NatService({
150
- rootDir: tmpRoot,
151
- cadreNode: makeNode(),
152
- secretsStore: makeSecrets(),
153
- portMapper: mapper,
154
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
155
- });
156
- await svc.start();
157
- await svc.stop();
158
- await svc.stop();
159
- expect(mapper.unmapCalls).toBe(1);
160
- expect(mapper.stopCalls).toBe(1);
161
- });
162
-
163
- it('getInviteAddresses → dns4 when DDNS configured + reachable', async () => {
164
- const mapper = new StubMapper();
165
- const secrets = makeSecrets({ [ddnsAccount('duckdns', 'token')]: 'T' });
166
- const svc = new NatService({
167
- rootDir: tmpRoot,
168
- cadreNode: makeNode('12D3KooWHost'),
169
- secretsStore: secrets,
170
- portMapper: mapper,
171
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
172
- });
173
- await svc.start();
174
- await svc.putDdns({
175
- providerId: 'duckdns',
176
- hostname: 'foo.duckdns.org',
177
- config: { token: 'T' },
178
- });
179
- const addrs = await svc.getInviteAddresses();
180
- expect(addrs).toEqual(['/dns4/foo.duckdns.org/tcp/4001/p2p/12D3KooWHost']);
181
- });
182
-
183
- it('getInviteAddresses → ip4 when reachable but no DDNS', async () => {
184
- const mapper = new StubMapper();
185
- const svc = new NatService({
186
- rootDir: tmpRoot,
187
- cadreNode: makeNode('12D3KooWHost'),
188
- secretsStore: makeSecrets(),
189
- portMapper: mapper,
190
- externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
191
- });
192
- await svc.start();
193
- const addrs = await svc.getInviteAddresses();
194
- expect(addrs).toEqual(['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWHost']);
195
- });
196
-
197
- it('getInviteAddresses → libp2p fallback when unreachable', async () => {
198
- const mapper = new StubMapper();
199
- mapper.mapFails = true;
200
- const svc = new NatService({
201
- rootDir: tmpRoot,
202
- cadreNode: makeNode('12D3KooWHost', ['/ip4/10.0.0.5/tcp/4001']),
203
- secretsStore: makeSecrets(),
204
- portMapper: mapper,
205
- externalIpDetector: makeDetector({ pub: null }),
206
- });
207
- await svc.start();
208
- const addrs = await svc.getInviteAddresses();
209
- expect(addrs).toEqual(['/ip4/10.0.0.5/tcp/4001/p2p/12D3KooWHost']);
210
- });
211
-
212
- it('putDdns persists secrets and updates status', async () => {
213
- const secrets = makeSecrets();
214
- const mapper = new StubMapper();
215
- const svc = new NatService({
216
- rootDir: tmpRoot,
217
- cadreNode: makeNode(),
218
- secretsStore: secrets,
219
- portMapper: mapper,
220
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
221
- });
222
- await svc.start();
223
- const status = await svc.putDdns({
224
- providerId: 'duckdns',
225
- hostname: 'h.duckdns.org',
226
- config: { token: 'TOK' },
227
- });
228
- expect(status.ddns.providerId).toBe('duckdns');
229
- expect(status.ddns.hostname).toBe('h.duckdns.org');
230
- expect(await secrets.get(ddnsAccount('duckdns', 'token'))).toBe('TOK');
231
- });
232
-
233
- it('putDdns with unknown provider → ddns_provider_unknown', async () => {
234
- const mapper = new StubMapper();
235
- const svc = new NatService({
236
- rootDir: tmpRoot,
237
- cadreNode: makeNode(),
238
- secretsStore: makeSecrets(),
239
- portMapper: mapper,
240
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
241
- });
242
- await svc.start();
243
- await expect(svc.putDdns({
244
- providerId: 'no-such-provider',
245
- hostname: 'x',
246
- config: {},
247
- })).rejects.toMatchObject({ code: 'ddns_provider_unknown' });
248
- });
249
-
250
- it('putSettings can disable UPnP and re-enable it', async () => {
251
- const mapper = new StubMapper();
252
- const svc = new NatService({
253
- rootDir: tmpRoot,
254
- cadreNode: makeNode(),
255
- secretsStore: makeSecrets(),
256
- portMapper: mapper,
257
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
258
- });
259
- await svc.start();
260
- expect(mapper.mapCalls).toBe(1);
261
-
262
- let s = await svc.putSettings({ upnpEnabled: false });
263
- expect(s.portMode).toBe('disabled');
264
-
265
- s = await svc.putSettings({ upnpEnabled: true });
266
- expect(s.portMode).toBe('auto-upnp');
267
- expect(mapper.mapCalls).toBeGreaterThanOrEqual(2);
268
- });
269
-
270
- it('testReachability re-runs IP detect and updates lastTestedAt', async () => {
271
- const mapper = new StubMapper();
272
- const svc = new NatService({
273
- rootDir: tmpRoot,
274
- cadreNode: makeNode(),
275
- secretsStore: makeSecrets(),
276
- portMapper: mapper,
277
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
278
- });
279
- await svc.start();
280
- expect(svc.getStatus().lastTestedAt).toBeNull();
281
- await svc.testReachability();
282
- expect(svc.getStatus().lastTestedAt).not.toBeNull();
283
- });
284
-
285
- it('listDdnsProviders returns at least DuckDNS', () => {
286
- const svc = new NatService({
287
- rootDir: tmpRoot,
288
- cadreNode: makeNode(),
289
- secretsStore: makeSecrets(),
290
- portMapper: new StubMapper(),
291
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
292
- });
293
- const providers = svc.listDdnsProviders();
294
- const duck = providers.find((p) => p.id === 'duckdns');
295
- expect(duck).toBeDefined();
296
- expect(duck!.configFields[0]).toMatchObject({ key: 'token', secret: true });
297
- });
298
- });
299
-
300
- describe('NatService — async channel node + onAddressesChanged', () => {
301
- it('getInviteAddresses awaits async getPeerId/getMultiaddrs from the channel', async () => {
302
- const asyncNode: CadreNodeLike = {
303
- getPeerId: async () => '12D3KooWAsync',
304
- getMultiaddrs: async () => ['/ip4/10.0.0.9/tcp/4001'],
305
- };
306
- const svc = new NatService({
307
- rootDir: tmpRoot,
308
- cadreNode: asyncNode,
309
- secretsStore: makeSecrets(),
310
- portMapper: new StubMapper(),
311
- externalIpDetector: makeDetector({ pub: '203.0.113.50' }),
312
- });
313
- await svc.start();
314
- const addrs = await svc.getInviteAddresses();
315
- expect(addrs).toEqual(['/ip4/203.0.113.50/tcp/4001/p2p/12D3KooWAsync']);
316
- });
317
-
318
- it('throws node_unavailable when the node reports an empty peer ID (not ready)', async () => {
319
- const notReadyNode: CadreNodeLike = {
320
- getPeerId: async () => '',
321
- getMultiaddrs: async () => [],
322
- };
323
- const svc = new NatService({
324
- rootDir: tmpRoot,
325
- cadreNode: notReadyNode,
326
- secretsStore: makeSecrets(),
327
- portMapper: new StubMapper(),
328
- externalIpDetector: makeDetector({ pub: '203.0.113.50' }),
329
- });
330
- await svc.start();
331
- await expect(svc.getInviteAddresses()).rejects.toMatchObject({ code: 'node_unavailable' });
332
- });
333
-
334
- it('fires onAddressesChanged on putSettings and testReachability', async () => {
335
- const svc = new NatService({
336
- rootDir: tmpRoot,
337
- cadreNode: makeNode('12D3KooWHook'),
338
- secretsStore: makeSecrets(),
339
- portMapper: new StubMapper(),
340
- externalIpDetector: makeDetector({ pub: '203.0.113.7' }),
341
- });
342
- await svc.start();
343
-
344
- const fired: string[][] = [];
345
- svc.onAddressesChanged((addrs) => { fired.push(addrs); });
346
-
347
- await svc.putSettings({ externalPort: 4002 });
348
- await svc.testReachability();
349
-
350
- expect(fired.length).toBeGreaterThanOrEqual(2);
351
- // The pushed addresses carry the node's peer ID.
352
- expect(fired[fired.length - 1]!.every((a: string) => a.includes('12D3KooWHook'))).toBe(true);
353
- });
354
-
355
- it('onAddressesChanged unsubscribe stops further notifications', async () => {
356
- const svc = new NatService({
357
- rootDir: tmpRoot,
358
- cadreNode: makeNode(),
359
- secretsStore: makeSecrets(),
360
- portMapper: new StubMapper(),
361
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
362
- });
363
- await svc.start();
364
- let count = 0;
365
- const off = svc.onAddressesChanged(() => { count++; });
366
- await svc.testReachability();
367
- off();
368
- await svc.testReachability();
369
- expect(count).toBe(1);
370
- });
371
- });
372
-
373
- describe('NatService — initial invite-address push retry', () => {
374
- it('delivers the initial push exactly once when the node is ready on the first attempt', async () => {
375
- // The common production happy path: node bound fast, listener registered
376
- // BEFORE start(). No retry needed — but the push must still fire (once).
377
- const { node, peerIdCalls } = makeFlakyNode(0, '12D3KooWReady');
378
- const svc = new NatService({
379
- rootDir: tmpRoot,
380
- cadreNode: node,
381
- secretsStore: makeSecrets(),
382
- portMapper: new StubMapper(),
383
- externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
384
- initialPushRetryMs: 1,
385
- initialPushTimeoutMs: 2_000,
386
- });
387
-
388
- const fired: string[][] = [];
389
- svc.onAddressesChanged((addrs) => { fired.push(addrs); });
390
-
391
- await svc.start();
392
-
393
- expect(fired).toEqual([['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWReady']]);
394
- expect(peerIdCalls()).toBe(1); // succeeded on the first attempt, no retry
395
- });
396
-
397
- it('retries past a not-yet-ready node and delivers the push exactly once', async () => {
398
- const { node, peerIdCalls } = makeFlakyNode(3, '12D3KooWFlaky');
399
- const svc = new NatService({
400
- rootDir: tmpRoot,
401
- cadreNode: node,
402
- secretsStore: makeSecrets(),
403
- portMapper: new StubMapper(),
404
- externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
405
- initialPushRetryMs: 1,
406
- initialPushTimeoutMs: 2_000,
407
- });
408
-
409
- // Listener registered BEFORE start() — this is the race the fix closes.
410
- const fired: string[][] = [];
411
- svc.onAddressesChanged((addrs) => { fired.push(addrs); });
412
-
413
- await svc.start();
414
-
415
- // Delivered exactly once, with the NAT-resolved address carrying the peer ID.
416
- expect(fired).toEqual([['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWFlaky']]);
417
- // It took the failing attempts plus the successful one (proves it retried).
418
- expect(peerIdCalls()).toBe(4);
419
- });
420
-
421
- it('gives up after the bounded timeout but still resolves start() (best-effort)', async () => {
422
- // Always unavailable — the retry budget elapses without a successful push.
423
- const node: CadreNodeLike = {
424
- getPeerId: async () => { throw new OwnerNodeUnavailableError('never ready'); },
425
- getMultiaddrs: async () => [],
426
- };
427
- const svc = new NatService({
428
- rootDir: tmpRoot,
429
- cadreNode: node,
430
- secretsStore: makeSecrets(),
431
- portMapper: new StubMapper(),
432
- externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
433
- initialPushRetryMs: 2,
434
- initialPushTimeoutMs: 20,
435
- });
436
-
437
- const fired: string[][] = [];
438
- svc.onAddressesChanged((addrs) => { fired.push(addrs); });
439
-
440
- await svc.start(); // resolves despite the node never coming up
441
- expect(fired).toEqual([]); // best-effort: nothing delivered
442
- // The process is otherwise healthy — status still builds.
443
- expect(svc.getStatus().portMode).toBe('auto-upnp');
444
- });
445
-
446
- it('does not retry on a non-node_unavailable error', async () => {
447
- let calls = 0;
448
- const node: CadreNodeLike = {
449
- getPeerId: async () => { calls += 1; throw new Error('boom'); },
450
- getMultiaddrs: async () => [],
451
- };
452
- const svc = new NatService({
453
- rootDir: tmpRoot,
454
- cadreNode: node,
455
- secretsStore: makeSecrets(),
456
- portMapper: new StubMapper(),
457
- externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
458
- initialPushRetryMs: 1,
459
- initialPushTimeoutMs: 2_000,
460
- });
461
- svc.onAddressesChanged(() => { /* registered before start */ });
462
-
463
- await svc.start(); // does not hang retrying a non-transient failure
464
- expect(calls).toBe(1);
465
- });
466
- });
467
-
468
- describe('createNatHandlers', () => {
469
- it('every handler delegates to the service', async () => {
470
- const mapper = new StubMapper();
471
- const svc = new NatService({
472
- rootDir: tmpRoot,
473
- cadreNode: makeNode(),
474
- secretsStore: makeSecrets(),
475
- portMapper: mapper,
476
- externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
477
- });
478
- await svc.start();
479
- const h = createNatHandlers(svc);
480
-
481
- expect((await h.getStatus()).portMode).toBe('auto-upnp');
482
- expect((await h.listDdnsProviders()).find((p) => p.id === 'duckdns')).toBeDefined();
483
-
484
- const status = await h.testReachability();
485
- expect(status.lastTestedAt).not.toBeNull();
486
-
487
- const after = await h.putSettings({ externalPort: 4002 });
488
- expect(after.externalPort).toBe(4002);
489
-
490
- const ddnsStatus = await h.putDdns({
491
- providerId: 'duckdns',
492
- hostname: 'a.duckdns.org',
493
- config: { token: 'T' },
494
- });
495
- expect(ddnsStatus.ddns.hostname).toBe('a.duckdns.org');
496
- });
497
- });
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { NatService, createNatHandlers } from '../nat-service.js';
7
+ import { ExternalIpDetector } from '../external-ip.js';
8
+ import type { PortMapper, PortMappingResult } from '../port-mapper.js';
9
+ import type { SecretsStore } from '../secrets/index.js';
10
+ import { ddnsAccount } from '../secrets/index.js';
11
+ import type { CadreNodeLike } from '../nat-service.js';
12
+ import { OwnerNodeUnavailableError } from '../../owner/owner-node-client.js';
13
+
14
+ class StubMapper implements PortMapper {
15
+ mapCalls = 0;
16
+ unmapCalls = 0;
17
+ stopCalls = 0;
18
+ externalIpValue: string | null = '203.0.113.10';
19
+ mapFails = false;
20
+ async map(o: { externalPort: number; internalPort: number; protocol?: 'tcp' | 'udp'; ttlMs?: number }): Promise<PortMappingResult> {
21
+ this.mapCalls++;
22
+ if (this.mapFails) throw new Error('router refused');
23
+ return {
24
+ mode: 'auto-upnp',
25
+ externalIp: this.externalIpValue,
26
+ externalPort: o.externalPort,
27
+ internalPort: o.internalPort,
28
+ protocol: o.protocol ?? 'tcp',
29
+ leaseExpiresAt: new Date(Date.now() + (o.ttlMs ?? 60_000)),
30
+ };
31
+ }
32
+ async verify() { return true; }
33
+ async externalIp() { return this.externalIpValue; }
34
+ async unmap() { this.unmapCalls++; }
35
+ async stop() { this.stopCalls++; }
36
+ }
37
+
38
+ function makeSecrets(seed: Record<string, string> = {}): SecretsStore {
39
+ const m = new Map(Object.entries(seed));
40
+ return {
41
+ async set(a, v) { m.set(a, v); },
42
+ async get(a) { return m.has(a) ? m.get(a)! : null; },
43
+ async delete(a) { return m.delete(a); },
44
+ async list() { return [...m.keys()]; },
45
+ };
46
+ }
47
+
48
+ function makeNode(peerId = '12D3KooWHost', addrs: string[] = ['/ip4/192.168.1.10/tcp/4001']): CadreNodeLike {
49
+ return {
50
+ getPeerId: () => peerId,
51
+ getMultiaddrs: () => addrs,
52
+ };
53
+ }
54
+
55
+ /**
56
+ * A node that mimics a freshly spawned owner child: `getPeerId` throws
57
+ * `OwnerNodeUnavailableError` for the first `failTimes` calls (admin channel
58
+ * not bound yet), then returns a real peer ID. Exposes the call count so tests
59
+ * can assert how many attempts the retry loop made.
60
+ */
61
+ function makeFlakyNode(
62
+ failTimes: number,
63
+ peerId = '12D3KooWFlaky',
64
+ addrs: string[] = ['/ip4/192.168.1.10/tcp/4001'],
65
+ ): { node: CadreNodeLike; peerIdCalls: () => number } {
66
+ let calls = 0;
67
+ const node: CadreNodeLike = {
68
+ getPeerId: async () => {
69
+ calls += 1;
70
+ if (calls <= failTimes) throw new OwnerNodeUnavailableError('admin channel not bound yet');
71
+ return peerId;
72
+ },
73
+ getMultiaddrs: async () => addrs,
74
+ };
75
+ return { node, peerIdCalls: () => calls };
76
+ }
77
+
78
+ function makeDetector(opts: { router?: string | null; pub?: string | null }): ExternalIpDetector {
79
+ return new ExternalIpDetector({
80
+ routerProbe: opts.router === undefined ? undefined : async () => opts.router ?? null,
81
+ fetch: (async () => ({
82
+ ok: opts.pub != null,
83
+ status: opts.pub != null ? 200 : 500,
84
+ async text() { return opts.pub ?? ''; },
85
+ })) as unknown as typeof fetch,
86
+ publicIpUrls: ['https://stub.test'],
87
+ });
88
+ }
89
+
90
+ /**
91
+ * The provider call a `putDdns` lands on. Injected wherever a case configures a real
92
+ * provider, so no case here reaches www.duckdns.org — an outbound request in a unit
93
+ * test is a hang waiting for a machine without network. DuckDNS's own contract (the
94
+ * plain-text `OK`) is covered in the ddns specs.
95
+ */
96
+ function okFetch(): typeof fetch {
97
+ return (async () => ({
98
+ ok: true,
99
+ status: 200,
100
+ statusText: 'OK',
101
+ async text() { return 'OK'; },
102
+ })) as unknown as typeof fetch;
103
+ }
104
+
105
+ let tmpRoot: string;
106
+ beforeEach(() => {
107
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-nat-svc-'));
108
+ });
109
+ afterEach(() => {
110
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
111
+ });
112
+
113
+ describe('NatService', () => {
114
+ it('start() runs port mapping, detects IP, status reflects auto-upnp', async () => {
115
+ const mapper = new StubMapper();
116
+ const svc = new NatService({
117
+ rootDir: tmpRoot,
118
+ cadreNode: makeNode(),
119
+ secretsStore: makeSecrets(),
120
+ portMapper: mapper,
121
+ externalIpDetector: makeDetector({ router: '203.0.113.10', pub: '203.0.113.10' }),
122
+ });
123
+ await svc.start();
124
+ const s = svc.getStatus();
125
+ expect(s.portMode).toBe('auto-upnp');
126
+ expect(s.externalPort).toBe(4001);
127
+ expect(s.externalIp).toBe('203.0.113.10');
128
+ expect(s.directReachability).toBe('reachable');
129
+ expect(mapper.mapCalls).toBe(1);
130
+ });
131
+
132
+ it('detects CGNAT and flags directReachability=cgnat', async () => {
133
+ const mapper = new StubMapper();
134
+ const svc = new NatService({
135
+ rootDir: tmpRoot,
136
+ cadreNode: makeNode(),
137
+ secretsStore: makeSecrets(),
138
+ portMapper: mapper,
139
+ externalIpDetector: makeDetector({ router: '100.64.0.5', pub: '203.0.113.10' }),
140
+ });
141
+ await svc.start();
142
+ const s = svc.getStatus();
143
+ expect(s.cgnatDetected).toBe(true);
144
+ expect(s.directReachability).toBe('cgnat');
145
+ });
146
+
147
+ it('flips portMode to failed when mapper throws', async () => {
148
+ const mapper = new StubMapper();
149
+ mapper.mapFails = true;
150
+ const svc = new NatService({
151
+ rootDir: tmpRoot,
152
+ cadreNode: makeNode(),
153
+ secretsStore: makeSecrets(),
154
+ portMapper: mapper,
155
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
156
+ });
157
+ await svc.start();
158
+ expect(svc.getStatus().portMode).toBe('failed');
159
+ expect(svc.getStatus().directReachability).toBe('unreachable');
160
+ });
161
+
162
+ it('stop() unmaps and is idempotent', async () => {
163
+ const mapper = new StubMapper();
164
+ const svc = new NatService({
165
+ rootDir: tmpRoot,
166
+ cadreNode: makeNode(),
167
+ secretsStore: makeSecrets(),
168
+ portMapper: mapper,
169
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
170
+ });
171
+ await svc.start();
172
+ await svc.stop();
173
+ await svc.stop();
174
+ expect(mapper.unmapCalls).toBe(1);
175
+ expect(mapper.stopCalls).toBe(1);
176
+ });
177
+
178
+ it('getInviteAddresses → dns4 when DDNS configured + reachable', async () => {
179
+ const mapper = new StubMapper();
180
+ const secrets = makeSecrets({ [ddnsAccount('duckdns', 'token')]: 'T' });
181
+ const svc = new NatService({
182
+ rootDir: tmpRoot,
183
+ cadreNode: makeNode('12D3KooWHost'),
184
+ secretsStore: secrets,
185
+ portMapper: mapper,
186
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
187
+ fetch: okFetch(),
188
+ });
189
+ await svc.start();
190
+ await svc.putDdns({
191
+ providerId: 'duckdns',
192
+ hostname: 'foo.duckdns.org',
193
+ config: { token: 'T' },
194
+ });
195
+ const addrs = await svc.getInviteAddresses();
196
+ expect(addrs).toEqual(['/dns4/foo.duckdns.org/tcp/4001/p2p/12D3KooWHost']);
197
+ });
198
+
199
+ it('getInviteAddresses → ip4 when reachable but no DDNS', async () => {
200
+ const mapper = new StubMapper();
201
+ const svc = new NatService({
202
+ rootDir: tmpRoot,
203
+ cadreNode: makeNode('12D3KooWHost'),
204
+ secretsStore: makeSecrets(),
205
+ portMapper: mapper,
206
+ externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
207
+ });
208
+ await svc.start();
209
+ const addrs = await svc.getInviteAddresses();
210
+ expect(addrs).toEqual(['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWHost']);
211
+ });
212
+
213
+ it('getInviteAddresses → libp2p fallback when unreachable', async () => {
214
+ const mapper = new StubMapper();
215
+ mapper.mapFails = true;
216
+ const svc = new NatService({
217
+ rootDir: tmpRoot,
218
+ cadreNode: makeNode('12D3KooWHost', ['/ip4/10.0.0.5/tcp/4001']),
219
+ secretsStore: makeSecrets(),
220
+ portMapper: mapper,
221
+ externalIpDetector: makeDetector({ pub: null }),
222
+ });
223
+ await svc.start();
224
+ const addrs = await svc.getInviteAddresses();
225
+ expect(addrs).toEqual(['/ip4/10.0.0.5/tcp/4001/p2p/12D3KooWHost']);
226
+ });
227
+
228
+ it('putDdns persists secrets and updates status', async () => {
229
+ const secrets = makeSecrets();
230
+ const mapper = new StubMapper();
231
+ const svc = new NatService({
232
+ rootDir: tmpRoot,
233
+ cadreNode: makeNode(),
234
+ secretsStore: secrets,
235
+ portMapper: mapper,
236
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
237
+ fetch: okFetch(),
238
+ });
239
+ await svc.start();
240
+ const status = await svc.putDdns({
241
+ providerId: 'duckdns',
242
+ hostname: 'h.duckdns.org',
243
+ config: { token: 'TOK' },
244
+ });
245
+ expect(status.ddns.providerId).toBe('duckdns');
246
+ expect(status.ddns.hostname).toBe('h.duckdns.org');
247
+ expect(await secrets.get(ddnsAccount('duckdns', 'token'))).toBe('TOK');
248
+ });
249
+
250
+ it('putDdns with unknown provider → ddns_provider_unknown', async () => {
251
+ const mapper = new StubMapper();
252
+ const svc = new NatService({
253
+ rootDir: tmpRoot,
254
+ cadreNode: makeNode(),
255
+ secretsStore: makeSecrets(),
256
+ portMapper: mapper,
257
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
258
+ });
259
+ await svc.start();
260
+ await expect(svc.putDdns({
261
+ providerId: 'no-such-provider',
262
+ hostname: 'x',
263
+ config: {},
264
+ })).rejects.toMatchObject({ code: 'ddns_provider_unknown' });
265
+ });
266
+
267
+ it('putSettings can disable UPnP and re-enable it', async () => {
268
+ const mapper = new StubMapper();
269
+ const svc = new NatService({
270
+ rootDir: tmpRoot,
271
+ cadreNode: makeNode(),
272
+ secretsStore: makeSecrets(),
273
+ portMapper: mapper,
274
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
275
+ });
276
+ await svc.start();
277
+ expect(mapper.mapCalls).toBe(1);
278
+
279
+ let s = await svc.putSettings({ upnpEnabled: false });
280
+ expect(s.portMode).toBe('disabled');
281
+
282
+ s = await svc.putSettings({ upnpEnabled: true });
283
+ expect(s.portMode).toBe('auto-upnp');
284
+ expect(mapper.mapCalls).toBeGreaterThanOrEqual(2);
285
+ });
286
+
287
+ it('testReachability re-runs IP detect and updates lastTestedAt', async () => {
288
+ const mapper = new StubMapper();
289
+ const svc = new NatService({
290
+ rootDir: tmpRoot,
291
+ cadreNode: makeNode(),
292
+ secretsStore: makeSecrets(),
293
+ portMapper: mapper,
294
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
295
+ });
296
+ await svc.start();
297
+ expect(svc.getStatus().lastTestedAt).toBeNull();
298
+ await svc.testReachability();
299
+ expect(svc.getStatus().lastTestedAt).not.toBeNull();
300
+ });
301
+
302
+ it('listDdnsProviders returns at least DuckDNS', () => {
303
+ const svc = new NatService({
304
+ rootDir: tmpRoot,
305
+ cadreNode: makeNode(),
306
+ secretsStore: makeSecrets(),
307
+ portMapper: new StubMapper(),
308
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
309
+ });
310
+ const providers = svc.listDdnsProviders();
311
+ const duck = providers.find((p) => p.id === 'duckdns');
312
+ expect(duck).toBeDefined();
313
+ expect(duck!.configFields[0]).toMatchObject({ key: 'token', secret: true });
314
+ });
315
+ });
316
+
317
+ describe('NatService — async channel node + onAddressesChanged', () => {
318
+ it('getInviteAddresses awaits async getPeerId/getMultiaddrs from the channel', async () => {
319
+ const asyncNode: CadreNodeLike = {
320
+ getPeerId: async () => '12D3KooWAsync',
321
+ getMultiaddrs: async () => ['/ip4/10.0.0.9/tcp/4001'],
322
+ };
323
+ const svc = new NatService({
324
+ rootDir: tmpRoot,
325
+ cadreNode: asyncNode,
326
+ secretsStore: makeSecrets(),
327
+ portMapper: new StubMapper(),
328
+ externalIpDetector: makeDetector({ pub: '203.0.113.50' }),
329
+ });
330
+ await svc.start();
331
+ const addrs = await svc.getInviteAddresses();
332
+ expect(addrs).toEqual(['/ip4/203.0.113.50/tcp/4001/p2p/12D3KooWAsync']);
333
+ });
334
+
335
+ it('throws node_unavailable when the node reports an empty peer ID (not ready)', async () => {
336
+ const notReadyNode: CadreNodeLike = {
337
+ getPeerId: async () => '',
338
+ getMultiaddrs: async () => [],
339
+ };
340
+ const svc = new NatService({
341
+ rootDir: tmpRoot,
342
+ cadreNode: notReadyNode,
343
+ secretsStore: makeSecrets(),
344
+ portMapper: new StubMapper(),
345
+ externalIpDetector: makeDetector({ pub: '203.0.113.50' }),
346
+ });
347
+ await svc.start();
348
+ await expect(svc.getInviteAddresses()).rejects.toMatchObject({ code: 'node_unavailable' });
349
+ });
350
+
351
+ it('fires onAddressesChanged on putSettings and testReachability', async () => {
352
+ const svc = new NatService({
353
+ rootDir: tmpRoot,
354
+ cadreNode: makeNode('12D3KooWHook'),
355
+ secretsStore: makeSecrets(),
356
+ portMapper: new StubMapper(),
357
+ externalIpDetector: makeDetector({ pub: '203.0.113.7' }),
358
+ });
359
+ await svc.start();
360
+
361
+ const fired: string[][] = [];
362
+ svc.onAddressesChanged((addrs) => { fired.push(addrs); });
363
+
364
+ await svc.putSettings({ externalPort: 4002 });
365
+ await svc.testReachability();
366
+
367
+ expect(fired.length).toBeGreaterThanOrEqual(2);
368
+ // The pushed addresses carry the node's peer ID.
369
+ expect(fired[fired.length - 1]!.every((a: string) => a.includes('12D3KooWHook'))).toBe(true);
370
+ });
371
+
372
+ it('onAddressesChanged unsubscribe stops further notifications', async () => {
373
+ const svc = new NatService({
374
+ rootDir: tmpRoot,
375
+ cadreNode: makeNode(),
376
+ secretsStore: makeSecrets(),
377
+ portMapper: new StubMapper(),
378
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
379
+ });
380
+ await svc.start();
381
+ let count = 0;
382
+ const off = svc.onAddressesChanged(() => { count++; });
383
+ await svc.testReachability();
384
+ off();
385
+ await svc.testReachability();
386
+ expect(count).toBe(1);
387
+ });
388
+ });
389
+
390
+ describe('NatService — initial invite-address push retry', () => {
391
+ it('delivers the initial push exactly once when the node is ready on the first attempt', async () => {
392
+ // The common production happy path: node bound fast, listener registered
393
+ // BEFORE start(). No retry needed — but the push must still fire (once).
394
+ const { node, peerIdCalls } = makeFlakyNode(0, '12D3KooWReady');
395
+ const svc = new NatService({
396
+ rootDir: tmpRoot,
397
+ cadreNode: node,
398
+ secretsStore: makeSecrets(),
399
+ portMapper: new StubMapper(),
400
+ externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
401
+ initialPushRetryMs: 1,
402
+ initialPushTimeoutMs: 2_000,
403
+ });
404
+
405
+ const fired: string[][] = [];
406
+ svc.onAddressesChanged((addrs) => { fired.push(addrs); });
407
+
408
+ await svc.start();
409
+
410
+ expect(fired).toEqual([['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWReady']]);
411
+ expect(peerIdCalls()).toBe(1); // succeeded on the first attempt, no retry
412
+ });
413
+
414
+ it('retries past a not-yet-ready node and delivers the push exactly once', async () => {
415
+ const { node, peerIdCalls } = makeFlakyNode(3, '12D3KooWFlaky');
416
+ const svc = new NatService({
417
+ rootDir: tmpRoot,
418
+ cadreNode: node,
419
+ secretsStore: makeSecrets(),
420
+ portMapper: new StubMapper(),
421
+ externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
422
+ initialPushRetryMs: 1,
423
+ initialPushTimeoutMs: 2_000,
424
+ });
425
+
426
+ // Listener registered BEFORE start() — this is the race the fix closes.
427
+ const fired: string[][] = [];
428
+ svc.onAddressesChanged((addrs) => { fired.push(addrs); });
429
+
430
+ await svc.start();
431
+
432
+ // Delivered exactly once, with the NAT-resolved address carrying the peer ID.
433
+ expect(fired).toEqual([['/ip4/203.0.113.42/tcp/4001/p2p/12D3KooWFlaky']]);
434
+ // It took the failing attempts plus the successful one (proves it retried).
435
+ expect(peerIdCalls()).toBe(4);
436
+ });
437
+
438
+ it('gives up after the bounded timeout but still resolves start() (best-effort)', async () => {
439
+ // Always unavailable — the retry budget elapses without a successful push.
440
+ const node: CadreNodeLike = {
441
+ getPeerId: async () => { throw new OwnerNodeUnavailableError('never ready'); },
442
+ getMultiaddrs: async () => [],
443
+ };
444
+ const svc = new NatService({
445
+ rootDir: tmpRoot,
446
+ cadreNode: node,
447
+ secretsStore: makeSecrets(),
448
+ portMapper: new StubMapper(),
449
+ externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
450
+ initialPushRetryMs: 2,
451
+ initialPushTimeoutMs: 20,
452
+ });
453
+
454
+ const fired: string[][] = [];
455
+ svc.onAddressesChanged((addrs) => { fired.push(addrs); });
456
+
457
+ await svc.start(); // resolves despite the node never coming up
458
+ expect(fired).toEqual([]); // best-effort: nothing delivered
459
+ // The process is otherwise healthy — status still builds.
460
+ expect(svc.getStatus().portMode).toBe('auto-upnp');
461
+ });
462
+
463
+ it('does not retry on a non-node_unavailable error', async () => {
464
+ let calls = 0;
465
+ const node: CadreNodeLike = {
466
+ getPeerId: async () => { calls += 1; throw new Error('boom'); },
467
+ getMultiaddrs: async () => [],
468
+ };
469
+ const svc = new NatService({
470
+ rootDir: tmpRoot,
471
+ cadreNode: node,
472
+ secretsStore: makeSecrets(),
473
+ portMapper: new StubMapper(),
474
+ externalIpDetector: makeDetector({ pub: '203.0.113.42' }),
475
+ initialPushRetryMs: 1,
476
+ initialPushTimeoutMs: 2_000,
477
+ });
478
+ svc.onAddressesChanged(() => { /* registered before start */ });
479
+
480
+ await svc.start(); // does not hang retrying a non-transient failure
481
+ expect(calls).toBe(1);
482
+ });
483
+ });
484
+
485
+ describe('createNatHandlers', () => {
486
+ it('every handler delegates to the service', async () => {
487
+ const mapper = new StubMapper();
488
+ const svc = new NatService({
489
+ rootDir: tmpRoot,
490
+ cadreNode: makeNode(),
491
+ secretsStore: makeSecrets(),
492
+ portMapper: mapper,
493
+ externalIpDetector: makeDetector({ pub: '1.2.3.4' }),
494
+ fetch: okFetch(),
495
+ });
496
+ await svc.start();
497
+ const h = createNatHandlers(svc);
498
+
499
+ expect((await h.getStatus()).portMode).toBe('auto-upnp');
500
+ expect((await h.listDdnsProviders()).find((p) => p.id === 'duckdns')).toBeDefined();
501
+
502
+ const status = await h.testReachability();
503
+ expect(status.lastTestedAt).not.toBeNull();
504
+
505
+ const after = await h.putSettings({ externalPort: 4002 });
506
+ expect(after.externalPort).toBe(4002);
507
+
508
+ const ddnsStatus = await h.putDdns({
509
+ providerId: 'duckdns',
510
+ hostname: 'a.duckdns.org',
511
+ config: { token: 'T' },
512
+ });
513
+ expect(ddnsStatus.ddns.hostname).toBe('a.duckdns.org');
514
+ });
515
+ });