@serfab/cadre-host 0.10.0 → 0.12.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 (158) 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 +9 -4
  13. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  14. package/dist/server/settings-store.d.ts +1 -1
  15. package/dist/server/settings-store.js +5 -1
  16. package/dist/server/settings-store.js.map +1 -1
  17. package/dist/server/static.js +38 -38
  18. package/dist/ui/assets/index-C-iks41M.js.map +1 -1
  19. package/dist/ui/index.html +12 -12
  20. package/package.json +4 -4
  21. package/service/cadre-host.service.tmpl +16 -16
  22. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  23. package/service/install-service.ps1 +98 -98
  24. package/service/uninstall-service.ps1 +19 -19
  25. package/src/__tests__/build-targets.test.ts +26 -26
  26. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  27. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  28. package/src/__tests__/cli.smoke.test.ts +51 -46
  29. package/src/__tests__/global-setup.ts +56 -51
  30. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  31. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -140
  32. package/src/__tests__/orchestrator-node-identity.test.ts +5 -5
  33. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  34. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  35. package/src/__tests__/orchestrator-push.test.ts +145 -145
  36. package/src/__tests__/orchestrator.test.ts +951 -951
  37. package/src/auth/__tests__/duration.test.ts +28 -28
  38. package/src/auth/__tests__/self-label.test.ts +85 -85
  39. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  40. package/src/auth/__tests__/trust-circle.test.ts +445 -445
  41. package/src/auth/duration.ts +33 -33
  42. package/src/auth/index.ts +21 -21
  43. package/src/auth/self-label.ts +74 -74
  44. package/src/auth/trust-circle-store.ts +155 -155
  45. package/src/auth/types.ts +99 -99
  46. package/src/bin/__tests__/cli-reference.test.ts +167 -0
  47. package/src/bin/host.ts +1326 -1299
  48. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  49. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  50. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  51. package/src/donation/__tests__/fake-orchestrator.ts +225 -225
  52. package/src/donation/__tests__/grant-service.test.ts +213 -213
  53. package/src/donation/__tests__/grant-store.test.ts +113 -113
  54. package/src/donation/donation-service.ts +962 -962
  55. package/src/donation/donation-store.ts +171 -171
  56. package/src/donation/donation-supervisor.ts +388 -388
  57. package/src/donation/grant-service.ts +200 -200
  58. package/src/donation/grant-store.ts +152 -152
  59. package/src/donation/index.ts +64 -64
  60. package/src/donation/types.ts +243 -243
  61. package/src/installer/__tests__/config.test.ts +134 -112
  62. package/src/installer/__tests__/identity.test.ts +34 -34
  63. package/src/installer/__tests__/paths.test.ts +47 -47
  64. package/src/installer/__tests__/service-host.test.ts +62 -62
  65. package/src/installer/__tests__/wizard.test.ts +64 -64
  66. package/src/installer/config.ts +5 -43
  67. package/src/installer/identity.ts +56 -49
  68. package/src/installer/paths.ts +109 -109
  69. package/src/installer/platform.ts +27 -27
  70. package/src/installer/service-host/index.ts +21 -21
  71. package/src/installer/service-host/template.ts +21 -21
  72. package/src/installer/wizard.ts +103 -103
  73. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  74. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  75. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  76. package/src/nat/__tests__/external-ip.test.ts +124 -124
  77. package/src/nat/__tests__/nat-service.test.ts +18 -0
  78. package/src/nat/__tests__/nat-store.test.ts +93 -93
  79. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  80. package/src/nat/__tests__/reachability.test.ts +24 -24
  81. package/src/nat/__tests__/secrets.test.ts +178 -178
  82. package/src/nat/address-resolver.ts +51 -51
  83. package/src/nat/ddns/duckdns.ts +76 -76
  84. package/src/nat/ddns/index.ts +55 -55
  85. package/src/nat/ddns/updater.ts +243 -243
  86. package/src/nat/external-ip.ts +154 -154
  87. package/src/nat/index.ts +71 -71
  88. package/src/nat/nat-service.ts +501 -501
  89. package/src/nat/nat-store.ts +154 -154
  90. package/src/nat/port-mapper.ts +329 -329
  91. package/src/nat/reachability.ts +34 -34
  92. package/src/nat/secrets/file-store.ts +130 -130
  93. package/src/nat/secrets/index.ts +112 -112
  94. package/src/nat/secrets/keytar-store.ts +67 -67
  95. package/src/nat/types.ts +159 -159
  96. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  97. package/src/orchestrator/host-process-orchestrator.ts +9 -4
  98. package/src/orchestrator/index.ts +10 -10
  99. package/src/orchestrator/log-rotator.ts +53 -53
  100. package/src/orchestrator/node-identity.ts +40 -40
  101. package/src/orchestrator/pid-liveness.ts +24 -24
  102. package/src/orchestrator/port-allocator.ts +91 -91
  103. package/src/orchestrator/state-store.ts +90 -90
  104. package/src/orchestrator/types.ts +141 -141
  105. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  106. package/src/owner/index.ts +12 -12
  107. package/src/owner/owner-node-client.ts +259 -259
  108. package/src/push/__tests__/push.test.ts +90 -90
  109. package/src/push/index.ts +146 -146
  110. package/src/server/__tests__/bus.test.ts +38 -38
  111. package/src/server/__tests__/error-handler.test.ts +118 -118
  112. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  113. package/src/server/__tests__/grants-route.test.ts +263 -263
  114. package/src/server/__tests__/nodes-route.test.ts +259 -259
  115. package/src/server/__tests__/origin-guard.test.ts +72 -72
  116. package/src/server/__tests__/publishers.test.ts +216 -216
  117. package/src/server/__tests__/server.smoke.test.ts +253 -253
  118. package/src/server/__tests__/settings-route.test.ts +195 -194
  119. package/src/server/__tests__/sse-route.test.ts +119 -119
  120. package/src/server/__tests__/static.test.ts +145 -145
  121. package/src/server/__tests__/status-route.test.ts +134 -134
  122. package/src/server/__tests__/strands-route.test.ts +233 -233
  123. package/src/server/error-handler.ts +178 -178
  124. package/src/server/events/bus.ts +42 -42
  125. package/src/server/events/sse-route.ts +81 -81
  126. package/src/server/events/types.ts +23 -23
  127. package/src/server/index.ts +267 -267
  128. package/src/server/origin-guard.ts +84 -84
  129. package/src/server/routes/grants-admin.ts +41 -41
  130. package/src/server/routes/grants.ts +210 -210
  131. package/src/server/routes/nat.ts +63 -63
  132. package/src/server/routes/nodes.ts +170 -170
  133. package/src/server/routes/settings.ts +123 -123
  134. package/src/server/routes/status.ts +118 -118
  135. package/src/server/routes/strands.ts +54 -54
  136. package/src/server/routes/trust-circle.ts +49 -49
  137. package/src/server/routes/update.ts +43 -43
  138. package/src/server/server.ts +122 -122
  139. package/src/server/settings-store.ts +5 -1
  140. package/src/server/static.ts +207 -207
  141. package/src/strands/__tests__/strand-service.test.ts +165 -165
  142. package/src/strands/index.ts +14 -14
  143. package/src/strands/strand-service.ts +135 -135
  144. package/src/strands/types.ts +102 -102
  145. package/src/update/__tests__/apply.test.ts +158 -158
  146. package/src/update/__tests__/manifest.test.ts +128 -128
  147. package/src/update/__tests__/release-key.test.ts +42 -42
  148. package/src/update/__tests__/sign.test.ts +78 -78
  149. package/src/update/__tests__/store.test.ts +81 -81
  150. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  151. package/src/update/__tests__/version.test.ts +31 -31
  152. package/src/update/apply.ts +190 -190
  153. package/src/update/index.ts +341 -341
  154. package/src/update/release-key.ts +71 -71
  155. package/src/update/sign.ts +74 -74
  156. package/src/update/store.ts +101 -101
  157. package/src/update/types.ts +109 -109
  158. package/src/update/version.ts +80 -80
