@serfab/cadre-host 0.7.1

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 (300) hide show
  1. package/README.md +101 -0
  2. package/dist/auth/duration.d.ts +1 -0
  3. package/dist/auth/duration.js +32 -0
  4. package/dist/auth/duration.js.map +1 -0
  5. package/dist/auth/index.d.ts +9 -0
  6. package/dist/auth/index.js +8 -0
  7. package/dist/auth/index.js.map +1 -0
  8. package/dist/auth/trust-circle-store.d.ts +26 -0
  9. package/dist/auth/trust-circle-store.js +129 -0
  10. package/dist/auth/trust-circle-store.js.map +1 -0
  11. package/dist/auth/trust-circle.d.ts +91 -0
  12. package/dist/auth/trust-circle.js +230 -0
  13. package/dist/auth/trust-circle.js.map +1 -0
  14. package/dist/auth/types.d.ts +81 -0
  15. package/dist/auth/types.js +24 -0
  16. package/dist/auth/types.js.map +1 -0
  17. package/dist/bin/host.d.ts +13 -0
  18. package/dist/bin/host.js +826 -0
  19. package/dist/bin/host.js.map +1 -0
  20. package/dist/index.d.ts +32 -0
  21. package/dist/index.js +27 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/installer/browser.d.ts +14 -0
  24. package/dist/installer/browser.js +35 -0
  25. package/dist/installer/browser.js.map +1 -0
  26. package/dist/installer/config.d.ts +43 -0
  27. package/dist/installer/config.js +113 -0
  28. package/dist/installer/config.js.map +1 -0
  29. package/dist/installer/identity.d.ts +23 -0
  30. package/dist/installer/identity.js +36 -0
  31. package/dist/installer/identity.js.map +1 -0
  32. package/dist/installer/index.d.ts +83 -0
  33. package/dist/installer/index.js +204 -0
  34. package/dist/installer/index.js.map +1 -0
  35. package/dist/installer/paths.d.ts +33 -0
  36. package/dist/installer/paths.js +84 -0
  37. package/dist/installer/paths.js.map +1 -0
  38. package/dist/installer/platform.d.ts +9 -0
  39. package/dist/installer/platform.js +21 -0
  40. package/dist/installer/platform.js.map +1 -0
  41. package/dist/installer/service-host/index.d.ts +11 -0
  42. package/dist/installer/service-host/index.js +16 -0
  43. package/dist/installer/service-host/index.js.map +1 -0
  44. package/dist/installer/service-host/launchd.d.ts +16 -0
  45. package/dist/installer/service-host/launchd.js +79 -0
  46. package/dist/installer/service-host/launchd.js.map +1 -0
  47. package/dist/installer/service-host/nssm.d.ts +20 -0
  48. package/dist/installer/service-host/nssm.js +88 -0
  49. package/dist/installer/service-host/nssm.js.map +1 -0
  50. package/dist/installer/service-host/systemd.d.ts +16 -0
  51. package/dist/installer/service-host/systemd.js +78 -0
  52. package/dist/installer/service-host/systemd.js.map +1 -0
  53. package/dist/installer/service-host/template.d.ts +6 -0
  54. package/dist/installer/service-host/template.js +20 -0
  55. package/dist/installer/service-host/template.js.map +1 -0
  56. package/dist/installer/service-host/types.d.ts +40 -0
  57. package/dist/installer/service-host/types.js +6 -0
  58. package/dist/installer/service-host/types.js.map +1 -0
  59. package/dist/installer/wizard.d.ts +31 -0
  60. package/dist/installer/wizard.js +67 -0
  61. package/dist/installer/wizard.js.map +1 -0
  62. package/dist/nat/address-resolver.d.ts +22 -0
  63. package/dist/nat/address-resolver.js +31 -0
  64. package/dist/nat/address-resolver.js.map +1 -0
  65. package/dist/nat/ddns/duckdns.d.ts +12 -0
  66. package/dist/nat/ddns/duckdns.js +57 -0
  67. package/dist/nat/ddns/duckdns.js.map +1 -0
  68. package/dist/nat/ddns/index.d.ts +30 -0
  69. package/dist/nat/ddns/index.js +21 -0
  70. package/dist/nat/ddns/index.js.map +1 -0
  71. package/dist/nat/ddns/updater.d.ts +68 -0
  72. package/dist/nat/ddns/updater.js +194 -0
  73. package/dist/nat/ddns/updater.js.map +1 -0
  74. package/dist/nat/external-ip.d.ts +62 -0
  75. package/dist/nat/external-ip.js +114 -0
  76. package/dist/nat/external-ip.js.map +1 -0
  77. package/dist/nat/index.d.ts +22 -0
  78. package/dist/nat/index.js +16 -0
  79. package/dist/nat/index.js.map +1 -0
  80. package/dist/nat/nat-service.d.ts +101 -0
  81. package/dist/nat/nat-service.js +284 -0
  82. package/dist/nat/nat-service.js.map +1 -0
  83. package/dist/nat/nat-store.d.ts +19 -0
  84. package/dist/nat/nat-store.js +136 -0
  85. package/dist/nat/nat-store.js.map +1 -0
  86. package/dist/nat/port-mapper.d.ts +98 -0
  87. package/dist/nat/port-mapper.js +226 -0
  88. package/dist/nat/port-mapper.js.map +1 -0
  89. package/dist/nat/reachability.d.ts +19 -0
  90. package/dist/nat/reachability.js +29 -0
  91. package/dist/nat/reachability.js.map +1 -0
  92. package/dist/nat/secrets/file-store.d.ts +23 -0
  93. package/dist/nat/secrets/file-store.js +102 -0
  94. package/dist/nat/secrets/file-store.js.map +1 -0
  95. package/dist/nat/secrets/index.d.ts +36 -0
  96. package/dist/nat/secrets/index.js +56 -0
  97. package/dist/nat/secrets/index.js.map +1 -0
  98. package/dist/nat/secrets/keytar-store.d.ts +18 -0
  99. package/dist/nat/secrets/keytar-store.js +52 -0
  100. package/dist/nat/secrets/keytar-store.js.map +1 -0
  101. package/dist/nat/types.d.ts +120 -0
  102. package/dist/nat/types.js +24 -0
  103. package/dist/nat/types.js.map +1 -0
  104. package/dist/orchestrator/host-process-orchestrator.d.ts +87 -0
  105. package/dist/orchestrator/host-process-orchestrator.js +557 -0
  106. package/dist/orchestrator/host-process-orchestrator.js.map +1 -0
  107. package/dist/orchestrator/index.d.ts +3 -0
  108. package/dist/orchestrator/index.js +2 -0
  109. package/dist/orchestrator/index.js.map +1 -0
  110. package/dist/orchestrator/log-rotator.d.ts +25 -0
  111. package/dist/orchestrator/log-rotator.js +56 -0
  112. package/dist/orchestrator/log-rotator.js.map +1 -0
  113. package/dist/orchestrator/pid-liveness.d.ts +11 -0
  114. package/dist/orchestrator/pid-liveness.js +26 -0
  115. package/dist/orchestrator/pid-liveness.js.map +1 -0
  116. package/dist/orchestrator/port-allocator.d.ts +16 -0
  117. package/dist/orchestrator/port-allocator.js +38 -0
  118. package/dist/orchestrator/port-allocator.js.map +1 -0
  119. package/dist/orchestrator/state-store.d.ts +32 -0
  120. package/dist/orchestrator/state-store.js +44 -0
  121. package/dist/orchestrator/state-store.js.map +1 -0
  122. package/dist/orchestrator/types.d.ts +85 -0
  123. package/dist/orchestrator/types.js +31 -0
  124. package/dist/orchestrator/types.js.map +1 -0
  125. package/dist/server/error-handler.d.ts +26 -0
  126. package/dist/server/error-handler.js +95 -0
  127. package/dist/server/error-handler.js.map +1 -0
  128. package/dist/server/events/bus.d.ts +17 -0
  129. package/dist/server/events/bus.js +36 -0
  130. package/dist/server/events/bus.js.map +1 -0
  131. package/dist/server/events/sse-route.d.ts +22 -0
  132. package/dist/server/events/sse-route.js +65 -0
  133. package/dist/server/events/sse-route.js.map +1 -0
  134. package/dist/server/events/types.d.ts +25 -0
  135. package/dist/server/events/types.js +8 -0
  136. package/dist/server/events/types.js.map +1 -0
  137. package/dist/server/index.d.ts +67 -0
  138. package/dist/server/index.js +149 -0
  139. package/dist/server/index.js.map +1 -0
  140. package/dist/server/origin-guard.d.ts +24 -0
  141. package/dist/server/origin-guard.js +72 -0
  142. package/dist/server/origin-guard.js.map +1 -0
  143. package/dist/server/routes/nat.d.ts +16 -0
  144. package/dist/server/routes/nat.js +42 -0
  145. package/dist/server/routes/nat.js.map +1 -0
  146. package/dist/server/routes/nodes.d.ts +23 -0
  147. package/dist/server/routes/nodes.js +128 -0
  148. package/dist/server/routes/nodes.js.map +1 -0
  149. package/dist/server/routes/settings.d.ts +26 -0
  150. package/dist/server/routes/settings.js +97 -0
  151. package/dist/server/routes/settings.js.map +1 -0
  152. package/dist/server/routes/status.d.ts +42 -0
  153. package/dist/server/routes/status.js +76 -0
  154. package/dist/server/routes/status.js.map +1 -0
  155. package/dist/server/routes/trust-circle.d.ts +17 -0
  156. package/dist/server/routes/trust-circle.js +35 -0
  157. package/dist/server/routes/trust-circle.js.map +1 -0
  158. package/dist/server/routes/update.d.ts +16 -0
  159. package/dist/server/routes/update.js +29 -0
  160. package/dist/server/routes/update.js.map +1 -0
  161. package/dist/server/server.d.ts +40 -0
  162. package/dist/server/server.js +90 -0
  163. package/dist/server/server.js.map +1 -0
  164. package/dist/server/settings-store.d.ts +24 -0
  165. package/dist/server/settings-store.js +27 -0
  166. package/dist/server/settings-store.js.map +1 -0
  167. package/dist/server/static.d.ts +25 -0
  168. package/dist/server/static.js +177 -0
  169. package/dist/server/static.js.map +1 -0
  170. package/dist/ui/assets/index-BwU5mJGF.css +1 -0
  171. package/dist/ui/assets/index-C9uChk2P.js +14 -0
  172. package/dist/ui/assets/index-C9uChk2P.js.map +1 -0
  173. package/dist/ui/index.html +14 -0
  174. package/dist/update/apply.d.ts +37 -0
  175. package/dist/update/apply.js +102 -0
  176. package/dist/update/apply.js.map +1 -0
  177. package/dist/update/index.d.ts +101 -0
  178. package/dist/update/index.js +228 -0
  179. package/dist/update/index.js.map +1 -0
  180. package/dist/update/manifest.d.ts +48 -0
  181. package/dist/update/manifest.js +152 -0
  182. package/dist/update/manifest.js.map +1 -0
  183. package/dist/update/release-key.d.ts +24 -0
  184. package/dist/update/release-key.js +52 -0
  185. package/dist/update/release-key.js.map +1 -0
  186. package/dist/update/store.d.ts +22 -0
  187. package/dist/update/store.js +81 -0
  188. package/dist/update/store.js.map +1 -0
  189. package/dist/update/types.d.ts +90 -0
  190. package/dist/update/types.js +22 -0
  191. package/dist/update/types.js.map +1 -0
  192. package/dist/update/version.d.ts +18 -0
  193. package/dist/update/version.js +76 -0
  194. package/dist/update/version.js.map +1 -0
  195. package/package.json +80 -0
  196. package/service/README.md +86 -0
  197. package/service/cadre-host.service.tmpl +16 -0
  198. package/service/com.serfab.cadre-host.plist.tmpl +35 -0
  199. package/service/install-service.ps1 +98 -0
  200. package/service/uninstall-service.ps1 +19 -0
  201. package/src/__tests__/cli-invite.smoke.test.ts +187 -0
  202. package/src/__tests__/cli-nat.smoke.test.ts +207 -0
  203. package/src/__tests__/cli.smoke.test.ts +41 -0
  204. package/src/__tests__/orchestrator.test.ts +570 -0
  205. package/src/auth/__tests__/duration.test.ts +28 -0
  206. package/src/auth/__tests__/trust-circle-integration.test.ts +128 -0
  207. package/src/auth/__tests__/trust-circle-store.test.ts +115 -0
  208. package/src/auth/__tests__/trust-circle.test.ts +334 -0
  209. package/src/auth/duration.ts +33 -0
  210. package/src/auth/index.ts +19 -0
  211. package/src/auth/trust-circle-store.ts +155 -0
  212. package/src/auth/trust-circle.ts +304 -0
  213. package/src/auth/types.ts +96 -0
  214. package/src/bin/host.ts +905 -0
  215. package/src/index.ts +167 -0
  216. package/src/installer/__tests__/config.test.ts +86 -0
  217. package/src/installer/__tests__/identity.test.ts +34 -0
  218. package/src/installer/__tests__/installer.smoke.test.ts +124 -0
  219. package/src/installer/__tests__/paths.test.ts +47 -0
  220. package/src/installer/__tests__/service-host.test.ts +62 -0
  221. package/src/installer/__tests__/wizard.test.ts +60 -0
  222. package/src/installer/browser.ts +42 -0
  223. package/src/installer/config.ts +153 -0
  224. package/src/installer/identity.ts +49 -0
  225. package/src/installer/index.ts +303 -0
  226. package/src/installer/paths.ts +109 -0
  227. package/src/installer/platform.ts +27 -0
  228. package/src/installer/service-host/index.ts +21 -0
  229. package/src/installer/service-host/launchd.ts +90 -0
  230. package/src/installer/service-host/nssm.ts +100 -0
  231. package/src/installer/service-host/systemd.ts +88 -0
  232. package/src/installer/service-host/template.ts +21 -0
  233. package/src/installer/service-host/types.ts +48 -0
  234. package/src/installer/wizard.ts +92 -0
  235. package/src/nat/__tests__/address-resolver.test.ts +82 -0
  236. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -0
  237. package/src/nat/__tests__/ddns-updater.test.ts +253 -0
  238. package/src/nat/__tests__/external-ip.test.ts +124 -0
  239. package/src/nat/__tests__/nat-service.test.ts +305 -0
  240. package/src/nat/__tests__/nat-store.test.ts +93 -0
  241. package/src/nat/__tests__/port-mapper.test.ts +191 -0
  242. package/src/nat/__tests__/reachability.test.ts +24 -0
  243. package/src/nat/__tests__/secrets.test.ts +156 -0
  244. package/src/nat/address-resolver.ts +51 -0
  245. package/src/nat/ddns/duckdns.ts +76 -0
  246. package/src/nat/ddns/index.ts +55 -0
  247. package/src/nat/ddns/updater.ts +243 -0
  248. package/src/nat/external-ip.ts +154 -0
  249. package/src/nat/index.ts +71 -0
  250. package/src/nat/nat-service.ts +375 -0
  251. package/src/nat/nat-store.ts +154 -0
  252. package/src/nat/port-mapper.ts +329 -0
  253. package/src/nat/reachability.ts +34 -0
  254. package/src/nat/secrets/file-store.ts +130 -0
  255. package/src/nat/secrets/index.ts +82 -0
  256. package/src/nat/secrets/keytar-store.ts +67 -0
  257. package/src/nat/types.ts +157 -0
  258. package/src/orchestrator/host-process-orchestrator.ts +626 -0
  259. package/src/orchestrator/index.ts +3 -0
  260. package/src/orchestrator/log-rotator.ts +53 -0
  261. package/src/orchestrator/pid-liveness.ts +24 -0
  262. package/src/orchestrator/port-allocator.ts +43 -0
  263. package/src/orchestrator/state-store.ts +72 -0
  264. package/src/orchestrator/types.ts +95 -0
  265. package/src/server/__tests__/bus.test.ts +38 -0
  266. package/src/server/__tests__/error-handler.test.ts +96 -0
  267. package/src/server/__tests__/nodes-route.test.ts +179 -0
  268. package/src/server/__tests__/origin-guard.test.ts +72 -0
  269. package/src/server/__tests__/publishers.test.ts +216 -0
  270. package/src/server/__tests__/server.smoke.test.ts +178 -0
  271. package/src/server/__tests__/settings-route.test.ts +177 -0
  272. package/src/server/__tests__/sse-route.test.ts +119 -0
  273. package/src/server/__tests__/status-route.test.ts +113 -0
  274. package/src/server/error-handler.ts +108 -0
  275. package/src/server/events/bus.ts +42 -0
  276. package/src/server/events/sse-route.ts +81 -0
  277. package/src/server/events/types.ts +22 -0
  278. package/src/server/index.ts +209 -0
  279. package/src/server/origin-guard.ts +84 -0
  280. package/src/server/routes/nat.ts +63 -0
  281. package/src/server/routes/nodes.ts +147 -0
  282. package/src/server/routes/settings.ts +115 -0
  283. package/src/server/routes/status.ts +108 -0
  284. package/src/server/routes/trust-circle.ts +49 -0
  285. package/src/server/routes/update.ts +43 -0
  286. package/src/server/server.ts +122 -0
  287. package/src/server/settings-store.ts +37 -0
  288. package/src/server/static.ts +191 -0
  289. package/src/update/__tests__/apply.test.ts +101 -0
  290. package/src/update/__tests__/manifest.test.ts +93 -0
  291. package/src/update/__tests__/store.test.ts +81 -0
  292. package/src/update/__tests__/update-service.integration.test.ts +221 -0
  293. package/src/update/__tests__/version.test.ts +31 -0
  294. package/src/update/apply.ts +148 -0
  295. package/src/update/index.ts +303 -0
  296. package/src/update/manifest.ts +172 -0
  297. package/src/update/release-key.ts +55 -0
  298. package/src/update/store.ts +101 -0
  299. package/src/update/types.ts +109 -0
  300. package/src/update/version.ts +80 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,34 @@
