ftown-bridge 0.30.80 → 0.30.84

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 (191) hide show
  1. package/dist/direct-transport/dtls-identity.d.ts +1 -1
  2. package/dist/direct-transport/dtls-identity.js +11 -5
  3. package/dist/direct-transport/dtls-identity.js.map +1 -1
  4. package/dist/direct-transport/loopback-server.d.ts +6 -1
  5. package/dist/direct-transport/loopback-server.js +19 -1
  6. package/dist/direct-transport/loopback-server.js.map +1 -1
  7. package/dist/direct-transport/peer-manager.d.ts +3 -0
  8. package/dist/direct-transport/peer-manager.js +3 -1
  9. package/dist/direct-transport/peer-manager.js.map +1 -1
  10. package/dist/endpoint-id-command.d.ts +5 -0
  11. package/dist/endpoint-id-command.js +28 -0
  12. package/dist/endpoint-id-command.js.map +1 -0
  13. package/dist/ftown-cli.d.ts +1 -1
  14. package/dist/ftown-cli.js +15 -3
  15. package/dist/ftown-cli.js.map +1 -1
  16. package/dist/index.js +298 -113
  17. package/dist/index.js.map +1 -1
  18. package/dist/local-api-server.d.ts +6 -0
  19. package/dist/local-api-server.js +39 -1
  20. package/dist/local-api-server.js.map +1 -1
  21. package/dist/peer-control.d.ts +16 -10
  22. package/dist/peer-control.js +103 -33
  23. package/dist/peer-control.js.map +1 -1
  24. package/dist/peer-lan-address.d.ts +8 -0
  25. package/dist/peer-lan-address.js +50 -0
  26. package/dist/peer-lan-address.js.map +1 -0
  27. package/dist/peer-lan-hints.d.ts +10 -0
  28. package/dist/peer-lan-hints.js +20 -0
  29. package/dist/peer-lan-hints.js.map +1 -0
  30. package/dist/peer-lan.d.ts +26 -0
  31. package/dist/peer-lan.js +283 -0
  32. package/dist/peer-lan.js.map +1 -0
  33. package/dist/peer-link.d.ts +82 -15
  34. package/dist/peer-link.js +256 -35
  35. package/dist/peer-link.js.map +1 -1
  36. package/dist/peer-pq-cli.d.ts +3 -0
  37. package/dist/peer-pq-cli.js +67 -0
  38. package/dist/peer-pq-cli.js.map +1 -0
  39. package/dist/peer-pq-identity.d.ts +11 -0
  40. package/dist/peer-pq-identity.js +126 -0
  41. package/dist/peer-pq-identity.js.map +1 -0
  42. package/dist/peer-pq-trust.d.ts +23 -0
  43. package/dist/peer-pq-trust.js +140 -0
  44. package/dist/peer-pq-trust.js.map +1 -0
  45. package/dist/peer-session-cache.d.ts +2 -2
  46. package/dist/peer-session-cache.js +10 -7
  47. package/dist/peer-session-cache.js.map +1 -1
  48. package/dist/peer-tls-channel.d.ts +18 -0
  49. package/dist/peer-tls-channel.js +253 -0
  50. package/dist/peer-tls-channel.js.map +1 -0
  51. package/dist/peer-tls-policy.d.ts +3 -0
  52. package/dist/peer-tls-policy.js +68 -0
  53. package/dist/peer-tls-policy.js.map +1 -0
  54. package/dist/peers-cli.js +8 -1
  55. package/dist/peers-cli.js.map +1 -1
  56. package/dist/protocol/comms.d.ts +22 -0
  57. package/dist/protocol/comms.js +48 -0
  58. package/dist/protocol/comms.js.map +1 -0
  59. package/dist/protocol/peer-routing.d.ts +1 -0
  60. package/dist/protocol/peer-routing.js +1 -0
  61. package/dist/protocol/peer-routing.js.map +1 -1
  62. package/dist/security/bridge/direct.js +1 -1
  63. package/dist/security/bridge/direct.js.map +1 -1
  64. package/dist/security/bridge/execute.js +3 -3
  65. package/dist/security/bridge/execute.js.map +1 -1
  66. package/dist/security/bridge/permissions.js +3 -1
  67. package/dist/security/bridge/permissions.js.map +1 -1
  68. package/dist/security/bridge/policy.d.ts +14 -4
  69. package/dist/security/bridge/policy.js +79 -10
  70. package/dist/security/bridge/policy.js.map +1 -1
  71. package/dist/security/bridge/security.d.ts +8 -4
  72. package/dist/security/bridge/security.js +97 -27
  73. package/dist/security/bridge/security.js.map +1 -1
  74. package/dist/security/protocol.d.ts +2 -0
  75. package/dist/security-cli.js +6 -0
  76. package/dist/security-cli.js.map +1 -1
  77. package/dist/start-commands.js +19 -5
  78. package/dist/start-commands.js.map +1 -1
  79. package/dist/workspace/authority.d.ts +274 -0
  80. package/dist/workspace/authority.js +732 -0
  81. package/dist/workspace/authority.js.map +1 -0
  82. package/dist/workspace/browser-access.d.ts +15 -0
  83. package/dist/workspace/browser-access.js +145 -0
  84. package/dist/workspace/browser-access.js.map +1 -0
  85. package/dist/workspace/browser-exchange.d.ts +6 -0
  86. package/dist/workspace/browser-exchange.js +18 -0
  87. package/dist/workspace/browser-exchange.js.map +1 -0
  88. package/dist/workspace/browser-gateway.d.ts +4 -0
  89. package/dist/workspace/browser-gateway.js +105 -0
  90. package/dist/workspace/browser-gateway.js.map +1 -0
  91. package/dist/workspace/browser-invitation.d.ts +50 -0
  92. package/dist/workspace/browser-invitation.js +79 -0
  93. package/dist/workspace/browser-invitation.js.map +1 -0
  94. package/dist/workspace/browser-qr.d.ts +2 -0
  95. package/dist/workspace/browser-qr.js +11 -0
  96. package/dist/workspace/browser-qr.js.map +1 -0
  97. package/dist/workspace/cli.d.ts +1 -0
  98. package/dist/workspace/cli.js +440 -0
  99. package/dist/workspace/cli.js.map +1 -0
  100. package/dist/workspace/continuity.d.ts +23 -0
  101. package/dist/workspace/continuity.js +94 -0
  102. package/dist/workspace/continuity.js.map +1 -0
  103. package/dist/workspace/cutover-commands.d.ts +2 -0
  104. package/dist/workspace/cutover-commands.js +56 -0
  105. package/dist/workspace/cutover-commands.js.map +1 -0
  106. package/dist/workspace/cutover-storage.d.ts +11 -0
  107. package/dist/workspace/cutover-storage.js +90 -0
  108. package/dist/workspace/cutover-storage.js.map +1 -0
  109. package/dist/workspace/cutover.d.ts +107 -0
  110. package/dist/workspace/cutover.js +614 -0
  111. package/dist/workspace/cutover.js.map +1 -0
  112. package/dist/workspace/device.d.ts +43 -0
  113. package/dist/workspace/device.js +268 -0
  114. package/dist/workspace/device.js.map +1 -0
  115. package/dist/workspace/enrollment.d.ts +61 -0
  116. package/dist/workspace/enrollment.js +241 -0
  117. package/dist/workspace/enrollment.js.map +1 -0
  118. package/dist/workspace/lan-discovery-network.d.ts +11 -0
  119. package/dist/workspace/lan-discovery-network.js +175 -0
  120. package/dist/workspace/lan-discovery-network.js.map +1 -0
  121. package/dist/workspace/lan-discovery-secrets.d.ts +6 -0
  122. package/dist/workspace/lan-discovery-secrets.js +90 -0
  123. package/dist/workspace/lan-discovery-secrets.js.map +1 -0
  124. package/dist/workspace/lan-discovery-wire.d.ts +27 -0
  125. package/dist/workspace/lan-discovery-wire.js +84 -0
  126. package/dist/workspace/lan-discovery-wire.js.map +1 -0
  127. package/dist/workspace/lan-discovery.d.ts +22 -0
  128. package/dist/workspace/lan-discovery.js +168 -0
  129. package/dist/workspace/lan-discovery.js.map +1 -0
  130. package/dist/workspace/listener.d.ts +56 -0
  131. package/dist/workspace/listener.js +354 -0
  132. package/dist/workspace/listener.js.map +1 -0
  133. package/dist/workspace/native-client-assets.d.ts +3 -0
  134. package/dist/workspace/native-client-assets.js +184 -0
  135. package/dist/workspace/native-client-assets.js.map +1 -0
  136. package/dist/workspace/native-client-bridge.d.ts +22 -0
  137. package/dist/workspace/native-client-bridge.js +70 -0
  138. package/dist/workspace/native-client-bridge.js.map +1 -0
  139. package/dist/workspace/native-client-cli.d.ts +3 -0
  140. package/dist/workspace/native-client-cli.js +164 -0
  141. package/dist/workspace/native-client-cli.js.map +1 -0
  142. package/dist/workspace/native-client-dashboard.d.ts +10 -0
  143. package/dist/workspace/native-client-dashboard.js +136 -0
  144. package/dist/workspace/native-client-dashboard.js.map +1 -0
  145. package/dist/workspace/native-client-protocol.d.ts +76 -0
  146. package/dist/workspace/native-client-protocol.js +197 -0
  147. package/dist/workspace/native-client-protocol.js.map +1 -0
  148. package/dist/workspace/native-client-tls.d.ts +25 -0
  149. package/dist/workspace/native-client-tls.js +101 -0
  150. package/dist/workspace/native-client-tls.js.map +1 -0
  151. package/dist/workspace/peer-sync.d.ts +46 -0
  152. package/dist/workspace/peer-sync.js +246 -0
  153. package/dist/workspace/peer-sync.js.map +1 -0
  154. package/dist/workspace/pq-provider.d.ts +1 -0
  155. package/dist/workspace/pq-provider.js +48 -0
  156. package/dist/workspace/pq-provider.js.map +1 -0
  157. package/dist/workspace/reenroll.d.ts +21 -0
  158. package/dist/workspace/reenroll.js +222 -0
  159. package/dist/workspace/reenroll.js.map +1 -0
  160. package/dist/workspace/remote-enrollment-peer.d.ts +17 -0
  161. package/dist/workspace/remote-enrollment-peer.js +149 -0
  162. package/dist/workspace/remote-enrollment-peer.js.map +1 -0
  163. package/dist/workspace/remote-enrollment-signal.d.ts +22 -0
  164. package/dist/workspace/remote-enrollment-signal.js +38 -0
  165. package/dist/workspace/remote-enrollment-signal.js.map +1 -0
  166. package/dist/workspace/remote-enrollment.d.ts +17 -0
  167. package/dist/workspace/remote-enrollment.js +350 -0
  168. package/dist/workspace/remote-enrollment.js.map +1 -0
  169. package/dist/workspace/rendezvous-client.d.ts +24 -0
  170. package/dist/workspace/rendezvous-client.js +107 -0
  171. package/dist/workspace/rendezvous-client.js.map +1 -0
  172. package/dist/workspace/rendezvous-crypto.d.ts +15 -0
  173. package/dist/workspace/rendezvous-crypto.js +100 -0
  174. package/dist/workspace/rendezvous-crypto.js.map +1 -0
  175. package/dist/workspace/rendezvous-runtime.d.ts +13 -0
  176. package/dist/workspace/rendezvous-runtime.js +23 -0
  177. package/dist/workspace/rendezvous-runtime.js.map +1 -0
  178. package/dist/workspace/rendezvous-wire.d.ts +50 -0
  179. package/dist/workspace/rendezvous-wire.js +95 -0
  180. package/dist/workspace/rendezvous-wire.js.map +1 -0
  181. package/dist/workspace/rendezvous.d.ts +65 -0
  182. package/dist/workspace/rendezvous.js +362 -0
  183. package/dist/workspace/rendezvous.js.map +1 -0
  184. package/dist/workspace/runtime.d.ts +24 -0
  185. package/dist/workspace/runtime.js +130 -0
  186. package/dist/workspace/runtime.js.map +1 -0
  187. package/dist/workspace/writer-only.d.ts +9 -0
  188. package/dist/workspace/writer-only.js +120 -0
  189. package/dist/workspace/writer-only.js.map +1 -0
  190. package/package.json +4 -2
  191. package/skills/ftown/SKILL.md +4 -0
