cli-setu 0.3.2 → 0.3.4
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/README.md +44 -40
- package/bin/setu.js +172 -149
- package/package.json +4 -1
- package/src/approvalRelay.js +73 -0
- package/src/cli-adapters/claude.js +400 -302
- package/src/cli-adapters/index.js +28 -27
- package/src/cli-adapters/shell.js +96 -88
- package/src/dedup.js +35 -0
- package/src/diagnostics.js +35 -0
- package/src/gitDiff.js +200 -0
- package/src/pair.js +162 -131
- package/src/providerProtocol.js +155 -0
- package/src/reconnect.js +94 -0
- package/src/sharedKey.js +40 -0
- package/src/status.js +1 -1
- package/src/stdinForwarder.js +33 -0
- package/src/supervisor.js +2234 -1369
- package/src/transportSplit.js +72 -0
package/src/pair.js
CHANGED
|
@@ -1,131 +1,162 @@
|
|
|
1
|
-
// The one-time pairing flow, exactly as proven in supervisor-qr.js's
|
|
2
|
-
// ensurePaired() - same real HTTP calls, same QR + typed-code dual path
|
|
3
|
-
// (either wins, whichever the phone actually uses). What changes here:
|
|
4
|
-
// the device name comes from config.js's auto-detected hostname instead
|
|
5
|
-
// of a hand-typed argv, and the result is saved to ~/.cli-setu/config.json
|
|
6
|
-
// instead of a per-device-name file in the install folder.
|
|
7
|
-
const qrcode = require('qrcode-terminal');
|
|
8
|
-
const { loadOrCreateConfig, writeConfig, hasKeypair } = require('./config');
|
|
9
|
-
const { generateKeypair, publicKeyToBase64, privateKeyToBase64 } = require('./crypto');
|
|
10
|
-
|
|
11
|
-
async function pair(authServer, authServerPublic) {
|
|
12
|
-
const config = loadOrCreateConfig();
|
|
13
|
-
|
|
14
|
-
// Section 1 E2E: generate this device's own keypair up front, before
|
|
15
|
-
// either pairing path below, so both qr-start and pair/start can send
|
|
16
|
-
// the SAME public key no matter which path the user actually takes
|
|
17
|
-
// (scan vs typed code - both start by calling this function). A
|
|
18
|
-
// re-pair (config.deviceToken was cleared just below, or this is a
|
|
19
|
-
// genuinely fresh config) always gets a FRESH keypair - never reuses
|
|
20
|
-
// a stale one left over from a previous, now-dead pairing.
|
|
21
|
-
if (!hasKeypair(config)) {
|
|
22
|
-
const { privateKey, publicKey } = generateKeypair();
|
|
23
|
-
config.devicePrivateKey = privateKeyToBase64(privateKey);
|
|
24
|
-
config.devicePublicKey = publicKeyToBase64(publicKey);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (config.deviceToken) {
|
|
28
|
-
// Real bug found by testing: unpairing from the phone deletes the
|
|
29
|
-
// device server-side, but the laptop's local config.json still has
|
|
30
|
-
// the old (now-dead) token - this used to trust that local file
|
|
31
|
-
// blindly and declare itself "already paired" even when the server
|
|
32
|
-
// had no record of it at all. Confirm the saved token is actually
|
|
33
|
-
// still valid before trusting it; a dead token (401 - the server
|
|
34
|
-
// genuinely doesn't recognize it) falls through to a real re-pair.
|
|
35
|
-
// A network error/unreachable server is a THIRD, distinct outcome -
|
|
36
|
-
// deliberately NOT treated as "unpaired," since that would force an
|
|
37
|
-
// unwanted re-pair on every flaky-wifi run; it proceeds as if still
|
|
38
|
-
// paired instead, same as this check not existing at all.
|
|
39
|
-
let serverSaysUnpaired = false;
|
|
40
|
-
try {
|
|
41
|
-
const res = await fetch(`${authServer}/device/whoami`, {
|
|
42
|
-
headers: { Authorization: `Bearer ${config.deviceToken}` },
|
|
43
|
-
});
|
|
44
|
-
serverSaysUnpaired = res.status === 401;
|
|
45
|
-
} catch {
|
|
46
|
-
// Network error/unreachable - unknown, not "unpaired". Fall through
|
|
47
|
-
// to the "already paired" branch below, unchanged from before this
|
|
48
|
-
// check existed.
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if (!serverSaysUnpaired) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
config
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
|
|
1
|
+
// The one-time pairing flow, exactly as proven in supervisor-qr.js's
|
|
2
|
+
// ensurePaired() - same real HTTP calls, same QR + typed-code dual path
|
|
3
|
+
// (either wins, whichever the phone actually uses). What changes here:
|
|
4
|
+
// the device name comes from config.js's auto-detected hostname instead
|
|
5
|
+
// of a hand-typed argv, and the result is saved to ~/.cli-setu/config.json
|
|
6
|
+
// instead of a per-device-name file in the install folder.
|
|
7
|
+
const qrcode = require('qrcode-terminal');
|
|
8
|
+
const { loadOrCreateConfig, writeConfig, hasKeypair } = require('./config');
|
|
9
|
+
const { generateKeypair, publicKeyToBase64, privateKeyToBase64 } = require('./crypto');
|
|
10
|
+
|
|
11
|
+
async function pair(authServer, authServerPublic) {
|
|
12
|
+
const config = loadOrCreateConfig();
|
|
13
|
+
|
|
14
|
+
// Section 1 E2E: generate this device's own keypair up front, before
|
|
15
|
+
// either pairing path below, so both qr-start and pair/start can send
|
|
16
|
+
// the SAME public key no matter which path the user actually takes
|
|
17
|
+
// (scan vs typed code - both start by calling this function). A
|
|
18
|
+
// re-pair (config.deviceToken was cleared just below, or this is a
|
|
19
|
+
// genuinely fresh config) always gets a FRESH keypair - never reuses
|
|
20
|
+
// a stale one left over from a previous, now-dead pairing.
|
|
21
|
+
if (!hasKeypair(config)) {
|
|
22
|
+
const { privateKey, publicKey } = generateKeypair();
|
|
23
|
+
config.devicePrivateKey = privateKeyToBase64(privateKey);
|
|
24
|
+
config.devicePublicKey = publicKeyToBase64(publicKey);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (config.deviceToken) {
|
|
28
|
+
// Real bug found by testing: unpairing from the phone deletes the
|
|
29
|
+
// device server-side, but the laptop's local config.json still has
|
|
30
|
+
// the old (now-dead) token - this used to trust that local file
|
|
31
|
+
// blindly and declare itself "already paired" even when the server
|
|
32
|
+
// had no record of it at all. Confirm the saved token is actually
|
|
33
|
+
// still valid before trusting it; a dead token (401 - the server
|
|
34
|
+
// genuinely doesn't recognize it) falls through to a real re-pair.
|
|
35
|
+
// A network error/unreachable server is a THIRD, distinct outcome -
|
|
36
|
+
// deliberately NOT treated as "unpaired," since that would force an
|
|
37
|
+
// unwanted re-pair on every flaky-wifi run; it proceeds as if still
|
|
38
|
+
// paired instead, same as this check not existing at all.
|
|
39
|
+
let serverSaysUnpaired = false;
|
|
40
|
+
try {
|
|
41
|
+
const res = await fetch(`${authServer}/device/whoami`, {
|
|
42
|
+
headers: { Authorization: `Bearer ${config.deviceToken}` },
|
|
43
|
+
});
|
|
44
|
+
serverSaysUnpaired = res.status === 401;
|
|
45
|
+
} catch {
|
|
46
|
+
// Network error/unreachable - unknown, not "unpaired". Fall through
|
|
47
|
+
// to the "already paired" branch below, unchanged from before this
|
|
48
|
+
// check existed.
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!serverSaysUnpaired) {
|
|
52
|
+
// Real gap found by review: this used to return silently with no
|
|
53
|
+
// next-step hint - a user running `cli-setu pair` again out of habit
|
|
54
|
+
// (or confusion about the SETU-001/018 pair/session split) got no
|
|
55
|
+
// indication of what to do next. Matches bin/setu.js's own exact
|
|
56
|
+
// phrasing for the equivalent "already paired" case (bare `cli-setu`
|
|
57
|
+
// with no subcommand) rather than inventing new wording.
|
|
58
|
+
//
|
|
59
|
+
// Real bug found immediately after adding this, before it ever
|
|
60
|
+
// shipped: bin/setu.js's own `pair` case unconditionally prints
|
|
61
|
+
// "Device paired successfully..." right after calling this function,
|
|
62
|
+
// regardless of whether anything actually happened - confirmed live,
|
|
63
|
+
// it printed BOTH this new hint AND that generic success line back
|
|
64
|
+
// to back, a confusing duplicate. alreadyPaired (checked by the
|
|
65
|
+
// caller) lets bin/setu.js only print its own success line for a
|
|
66
|
+
// GENUINELY new pairing.
|
|
67
|
+
console.log(`[cli-setu] "${config.deviceName}" is already paired. Run \`cli-setu session\` to start a terminal session.`);
|
|
68
|
+
return { config, alreadyPaired: true };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
console.log(`[cli-setu] This device's pairing is no longer valid on the server (likely unpaired from the app) - re-pairing...`);
|
|
72
|
+
config.deviceToken = null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
console.log(`[cli-setu] Pairing as "${config.deviceName}"...`);
|
|
76
|
+
console.log('[cli-setu] (This is your computer\'s name. Rename it in ~/.cli-setu/config.json before pairing if you want something else.)');
|
|
77
|
+
|
|
78
|
+
// qr-start also needs a sessionId up front (mirrors supervisor-qr.js's
|
|
79
|
+
// "the QR both pairs it AND jumps the phone straight to watching THIS
|
|
80
|
+
// session" behavior) - 'pairing' is a placeholder id here since
|
|
81
|
+
// `cli-setu pair` itself never streams a terminal; the real per-run
|
|
82
|
+
// session id is generated fresh by supervisor.js on every `cli-setu`
|
|
83
|
+
// (bare) invocation.
|
|
84
|
+
const startRes = await fetch(`${authServer}/device/pair/qr-start`, {
|
|
85
|
+
method: 'POST',
|
|
86
|
+
headers: { 'Content-Type': 'application/json' },
|
|
87
|
+
body: JSON.stringify({ deviceName: config.deviceName, sessionId: 'pairing', devicePublicKey: config.devicePublicKey }),
|
|
88
|
+
});
|
|
89
|
+
const { qrToken } = await startRes.json();
|
|
90
|
+
|
|
91
|
+
const scanUrl = `${authServerPublic}/scan.html?token=${qrToken}&session=pairing&device=${encodeURIComponent(config.deviceName)}`;
|
|
92
|
+
|
|
93
|
+
console.log('');
|
|
94
|
+
qrcode.generate(scanUrl, { small: true });
|
|
95
|
+
console.log('[cli-setu] Scan this with your phone camera.');
|
|
96
|
+
console.log(`[cli-setu] (Testing on one PC? Paste this URL into a browser tab instead: ${scanUrl})`);
|
|
97
|
+
|
|
98
|
+
const codeRes = await fetch(`${authServer}/device/pair/start`, {
|
|
99
|
+
method: 'POST',
|
|
100
|
+
headers: { 'Content-Type': 'application/json' },
|
|
101
|
+
body: JSON.stringify({ deviceName: config.deviceName, devicePublicKey: config.devicePublicKey }),
|
|
102
|
+
});
|
|
103
|
+
const { code: typedCode, pairId: typedPairId } = await codeRes.json();
|
|
104
|
+
console.log(`[cli-setu] Or type this code in the app's Devices tab: ${typedCode}`);
|
|
105
|
+
console.log('[cli-setu] Waiting for scan or code entry...');
|
|
106
|
+
|
|
107
|
+
let confirmed = false;
|
|
108
|
+
while (!confirmed) {
|
|
109
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
110
|
+
const statusRes = await fetch(`${authServer}/device/pair/qr-status?token=${qrToken}`);
|
|
111
|
+
const status = await statusRes.json();
|
|
112
|
+
|
|
113
|
+
if (status.status === 'CONFIRMED') {
|
|
114
|
+
confirmed = true;
|
|
115
|
+
config.deviceToken = status.deviceToken;
|
|
116
|
+
// Section 1 E2E: the phone's public key, so this laptop can derive
|
|
117
|
+
// the shared secret for terminal.input/output - see crypto.js's
|
|
118
|
+
// deriveSharedSecret and supervisor.js's own use of it.
|
|
119
|
+
if (status.phonePublicKey) config.phonePublicKey = status.phonePublicKey;
|
|
120
|
+
writeConfig(config);
|
|
121
|
+
console.log(`[cli-setu] ✓ Paired via QR and saved to ~/.cli-setu/config.json`);
|
|
122
|
+
break;
|
|
123
|
+
} else if (status.status === 'EXPIRED') {
|
|
124
|
+
console.error('[cli-setu] QR code expired. Run `cli-setu pair` again to get a new one.');
|
|
125
|
+
process.exit(1);
|
|
126
|
+
} else if (status.status === 'REJECTED') {
|
|
127
|
+
console.error(`[cli-setu] Pairing rejected: ${status.rejectReason || 'the server declined this pairing.'}`);
|
|
128
|
+
process.exit(1);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const typedStatusRes = await fetch(`${authServer}/device/pair/status?pairId=${typedPairId}`);
|
|
132
|
+
const typedStatus = await typedStatusRes.json();
|
|
133
|
+
if (typedStatus.status === 'CONFIRMED') {
|
|
134
|
+
confirmed = true;
|
|
135
|
+
config.deviceToken = typedStatus.deviceToken;
|
|
136
|
+
if (typedStatus.phonePublicKey) config.phonePublicKey = typedStatus.phonePublicKey;
|
|
137
|
+
writeConfig(config);
|
|
138
|
+
console.log(`[cli-setu] ✓ Paired via typed code and saved to ~/.cli-setu/config.json`);
|
|
139
|
+
break;
|
|
140
|
+
} else if (typedStatus.status === 'EXPIRED') {
|
|
141
|
+
// Real gap found by investigation (SESSION_MONITORING_ARCHITECTURE.md
|
|
142
|
+
// #10): this loop already checks the QR side's own EXPIRED/REJECTED
|
|
143
|
+
// and exits cleanly - the typed-code side's own EXPIRED was silently
|
|
144
|
+
// ignored here, so the two poll paths could disagree about whether
|
|
145
|
+
// this pairing attempt is actually over. Both tokens are minted
|
|
146
|
+
// back-to-back with the same 5-minute TTL (see auth-server.js's
|
|
147
|
+
// qr-start/pair/start handlers), so in practice the QR side's own
|
|
148
|
+
// expiry check almost always caught this first - but "almost
|
|
149
|
+
// always" isn't "always," and a loop with no real exit guarantee on
|
|
150
|
+
// one of its two paths is worth closing regardless. (REJECTED isn't
|
|
151
|
+
// checked here because auth-server.js never actually sets that
|
|
152
|
+
// status on this path today - only the QR path's pairings can be
|
|
153
|
+
// rejected, e.g. the device-limit check in /device/pair/qr-confirm.)
|
|
154
|
+
console.error('[cli-setu] Pairing code expired. Run `cli-setu pair` again to get a new one.');
|
|
155
|
+
process.exit(1);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return { config, alreadyPaired: false };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
module.exports = { pair };
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// Provider-specific connection framing. Azure Web PubSub needs NONE of
|
|
2
|
+
// this - a plain WebSocket, opened with a URL that already carries a
|
|
3
|
+
// scoped access token, is immediately ready to send/receive. Ably's own
|
|
4
|
+
// raw WebSocket endpoint (confirmed real and working via direct
|
|
5
|
+
// research, see ablyAdapter.js's own header comment on the backend)
|
|
6
|
+
// needs one extra step: after the socket opens, the client must wait
|
|
7
|
+
// for Ably's CONNECTED handshake, then send one ATTACH ProtocolMessage
|
|
8
|
+
// to join the channel, then wait for ATTACHED before the connection is
|
|
9
|
+
// actually ready to receive anything - Azure's groups need no
|
|
10
|
+
// equivalent client-side step at all (group membership is entirely
|
|
11
|
+
// server-side there).
|
|
12
|
+
//
|
|
13
|
+
// This module exists so that difference lives in ONE place, not
|
|
14
|
+
// scattered through supervisor.js's existing message-handling code
|
|
15
|
+
// (which stays completely untouched for the Azure case - see
|
|
16
|
+
// supervisor.js's own call site for how this wraps around the existing
|
|
17
|
+
// `new WebSocket(...)` + `ws.on('open'/'message')` pattern rather than
|
|
18
|
+
// replacing it).
|
|
19
|
+
//
|
|
20
|
+
// Wire format confirmed via direct research cross-checking TWO
|
|
21
|
+
// independent sources (Ably's own published protocol spec AND the
|
|
22
|
+
// ably-js SDK's literal source code for the numeric action constants -
|
|
23
|
+
// both agreed field-for-field, number-for-number):
|
|
24
|
+
// CONNECTED = 4, ERROR = 9, ATTACH = 10, ATTACHED = 11, MESSAGE = 15
|
|
25
|
+
// A real published message arrives as
|
|
26
|
+
// { action: 15, channel, messages: [{ data, ... }, ...] }
|
|
27
|
+
// - note `messages` is an ARRAY (a single publish can batch several
|
|
28
|
+
// messages), so every one must be delivered to the caller, not just the
|
|
29
|
+
// first.
|
|
30
|
+
const ABLY_ACTION = {
|
|
31
|
+
CONNECTED: 4,
|
|
32
|
+
ERROR: 9,
|
|
33
|
+
ATTACH: 10,
|
|
34
|
+
ATTACHED: 11,
|
|
35
|
+
MESSAGE: 15,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// Azure Web PubSub's own wssUrl looks like
|
|
39
|
+
// wss://<name>.webpubsub.azure.com/client/hubs/<hub>?access_token=...
|
|
40
|
+
// Ably's raw endpoint (see ablyAdapter.js) is always exactly
|
|
41
|
+
// wss://realtime.ably.io/?access_token=...&v=6&format=json - checking
|
|
42
|
+
// the hostname is simpler and more robust than parsing query params,
|
|
43
|
+
// and matches exactly how the backend actually mints each provider's
|
|
44
|
+
// URL today (never guessing at a shape neither provider actually uses).
|
|
45
|
+
function detectProvider(wssUrl) {
|
|
46
|
+
try {
|
|
47
|
+
const host = new URL(wssUrl).hostname;
|
|
48
|
+
if (host === 'realtime.ably.io') return 'ably';
|
|
49
|
+
return 'azure';
|
|
50
|
+
} catch {
|
|
51
|
+
return 'azure'; // malformed URL - let the existing Azure path's own error handling surface this, same as before this module existed
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Wraps a freshly-constructed `ws` WebSocket instance (already
|
|
56
|
+
// `new WebSocket(wssUrl)`-created by the caller, not yet opened) so that
|
|
57
|
+
// for Ably, the caller's own `onReady` callback only fires once the
|
|
58
|
+
// ATTACH/ATTACHED handshake has actually completed - not just on the
|
|
59
|
+
// raw socket's own 'open' event, which for Ably is NOT yet enough to
|
|
60
|
+
// safely assume messages will be delivered. For Azure, onReady fires
|
|
61
|
+
// exactly where it always did (immediately on 'open'), so existing
|
|
62
|
+
// Azure behavior is completely unchanged.
|
|
63
|
+
//
|
|
64
|
+
// onMessage(payload) is called once per real application-level message
|
|
65
|
+
// (already unwrapped from Ably's own `messages[]` envelope, or passed
|
|
66
|
+
// straight through unchanged for Azure) - the caller's existing
|
|
67
|
+
// `JSON.parse` + `msg.type === ...` handling needs no changes at all for
|
|
68
|
+
// either provider.
|
|
69
|
+
function attachProviderProtocol(ws, wssUrl, groupName, { onReady, onMessage, log = () => {} }) {
|
|
70
|
+
const provider = detectProvider(wssUrl);
|
|
71
|
+
|
|
72
|
+
if (provider === 'azure') {
|
|
73
|
+
// Unchanged from before this module existed.
|
|
74
|
+
ws.on('open', onReady);
|
|
75
|
+
ws.on('message', (raw) => {
|
|
76
|
+
let msg;
|
|
77
|
+
try {
|
|
78
|
+
msg = JSON.parse(raw.toString());
|
|
79
|
+
} catch {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
onMessage(msg);
|
|
83
|
+
});
|
|
84
|
+
return { provider };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// provider === 'ably'
|
|
88
|
+
let attached = false;
|
|
89
|
+
ws.on('open', () => {
|
|
90
|
+
log('[supervisor] Ably socket open - waiting for CONNECTED handshake...');
|
|
91
|
+
});
|
|
92
|
+
ws.on('message', (raw) => {
|
|
93
|
+
let frame;
|
|
94
|
+
try {
|
|
95
|
+
frame = JSON.parse(raw.toString());
|
|
96
|
+
} catch {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
switch (frame.action) {
|
|
100
|
+
case ABLY_ACTION.CONNECTED:
|
|
101
|
+
log('[supervisor] Ably CONNECTED - sending ATTACH for channel:', groupName);
|
|
102
|
+
ws.send(JSON.stringify({ action: ABLY_ACTION.ATTACH, channel: groupName }));
|
|
103
|
+
break;
|
|
104
|
+
case ABLY_ACTION.ATTACHED:
|
|
105
|
+
if (frame.channel === groupName && !attached) {
|
|
106
|
+
attached = true;
|
|
107
|
+
log('[supervisor] Ably ATTACHED - channel ready.');
|
|
108
|
+
onReady();
|
|
109
|
+
}
|
|
110
|
+
break;
|
|
111
|
+
case ABLY_ACTION.MESSAGE:
|
|
112
|
+
if (frame.channel === groupName) {
|
|
113
|
+
// A single publish can batch multiple messages - deliver every
|
|
114
|
+
// one, not just the first (see this file's own header comment).
|
|
115
|
+
//
|
|
116
|
+
// Real bug caught live (2026-10-24): the backend's
|
|
117
|
+
// channel.publish() call (ablyAdapter.js's broadcastToGroup)
|
|
118
|
+
// passes a plain JS object, but Ably's own client library
|
|
119
|
+
// serializes that to a JSON STRING before sending (encoding:
|
|
120
|
+
// "json" in the real wire frame) - it does NOT arrive
|
|
121
|
+
// pre-parsed the way Azure's raw JSON frames do. Every
|
|
122
|
+
// onMessage(m.data) caller downstream (supervisor.js) does
|
|
123
|
+
// `msg.type === ...` checks that silently never match against
|
|
124
|
+
// a raw string, so every single message would be dropped with
|
|
125
|
+
// no error at all. Parse here, once, so onMessage's contract
|
|
126
|
+
// ("already-parsed object, same shape for both providers") is
|
|
127
|
+
// actually true for Ably too.
|
|
128
|
+
for (const m of frame.messages || []) {
|
|
129
|
+
let data = m.data;
|
|
130
|
+
if (typeof data === 'string') {
|
|
131
|
+
try {
|
|
132
|
+
data = JSON.parse(data);
|
|
133
|
+
} catch {
|
|
134
|
+
log('[supervisor] Ably message data was a string but not valid JSON - dropping:', data);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
onMessage(data);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
break;
|
|
142
|
+
case ABLY_ACTION.ERROR:
|
|
143
|
+
log('[supervisor] Ably protocol ERROR:', frame.error?.message || JSON.stringify(frame.error));
|
|
144
|
+
break;
|
|
145
|
+
default:
|
|
146
|
+
// HEARTBEAT, ACK, NACK, DISCONNECTED, etc. - no action needed for
|
|
147
|
+
// this relay's purposes.
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
return { provider };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { detectProvider, attachProviderProtocol, ABLY_ACTION };
|
package/src/reconnect.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Exponential backoff with jitter for the laptop's own reconnection to
|
|
2
|
+
// the backend/Azure Web PubSub - used by supervisor.js's connectToAzure
|
|
3
|
+
// retry paths (both the /device/connect HTTP retry and the WebSocket's
|
|
4
|
+
// own onclose reconnect).
|
|
5
|
+
//
|
|
6
|
+
// Real gap this fixes (confirmed by direct investigation of the actual
|
|
7
|
+
// code, see docs/SESSION_MONITORING_ARCHITECTURE.md): both retry paths
|
|
8
|
+
// used a FIXED interval (3s / 2s) with NO retry counter, NO backoff, and
|
|
9
|
+
// NO cap - they retry silently and identically forever. This exact shape
|
|
10
|
+
// - "stopped working, then quietly started working again hours later" -
|
|
11
|
+
// produces ZERO distinguishing evidence between "a transient blip that
|
|
12
|
+
// self-healed on attempt #2" and "a real outage that self-healed on
|
|
13
|
+
// attempt #400," which is precisely the ambiguity a PM got upset about
|
|
14
|
+
// from a real production incident. A visible, bounded, backed-off retry
|
|
15
|
+
// makes that distinction a fact instead of a guess - after enough
|
|
16
|
+
// attempts, this surfaces a clear "still trying, something is wrong"
|
|
17
|
+
// state instead of silence.
|
|
18
|
+
//
|
|
19
|
+
// A fixed-interval retry across MANY simultaneously-reconnecting clients
|
|
20
|
+
// (e.g. a brief Azure blip affecting every connected laptop at once) also
|
|
21
|
+
// creates a reconnect storm - all of them retry at the exact same cadence,
|
|
22
|
+
// hammering the backend in lockstep the moment it recovers. Jitter
|
|
23
|
+
// (randomizing each client's actual wait within a range) spreads that
|
|
24
|
+
// load out instead of synchronizing it.
|
|
25
|
+
|
|
26
|
+
// Tunable via env vars so this can be dialed differently without a code
|
|
27
|
+
// change (e.g. a much more patient cap when running inside a CI/test
|
|
28
|
+
// harness that expects provider blips).
|
|
29
|
+
const BASE_DELAY_MS = Number(process.env.CLI_SETU_RECONNECT_BASE_MS) || 1000;
|
|
30
|
+
const MAX_DELAY_MS = Number(process.env.CLI_SETU_RECONNECT_MAX_MS) || 60_000;
|
|
31
|
+
// After this many consecutive failures, stop silently retrying forever -
|
|
32
|
+
// surface a clear, visible "still down" message instead. Not a hard
|
|
33
|
+
// stop (the caller decides what "give up" actually means - for
|
|
34
|
+
// supervisor.js, that's printing a loud status line and CONTINUING to
|
|
35
|
+
// retry at the max interval, not exiting, since this failure could still
|
|
36
|
+
// self-heal) - this constant is just the point past which staying quiet
|
|
37
|
+
// stops being reasonable.
|
|
38
|
+
const WARN_AFTER_ATTEMPTS = Number(process.env.CLI_SETU_RECONNECT_WARN_AFTER) || 5;
|
|
39
|
+
|
|
40
|
+
// Full jitter (AWS's own documented strategy for this exact problem,
|
|
41
|
+
// see their "Exponential Backoff And Jitter" architecture blog) - the
|
|
42
|
+
// delay is a random value between 0 and the capped exponential delay,
|
|
43
|
+
// not a fixed delay plus a small random offset. This is the strategy
|
|
44
|
+
// with the best-documented reconnect-storm-avoidance properties of the
|
|
45
|
+
// common options (full jitter / equal jitter / decorrelated jitter).
|
|
46
|
+
function computeDelayMs(attemptNumber) {
|
|
47
|
+
const exponential = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attemptNumber - 1));
|
|
48
|
+
return Math.floor(Math.random() * exponential);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Tracks one logical reconnection loop's attempt count + timer handle.
|
|
52
|
+
// A fresh instance per "thing that reconnects" (this process has
|
|
53
|
+
// exactly one - the Azure WebSocket/device-connect pair share the same
|
|
54
|
+
// logical retry loop since a /device/connect failure and a WebSocket
|
|
55
|
+
// close are the same underlying "not connected right now" condition) -
|
|
56
|
+
// not a singleton, so a future multi-session-per-process design (if
|
|
57
|
+
// that ever happens) wouldn't need this rewritten.
|
|
58
|
+
function createReconnectManager({ onAttempt, onWarn, log = console.log }) {
|
|
59
|
+
let attemptNumber = 0;
|
|
60
|
+
let timer = null;
|
|
61
|
+
let stopped = false;
|
|
62
|
+
|
|
63
|
+
function reset() {
|
|
64
|
+
attemptNumber = 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function scheduleRetry() {
|
|
68
|
+
if (stopped) return;
|
|
69
|
+
attemptNumber += 1;
|
|
70
|
+
const delayMs = computeDelayMs(attemptNumber);
|
|
71
|
+
if (attemptNumber === WARN_AFTER_ATTEMPTS) {
|
|
72
|
+
// Fires exactly once per outage (not every attempt past the
|
|
73
|
+
// threshold) - a single clear escalation, not repeated noise.
|
|
74
|
+
onWarn?.(attemptNumber);
|
|
75
|
+
}
|
|
76
|
+
log(`[reconnect] Retry ${attemptNumber} in ${(delayMs / 1000).toFixed(1)}s`);
|
|
77
|
+
timer = setTimeout(() => {
|
|
78
|
+
timer = null;
|
|
79
|
+
onAttempt(attemptNumber);
|
|
80
|
+
}, delayMs);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function stop() {
|
|
84
|
+
stopped = true;
|
|
85
|
+
if (timer) {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
timer = null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return { scheduleRetry, reset, stop, getAttemptNumber: () => attemptNumber };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { createReconnectManager, computeDelayMs, BASE_DELAY_MS, MAX_DELAY_MS, WARN_AFTER_ATTEMPTS };
|
package/src/sharedKey.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Keeps the laptop's shared encryption secret in step with the phone's CURRENT
|
|
2
|
+
// public key (P0: "could not decrypt output from this device").
|
|
3
|
+
//
|
|
4
|
+
// Confirmed cause: the laptop derived its secret once, from the phone key saved
|
|
5
|
+
// at pair time, and never looked again. The backend is the key directory: it
|
|
6
|
+
// holds the phone key that the phone last registered for this device (pairing,
|
|
7
|
+
// a re-scan, a second phone, a reinstall, a late sync). When that key differed
|
|
8
|
+
// from the one frozen in config.json, every message the laptop encrypted failed
|
|
9
|
+
// the phone's GCM auth check, and the only "recovery" was a full unpair and
|
|
10
|
+
// re-pair.
|
|
11
|
+
//
|
|
12
|
+
// Now /device/connect returns the registered phone key and each session start
|
|
13
|
+
// calls adoptPhoneKey(). Encryption is never weakened: a key that cannot be
|
|
14
|
+
// used is rejected (the old secret is kept), nothing falls back to plaintext
|
|
15
|
+
// because of a key change, and private keys are never logged.
|
|
16
|
+
const setuCrypto = require('./crypto');
|
|
17
|
+
|
|
18
|
+
function deriveFor(config, phonePublicKeyB64) {
|
|
19
|
+
const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
|
|
20
|
+
return setuCrypto.deriveSharedSecret(privateKey, phonePublicKeyB64);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Returns { secret, changed, error }.
|
|
24
|
+
// - secret: the secret to use from now on (unchanged when nothing changed or the new key is unusable)
|
|
25
|
+
// - changed: true when config.phonePublicKey was replaced (caller persists)
|
|
26
|
+
// - error: a short reason when the offered key was rejected, never key material
|
|
27
|
+
function adoptPhoneKey({ config, offeredKey, currentSecret }) {
|
|
28
|
+
if (!config.devicePrivateKey) return { secret: currentSecret, changed: false, error: null };
|
|
29
|
+
if (!offeredKey) return { secret: currentSecret, changed: false, error: null };
|
|
30
|
+
if (offeredKey === config.phonePublicKey && currentSecret) return { secret: currentSecret, changed: false, error: null };
|
|
31
|
+
try {
|
|
32
|
+
const secret = deriveFor(config, offeredKey);
|
|
33
|
+
const changed = offeredKey !== config.phonePublicKey;
|
|
34
|
+
return { secret, changed, error: null };
|
|
35
|
+
} catch (err) {
|
|
36
|
+
return { secret: currentSecret, changed: false, error: `phone public key rejected: ${err.message}` };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { adoptPhoneKey, deriveFor };
|
package/src/status.js
CHANGED
|
@@ -93,7 +93,7 @@ async function status(authServer) {
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
if (running.length === 0) {
|
|
96
|
-
console.log('[cli-setu] No sessions currently running. Run `cli-setu` in a project folder to start one.');
|
|
96
|
+
console.log('[cli-setu] No sessions currently running. Run `cli-setu session` in a project folder to start one.');
|
|
97
97
|
return;
|
|
98
98
|
}
|
|
99
99
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Forwards the laptop keyboard to the PTY (P0: "first character is dropped").
|
|
2
|
+
//
|
|
3
|
+
// Two defects this replaces in supervisor.js:
|
|
4
|
+
// 1. Raw mode and the data listener were attached at the END of main(), after
|
|
5
|
+
// all the other start-up work. Until then the console is in cooked
|
|
6
|
+
// (line-buffered) mode, so keys typed while the shell was still starting
|
|
7
|
+
// were held in the console's line buffer and could be discarded when raw mode
|
|
8
|
+
// was switched on. The forwarder is now attached the moment the PTY exists.
|
|
9
|
+
// 2. `data.toString()` on each chunk corrupts a multi-byte UTF-8 character
|
|
10
|
+
// that is split across two chunks. A StringDecoder keeps the partial bytes
|
|
11
|
+
// until the rest arrive.
|
|
12
|
+
// Every chunk is written exactly once, in order. Nothing here reads or echoes
|
|
13
|
+
// input itself: echo is the shell's job, through the PTY.
|
|
14
|
+
const { StringDecoder } = require('string_decoder');
|
|
15
|
+
|
|
16
|
+
function attachStdinForwarder({ stdin, write }) {
|
|
17
|
+
const decoder = new StringDecoder('utf8');
|
|
18
|
+
const onData = (chunk) => {
|
|
19
|
+
const text = typeof chunk === 'string' ? chunk : decoder.write(chunk);
|
|
20
|
+
if (text) write(text);
|
|
21
|
+
};
|
|
22
|
+
if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
|
|
23
|
+
stdin.on('data', onData);
|
|
24
|
+
stdin.resume();
|
|
25
|
+
|
|
26
|
+
return function detach() {
|
|
27
|
+
stdin.removeListener('data', onData);
|
|
28
|
+
try { if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(false); } catch { /* terminal already gone */ }
|
|
29
|
+
stdin.pause();
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { attachStdinForwarder };
|