@serfab/cadre-host 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/server/static.js +38 -38
  2. package/dist/ui/assets/index-C-iks41M.js.map +1 -1
  3. package/dist/ui/index.html +12 -12
  4. package/package.json +4 -4
  5. package/service/cadre-host.service.tmpl +16 -16
  6. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  7. package/service/install-service.ps1 +98 -98
  8. package/service/uninstall-service.ps1 +19 -19
  9. package/src/__tests__/build-targets.test.ts +26 -26
  10. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  11. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  12. package/src/__tests__/cli.smoke.test.ts +46 -46
  13. package/src/__tests__/global-setup.ts +51 -51
  14. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  15. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -140
  16. package/src/__tests__/orchestrator-node-identity.test.ts +204 -204
  17. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  18. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  19. package/src/__tests__/orchestrator-push.test.ts +145 -145
  20. package/src/__tests__/orchestrator.test.ts +951 -951
  21. package/src/auth/__tests__/duration.test.ts +28 -28
  22. package/src/auth/__tests__/self-label.test.ts +85 -85
  23. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  24. package/src/auth/__tests__/trust-circle.test.ts +445 -445
  25. package/src/auth/duration.ts +33 -33
  26. package/src/auth/index.ts +21 -21
  27. package/src/auth/self-label.ts +74 -74
  28. package/src/auth/trust-circle-store.ts +155 -155
  29. package/src/auth/types.ts +99 -99
  30. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  31. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  32. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  33. package/src/donation/__tests__/fake-orchestrator.ts +225 -225
  34. package/src/donation/__tests__/grant-service.test.ts +213 -213
  35. package/src/donation/__tests__/grant-store.test.ts +113 -113
  36. package/src/donation/donation-service.ts +962 -962
  37. package/src/donation/donation-store.ts +171 -171
  38. package/src/donation/donation-supervisor.ts +388 -388
  39. package/src/donation/grant-service.ts +200 -200
  40. package/src/donation/grant-store.ts +152 -152
  41. package/src/donation/index.ts +64 -64
  42. package/src/donation/types.ts +243 -243
  43. package/src/installer/__tests__/identity.test.ts +34 -34
  44. package/src/installer/__tests__/paths.test.ts +47 -47
  45. package/src/installer/__tests__/service-host.test.ts +62 -62
  46. package/src/installer/__tests__/wizard.test.ts +64 -64
  47. package/src/installer/identity.ts +49 -49
  48. package/src/installer/paths.ts +109 -109
  49. package/src/installer/platform.ts +27 -27
  50. package/src/installer/service-host/index.ts +21 -21
  51. package/src/installer/service-host/template.ts +21 -21
  52. package/src/installer/wizard.ts +103 -103
  53. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  54. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  55. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  56. package/src/nat/__tests__/external-ip.test.ts +124 -124
  57. package/src/nat/__tests__/nat-service.test.ts +497 -497
  58. package/src/nat/__tests__/nat-store.test.ts +93 -93
  59. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  60. package/src/nat/__tests__/reachability.test.ts +24 -24
  61. package/src/nat/__tests__/secrets.test.ts +178 -178
  62. package/src/nat/address-resolver.ts +51 -51
  63. package/src/nat/ddns/duckdns.ts +76 -76
  64. package/src/nat/ddns/index.ts +55 -55
  65. package/src/nat/ddns/updater.ts +243 -243
  66. package/src/nat/external-ip.ts +154 -154
  67. package/src/nat/index.ts +71 -71
  68. package/src/nat/nat-service.ts +501 -501
  69. package/src/nat/nat-store.ts +154 -154
  70. package/src/nat/port-mapper.ts +329 -329
  71. package/src/nat/reachability.ts +34 -34
  72. package/src/nat/secrets/file-store.ts +130 -130
  73. package/src/nat/secrets/index.ts +112 -112
  74. package/src/nat/secrets/keytar-store.ts +67 -67
  75. package/src/nat/types.ts +159 -159
  76. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  77. package/src/orchestrator/host-process-orchestrator.ts +1133 -1133
  78. package/src/orchestrator/index.ts +10 -10
  79. package/src/orchestrator/log-rotator.ts +53 -53
  80. package/src/orchestrator/node-identity.ts +40 -40
  81. package/src/orchestrator/pid-liveness.ts +24 -24
  82. package/src/orchestrator/port-allocator.ts +91 -91
  83. package/src/orchestrator/state-store.ts +90 -90
  84. package/src/orchestrator/types.ts +141 -141
  85. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  86. package/src/owner/index.ts +12 -12
  87. package/src/owner/owner-node-client.ts +259 -259
  88. package/src/push/__tests__/push.test.ts +90 -90
  89. package/src/push/index.ts +146 -146
  90. package/src/server/__tests__/bus.test.ts +38 -38
  91. package/src/server/__tests__/error-handler.test.ts +118 -118
  92. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  93. package/src/server/__tests__/grants-route.test.ts +263 -263
  94. package/src/server/__tests__/nodes-route.test.ts +259 -259
  95. package/src/server/__tests__/origin-guard.test.ts +72 -72
  96. package/src/server/__tests__/publishers.test.ts +216 -216
  97. package/src/server/__tests__/server.smoke.test.ts +253 -253
  98. package/src/server/__tests__/settings-route.test.ts +194 -194
  99. package/src/server/__tests__/sse-route.test.ts +119 -119
  100. package/src/server/__tests__/static.test.ts +145 -145
  101. package/src/server/__tests__/status-route.test.ts +134 -134
  102. package/src/server/__tests__/strands-route.test.ts +233 -233
  103. package/src/server/error-handler.ts +178 -178
  104. package/src/server/events/bus.ts +42 -42
  105. package/src/server/events/sse-route.ts +81 -81
  106. package/src/server/events/types.ts +23 -23
  107. package/src/server/index.ts +267 -267
  108. package/src/server/origin-guard.ts +84 -84
  109. package/src/server/routes/grants-admin.ts +41 -41
  110. package/src/server/routes/grants.ts +210 -210
  111. package/src/server/routes/nat.ts +63 -63
  112. package/src/server/routes/nodes.ts +170 -170
  113. package/src/server/routes/settings.ts +123 -123
  114. package/src/server/routes/status.ts +118 -118
  115. package/src/server/routes/strands.ts +54 -54
  116. package/src/server/routes/trust-circle.ts +49 -49
  117. package/src/server/routes/update.ts +43 -43
  118. package/src/server/server.ts +122 -122
  119. package/src/server/settings-store.ts +37 -37
  120. package/src/server/static.ts +207 -207
  121. package/src/strands/__tests__/strand-service.test.ts +165 -165
  122. package/src/strands/index.ts +14 -14
  123. package/src/strands/strand-service.ts +135 -135
  124. package/src/strands/types.ts +102 -102
  125. package/src/update/__tests__/apply.test.ts +158 -158
  126. package/src/update/__tests__/manifest.test.ts +128 -128
  127. package/src/update/__tests__/release-key.test.ts +42 -42
  128. package/src/update/__tests__/sign.test.ts +78 -78
  129. package/src/update/__tests__/store.test.ts +81 -81
  130. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  131. package/src/update/__tests__/version.test.ts +31 -31
  132. package/src/update/apply.ts +190 -190
  133. package/src/update/index.ts +341 -341
  134. package/src/update/release-key.ts +71 -71
  135. package/src/update/sign.ts +74 -74
  136. package/src/update/store.ts +101 -101
  137. package/src/update/types.ts +109 -109
  138. 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
+ }