package/dist/index.js CHANGED
@@ -1,4 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { attachWorkspaceRendezvous } from './workspace/rendezvous-runtime.js';
3
+ import { startWorkspaceNativeControl } from './workspace/native-client-bridge.js';
4
+ import { acquireReadyWorkspaceBridgeInstance, acquireSoloKeyRotation } from './workspace/cutover.js';
5
+ import { startWorkspaceBrowserGateway } from './workspace/browser-gateway.js';
6
+ import { WorkspaceRuntime } from './workspace/runtime.js';
7
+ import { workspaceExists } from './workspace/authority.js';
2
8
  import { deliverDiscussionMail, discussionSession } from './project-discussion-delivery.js';
3
9
  import { TicketNotificationInbox, deliverTicketNotifications } from './ticket-notifications.js';
4
10
  import { Command as Commander, CommanderError } from 'commander';
@@ -6,10 +12,9 @@ import { v4 as uuidv4 } from 'uuid';
6
12
  import { resolve, dirname, join } from 'node:path';
7
13
  import { hostname as osHostname, networkInterfaces, homedir } from 'node:os';
8
14
  import { fileURLToPath } from 'node:url';
9
- import { mkdirSync, readFileSync, writeFileSync, unlinkSync, realpathSync, chmodSync } from 'node:fs';
15
+ import { mkdirSync, readFileSync, writeFileSync, unlinkSync, realpathSync, chmodSync, renameSync, rmSync } from 'node:fs';
10
16
  import { randomBytes } from 'node:crypto';
11
17
  import { cleanup as ndcCleanup } from 'node-datachannel';
12
- import { acquireBridgeInstance } from './bridge-instance.js';
13
18
  import { configureUpdateOptions } from './update-options.js';
14
19
  import { CentrifugoClient } from './centrifugo-client.js';
15
20
  import { WatchRegistry } from './direct-transport/watch-registry.js';