@@ -1,329 +1,329 @@
1
- import debug from 'debug';
2
-
3
- import { NatError, type PortForwardMode } from './types.js';
4
-
5
- const log = debug('cadre:host:nat-port-mapper');
6
-
7
- /** Default lease TTL: 1 hour. The router must keep our mapping at least this long. */
8
- export const DEFAULT_LEASE_TTL_MS = 60 * 60 * 1000;
9
-
10
- /** Default refresh cadence: half the TTL, so two refreshes per lease. */
11
- export const DEFAULT_REFRESH_MS = 30 * 60 * 1000;
12
-
13
- /** Result of a successful map(). */
14
- export interface PortMappingResult {
15
- mode: 'auto-upnp' | 'auto-natpmp';
16
- externalIp: string | null;
17
- externalPort: number;
18
- internalPort: number;
19
- protocol: 'tcp' | 'udp';
20
- leaseExpiresAt: Date;
21
- }
22
-
23
- export interface PortMapOptions {
24
- externalPort: number;
25
- internalPort: number;
26
- protocol?: 'tcp' | 'udp';
27
- /** Lease TTL in milliseconds. Defaults to DEFAULT_LEASE_TTL_MS. */
28
- ttlMs?: number;
29
- }
30
-
31
- /**
32
- * Wrapper around the underlying UPnP/NAT-PMP client. Abstract so tests can
33
- * stub the network behavior without spinning up a real router.
34
- */
35
- export interface PortMapper {
36
- /** Attempt to install a port mapping. Throws NatError(mapping_failed) on failure. */
37
- map(opts: PortMapOptions): Promise<PortMappingResult>;
38
- /** Re-query the router; returns true if the mapping is still present. */
39
- verify(externalPort: number, protocol?: 'tcp' | 'udp'): Promise<boolean>;
40
- /** Query the router's WAN/external IP, if exposed. */
41
- externalIp(): Promise<string | null>;
42
- /** Remove a mapping installed by this mapper. */
43
- unmap(externalPort: number, protocol?: 'tcp' | 'udp'): Promise<void>;
44
- /** Release client resources (timers, sockets). Idempotent. */
45
- stop(): Promise<void>;
46
- }
47
-
48
- /** Constructor for the default mapper. Loads `@achingbrain/nat-port-mapper` dynamically. */
49
- export type PortMapperFactory = () => Promise<PortMapper>;
50
-
51
- interface NatPortMapperClient {
52
- externalIp(): Promise<string>;
53
- map(opts: Record<string, unknown>): Promise<unknown>;
54
- unmap(opts: Record<string, unknown>): Promise<void>;
55
- stop(): Promise<void>;
56
- }
57
-
58
- interface NatPortMapperModule {
59
- upnpNat(opts?: Record<string, unknown>): Promise<NatPortMapperClient>;
60
- }
61
-
62
- /**
63
- * Default factory: loads @achingbrain/nat-port-mapper. Wrapped in dynamic
64
- * import so a missing dep at install time doesn't crash the package.
65
- */
66
- export async function createDefaultPortMapper(opts: {
67
- description?: string;
68
- ttlMs?: number;
69
- } = {}): Promise<PortMapper> {
70
- let mod: NatPortMapperModule;
71
- try {
72
- mod = (await import('@achingbrain/nat-port-mapper' as string)) as NatPortMapperModule;
73
- } catch (err) {
74
- throw new NatError(
75
- 'mapping_failed',
76
- `@achingbrain/nat-port-mapper is not installed: ${(err as Error).message}`,
77
- );
78
- }
79
-
80
- let client: NatPortMapperClient;
81
- try {
82
- client = await mod.upnpNat({
83
- description: opts.description ?? 'sereus-cadre-host',
84
- ttl: Math.round((opts.ttlMs ?? DEFAULT_LEASE_TTL_MS) / 1000),
85
- });
86
- } catch (err) {
87
- throw new NatError(
88
- 'mapping_failed',
89
- `upnpNat() failed: ${(err as Error).message}`,
90
- );
91
- }
92
-
93
- return new NatPortMapperAdapter(client, opts.ttlMs ?? DEFAULT_LEASE_TTL_MS);
94
- }
95
-
96
- class NatPortMapperAdapter implements PortMapper {
97
- constructor(
98
- private readonly client: NatPortMapperClient,
99
- private readonly defaultTtlMs: number,
100
- ) {}
101
-
102
- async map(opts: PortMapOptions): Promise<PortMappingResult> {
103
- const ttlMs = opts.ttlMs ?? this.defaultTtlMs;
104
- const protocol = opts.protocol ?? 'tcp';
105
- let externalIp: string | null = null;
106
- try {
107
- externalIp = await this.client.externalIp();
108
- } catch (err) {
109
- log('externalIp() failed: %s', (err as Error).message);
110
- }
111
- try {
112
- await this.client.map({
113
- localPort: opts.internalPort,
114
- externalPort: opts.externalPort,
115
- protocol,
116
- ttl: Math.round(ttlMs / 1000),
117
- });
118
- } catch (err) {
119
- throw new NatError(
120
- 'mapping_failed',
121
- `router refused mapping for port ${opts.externalPort}: ${(err as Error).message}`,
122
- );
123
- }
124
- return {
125
- mode: 'auto-upnp',
126
- externalIp,
127
- externalPort: opts.externalPort,
128
- internalPort: opts.internalPort,
129
- protocol,
130
- leaseExpiresAt: new Date(Date.now() + ttlMs),
131
- };
132
- }
133
-
134
- async verify(externalPort: number, protocol: 'tcp' | 'udp' = 'tcp'): Promise<boolean> {
135
- void externalPort;
136
- void protocol;
137
- // The current library doesn't expose an introspection API. Treat a
138
- // working externalIp() as a proxy for "router still reachable" — refresh
139
- // failures will surface via re-running map().
140
- try {
141
- await this.client.externalIp();
142
- return true;
143
- } catch (err) {
144
- log('verify() failed: %s', (err as Error).message);
145
- return false;
146
- }
147
- }
148
-
149
- async externalIp(): Promise<string | null> {
150
- try {
151
- return await this.client.externalIp();
152
- } catch (err) {
153
- log('externalIp() failed: %s', (err as Error).message);
154
- return null;
155
- }
156
- }
157
-
158
- async unmap(externalPort: number, protocol: 'tcp' | 'udp' = 'tcp'): Promise<void> {
159
- try {
160
- await this.client.unmap({ externalPort, protocol });
161
- } catch (err) {
162
- log('unmap(%d) failed: %s', externalPort, (err as Error).message);
163
- }
164
- }
165
-
166
- async stop(): Promise<void> {
167
- try {
168
- await this.client.stop();
169
- } catch (err) {
170
- log('stop() failed: %s', (err as Error).message);
171
- }
172
- }
173
- }
174
-
175
- /** Public-facing port-mapper service: wraps a PortMapper with refresh + state. */
176
- export interface PortMapperServiceOptions {
177
- mapper: PortMapper;
178
- externalPort: number;
179
- internalPort: number;
180
- protocol?: 'tcp' | 'udp';
181
- ttlMs?: number;
182
- refreshMs?: number;
183
- /** Clock override for tests. */
184
- now?: () => Date;
185
- /** Timer overrides for tests (must return a handle usable by `clear`). */
186
- setTimer?: (fn: () => void, ms: number) => NodeJS.Timeout;
187
- clearTimer?: (h: NodeJS.Timeout) => void;
188
- }
189
-
190
- /** State snapshot returned by `PortMapperService.getStatus()`. */
191
- export interface PortMapperState {
192
- mode: PortForwardMode;
193
- externalPort: number;
194
- internalPort: number;
195
- routerExternalIp: string | null;
196
- leaseExpiresAt: Date | null;
197
- lastError: string | null;
198
- }
199
-
200
- /**
201
- * Long-running orchestrator over a PortMapper. Owns the refresh timer and
202
- * surfaces the latest state for the NatService snapshot.
203
- */
204
- export class PortMapperService {
205
- private readonly mapper: PortMapper;
206
- private readonly externalPort: number;
207
- private readonly internalPort: number;
208
- private readonly protocol: 'tcp' | 'udp';
209
- private readonly ttlMs: number;
210
- private readonly refreshMs: number;
211
- private readonly nowFn: () => Date;
212
- private readonly setTimer: (fn: () => void, ms: number) => NodeJS.Timeout;
213
- private readonly clearTimer: (h: NodeJS.Timeout) => void;
214
-
215
- private state: PortMapperState;
216
- private refreshHandle: NodeJS.Timeout | null = null;
217
- private started = false;
218
-
219
- constructor(opts: PortMapperServiceOptions) {
220
- this.mapper = opts.mapper;
221
- this.externalPort = opts.externalPort;
222
- this.internalPort = opts.internalPort;
223
- this.protocol = opts.protocol ?? 'tcp';
224
- this.ttlMs = opts.ttlMs ?? DEFAULT_LEASE_TTL_MS;
225
- this.refreshMs = opts.refreshMs ?? DEFAULT_REFRESH_MS;
226
- this.nowFn = opts.now ?? (() => new Date());
227
- this.setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
228
- this.clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h));
229
-
230
- this.state = {
231
- mode: 'disabled',
232
- externalPort: this.externalPort,
233
- internalPort: this.internalPort,
234
- routerExternalIp: null,
235
- leaseExpiresAt: null,
236
- lastError: null,
237
- };
238
- }
239
-
240
- getState(): PortMapperState {
241
- return { ...this.state };
242
- }
243
-
244
- /** Install the mapping and schedule periodic refresh. */
245
- async start(): Promise<void> {
246
- if (this.started) return;
247
- this.started = true;
248
- await this.installMapping();
249
- this.scheduleRefresh();
250
- }
251
-
252
- /** Release the mapping and clear timers. Idempotent. */
253
- async stop(): Promise<void> {
254
- if (!this.started) return;
255
- this.started = false;
256
- if (this.refreshHandle) {
257
- this.clearTimer(this.refreshHandle);
258
- this.refreshHandle = null;
259
- }
260
- try {
261
- await this.mapper.unmap(this.externalPort, this.protocol);
262
- } catch (err) {
263
- log('unmap during stop failed: %s', (err as Error).message);
264
- }
265
- try {
266
- await this.mapper.stop();
267
- } catch (err) {
268
- log('mapper.stop() failed: %s', (err as Error).message);
269
- }
270
- this.state = {
271
- ...this.state,
272
- mode: 'disabled',
273
- routerExternalIp: null,
274
- leaseExpiresAt: null,
275
- };
276
- }
277
-
278
- /** Force an immediate verify+refresh cycle (used by testReachability). */
279
- async refresh(): Promise<PortMapperState> {
280
- if (!this.started) return this.getState();
281
- const ok = await this.mapper.verify(this.externalPort, this.protocol).catch(() => false);
282
- if (!ok) {
283
- log('verify() returned false; re-mapping');
284
- await this.installMapping();
285
- return this.getState();
286
- }
287
- // Refresh: re-issue the mapping to extend the lease.
288
- await this.installMapping();
289
- return this.getState();
290
- }
291
-
292
- private scheduleRefresh(): void {
293
- if (this.refreshHandle) this.clearTimer(this.refreshHandle);
294
- this.refreshHandle = this.setTimer(() => {
295
- void this.refresh().catch((err) => log('refresh timer error: %s', (err as Error).message));
296
- // Re-arm after the call to avoid drift.
297
- this.scheduleRefresh();
298
- }, this.refreshMs);
299
- }
300
-
301
- private async installMapping(): Promise<void> {
302
- try {
303
- const r = await this.mapper.map({
304
- externalPort: this.externalPort,
305
- internalPort: this.internalPort,
306
- protocol: this.protocol,
307
- ttlMs: this.ttlMs,
308
- });
309
- this.state = {
310
- mode: r.mode,
311
- externalPort: r.externalPort,
312
- internalPort: r.internalPort,
313
- routerExternalIp: r.externalIp,
314
- leaseExpiresAt: r.leaseExpiresAt,
315
- lastError: null,
316
- };
317
- log('mapped port %d (mode=%s, externalIp=%s)', r.externalPort, r.mode, r.externalIp ?? '?');
318
- } catch (err) {
319
- const message = (err as Error).message;
320
- this.state = {
321
- ...this.state,
322
- mode: 'failed',
323
- leaseExpiresAt: null,
324
- lastError: message,
325
- };
326
- log('mapping failed: %s', message);
327
- }
328
- }
329
- }
1
+ import debug from 'debug';
2
+
3
+ import { NatError, type PortForwardMode } from './types.js';
4
+
5
+ const log = debug('cadre:host:nat-port-mapper');
6
+
7
+ /** Default lease TTL: 1 hour. The router must keep our mapping at least this long. */
8
+ export const DEFAULT_LEASE_TTL_MS = 60 * 60 * 1000;
9
+
10
+ /** Default refresh cadence: half the TTL, so two refreshes per lease. */
11
+ export const DEFAULT_REFRESH_MS = 30 * 60 * 1000;
12
+
13
+ /** Result of a successful map(). */
14
+ export interface PortMappingResult {
15
+ mode: 'auto-upnp' | 'auto-natpmp';
16
+ externalIp: string | null;
17
+ externalPort: number;
18
+ internalPort: number;
19
+ protocol: 'tcp' | 'udp';
20
+ leaseExpiresAt: Date;
21
+ }
22
+
23
+ export interface PortMapOptions {
24
+ externalPort: number;
25
+ internalPort: number;
26
+ protocol?: 'tcp' | 'udp';
27
+ /** Lease TTL in milliseconds. Defaults to DEFAULT_LEASE_TTL_MS. */
28
+ ttlMs?: number;
29
+ }
30
+
31
+ /**
32
+ * Wrapper around the underlying UPnP/NAT-PMP client. Abstract so tests can
33
+ * stub the network behavior without spinning up a real router.
34
+ */
35
+ export interface PortMapper {
36
+ /** Attempt to install a port mapping. Throws NatError(mapping_failed) on failure. */
37
+ map(opts: PortMapOptions): Promise<PortMappingResult>;
38
+ /** Re-query the router; returns true if the mapping is still present. */
39
+ verify(externalPort: number, protocol?: 'tcp' | 'udp'): Promise<boolean>;
40
+ /** Query the router's WAN/external IP, if exposed. */
41
+ externalIp(): Promise<string | null>;
42
+ /** Remove a mapping installed by this mapper. */
43
+ unmap(externalPort: number, protocol?: 'tcp' | 'udp'): Promise<void>;
44
+ /** Release client resources (timers, sockets). Idempotent. */
45
+ stop(): Promise<void>;
46
+ }
47
+
48
+ /** Constructor for the default mapper. Loads `@achingbrain/nat-port-mapper` dynamically. */
49
+ export type PortMapperFactory = () => Promise<PortMapper>;
50
+
51
+ interface NatPortMapperClient {
52
+ externalIp(): Promise<string>;
53
+ map(opts: Record<string, unknown>): Promise<unknown>;
54
+ unmap(opts: Record<string, unknown>): Promise<void>;
55
+ stop(): Promise<void>;
56
+ }
57
+
58
+ interface NatPortMapperModule {
59
+ upnpNat(opts?: Record<string, unknown>): Promise<NatPortMapperClient>;
60
+ }
61
+
62
+ /**
63
+ * Default factory: loads @achingbrain/nat-port-mapper. Wrapped in dynamic
64
+ * import so a missing dep at install time doesn't crash the package.
65
+ */
66
+ export async function createDefaultPortMapper(opts: {
67
+ description?: string;
68
+ ttlMs?: number;
69
+ } = {}): Promise<PortMapper> {
70
+ let mod: NatPortMapperModule;
71
+ try {
72
+ mod = (await import('@achingbrain/nat-port-mapper' as string)) as NatPortMapperModule;
73
+ } catch (err) {
74
+ throw new NatError(
75
+ 'mapping_failed',
76
+ `@achingbrain/nat-port-mapper is not installed: ${(err as Error).message}`,
77
+ );
78
+ }
79
+
80
+ let client: NatPortMapperClient;
81
+ try {
82
+ client = await mod.upnpNat({
83
+ description: opts.description ?? 'sereus-cadre-host',
84
+ ttl: Math.round((opts.ttlMs ?? DEFAULT_LEASE_TTL_MS) / 1000),
85
+ });
86
+ } catch (err) {
87
+ throw new NatError(
88
+ 'mapping_failed',
89
+ `upnpNat() failed: ${(err as Error).message}`,
90
+ );
91
+ }
92
+
93
+ return new NatPortMapperAdapter(client, opts.ttlMs ?? DEFAULT_LEASE_TTL_MS);
94
+ }
95
+
96
+ class NatPortMapperAdapter implements PortMapper {
97
+ constructor(
98
+ private readonly client: NatPortMapperClient,
99
+ private readonly defaultTtlMs: number,
100
+ ) {}
101
+
102
+ async map(opts: PortMapOptions): Promise<PortMappingResult> {
103
+ const ttlMs = opts.ttlMs ?? this.defaultTtlMs;
104
+ const protocol = opts.protocol ?? 'tcp';
105
+ let externalIp: string | null = null;
106
+ try {
107
+ externalIp = await this.client.externalIp();
108
+ } catch (err) {
109
+ log('externalIp() failed: %s', (err as Error).message);
110
+ }
111
+ try {
112
+ await this.client.map({
113
+ localPort: opts.internalPort,
114
+ externalPort: opts.externalPort,
115
+ protocol,
116
+ ttl: Math.round(ttlMs / 1000),
117
+ });
118
+ } catch (err) {
119
+ throw new NatError(
120
+ 'mapping_failed',
121
+ `router refused mapping for port ${opts.externalPort}: ${(err as Error).message}`,
122
+ );
123
+ }
124
+ return {
125
+ mode: 'auto-upnp',
126
+ externalIp,
127
+ externalPort: opts.externalPort,
128
+ internalPort: opts.internalPort,
129
+ protocol,
130
+ leaseExpiresAt: new Date(Date.now() + ttlMs),
131
+ };
132
+ }
133
+
134
+ async verify(externalPort: number, protocol: 'tcp' | 'udp' = 'tcp'): Promise<boolean> {
135
+ void externalPort;
136
+ void protocol;
137
+ // The current library doesn't expose an introspection API. Treat a
138
+ // working externalIp() as a proxy for "router still reachable" — refresh
139
+ // failures will surface via re-running map().
140
+ try {
141
+ await this.client.externalIp();
142
+ return true;
143
+ } catch (err) {
144
+ log('verify() failed: %s', (err as Error).message);
145
+ return false;
146
+ }
147
+ }
148
+
149
+ async externalIp(): Promise<string | null> {
150
+ try {
151
+ return await this.client.externalIp();
152
+ } catch (err) {
153
+ log('externalIp() failed: %s', (err as Error).message);
154
+ return null;
155
+ }
156
+ }
157
+
158
+ async unmap(externalPort: number, protocol: 'tcp' | 'udp' = 'tcp'): Promise<void> {
159
+ try {
160
+ await this.client.unmap({ externalPort, protocol });
161
+ } catch (err) {
162
+ log('unmap(%d) failed: %s', externalPort, (err as Error).message);
163
+ }
164
+ }
165
+
166
+ async stop(): Promise<void> {
167
+ try {
168
+ await this.client.stop();
169
+ } catch (err) {
170
+ log('stop() failed: %s', (err as Error).message);
171
+ }
172
+ }
173
+ }
174
+
175
+ /** Public-facing port-mapper service: wraps a PortMapper with refresh + state. */
176
+ export interface PortMapperServiceOptions {
177
+ mapper: PortMapper;
178
+ externalPort: number;
179
+ internalPort: number;
180
+ protocol?: 'tcp' | 'udp';
181
+ ttlMs?: number;
182
+ refreshMs?: number;
183
+ /** Clock override for tests. */
184
+ now?: () => Date;
185
+ /** Timer overrides for tests (must return a handle usable by `clear`). */
186
+ setTimer?: (fn: () => void, ms: number) => NodeJS.Timeout;
187
+ clearTimer?: (h: NodeJS.Timeout) => void;
188
+ }
189
+
190
+ /** State snapshot returned by `PortMapperService.getStatus()`. */
191
+ export interface PortMapperState {
192
+ mode: PortForwardMode;
193
+ externalPort: number;
194
+ internalPort: number;
195
+ routerExternalIp: string | null;
196
+ leaseExpiresAt: Date | null;
197
+ lastError: string | null;
198
+ }
199
+
200
+ /**
201
+ * Long-running orchestrator over a PortMapper. Owns the refresh timer and
202
+ * surfaces the latest state for the NatService snapshot.
203
+ */
204
+ export class PortMapperService {
205
+ private readonly mapper: PortMapper;
206
+ private readonly externalPort: number;
207
+ private readonly internalPort: number;
208
+ private readonly protocol: 'tcp' | 'udp';
209
+ private readonly ttlMs: number;
210
+ private readonly refreshMs: number;
211
+ private readonly nowFn: () => Date;
212
+ private readonly setTimer: (fn: () => void, ms: number) => NodeJS.Timeout;
213
+ private readonly clearTimer: (h: NodeJS.Timeout) => void;
214
+
215
+ private state: PortMapperState;
216
+ private refreshHandle: NodeJS.Timeout | null = null;
217
+ private started = false;
218
+
219
+ constructor(opts: PortMapperServiceOptions) {
220
+ this.mapper = opts.mapper;
221
+ this.externalPort = opts.externalPort;
222
+ this.internalPort = opts.internalPort;
223
+ this.protocol = opts.protocol ?? 'tcp';
224
+ this.ttlMs = opts.ttlMs ?? DEFAULT_LEASE_TTL_MS;
225
+ this.refreshMs = opts.refreshMs ?? DEFAULT_REFRESH_MS;
226
+ this.nowFn = opts.now ?? (() => new Date());
227
+ this.setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
228
+ this.clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h));
229
+
230
+ this.state = {
231
+ mode: 'disabled',
232
+ externalPort: this.externalPort,
233
+ internalPort: this.internalPort,
234
+ routerExternalIp: null,
235
+ leaseExpiresAt: null,
236
+ lastError: null,
237
+ };
238
+ }
239
+
240
+ getState(): PortMapperState {
241
+ return { ...this.state };
242
+ }
243
+
244
+ /** Install the mapping and schedule periodic refresh. */
245
+ async start(): Promise<void> {
246
+ if (this.started) return;
247
+ this.started = true;
248
+ await this.installMapping();
249
+ this.scheduleRefresh();
250
+ }
251
+
252
+ /** Release the mapping and clear timers. Idempotent. */
253
+ async stop(): Promise<void> {
254
+ if (!this.started) return;
255
+ this.started = false;
256
+ if (this.refreshHandle) {
257
+ this.clearTimer(this.refreshHandle);
258
+ this.refreshHandle = null;
259
+ }
260
+ try {
261
+ await this.mapper.unmap(this.externalPort, this.protocol);
262
+ } catch (err) {
263
+ log('unmap during stop failed: %s', (err as Error).message);
264
+ }
265
+ try {
266
+ await this.mapper.stop();
267
+ } catch (err) {
268
+ log('mapper.stop() failed: %s', (err as Error).message);
269
+ }
270
+ this.state = {
271
+ ...this.state,
272
+ mode: 'disabled',
273
+ routerExternalIp: null,
274
+ leaseExpiresAt: null,
275
+ };
276
+ }
277
+
278
+ /** Force an immediate verify+refresh cycle (used by testReachability). */
279
+ async refresh(): Promise<PortMapperState> {
280
+ if (!this.started) return this.getState();
281
+ const ok = await this.mapper.verify(this.externalPort, this.protocol).catch(() => false);
282
+ if (!ok) {
283
+ log('verify() returned false; re-mapping');
284
+ await this.installMapping();
285
+ return this.getState();
286
+ }
287
+ // Refresh: re-issue the mapping to extend the lease.
288
+ await this.installMapping();
289
+ return this.getState();
290
+ }
291
+
292
+ private scheduleRefresh(): void {
293
+ if (this.refreshHandle) this.clearTimer(this.refreshHandle);
294
+ this.refreshHandle = this.setTimer(() => {
295
+ void this.refresh().catch((err) => log('refresh timer error: %s', (err as Error).message));
296
+ // Re-arm after the call to avoid drift.
297
+ this.scheduleRefresh();
298
+ }, this.refreshMs);
299
+ }
300
+
301
+ private async installMapping(): Promise<void> {
302
+ try {
303
+ const r = await this.mapper.map({
304
+ externalPort: this.externalPort,
305
+ internalPort: this.internalPort,
306
+ protocol: this.protocol,
307
+ ttlMs: this.ttlMs,
308
+ });
309
+ this.state = {
310
+ mode: r.mode,
311
+ externalPort: r.externalPort,
312
+ internalPort: r.internalPort,
313
+ routerExternalIp: r.externalIp,
314
+ leaseExpiresAt: r.leaseExpiresAt,
315
+ lastError: null,
316
+ };
317
+ log('mapped port %d (mode=%s, externalIp=%s)', r.externalPort, r.mode, r.externalIp ?? '?');
318
+ } catch (err) {
319
+ const message = (err as Error).message;
320
+ this.state = {
321
+ ...this.state,
322
+ mode: 'failed',
323
+ leaseExpiresAt: null,
324
+ lastError: message,
325
+ };
326
+ log('mapping failed: %s', message);
327
+ }
328
+ }
329
+ }