@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

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 (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The host's per-model reasoning-effort preferences:
3
+ * `$DSH_HOME/remote-bridge/model-efforts.json`.
4
+ *
5
+ * A preference belongs to a MODEL, not to a session or a device: the phone picks
6
+ * a level for one model once, and every session on this host that later selects
7
+ * that model is handed the same level. The table therefore has exactly one scope
8
+ * — the whole host — and nothing expires an entry when a session ends.
9
+ *
10
+ * It is deliberately not the catalog's `reasoning.defaultEffort`: that is what
11
+ * the harness publishes for a model, this is what the user chose here, and the
12
+ * two disagree the moment somebody picks a level the catalog does not call the
13
+ * default. The wire keeps them apart too (`session.models` rows carry this one
14
+ * as `preferredEffort`, beside the catalog's own `reasoning`).
15
+ * @module dsh-remote-bridge/core/model-efforts
16
+ */
17
+
18
+ import { chmod, mkdir, open, readFile, rename } from 'node:fs/promises'
19
+ import { dirname } from 'node:path'
20
+
21
+ /** The schema version this build writes; an older file is read as the table it is. */
22
+ export const EFFORT_TABLE_VERSION = 1
23
+
24
+ /** One remembered choice: the model it belongs to and the level it was given. */
25
+ export interface EffortPreference {
26
+ readonly provider: string
27
+ readonly model: string
28
+ readonly effort: string
29
+ }
30
+
31
+ export interface ModelEffortPreferencesOptions {
32
+ /** Absolute path of the preference file. */
33
+ readonly file: string
34
+ readonly log?: (message: string) => void
35
+ }
36
+
37
+ /**
38
+ * The key one model is remembered under: a provider id and a model id, which are
39
+ * only unique together.
40
+ * @param provider - provider id, as the catalog's group id spells it.
41
+ * @param model - model id, as the catalog's row id spells it.
42
+ * @returns the table key of that pair.
43
+ */
44
+ function keyOf(provider: string, model: string): string {
45
+ return `${provider}\u0000${model}`
46
+ }
47
+
48
+ /** @returns whether a row read from the file is a preference this build can use. */
49
+ function isPreference(value: unknown): value is EffortPreference {
50
+ if (typeof value !== 'object' || value === null) return false
51
+ const row = value as Record<string, unknown>
52
+ return typeof row.provider === 'string' && row.provider !== ''
53
+ && typeof row.model === 'string' && row.model !== ''
54
+ && typeof row.effort === 'string' && row.effort !== ''
55
+ }
56
+
57
+ /**
58
+ * The persisted effort table, shared by every connection of one host.
59
+ *
60
+ * Read once per process and written atomically: a corrupt file is an EMPTY table
61
+ * with one log line, never a failed mount — a phone must still be able to read
62
+ * the catalog and pick a model on a host whose preference file went bad, and the
63
+ * next write replaces the file rather than writing into the damage.
64
+ */
65
+ export class ModelEffortPreferences {
66
+ readonly #file: string
67
+ readonly #log: (message: string) => void
68
+ readonly #rows = new Map<string, EffortPreference>()
69
+ #loaded: Promise<void> | undefined
70
+ #writeQueue: Promise<void> = Promise.resolve()
71
+
72
+ constructor(options: ModelEffortPreferencesOptions) {
73
+ this.#file = options.file
74
+ this.#log = options.log ?? (() => undefined)
75
+ }
76
+
77
+ /**
78
+ * Read the table once. A missing file is an empty table, and an unreadable or
79
+ * malformed one is reported and then read as empty.
80
+ * @returns when the in-memory table reflects the file.
81
+ */
82
+ load(): Promise<void> {
83
+ this.#loaded ??= this.#read()
84
+ return this.#loaded
85
+ }
86
+
87
+ /**
88
+ * @param provider - provider id.
89
+ * @param model - model id.
90
+ * @returns the level remembered for that model, or undefined when the table has none.
91
+ */
92
+ effortOf(provider: string, model: string): string | undefined {
93
+ return this.#rows.get(keyOf(provider, model))?.effort
94
+ }
95
+
96
+ /**
97
+ * Remember one level and persist it before answering.
98
+ *
99
+ * The write is what the caller is told succeeded, so the memory copy is set
100
+ * first only for the duration of it: a failed write rejects, and the answer
101
+ * the client sees is the failure rather than a level this host never stored.
102
+ * @param provider - provider id.
103
+ * @param model - model id.
104
+ * @param effort - the level chosen for that model.
105
+ */
106
+ async save(provider: string, model: string, effort: string): Promise<void> {
107
+ const key = keyOf(provider, model)
108
+ const previous = this.#rows.get(key)
109
+ const written: EffortPreference = { provider, model, effort }
110
+ this.#rows.set(key, written)
111
+ try {
112
+ await this.#persist()
113
+ } catch (error) {
114
+ // Only this call's own value is rolled back: a later save that already
115
+ // replaced it in memory is the newer truth, and restoring the older level
116
+ // here would silently undo a choice nothing failed on.
117
+ if (this.#rows.get(key) === written) {
118
+ if (previous === undefined) this.#rows.delete(key)
119
+ else this.#rows.set(key, previous)
120
+ }
121
+ throw error
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Drop the remembered level for one model, but only the one judged stale.
127
+ *
128
+ * A level a model stopped publishing is worse than none at all: the backfill in
129
+ * `session.setModel` would send it, the harness would refuse, and the model
130
+ * would become unswitchable — and because that backfill is the only writer, the
131
+ * row could never heal itself. Dropping it makes the next switch plain.
132
+ *
133
+ * The `staleEffort` argument is what keeps that cure from being worse than the
134
+ * disease: an awaited catalog read sits between judging a level stale and
135
+ * arriving here, and frames of one connection are dispatched concurrently, so
136
+ * the user may have typed a NEW level in that window. A row that no longer holds
137
+ * the level this caller judged is a newer choice, and it survives.
138
+ * @param provider - provider id.
139
+ * @param model - model id.
140
+ * @param staleEffort - the level this caller found the catalog no longer offers.
141
+ * @param reason - why it is being dropped, for the log line.
142
+ */
143
+ async forget(provider: string, model: string, staleEffort: string, reason: string): Promise<void> {
144
+ const key = keyOf(provider, model)
145
+ const previous = this.#rows.get(key)
146
+ if (previous === undefined || previous.effort !== staleEffort) return
147
+ this.#rows.delete(key)
148
+ try {
149
+ await this.#persist()
150
+ } catch (error) {
151
+ // Same rule on the way back: a row that appeared while the write failed is
152
+ // a newer choice, and restoring the stale one would undo it.
153
+ if (this.#rows.get(key) === undefined) this.#rows.set(key, previous)
154
+ throw error
155
+ }
156
+ this.#log(`model effort table: dropped ${provider}/${model} = ${previous.effort} (${reason})`)
157
+ }
158
+
159
+ async #read(): Promise<void> {
160
+ let text: string
161
+ try {
162
+ text = await readFile(this.#file, 'utf8')
163
+ } catch (error) {
164
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
165
+ this.#log(`model effort table ${this.#file} is unreadable (${String(error)}); continuing with an empty table`)
166
+ return
167
+ }
168
+ let parsed: unknown
169
+ try {
170
+ parsed = JSON.parse(text)
171
+ } catch {
172
+ this.#log(`model effort table ${this.#file} is not JSON; continuing with an empty table`)
173
+ return
174
+ }
175
+ const rows = (parsed as { efforts?: unknown } | null)?.efforts
176
+ if (!Array.isArray(rows)) {
177
+ this.#log(`model effort table ${this.#file} has no effort table; continuing with an empty table`)
178
+ return
179
+ }
180
+ // One unreadable row is not a reason to lose the rest: the table is written
181
+ // WHOLE on the next save, so every row dropped here would be erased by that
182
+ // write. Keeping everything this build can read is what makes that write
183
+ // preserve the user's other choices.
184
+ let dropped = 0
185
+ for (const row of rows) {
186
+ if (!isPreference(row)) {
187
+ dropped += 1
188
+ continue
189
+ }
190
+ this.#rows.set(keyOf(row.provider, row.model), { provider: row.provider, model: row.model, effort: row.effort })
191
+ }
192
+ if (dropped > 0) this.#log(`model effort table ${this.#file}: dropped ${dropped} unreadable row(s)`)
193
+ this.#log(`model effort table ${this.#file}: ${rows.length - dropped} remembered model(s)`)
194
+ }
195
+
196
+ /**
197
+ * Write the table atomically: same directory, 0600 from creation, flushed
198
+ * before the rename so a crash cannot leave a truncated file in place.
199
+ * Writes are serialized so two sessions choosing the same model cannot race
200
+ * the replacement.
201
+ */
202
+ async #persist(): Promise<void> {
203
+ const pending = this.#writeQueue.then(() => this.#write())
204
+ this.#writeQueue = pending.catch(() => undefined)
205
+ return pending
206
+ }
207
+
208
+ async #write(): Promise<void> {
209
+ const directory = dirname(this.#file)
210
+ await mkdir(directory, { recursive: true, mode: 0o700 })
211
+ const payload = JSON.stringify({ version: EFFORT_TABLE_VERSION, efforts: [...this.#rows.values()] }, null, 2)
212
+ const temporary = `${this.#file}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`
213
+ const handle = await open(temporary, 'w', 0o600)
214
+ try {
215
+ await handle.writeFile(payload, 'utf8')
216
+ await handle.sync()
217
+ } finally {
218
+ await handle.close()
219
+ }
220
+ await rename(temporary, this.#file)
221
+ await chmod(this.#file, 0o600)
222
+ }
223
+ }
@@ -18,6 +18,8 @@ export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
18
18
  export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
19
19
  export const METHOD_SESSION_MODELS = 'session.models'
20
20
  export const METHOD_SESSION_SET_MODEL = 'session.setModel'
21
+ /** Remember one model's reasoning level, without switching the session's model. */
22
+ export const METHOD_SESSION_SET_EFFORT = 'session.setEffort'
21
23
  export const METHOD_SESSION_CREATE = 'session.create'
22
24
  export const METHOD_SESSION_FORK = 'session.fork'
23
25
  export const METHOD_SESSION_COMMANDS = 'session.commands'
@@ -455,6 +457,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
455
457
  METHOD_SESSION_SET_PERMISSION,
456
458
  METHOD_SESSION_MODELS,
457
459
  METHOD_SESSION_SET_MODEL,
460
+ METHOD_SESSION_SET_EFFORT,
458
461
  METHOD_PAIR_BEGIN,
459
462
  METHOD_PAIR_FINISH,
460
463
  METHOD_APPROVAL_RESOLVE,
package/src/core/push.ts CHANGED
@@ -30,6 +30,17 @@ import { basename } from 'node:path'
30
30
  /** One thing a notification can be about. */
31
31
  export type PushEvent = 'turn-end' | 'turn-error' | 'question' | 'approval'
32
32
 
33
+ /**
34
+ * Which way this bridge delivers a notification.
35
+ *
36
+ * `direct` signs for APNs with this machine's own Apple key, `relay` asks the
37
+ * hosted service to sign with the one key no deployment may hold, and `off` is a
38
+ * bridge with neither route — the channel's original shape, byte for byte. The two
39
+ * routes are exclusive rather than a fallback chain: a machine holding a key keeps
40
+ * using it, so a developer's delivery never travels through the service.
41
+ */
42
+ export type PushRoute = 'direct' | 'relay' | 'off'
43
+
33
44
  /** Window inside which the same `(sessionId, event)` is one notification. */
34
45
  export const PUSH_DEDUPE_MS = 30_000
35
46
  /** Shortest gap between two notifications about the same session. */
@@ -61,6 +72,14 @@ export interface PushAddress {
61
72
  readonly environment: 'sandbox' | 'production'
62
73
  readonly bundle: string
63
74
  readonly locale?: string
75
+ /**
76
+ * The relay credential that same row registered, when it registered one.
77
+ *
78
+ * Present on the address rather than looked up by the sender so the two routes
79
+ * stay one decision: a row carries the token only in relay mode, and the sender
80
+ * that reads it is the only one this bridge built.
81
+ */
82
+ readonly relayToken?: string
64
83
  }
65
84
 
66
85
  /** The request body one APNs delivery carries (protocol §28.4). */
@@ -79,10 +98,19 @@ export interface PushNotification {
79
98
  /** What one delivery attempt reported. */
80
99
  export interface PushSendResult {
81
100
  readonly ok: boolean
82
- /** The status APNs answered, when it answered at all. */
101
+ /** The status APNs answered, or the relay did, when it answered at all. */
83
102
  readonly status?: number
84
103
  /** The reason APNs named, or this bridge's own note. */
85
104
  readonly reason?: string
105
+ /**
106
+ * Whether the answer said this registration will never work again.
107
+ *
108
+ * APNs says it in a status and a reason this module can read; the relay says it
109
+ * in a count of tokens it just retired, which names no status of its own. The
110
+ * sender that learned it reports the fact here instead of borrowing an APNs
111
+ * status it did not receive.
112
+ */
113
+ readonly dead?: boolean
86
114
  }
87
115
 
88
116
  /** One delivery a sender refused, in the words the bridge needs to read it. */
@@ -93,6 +121,8 @@ export interface PushDeliveryFailure {
93
121
  readonly status?: number
94
122
  /** The reason APNs named, or this bridge's own note. */
95
123
  readonly reason?: string
124
+ /** Whether this failure was final about the registration behind it. */
125
+ readonly dead?: boolean
96
126
  }
97
127
 
98
128
  /** What one {@link PushNotifier.notify} ended up doing, once every attempt settled. */
@@ -114,6 +144,7 @@ export interface PushDeliveryReport {
114
144
  * a claim held for it is a claim held for a phone that cannot come back.
115
145
  */
116
146
  export function isDeadPushToken(failure: PushDeliveryFailure): boolean {
147
+ if (failure.dead === true) return true
117
148
  const reason = failure.reason ?? ''
118
149
  if (reason === 'Unregistered' || reason === 'BadDeviceToken') return true
119
150
  return failure.status === 410
@@ -141,6 +172,18 @@ export interface PushNotifierOptions {
141
172
  readonly targets: () => readonly PushAddress[]
142
173
  /** The sender; absent is a bridge with no signing key, and then nothing happens. */
143
174
  readonly sender?: PushSender
175
+ /**
176
+ * Whether the configured route can reach a phone right now.
177
+ *
178
+ * Absent means "the sender is reason enough", which is what a machine holding its
179
+ * own Apple key is: the key is configured or it is not. The relay has a second
180
+ * fact in front of the credential — some paired row must still hold a relay
181
+ * token — and reading it per event is what keeps a bridge with neither route
182
+ * exactly as inert as one with no key at all.
183
+ */
184
+ readonly available?: () => boolean
185
+ /** Which route this notifier stands on; `direct` by default, as before the relay existed. */
186
+ readonly mode?: PushRoute
144
187
  /** The session's own title (§26's source), read per event. */
145
188
  readonly titles?: (sessionId: string) => string | undefined
146
189
  readonly now?: () => number
@@ -232,9 +275,31 @@ export class PushNotifier {
232
275
  this.#log = options.log ?? (() => undefined)
233
276
  }
234
277
 
235
- /** @returns whether this bridge will actually deliver anything. */
278
+ /**
279
+ * @returns whether this bridge will actually deliver anything.
280
+ *
281
+ * Read by every entrance — a delta path, a claim, a watcher — so a bridge whose
282
+ * route is not armed is indistinguishable from one that never had a channel: no
283
+ * target is read, no clock is consulted and no timer is armed.
284
+ */
236
285
  get enabled(): boolean {
237
- return this.#options.sender !== undefined
286
+ return this.#available() && this.#options.sender !== undefined
287
+ }
288
+
289
+ /** @returns which road a delivery would take: this machine's key or the hosted relay. */
290
+ get mode(): PushRoute {
291
+ return this.#options.mode ?? 'direct'
292
+ }
293
+
294
+ /** @returns whether the route in front of the sender is reachable; a throwing probe reaches nothing. */
295
+ #available(): boolean {
296
+ const available = this.#options.available
297
+ if (available === undefined) return true
298
+ try {
299
+ return available()
300
+ } catch {
301
+ return false
302
+ }
238
303
  }
239
304
 
240
305
  /**
@@ -279,7 +344,7 @@ export class PushNotifier {
279
344
  * was attempted: no sender, no target, or a rate limit that dropped this event.
280
345
  */
281
346
  notify(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void {
282
- if (this.#options.sender === undefined) return
347
+ if (!this.enabled) return
283
348
  try {
284
349
  this.#announce(event, sessionId, onReport)
285
350
  } catch (error) {
@@ -330,6 +395,7 @@ export class PushNotifier {
330
395
  deviceToken: target.deviceToken,
331
396
  ...(result.status === undefined ? {} : { status: result.status }),
332
397
  ...(result.reason === undefined ? {} : { reason: result.reason }),
398
+ ...(result.dead === true ? { dead: true } : {}),
333
399
  })
334
400
  })
335
401
  .catch((error: unknown) => {
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Host firewall management for the LAN bind toggle: while LAN access is on,
3
+ * keep one inbound allow rule for the bound port; when it turns off, remove
4
+ * the rule. Windows manages the Windows Defender Firewall rule via netsh;
5
+ * Linux uses the first available manager among firewalld / ufw / iptables.
6
+ * On every other platform (macOS included) the plugin reports the firewall
7
+ * as unmanaged: the port usually needs no rule there, and managing pf or the
8
+ * application firewall is out of scope for a distributable plugin.
9
+ *
10
+ * Ported from the dsh-LAN reference implementation (MIT), adapted to this
11
+ * package's structure and test seams.
12
+ */
13
+
14
+ import { spawnSync } from 'node:child_process'
15
+
16
+ /** Rule name shared by every backend so re-runs recreate the same rule. */
17
+ export const FIREWALL_RULE_NAME = 'remote-web-ui (auto)'
18
+
19
+ /** One command execution result (test seam replaces the runner). */
20
+ export interface ToolResult {
21
+ ok: boolean
22
+ out: string
23
+ err: string
24
+ /** true when the binary could not be spawned at all (ENOENT et al). */
25
+ missing?: boolean
26
+ }
27
+
28
+ /** The command runner seam: spawnSync in production, a stub in tests. */
29
+ export type CommandRunner = (cmd: string, args: readonly string[]) => ToolResult
30
+
31
+ /** Production runner: spawn without a shell, capture text, 20s timeout. */
32
+ export const spawnRunner: CommandRunner = (cmd, args) => {
33
+ const result = spawnSync(cmd, args, {
34
+ shell: false,
35
+ encoding: 'utf8',
36
+ windowsHide: process.platform === 'win32',
37
+ timeout: 20_000,
38
+ })
39
+ return {
40
+ ok: result.status === 0,
41
+ out: result.stdout ?? '',
42
+ err: result.stderr ?? '',
43
+ missing: result.error !== undefined,
44
+ }
45
+ }
46
+
47
+ /** A firewall backend manages one allow rule for a TCP port. */
48
+ export interface FirewallBackend {
49
+ /** Short label surfaced in the settings card (netsh, firewalld, ...). */
50
+ readonly label: string
51
+ ruleExists(port: number): boolean
52
+ addRule(port: number): boolean
53
+ removeRule(port: number): boolean
54
+ }
55
+
56
+ function netshBackend(run: CommandRunner): FirewallBackend {
57
+ // `show rule name=` exits 0 even when nothing matches (the localized "no
58
+ // rules match" note), so exit-code-only probes always report the rule as
59
+ // present. The verbose listing echoes the full rule name — the one
60
+ // locale-independent field — and is matched literally instead.
61
+ const show = (): boolean => {
62
+ const result = run('netsh', ['advfirewall', 'firewall', 'show', 'rule', `name=${FIREWALL_RULE_NAME}`, 'verbose'])
63
+ return result.ok && result.out.includes(FIREWALL_RULE_NAME)
64
+ }
65
+ return {
66
+ label: 'netsh',
67
+ ruleExists: show,
68
+ addRule: (port) => run('netsh', [
69
+ 'advfirewall', 'firewall', 'add', 'rule', `name=${FIREWALL_RULE_NAME}`,
70
+ 'dir=in', 'action=allow', 'protocol=TCP', `localport=${String(port)}`, 'profile=private,domain',
71
+ ]).ok,
72
+ removeRule: () => {
73
+ if (!show()) return true
74
+ return run('netsh', ['advfirewall', 'firewall', 'delete', 'rule', `name=${FIREWALL_RULE_NAME}`]).ok
75
+ },
76
+ }
77
+ }
78
+
79
+ function firewalldBackend(run: CommandRunner): FirewallBackend {
80
+ return {
81
+ label: 'firewalld',
82
+ ruleExists: (port) => run('firewall-cmd', ['--permanent', '--query-port', `${String(port)}/tcp`]).ok,
83
+ addRule: (port) => {
84
+ const add = run('firewall-cmd', ['--permanent', '--add-port', `${String(port)}/tcp`])
85
+ const reload = run('firewall-cmd', ['--reload'])
86
+ return add.ok && reload.ok
87
+ },
88
+ removeRule: (port) => {
89
+ const del = run('firewall-cmd', ['--permanent', '--remove-port', `${String(port)}/tcp`])
90
+ const reload = run('firewall-cmd', ['--reload'])
91
+ return del.ok && reload.ok
92
+ },
93
+ }
94
+ }
95
+
96
+ function ufwBackend(run: CommandRunner): FirewallBackend {
97
+ return {
98
+ label: 'ufw',
99
+ ruleExists: (port) => {
100
+ const result = run('ufw', ['status'])
101
+ // Anchored so a superset port's row (1443/tcp) cannot satisfy the
102
+ // probe for a shorter one (443/tcp).
103
+ return result.ok && new RegExp(`(^|\\s)${String(port)}/tcp\\s+ALLOW`, 'i').test(result.out)
104
+ },
105
+ addRule: (port) => run('ufw', ['allow', `${String(port)}/tcp`]).ok,
106
+ removeRule: (port) => run('ufw', ['delete', 'allow', `${String(port)}/tcp`]).ok,
107
+ }
108
+ }
109
+
110
+ function iptablesBackend(run: CommandRunner): FirewallBackend {
111
+ const rule = (port: number): string[] => ['INPUT', '-p', 'tcp', '--dport', String(port), '-j', 'ACCEPT']
112
+ return {
113
+ label: 'iptables',
114
+ ruleExists: (port) => run('iptables', ['-C', ...rule(port)]).ok,
115
+ addRule: (port) => run('iptables', ['-A', ...rule(port)]).ok,
116
+ removeRule: (port) => run('iptables', ['-D', ...rule(port)]).ok,
117
+ }
118
+ }
119
+
120
+ function toolAvailable(run: CommandRunner, cmd: string): boolean {
121
+ try {
122
+ // A missing binary reports through the runner's missing flag (spawnSync
123
+ // sets result.error for ENOENT); any graceful answer counts as present.
124
+ return run(cmd, ['--version']).missing !== true
125
+ } catch {
126
+ return false
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Detect the platform firewall manager. Returns undefined when the platform
132
+ * has no supported manager (macOS, unknown Linux without tools): the port
133
+ * then usually needs no rule and the UI reports "unmanaged".
134
+ */
135
+ export function detectFirewallBackend(
136
+ platform: NodeJS.Platform,
137
+ run: CommandRunner = spawnRunner,
138
+ ): FirewallBackend | undefined {
139
+ if (platform === 'win32') return netshBackend(run)
140
+ if (platform !== 'linux') return undefined
141
+ if (toolAvailable(run, 'firewall-cmd')) {
142
+ // firewalld only counts when its daemon answers; an installed-but-idle
143
+ // firewall-cmd would otherwise claim management it cannot exercise.
144
+ if (run('firewall-cmd', ['--state']).ok) return firewalldBackend(run)
145
+ }
146
+ if (toolAvailable(run, 'ufw')) return ufwBackend(run)
147
+ if (toolAvailable(run, 'iptables')) return iptablesBackend(run)
148
+ return undefined
149
+ }
150
+
151
+ let cachedBackend: { platform: NodeJS.Platform; backend: FirewallBackend | undefined } | undefined
152
+
153
+ /** Cached detection for the running platform (per process). */
154
+ export function firewallBackend(): FirewallBackend | undefined {
155
+ const platform = process.platform
156
+ if (cachedBackend === undefined || cachedBackend.platform !== platform) {
157
+ cachedBackend = { platform, backend: detectFirewallBackend(platform) }
158
+ }
159
+ return cachedBackend.backend
160
+ }
161
+
162
+ /** Firewall state reported to the settings card. */
163
+ export interface FirewallSummary {
164
+ /** true when the rule state matches the LAN toggle (or nothing to manage). */
165
+ ok: boolean
166
+ /** false when no supported firewall manager exists on this platform. */
167
+ managed: boolean
168
+ /** Backend label or an explanation for unmanaged platforms. */
169
+ note?: string
170
+ }
171
+
172
+ /**
173
+ * Delete-and-add: recreating the rule is idempotent and locale-proof (netsh
174
+ * output is localized, so parsing the live rule's port is fragile; the Linux
175
+ * backends follow the same recreate pattern).
176
+ */
177
+ export function ensureFirewallRule(port: number): boolean {
178
+ invalidateFirewallSummary()
179
+ const backend = firewallBackend()
180
+ if (backend === undefined) return true
181
+ backend.removeRule(port)
182
+ return backend.addRule(port)
183
+ }
184
+
185
+ export function removeFirewallRule(port: number): boolean {
186
+ invalidateFirewallSummary()
187
+ const backend = firewallBackend()
188
+ if (backend === undefined) return true
189
+ return backend.removeRule(port)
190
+ }
191
+
192
+ /**
193
+ * Human-readable firewall state for the status endpoint. A missing backend
194
+ * means the platform has nothing to manage; detection stays at the call site
195
+ * so an explicit undefined cannot silently re-probe the real OS mid-test.
196
+ */
197
+ export function computeFirewallSummary(
198
+ port: number,
199
+ lanEnabled: boolean,
200
+ backend: FirewallBackend | undefined,
201
+ ): FirewallSummary {
202
+ if (backend === undefined) return { ok: true, managed: false }
203
+ return { ok: lanEnabled ? backend.ruleExists(port) : !backend.ruleExists(port), managed: true, note: backend.label }
204
+ }
205
+
206
+ /** How long a firewallSummary answer is reused before the backend is probed again. */
207
+ export const FIREWALL_SUMMARY_TTL_MS = 30_000
208
+
209
+ let summaryCache: { key: string; at: number; value: FirewallSummary } | undefined
210
+
211
+ /** Forget the cached summary (rule mutations call this). */
212
+ export function invalidateFirewallSummary(): void {
213
+ summaryCache = undefined
214
+ }
215
+
216
+ /**
217
+ * The settings card polls this every ten seconds; the probes are blocking
218
+ * spawnSync subprocesses on managed platforms, so short-TTL memoization
219
+ * keeps one poll from freezing the host event loop per request.
220
+ */
221
+ export function firewallSummary(port: number, lanEnabled: boolean): FirewallSummary {
222
+ const key = `${String(port)}|${lanEnabled ? '1' : '0'}`
223
+ const now = Date.now()
224
+ if (summaryCache !== undefined && summaryCache.key === key && now - summaryCache.at < FIREWALL_SUMMARY_TTL_MS) {
225
+ return summaryCache.value
226
+ }
227
+ const value = computeFirewallSummary(port, lanEnabled, firewallBackend())
228
+ summaryCache = { key, at: now, value }
229
+ return value
230
+ }