@@ -31,6 +36,10 @@ import { hasPendingChild, parseRemoteParent, sessionRequestPrincipal, SessionHie
31
36
  import { remoteChildPlanStore, remotePlanBlocksHandoff } from './remote-child-plan.js';
32
37
  import { PeerControl } from './peer-control.js';
33
38
  import { PeerLinks } from './peer-link.js';
39
+ import { startPeerLan } from './peer-lan.js';
40
+ import { parsePeerLanAddressOverrides } from './peer-lan-address.js';
41
+ import { WorkspacePeerSync } from './workspace/peer-sync.js';
42
+ import { loadPeerTlsPolicy } from './peer-tls-policy.js';
34
43
  import { launchCapabilities, probeLaunchCapabilities } from './harness-registry.js';
35
44
  import { startAddressedListener } from './direct-transport/addressed-setup.js';
36
45
  import { executeSecurePacket } from './security/bridge/execute.js';
@@ -69,7 +78,7 @@ import { runLedgerPairing } from './ledger-pairing-client.js';
69
78
  import { resolveDefaultDataDir, resolveFtownHome } from './ftown-home.js';
70
79
  import { SessionController } from './session-controller.js';
71
80
  import { createServer } from 'node:http';
72
- import { generateAccessKey, mintHubJwt, sha256Hex } from './solo/solo-auth.js';
81
+ import { generateAccessKey, mintHubJwt } from './solo/solo-auth.js';
73
82
  import { DEFAULT_SOLO_PORT, SOLO_USER_ID } from './solo/contract.js';
74
83
  import { ensureHubBinary, startHub, stopHub, writeHubConfig } from './solo/hub-manager.js';
75
84
  import { ensurePanelBundle, findPanelServerDir, normalizePanelVersion, startPanel, stopPanel, } from './solo/panel-manager.js';
@@ -81,6 +90,20 @@ import { BridgeUpdateCoordinator } from './bridge-update.js';
81
90
  import { resolveStableRelease, prepareRelease, discardPreparedRelease } from './update-release.js';
82
91
  import { assertUpdateReservationAllowed, readUpdateRestartContext, reportUpdateReady, reserveUpdate, prepareHandoff, readUpdateReceipt, writeUpdateReceipt } from './update-handoff.js';
83
92
  import { detectWsl2, soloBannerLines } from './wsl2.js';
93
+ function writeNewSoloAccessKey(keyHashPath) {
94
+ const key = generateAccessKey();
95
+ const folder = dirname(keyHashPath);
96
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
97
+ const temporary = join(folder, `.access-key-${uuidv4()}.tmp`);
98
+ try {
99
+ writeFileSync(temporary, key.hash + '\n', { mode: 0o600, flag: 'wx', flush: true });
100
+ renameSync(temporary, keyHashPath);
101
+ }
102
+ finally {
103
+ rmSync(temporary, { force: true });
104
+ }
105
+ return key;
106
+ }
84
107
  /** Bridge package version — doubles as the default panel bundle version. */
85
108
  const BRIDGE_VERSION = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8')).version;
86
109
  /** Open attention items for one session, any route. Pages until the ledger is exhausted. */
@@ -129,15 +152,19 @@ export async function finishUpdateRestartAdmission(admission, reportReady) {
129
152
  export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
130
153
  const isWsl2 = deps.isWsl2 ?? detectWsl2;
131
154
  const program = new Commander();
155
+ // runBridge is also embedded in CLI callers. A rejected start must release its handles without exiting their process.
156
+ const partialStartup = [];
157
+ let releaseFailedInstance;
132
158
  program.exitOverride();
133
159
  configureUpdateOptions(program);
134
160
  program
135
161
  .name(commandName)
136
162
  .description('ftown orchestrator bridge for Centrifugo')
137
163
  .option('--local', 'Local browser control only: no cloud account or connection')
164
+ .option('--local-only', 'Connect paired devices over private networks without hosted rendezvous or public STUN')
138
165
  .option('--solo', 'Single-port LAN deployment: no account service, managed hub + panel children, key-based auth')
139
166
  .option('--port <port>', 'Public port for --solo front (default: see DEFAULT_SOLO_PORT)')
140
- .option('--rotate-key', 'With --solo: regenerate the access key, print the new banner, exit (offline)')
167
+ .option('--rotate-key', 'With --solo: generate and print a new access key for the next startup')
141
168
  .option('--api-url <url>', 'ftown UI API URL', DEFAULT_API_URL)
142
169
  .option('--data-dir <path>', 'Directory for session data (default: ~/.ftown/data)')
143
170
  .option('--bridge-id <id>', 'Bridge instance ID (default: persisted per data dir)')
@@ -147,6 +174,8 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
147
174
  program.error('--local and --solo cannot be combined');
148
175
  if ((opts.local || opts.solo) && opts.newIdentity)
149
176
  program.error('--new-identity requires cloud mode');
177
+ if (opts.rotateKey && !opts.solo)
178
+ program.error('--rotate-key requires --solo');
150
179
  const apiUrl = new URL(opts.apiUrl);
151
180
  const isLocalHost = apiUrl.hostname === 'localhost' ||
152
181
  apiUrl.hostname === '127.0.0.1' ||
@@ -164,11 +193,39 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
164
193
  const dataDir = opts.dataDir ? resolve(opts.dataDir) : defaultDataDir;
165
194
  // No bridge starts, and no identity is reset, while an update holds the reservation.
166
195
  assertUpdateReservationAllowed(homedir());
167
- if (!opts.rotateKey) {
168
- const instance = await acquireBridgeInstance(dataDir);
169
- // Hold ownership through teardown, including partial startup failures. The update
170
- // helper starts its successor only after this process exits.
171
- process.once('exit', () => instance.close());
196
+ const networkLocalOnly = Boolean(opts.localOnly);
197
+ if (networkLocalOnly && (opts.solo || opts.newIdentity || opts.local))
198
+ program.error('--local-only requires a paired bridge.');
199
+ const soloKeyPath = join(dataDir, 'solo', 'access-key-hash');
200
+ if (opts.rotateKey) {
201
+ if (readUpdateRestartContext())
202
+ throw new Error('Invalid update restart context');
203
+ const instance = await acquireSoloKeyRotation(dataDir);
204
+ try {
205
+ const { raw } = writeNewSoloAccessKey(soloKeyPath);
206
+ const port = opts.port ? Number(opts.port) : DEFAULT_SOLO_PORT;
207
+ const ips = networkInterfacesForBanner();
208
+ console.log('========================================');
209
+ console.log(' ftown SOLO — access key rotated');
210
+ for (const line of soloBannerLines({ ips: ips.length ? ips : ['localhost'], port, accessKeyRaw: raw, isWsl2: isWsl2() })) {
211
+ console.log(line);
212
+ }
213
+ console.log('========================================');
214
+ }
215
+ finally {
216
+ instance?.close();
217
+ }
218
+ return;
219
+ }
220
+ const instance = await acquireReadyWorkspaceBridgeInstance(dataDir);
221
+ // Hold ownership through teardown, including partial startup failures. The update
222
+ // helper starts its successor only after this process exits.
223
+ const releaseInstance = () => instance.close();
224
+ process.once('exit', releaseInstance);
225
+ releaseFailedInstance = () => { process.off('exit', releaseInstance); releaseInstance(); };
226
+ const workspaceConfigured = workspaceExists(dataDir);
227
+ if (workspaceConfigured && (opts.newIdentity || opts.local || opts.solo || opts.bridgeId)) {
228
+ program.error('This data directory has a workspace identity. Start it with ftown start or ftown start --local-only.');
172
229
  }
173
230
  const runMode = bridgeMode(opts);
174
231
  // Restart context is authenticated by the private helper channel before any mutation. It is read before any reset because a
@@ -183,7 +240,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
183
240
  }
184
241
  const launchedByUpdate = launchContext !== null || launchContextError !== null;
185
242
  // Account mode: --new-identity or v1 account state starts a reset. Every mode finishes one a revoked restart or a crash left pending.
186
- const resetOutcome = resetIdentityForStart({ dataDir, mode: runMode, newIdentity: Boolean(opts.newIdentity), updateRestart: launchedByUpdate,
243
+ const resetOutcome = workspaceConfigured ? { kind: 'continue', reset: null } : resetIdentityForStart({ dataDir, mode: runMode, newIdentity: Boolean(opts.newIdentity), updateRestart: launchedByUpdate,
187
244
  log: line => console.log(line) });
188
245
  if (resetOutcome.kind === 'exit') {
189
246
  console.log(resetOutcome.message);
@@ -249,6 +306,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
249
306
  // Signed revocation of this bridgeId restarts the process as a fresh install, at most once.
250
307
  // The re-exec keeps this PID, so whatever startup has acquired so far is released first.
251
308
  let releaseForRestart = async () => { };
309
+ partialStartup.push(() => releaseForRestart());
252
310
  // Mirrors the update coordinator's receipts; an active operation holds the reservation under this PID.
253
311
  let updatePhase = null;
254
312
  const revokedRestart = createRevokedRestart({
@@ -256,26 +314,6 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
256
314
  shutdown: () => releaseForRestart(), log: message => console.log(message), exit: code => process.exit(code),
257
315
  canReexec: () => canReexecAfterRevocation({ updateRestart: updateRestart !== null, updatePhase }),
258
316
  });
259
- // L4: --rotate-key short-circuits BEFORE any listener binds (exit 0,
260
- // nothing started). Without --solo it is an argument error.
261
- if (opts.rotateKey && !opts.solo) {
262
- program.error('--rotate-key requires --solo');
263
- }
264
- if (opts.solo && opts.rotateKey) {
265
- const raw = generateAccessKey().raw;
266
- mkdirSync(join(dataDir, 'solo'), { recursive: true, mode: 0o700 });
267
- writeFileSync(join(dataDir, 'solo', 'access-key-hash'), `${sha256Hex(raw)}\n`, { mode: 0o600 });
268
- const port = opts.port ? Number(opts.port) : DEFAULT_SOLO_PORT;
269
- console.log('========================================');
270
- console.log(' ftown SOLO — access key rotated');
271
- for (const line of soloBannerLines({
272
- ips: networkInterfacesForBanner(), port, accessKeyRaw: raw, isWsl2: isWsl2(),
273
- })) {
274
- console.log(line);
275
- }
276
- console.log('========================================');
277
- process.exit(0);
278
- }
279
317
  // The local API server binds before the token fetch: its ephemeral port and
280
318
  // the per-process loopback nonce ride the auth request so the UI can embed
281
319
  // them in the Centrifugo connection JWT `info` claim (presence advert, L2).
@@ -304,6 +342,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
304
342
  writeFileSync(localPortPath, `${hookPort}\n`, { mode: 0o600 });
305
343
  console.log(`[Bridge] Local API server started on port ${hookPort}`);
306
344
  const localNonce = randomBytes(16).toString('hex');
345
+ partialStartup.push(() => localApiServer.closeTransfers());
307
346
  // ----- SOLO MODE (contract: bridge/src/solo/contract.ts, lifecycle L1-L4) -----
308
347
  let solo;
309
348
  if (opts.solo) {
@@ -321,18 +360,18 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
321
360
  // in the one-time banner. Persisted state is the hash alone. Rotation is
322
361
  // handled by the L4 short-circuit above; here a missing hash means FIRST
323
362
  // boot — generate fresh so the banner can print the full link.
324
- const keyHashPath = join(dataDir, 'solo', 'access-key-hash');
325
363
  let accessKeyRaw;
326
364
  let accessKeyHash;
327
365
  try {
328
- accessKeyHash = readFileSync(keyHashPath, 'utf8').trim();
366
+ accessKeyHash = readFileSync(soloKeyPath, 'utf8').trim();
329
367
  }
330
- catch {
331
- accessKeyRaw = generateAccessKey().raw;
332
- accessKeyHash = sha256Hex(accessKeyRaw);
368
+ catch (error) {
369
+ if (error.code !== 'ENOENT')
370
+ throw error;
371
+ const key = writeNewSoloAccessKey(soloKeyPath);
372
+ accessKeyRaw = key.raw;
373
+ accessKeyHash = key.hash;
333
374
  }
334
- mkdirSync(join(dataDir, 'solo'), { recursive: true, mode: 0o700 });
335
- writeFileSync(keyHashPath, `${accessKeyHash}\n`, { mode: 0o600 });
336
375
  // Ephemeral private ports for children: probe free ports on loopback so
337
376
  // collisions are practically impossible (contract "Ports" block).
338
377
  const probeFreePort = () => new Promise((resolveP, rejectP) => {
@@ -365,6 +404,10 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
365
404
  hub: { isHealthy: () => hubHealthy.up },
366
405
  panel: { isHealthy: () => panelHealthy.up },
367
406
  });
407
+ let cancelled = false;
408
+ let startingHub;
409
+ let startingPanel;
410
+ partialStartup.push(() => startingHub?.then(() => stopHub(dataDir)), () => startingPanel?.then(() => stopPanel(dataDir)), () => { cancelled = true; return front.close(); });
368
411
  // Children ensured asynchronously AFTER the front listens (L1). The hub
369
412
  // must be healthy before the Centrifugo client connects — gated below.
370
413
  const soloDir = join(dataDir, 'solo');
@@ -372,7 +415,10 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
372
415
  const binPath = await ensureHubBinary({ dataDir });
373
416
  const configPath = join(soloDir, 'centrifugo.json');
374
417
  await writeHubConfig(configPath, { port: hubPort, secret: hubSecret });
375
- await startHub({ configPath, binPath, dataDir });
418
+ if (cancelled)
419
+ return;
420
+ startingHub = startHub({ configPath, binPath, dataDir });
421
+ await startingHub;
376
422
  hubHealthy.up = true;
377
423
  console.log('[Solo] Hub is up (private port)');
378
424
  })();
@@ -390,12 +436,18 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
390
436
  // Dev escape hatch: serve an already-built standalone directory.
391
437
  const serverDir = await findPanelServerDir(resolve(process.env.FTOWN_SOLO_PANEL_DIR));
392
438
  console.log(`[Solo] Using local panel dir: ${serverDir}`);
393
- await startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
439
+ if (cancelled)
440
+ return;
441
+ startingPanel = startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
442
+ await startingPanel;
394
443
  }
395
444
  else {
396
445
  const bundleDir = await ensurePanelBundle({ dataDir, version: panelVersion });
397
446
  const serverDir = await findPanelServerDir(bundleDir);
398
- await startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
447
+ if (cancelled)
448
+ return;
449
+ startingPanel = startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
450
+ await startingPanel;
399
451
  }
400
452
  panelHealthy.up = true;
401
453
  console.log('[Solo] Panel is up (private port)');
@@ -460,7 +512,56 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
460
512
  let accountRegistrar;
461
513
  /** Bound once the relay client exists: a relay refused earlier reconnects when the key is accepted again. */
462
514
  let reconnectRelay = () => { };
463
- if (!usesLedger(runMode)) {
515
+ let workspaceRuntime;
516
+ let nativeControl;
517
+ let stopWorkspaceBrowserGateway;
518
+ let stopWorkspace;
519
+ let workspaceRendezvous;
520
+ let publishedGrantState;
521
+ let publishingGrants = false;
522
+ const workspaceChanged = () => {
523
+ security.workspaceChanged();
524
+ if (!workspaceRuntime || !workspaceRendezvous || publishingGrants)
525
+ return;
526
+ let state;
527
+ try {
528
+ const { generation, head, leaseUntil, leaseOrder } = workspaceRuntime.snapshot;
529
+ state = JSON.stringify([generation, head, leaseOrder ?? leaseUntil]);
530
+ }
531
+ catch {
532
+ return;
533
+ }
534
+ if (state === publishedGrantState)
535
+ return;
536
+ publishingGrants = true;
537
+ void workspaceRendezvous.refreshGrants().then(() => { publishedGrantState = state; })
538
+ .catch(() => { })
539
+ .finally(() => { publishingGrants = false; });
540
+ };
541
+ if (workspaceConfigured) {
542
+ workspaceRuntime = await WorkspaceRuntime.open(dataDir, bridgeId, browserOrigin);
543
+ const identity = workspaceRuntime.identity;
544
+ if (updateRestart && (identity.endpoint.id !== updateRestart.endpointId || identity.endpoint.ownerId !== updateRestart.ownerId))
545
+ throw new Error('Workspace restart identity mismatch');
546
+ auth = { ownerId: identity.endpoint.ownerId, userId: identity.endpoint.ownerId, token: '', centrifugoUrl: 'ws://127.0.0.1/disabled' };
547
+ security = new BridgeSecurityService(identity, bridgeId, dataDir, { workspace: workspaceRuntime, relayUserId: auth.userId, browserOrigin, localOrigin });
548
+ releaseForRestart = async () => {
549
+ workspaceRendezvous?.close();
550
+ stopWorkspaceBrowserGateway?.();
551
+ stopWorkspace?.();
552
+ localApiServer.stop();
553
+ try {
554
+ await nativeControl?.close();
555
+ }
556
+ finally {
557
+ await security.close();
558
+ }
559
+ };
560
+ localApiServer.setWorkspaceBrowserAccess(workspaceRuntime.browserAccess);
561
+ stopWorkspace = await workspaceRuntime.listen(workspaceChanged);
562
+ await security.policy.provisionLocalEndpoint((await loadOrCreateIdentity(dataDir, auth.ownerId, 'local-cli')).endpoint);
563
+ }
564
+ else if (!usesLedger(runMode)) {
464
565
  // Solo and --local: identity is synthesized locally (contract S2/S10); no account, no ledger, no relay token by proof.
465
566
  const boundAtStartup = await readBoundBridgeIdentity(dataDir);
466
567
  if (updateRestart && (!boundAtStartup || boundAtStartup.identity.endpoint.id !== updateRestart.endpointId ||
@@ -495,13 +596,14 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
495
596
  else {
496
597
  // ----- ACCOUNT MODE: the passkey ledger (CONTRACT C5) -----
497
598
  const server = createLedgerServer({ apiUrl: opts.apiUrl });
599
+ const fetchLedger = (id) => networkLocalOnly ? Promise.reject(new Error('Local-only mode')) : server.fetchLedger(id);
498
600
  // Steps 3-4: pair when unpaired, recover the replica when needed, then this bridge's own status, before any network identity use.
499
601
  const startup = await startAccountIdentity({
500
602
  // A helper-started bridge (even one whose context a reset discarded) has no terminal for the pairing link.
501
- dataDir, bridgeId, allowPairing: !launchedByUpdate,
603
+ dataDir, bridgeId, allowPairing: !launchedByUpdate && !networkLocalOnly,
502
604
  pair: (keys, store) => runLedgerPairing({ apiUrl: opts.apiUrl, dataDir, bridgeId, label: osHostname(), identity: keys, store,
503
605
  bindIdentity: accountId => bindLedgerIdentity(dataDir, accountId), print: line => console.log(line) }),
504
- fetchLedger: accountId => server.fetchLedger(accountId),
606
+ fetchLedger,
505
607
  });
506
608
  if (startup.kind === 'revoked') {
507
609
  await revokedRestart();
@@ -515,7 +617,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
515
617
  const localIdentity = await loadOrCreateIdentity(dataDir, bound.accountId, 'local-cli');
516
618
  const ledgerSecurity = new BridgeSecurityService({ endpoint: bound.endpoint, keyPair: bound.keyPair }, bridgeId, dataDir, {
517
619
  relayUserId: bound.accountId, browserOrigin, localOrigin,
518
- ledger: { store: startup.store, bridgeId, authPublicKey: bound.authPublicKey, fetchLedger: () => server.fetchLedger(bound.accountId) },
620
+ ledger: { store: startup.store, bridgeId, authPublicKey: bound.authPublicKey, fetchLedger: () => fetchLedger(bound.accountId) },
519
621
  });
520
622
  security = ledgerSecurity;
521
623
  releaseForRestart = async () => { localApiServer.stop(); await ledgerSecurity.close(); };
@@ -528,65 +630,70 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
528
630
  await revokedRestart();
529
631
  return;
530
632
  }
531
- const relay = createAccountRelay({
532
- apiUrl: opts.apiUrl, accountId: bound.accountId, bridgeId, authPrivateKey: bound.authPrivateKey, security: ledgerSecurity,
533
- store: startup.store, server, hostname: () => osHostname(), localPort: () => hookPort,
534
- relayUrlOverride: process.env.FTOWN_CENTRIFUGO_URL,
535
- // The last relay URL the server named lets a later start come up while the server is unreachable.
536
- savedRelayUrl: readSavedRelayUrl(dataDir, opts.apiUrl), onRelayUrl: url => saveRelayUrl(dataDir, url),
537
- reconnect: () => reconnectRelay(),
538
- });
539
- accountRelay = relay;
540
- releaseForRestart = async () => {
541
- await localApiServer.closeTransfers();
542
- relay.stop();
543
- localApiServer.stop();
544
- await ledgerSecurity.close();
545
- };
546
- // A browser that enrolled moments ago may not be in this replica yet: its refused request pulls the server ledger (rate-limited),
547
- // so the browser's retry succeeds without waiting for the relay.
548
- if (!subscribeApprovalRequired(ledgerSecurity, () => relay.onUnknownEndpoint())) {
549
- console.warn('[Bridge] This security service has no approval-required signal; new browsers wait for the relay ledger update.');
633
+ if (networkLocalOnly) {
634
+ auth = { ownerId: bound.accountId, userId: bound.accountId, token: '', centrifugoUrl: 'ws://127.0.0.1/disabled' };
550
635
  }
551
- // Only this bridge's own ledger endpoint is published, authenticated by its relay token.
552
- // An active member of its own history may hold the only copy of it: a refusal never makes it exit or advise a reset.
553
- const holdsHistory = () => !bridgeRevoked && ledgerSecurity.ledgerStatus().own === 'active';
554
- const registrar = createEndpointRegistrar({
555
- register: token => registerBridgeEndpoint({ apiUrl: opts.apiUrl, token, endpoint: bound.endpoint, bridgeId, label: osHostname() }),
556
- tokens: relay.tokens, bridgeRevoked: () => bridgeRevoked, held: holdsHistory, log: line => console.warn(line),
557
- });
558
- accountRegistrar = registrar;
559
- // Step 5: a refusal of a computer that holds its own history starts offline (with the held-history notice); any other refusal exits;
560
- // a temporary failure starts offline (local API, sessions) and keeps retrying in the background.
561
- const relayStart = await startRelay({ getToken: () => relay.tokens.getToken(), relayUrl: () => relay.relayUrl(),
562
- bridgeRevoked: () => bridgeRevoked, apiUrl: opts.apiUrl, held: () => holdsHistory() ? heldHistoryNotice(ledgerSecurity.uniqueHistory()) : null });
563
- if (relayStart.kind === 'revoked') {
564
- await revokedRestart();
565
- return;
566
- }
567
- if (relayStart.kind === 'exit')
568
- return fail(relayStart.message);
569
- if (relayStart.kind === 'online') {
570
- const registration = await registrar.registerNow(relayStart.token);
571
- if (registration.kind === 'revoked') {
636
+ else {
637
+ const relay = createAccountRelay({
638
+ apiUrl: opts.apiUrl, accountId: bound.accountId, bridgeId, authPrivateKey: bound.authPrivateKey, security: ledgerSecurity,
639
+ store: startup.store, server, hostname: () => osHostname(), localPort: () => hookPort,
640
+ relayUrlOverride: process.env.FTOWN_CENTRIFUGO_URL,
641
+ // The last relay URL the server named lets a later start come up while the server is unreachable.
642
+ savedRelayUrl: readSavedRelayUrl(dataDir, opts.apiUrl), onRelayUrl: url => saveRelayUrl(dataDir, url),
643
+ reconnect: () => reconnectRelay(),
644
+ });
645
+ accountRelay = relay;
646
+ releaseForRestart = async () => {
647
+ await localApiServer.closeTransfers();
648
+ relay.stop();
649
+ localApiServer.stop();
650
+ await ledgerSecurity.close();
651
+ };
652
+ // A browser that enrolled moments ago may not be in this replica yet: its refused request pulls the server ledger (rate-limited),
653
+ // so the browser's retry succeeds without waiting for the relay.
654
+ if (!subscribeApprovalRequired(ledgerSecurity, () => relay.onUnknownEndpoint())) {
655
+ console.warn('[Bridge] This security service has no approval-required signal; new browsers wait for the relay ledger update.');
656
+ }
657
+ // Only this bridge's own ledger endpoint is published, authenticated by its relay token.
658
+ // An active member of its own history may hold the only copy of it: a refusal never makes it exit or advise a reset.
659
+ const holdsHistory = () => !bridgeRevoked && ledgerSecurity.ledgerStatus().own === 'active';
660
+ const registrar = createEndpointRegistrar({
661
+ register: token => registerBridgeEndpoint({ apiUrl: opts.apiUrl, token, endpoint: bound.endpoint, bridgeId, label: osHostname() }),
662
+ tokens: relay.tokens, bridgeRevoked: () => bridgeRevoked, held: holdsHistory, log: line => console.warn(line),
663
+ });
664
+ accountRegistrar = registrar;
665
+ // Step 5: a refusal of a computer that holds its own history starts offline (with the held-history notice); any other refusal exits;
666
+ // a temporary failure starts offline (local API, sessions) and keeps retrying in the background.
667
+ const relayStart = await startRelay({ getToken: () => relay.tokens.getToken(), relayUrl: () => relay.relayUrl(),
668
+ bridgeRevoked: () => bridgeRevoked, apiUrl: opts.apiUrl, held: () => holdsHistory() ? heldHistoryNotice(ledgerSecurity.uniqueHistory()) : null });
669
+ if (relayStart.kind === 'revoked') {
572
670
  await revokedRestart();
573
671
  return;
574
672
  }
575
- if (registration.kind === 'exit')
576
- return fail(registration.message);
577
- if (registration.kind === 'retry')
673
+ if (relayStart.kind === 'exit')
674
+ return fail(relayStart.message);
675
+ if (relayStart.kind === 'online') {
676
+ const registration = await registrar.registerNow(relayStart.token);
677
+ if (registration.kind === 'revoked') {
678
+ await revokedRestart();
679
+ return;
680
+ }
681
+ if (registration.kind === 'exit')
682
+ return fail(registration.message);
683
+ if (registration.kind === 'retry')
684
+ registrar.retryInBackground();
685
+ }
686
+ else {
687
+ if (relayStart.notice)
688
+ for (const line of relayStart.notice)
689
+ console.warn(line);
690
+ else
691
+ console.warn(`[Bridge] Could not reach the ftown server (${relayStart.reason}). Starting offline with the last relay URL; reconnecting in the background.`);
578
692
  registrar.retryInBackground();
693
+ }
694
+ auth = { ownerId: bound.accountId, userId: bound.accountId, token: relayStart.kind === 'online' ? relayStart.token : '',
695
+ centrifugoUrl: relayStart.relayUrl };
579
696
  }
580
- else {
581
- if (relayStart.notice)
582
- for (const line of relayStart.notice)
583
- console.warn(line);
584
- else
585
- console.warn(`[Bridge] Could not reach the ftown server (${relayStart.reason}). Starting offline with the last relay URL; reconnecting in the background.`);
586
- registrar.retryInBackground();
587
- }
588
- auth = { ownerId: bound.accountId, userId: bound.accountId, token: relayStart.kind === 'online' ? relayStart.token : '',
589
- centrifugoUrl: relayStart.relayUrl };
590
697
  }
591
698
  const userId = auth.userId;
592
699
  const centrifugoUrl = auth.centrifugoUrl;
@@ -653,7 +760,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
653
760
  } : {};
654
761
  const centrifugo = new CentrifugoClient(centrifugoUrl, auth.token, getToken, {
655
762
  ...ledgerOptions,
656
- disabled: opts.local,
763
+ disabled: Boolean(opts.local || networkLocalOnly || workspaceRuntime),
657
764
  isSessionRetired: id => store.isRetired(id),
658
765
  // On a transport reconnect, re-publish the session snapshot. The UI does
659
766
  // not re-request its list on reconnect, so without this its session list
@@ -703,8 +810,11 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
703
810
  throw new BridgeStartingError();
704
811
  return localApiServer.dispatchSecure(message);
705
812
  };
813
+ partialStartup.push(() => centrifugo.disconnect());
706
814
  const watchRegistry = new WatchRegistry();
815
+ partialStartup.push(() => watchRegistry.dispose());
707
816
  const directPeers = new DirectPeerManager({
817
+ localOnly: networkLocalOnly || !!workspaceRuntime,
708
818
  security,
709
819
  bridgeId,
710
820
  sendSignal: (msg) => {
@@ -727,6 +837,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
727
837
  apiOrigin = new URL(opts.apiUrl).origin;
728
838
  }
729
839
  catch { /* leave empty; only localhost origins accepted */ }
840
+ partialStartup.push(() => directPeers.closeAll());
730
841
  const loopbackServer = new LoopbackPeerServer({
731
842
  security,
732
843
  bridgeId,
@@ -742,6 +853,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
742
853
  // all, so a bridge on the same network or VPN stays reachable without the relay. Connections land in the same peer manager,
743
854
  // where the encrypted hello decides what they may do. FTOWN_DIRECT_ADDRESS=0 turns the listener off.
744
855
  let addressed = null;
856
+ partialStartup.push(() => loopbackServer.closeAll(), () => addressed?.listener.stop());
745
857
  if (process.env.FTOWN_DIRECT_ADDRESS !== '0') {
746
858
  try {
747
859
  addressed = await startAddressedListener(dataDir, (pc, channel, pairId) => directPeers.adoptAddressed(pc, channel, pairId));
@@ -844,6 +956,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
844
956
  getToken: () => ledgerRelay.tokens.getToken(),
845
957
  getSession: (sessionId) => store.loadSession(sessionId),
846
958
  });
959
+ partialStartup.push(() => pushNotifier?.stop());
847
960
  const attentionStore = new AttentionStore((sessionId) => store.sessionDir(sessionId), 500, pushNotifier ? (sessionId, notice) => pushNotifier.notify(sessionId, notice) : undefined, {
848
961
  isSessionActive: async (sessionId) => {
849
962
  const session = await store.loadSession(sessionId);
@@ -853,6 +966,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
853
966
  onSubagentIdle: (signal, isCurrent) => localApiServer.notifyIdleParent(signal, isCurrent),
854
967
  });
855
968
  localApiServer.setAttentionStore(attentionStore);
969
+ partialStartup.push(() => attentionStore.stopNotifications());
856
970
  const mailStore = new MailStore((sessionId) => store.sessionDir(sessionId));
857
971
  localApiServer.setMailStore(mailStore);
858
972
  const pullRequestStatuses = new PullRequestStatusService();
@@ -908,6 +1022,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
908
1022
  }
909
1023
  }
910
1024
  });
1025
+ partialStartup.push(stopPushSessionObserver, stopBoardObserver, () => boardPublisher?.stop());
911
1026
  const handleSessionExit = (sid) => {
912
1027
  unregisterSession(sid);
913
1028
  void coordination.onSessionExit(sid).catch((err) => {
@@ -922,6 +1037,12 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
922
1037
  // Direct bridge-to-bridge links: cross-bridge requests leave the relay once a link to the peer is open.
923
1038
  let peerLinkAdmission = Promise.resolve();
924
1039
  const peerLinks = new PeerLinks({
1040
+ roster: workspaceRuntime ? new WorkspacePeerSync(dataDir, workspaceRuntime.snapshot.workspaceId, () => {
1041
+ workspaceChanged();
1042
+ peerLinks.revalidate();
1043
+ }) : undefined,
1044
+ iceServers: networkLocalOnly ? [] : undefined,
1045
+ hybridTls: workspaceRuntime?.tls ?? (accountRelay || networkLocalOnly ? loadPeerTlsPolicy(dataDir, security.endpoint.id, process.env.FTOWN_PEER_HYBRID_TLS) : undefined),
925
1046
  bridgeId, endpointId: security.endpoint.id, peers: () => security.peerBridges(),
926
1047
  onRevoked: listener => security.onRevoked(listener),
927
1048
  execute: (packet, route) => executeSecurePacket(security, packet, route, async (message) => {
@@ -934,8 +1055,30 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
934
1055
  return accepted;
935
1056
  }),
936
1057
  });
1058
+ partialStartup.push(() => peerLinks.closeAll());
1059
+ if (peerLinks.hybridTls?.independentTrust) {
1060
+ const manualPeerAddresses = parsePeerLanAddressOverrides(process.env.FTOWN_PEER_LAN_ADDRESSES);
1061
+ await startPeerLan({
1062
+ statePort: workspaceRuntime ? Number(process.env.FTOWN_WORKSPACE_ENROLLMENT_PORT ?? 47642) : undefined,
1063
+ links: peerLinks, dataDir, scope: workspaceRuntime?.snapshot.workspaceId ?? auth.ownerId,
1064
+ peers: () => security.peerBridges(),
1065
+ discoveryIdentity: { endpointId: security.endpoint.id, keyPair: security.identity.keyPair },
1066
+ strictDiscovery: workspaceRuntime?.snapshot.policy === 'strict',
1067
+ bootstrap: peer => manualPeerAddresses.get(peer.bridgeId)
1068
+ ?? workspaceRuntime?.peerAddresses(peer.endpoint.id),
1069
+ port: process.env.FTOWN_PEER_LAN_PORT === undefined ? undefined : Number(process.env.FTOWN_PEER_LAN_PORT),
1070
+ }).catch(error => {
1071
+ if (workspaceRuntime && networkLocalOnly)
1072
+ throw error;
1073
+ console.warn('[Peers] Could not start LAN listener:', error instanceof Error ? error.message : String(error));
1074
+ });
1075
+ }
937
1076
  const peerControl = new PeerControl(security, centrifugo, peerLinks);
1077
+ workspaceRendezvous = workspaceRuntime ? attachWorkspaceRendezvous(workspaceRuntime, security, peerLinks, peerControl, localApiServer, {
1078
+ localOnly: networkLocalOnly, brokerOrigin: browserOrigin, presence: process.env.FTOWN_WORKSPACE_PRESENCE !== '0',
1079
+ }) : undefined;
938
1080
  teamOutbox = new PeerTeamOutbox(join(dataDir, 'team-outbox-' + security.endpoint.id + '.sqlite'), peerControl);
1081
+ partialStartup.push(() => teamOutbox.close());
939
1082
  const hierarchyWrites = new SessionHierarchyWrites();
940
1083
  const sessionFactoryDeps = {
941
1084
  hierarchyWrites,
@@ -1053,13 +1196,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1053
1196
  publishSessionUpdate: (session) => centrifugo.publishSessionUpdate(userId, session),
1054
1197
  });
1055
1198
  // Session operations shared by local HTTP and dashboard RPC.
1056
- // Which launch defaults the installed codex and claude understand; until it answers, the current defaults are assumed.
1057
- void probeLaunchCapabilities().then(() => {
1058
- if (!launchCapabilities.codexApproveForMe)
1059
- console.log('[Bridge] codex predates --approve-for-me: codex sessions keep the bypass flags');
1060
- if (!launchCapabilities.claudeAutoMode)
1061
- console.log('[Bridge] claude predates auto mode: claude sessions keep their default permission mode');
1062
- }).catch(() => { });
1199
+ partialStartup.push(() => terminalOutput.stop());
1063
1200
  const sessionController = new SessionController({
1064
1201
  store,
1065
1202
  runner,
@@ -1088,7 +1225,9 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1088
1225
  notifyCommitted: (session, sender) => localApiServer.notifyCommittedMail(session, sender, true),
1089
1226
  });
1090
1227
  pullRequestEvents.setTreeEventEmitter((session, kind, summary, ref) => coordination.emit(session, kind, summary, ref));
1091
- pullRequestEvents.start();
1228
+ partialStartup.push(() => pullRequestEvents.stop());
1229
+ if (!networkLocalOnly)
1230
+ pullRequestEvents.start();
1092
1231
  const updateHome = realpathSync(homedir());
1093
1232
  const stagingRoot = join(updateHome, '.ftown', 'updates');
1094
1233
  const canonicalLaunch = (() => {
@@ -1103,7 +1242,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1103
1242
  bridgeId, currentVersion: BRIDGE_VERSION, stagingRoot, resuming: !!updateRestart,
1104
1243
  restart: { mode: opts.local ? 'local' : 'cloud', home: updateHome, dataDir: join(updateHome, '.ftown', 'data'), cwd: process.cwd(),
1105
1244
  apiUrl: opts.apiUrl, bridgeId, ownerId: auth.ownerId, endpointId: security.endpoint.id },
1106
- support: () => !opts.allowUpdates ? 'not_enabled' : process.platform === 'win32' || !!opts.solo ||
1245
+ support: () => !opts.allowUpdates || networkLocalOnly || workspaceConfigured ? 'not_enabled' : process.platform === 'win32' || !!opts.solo ||
1107
1246
  !canonicalLaunch || realpathSync(dataDir) !== realpathSync(defaultDataDir) ? 'unsupported_launch' : null,
1108
1247
  busy: async () => {
1109
1248
  if (!resurrectionComplete || watchReattachInFlight.size)
@@ -1159,6 +1298,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1159
1298
  catch { /* already gone or owned by a newer bridge */ }
1160
1299
  };
1161
1300
  process.on('exit', cleanupPointer);
1301
+ partialStartup.push(() => { process.off('exit', cleanupPointer); cleanupPointer(); });
1162
1302
  function publishScreenDump(sid) {
1163
1303
  terminalOutput.publishScreenDump(sid);
1164
1304
  }
@@ -1244,15 +1384,23 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1244
1384
  };
1245
1385
  localApiServer.setHandoff(runHandoff);
1246
1386
  const projectBoards = new ProjectBoardStore(dataDir, bridgeId);
1387
+ const authoritativeRoster = () => {
1388
+ if (!workspaceRuntime)
1389
+ return true;
1390
+ const roster = workspaceRuntime.snapshot;
1391
+ return roster.leaseUntil > Date.now() || roster.revoked.includes(security.endpoint.id);
1392
+ };
1247
1393
  const peerCache = await startPeerSessionCache(peerControl, join(dataDir, "peer-sessions-" + security.endpoint.id + ".json"), rows => {
1248
1394
  for (const id of new Set(rows.filter(row => row.parentBridgeId === bridgeId).map(row => row.parentSessionId))) {
1249
1395
  if (id)
1250
1396
  scheduleBoard(id);
1251
1397
  }
1252
- });
1398
+ }, authoritativeRoster);
1399
+ partialStartup.push(() => peerCache.stop());
1253
1400
  remoteChildren = async (managerId) => (await peerCache.list()).flatMap(child => child.parentSessionId === managerId && child.parentBridgeId === bridgeId && child.status !== 'disconnected'
1254
1401
  ? [{ ...child, status: child.status }] : []);
1255
- const projectDirectory = await startPeerProjectDirectory(peerControl, join(dataDir, "peer-projects-" + security.endpoint.id + ".json"));
1402
+ const projectDirectory = await startPeerProjectDirectory(peerControl, join(dataDir, "peer-projects-" + security.endpoint.id + ".json"), authoritativeRoster);
1403
+ partialStartup.push(() => projectDirectory.stop());
1256
1404
  const storageMoves = new ProjectStorageMoves(dataDir, bridgeId, projectBoards, peerControl, projectDirectory.rememberMove);
1257
1405
  localApiServer.setLocalProjects(() => projectBoards.list());
1258
1406
  const findDiscussionSession = (origin, id) => discussionSession(bridgeId, sid => store.loadSession(sid), peerControl, origin, id);
@@ -1345,6 +1493,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1345
1493
  .finally(() => { maintenance = undefined; });
1346
1494
  }, 30_000);
1347
1495
  ticketTimer.unref();
1496
+ partialStartup.push(() => clearInterval(ticketTimer));
1348
1497
  const hostResources = hostResourceSampler(dataDir);
1349
1498
  const dispatchCommand = async (message) => {
1350
1499
  if (!ready)
@@ -1382,6 +1531,14 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1382
1531
  relayUserId: userId }, dispatchCommand, updateEffects);
1383
1532
  localApiServer.setPeerControl(peerControl, peerLinks, join(dataDir, 'folder-transfers'), peerCache.list, hostResources);
1384
1533
  localApiServer.startInstructionSync(security.bridgeId);
1534
+ if (workspaceRuntime) {
1535
+ stopWorkspaceBrowserGateway = await startWorkspaceBrowserGateway(workspaceRuntime, hookPort, loopbackServer);
1536
+ nativeControl = await startWorkspaceNativeControl({ dataDir, bridgeId, bridgeEndpointId: security.endpoint.id,
1537
+ policy: security.policy, ready: () => ready, sessionController, localApiServer, store, terminalManager,
1538
+ port: process.env.FTOWN_WORKSPACE_NATIVE_PORT === undefined ? undefined : Number(process.env.FTOWN_WORKSPACE_NATIVE_PORT),
1539
+ });
1540
+ workspaceRendezvous?.start();
1541
+ }
1385
1542
  // Solo: the hub child must be healthy before connecting (L1 gates the
1386
1543
  // transport, not the front). A failed hub is fatal for solo — exit cleanly
1387
1544
  // instead of crashing on an unhandled rejection.
@@ -1410,8 +1567,16 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1410
1567
  ready = true;
1411
1568
  console.log('[Bridge] Ready and listening for commands');
1412
1569
  if (bridgePointerPublished) {
1413
- // Invitations are for Solo and --local only; an account bridge trusts the browsers its passkey ledger lists.
1414
- if (opts.local || opts.solo)
1570
+ if (workspaceConfigured) {
1571
+ if (workspaceRuntime?.snapshot.writerId === security.endpoint.id) {
1572
+ console.log('[Bridge] Trusted-local workspace writer ready. Use ftown workspace owner --host <private-ip> for native enrollment. Run only sessions you trust with this account.');
1573
+ }
1574
+ else {
1575
+ console.log('[Bridge] Workspace member ready. Manage enrollment on the workspace writer.');
1576
+ }
1577
+ }
1578
+ // Legacy browser invitations are for Solo and --local; account bridges use the passkey ledger.
1579
+ else if (opts.local || opts.solo)
1415
1580
  console.log('[Bridge] Encrypted endpoint ready. Run ftown security invite to pair a browser.');
1416
1581
  else
1417
1582
  console.log('[Bridge] Encrypted endpoint ready. Browsers signed in to your account with a passkey can reach this computer.');
@@ -1434,7 +1599,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1434
1599
  if (updateRestart && !shutdownRun) {
1435
1600
  if (!bridgePointerPublished)
1436
1601
  throw new Error('Update restart pointer unavailable');
1437
- if (!opts.local)
1602
+ if (!opts.local && !networkLocalOnly && !workspaceConfigured)
1438
1603
  await centrifugo.waitUntilSecureCommandsReady(45_000);
1439
1604
  await finishUpdateRestartAdmission(updateAdmission, () => reportUpdateReady({ version: BRIDGE_VERSION, bridgeId, ownerId: auth.ownerId, endpointId: security.endpoint.id }));
1440
1605
  if (shutdownRun)
@@ -1448,11 +1613,13 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1448
1613
  }
1449
1614
  })();
1450
1615
  }, 2000);
1616
+ partialStartup.push(() => clearTimeout(startupTimer));
1451
1617
  const autoUpdateTimer = setInterval(() => {
1452
1618
  if (ready)
1453
1619
  void updates.checkAutomaticUpdate().catch(error => console.error('[Bridge] Automatic update check failed:', error));
1454
1620
  }, 30 * 60_000);
1455
1621
  autoUpdateTimer.unref();
1622
+ partialStartup.push(() => clearInterval(autoUpdateTimer));
1456
1623
  // Leaves tmux sessions running and the process alive; a revoked restart re-executes this same PID
1457
1624
  // afterwards, so the local port, pointer, relay connection and timers must all be released here.
1458
1625
  function shutdown() {
@@ -1460,6 +1627,9 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1460
1627
  console.log('\n[Bridge] Shutting down...');
1461
1628
  ready = false;
1462
1629
  clearTimeout(startupTimer);
1630
+ workspaceRendezvous?.close();
1631
+ stopWorkspaceBrowserGateway?.();
1632
+ stopWorkspace?.();
1463
1633
  clearInterval(autoUpdateTimer);
1464
1634
  clearInterval(ticketTimer);
1465
1635
  try {
@@ -1484,7 +1654,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1484
1654
  watchRegistry.dispose();
1485
1655
  centrifugo.disconnect();
1486
1656
  const drained = await Promise.allSettled([
1487
- teamOutbox.close(), localApiServer.closeTransfers(), peerCache.stop(), projectDirectory.stop(), pullRequestEvents.stop(),
1657
+ nativeControl?.close(), teamOutbox.close(), localApiServer.closeTransfers(), peerCache.stop(), projectDirectory.stop(), pullRequestEvents.stop(),
1488
1658
  maintenance, ...deliveries.values(),
1489
1659
  // An already-started resurrection can still attach a PTY. Detach once it finishes.
1490
1660
  Promise.resolve(startupWork).then(() => terminalOutput.stop()),
@@ -1527,13 +1697,28 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
1527
1697
  };
1528
1698
  process.on('SIGINT', onStopSignal);
1529
1699
  process.on('SIGTERM', onStopSignal);
1700
+ // Run optional external probes only after all required listeners have opened.
1701
+ void probeLaunchCapabilities().then(() => {
1702
+ if (!launchCapabilities.codexApproveForMe)
1703
+ console.log('[Bridge] codex predates --approve-for-me: codex sessions keep the bypass flags');
1704
+ if (!launchCapabilities.claudeAutoMode)
1705
+ console.log('[Bridge] claude predates auto mode: claude sessions keep their default permission mode');
1706
+ }).catch(() => { });
1530
1707
  });
1531
1708
  registerLocalBrowserCommands(program);
1532
1709
  try {
1533
1710
  await program.parseAsync(argv, { from: 'user' });
1711
+ partialStartup.length = 0;
1534
1712
  return 0;
1535
1713
  }
1536
1714
  catch (error) {
1715
+ // Signal every acquired resource before waiting: a pending snapshot can be blocked on a peer socket.
1716
+ // The instance remains exclusively held until all cleanup callbacks have settled.
1717
+ const settled = await Promise.allSettled(partialStartup.reverse().map(async (close) => close()));
1718
+ for (const result of settled)
1719
+ if (result.status === 'rejected')
1720
+ console.warn('[Bridge] Startup cleanup failed:', result.reason);
1721
+ releaseFailedInstance?.();
1537
1722
  if (error instanceof CommanderError)
1538
1723
  return error.exitCode;
1539
1724
  throw error;