ftown-bridge 0.30.80 → 0.30.83
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.
- package/dist/direct-transport/dtls-identity.d.ts +1 -1
- package/dist/direct-transport/dtls-identity.js +11 -5
- package/dist/direct-transport/dtls-identity.js.map +1 -1
- package/dist/direct-transport/loopback-server.d.ts +6 -1
- package/dist/direct-transport/loopback-server.js +19 -1
- package/dist/direct-transport/loopback-server.js.map +1 -1
- package/dist/direct-transport/peer-manager.d.ts +3 -0
- package/dist/direct-transport/peer-manager.js +3 -1
- package/dist/direct-transport/peer-manager.js.map +1 -1
- package/dist/ftown-cli.d.ts +1 -1
- package/dist/ftown-cli.js +15 -3
- package/dist/ftown-cli.js.map +1 -1
- package/dist/index.js +253 -86
- package/dist/index.js.map +1 -1
- package/dist/local-api-server.d.ts +6 -0
- package/dist/local-api-server.js +39 -1
- package/dist/local-api-server.js.map +1 -1
- package/dist/peer-control.d.ts +16 -10
- package/dist/peer-control.js +103 -33
- package/dist/peer-control.js.map +1 -1
- package/dist/peer-lan-address.d.ts +8 -0
- package/dist/peer-lan-address.js +50 -0
- package/dist/peer-lan-address.js.map +1 -0
- package/dist/peer-lan-hints.d.ts +10 -0
- package/dist/peer-lan-hints.js +20 -0
- package/dist/peer-lan-hints.js.map +1 -0
- package/dist/peer-lan.d.ts +26 -0
- package/dist/peer-lan.js +283 -0
- package/dist/peer-lan.js.map +1 -0
- package/dist/peer-link.d.ts +82 -15
- package/dist/peer-link.js +256 -35
- package/dist/peer-link.js.map +1 -1
- package/dist/peer-pq-cli.d.ts +3 -0
- package/dist/peer-pq-cli.js +66 -0
- package/dist/peer-pq-cli.js.map +1 -0
- package/dist/peer-pq-identity.d.ts +11 -0
- package/dist/peer-pq-identity.js +126 -0
- package/dist/peer-pq-identity.js.map +1 -0
- package/dist/peer-pq-trust.d.ts +23 -0
- package/dist/peer-pq-trust.js +140 -0
- package/dist/peer-pq-trust.js.map +1 -0
- package/dist/peer-session-cache.d.ts +2 -2
- package/dist/peer-session-cache.js +10 -7
- package/dist/peer-session-cache.js.map +1 -1
- package/dist/peer-tls-channel.d.ts +18 -0
- package/dist/peer-tls-channel.js +253 -0
- package/dist/peer-tls-channel.js.map +1 -0
- package/dist/peer-tls-policy.d.ts +3 -0
- package/dist/peer-tls-policy.js +68 -0
- package/dist/peer-tls-policy.js.map +1 -0
- package/dist/peers-cli.js +8 -1
- package/dist/peers-cli.js.map +1 -1
- package/dist/protocol/comms.d.ts +22 -0
- package/dist/protocol/comms.js +48 -0
- package/dist/protocol/comms.js.map +1 -0
- package/dist/protocol/peer-routing.d.ts +1 -0
- package/dist/protocol/peer-routing.js +1 -0
- package/dist/protocol/peer-routing.js.map +1 -1
- package/dist/security/bridge/direct.js +1 -1
- package/dist/security/bridge/direct.js.map +1 -1
- package/dist/security/bridge/execute.js +3 -3
- package/dist/security/bridge/execute.js.map +1 -1
- package/dist/security/bridge/permissions.js +3 -1
- package/dist/security/bridge/permissions.js.map +1 -1
- package/dist/security/bridge/policy.d.ts +14 -4
- package/dist/security/bridge/policy.js +79 -10
- package/dist/security/bridge/policy.js.map +1 -1
- package/dist/security/bridge/security.d.ts +8 -4
- package/dist/security/bridge/security.js +97 -27
- package/dist/security/bridge/security.js.map +1 -1
- package/dist/security/protocol.d.ts +2 -0
- package/dist/security-cli.js +6 -0
- package/dist/security-cli.js.map +1 -1
- package/dist/start-commands.js +19 -5
- package/dist/start-commands.js.map +1 -1
- package/dist/workspace/authority.d.ts +274 -0
- package/dist/workspace/authority.js +732 -0
- package/dist/workspace/authority.js.map +1 -0
- package/dist/workspace/browser-access.d.ts +15 -0
- package/dist/workspace/browser-access.js +145 -0
- package/dist/workspace/browser-access.js.map +1 -0
- package/dist/workspace/browser-exchange.d.ts +6 -0
- package/dist/workspace/browser-exchange.js +18 -0
- package/dist/workspace/browser-exchange.js.map +1 -0
- package/dist/workspace/browser-gateway.d.ts +4 -0
- package/dist/workspace/browser-gateway.js +105 -0
- package/dist/workspace/browser-gateway.js.map +1 -0
- package/dist/workspace/browser-invitation.d.ts +50 -0
- package/dist/workspace/browser-invitation.js +79 -0
- package/dist/workspace/browser-invitation.js.map +1 -0
- package/dist/workspace/browser-qr.d.ts +2 -0
- package/dist/workspace/browser-qr.js +11 -0
- package/dist/workspace/browser-qr.js.map +1 -0
- package/dist/workspace/cli.d.ts +1 -0
- package/dist/workspace/cli.js +441 -0
- package/dist/workspace/cli.js.map +1 -0
- package/dist/workspace/continuity.d.ts +23 -0
- package/dist/workspace/continuity.js +94 -0
- package/dist/workspace/continuity.js.map +1 -0
- package/dist/workspace/cutover-commands.d.ts +2 -0
- package/dist/workspace/cutover-commands.js +56 -0
- package/dist/workspace/cutover-commands.js.map +1 -0
- package/dist/workspace/cutover-storage.d.ts +11 -0
- package/dist/workspace/cutover-storage.js +90 -0
- package/dist/workspace/cutover-storage.js.map +1 -0
- package/dist/workspace/cutover.d.ts +104 -0
- package/dist/workspace/cutover.js +596 -0
- package/dist/workspace/cutover.js.map +1 -0
- package/dist/workspace/device.d.ts +43 -0
- package/dist/workspace/device.js +268 -0
- package/dist/workspace/device.js.map +1 -0
- package/dist/workspace/enrollment.d.ts +61 -0
- package/dist/workspace/enrollment.js +241 -0
- package/dist/workspace/enrollment.js.map +1 -0
- package/dist/workspace/lan-discovery-network.d.ts +11 -0
- package/dist/workspace/lan-discovery-network.js +175 -0
- package/dist/workspace/lan-discovery-network.js.map +1 -0
- package/dist/workspace/lan-discovery-secrets.d.ts +6 -0
- package/dist/workspace/lan-discovery-secrets.js +90 -0
- package/dist/workspace/lan-discovery-secrets.js.map +1 -0
- package/dist/workspace/lan-discovery-wire.d.ts +27 -0
- package/dist/workspace/lan-discovery-wire.js +84 -0
- package/dist/workspace/lan-discovery-wire.js.map +1 -0
- package/dist/workspace/lan-discovery.d.ts +22 -0
- package/dist/workspace/lan-discovery.js +168 -0
- package/dist/workspace/lan-discovery.js.map +1 -0
- package/dist/workspace/listener.d.ts +56 -0
- package/dist/workspace/listener.js +354 -0
- package/dist/workspace/listener.js.map +1 -0
- package/dist/workspace/native-client-assets.d.ts +3 -0
- package/dist/workspace/native-client-assets.js +184 -0
- package/dist/workspace/native-client-assets.js.map +1 -0
- package/dist/workspace/native-client-bridge.d.ts +22 -0
- package/dist/workspace/native-client-bridge.js +70 -0
- package/dist/workspace/native-client-bridge.js.map +1 -0
- package/dist/workspace/native-client-cli.d.ts +3 -0
- package/dist/workspace/native-client-cli.js +164 -0
- package/dist/workspace/native-client-cli.js.map +1 -0
- package/dist/workspace/native-client-dashboard.d.ts +10 -0
- package/dist/workspace/native-client-dashboard.js +136 -0
- package/dist/workspace/native-client-dashboard.js.map +1 -0
- package/dist/workspace/native-client-protocol.d.ts +76 -0
- package/dist/workspace/native-client-protocol.js +197 -0
- package/dist/workspace/native-client-protocol.js.map +1 -0
- package/dist/workspace/native-client-tls.d.ts +25 -0
- package/dist/workspace/native-client-tls.js +101 -0
- package/dist/workspace/native-client-tls.js.map +1 -0
- package/dist/workspace/peer-sync.d.ts +46 -0
- package/dist/workspace/peer-sync.js +246 -0
- package/dist/workspace/peer-sync.js.map +1 -0
- package/dist/workspace/pq-provider.d.ts +1 -0
- package/dist/workspace/pq-provider.js +48 -0
- package/dist/workspace/pq-provider.js.map +1 -0
- package/dist/workspace/reenroll.d.ts +21 -0
- package/dist/workspace/reenroll.js +222 -0
- package/dist/workspace/reenroll.js.map +1 -0
- package/dist/workspace/remote-enrollment-peer.d.ts +17 -0
- package/dist/workspace/remote-enrollment-peer.js +149 -0
- package/dist/workspace/remote-enrollment-peer.js.map +1 -0
- package/dist/workspace/remote-enrollment-signal.d.ts +22 -0
- package/dist/workspace/remote-enrollment-signal.js +38 -0
- package/dist/workspace/remote-enrollment-signal.js.map +1 -0
- package/dist/workspace/remote-enrollment.d.ts +17 -0
- package/dist/workspace/remote-enrollment.js +350 -0
- package/dist/workspace/remote-enrollment.js.map +1 -0
- package/dist/workspace/rendezvous-client.d.ts +24 -0
- package/dist/workspace/rendezvous-client.js +107 -0
- package/dist/workspace/rendezvous-client.js.map +1 -0
- package/dist/workspace/rendezvous-crypto.d.ts +15 -0
- package/dist/workspace/rendezvous-crypto.js +100 -0
- package/dist/workspace/rendezvous-crypto.js.map +1 -0
- package/dist/workspace/rendezvous-runtime.d.ts +13 -0
- package/dist/workspace/rendezvous-runtime.js +23 -0
- package/dist/workspace/rendezvous-runtime.js.map +1 -0
- package/dist/workspace/rendezvous-wire.d.ts +49 -0
- package/dist/workspace/rendezvous-wire.js +92 -0
- package/dist/workspace/rendezvous-wire.js.map +1 -0
- package/dist/workspace/rendezvous.d.ts +65 -0
- package/dist/workspace/rendezvous.js +362 -0
- package/dist/workspace/rendezvous.js.map +1 -0
- package/dist/workspace/runtime.d.ts +24 -0
- package/dist/workspace/runtime.js +130 -0
- package/dist/workspace/runtime.js.map +1 -0
- package/dist/workspace/writer-only.d.ts +9 -0
- package/dist/workspace/writer-only.js +120 -0
- package/dist/workspace/writer-only.js.map +1 -0
- package/package.json +4 -2
- 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 } 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';
|
|
@@ -9,7 +15,6 @@ import { fileURLToPath } from 'node:url';
|
|
|
9
15
|
import { mkdirSync, readFileSync, writeFileSync, unlinkSync, realpathSync, chmodSync } 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';
|
|
@@ -129,12 +138,16 @@ export async function finishUpdateRestartAdmission(admission, reportReady) {
|
|
|
129
138
|
export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
130
139
|
const isWsl2 = deps.isWsl2 ?? detectWsl2;
|
|
131
140
|
const program = new Commander();
|
|
141
|
+
// runBridge is also embedded in CLI callers. A rejected start must release its handles without exiting their process.
|
|
142
|
+
const partialStartup = [];
|
|
143
|
+
let releaseFailedInstance;
|
|
132
144
|
program.exitOverride();
|
|
133
145
|
configureUpdateOptions(program);
|
|
134
146
|
program
|
|
135
147
|
.name(commandName)
|
|
136
148
|
.description('ftown orchestrator bridge for Centrifugo')
|
|
137
149
|
.option('--local', 'Local browser control only: no cloud account or connection')
|
|
150
|
+
.option('--local-only', 'Connect paired devices over private networks without hosted rendezvous or public STUN')
|
|
138
151
|
.option('--solo', 'Single-port LAN deployment: no account service, managed hub + panel children, key-based auth')
|
|
139
152
|
.option('--port <port>', 'Public port for --solo front (default: see DEFAULT_SOLO_PORT)')
|
|
140
153
|
.option('--rotate-key', 'With --solo: regenerate the access key, print the new banner, exit (offline)')
|
|
@@ -147,6 +160,8 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
147
160
|
program.error('--local and --solo cannot be combined');
|
|
148
161
|
if ((opts.local || opts.solo) && opts.newIdentity)
|
|
149
162
|
program.error('--new-identity requires cloud mode');
|
|
163
|
+
if (opts.rotateKey && !opts.solo)
|
|
164
|
+
program.error('--rotate-key requires --solo');
|
|
150
165
|
const apiUrl = new URL(opts.apiUrl);
|
|
151
166
|
const isLocalHost = apiUrl.hostname === 'localhost' ||
|
|
152
167
|
apiUrl.hostname === '127.0.0.1' ||
|
|
@@ -164,12 +179,19 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
164
179
|
const dataDir = opts.dataDir ? resolve(opts.dataDir) : defaultDataDir;
|
|
165
180
|
// No bridge starts, and no identity is reset, while an update holds the reservation.
|
|
166
181
|
assertUpdateReservationAllowed(homedir());
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
182
|
+
const instance = await acquireReadyWorkspaceBridgeInstance(dataDir);
|
|
183
|
+
// Hold ownership through teardown, including partial startup failures. The update
|
|
184
|
+
// helper starts its successor only after this process exits.
|
|
185
|
+
const releaseInstance = () => instance.close();
|
|
186
|
+
process.once('exit', releaseInstance);
|
|
187
|
+
releaseFailedInstance = () => { process.off('exit', releaseInstance); releaseInstance(); };
|
|
188
|
+
const workspaceConfigured = workspaceExists(dataDir);
|
|
189
|
+
const networkLocalOnly = Boolean(opts.localOnly);
|
|
190
|
+
if (workspaceConfigured && (opts.newIdentity || opts.local || opts.solo || opts.bridgeId)) {
|
|
191
|
+
program.error('This data directory has a workspace identity. Start it with ftown start or ftown start --local-only.');
|
|
172
192
|
}
|
|
193
|
+
if (networkLocalOnly && (opts.solo || opts.newIdentity || opts.local))
|
|
194
|
+
program.error('--local-only requires a paired bridge.');
|
|
173
195
|
const runMode = bridgeMode(opts);
|
|
174
196
|
// Restart context is authenticated by the private helper channel before any mutation. It is read before any reset because a
|
|
175
197
|
// helper-started bridge has no visible terminal: it must never print a pairing link (an invalid context matters only below).
|
|
@@ -183,7 +205,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
183
205
|
}
|
|
184
206
|
const launchedByUpdate = launchContext !== null || launchContextError !== null;
|
|
185
207
|
// 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,
|
|
208
|
+
const resetOutcome = workspaceConfigured ? { kind: 'continue', reset: null } : resetIdentityForStart({ dataDir, mode: runMode, newIdentity: Boolean(opts.newIdentity), updateRestart: launchedByUpdate,
|
|
187
209
|
log: line => console.log(line) });
|
|
188
210
|
if (resetOutcome.kind === 'exit') {
|
|
189
211
|
console.log(resetOutcome.message);
|
|
@@ -249,6 +271,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
249
271
|
// Signed revocation of this bridgeId restarts the process as a fresh install, at most once.
|
|
250
272
|
// The re-exec keeps this PID, so whatever startup has acquired so far is released first.
|
|
251
273
|
let releaseForRestart = async () => { };
|
|
274
|
+
partialStartup.push(() => releaseForRestart());
|
|
252
275
|
// Mirrors the update coordinator's receipts; an active operation holds the reservation under this PID.
|
|
253
276
|
let updatePhase = null;
|
|
254
277
|
const revokedRestart = createRevokedRestart({
|
|
@@ -258,9 +281,6 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
258
281
|
});
|
|
259
282
|
// L4: --rotate-key short-circuits BEFORE any listener binds (exit 0,
|
|
260
283
|
// nothing started). Without --solo it is an argument error.
|
|
261
|
-
if (opts.rotateKey && !opts.solo) {
|
|
262
|
-
program.error('--rotate-key requires --solo');
|
|
263
|
-
}
|
|
264
284
|
if (opts.solo && opts.rotateKey) {
|
|
265
285
|
const raw = generateAccessKey().raw;
|
|
266
286
|
mkdirSync(join(dataDir, 'solo'), { recursive: true, mode: 0o700 });
|
|
@@ -304,6 +324,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
304
324
|
writeFileSync(localPortPath, `${hookPort}\n`, { mode: 0o600 });
|
|
305
325
|
console.log(`[Bridge] Local API server started on port ${hookPort}`);
|
|
306
326
|
const localNonce = randomBytes(16).toString('hex');
|
|
327
|
+
partialStartup.push(() => localApiServer.closeTransfers());
|
|
307
328
|
// ----- SOLO MODE (contract: bridge/src/solo/contract.ts, lifecycle L1-L4) -----
|
|
308
329
|
let solo;
|
|
309
330
|
if (opts.solo) {
|
|
@@ -365,6 +386,10 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
365
386
|
hub: { isHealthy: () => hubHealthy.up },
|
|
366
387
|
panel: { isHealthy: () => panelHealthy.up },
|
|
367
388
|
});
|
|
389
|
+
let cancelled = false;
|
|
390
|
+
let startingHub;
|
|
391
|
+
let startingPanel;
|
|
392
|
+
partialStartup.push(() => startingHub?.then(() => stopHub(dataDir)), () => startingPanel?.then(() => stopPanel(dataDir)), () => { cancelled = true; return front.close(); });
|
|
368
393
|
// Children ensured asynchronously AFTER the front listens (L1). The hub
|
|
369
394
|
// must be healthy before the Centrifugo client connects — gated below.
|
|
370
395
|
const soloDir = join(dataDir, 'solo');
|
|
@@ -372,7 +397,10 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
372
397
|
const binPath = await ensureHubBinary({ dataDir });
|
|
373
398
|
const configPath = join(soloDir, 'centrifugo.json');
|
|
374
399
|
await writeHubConfig(configPath, { port: hubPort, secret: hubSecret });
|
|
375
|
-
|
|
400
|
+
if (cancelled)
|
|
401
|
+
return;
|
|
402
|
+
startingHub = startHub({ configPath, binPath, dataDir });
|
|
403
|
+
await startingHub;
|
|
376
404
|
hubHealthy.up = true;
|
|
377
405
|
console.log('[Solo] Hub is up (private port)');
|
|
378
406
|
})();
|
|
@@ -390,12 +418,18 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
390
418
|
// Dev escape hatch: serve an already-built standalone directory.
|
|
391
419
|
const serverDir = await findPanelServerDir(resolve(process.env.FTOWN_SOLO_PANEL_DIR));
|
|
392
420
|
console.log(`[Solo] Using local panel dir: ${serverDir}`);
|
|
393
|
-
|
|
421
|
+
if (cancelled)
|
|
422
|
+
return;
|
|
423
|
+
startingPanel = startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
|
|
424
|
+
await startingPanel;
|
|
394
425
|
}
|
|
395
426
|
else {
|
|
396
427
|
const bundleDir = await ensurePanelBundle({ dataDir, version: panelVersion });
|
|
397
428
|
const serverDir = await findPanelServerDir(bundleDir);
|
|
398
|
-
|
|
429
|
+
if (cancelled)
|
|
430
|
+
return;
|
|
431
|
+
startingPanel = startPanel({ bundleDir: serverDir, port: panelPort, dataDir });
|
|
432
|
+
await startingPanel;
|
|
399
433
|
}
|
|
400
434
|
panelHealthy.up = true;
|
|
401
435
|
console.log('[Solo] Panel is up (private port)');
|
|
@@ -460,7 +494,56 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
460
494
|
let accountRegistrar;
|
|
461
495
|
/** Bound once the relay client exists: a relay refused earlier reconnects when the key is accepted again. */
|
|
462
496
|
let reconnectRelay = () => { };
|
|
463
|
-
|
|
497
|
+
let workspaceRuntime;
|
|
498
|
+
let nativeControl;
|
|
499
|
+
let stopWorkspaceBrowserGateway;
|
|
500
|
+
let stopWorkspace;
|
|
501
|
+
let workspaceRendezvous;
|
|
502
|
+
let publishedGrantState;
|
|
503
|
+
let publishingGrants = false;
|
|
504
|
+
const workspaceChanged = () => {
|
|
505
|
+
security.workspaceChanged();
|
|
506
|
+
if (!workspaceRuntime || !workspaceRendezvous || publishingGrants)
|
|
507
|
+
return;
|
|
508
|
+
let state;
|
|
509
|
+
try {
|
|
510
|
+
const { generation, head, leaseUntil, leaseOrder } = workspaceRuntime.snapshot;
|
|
511
|
+
state = JSON.stringify([generation, head, leaseOrder ?? leaseUntil]);
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (state === publishedGrantState)
|
|
517
|
+
return;
|
|
518
|
+
publishingGrants = true;
|
|
519
|
+
void workspaceRendezvous.refreshGrants().then(() => { publishedGrantState = state; })
|
|
520
|
+
.catch(() => { })
|
|
521
|
+
.finally(() => { publishingGrants = false; });
|
|
522
|
+
};
|
|
523
|
+
if (workspaceConfigured) {
|
|
524
|
+
workspaceRuntime = await WorkspaceRuntime.open(dataDir, bridgeId, browserOrigin);
|
|
525
|
+
const identity = workspaceRuntime.identity;
|
|
526
|
+
if (updateRestart && (identity.endpoint.id !== updateRestart.endpointId || identity.endpoint.ownerId !== updateRestart.ownerId))
|
|
527
|
+
throw new Error('Workspace restart identity mismatch');
|
|
528
|
+
auth = { ownerId: identity.endpoint.ownerId, userId: identity.endpoint.ownerId, token: '', centrifugoUrl: 'ws://127.0.0.1/disabled' };
|
|
529
|
+
security = new BridgeSecurityService(identity, bridgeId, dataDir, { workspace: workspaceRuntime, relayUserId: auth.userId, browserOrigin, localOrigin });
|
|
530
|
+
releaseForRestart = async () => {
|
|
531
|
+
workspaceRendezvous?.close();
|
|
532
|
+
stopWorkspaceBrowserGateway?.();
|
|
533
|
+
stopWorkspace?.();
|
|
534
|
+
localApiServer.stop();
|
|
535
|
+
try {
|
|
536
|
+
await nativeControl?.close();
|
|
537
|
+
}
|
|
538
|
+
finally {
|
|
539
|
+
await security.close();
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
localApiServer.setWorkspaceBrowserAccess(workspaceRuntime.browserAccess);
|
|
543
|
+
stopWorkspace = await workspaceRuntime.listen(workspaceChanged);
|
|
544
|
+
await security.policy.provisionLocalEndpoint((await loadOrCreateIdentity(dataDir, auth.ownerId, 'local-cli')).endpoint);
|
|
545
|
+
}
|
|
546
|
+
else if (!usesLedger(runMode)) {
|
|
464
547
|
// Solo and --local: identity is synthesized locally (contract S2/S10); no account, no ledger, no relay token by proof.
|
|
465
548
|
const boundAtStartup = await readBoundBridgeIdentity(dataDir);
|
|
466
549
|
if (updateRestart && (!boundAtStartup || boundAtStartup.identity.endpoint.id !== updateRestart.endpointId ||
|
|
@@ -495,13 +578,14 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
495
578
|
else {
|
|
496
579
|
// ----- ACCOUNT MODE: the passkey ledger (CONTRACT C5) -----
|
|
497
580
|
const server = createLedgerServer({ apiUrl: opts.apiUrl });
|
|
581
|
+
const fetchLedger = (id) => networkLocalOnly ? Promise.reject(new Error('Local-only mode')) : server.fetchLedger(id);
|
|
498
582
|
// Steps 3-4: pair when unpaired, recover the replica when needed, then this bridge's own status, before any network identity use.
|
|
499
583
|
const startup = await startAccountIdentity({
|
|
500
584
|
// A helper-started bridge (even one whose context a reset discarded) has no terminal for the pairing link.
|
|
501
|
-
dataDir, bridgeId, allowPairing: !launchedByUpdate,
|
|
585
|
+
dataDir, bridgeId, allowPairing: !launchedByUpdate && !networkLocalOnly,
|
|
502
586
|
pair: (keys, store) => runLedgerPairing({ apiUrl: opts.apiUrl, dataDir, bridgeId, label: osHostname(), identity: keys, store,
|
|
503
587
|
bindIdentity: accountId => bindLedgerIdentity(dataDir, accountId), print: line => console.log(line) }),
|
|
504
|
-
fetchLedger
|
|
588
|
+
fetchLedger,
|
|
505
589
|
});
|
|
506
590
|
if (startup.kind === 'revoked') {
|
|
507
591
|
await revokedRestart();
|
|
@@ -515,7 +599,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
515
599
|
const localIdentity = await loadOrCreateIdentity(dataDir, bound.accountId, 'local-cli');
|
|
516
600
|
const ledgerSecurity = new BridgeSecurityService({ endpoint: bound.endpoint, keyPair: bound.keyPair }, bridgeId, dataDir, {
|
|
517
601
|
relayUserId: bound.accountId, browserOrigin, localOrigin,
|
|
518
|
-
ledger: { store: startup.store, bridgeId, authPublicKey: bound.authPublicKey, fetchLedger: () =>
|
|
602
|
+
ledger: { store: startup.store, bridgeId, authPublicKey: bound.authPublicKey, fetchLedger: () => fetchLedger(bound.accountId) },
|
|
519
603
|
});
|
|
520
604
|
security = ledgerSecurity;
|
|
521
605
|
releaseForRestart = async () => { localApiServer.stop(); await ledgerSecurity.close(); };
|
|
@@ -528,65 +612,70 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
528
612
|
await revokedRestart();
|
|
529
613
|
return;
|
|
530
614
|
}
|
|
531
|
-
|
|
532
|
-
|
|
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.');
|
|
550
|
-
}
|
|
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;
|
|
615
|
+
if (networkLocalOnly) {
|
|
616
|
+
auth = { ownerId: bound.accountId, userId: bound.accountId, token: '', centrifugoUrl: 'ws://127.0.0.1/disabled' };
|
|
566
617
|
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
618
|
+
else {
|
|
619
|
+
const relay = createAccountRelay({
|
|
620
|
+
apiUrl: opts.apiUrl, accountId: bound.accountId, bridgeId, authPrivateKey: bound.authPrivateKey, security: ledgerSecurity,
|
|
621
|
+
store: startup.store, server, hostname: () => osHostname(), localPort: () => hookPort,
|
|
622
|
+
relayUrlOverride: process.env.FTOWN_CENTRIFUGO_URL,
|
|
623
|
+
// The last relay URL the server named lets a later start come up while the server is unreachable.
|
|
624
|
+
savedRelayUrl: readSavedRelayUrl(dataDir, opts.apiUrl), onRelayUrl: url => saveRelayUrl(dataDir, url),
|
|
625
|
+
reconnect: () => reconnectRelay(),
|
|
626
|
+
});
|
|
627
|
+
accountRelay = relay;
|
|
628
|
+
releaseForRestart = async () => {
|
|
629
|
+
await localApiServer.closeTransfers();
|
|
630
|
+
relay.stop();
|
|
631
|
+
localApiServer.stop();
|
|
632
|
+
await ledgerSecurity.close();
|
|
633
|
+
};
|
|
634
|
+
// A browser that enrolled moments ago may not be in this replica yet: its refused request pulls the server ledger (rate-limited),
|
|
635
|
+
// so the browser's retry succeeds without waiting for the relay.
|
|
636
|
+
if (!subscribeApprovalRequired(ledgerSecurity, () => relay.onUnknownEndpoint())) {
|
|
637
|
+
console.warn('[Bridge] This security service has no approval-required signal; new browsers wait for the relay ledger update.');
|
|
638
|
+
}
|
|
639
|
+
// Only this bridge's own ledger endpoint is published, authenticated by its relay token.
|
|
640
|
+
// An active member of its own history may hold the only copy of it: a refusal never makes it exit or advise a reset.
|
|
641
|
+
const holdsHistory = () => !bridgeRevoked && ledgerSecurity.ledgerStatus().own === 'active';
|
|
642
|
+
const registrar = createEndpointRegistrar({
|
|
643
|
+
register: token => registerBridgeEndpoint({ apiUrl: opts.apiUrl, token, endpoint: bound.endpoint, bridgeId, label: osHostname() }),
|
|
644
|
+
tokens: relay.tokens, bridgeRevoked: () => bridgeRevoked, held: holdsHistory, log: line => console.warn(line),
|
|
645
|
+
});
|
|
646
|
+
accountRegistrar = registrar;
|
|
647
|
+
// Step 5: a refusal of a computer that holds its own history starts offline (with the held-history notice); any other refusal exits;
|
|
648
|
+
// a temporary failure starts offline (local API, sessions) and keeps retrying in the background.
|
|
649
|
+
const relayStart = await startRelay({ getToken: () => relay.tokens.getToken(), relayUrl: () => relay.relayUrl(),
|
|
650
|
+
bridgeRevoked: () => bridgeRevoked, apiUrl: opts.apiUrl, held: () => holdsHistory() ? heldHistoryNotice(ledgerSecurity.uniqueHistory()) : null });
|
|
651
|
+
if (relayStart.kind === 'revoked') {
|
|
572
652
|
await revokedRestart();
|
|
573
653
|
return;
|
|
574
654
|
}
|
|
575
|
-
if (
|
|
576
|
-
return fail(
|
|
577
|
-
if (
|
|
655
|
+
if (relayStart.kind === 'exit')
|
|
656
|
+
return fail(relayStart.message);
|
|
657
|
+
if (relayStart.kind === 'online') {
|
|
658
|
+
const registration = await registrar.registerNow(relayStart.token);
|
|
659
|
+
if (registration.kind === 'revoked') {
|
|
660
|
+
await revokedRestart();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (registration.kind === 'exit')
|
|
664
|
+
return fail(registration.message);
|
|
665
|
+
if (registration.kind === 'retry')
|
|
666
|
+
registrar.retryInBackground();
|
|
667
|
+
}
|
|
668
|
+
else {
|
|
669
|
+
if (relayStart.notice)
|
|
670
|
+
for (const line of relayStart.notice)
|
|
671
|
+
console.warn(line);
|
|
672
|
+
else
|
|
673
|
+
console.warn(`[Bridge] Could not reach the ftown server (${relayStart.reason}). Starting offline with the last relay URL; reconnecting in the background.`);
|
|
578
674
|
registrar.retryInBackground();
|
|
675
|
+
}
|
|
676
|
+
auth = { ownerId: bound.accountId, userId: bound.accountId, token: relayStart.kind === 'online' ? relayStart.token : '',
|
|
677
|
+
centrifugoUrl: relayStart.relayUrl };
|
|
579
678
|
}
|
|
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
679
|
}
|
|
591
680
|
const userId = auth.userId;
|
|
592
681
|
const centrifugoUrl = auth.centrifugoUrl;
|
|
@@ -653,7 +742,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
653
742
|
} : {};
|
|
654
743
|
const centrifugo = new CentrifugoClient(centrifugoUrl, auth.token, getToken, {
|
|
655
744
|
...ledgerOptions,
|
|
656
|
-
disabled: opts.local,
|
|
745
|
+
disabled: Boolean(opts.local || networkLocalOnly || workspaceRuntime),
|
|
657
746
|
isSessionRetired: id => store.isRetired(id),
|
|
658
747
|
// On a transport reconnect, re-publish the session snapshot. The UI does
|
|
659
748
|
// not re-request its list on reconnect, so without this its session list
|
|
@@ -703,8 +792,11 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
703
792
|
throw new BridgeStartingError();
|
|
704
793
|
return localApiServer.dispatchSecure(message);
|
|
705
794
|
};
|
|
795
|
+
partialStartup.push(() => centrifugo.disconnect());
|
|
706
796
|
const watchRegistry = new WatchRegistry();
|
|
797
|
+
partialStartup.push(() => watchRegistry.dispose());
|
|
707
798
|
const directPeers = new DirectPeerManager({
|
|
799
|
+
localOnly: networkLocalOnly || !!workspaceRuntime,
|
|
708
800
|
security,
|
|
709
801
|
bridgeId,
|
|
710
802
|
sendSignal: (msg) => {
|
|
@@ -727,6 +819,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
727
819
|
apiOrigin = new URL(opts.apiUrl).origin;
|
|
728
820
|
}
|
|
729
821
|
catch { /* leave empty; only localhost origins accepted */ }
|
|
822
|
+
partialStartup.push(() => directPeers.closeAll());
|
|
730
823
|
const loopbackServer = new LoopbackPeerServer({
|
|
731
824
|
security,
|
|
732
825
|
bridgeId,
|
|
@@ -742,6 +835,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
742
835
|
// all, so a bridge on the same network or VPN stays reachable without the relay. Connections land in the same peer manager,
|
|
743
836
|
// where the encrypted hello decides what they may do. FTOWN_DIRECT_ADDRESS=0 turns the listener off.
|
|
744
837
|
let addressed = null;
|
|
838
|
+
partialStartup.push(() => loopbackServer.closeAll(), () => addressed?.listener.stop());
|
|
745
839
|
if (process.env.FTOWN_DIRECT_ADDRESS !== '0') {
|
|
746
840
|
try {
|
|
747
841
|
addressed = await startAddressedListener(dataDir, (pc, channel, pairId) => directPeers.adoptAddressed(pc, channel, pairId));
|
|
@@ -844,6 +938,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
844
938
|
getToken: () => ledgerRelay.tokens.getToken(),
|
|
845
939
|
getSession: (sessionId) => store.loadSession(sessionId),
|
|
846
940
|
});
|
|
941
|
+
partialStartup.push(() => pushNotifier?.stop());
|
|
847
942
|
const attentionStore = new AttentionStore((sessionId) => store.sessionDir(sessionId), 500, pushNotifier ? (sessionId, notice) => pushNotifier.notify(sessionId, notice) : undefined, {
|
|
848
943
|
isSessionActive: async (sessionId) => {
|
|
849
944
|
const session = await store.loadSession(sessionId);
|
|
@@ -853,6 +948,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
853
948
|
onSubagentIdle: (signal, isCurrent) => localApiServer.notifyIdleParent(signal, isCurrent),
|
|
854
949
|
});
|
|
855
950
|
localApiServer.setAttentionStore(attentionStore);
|
|
951
|
+
partialStartup.push(() => attentionStore.stopNotifications());
|
|
856
952
|
const mailStore = new MailStore((sessionId) => store.sessionDir(sessionId));
|
|
857
953
|
localApiServer.setMailStore(mailStore);
|
|
858
954
|
const pullRequestStatuses = new PullRequestStatusService();
|
|
@@ -908,6 +1004,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
908
1004
|
}
|
|
909
1005
|
}
|
|
910
1006
|
});
|
|
1007
|
+
partialStartup.push(stopPushSessionObserver, stopBoardObserver, () => boardPublisher?.stop());
|
|
911
1008
|
const handleSessionExit = (sid) => {
|
|
912
1009
|
unregisterSession(sid);
|
|
913
1010
|
void coordination.onSessionExit(sid).catch((err) => {
|
|
@@ -922,6 +1019,12 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
922
1019
|
// Direct bridge-to-bridge links: cross-bridge requests leave the relay once a link to the peer is open.
|
|
923
1020
|
let peerLinkAdmission = Promise.resolve();
|
|
924
1021
|
const peerLinks = new PeerLinks({
|
|
1022
|
+
roster: workspaceRuntime ? new WorkspacePeerSync(dataDir, workspaceRuntime.snapshot.workspaceId, () => {
|
|
1023
|
+
workspaceChanged();
|
|
1024
|
+
peerLinks.revalidate();
|
|
1025
|
+
}) : undefined,
|
|
1026
|
+
iceServers: networkLocalOnly ? [] : undefined,
|
|
1027
|
+
hybridTls: workspaceRuntime?.tls ?? (accountRelay || networkLocalOnly ? loadPeerTlsPolicy(dataDir, security.endpoint.id, process.env.FTOWN_PEER_HYBRID_TLS) : undefined),
|
|
925
1028
|
bridgeId, endpointId: security.endpoint.id, peers: () => security.peerBridges(),
|
|
926
1029
|
onRevoked: listener => security.onRevoked(listener),
|
|
927
1030
|
execute: (packet, route) => executeSecurePacket(security, packet, route, async (message) => {
|
|
@@ -934,8 +1037,30 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
934
1037
|
return accepted;
|
|
935
1038
|
}),
|
|
936
1039
|
});
|
|
1040
|
+
partialStartup.push(() => peerLinks.closeAll());
|
|
1041
|
+
if (peerLinks.hybridTls?.independentTrust) {
|
|
1042
|
+
const manualPeerAddresses = parsePeerLanAddressOverrides(process.env.FTOWN_PEER_LAN_ADDRESSES);
|
|
1043
|
+
await startPeerLan({
|
|
1044
|
+
statePort: workspaceRuntime ? Number(process.env.FTOWN_WORKSPACE_ENROLLMENT_PORT ?? 47642) : undefined,
|
|
1045
|
+
links: peerLinks, dataDir, scope: workspaceRuntime?.snapshot.workspaceId ?? auth.ownerId,
|
|
1046
|
+
peers: () => security.peerBridges(),
|
|
1047
|
+
discoveryIdentity: { endpointId: security.endpoint.id, keyPair: security.identity.keyPair },
|
|
1048
|
+
strictDiscovery: workspaceRuntime?.snapshot.policy === 'strict',
|
|
1049
|
+
bootstrap: peer => manualPeerAddresses.get(peer.bridgeId)
|
|
1050
|
+
?? workspaceRuntime?.peerAddresses(peer.endpoint.id),
|
|
1051
|
+
port: process.env.FTOWN_PEER_LAN_PORT === undefined ? undefined : Number(process.env.FTOWN_PEER_LAN_PORT),
|
|
1052
|
+
}).catch(error => {
|
|
1053
|
+
if (workspaceRuntime && networkLocalOnly)
|
|
1054
|
+
throw error;
|
|
1055
|
+
console.warn('[Peers] Could not start LAN listener:', error instanceof Error ? error.message : String(error));
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
937
1058
|
const peerControl = new PeerControl(security, centrifugo, peerLinks);
|
|
1059
|
+
workspaceRendezvous = workspaceRuntime ? attachWorkspaceRendezvous(workspaceRuntime, security, peerLinks, peerControl, localApiServer, {
|
|
1060
|
+
localOnly: networkLocalOnly, brokerOrigin: browserOrigin, presence: process.env.FTOWN_WORKSPACE_PRESENCE !== '0',
|
|
1061
|
+
}) : undefined;
|
|
938
1062
|
teamOutbox = new PeerTeamOutbox(join(dataDir, 'team-outbox-' + security.endpoint.id + '.sqlite'), peerControl);
|
|
1063
|
+
partialStartup.push(() => teamOutbox.close());
|
|
939
1064
|
const hierarchyWrites = new SessionHierarchyWrites();
|
|
940
1065
|
const sessionFactoryDeps = {
|
|
941
1066
|
hierarchyWrites,
|
|
@@ -1053,13 +1178,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1053
1178
|
publishSessionUpdate: (session) => centrifugo.publishSessionUpdate(userId, session),
|
|
1054
1179
|
});
|
|
1055
1180
|
// Session operations shared by local HTTP and dashboard RPC.
|
|
1056
|
-
|
|
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(() => { });
|
|
1181
|
+
partialStartup.push(() => terminalOutput.stop());
|
|
1063
1182
|
const sessionController = new SessionController({
|
|
1064
1183
|
store,
|
|
1065
1184
|
runner,
|
|
@@ -1088,7 +1207,9 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1088
1207
|
notifyCommitted: (session, sender) => localApiServer.notifyCommittedMail(session, sender, true),
|
|
1089
1208
|
});
|
|
1090
1209
|
pullRequestEvents.setTreeEventEmitter((session, kind, summary, ref) => coordination.emit(session, kind, summary, ref));
|
|
1091
|
-
pullRequestEvents.
|
|
1210
|
+
partialStartup.push(() => pullRequestEvents.stop());
|
|
1211
|
+
if (!networkLocalOnly)
|
|
1212
|
+
pullRequestEvents.start();
|
|
1092
1213
|
const updateHome = realpathSync(homedir());
|
|
1093
1214
|
const stagingRoot = join(updateHome, '.ftown', 'updates');
|
|
1094
1215
|
const canonicalLaunch = (() => {
|
|
@@ -1103,7 +1224,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1103
1224
|
bridgeId, currentVersion: BRIDGE_VERSION, stagingRoot, resuming: !!updateRestart,
|
|
1104
1225
|
restart: { mode: opts.local ? 'local' : 'cloud', home: updateHome, dataDir: join(updateHome, '.ftown', 'data'), cwd: process.cwd(),
|
|
1105
1226
|
apiUrl: opts.apiUrl, bridgeId, ownerId: auth.ownerId, endpointId: security.endpoint.id },
|
|
1106
|
-
support: () => !opts.allowUpdates ? 'not_enabled' : process.platform === 'win32' || !!opts.solo ||
|
|
1227
|
+
support: () => !opts.allowUpdates || networkLocalOnly || workspaceConfigured ? 'not_enabled' : process.platform === 'win32' || !!opts.solo ||
|
|
1107
1228
|
!canonicalLaunch || realpathSync(dataDir) !== realpathSync(defaultDataDir) ? 'unsupported_launch' : null,
|
|
1108
1229
|
busy: async () => {
|
|
1109
1230
|
if (!resurrectionComplete || watchReattachInFlight.size)
|
|
@@ -1159,6 +1280,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1159
1280
|
catch { /* already gone or owned by a newer bridge */ }
|
|
1160
1281
|
};
|
|
1161
1282
|
process.on('exit', cleanupPointer);
|
|
1283
|
+
partialStartup.push(() => { process.off('exit', cleanupPointer); cleanupPointer(); });
|
|
1162
1284
|
function publishScreenDump(sid) {
|
|
1163
1285
|
terminalOutput.publishScreenDump(sid);
|
|
1164
1286
|
}
|
|
@@ -1244,15 +1366,23 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1244
1366
|
};
|
|
1245
1367
|
localApiServer.setHandoff(runHandoff);
|
|
1246
1368
|
const projectBoards = new ProjectBoardStore(dataDir, bridgeId);
|
|
1369
|
+
const authoritativeRoster = () => {
|
|
1370
|
+
if (!workspaceRuntime)
|
|
1371
|
+
return true;
|
|
1372
|
+
const roster = workspaceRuntime.snapshot;
|
|
1373
|
+
return roster.leaseUntil > Date.now() || roster.revoked.includes(security.endpoint.id);
|
|
1374
|
+
};
|
|
1247
1375
|
const peerCache = await startPeerSessionCache(peerControl, join(dataDir, "peer-sessions-" + security.endpoint.id + ".json"), rows => {
|
|
1248
1376
|
for (const id of new Set(rows.filter(row => row.parentBridgeId === bridgeId).map(row => row.parentSessionId))) {
|
|
1249
1377
|
if (id)
|
|
1250
1378
|
scheduleBoard(id);
|
|
1251
1379
|
}
|
|
1252
|
-
});
|
|
1380
|
+
}, authoritativeRoster);
|
|
1381
|
+
partialStartup.push(() => peerCache.stop());
|
|
1253
1382
|
remoteChildren = async (managerId) => (await peerCache.list()).flatMap(child => child.parentSessionId === managerId && child.parentBridgeId === bridgeId && child.status !== 'disconnected'
|
|
1254
1383
|
? [{ ...child, status: child.status }] : []);
|
|
1255
|
-
const projectDirectory = await startPeerProjectDirectory(peerControl, join(dataDir, "peer-projects-" + security.endpoint.id + ".json"));
|
|
1384
|
+
const projectDirectory = await startPeerProjectDirectory(peerControl, join(dataDir, "peer-projects-" + security.endpoint.id + ".json"), authoritativeRoster);
|
|
1385
|
+
partialStartup.push(() => projectDirectory.stop());
|
|
1256
1386
|
const storageMoves = new ProjectStorageMoves(dataDir, bridgeId, projectBoards, peerControl, projectDirectory.rememberMove);
|
|
1257
1387
|
localApiServer.setLocalProjects(() => projectBoards.list());
|
|
1258
1388
|
const findDiscussionSession = (origin, id) => discussionSession(bridgeId, sid => store.loadSession(sid), peerControl, origin, id);
|
|
@@ -1345,6 +1475,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1345
1475
|
.finally(() => { maintenance = undefined; });
|
|
1346
1476
|
}, 30_000);
|
|
1347
1477
|
ticketTimer.unref();
|
|
1478
|
+
partialStartup.push(() => clearInterval(ticketTimer));
|
|
1348
1479
|
const hostResources = hostResourceSampler(dataDir);
|
|
1349
1480
|
const dispatchCommand = async (message) => {
|
|
1350
1481
|
if (!ready)
|
|
@@ -1382,6 +1513,14 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1382
1513
|
relayUserId: userId }, dispatchCommand, updateEffects);
|
|
1383
1514
|
localApiServer.setPeerControl(peerControl, peerLinks, join(dataDir, 'folder-transfers'), peerCache.list, hostResources);
|
|
1384
1515
|
localApiServer.startInstructionSync(security.bridgeId);
|
|
1516
|
+
if (workspaceRuntime) {
|
|
1517
|
+
stopWorkspaceBrowserGateway = await startWorkspaceBrowserGateway(workspaceRuntime, hookPort, loopbackServer);
|
|
1518
|
+
nativeControl = await startWorkspaceNativeControl({ dataDir, bridgeId, bridgeEndpointId: security.endpoint.id,
|
|
1519
|
+
policy: security.policy, ready: () => ready, sessionController, localApiServer, store, terminalManager,
|
|
1520
|
+
port: process.env.FTOWN_WORKSPACE_NATIVE_PORT === undefined ? undefined : Number(process.env.FTOWN_WORKSPACE_NATIVE_PORT),
|
|
1521
|
+
});
|
|
1522
|
+
workspaceRendezvous?.start();
|
|
1523
|
+
}
|
|
1385
1524
|
// Solo: the hub child must be healthy before connecting (L1 gates the
|
|
1386
1525
|
// transport, not the front). A failed hub is fatal for solo — exit cleanly
|
|
1387
1526
|
// instead of crashing on an unhandled rejection.
|
|
@@ -1410,8 +1549,16 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1410
1549
|
ready = true;
|
|
1411
1550
|
console.log('[Bridge] Ready and listening for commands');
|
|
1412
1551
|
if (bridgePointerPublished) {
|
|
1413
|
-
|
|
1414
|
-
|
|
1552
|
+
if (workspaceConfigured) {
|
|
1553
|
+
if (workspaceRuntime?.snapshot.writerId === security.endpoint.id) {
|
|
1554
|
+
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.');
|
|
1555
|
+
}
|
|
1556
|
+
else {
|
|
1557
|
+
console.log('[Bridge] Workspace member ready. Manage enrollment on the workspace writer.');
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
// Legacy browser invitations are for Solo and --local; account bridges use the passkey ledger.
|
|
1561
|
+
else if (opts.local || opts.solo)
|
|
1415
1562
|
console.log('[Bridge] Encrypted endpoint ready. Run ftown security invite to pair a browser.');
|
|
1416
1563
|
else
|
|
1417
1564
|
console.log('[Bridge] Encrypted endpoint ready. Browsers signed in to your account with a passkey can reach this computer.');
|
|
@@ -1434,7 +1581,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1434
1581
|
if (updateRestart && !shutdownRun) {
|
|
1435
1582
|
if (!bridgePointerPublished)
|
|
1436
1583
|
throw new Error('Update restart pointer unavailable');
|
|
1437
|
-
if (!opts.local)
|
|
1584
|
+
if (!opts.local && !networkLocalOnly && !workspaceConfigured)
|
|
1438
1585
|
await centrifugo.waitUntilSecureCommandsReady(45_000);
|
|
1439
1586
|
await finishUpdateRestartAdmission(updateAdmission, () => reportUpdateReady({ version: BRIDGE_VERSION, bridgeId, ownerId: auth.ownerId, endpointId: security.endpoint.id }));
|
|
1440
1587
|
if (shutdownRun)
|
|
@@ -1448,11 +1595,13 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1448
1595
|
}
|
|
1449
1596
|
})();
|
|
1450
1597
|
}, 2000);
|
|
1598
|
+
partialStartup.push(() => clearTimeout(startupTimer));
|
|
1451
1599
|
const autoUpdateTimer = setInterval(() => {
|
|
1452
1600
|
if (ready)
|
|
1453
1601
|
void updates.checkAutomaticUpdate().catch(error => console.error('[Bridge] Automatic update check failed:', error));
|
|
1454
1602
|
}, 30 * 60_000);
|
|
1455
1603
|
autoUpdateTimer.unref();
|
|
1604
|
+
partialStartup.push(() => clearInterval(autoUpdateTimer));
|
|
1456
1605
|
// Leaves tmux sessions running and the process alive; a revoked restart re-executes this same PID
|
|
1457
1606
|
// afterwards, so the local port, pointer, relay connection and timers must all be released here.
|
|
1458
1607
|
function shutdown() {
|
|
@@ -1460,6 +1609,9 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1460
1609
|
console.log('\n[Bridge] Shutting down...');
|
|
1461
1610
|
ready = false;
|
|
1462
1611
|
clearTimeout(startupTimer);
|
|
1612
|
+
workspaceRendezvous?.close();
|
|
1613
|
+
stopWorkspaceBrowserGateway?.();
|
|
1614
|
+
stopWorkspace?.();
|
|
1463
1615
|
clearInterval(autoUpdateTimer);
|
|
1464
1616
|
clearInterval(ticketTimer);
|
|
1465
1617
|
try {
|
|
@@ -1484,7 +1636,7 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1484
1636
|
watchRegistry.dispose();
|
|
1485
1637
|
centrifugo.disconnect();
|
|
1486
1638
|
const drained = await Promise.allSettled([
|
|
1487
|
-
teamOutbox.close(), localApiServer.closeTransfers(), peerCache.stop(), projectDirectory.stop(), pullRequestEvents.stop(),
|
|
1639
|
+
nativeControl?.close(), teamOutbox.close(), localApiServer.closeTransfers(), peerCache.stop(), projectDirectory.stop(), pullRequestEvents.stop(),
|
|
1488
1640
|
maintenance, ...deliveries.values(),
|
|
1489
1641
|
// An already-started resurrection can still attach a PTY. Detach once it finishes.
|
|
1490
1642
|
Promise.resolve(startupWork).then(() => terminalOutput.stop()),
|
|
@@ -1527,13 +1679,28 @@ export async function runBridge(argv, commandName = 'ftown-bridge', deps = {}) {
|
|
|
1527
1679
|
};
|
|
1528
1680
|
process.on('SIGINT', onStopSignal);
|
|
1529
1681
|
process.on('SIGTERM', onStopSignal);
|
|
1682
|
+
// Run optional external probes only after all required listeners have opened.
|
|
1683
|
+
void probeLaunchCapabilities().then(() => {
|
|
1684
|
+
if (!launchCapabilities.codexApproveForMe)
|
|
1685
|
+
console.log('[Bridge] codex predates --approve-for-me: codex sessions keep the bypass flags');
|
|
1686
|
+
if (!launchCapabilities.claudeAutoMode)
|
|
1687
|
+
console.log('[Bridge] claude predates auto mode: claude sessions keep their default permission mode');
|
|
1688
|
+
}).catch(() => { });
|
|
1530
1689
|
});
|
|
1531
1690
|
registerLocalBrowserCommands(program);
|
|
1532
1691
|
try {
|
|
1533
1692
|
await program.parseAsync(argv, { from: 'user' });
|
|
1693
|
+
partialStartup.length = 0;
|
|
1534
1694
|
return 0;
|
|
1535
1695
|
}
|
|
1536
1696
|
catch (error) {
|
|
1697
|
+
// Signal every acquired resource before waiting: a pending snapshot can be blocked on a peer socket.
|
|
1698
|
+
// The instance remains exclusively held until all cleanup callbacks have settled.
|
|
1699
|
+
const settled = await Promise.allSettled(partialStartup.reverse().map(async (close) => close()));
|
|
1700
|
+
for (const result of settled)
|
|
1701
|
+
if (result.status === 'rejected')
|
|
1702
|
+
console.warn('[Bridge] Startup cleanup failed:', result.reason);
|
|
1703
|
+
releaseFailedInstance?.();
|
|
1537
1704
|
if (error instanceof CommanderError)
|
|
1538
1705
|
return error.exitCode;
|
|
1539
1706
|
throw error;
|