1
+ import type { DirectReachability, PortForwardMode } from './types.js';
2
+
3
+ export interface ReachabilityInput {
4
+ portMode: PortForwardMode;
5
+ cgnatDetected: boolean;
6
+ }
7
+
8
+ /**
9
+ * v1 reachability heuristic.
10
+ *
11
+ * Returns:
12
+ * - 'cgnat' when CGNAT was detected (highest signal — UPnP succeeded but our
13
+ * external IP isn't actually reachable from the open internet).
14
+ * - 'unreachable' when port mapping failed.
15
+ * - 'reachable' when an auto mapping succeeded.
16
+ * - 'unknown' otherwise (manual config, disabled UPnP, etc).
17
+ *
18
+ * A future ticket will replace this with libp2p AutoNAT or a sereus-owned
19
+ * dial-back probe (see the follow-up section of `6.3-cadre-host-nat`).
20
+ */
21
+ export function evaluateReachability(input: ReachabilityInput): DirectReachability {
22
+ if (input.cgnatDetected) return 'cgnat';
23
+ switch (input.portMode) {
24
+ case 'auto-upnp':
25
+ case 'auto-natpmp':
26
+ return 'reachable';
27
+ case 'failed':
28
+ return 'unreachable';
29
+ case 'manual':
30
+ case 'disabled':
31
+ default:
32
+ return 'unknown';
33
+ }
34
+ }
@@ -0,0 +1,130 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import debug from 'debug';
11
+
12
+ import { NatError } from '../types.js';
13
+ import type { SecretsStore } from './index.js';
14
+
15
+ const log = debug('cadre:host:nat-secrets:file');
16
+
17
+ const FILE_VERSION = 1;
18
+
19
+ interface FileShape {
20
+ version: 1;
21
+ /** Account → secret value. */
22
+ entries: Record<string, string>;
23
+ }
24
+
25
+ /**
26
+ * Filesystem fallback for `SecretsStore`. Writes to `<rootDir>/nat-secrets.json`
27
+ * with mode 0o600.
28
+ *
29
+ * This is NOT a substitute for the OS keychain — the file is plain JSON, only
30
+ * protected by POSIX permissions. We use it only when keytar is unavailable
31
+ * and the caller has been warned (see `createSecretsStore`).
32
+ *
33
+ * Windows: chmod is a no-op (mode bits don't apply), so the file is readable
34
+ * by any user on the same machine. This is documented.
35
+ */
36
+ export class FileSecretsStore implements SecretsStore {
37
+ private readonly path: string;
38
+
39
+ constructor(rootDir: string) {
40
+ mkdirSync(rootDir, { recursive: true });
41
+ this.path = join(rootDir, 'nat-secrets.json');
42
+ }
43
+
44
+ filePath(): string {
45
+ return this.path;
46
+ }
47
+
48
+ async set(account: string, value: string): Promise<void> {
49
+ const data = this.load();
50
+ data.entries[account] = value;
51
+ this.save(data);
52
+ }
53
+
54
+ async get(account: string): Promise<string | null> {
55
+ const data = this.load();
56
+ return Object.prototype.hasOwnProperty.call(data.entries, account)
57
+ ? data.entries[account]!
58
+ : null;
59
+ }
60
+
61
+ async delete(account: string): Promise<boolean> {
62
+ const data = this.load();
63
+ if (!Object.prototype.hasOwnProperty.call(data.entries, account)) return false;
64
+ delete data.entries[account];
65
+ this.save(data);
66
+ return true;
67
+ }
68
+
69
+ async list(): Promise<string[]> {
70
+ return Object.keys(this.load().entries);
71
+ }
72
+
73
+ private load(): FileShape {
74
+ if (!existsSync(this.path)) {
75
+ return { version: FILE_VERSION, entries: {} };
76
+ }
77
+ let raw: string;
78
+ try {
79
+ raw = readFileSync(this.path, 'utf8');
80
+ } catch (err) {
81
+ throw new NatError(
82
+ 'storage_error',
83
+ `failed to read nat-secrets file at ${this.path}: ${(err as Error).message}`,
84
+ );
85
+ }
86
+ let parsed: unknown;
87
+ try {
88
+ parsed = JSON.parse(raw);
89
+ } catch (err) {
90
+ throw new NatError(
91
+ 'storage_error',
92
+ `nat-secrets file at ${this.path} is not valid JSON: ${(err as Error).message}`,
93
+ );
94
+ }
95
+ if (!isFileShape(parsed)) {
96
+ throw new NatError(
97
+ 'storage_error',
98
+ `nat-secrets file at ${this.path} has unexpected shape`,
99
+ );
100
+ }
101
+ return parsed;
102
+ }
103
+
104
+ private save(data: FileShape): void {
105
+ mkdirSync(dirname(this.path), { recursive: true });
106
+ const payload = JSON.stringify({ ...data, version: FILE_VERSION }, null, 2);
107
+ const tmp = `${this.path}.tmp`;
108
+ writeFileSync(tmp, payload, { encoding: 'utf8', mode: 0o600 });
109
+ renameSync(tmp, this.path);
110
+ // chmod again after rename — some platforms reset perms on rename.
111
+ if (process.platform !== 'win32') {
112
+ try {
113
+ chmodSync(this.path, 0o600);
114
+ } catch (err) {
115
+ log('chmod 0600 on %s failed: %s', this.path, (err as Error).message);
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ function isFileShape(v: unknown): v is FileShape {
122
+ if (!v || typeof v !== 'object') return false;
123
+ const obj = v as Record<string, unknown>;
124
+ if (obj.version !== FILE_VERSION) return false;
125
+ if (!obj.entries || typeof obj.entries !== 'object') return false;
126
+ for (const val of Object.values(obj.entries as Record<string, unknown>)) {
127
+ if (typeof val !== 'string') return false;
128
+ }
129
+ return true;
130
+ }
@@ -0,0 +1,82 @@
1
+ import debug from 'debug';
2
+
3
+ import { NatError } from '../types.js';
4
+ import { KeytarSecretsStore } from './keytar-store.js';
5
+ import { FileSecretsStore } from './file-store.js';
6
+
7
+ const log = debug('cadre:host:nat-secrets');
8
+
9
+ /** Service name used as the keytar collection. */
10
+ export const KEYTAR_SERVICE = 'sereus-cadre-host';
11
+
12
+ /**
13
+ * Abstract credential store. Keys are opaque to the store
14
+ * (e.g. "ddns:duckdns:token").
15
+ */
16
+ export interface SecretsStore {
17
+ set(account: string, value: string): Promise<void>;
18
+ get(account: string): Promise<string | null>;
19
+ delete(account: string): Promise<boolean>;
20
+ list(): Promise<string[]>;
21
+ }
22
+
23
+ export { KeytarSecretsStore, FileSecretsStore };
24
+
25
+ /**
26
+ * Try the OS keychain (keytar) first; fall back to a 0600 JSON file in the
27
+ * cadre-host rootDir. The fallback path is documented in `docs/cadre-host.md`.
28
+ *
29
+ * `keytar` is loaded via dynamic import inside a try/catch so a missing native
30
+ * dependency never crashes package import. The same applies to runtime errors
31
+ * (some Linux desktops have keytar installed but no DBus secret service).
32
+ */
33
+ export async function createSecretsStore(rootDir: string): Promise<SecretsStore> {
34
+ // First, try to load keytar.
35
+ let keytarMod: unknown;
36
+ try {
37
+ keytarMod = await import('keytar');
38
+ } catch (err) {
39
+ log('keytar unavailable (%s); using file fallback', (err as Error).message);
40
+ return makeFileFallback(rootDir, `keytar not installed: ${(err as Error).message}`);
41
+ }
42
+
43
+ // Probe with a sentinel write — some installs load but throw at runtime.
44
+ const ks = new KeytarSecretsStore(KEYTAR_SERVICE, keytarMod as KeytarLike);
45
+ const probeAccount = '__cadre_host_probe__';
46
+ try {
47
+ await ks.set(probeAccount, '1');
48
+ await ks.delete(probeAccount);
49
+ log('using keytar for DDNS credentials (service=%s)', KEYTAR_SERVICE);
50
+ return ks;
51
+ } catch (err) {
52
+ log('keytar probe failed (%s); using file fallback', (err as Error).message);
53
+ return makeFileFallback(rootDir, `keytar runtime error: ${(err as Error).message}`);
54
+ }
55
+ }
56
+
57
+ function makeFileFallback(rootDir: string, reason: string): SecretsStore {
58
+ const store = new FileSecretsStore(rootDir);
59
+ // eslint-disable-next-line no-console
60
+ console.warn(
61
+ `[cadre-host] DDNS credentials will be stored UNENCRYPTED at ` +
62
+ `${store.filePath()} (${reason}). Install keytar's native dependencies ` +
63
+ `for OS keychain protection.`,
64
+ );
65
+ return store;
66
+ }
67
+
68
+ /** Subset of keytar's surface that KeytarSecretsStore uses. */
69
+ export interface KeytarLike {
70
+ setPassword(service: string, account: string, password: string): Promise<void>;
71
+ getPassword(service: string, account: string): Promise<string | null>;
72
+ deletePassword(service: string, account: string): Promise<boolean>;
73
+ findCredentials(service: string): Promise<Array<{ account: string; password: string }>>;
74
+ }
75
+
76
+ /** Build the keytar account key for a DDNS credential. */
77
+ export function ddnsAccount(providerId: string, fieldKey: string): string {
78
+ if (!providerId || !fieldKey) {
79
+ throw new NatError('invalid_config', 'providerId and fieldKey are required');
80
+ }
81
+ return `ddns:${providerId}:${fieldKey}`;
82
+ }
@@ -0,0 +1,67 @@
1
+ import debug from 'debug';
2
+
3
+ import { NatError } from '../types.js';
4
+ import type { KeytarLike, SecretsStore } from './index.js';
5
+
6
+ const log = debug('cadre:host:nat-secrets:keytar');
7
+
8
+ /**
9
+ * SecretsStore backed by the OS keychain via the `keytar` npm package.
10
+ *
11
+ * The keytar module is injected (rather than imported here) so:
12
+ * - The native dependency is loaded lazily by `createSecretsStore` and
13
+ * unavailable platforms fall through cleanly to the file store.
14
+ * - Unit tests can stub the entire keytar surface.
15
+ */
16
+ export class KeytarSecretsStore implements SecretsStore {
17
+ constructor(
18
+ private readonly service: string,
19
+ private readonly keytar: KeytarLike,
20
+ ) {}
21
+
22
+ async set(account: string, value: string): Promise<void> {
23
+ try {
24
+ await this.keytar.setPassword(this.service, account, value);
25
+ } catch (err) {
26
+ throw new NatError(
27
+ 'secrets_unavailable',
28
+ `keytar setPassword failed: ${(err as Error).message}`,
29
+ );
30
+ }
31
+ }
32
+
33
+ async get(account: string): Promise<string | null> {
34
+ try {
35
+ return await this.keytar.getPassword(this.service, account);
36
+ } catch (err) {
37
+ throw new NatError(
38
+ 'secrets_unavailable',
39
+ `keytar getPassword failed: ${(err as Error).message}`,
40
+ );
41
+ }
42
+ }
43
+
44
+ async delete(account: string): Promise<boolean> {
45
+ try {
46
+ return await this.keytar.deletePassword(this.service, account);
47
+ } catch (err) {
48
+ throw new NatError(
49
+ 'secrets_unavailable',
50
+ `keytar deletePassword failed: ${(err as Error).message}`,
51
+ );
52
+ }
53
+ }
54
+
55
+ async list(): Promise<string[]> {
56
+ try {
57
+ const creds = await this.keytar.findCredentials(this.service);
58
+ log('keytar findCredentials returned %d entries', creds.length);
59
+ return creds.map((c) => c.account);
60
+ } catch (err) {
61
+ throw new NatError(
62
+ 'secrets_unavailable',
63
+ `keytar findCredentials failed: ${(err as Error).message}`,
64
+ );
65
+ }
66
+ }
67
+ }